diff --git a/docs/dev/rest-api/authentication.md b/docs/dev/rest-api/authentication.md index 730bf121e..c4fb1a6ff 100644 --- a/docs/dev/rest-api/authentication.md +++ b/docs/dev/rest-api/authentication.md @@ -236,8 +236,7 @@ The CORS headers expose these headers and `Retry-After` to a browser client. A `--remote` client that gets a `429` with `Retry-After` shows a countdown, waits that time (one hour at most), and then sends the request again. It stops after 3 waits for one request. -The keep-alive, the poll for CDM calls, the health check and the drain check do not wait: each -tries again at its next interval. +The health check does not wait: it tries again at its next interval. !!! warning "`429` is not the `RATE_LIMITED` error body" `RATE_LIMITED` in [Errors](errors.md) is a *service* rate limit that a handler raises, and it diff --git a/docs/dev/rest-api/dashboard.md b/docs/dev/rest-api/dashboard.md index 37707ba44..17cb890c4 100644 --- a/docs/dev/rest-api/dashboard.md +++ b/docs/dev/rest-api/dashboard.md @@ -50,7 +50,7 @@ All are `GET`, except the two `drain` routes. | `/api/dashboard/status` | Version, `code_hash`, bind host and port, `mode` (`full`, `api_only`, `remote_only`), uptime, `requests_total`, `requests_rejected` (401s), `requests_by_key` (label → count), `errors` (error counts by service tag, then by `error_code`), configured service count (the same services as `/api/dashboard/services`), session count, `max_sessions` (`null` when the operator configured no limit), `session_ttl`, job counts by status. `draining` is `true` while a drain is on. The service count includes services that failed to import - use `/api/dashboard/services` for the number that loaded. | | `POST /api/dashboard/drain` | Starts a drain before a restart and returns the `/status` body. The server then refuses each new remote session, download job and job retry with `SERVER_DRAINING` (409). Open remote sessions and jobs continue, and each open remote session gets a warning in its service log, which the client shows to the user. Poll `/status` until `sessions` and the queued and downloading jobs are 0, then restart. The drain ends when the process stops. A second call changes nothing. | | `DELETE /api/dashboard/drain` | Cancels the drain and returns the `/status` body. The server accepts new work again. | -| `/api/dashboard/sessions` | Every live remote session: `id`, `owner` (username or masked key), `creator_ip`, `service`, `title_id`, `titles`, `tracks`, `title` (the display name of the title the client is on: the last one it asked tracks for, else the first resolved title), `auth_status`, `auth_error`, `server_account` (the server profile lent to the remote session, else `null`), `server_cdm` (`false` when the client's own device licenses the remote session), `server_cdm_max_height` (the tallest video the server CDM licenses live, else `null`), `client`, `actions`, `created_at` and `last_accessed` (ISO 8601) with `created_ts` and `last_accessed_ts` (Unix epoch, the same clock as log `ts`), `age_seconds`, `idle_seconds`, `log_seq`. `client` is whatever the remote client sent as `client` in its session create request. The CLI sends `version`, `code_hash` (the commit the client runs, `null` when its source cannot be read), `platform` and `argv`. `argv` is the command line the user ran: proxy and URL userinfo, secret query parameters and credential values become `***`, home and install paths shorten as in the logs, and the line is cut at 3000 characters. An older client sends less or nothing and the field is `{}`. `log_seq` is the last sequence number in the remote session's service log - poll `/api/dashboard/sessions/{id}/logs` when it changes. `actions` is the session's request log, newest last, capped at 500: `ts`, `method`, `action` (`titles`, `tracks`, `segments`, `license`, `prompt`, …), `query`, `status`, `ms`, `bytes_in`, `bytes_out`. | +| `/api/dashboard/sessions` | Every live remote session: `id`, `owner` (username or masked key), `creator_ip`, `service`, `title_id`, `titles`, `tracks`, `title` (the display name of the title the client is on: the last one it asked tracks for, else the first resolved title), `auth_status`, `auth_error`, `server_account` (the server profile lent to the remote session, else `null`), `server_cdm` (`false` when the client's own device licenses the remote session), `server_cdm_max_height` (the tallest video the server CDM licenses live, else `null`), `client`, `actions`, `created_at` and `last_accessed` (ISO 8601) with `created_ts` and `last_accessed_ts` (Unix epoch, the same clock as log `ts`), `age_seconds`, `idle_seconds`, `log_seq`. `client` is whatever the remote client sent as `client` in its session create request. The CLI sends `version`, `code_hash` (the commit the client runs, `null` when its source cannot be read), `platform` and `argv`. `argv` is the command line the user ran: proxy and URL userinfo, secret query parameters and credential values become `***`, home and install paths shorten as in the logs, and the line is cut at 3000 characters. An older client sends less or nothing and the field is `{}`. `log_seq` is the last sequence number in the remote session's service log - poll `/api/dashboard/sessions/{id}/logs` when it changes. `actions` is the session's request log, newest last, capped at 500: `ts`, `method`, `action` (`titles`, `tracks`, `segments`, `license`, …), `query`, `status`, `ms`, `bytes_in`, `bytes_out`. | | `/api/dashboard/jobs` | Every download job with full detail, regardless of owner. Empty in `--remote-only` mode. | | `/api/dashboard/logs` | `{"seq": N, "records": [...]}`: the last 1000 log records. `?since=` returns only newer records; `?level=WARNING` sets the minimum level; `?logger=serve` keeps one logger and its children. `ts` is a Unix epoch in seconds. | | `/api/dashboard/cdm-logs` | `{"seq": N, "records": [...], "sessions": [...]}`: the last 5000 calls to the Widevine and PlayReady CDM device routes, and the open sessions of each device. `?since=` returns only newer records. See [CDM calls](#cdm-calls). | @@ -111,12 +111,12 @@ GET /api/dashboard/sessions/{session_id}/logs?since=12 ``` The field name is `records`, the same one `/api/dashboard/logs` uses, so one dashboard reads -both logs the same way. Each record has the shape the client route `/api/session/{id}/logs` -returns. `last_seq` is the buffer's own last sequence number, so an empty page still reports +both logs the same way. Each record has the fields of a `log` message on the remote session +channel. `last_seq` is the buffer's own last sequence number, so an empty page still reports the true value. -Reading is a cursor read, not a drain: the client draining the same buffer still gets every -record. It also does not refresh the remote session's idle timer, so polling a remote session here +Reading is a cursor read, not a drain: the remote session channel still sends every record to +the client. It also does not refresh the remote session's idle timer, so polling a remote session here never keeps it alive or makes it look active. !!! note "`log_seq` is a poll trigger, not a push" diff --git a/docs/dev/rest-api/errors.md b/docs/dev/rest-api/errors.md index d266d02ec..1fda93c73 100644 --- a/docs/dev/rest-api/errors.md +++ b/docs/dev/rest-api/errors.md @@ -121,6 +121,7 @@ while the server restarts. | `FORBIDDEN` | 403 | The action is not allowed. Raised by server-side gates (per-key restrictions on CDM or credential overrides) and by remote session IP binding. | | `SERVER_CDM_CAPPED` | 403 | The server CDM does not license live above the `server_cdm_max_height` of the API key. `details.reason` is `server_cdm_max_height` (with `details.max_height`), `client_device`, for a remote session where the client's own device licenses, or `server_device`, for a remote session that runs on the server's device. A remote client licenses the track with its own device, except for `server_device`: then only its own vaults can supply the key. | | `GEOFENCE` | 403 | The title is not available in the applicable region. | +| `CLIENT_OUTDATED` | 426 | The remote client is older than the server accepts: its create has no `session_id`, or it calls a service route of a remote session without the remote session channel. Update the client. | | `NOT_FOUND` | 404 | A requested resource (title, history entry, and so on) does not exist. | | `NO_CONTENT` | 404 | The request was valid but produced nothing: no matching titles, tracks, episodes, or keys. | | `JOB_NOT_FOUND` | 404 | The referenced download job does not exist. | diff --git a/docs/dev/rest-api/remote-sessions.md b/docs/dev/rest-api/remote-sessions.md index cfb63e818..84035f665 100644 --- a/docs/dev/rest-api/remote-sessions.md +++ b/docs/dev/rest-api/remote-sessions.md @@ -24,9 +24,6 @@ in the wire form of `unshackle/core/wire.py`. To set up `dl --remote`, read | `GET` | `/api/tunnel` | [The WebSocket of a `--local-proxy` tunnel](#get-apitunnel). | | `GET` | `/api/tunnel/check` | [The exit IP address through a tunnel](#get-apitunnelcheck). | | `GET` | `/api/session/{session_id}/channel` | [The remote session channel](#get-apisessionsession_idchannel): the messages the server starts, and the client's answers. | -| `GET` | `/api/session/{session_id}/prompt` | [The login state and a waiting prompt](#get-apisessionsession_idprompt), the polling fallback of the remote session channel. | -| `POST` | `/api/session/{session_id}/prompt` | [Answer a prompt](#post-apisessionsession_idprompt), the polling fallback. | -| `GET` | `/api/session/{session_id}/logs` | [Service log records](#get-apisessionsession_idlogs), the polling fallback. | | `GET` | `/api/session/{session_id}/titles` | [The titles](#get-apisessionsession_idtitles). | | `POST` | `/api/session/{session_id}/tracks` | [The tracks, chapters and manifests of a title](#post-apisessionsession_idtracks). | | `POST` | `/api/session/{session_id}/segments` | [The URL, DRM, headers and cookies of the selected tracks](#post-apisessionsession_idsegments). | @@ -63,9 +60,9 @@ DELETE /api/session/{id} → the end, with the changed cache files `error_code` from `APIErrorCode`. The server never answers with a `5xx` status. - **Body size.** The create request and `POST /api/search` take a body of up to 8 MiB, the `samples` route up to 16 MiB, and every other route up to 1 MiB. -- **A route that the server lacks.** A client counts an optional call (the segment filter, a bad - content key report, the log poll) as empty only when the server answers `404` with no - `error_code`. Any other error stops the call. +- **Older clients.** The server accepts only the current client flow. A create without + `session_id`, and a service route of a remote session whose client never opened the remote session + channel, get `426 CLIENT_OUTDATED`. ### Slow responses @@ -91,15 +88,14 @@ The login state (`AuthStatus`) tells where the login of a remote session stands: | `authenticated` | The login succeeded. The service routes answer. | | `failed` | The login failed. `error` gives the reason, and each service route answers `AUTH_FAILED`. | -`pending_input` is not a login state: the prompt route reports it while a prompt or a CDM call -waits for the client. The login state stays `authenticating` during that time. Each service route +A prompt or a CDM call that waits for the client does not change the login state: it stays +`authenticating` during that time. Each service route (`titles`, `tracks`, `segments`, `segment_filter`, `samples`, `license`, `keys`, `keys/bad`) answers `400 INVALID_INPUT` while the login state is `authenticating`, and `401 AUTH_FAILED` after a failed login. A prompt waits up to 600 seconds for its answer. When the time ends, the login fails. A prompt after -the login (in the titles, tracks or licence step) goes to the client on an open remote session channel. -Without the channel it fails at once, because the client polls for prompts only during the login. +the login (in the titles, tracks or licence step) goes to the client on the remote session channel. A CDM call goes to the client in any login state. A call that no client takes within 10 seconds fails, because no client listens. A call that a client took waits 60 seconds for its answer. An answer to a @@ -115,7 +111,7 @@ create request, for the whole remote session: | Server CDM | `server_cdm` | The server's device, live, up to the licence cap of the API key. The server vault answers first. | | Client device | `client_device` | The client's own device, through the licence relay. The service sees a stand-in for that device. With `server_vault`, the server vault answers first. | | Lent device | `lent_device` | Nobody licenses live: the service runs on the server's device, and the content keys come only from a vault. | -| No device | `no_device` | No server CDM, and no client device that the service can see: the create had no `cdm_type`, or no `cdm_relay: true`. A client with a CDM licenses through the licence relay. | +| No device | `no_device` | No server CDM, and no client device that the service can see: the create had no `cdm_type`. A client with a CDM licenses through the licence relay. | The create response gives the mode in four fields, and the client reads them back: @@ -126,15 +122,14 @@ The create response gives the mode in four fields, and the client reads them bac | `server_vault` | `false` | the grant | the grant | `false` | | `server_cdm_max_height` | the licence cap, or `null` | the licence cap, or `null` | the licence cap, or `null` | the licence cap, or `null` | -The client reads the no-device mode, and a create response without `server_cdm` and -`server_device`, as the client-device mode. +The client reads the no-device mode as the client-device mode. The server picks the server CDM when the API key has the `server_cdm` grant for the service, unless the client sends `server_cdm: false` with a `cdm_type`, or `quality` asks for more than the licence cap with a `cdm_type`. Above the licence cap without a `cdm_type`, the server refuses the create with `403 SERVER_CDM_CAPPED`. A request that sets one of the service's `SERVER_DEVICE_OPTIONS` keeps the -server CDM. Without the server CDM, a create with `cdm_type` and `cdm_relay: true` (or with a -licence cap) gets the client-device mode, and any other create gets the no-device mode. A service +server CDM. Without the server CDM, a create with `cdm_type` gets the client-device mode, and any other +create gets the no-device mode. A service that calls `lend_server_device()` turns a client-device mode into the lent-device mode. The user's view of each mode is in [Who licenses the tracks](../../guide/remote-sessions.md#who-licenses-the-tracks). @@ -147,8 +142,7 @@ limit, the server ends the remote session. | State | When | Limit | |---|---|---| -| awaited | The client gave the remote session its ID in the create request, and has sent no request and opened no remote session channel since | 150s | -| polling | The client has had no remote session channel | The TTL rule only | +| awaited | The client has opened no remote session channel since the create request | 150s | | present | The remote session channel is open | None | | away | The remote session channel closed with any code except 1000, the connection broke, or the server closed the channel | 180s, or half of `session_ttl` when that is more | | left | The client closed the remote session channel with code 1000 | 90s | @@ -187,7 +181,7 @@ the cache directory of the remote session. A request that waits for the remote s Before a restart the operator can start a drain. A create request then gets `409 SERVER_DRAINING`, and the requests of open remote sessions continue. The server tells each client with the `drain` -message of the remote session channel and the `draining` field of the info route. +message of the remote session channel. --- @@ -203,7 +197,7 @@ the background, and answers at once with the login state `authenticating`. The b |---|---| | `service` | Required. The service tag, in any case, or an alias. | | `title_id` | Required. The title ID or URL, as for `dl`. | -| `session_id` | The ID that the client gives the remote session: the canonical text of a version 4 UUID. Without it, the server makes the ID. | +| `session_id` | Required. The ID that the client gives the remote session: the canonical text of a version 4 UUID. Without it, the create gets `426 CLIENT_OUTDATED`. | | `credentials` | `{username, password, extra?}` for the profile. | | `cookies` | The Netscape cookie file of the profile, zlib-compressed and base64-encoded. | | `cache` | The cache files of the service: a map of cache key to the zlib-compressed, base64-encoded file. See [Cache files](#cache-files). | @@ -214,7 +208,6 @@ the background, and answers at once with the login state `authenticating`. The b | `proxy_region` | The country code that the client resolved `proxy` from. For a server-account service, the server matches it against its own accounts. | | `server_cdm` | `false` when the client declines the server CDM. | | `cdm_type` | The DRM system of the client's CDM (`widevine`, `playready`), or the id of a DRM plugin. | -| `cdm_relay` | `true` when the client answers CDM calls. A plugin `cdm_type` gets no relay. | | `cdm_security_level`, `cdm_system_id`, `cdm_device_type` | The device facts of the client's CDM. `cdm_system_id` and `cdm_device_type` are for Widevine only. | | `service_config` | The identity config keys that the service lists in `client_config`, and the client's `preferences` block. At most 16384 bytes of JSON. | | `plugins` | The DRM plugins of the client: id to `{version, device?}`. `device` holds the plain values of the device attributes that the plugin names in `device_facts`. At most 16384 bytes of JSON. | @@ -226,8 +219,8 @@ the background, and answers at once with the login state `authenticating`. The b `session_id` lets the client delete the remote session before the create answers. A second create with the same ID from the same API key and IP address ends the first one if the first one has not answered, and replaces its remote session when the new one is stored. A second create that fails -leaves that remote session open. A remote session with an ID from the client ends when the client -sends no request for it and opens no remote session channel within 150 seconds of the create. +leaves that remote session open. A remote session ends when the client opens no remote session channel within 150 seconds of the +create. `dl_params` holds `lang`, `v_lang`, `a_lang` and `s_lang` (arrays of language strings), `acodec` (an array of audio codec names or `dl -a` aliases such as `ddp`), and `forced_subs` and `exact_lang` @@ -293,6 +286,7 @@ keys from track data, and keeps the cache on the server. | `400` | `INVALID_SERVICE` | An unknown service, or one that the API key may not use. | | `403` | `FORBIDDEN` | Another API key or another IP address has the `session_id`. | | `404` | `SESSION_NOT_FOUND` | A `DELETE` or a newer create with the same `session_id` ended this create. | +| `426` | `CLIENT_OUTDATED` | No `session_id`: the client is older than the server accepts. | | `409` | `SERVER_DRAINING` | The server drains before a restart. | ### `GET /api/tunnel` @@ -348,27 +342,26 @@ Each message is a JSON text frame with a `type` field (`ChannelMessage`): |---|---|---|---| | `prompt` | server | `id`, `prompt`, `qr` | The service asks the user for input. `qr`, when present, is the text of a QR code to draw with it. | | `cdm_call` | server | `id`, `call` | The service calls the client's CDM. `call` has the shape of [`cdm_call`](#cdm-calls). | -| `log` | server | `seq`, `level`, `message`, `ts`, `qr` | One record of the service log, as the logs route gives it. `qr`, when present, is the text of a QR code to draw under the message. | +| `log` | server | `seq`, `level`, `message`, `ts`, `qr` | One record of the service log. `qr`, when present, is the text of a QR code to draw under the message. | | `status` | server | `status`, `error` | The login state, on attach and at each change. | | `drain` | server | `draining` | The operator started or stopped a drain before a restart. | | `answer` | client | `id`, `response`, `error` | The answer to the `prompt` or `cdm_call` with this `id`. The answer to a CDM call is its JSON object as a string. `error` says why the client cannot answer a prompt, and the service stops at once. | When the client attaches, the server first sends the log records after `since`, the drain state, the prompts and CDM calls that the client did not answer, and the login state. A log record can arrive -twice after a reconnect: the client skips a `seq` it already has. Each prompt and CDM call goes to one -path only: the remote session channel, or the prompt route. +twice after a reconnect: the client skips a `seq` it already has. A prompt or CDM call waits on the +server while the remote session channel is down, and goes out when the client attaches again. The server closes the remote session channel with code `4404` when the remote session ends. The client then stops reconnecting, and its next request finds the remote session gone. The server sends a ping after 20 seconds without data. -The client uses the polling fallback (the prompt and logs routes, and a keep-alive request to the info -route at a third of `expires_in`) in these cases: - -- A gateway in front of the server refuses the WebSocket upgrade, or the connection fails, at the - create. The client then polls for the life of the process. -- The remote session channel drops. The client polls until it reconnects, with a backoff from 1 to 30 - seconds. +The client opens the remote session channel right after the create answers, and keeps it open for the +life of the remote session. When the channel drops, the client connects again with a backoff from 1 to +30 seconds. A refused upgrade at the start ends the run with an error that names the host and the +status. A service route (`titles`, `tracks`, `segments`, `segment_filter`, `samples`, `license`, +`keys` and `keys/bad`) of a remote session whose client never opened the channel gets +`426 CLIENT_OUTDATED`. | Status | Error code | Meaning | | --- | --- | --- | @@ -376,82 +369,6 @@ route at a third of `expires_in`) in these cases: | `403` | `FORBIDDEN` | The remote session belongs to another API key or IP address. | | `404` | `SESSION_NOT_FOUND` | No such remote session. | -### `GET /api/session/{session_id}/prompt` - -The polling fallback of the remote session channel: the login state, and the prompt or CDM call that waits -for the client (`PromptReply`). A client without the remote session channel polls it every 2 seconds during -the login, and every 0.5 seconds while one of its requests runs service code, so that it takes each -CDM call within the 10 seconds of the pickup. - -```json -{ "status": "authenticating" } -{ "status": "pending_input", "prompt": "Enter code: " } -{ "status": "pending_input", "prompt": "Scan the code, then press Enter", "qr": "https://login.example/scan" } -{ "status": "pending_input", "prompt": "...", "cdm_call": { "op": "challenge", "drm": "widevine", "init_data": "...", "license_type": "OFFLINE", "privacy_mode": true, "service_certificate": "..." } } -{ "status": "authenticated" } -{ "status": "failed", "error": "Invalid credentials" } -``` - -#### CDM calls - -A `cdm_call` comes first, in any login state. Its `op` is `challenge`, `keys` (parse a licence and return its keys) or `close`. The -client answers it with a JSON object in `response`: `{"session": "...", "challenge": ""}` for -`challenge`, `{"keys": [{"kid", "type", "key", "permissions"}]}` for `keys`, `{}` for `close`, or -`{"error": "..."}` when its CDM refuses. A `keys` answer holds only the Widevine `OPERATOR_SESSION` and -`SIGNING` keys, never a content key, and the client refuses a PlayReady `keys` call. An answered call -stops waiting at once, so a client that polls again at once does not get it two times. - -| Status | Error code | Meaning | -| --- | --- | --- | -| `200` | - | The login state, and the waiting prompt or CDM call. | -| `403` | `FORBIDDEN` | The remote session belongs to another API key or IP address. | -| `404` | `SESSION_NOT_FOUND` | No such remote session. | - -### `POST /api/session/{session_id}/prompt` - -Answer the waiting prompt or CDM call. Body: `{ "response": "..." }` (`PromptAnswer`). - -=== "Response `200`" - - ```json - { "status": "accepted" } - ``` - -| Status | Error code | Meaning | -| --- | --- | --- | -| `200` | - | Answer accepted. | -| `400` | `INVALID_INPUT` | No `response`, or no prompt waits. | -| `404` | `SESSION_NOT_FOUND` | No such remote session. | - -### `GET /api/session/{session_id}/logs` - -The polling fallback of the remote session channel: the records of the service's own log (`LogsReply`). -Pass `since=` to get only the records after the last sequence number. The route answers in each -login state, `failed` too. - -=== "Response `200`" - - ```json - { - "session_id": "d4e5f6a7-...", - "logs": [ - { "seq": 1, "level": "INFO", "message": "Signed in as profile 'Main'", "ts": 1724990000.1 }, - { "seq": 2, "level": "WARNING", "message": " - The service returned no streams", "ts": 1724990002.7 } - ], - "last_seq": 2 - } - ``` - -The buffer keeps the newest 500 records. Only the logger of the service is copied: the core loggers -stay on the server, and the HTTP requests that the server makes for the service never reach the -client. A server-account remote session sends no log records, because the output of its login can -carry the identity of the operator's account. - -| Status | Error code | Meaning | -| --- | --- | --- | -| `200` | - | Records, oldest first (an empty list when nothing is new). | -| `404` | `SESSION_NOT_FOUND` | No such remote session. | - ### `GET /api/session/{session_id}/titles` The titles of an authenticated remote session (`TitlesReply`), each in the wire form. A slow answer @@ -741,8 +658,7 @@ client never learns the server vault names. ### `GET /api/session/{session_id}` -Remote session info (`SessionInfo`). The client also uses it as the keep-alive of the polling -fallback. +Remote session info (`SessionInfo`). === "Response `200`" @@ -751,17 +667,11 @@ fallback. "session_id": "d4e5f6a7-...", "service": "EXAMPLE", "valid": true, - "expires_in": 300, - "draining": false, "track_count": 4, "title_count": 10 } ``` -`expires_in` is the configured `session_ttl`, not the seconds that remain for this remote session. -`draining` is `true` after the operator starts a drain before a restart. The client checks it before -each title. - | Status | Error code | Meaning | | --- | --- | --- | | `200` | - | Info returned. | diff --git a/tests/core/test_drm_plugins.py b/tests/core/test_drm_plugins.py index 0afed76f3..1325542c7 100644 --- a/tests/core/test_drm_plugins.py +++ b/tests/core/test_drm_plugins.py @@ -184,7 +184,7 @@ def test_a_stub_of_a_plugin_system_is_that_system(example_plugins: None) -> None def test_a_client_with_a_plugin_cdm_is_a_stand_in_of_its_system(example_plugins: None) -> None: from unshackle.core.api.handlers import client_device_cdm - cdm = client_device_cdm({"cdm_type": "example", "cdm_relay": True}, input_bridge=SimpleNamespace()) + cdm = client_device_cdm({"cdm_type": "example"}, input_bridge=SimpleNamespace()) assert cdm_system(cdm) == "example" diff --git a/tests/remote/e2e/channel.py b/tests/remote/e2e/channel.py new file mode 100644 index 000000000..8d3e0fee4 --- /dev/null +++ b/tests/remote/e2e/channel.py @@ -0,0 +1,35 @@ +"""Open a remote session as the dl --remote client does: a create with its own session_id, then the channel.""" + +from __future__ import annotations + +import asyncio +import threading +import uuid +from typing import Any + +import aiohttp +import requests + +from unshackle.core.remote_protocol import CHANNEL_ROUTE, SESSION_CREATE_ROUTE + + +def open_session(http_session: requests.Session, server_url: str, payload: dict[str, Any]) -> requests.Response: + """POST create and hold the remote session channel open on a daemon thread; the create reply.""" + session_id = str(uuid.uuid4()) + body = {**payload, "session_id": session_id} + reply = http_session.post(server_url + SESSION_CREATE_ROUTE, json=body, timeout=120) + if reply.ok: + attached = threading.Event() + headers = {k: str(v) for k, v in http_session.headers.items() if k.startswith("X-")} + url = server_url + CHANNEL_ROUTE.format(session_id=session_id) + threading.Thread(target=asyncio.run, args=(hold_channel(url, headers, attached),), daemon=True).start() + assert attached.wait(30), f"the remote session channel of {session_id} did not open" + return reply + + +async def hold_channel(url: str, headers: dict[str, str], attached: threading.Event) -> None: + """Read the channel until the server closes it, as the remote session ends.""" + async with aiohttp.ClientSession(headers=headers) as http, http.ws_connect(url) as ws: + attached.set() + async for _ in ws: + pass diff --git a/tests/remote/e2e/test_live_download.py b/tests/remote/e2e/test_live_download.py index febe24e80..993966946 100644 --- a/tests/remote/e2e/test_live_download.py +++ b/tests/remote/e2e/test_live_download.py @@ -17,6 +17,8 @@ import time import pytest +from tests.remote.e2e.channel import open_session + pytestmark = [pytest.mark.live, pytest.mark.slow] @@ -31,7 +33,7 @@ def wait_titles(http_session, server_url: str, sid: str, timeout: float = 120.0) body = r.json() except Exception: body = {} - if (body.get("details") or {}).get("auth_status") in ("authenticating", "pending_input"): + if (body.get("details") or {}).get("auth_status") == "authenticating": time.sleep(2.0) continue return None @@ -60,9 +62,10 @@ def test_download_manifest_fetch(http_session, server_url: str, service_case) -> if not title_input: pytest.skip(f"{service}: no title/series in fixture") - r = http_session.post( - f"{server_url}/api/session/create", - json={ + r = open_session( + http_session, + server_url, + { "service": service, "title_id": title_input, "range_": ["SDR"], @@ -70,7 +73,6 @@ def test_download_manifest_fetch(http_session, server_url: str, service_case) -> "quality": [target_height], "best_available": True, }, - timeout=120, ) if r.status_code >= 400: pytest.skip(f"{service}: session create failed {r.status_code}: {r.text[:200]}") diff --git a/tests/remote/e2e/test_live_input_bridge.py b/tests/remote/e2e/test_live_input_bridge.py deleted file mode 100644 index 677307f80..000000000 --- a/tests/remote/e2e/test_live_input_bridge.py +++ /dev/null @@ -1,46 +0,0 @@ -"""E2E: interactive auth prompt round-trip. - -For services that don't naturally prompt during ``authenticate()``, the -test still verifies the GET prompt endpoint returns the documented -shape (empty when no prompt pending). -""" - -from __future__ import annotations - -import pytest - -pytestmark = [pytest.mark.live, pytest.mark.slow] - - -def test_prompt_endpoint_shape_without_pending(http_session, server_url: str, service_case) -> None: - service, conf = service_case - r = http_session.post( - f"{server_url}/api/session/create", - json={"service": service, "title_id": conf["title_url"]}, - timeout=120, - ) - if r.status_code >= 400: - pytest.skip(f"{service}: session creation failed: {r.status_code}") - sid = r.json()["session_id"] - try: - pr = http_session.get(f"{server_url}/api/session/{sid}/prompt", timeout=10) - assert pr.status_code in (200, 404), pr.text - if pr.status_code == 200: - body = pr.json() - assert "prompt" in body or "status" in body - finally: - http_session.delete(f"{server_url}/api/session/{sid}", timeout=30) - - -def test_prompt_post_unknown_session_returns_404(http_session, server_url: str) -> None: - r = http_session.post( - f"{server_url}/api/session/bogus-session-id/prompt", - json={"response": "irrelevant"}, - timeout=10, - ) - assert r.status_code == 404 - - -def test_prompt_get_unknown_session_returns_404(http_session, server_url: str) -> None: - r = http_session.get(f"{server_url}/api/session/bogus-session-id/prompt", timeout=10) - assert r.status_code == 404 diff --git a/tests/remote/e2e/test_live_license.py b/tests/remote/e2e/test_live_license.py index f87e895fd..19cd6f957 100644 --- a/tests/remote/e2e/test_live_license.py +++ b/tests/remote/e2e/test_live_license.py @@ -17,6 +17,8 @@ import time import pytest +from tests.remote.e2e.channel import open_session + pytestmark = [pytest.mark.live, pytest.mark.slow] @@ -31,7 +33,7 @@ def wait_titles(http_session, server_url: str, sid: str, timeout: float = 120.0) body = r.json() except Exception: body = {} - if (body.get("details") or {}).get("auth_status") in ("authenticating", "pending_input"): + if (body.get("details") or {}).get("auth_status") == "authenticating": time.sleep(2.0) continue return None @@ -64,16 +66,16 @@ def test_license_server_cdm(http_session, server_url: str, service_case) -> None if not title_input: pytest.skip(f"{service}: no title/series in fixture") - r = http_session.post( - f"{server_url}/api/session/create", - json={ + r = open_session( + http_session, + server_url, + { "service": service, "title_id": title_input, "range_": ["SDR"], "vcodec": ["AVC"], "best_available": True, }, - timeout=120, ) if r.status_code >= 400: pytest.skip(f"{service}: session create failed {r.status_code}: {r.text[:200]}") diff --git a/tests/remote/e2e/test_live_quality.py b/tests/remote/e2e/test_live_quality.py index 84ac84066..da6f9e366 100644 --- a/tests/remote/e2e/test_live_quality.py +++ b/tests/remote/e2e/test_live_quality.py @@ -15,6 +15,8 @@ from typing import Any import pytest +from tests.remote.e2e.channel import open_session + pytestmark = [pytest.mark.live, pytest.mark.slow] @@ -27,7 +29,7 @@ def create_session(http_session, server_url: str, service: str, title_id: str) - "vcodec": ["AVC", "HEVC"], "best_available": True, } - r = http_session.post(f"{server_url}/api/session/create", json=payload, timeout=120) + r = open_session(http_session, server_url, payload) if r.status_code >= 400: pytest.skip(f"{service}: session create failed {r.status_code}: {r.text[:200]}") return r.json()["session_id"] @@ -44,7 +46,7 @@ def wait_for_titles(http_session, server_url: str, sid: str, timeout: float = 12 body = r.json() except Exception: body = {} - if (body.get("details") or {}).get("auth_status") in ("authenticating", "pending_input"): + if (body.get("details") or {}).get("auth_status") == "authenticating": time.sleep(2.0) continue return r.status_code, r.json() if r.text else {} diff --git a/tests/remote/e2e/test_live_session_lifecycle.py b/tests/remote/e2e/test_live_session_lifecycle.py index 6a361698e..0d2321f93 100644 --- a/tests/remote/e2e/test_live_session_lifecycle.py +++ b/tests/remote/e2e/test_live_session_lifecycle.py @@ -6,12 +6,14 @@ import time import pytest +from tests.remote.e2e.channel import open_session + pytestmark = [pytest.mark.live, pytest.mark.slow] def create_session(http_session, server_url: str, service: str, conf: dict) -> str: payload = {"service": service, "title_id": conf["title_url"]} - r = http_session.post(f"{server_url}/api/session/create", json=payload, timeout=120) + r = open_session(http_session, server_url, payload) if r.status_code >= 400: pytest.skip(f"Auth/setup not available for {service}: {r.status_code} {r.text[:200]}") body = r.json() @@ -37,7 +39,7 @@ def wait_for_titles(http_session, server_url: str, sid: str, timeout: float = 12 except Exception: body = {} auth_status = (body.get("details") or {}).get("auth_status") - if auth_status in ("authenticating", "pending_input"): + if auth_status == "authenticating": time.sleep(2.0) continue return r.status_code, r.json() if r.text else {} diff --git a/tests/remote/key_source.py b/tests/remote/key_source.py index 06fb895ec..f871a8390 100644 --- a/tests/remote/key_source.py +++ b/tests/remote/key_source.py @@ -82,7 +82,6 @@ def remote_session(local_cdm: Any, answer: dict) -> RemoteService: svc.log = logging.getLogger("test-remote-session") posts: list = [] svc.client = SimpleNamespace(post=lambda endpoint, payload, expect=(): posts.append(payload) or answer) - svc.drain_server_logs = lambda: None svc.posts = posts return svc diff --git a/tests/remote/sessions.py b/tests/remote/sessions.py index e2e19d402..5dd4fd330 100644 --- a/tests/remote/sessions.py +++ b/tests/remote/sessions.py @@ -18,8 +18,8 @@ from unshackle.core.remote_service import RemoteClient def session_entry(**fields: Any) -> SessionEntry: - """A remote session that the server CDM licenses, unless *fields* set another :class:`SessionEntry` value.""" - return SessionEntry( + """A remote session that the server CDM licenses and whose client attached its channel, unless *fields* say other.""" + entry = SessionEntry( **{ "session_id": "sess", "service_tag": "EXAMPLE", @@ -28,6 +28,8 @@ def session_entry(**fields: Any) -> SessionEntry: **fields, } ) + entry.presence.attached() + return entry def session_launch(licensor: Licensor = Licensor.NO_DEVICE, **fields: Any) -> SessionLaunch: @@ -75,4 +77,5 @@ def hold_session(service: Any, session_id: str | None = "sess") -> None: client = SimpleNamespace(send=unreachable, timeout=1, tunnel=None) service.lifetime = RemoteSessionLifetime(client, lambda cache: None) # type: ignore[arg-type] if session_id: - service.lifetime.adopt(service.lifetime.name(), session_id) + service.lifetime._held.add(session_id) + service.lifetime.adopt(session_id) diff --git a/tests/remote/unit/snapshots/route_error_replies.json b/tests/remote/unit/snapshots/route_error_replies.json index c29b8a7f3..9c3299cc6 100644 --- a/tests/remote/unit/snapshots/route_error_replies.json +++ b/tests/remote/unit/snapshots/route_error_replies.json @@ -558,184 +558,6 @@ }, "status": 403 }, - "GET /api/session/{session_id}/logs no key": { - "body": { - "message": "Secret Key is Empty.", - "status": 401 - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [], - "stats": { - "error": null, - "late_status": null - }, - "status": 401 - }, - "GET /api/session/{session_id}/logs plain before the handler's try": { - "body": { - "details": { - "operation": "session_logs" - }, - "error_code": "INTERNAL_ERROR", - "message": "An unexpected error occurred: pinned failure (ref REF)", - "ref": "REF", - "status": "error", - "timestamp": "TIMESTAMP" - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [ - "Error ref REF: INTERNAL_ERROR 422 GET /api/session/pinned-session/logs service=- user=test\u2026: An unexpected error occurred: pinned failure" - ], - "stats": { - "error": { - "code": "INTERNAL_ERROR", - "message": "An unexpected error occurred: pinned failure", - "ref": "REF" - }, - "late_status": null - }, - "status": 422 - }, - "GET /api/session/{session_id}/logs unknown session": { - "body": { - "details": { - "session_id": "pinned-session" - }, - "error_code": "SESSION_NOT_FOUND", - "message": "Session not found or expired: pinned-session (ref REF)", - "ref": "REF", - "status": "error", - "timestamp": "TIMESTAMP" - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [ - "Error ref REF: SESSION_NOT_FOUND 404 GET /api/session/pinned-session/logs service=- user=test\u2026: Session not found or expired: pinned-session" - ], - "stats": { - "error": { - "code": "SESSION_NOT_FOUND", - "message": "Session not found or expired: pinned-session", - "ref": "REF" - }, - "late_status": null - }, - "status": 404 - }, - "GET /api/session/{session_id}/logs wrong owner": { - "body": { - "error_code": "FORBIDDEN", - "message": "Session access denied (ref REF)", - "ref": "REF", - "status": "error", - "timestamp": "TIMESTAMP" - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [ - "Error ref REF: FORBIDDEN 403 GET /api/session/pinned-session/logs service=EXAMPLE user=test\u2026: Session access denied" - ], - "stats": { - "error": { - "code": "FORBIDDEN", - "message": "Session access denied", - "ref": "REF" - }, - "late_status": null - }, - "status": 403 - }, - "GET /api/session/{session_id}/prompt no key": { - "body": { - "message": "Secret Key is Empty.", - "status": 401 - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [], - "stats": { - "error": null, - "late_status": null - }, - "status": 401 - }, - "GET /api/session/{session_id}/prompt plain before the handler's try": { - "body": { - "details": { - "operation": "session_prompt_get" - }, - "error_code": "INTERNAL_ERROR", - "message": "An unexpected error occurred: pinned failure (ref REF)", - "ref": "REF", - "status": "error", - "timestamp": "TIMESTAMP" - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [ - "Error ref REF: INTERNAL_ERROR 422 GET /api/session/pinned-session/prompt service=- user=test\u2026: An unexpected error occurred: pinned failure" - ], - "stats": { - "error": { - "code": "INTERNAL_ERROR", - "message": "An unexpected error occurred: pinned failure", - "ref": "REF" - }, - "late_status": null - }, - "status": 422 - }, - "GET /api/session/{session_id}/prompt unknown session": { - "body": { - "details": { - "session_id": "pinned-session" - }, - "error_code": "SESSION_NOT_FOUND", - "message": "Session not found or expired: pinned-session (ref REF)", - "ref": "REF", - "status": "error", - "timestamp": "TIMESTAMP" - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [ - "Error ref REF: SESSION_NOT_FOUND 404 GET /api/session/pinned-session/prompt service=- user=test\u2026: Session not found or expired: pinned-session" - ], - "stats": { - "error": { - "code": "SESSION_NOT_FOUND", - "message": "Session not found or expired: pinned-session", - "ref": "REF" - }, - "late_status": null - }, - "status": 404 - }, - "GET /api/session/{session_id}/prompt wrong owner": { - "body": { - "error_code": "FORBIDDEN", - "message": "Session access denied (ref REF)", - "ref": "REF", - "status": "error", - "timestamp": "TIMESTAMP" - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [ - "Error ref REF: FORBIDDEN 403 GET /api/session/pinned-session/prompt service=EXAMPLE user=test\u2026: Session access denied" - ], - "stats": { - "error": { - "code": "FORBIDDEN", - "message": "Session access denied", - "ref": "REF" - }, - "late_status": null - }, - "status": 403 - }, "GET /api/session/{session_id}/titles no key": { "body": { "message": "Secret Key is Empty.", @@ -1942,144 +1764,6 @@ }, "status": 403 }, - "POST /api/session/{session_id}/prompt no key": { - "body": { - "message": "Secret Key is Empty.", - "status": 401 - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [], - "stats": { - "error": null, - "late_status": null - }, - "status": 401 - }, - "POST /api/session/{session_id}/prompt not an object": { - "body": { - "error_code": "INVALID_INPUT", - "message": "The request body must be a JSON object (ref REF)", - "ref": "REF", - "status": "error", - "timestamp": "TIMESTAMP" - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [ - "Error ref REF: INVALID_INPUT 400 POST /api/session/pinned-session/prompt service=- user=test\u2026: The request body must be a JSON object" - ], - "stats": { - "error": { - "code": "INVALID_INPUT", - "message": "The request body must be a JSON object", - "ref": "REF" - }, - "late_status": null - }, - "status": 400 - }, - "POST /api/session/{session_id}/prompt not json": { - "body": { - "details": { - "error": "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)" - }, - "error_code": "INVALID_INPUT", - "message": "Invalid JSON request body (ref REF)", - "ref": "REF", - "status": "error", - "timestamp": "TIMESTAMP" - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [ - "Error ref REF: INVALID_INPUT 400 POST /api/session/pinned-session/prompt service=- user=test\u2026: Invalid JSON request body" - ], - "stats": { - "error": { - "code": "INVALID_INPUT", - "message": "Invalid JSON request body", - "ref": "REF" - }, - "late_status": null - }, - "status": 400 - }, - "POST /api/session/{session_id}/prompt plain before the handler's try": { - "body": { - "details": { - "operation": "session_prompt_submit" - }, - "error_code": "INTERNAL_ERROR", - "message": "An unexpected error occurred: pinned failure (ref REF)", - "ref": "REF", - "status": "error", - "timestamp": "TIMESTAMP" - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [ - "Error ref REF: INTERNAL_ERROR 422 POST /api/session/pinned-session/prompt service=- user=test\u2026: An unexpected error occurred: pinned failure" - ], - "stats": { - "error": { - "code": "INTERNAL_ERROR", - "message": "An unexpected error occurred: pinned failure", - "ref": "REF" - }, - "late_status": null - }, - "status": 422 - }, - "POST /api/session/{session_id}/prompt unknown session": { - "body": { - "details": { - "session_id": "pinned-session" - }, - "error_code": "SESSION_NOT_FOUND", - "message": "Session not found or expired: pinned-session (ref REF)", - "ref": "REF", - "status": "error", - "timestamp": "TIMESTAMP" - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [ - "Error ref REF: SESSION_NOT_FOUND 404 POST /api/session/pinned-session/prompt service=- user=test\u2026: Session not found or expired: pinned-session" - ], - "stats": { - "error": { - "code": "SESSION_NOT_FOUND", - "message": "Session not found or expired: pinned-session", - "ref": "REF" - }, - "late_status": null - }, - "status": 404 - }, - "POST /api/session/{session_id}/prompt wrong owner": { - "body": { - "error_code": "FORBIDDEN", - "message": "Session access denied (ref REF)", - "ref": "REF", - "status": "error", - "timestamp": "TIMESTAMP" - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [ - "Error ref REF: FORBIDDEN 403 POST /api/session/pinned-session/prompt service=EXAMPLE user=test\u2026: Session access denied" - ], - "stats": { - "error": { - "code": "FORBIDDEN", - "message": "Session access denied", - "ref": "REF" - }, - "late_status": null - }, - "status": 403 - }, "POST /api/session/{session_id}/samples no key": { "body": { "message": "Secret Key is Empty.", @@ -3025,219 +2709,6 @@ }, "status": 422 }, - "logs api": { - "body": { - "details": { - "pinned": true - }, - "error_code": "SERVICE_ERROR", - "message": "pinned refusal (ref REF)", - "ref": "REF", - "status": "error", - "timestamp": "TIMESTAMP" - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [ - "Error ref REF: SERVICE_ERROR 422 GET /api/session/pinned-session/logs service=EXAMPLE user=test\u2026: pinned refusal" - ], - "stats": { - "error": { - "code": "SERVICE_ERROR", - "message": "pinned refusal", - "ref": "REF" - }, - "late_status": null - }, - "status": 422 - }, - "logs exit": { - "body": { - "details": { - "reason": "service_exit" - }, - "error_code": "SERVICE_ERROR", - "message": "Service exited (ref REF)", - "ref": "REF", - "status": "error", - "timestamp": "TIMESTAMP" - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [], - "stats": { - "raised": true - }, - "status": 422 - }, - "logs plain": { - "body": { - "details": { - "operation": "session_logs" - }, - "error_code": "INTERNAL_ERROR", - "message": "An unexpected error occurred: pinned failure (ref REF)", - "ref": "REF", - "status": "error", - "timestamp": "TIMESTAMP" - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [ - "Error ref REF: INTERNAL_ERROR 422 GET /api/session/pinned-session/logs service=EXAMPLE user=test\u2026: An unexpected error occurred: pinned failure" - ], - "stats": { - "error": { - "code": "INTERNAL_ERROR", - "message": "An unexpected error occurred: pinned failure", - "ref": "REF" - }, - "late_status": null - }, - "status": 422 - }, - "prompt get api": { - "body": { - "details": { - "pinned": true - }, - "error_code": "SERVICE_ERROR", - "message": "pinned refusal (ref REF)", - "ref": "REF", - "status": "error", - "timestamp": "TIMESTAMP" - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [ - "Error ref REF: SERVICE_ERROR 422 GET /api/session/pinned-session/prompt service=EXAMPLE user=test\u2026: pinned refusal" - ], - "stats": { - "error": { - "code": "SERVICE_ERROR", - "message": "pinned refusal", - "ref": "REF" - }, - "late_status": null - }, - "status": 422 - }, - "prompt get exit": { - "body": { - "details": { - "reason": "service_exit" - }, - "error_code": "SERVICE_ERROR", - "message": "Service exited (ref REF)", - "ref": "REF", - "status": "error", - "timestamp": "TIMESTAMP" - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [], - "stats": { - "raised": true - }, - "status": 422 - }, - "prompt get plain": { - "body": { - "details": { - "operation": "session_prompt_get" - }, - "error_code": "INTERNAL_ERROR", - "message": "An unexpected error occurred: pinned failure (ref REF)", - "ref": "REF", - "status": "error", - "timestamp": "TIMESTAMP" - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [ - "Error ref REF: INTERNAL_ERROR 422 GET /api/session/pinned-session/prompt service=EXAMPLE user=test\u2026: An unexpected error occurred: pinned failure" - ], - "stats": { - "error": { - "code": "INTERNAL_ERROR", - "message": "An unexpected error occurred: pinned failure", - "ref": "REF" - }, - "late_status": null - }, - "status": 422 - }, - "prompt submit api": { - "body": { - "details": { - "pinned": true - }, - "error_code": "SERVICE_ERROR", - "message": "pinned refusal (ref REF)", - "ref": "REF", - "status": "error", - "timestamp": "TIMESTAMP" - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [ - "Error ref REF: SERVICE_ERROR 422 POST /api/session/pinned-session/prompt service=EXAMPLE user=test\u2026: pinned refusal" - ], - "stats": { - "error": { - "code": "SERVICE_ERROR", - "message": "pinned refusal", - "ref": "REF" - }, - "late_status": null - }, - "status": 422 - }, - "prompt submit exit": { - "body": { - "details": { - "reason": "service_exit" - }, - "error_code": "SERVICE_ERROR", - "message": "Service exited (ref REF)", - "ref": "REF", - "status": "error", - "timestamp": "TIMESTAMP" - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [], - "stats": { - "raised": true - }, - "status": 422 - }, - "prompt submit plain": { - "body": { - "details": { - "operation": "session_prompt_submit" - }, - "error_code": "INTERNAL_ERROR", - "message": "An unexpected error occurred: pinned failure (ref REF)", - "ref": "REF", - "status": "error", - "timestamp": "TIMESTAMP" - }, - "content_type": "application/json", - "leading_newlines": false, - "log": [ - "Error ref REF: INTERNAL_ERROR 422 POST /api/session/pinned-session/prompt service=EXAMPLE user=test\u2026: An unexpected error occurred: pinned failure" - ], - "stats": { - "error": { - "code": "INTERNAL_ERROR", - "message": "An unexpected error occurred: pinned failure", - "ref": "REF" - }, - "late_status": null - }, - "status": 422 - }, "samples api": { "body": { "details": { @@ -3879,6 +3350,29 @@ }, "status": 422 }, + "session create no session id": { + "body": { + "error_code": "CLIENT_OUTDATED", + "message": "This client is older than the server accepts: update unshackle to the current dev build (ref REF)", + "ref": "REF", + "status": "error", + "timestamp": "TIMESTAMP" + }, + "content_type": "application/json", + "leading_newlines": false, + "log": [ + "Error ref REF: CLIENT_OUTDATED 426 POST /api/session/create service=EXAMPLE user=test\u2026: This client is older than the server accepts: update unshackle to the current dev build" + ], + "stats": { + "error": { + "code": "CLIENT_OUTDATED", + "message": "This client is older than the server accepts: update unshackle to the current dev build", + "ref": "REF" + }, + "late_status": null + }, + "status": 426 + }, "session create no title": { "body": { "error_code": "INVALID_INPUT", @@ -4118,6 +3612,29 @@ }, "status": 200 }, + "titles no channel": { + "body": { + "error_code": "CLIENT_OUTDATED", + "message": "This client is older than the server accepts: update unshackle to the current dev build (ref REF)", + "ref": "REF", + "status": "error", + "timestamp": "TIMESTAMP" + }, + "content_type": "application/json", + "leading_newlines": false, + "log": [ + "Error ref REF: CLIENT_OUTDATED 426 GET /api/session/pinned-session/titles service=EXAMPLE user=test\u2026: This client is older than the server accepts: update unshackle to the current dev build" + ], + "stats": { + "error": { + "code": "CLIENT_OUTDATED", + "message": "This client is older than the server accepts: update unshackle to the current dev build", + "ref": "REF" + }, + "late_status": null + }, + "status": 426 + }, "titles plain": { "body": { "details": { diff --git a/tests/remote/unit/test_client_device_cdm.py b/tests/remote/unit/test_client_device_cdm.py index 25de90d95..b1f0c8c6b 100644 --- a/tests/remote/unit/test_client_device_cdm.py +++ b/tests/remote/unit/test_client_device_cdm.py @@ -15,6 +15,7 @@ from pywidevine import DeviceTypes from pywidevine.pssh import PSSH from tests.remote.sessions import hold_session, launch_session, session_entry +from tests.remote.unit.test_tunnel import wait_until from unshackle.core.api import handlers, key_policy, server_keys from unshackle.core.api.errors import APIError from unshackle.core.api.input_bridge import InputBridge @@ -64,7 +65,7 @@ class FakeWidevineCdm: class DirectBridge: - """Answers each call at once on the client's CDM, as the client poller would.""" + """Answers each call at once on the client's CDM, as the client's session channel would.""" def __init__(self, cdm: Any) -> None: self.cdm = cdm @@ -106,24 +107,34 @@ def test_the_client_refuses_a_challenge_for_the_other_drm_system() -> None: assert "not a playready device" in answer["error"] +def attached_channel(bridge: InputBridge) -> list[Any]: + """Attach a session channel that takes every ask; the asks it took.""" + offered: list[Any] = [] + bridge.channel = SimpleNamespace(attached=True, offer=lambda ask: offered.append(ask) or True) # type: ignore[assignment] + return offered + + +def wait_offered(offered: list[Any]) -> Any: + assert wait_until(lambda: offered, 5), "the bridge offered no ask to the channel" + return offered[0] + + def test_a_cdm_call_after_authentication_leaves_the_status_alone() -> None: bridge = InputBridge() bridge.login_status = AuthStatus.AUTHENTICATED + offered = attached_channel(bridge) result: list[dict] = [] worker = threading.Thread(target=lambda: result.append(bridge.request_cdm({"op": "challenge"}, timeout=5))) worker.start() - for _ in range(100): - if bridge.get_pending_cdm_call(): - break - time.sleep(0.01) - assert bridge.get_pending_cdm_call() == {"op": "challenge"} + ask = wait_offered(offered) + assert ask.cdm_call == {"op": "challenge"} - assert bridge.submit_response(json.dumps({"session": "s", "challenge": "Yw=="})) + assert bridge.answer(ask.id, json.dumps({"session": "s", "challenge": "Yw=="})) worker.join(timeout=2) assert result == [{"session": "s", "challenge": "Yw=="}] - assert bridge.status is AuthStatus.AUTHENTICATED - assert bridge.get_pending_cdm_call() is None + assert bridge.login_status is AuthStatus.AUTHENTICATED + assert bridge.get_pending_ask() is None @pytest.mark.parametrize( @@ -183,7 +194,6 @@ def test_a_relaying_client_gets_a_stand_in_with_its_device_facts(monkeypatch: py data = { "cdm_type": "widevine", "cdm_security_level": 1, - "cdm_relay": True, "cdm_system_id": 4464, "cdm_device_type": "ANDROID", "service_config": {"esn": "CLIENT"}, @@ -224,12 +234,12 @@ def test_an_answered_call_is_no_longer_pending_before_the_service_wakes(monkeypa worker = threading.Thread(target=lambda: bridge.request_cdm({"op": "challenge"}, timeout=5)) worker.start() for _ in range(100): - if bridge.get_pending_cdm_call(): + if bridge.get_pending_ask(): break time.sleep(0.01) assert bridge.submit_response(json.dumps({"session": "s", "challenge": "Yw=="})) - assert bridge.get_pending_cdm_call() is None + assert bridge.get_pending_ask() is None assert bridge.submit_response("{}") is False release.set() worker.join(timeout=2) @@ -341,7 +351,7 @@ def test_a_lent_device_gives_the_service_the_server_config_back(monkeypatch: pyt monkeypatch.setattr(handlers.Services, "load", lambda tag: Declares) monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: SimpleNamespace()) - data = {"cdm_type": "widevine", "cdm_relay": True, "service_config": {"esn": "CLIENT", "esn_map": {"1": "c"}}} + data = {"cdm_type": "widevine", "service_config": {"esn": "CLIENT", "esn_map": {"1": "c"}}} launch_session("EXAMPLE1", "t", data, licensor=Licensor.CLIENT_DEVICE) service_config = built["config"] assert service_config["esn"] == "CLIENT" @@ -382,7 +392,7 @@ def test_a_server_device_option_takes_the_first_listed_device_of_a_dual_entry( monkeypatch.setattr(handlers.Services, "load", lambda tag: ServerSideService) monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: SimpleNamespace()) - data = {"cdm_type": client_type, "cdm_relay": True, "service_params": {"server_side": server_side}} + data = {"cdm_type": client_type, "service_params": {"server_side": server_side}} launch_session("EXAMPLE1", "t", data, licensor=Licensor.CLIENT_DEVICE if client_device else Licensor.SERVER_CDM) if client_device: built["cdm"].lend_server_device() @@ -444,7 +454,7 @@ def test_a_lent_device_session_returns_no_cache_at_the_end(monkeypatch: pytest.M session = lent_device_session() - async def validated(session_id: str, request: Any) -> Any: + async def validated(session_id: str, request: Any, needs_channel: bool = True) -> Any: return session monkeypatch.setattr(handlers, "get_validated_session", validated) @@ -498,21 +508,19 @@ def test_a_call_no_client_fetches_fails_fast_and_restores_the_status() -> None: with pytest.raises(TimeoutError, match="none is listening"): bridge.request_cdm({"op": "challenge"}, timeout=30, pickup=0.2) assert time.monotonic() - started < 5 - assert bridge.status is AuthStatus.AUTHENTICATED - assert bridge.get_pending_cdm_call() is None + assert bridge.login_status is AuthStatus.AUTHENTICATED + assert bridge.get_pending_ask() is None -def test_a_fetched_call_gets_the_full_answer_window() -> None: +def test_a_call_the_channel_took_gets_the_full_answer_window() -> None: bridge = InputBridge() + offered = attached_channel(bridge) result: list[dict] = [] worker = threading.Thread(target=lambda: result.append(bridge.request_cdm({"op": "keys"}, timeout=5, pickup=0.3))) worker.start() - for _ in range(100): - if bridge.get_pending_cdm_call(): - break - time.sleep(0.01) - time.sleep(0.6) # past the pickup window: a fetched call must still wait for its answer - assert bridge.submit_response(json.dumps({"keys": []})) + ask = wait_offered(offered) + time.sleep(0.6) # past the pickup window: a call the channel took must still wait for its answer + assert bridge.answer(ask.id, json.dumps({"keys": []})) worker.join(timeout=2) assert result == [{"keys": []}] diff --git a/tests/remote/unit/test_client_presence.py b/tests/remote/unit/test_client_presence.py index 566a1339f..802824490 100644 --- a/tests/remote/unit/test_client_presence.py +++ b/tests/remote/unit/test_client_presence.py @@ -24,11 +24,9 @@ from aiohttp import web from tests.remote.unit.test_remote_loopback import server # noqa: F401 from tests.remote.unit.test_remote_loopback import ( - CODE, KEY, OTHER_KEY, StubService, - gate_channel, make_client, on_loop, ) @@ -54,20 +52,18 @@ from unshackle.core.api.client_presence import ( from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge from unshackle.core.api.session_store import SessionEntry, SessionStore from unshackle.core.config import config -from unshackle.core.remote_channel import CDM_CLOSE_TIMEOUT +from unshackle.core.remote_channel import CDM_CLOSE_TIMEOUT, RECONNECT_DELAY, RECONNECT_MAX from unshackle.core.remote_lifetime import END_TIMEOUT from unshackle.core.remote_protocol import ( CHANNEL_ROUTE, CHANNEL_SESSION_GONE, - LOGS_ROUTE, - PROMPT_ROUTE, SESSION_CREATE_ROUTE, SESSION_ROUTE, TITLES_ROUTE, APIErrorCode, AuthStatus, ) -from unshackle.core.remote_service import PROBE_TIMEOUT +from unshackle.core.remote_service import RemoteError from unshackle.core.tunnel import HEARTBEAT pytestmark = pytest.mark.unit @@ -222,6 +218,7 @@ def test_a_request_that_waits_for_the_lock_does_not_start_after_the_end( assert create(server.url, session_id).status_code == 200 (entry,) = sessions() assert logged_in(entry) + entry.presence.attached() try: first = in_thread(lambda: get(server, TITLES_ROUTE, entry)) assert wait_until(lambda: len(started) == 1, DEADLINE) @@ -235,37 +232,6 @@ def test_a_request_that_waits_for_the_lock_does_not_start_after_the_end( assert len(started) == 1 -@pytest.mark.parametrize("route", [SESSION_ROUTE, PROMPT_ROUTE, LOGS_ROUTE]) -def test_the_polls_of_a_client_without_its_channel_keep_its_session_during_a_long_request( - server: SimpleNamespace, # noqa: F811 - logins: list[Any], # noqa: F811 - monkeypatch: pytest.MonkeyPatch, - route: str, -) -> None: - refuse, release = gate_channel(monkeypatch), Event() - monkeypatch.setitem(StubService.hooks, "titles", lambda stub: release.wait(DEADLINE)) - service = make_client(server.url) - try: - service.authenticate() - (entry,) = sessions() - assert state_is(entry, ClientState.PRESENT) - listing = in_thread(service.get_titles) - assert wait_until(entry.lock.locked, DEADLINE) - refuse.set() - on_loop(server, entry.channel.ws.close()) # type: ignore[union-attr] - assert state_is(entry, ClientState.AWAY), "a close that the server starts is not the client's" - for _ in range(3): - silent_for(entry, AWAY_LIMIT - 5) - assert get(server, route, entry).ok and entry.lock.locked() - assert entry.presence.silence < AWAY_LIMIT / 2 and entry.presence.state is ClientState.AWAY - assert sweep(server) == 0 - release.set() - assert len(listing()) == 3 - finally: - release.set() - service.close() - - def test_a_delete_after_the_close_of_the_channel_returns_the_login_cache( server: SimpleNamespace, # noqa: F811 logins: list[Any], # noqa: F811 @@ -331,34 +297,18 @@ def half_open_gateway(server: SimpleNamespace) -> Iterator[str]: # noqa: F811 on_loop(server, runner.cleanup()) -def test_a_user_who_types_a_code_keeps_the_session_that_the_channel_failed_to_open( +def test_a_refused_channel_upgrade_stops_the_client_with_one_line( server: SimpleNamespace, # noqa: F811 - monkeypatch: pytest.MonkeyPatch, + logins: list[Any], # noqa: F811 ) -> None: - """The server saw a channel and its loss, and the client polls: it must do so while its user types.""" - typing, typed = Event(), Event() with half_open_gateway(server) as url: service = make_client(url) - - def ask(prompt: str, qr: object = None) -> str: - typing.set() - assert typed.wait(DEADLINE) - return CODE - - service._input_bridge = SimpleNamespace(request_input=ask) - monkeypatch.setitem(config.serve, "session_ttl", 3) - login = in_thread(service.authenticate) try: - assert typing.wait(DEADLINE) - (entry,) = sessions() - assert entry.presence.state is ClientState.AWAY - silent_for(entry, AWAY_LIMIT - 5) - assert wait_until(lambda: entry.presence.silence < AWAY_LIMIT / 2, DEADLINE), "the client does not poll" - typed.set() - assert login() is None + with pytest.raises(RemoteError, match=r"^The remote server at \S+ refused the session channel: HTTP 502$"): + service.authenticate() finally: - typed.set() service.close() + assert wait_until(lambda: sessions() == [], DEADLINE) Socket = aiohttp.ClientWebSocketResponse @@ -450,7 +400,7 @@ def test_a_new_channel_or_a_request_after_the_leave_is_a_client_that_still_works server: SimpleNamespace, # noqa: F811 channel: Callable[..., None], ) -> None: - """A client that gives up on a slow channel closes it with 1000 and then polls.""" + """A client that gives up on a slow channel closes it with 1000, then opens a new one or sends a request.""" async def check(entry: SessionEntry, connect: Callable[[], Any]) -> None: await (await connect()).close() @@ -478,26 +428,22 @@ def test_a_client_that_never_comes_back_for_its_session_loses_it( assert ends_after(server, entry, FIRST_CONTACT_LIMIT) -@pytest.mark.parametrize("client_kind", ["polls", "no-id"]) -def test_a_client_without_a_channel_keeps_the_ttl( +def test_a_client_without_the_session_channel_is_refused( server: SimpleNamespace, # noqa: F811 logins: list[Any], # noqa: F811 - client_kind: str, ) -> None: - if client_kind == "polls": - assert create(server.url, str(uuid.uuid4())).status_code == 200 - (entry,) = sessions() - assert get(server, PROMPT_ROUTE, entry).ok - else: - body = {"service": "EXAMPLE", "title_id": "example-1"} - headers = {"X-Secret-Key": KEY} - assert requests.post(server.url + SESSION_CREATE_ROUTE, json=body, headers=headers, timeout=DEADLINE).ok - (entry,) = sessions() - assert logged_in(entry) and stays(server, entry) - entry.idle_since = time.monotonic() - (TTL - 5) - assert sweep(server) == 0 - entry.idle_since = time.monotonic() - (TTL + 1) - assert sweep(server) == 1 + body = {"service": "EXAMPLE", "title_id": "example-1"} + headers = {"X-Secret-Key": KEY} + refused = requests.post(server.url + SESSION_CREATE_ROUTE, json=body, headers=headers, timeout=DEADLINE) + assert refused.status_code == 426 and refused.json()["error_code"] == APIErrorCode.CLIENT_OUTDATED + assert "\n" not in refused.json()["message"] and sessions() == [] + assert create(server.url, str(uuid.uuid4())).status_code == 200 + (entry,) = sessions() + assert logged_in(entry) + titles = get(server, TITLES_ROUTE, entry) + assert titles.status_code == 426 and titles.json()["error_code"] == APIErrorCode.CLIENT_OUTDATED + assert get(server, SESSION_ROUTE, entry).ok + assert entry.presence.state is ClientState.AWAITED @pytest.mark.parametrize("busy", [False, True], ids=["idle", "busy"]) @@ -524,18 +470,14 @@ def test_each_limit_is_longer_than_the_silence_of_a_client_that_still_works() -> """The numbers of the client: a ping is lost, the DELETE is late, or the create reply never arrives.""" detection = HEARTBEAT * 1.5 delete_arrives = 5 + CDM_CLOSE_TIMEOUT + 3 * END_TIMEOUT - reconnects = sum((1, 2, 4, 8, 16, 30)) + reconnects = sum(min(RECONNECT_DELAY * 2**n, RECONNECT_MAX) for n in range(6)) assert 120 + END_TIMEOUT < FIRST_CONTACT_LIMIT <= 150 - assert detection + PROBE_TIMEOUT + 100 < AWAY_LIMIT <= 180 + assert detection + reconnects < AWAY_LIMIT <= 180 assert max(delete_arrives, reconnects) < LEFT_LIMIT <= 90 - presence = ClientPresence() - presence.detached(left=False) - for ttl_seconds in range(1, 7200): - assert presence.limit(ttl_seconds) > ttl_seconds / 3 + PROBE_TIMEOUT def test_a_client_that_is_present_has_no_limit() -> None: - presence = ClientPresence(named=True) + presence = ClientPresence() presence.attached() assert presence.limit(TTL) == math.inf diff --git a/tests/remote/unit/test_dashboard.py b/tests/remote/unit/test_dashboard.py index 6ed9f39a5..af4daf1eb 100644 --- a/tests/remote/unit/test_dashboard.py +++ b/tests/remote/unit/test_dashboard.py @@ -6,6 +6,7 @@ import asyncio import logging import sys import threading +import uuid from collections.abc import Callable from datetime import UTC, datetime, timedelta @@ -330,7 +331,8 @@ async def test_drain_refuses_new_work_and_warns_open_sessions(aiohttp_client, da await client.post("/api/dashboard/drain", headers=headers) assert [r["level"] for r in entry.log_buffer.since(0)] == ["WARNING"] - refused = await client.post("/api/session/create", json={}) + create = {"session_id": str(uuid.uuid4())} + refused = await client.post("/api/session/create", json=create) assert refused.status == 409 assert (await refused.json())["error_code"] == "SERVER_DRAINING" with pytest.raises(APIError, match="restarts for an update"): @@ -338,7 +340,7 @@ async def test_drain_refuses_new_work_and_warns_open_sessions(aiohttp_client, da body = await (await client.delete("/api/dashboard/drain", headers=headers)).json() assert body["draining"] is False - assert (await client.post("/api/session/create", json={})).status == 400 + assert (await client.post("/api/session/create", json=create)).status == 400 finally: store.stop_drain() await store.delete(entry.session_id) diff --git a/tests/remote/unit/test_errors.py b/tests/remote/unit/test_errors.py index b6f4df8dd..c99d7fb7f 100644 --- a/tests/remote/unit/test_errors.py +++ b/tests/remote/unit/test_errors.py @@ -32,6 +32,7 @@ def test_api_error_default_http_status_per_code() -> None: APIErrorCode.INVALID_PARAMETERS: 400, APIErrorCode.AUTH_FAILED: 401, APIErrorCode.FORBIDDEN: 403, + APIErrorCode.CLIENT_OUTDATED: 426, APIErrorCode.GEOFENCE: 403, APIErrorCode.SERVER_CDM_CAPPED: 403, APIErrorCode.NOT_FOUND: 404, diff --git a/tests/remote/unit/test_handler_event_loop.py b/tests/remote/unit/test_handler_event_loop.py index e9e0e9674..ac7b9ccb3 100644 --- a/tests/remote/unit/test_handler_event_loop.py +++ b/tests/remote/unit/test_handler_event_loop.py @@ -78,7 +78,8 @@ class BlockingTracks: async def test_session_titles_leaves_the_loop_free() -> None: handshake = Handshake() store = get_session_store() - await store.create("EXAMPLE", BlockingTitles(handshake), session_id="loop-test-titles") + session = await store.create("EXAMPLE", BlockingTitles(handshake), session_id="loop-test-titles") + session.presence.attached() try: response = await handshake.drive(lambda: handlers.session_titles_handler("loop-test-titles")) finally: diff --git a/tests/remote/unit/test_handler_proxy_policy.py b/tests/remote/unit/test_handler_proxy_policy.py index 003a6fc11..442ceac3a 100644 --- a/tests/remote/unit/test_handler_proxy_policy.py +++ b/tests/remote/unit/test_handler_proxy_policy.py @@ -213,6 +213,7 @@ def test_session_create_builds_service_off_the_event_loop(monkeypatch): import json import logging import threading + import uuid seen: dict = {} @@ -233,7 +234,9 @@ def test_session_create_builds_service_off_the_event_loop(monkeypatch): monkeypatch.setattr(handlers, "SessionLogBuffer", RecordingBuffer) stub_service_build(monkeypatch, failed_check) - response = asyncio.run(handlers.session_create_handler({"service": "EXAMPLE", "title_id": "t"})) + response = asyncio.run( + handlers.session_create_handler({"service": "EXAMPLE", "title_id": "t", "session_id": str(uuid.uuid4())}) + ) assert seen["thread"] != threading.get_ident() assert [r["message"] for r in seen["buffer"].since(0)] == ["checking proxy"] diff --git a/tests/remote/unit/test_input_bridge.py b/tests/remote/unit/test_input_bridge.py index f3ccc0407..c41194d3a 100644 --- a/tests/remote/unit/test_input_bridge.py +++ b/tests/remote/unit/test_input_bridge.py @@ -14,10 +14,15 @@ from unshackle.core.remote_protocol import AuthStatus pytestmark = pytest.mark.unit +def pending_prompt(bridge: InputBridge) -> str | None: + ask = bridge.get_pending_ask() + return ask.prompt if ask else None + + def test_initial_status_is_authenticating() -> None: bridge = InputBridge() - assert bridge.status is AuthStatus.AUTHENTICATING - assert bridge.get_pending_prompt() is None + assert bridge.login_status is AuthStatus.AUTHENTICATING + assert pending_prompt(bridge) is None def test_submit_response_returns_false_when_no_prompt_pending() -> None: @@ -35,28 +40,27 @@ def test_request_input_blocks_until_submit() -> None: t = threading.Thread(target=worker) t.start() for _ in range(50): - if bridge.get_pending_prompt() == "OTP?": + if pending_prompt(bridge) == "OTP?": break time.sleep(0.02) - assert bridge.status is AuthStatus.PENDING_INPUT - assert bridge.get_pending_prompt() == "OTP?" + assert pending_prompt(bridge) == "OTP?" assert bridge.submit_response("123456") is True t.join(timeout=2) assert result == ["123456"] - assert bridge.status is AuthStatus.AUTHENTICATING - assert bridge.get_pending_prompt() is None + assert bridge.login_status is AuthStatus.AUTHENTICATING + assert pending_prompt(bridge) is None def test_request_input_times_out() -> None: bridge = InputBridge() with pytest.raises(TimeoutError, match="No client response"): bridge.request_input("hello", timeout=0.6) - assert bridge.status is AuthStatus.AUTHENTICATING + assert bridge.login_status is AuthStatus.AUTHENTICATING def test_a_prompt_after_a_timed_out_one_takes_its_answer() -> None: - """A login that catches the timeout and asks again gets the answer through the prompt routes.""" + """A login that catches the timeout and asks again gets the answer through the remote login routes.""" bridge = InputBridge() with pytest.raises(TimeoutError): bridge.request_input("Code?", timeout=0.01) @@ -66,7 +70,7 @@ def test_a_prompt_after_a_timed_out_one_takes_its_answer() -> None: worker = threading.Thread(target=lambda: answers.append(bridge.request_input("Code again?", timeout=5))) worker.start() assert offered.wait(5) - assert bridge.status is AuthStatus.PENDING_INPUT + assert pending_prompt(bridge) == "Code again?" assert bridge.submit_response("1234") worker.join(5) assert answers == ["1234"] @@ -77,7 +81,7 @@ def test_cancel_before_request_raises_immediately() -> None: bridge.cancel() with pytest.raises(RuntimeError, match="cancelled"): bridge.request_input("hello", timeout=5) - assert bridge.status is AuthStatus.AUTHENTICATING # ending a session leaves its login state as it was + assert bridge.login_status is AuthStatus.AUTHENTICATING def test_cancel_unblocks_pending_request() -> None: @@ -93,32 +97,27 @@ def test_cancel_unblocks_pending_request() -> None: t = threading.Thread(target=worker) t.start() for _ in range(50): - if bridge.status is AuthStatus.PENDING_INPUT: + if pending_prompt(bridge): break time.sleep(0.02) bridge.cancel() t.join(timeout=2) assert exc and isinstance(exc[0], RuntimeError) - assert bridge.status is AuthStatus.AUTHENTICATING - - -def test_get_pending_prompt_returns_none_outside_pending_state() -> None: - bridge = InputBridge() - bridge.login_status = AuthStatus.AUTHENTICATED - assert bridge.get_pending_prompt() is None + assert bridge.login_status is AuthStatus.AUTHENTICATING def test_login_status_setter() -> None: bridge = InputBridge() bridge.login_status = AuthStatus.AUTHENTICATED - assert bridge.status is AuthStatus.AUTHENTICATED + assert bridge.login_status is AuthStatus.AUTHENTICATED + assert pending_prompt(bridge) is None def test_request_input_after_authentication_fails_fast() -> None: - """The client stops polling for prompts once authenticated, so a later prompt must not wait for an answer.""" + """After the login, a prompt with no attached session channel must not wait for an answer.""" bridge = InputBridge() bridge.login_status = AuthStatus.AUTHENTICATED with pytest.raises(RuntimeError, match="after authentication"): bridge.request_input("Pick a profile", timeout=5) - assert bridge.status is AuthStatus.AUTHENTICATED + assert bridge.login_status is AuthStatus.AUTHENTICATED diff --git a/tests/remote/unit/test_key_identity.py b/tests/remote/unit/test_key_identity.py index 0509ca6f1..ef3836f66 100644 --- a/tests/remote/unit/test_key_identity.py +++ b/tests/remote/unit/test_key_identity.py @@ -3,6 +3,7 @@ import asyncio import base64 import json +import uuid import zlib from types import SimpleNamespace @@ -121,8 +122,8 @@ def test_a_known_device_passes_validation(server, monkeypatch): [ (True, {}, True, {"tokens", "keys/planted"}), (False, {}, True, {"tokens", "keys/planted"}), - (False, {"cdm_type": "playready", "cdm_relay": True}, True, {"tokens", "keys/planted"}), - (False, {"cdm_type": "playready", "cdm_relay": True}, False, {"tokens", "keys/device1", "keys/planted"}), + (False, {"cdm_type": "playready"}, True, {"tokens", "keys/planted"}), + (False, {"cdm_type": "playready"}, False, {"tokens", "keys/device1", "keys/planted"}), ], ) def test_a_session_keeps_identity_keys_from_the_client_unless_the_identity_is_the_clients( @@ -147,7 +148,14 @@ def test_a_session_keeps_identity_keys_from_the_client_unless_the_identity_is_th monkeypatch.setattr(handlers, "load_client_cookies", lambda text: text) async def run(): - data = {"service": "EXAMPLE", "title_id": "t", "cookies": "x", "cache": {"keys/planted": text}, **sent} + data = { + "service": "EXAMPLE", + "title_id": "t", + "session_id": str(uuid.uuid4()), + "cookies": "x", + "cache": {"keys/planted": text}, + **sent, + } response = await handlers.session_create_handler(data) session = get_session_store().peek(json.loads(response.body)["session_id"]) try: @@ -183,7 +191,13 @@ def test_a_service_on_the_lent_device_makes_a_lent_device_session(server, monkey monkeypatch.setattr(handlers, "load_client_cookies", lambda text: text) async def run(): - data = {"service": "EXAMPLE", "title_id": "t", "cookies": "x", "cdm_type": "widevine", "cdm_relay": True} + data = { + "service": "EXAMPLE", + "title_id": "t", + "session_id": str(uuid.uuid4()), + "cookies": "x", + "cdm_type": "widevine", + } reply = json.loads((await handlers.session_create_handler(data)).body) session = get_session_store().peek(reply["session_id"]) try: diff --git a/tests/remote/unit/test_licensing_mode.py b/tests/remote/unit/test_licensing_mode.py index 47540e9d8..f6cf49447 100644 --- a/tests/remote/unit/test_licensing_mode.py +++ b/tests/remote/unit/test_licensing_mode.py @@ -1,15 +1,10 @@ """A remote session's licensing mode: one value that the server decides at session create and the client adopts.""" -import logging -from types import SimpleNamespace - import pytest -from tests.remote.sessions import hold_session from unshackle.core.api import handlers from unshackle.core.api.key_policy import KeyPolicy from unshackle.core.remote_protocol import LicensingMode, Licensor -from unshackle.core.remote_service import RemoteService pytestmark = pytest.mark.unit @@ -79,50 +74,14 @@ def test_an_older_server_reply_with_vault_and_server_cdm_is_a_server_cdm_session @pytest.mark.parametrize( ("choice", "data", "policy", "mode"), [ - ((True, 1080), {"cdm_type": "widevine", "cdm_relay": True}, {}, SERVER_CDM), - ((False, None), {"cdm_type": "widevine", "cdm_relay": True}, {"server_vault": True}, CLIENT_DEVICE), - ((False, None), {"cdm_type": "widevine", "cdm_relay": True}, {}, LicensingMode(Licensor.CLIENT_DEVICE)), + ((True, 1080), {"cdm_type": "widevine"}, {}, SERVER_CDM), + ((False, None), {"cdm_type": "widevine"}, {"server_vault": True}, CLIENT_DEVICE), + ((False, None), {"cdm_type": "widevine"}, {}, LicensingMode(Licensor.CLIENT_DEVICE)), ((False, 1080), {"cdm_type": "widevine"}, {}, LicensingMode(Licensor.CLIENT_DEVICE, 1080)), - ((False, None), {"cdm_type": "widevine"}, {"server_vault": True}, NO_DEVICE), ((False, None), {}, {"server_vault": True}, NO_DEVICE), ], - ids=["server-cdm", "relay-vault", "relay", "capped-old-client", "old-client", "no-device"], + ids=["server-cdm", "relay-vault", "relay", "capped", "no-device"], ) def test_session_create_decides_one_mode(choice, data, policy, mode, monkeypatch): monkeypatch.setattr(handlers, "choose_session_cdm", lambda *args: choice) assert handlers.session_licensing(KeyPolicy(policy), "EXAMPLE", data) == mode - - -@pytest.mark.parametrize( - ("held", "request_", "reply", "mode", "fallback"), - [ - (None, None, True, LicensingMode(Licensor.SERVER_CDM), False), - (None, True, False, LicensingMode(Licensor.CLIENT_DEVICE), True), - (None, False, True, LicensingMode(Licensor.CLIENT_DEVICE), False), - (SERVER_CDM, None, False, LicensingMode(Licensor.CLIENT_DEVICE, 1080), True), - (LENT_DEVICE, None, False, LENT_DEVICE, False), - (SERVER_CDM, None, True, SERVER_CDM, False), - ], - ids=["older-server", "older-server-refuses", "declined", "reopen-on-older-server", "lent", "same"], -) -def test_the_tracks_reply_settles_the_mode_an_older_server_left_out(held, request_, reply, mode, fallback, caplog): - service = object.__new__(RemoteService) - service.__dict__.update( - licensing=held, - _server_cdm_request=request_, - _tracks_by_title={}, - _chapters_by_title={}, - _title_alias={}, - _sample_decrypt_tracks=set(), - service_tag="EXAMPLE", - ctx=SimpleNamespace(obj=None), - log=logging.getLogger("test"), - client=SimpleNamespace(post=lambda path, body: {"server_cdm": reply}, probe=lambda endpoint: {}), - drain_server_logs=lambda: None, - ) - service.session = SimpleNamespace(headers={}) - hold_session(service) - with caplog.at_level(logging.INFO): - service.get_tracks(SimpleNamespace(id="t1")) - assert service.licensing == mode - assert ("falling back to the local CDM" in caplog.text) is fallback diff --git a/tests/remote/unit/test_malformed_input.py b/tests/remote/unit/test_malformed_input.py index addc130da..a6e68a5e5 100644 --- a/tests/remote/unit/test_malformed_input.py +++ b/tests/remote/unit/test_malformed_input.py @@ -16,13 +16,12 @@ import requests from aiohttp import WSMsgType, web from click.testing import CliRunner -from tests.remote.sessions import hold_session from tests.remote.unit.test_session_reopen import make_service from unshackle.core import remote_service from unshackle.core.api import handlers from unshackle.core.api.errors import APIError, APIErrorCode from unshackle.core.api.routes import setup_routes -from unshackle.core.remote_channel import PollingChannel, ServerMessages, WebSocketChannel +from unshackle.core.remote_channel import ServerMessages, WebSocketChannel from unshackle.core.remote_protocol import AuthStatus from unshackle.core.remote_service import RemoteClient, RemoteError, RemoteService @@ -111,7 +110,6 @@ def test_malformed_titles_from_the_server_are_one_remote_error(answer: dict[str, service.service_tag = "EXAMPLE" service.title_id = "t" service.session_call = lambda call: answer # type: ignore[method-assign] - service.drain_server_logs = lambda: None # type: ignore[method-assign] with pytest.raises(RemoteError): service.get_titles() @@ -125,7 +123,6 @@ def test_malformed_tracks_from_the_server_are_one_remote_error(answer: dict[str, service._title_alias = {} service.server_draining = lambda: False # type: ignore[method-assign] service.session_call = lambda call: answer # type: ignore[method-assign] - service.drain_server_logs = lambda: None # type: ignore[method-assign] with pytest.raises(RemoteError): service.get_tracks(Movie(id_="title-1", service=RemoteService, name="Name")) @@ -239,18 +236,6 @@ def test_server_text_loses_its_control_characters() -> None: assert "\x1b" not in error.message and "\n" not in error.message and "\r" not in error.message -def test_relayed_server_logs_lose_their_control_characters(monkeypatch: pytest.MonkeyPatch) -> None: - service = RemoteService.__new__(RemoteService) - hold_session(service, "sid") - seen: list[str] = [] - service.log = SimpleNamespace(log=lambda level, message: seen.append(message)) # type: ignore[assignment] - service.client = SimpleNamespace( - get_optional=lambda _: {"logs": [{"seq": 1, "level": "INFO", "message": "a\x1b[2Jb\nc"}], "last_seq": 1} - ) - PollingChannel(ServerMessages(service)).drain_logs() - assert seen == ["a[2Jb\nc"] - - def test_a_relayed_login_prompt_loses_its_control_characters() -> None: service = RemoteService.__new__(RemoteService) asked: list[tuple[str, str | None]] = [] @@ -286,7 +271,7 @@ def channel_logging_to(seen: list[str]) -> WebSocketChannel: service = make_service() service.log = SimpleNamespace(log=lambda level, message: seen.append(message)) # type: ignore[assignment] messages = ServerMessages(service) - return WebSocketChannel(messages, PollingChannel(messages)) + return WebSocketChannel(messages) @pytest.mark.parametrize("seq", ["x", "2", None, [1], {"a": 1}, float("inf")]) @@ -298,15 +283,10 @@ async def test_a_log_record_with_a_malformed_seq_is_skipped(seq: Any) -> None: assert channel.messages.log_seq == 1 -@pytest.mark.parametrize( - ("logs", "shown"), [(["x", {"seq": 1, "message": "good"}], ["good"]), (None, []), (5, []), ("ab", [])] -) -def test_a_malformed_polled_log_reply_is_skipped(logs: Any, shown: list[str]) -> None: +async def test_relayed_server_logs_lose_their_control_characters() -> None: seen: list[str] = [] - channel = channel_logging_to(seen) - channel.service.client = SimpleNamespace(get_optional=lambda _: {"logs": logs}) # type: ignore[assignment] - channel.fallback.drain_logs() - assert seen == shown + await feed(channel_logging_to(seen), {"type": "log", "seq": 1, "level": "INFO", "message": "a\x1b[2Jb\nc"}) + assert seen == ["a[2Jb\nc"] async def test_a_channel_message_that_fails_is_skipped(monkeypatch: pytest.MonkeyPatch) -> None: @@ -331,7 +311,6 @@ def test_a_relayed_licence_with_no_licence_is_one_click_error(answer: dict[str, service = RemoteService.__new__(RemoteService) service._track_alias = {} service.session_call = lambda call: answer # type: ignore[method-assign] - service.drain_server_logs = lambda: None # type: ignore[method-assign] track = SimpleNamespace(id="v1", drm=[]) with pytest.raises(click.ClickException, match="no valid licence for track v1"): service.proxy_license(b"challenge", cast(Any, track), "widevine") diff --git a/tests/remote/unit/test_relay_stop.py b/tests/remote/unit/test_relay_stop.py index facb0d655..1492c9bb6 100644 --- a/tests/remote/unit/test_relay_stop.py +++ b/tests/remote/unit/test_relay_stop.py @@ -37,7 +37,6 @@ from unshackle.core.api.handlers import ( ) from unshackle.core.api.routes import setup_routes from unshackle.core.remote_protocol import ( - PROMPT_ROUTE, SESSION_ROUTE, TITLES_ROUTE, APIErrorCode, @@ -148,10 +147,8 @@ def nothing(stub: StubService) -> None: (True, ask, nothing), (True, poll_a_device, nothing), (True, nothing, ask), - (False, ask, nothing), - (False, poll_a_device, nothing), ], - ids=["prompt", "device", "prompt-after-login", "prompt-polling", "device-polling"], + ids=["prompt", "device", "prompt-after-login"], indirect=["server"], ) def test_a_stop_ends_a_remote_login( @@ -165,9 +162,7 @@ def test_a_stop_ends_a_remote_login( monkeypatch.setattr(StubService, "authenticate", lambda self, cookies, credential: login(self)) StubService.hooks["titles"] = titles reply = relay.list() - assert wait_until( - lambda: count(server, "GET", PROMPT_ROUTE) > 0 or any(entry.channel.attached for entry in sessions()), DEADLINE - ) + assert wait_until(lambda: any(entry.channel.attached for entry in sessions()), DEADLINE) assert ask not in (login, titles) or wait_until(relay.asks, DEADLINE) relay.stop() relay.ended_well() diff --git a/tests/remote/unit/test_remote_client.py b/tests/remote/unit/test_remote_client.py index c499d00bc..971f05206 100644 --- a/tests/remote/unit/test_remote_client.py +++ b/tests/remote/unit/test_remote_client.py @@ -211,14 +211,6 @@ def test_late_error_after_heartbeat_is_fatal(client: RemoteClient) -> None: responses.add(responses.GET, "http://srv:8786/api/session/s/titles", body=body, status=200) with pytest.raises(SystemExit): client.get("/api/session/s/titles") - with pytest.raises(RemoteError): - client.request("get", "/api/session/s/titles", optional=True) - - -@responses.activate -def test_an_optional_route_the_server_lacks_answers_empty(client: RemoteClient) -> None: - responses.add(responses.POST, "http://srv:8786/api/session/s/segment_filter", body="404: Not Found", status=404) - assert client.post_optional("/api/session/s/segment_filter", {}) == {} @pytest.mark.parametrize( @@ -226,11 +218,11 @@ def test_an_optional_route_the_server_lacks_answers_empty(client: RemoteClient) [(422, "SERVICE_ERROR"), (404, "TRACK_NOT_FOUND"), (404, "SESSION_NOT_FOUND"), (503, "SERVER_DRAINING")], ) @responses.activate -def test_an_optional_route_that_fails_on_the_server_raises(client: RemoteClient, status: int, code: str) -> None: +def test_a_route_that_fails_on_the_server_raises(client: RemoteClient, status: int, code: str) -> None: body = {"status": "error", "error_code": code, "message": "no"} responses.add(responses.POST, "http://srv:8786/api/session/s/segment_filter", json=body, status=status) with pytest.raises(RemoteError) as e: - client.post_optional("/api/session/s/segment_filter", {}) + client.post("/api/session/s/segment_filter", {}) assert e.value.kind == code diff --git a/tests/remote/unit/test_remote_loopback.py b/tests/remote/unit/test_remote_loopback.py index 0d2e5fed1..84eba6a52 100644 --- a/tests/remote/unit/test_remote_loopback.py +++ b/tests/remote/unit/test_remote_loopback.py @@ -31,8 +31,8 @@ from unshackle.core.api.routes import cors_middleware, no_5xx_middleware, setup_ 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_channel import WebSocketChannel +from unshackle.core.remote_protocol import CHANNEL_ROUTE, SESSION_ROUTE, TITLES_ROUTE, APIErrorCode, ClientErrorKind from unshackle.core.remote_service import RemoteError, RemoteService from unshackle.core.service import Service from unshackle.core.session import RnetSession, record_requests @@ -103,6 +103,10 @@ class StubService: def decrypts_samples(self, track: Any) -> bool: return False + def get_widevine_license(self, *, challenge: bytes, title: Movie, track: Any, **_: Any) -> bytes: + """Make one call on the client's CDM, as a service with a CDM-based licence step does.""" + return json.dumps(self._input_bridge.request_cdm({"op": "close", "session": "EXAMPLE"})).encode() + fairplay_bridge = TitleSource.fairplay_bridge @@ -146,7 +150,6 @@ def server(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch, tmp_ monkeypatch.setattr(StubService, "hooks", {}) monkeypatch.setattr(routes, "HEARTBEAT_INTERVAL", 0.02) monkeypatch.setattr(routes.web, "StreamResponse", CountedHeartbeat) - monkeypatch.setattr(remote_channel, "KEEPALIVE_MIN_INTERVAL", 0.05) monkeypatch.setattr(remote_channel, "AUTH_POLL_INTERVAL", 0.01) monkeypatch.setattr(remote_service, "REOPEN_WAIT", 5.0) monkeypatch.setattr(session_store, "session_store", None) @@ -223,57 +226,47 @@ def count(server: SimpleNamespace, method: str, route: str, session_id: str | No return len([s for s in server.seen if s[:2] == (method, route.format(session_id=session_id))]) +def polled(server: SimpleNamespace) -> list[tuple[str, str, int]]: + """The requests to a prompt or logs route, which the server no longer has and the client never sends.""" + return [s for s in server.seen if s[1].endswith(("/prompt", "/logs"))] + + def example_messages(caplog: pytest.LogCaptureFixture) -> list[str]: """What the client logged as the service's own lines, which the server relayed.""" return [r.getMessage() for r in caplog.records if r.name == "EXAMPLE"] -@pytest.mark.parametrize( - "server,channel", - [(True, "none"), (False, "refused"), (True, "failed")], - ids=["old-client", "refused-upgrade", "failed-connect"], - indirect=["server"], -) -def test_a_remote_session_runs_end_to_end_over_http( - server: SimpleNamespace, channel: str, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +def test_a_remote_session_runs_end_to_end_over_the_channel( + server: SimpleNamespace, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch ) -> None: - """A client that does not open the channel, or whose upgrade is refused or fails, polls with the same replies.""" + """Create, a login prompt, titles, tracks, a licence that calls the client's CDM and a lost session: none polls.""" caplog.set_level(logging.DEBUG) monkeypatch.setattr(session_store.SessionStore, "_expired", lambda self, entry: False) - if channel == "none": - monkeypatch.setattr(WebSocketChannel, "open", lambda self, timeout=0: False) - if channel == "failed": - - async def unreachable(self: Any, url: str, **kwargs: Any) -> Any: - raise aiohttp.ClientConnectionError("EXAMPLE connect failed") - - monkeypatch.setattr(aiohttp.ClientSession, "_ws_connect", unreachable) - service = make_client(server.url) + monkeypatch.setattr(client_relay, "answer_cdm_call", lambda cdm, call, sessions: {"op": call["op"]}) + asked: list[str] = [] + service = make_client(server.url, cdm=SimpleNamespace()) + service._input_bridge = SimpleNamespace(request_input=lambda prompt, qr=None: asked.append(prompt) or CODE) try: service.authenticate() first = service._session_id assert first assert server.seen[0] == ("POST", "/api/session/create", 401) - assert ("GET", f"/api/session/{first}/prompt", 200) in server.seen - assert isinstance(service.channel, PollingChannel) - assert count(server, "GET", CHANNEL_ROUTE, first) == int(channel == "refused") - channel_lines = [r for r in caplog.records if r.name == "remote_channel"] - assert all(r.levelno == logging.DEBUG for r in channel_lines) - assert bool(channel_lines) == (channel != "none") + assert asked == ["Enter the EXAMPLE code"] + assert isinstance(service.channel, WebSocketChannel) and service.channel.connected.is_set() assert any(r.name == "EXAMPLE" and r.message == "Logged in to EXAMPLE, login 1" for r in caplog.records) - info = SESSION_ROUTE.format(session_id=first) - assert wait_until(lambda: len([s for s in server.seen if s[:2] == ("GET", info)]) >= 2, 10) - titles = service.get_titles() assert [str(t.id) for t in titles] == ["example-1", "example-2", "example-3"] m1, m2, m3 = titles - assert [str(t.id) for t in service.get_tracks(m1).audio] == ["example-1-login1"] + (audio,) = service.get_tracks(m1).audio + assert str(audio.id) == "example-1-login1" + assert service.get_widevine_license(challenge=b"EXAMPLE", title=m1, track=audio) == b'{"op": "close"}' forget(server, first) assert [str(t.id) for t in service.get_tracks(m2).audio] == ["example-2-login2"] assert service._session_id not in (None, first) assert "The remote session was lost, opening a new one" in caplog.messages + assert asked == ["Enter the EXAMPLE code"] * 2 with pytest.raises(RemoteError) as late: service.get_tracks(m3) @@ -286,26 +279,74 @@ def test_a_remote_session_runs_end_to_end_over_http( assert service.channel is None assert ("DELETE", SESSION_ROUTE.format(session_id=second), 200) in server.seen assert not session_store.get_session_store()._sessions - prompts = {body for path, body in server.bodies if path.endswith("/prompt")} - assert prompts <= { - b'{"status": "authenticating"}', - b'{"status": "pending_input", "prompt": "Enter the EXAMPLE code"}', - b'{"status": "authenticated"}', - b'{"status": "accepted"}', - } - assert b'{"status": "pending_input", "prompt": "Enter the EXAMPLE code"}' in prompts - logs = [json.loads(body) for path, body in server.bodies if path.endswith("/logs")] - assert logs and all(list(reply) == ["session_id", "logs", "last_seq"] for reply in logs) - assert [list(r) for reply in logs for r in reply["logs"]][:1] == [["seq", "level", "message", "ts"]] + assert polled(server) == [] -@pytest.mark.parametrize("channel", ["socket", "polling"]) -def test_a_qr_code_reaches_the_client_terminal_with_its_prompt( +@pytest.mark.parametrize( + "server,channel", + [(False, "refused"), (True, "failed")], + ids=["refused-upgrade", "failed-connect"], + indirect=["server"], +) +def test_a_channel_that_cannot_open_stops_the_client_with_one_line( server: SimpleNamespace, channel: str, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(remote_channel, "RECONNECT_DELAY", 0.05) + if channel == "failed": + + async def unreachable(self: Any, url: str, **kwargs: Any) -> Any: + raise aiohttp.ClientConnectionError("EXAMPLE connect failed") + + monkeypatch.setattr(aiohttp.ClientSession, "_ws_connect", unreachable) + service = make_client(server.url) + try: + with pytest.raises(RemoteError) as stopped: + service.authenticate() + finally: + service.close() + if channel == "refused": + assert stopped.value.message == f"The remote server at {server.url} refused the session channel: HTTP 502" + assert stopped.value.kind == ClientErrorKind.UNKNOWN + else: + assert stopped.value.message == f"Could not open the session channel to {server.url}: EXAMPLE connect failed" + assert stopped.value.kind == ClientErrorKind.CONNECT + assert count(server, "GET", TITLES_ROUTE) == 0 and polled(server) == [] + assert wait_until(lambda: not session_store.get_session_store()._sessions, 5) + assert count(server, "GET", CHANNEL_ROUTE) == (2 if channel == "refused" else 0) + + +@pytest.mark.parametrize(("status", "opens"), [(429, True), (422, False)]) +def test_the_first_channel_open_tries_once_more_after_a_rate_limit_answer( + server: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, status: int, opens: bool +) -> None: + monkeypatch.setattr(remote_channel, "RECONNECT_DELAY", 0.05) + channel_handler = routes.session_channel_handler + answered: list[int] = [] + + async def once(session_id: str, request: web.Request) -> web.StreamResponse: + if not answered: + answered.append(status) + return web.Response(status=status, headers={"Retry-After": "0"}) + return await channel_handler(session_id, request) + + monkeypatch.setattr(routes, "session_channel_handler", once) + service = make_client(server.url) + try: + if opens: + service.authenticate() + assert isinstance(service.channel, WebSocketChannel) and service.channel.connected.is_set() + else: + with pytest.raises(RemoteError, match=f"refused the session channel: HTTP {status}$"): + service.authenticate() + finally: + service.close() + assert answered == [status] + + +def test_a_qr_code_reaches_the_client_terminal_with_its_prompt( + server: SimpleNamespace, 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: @@ -320,21 +361,18 @@ def test_a_qr_code_reaches_the_client_terminal_with_its_prompt( service._input_bridge = None try: service.authenticate() - assert isinstance(service.channel, WebSocketChannel if channel == "socket" else PollingChannel) + assert isinstance(service.channel, WebSocketChannel) 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 + server: SimpleNamespace, 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)) @@ -351,7 +389,7 @@ def test_a_qr_code_to_approve_reaches_the_client_with_its_log_line( service._input_bridge = None try: service.authenticate() - assert isinstance(service.channel, WebSocketChannel if channel == "socket" else PollingChannel) + assert isinstance(service.channel, WebSocketChannel) finally: service.close() assert "Scan the EXAMPLE code" in example_messages(caplog) @@ -392,7 +430,6 @@ def test_the_session_channel_carries_what_the_server_starts( assert [str(t.id) for t in listed[0]] == ["example-1", "example-2", "example-3"] assert answers == [{"op": "close"}, CODE] assert service.get_tracks(listed[0][0]).audio - assert count(server, "GET", PROMPT_ROUTE) == count(server, "GET", LOGS_ROUTE) == 0 forget(server, first) assert wait_until(lambda: not service.channel.connected.is_set(), 5) @@ -411,7 +448,7 @@ def test_the_session_channel_carries_what_the_server_starts( server.loop.call_soon_threadsafe(store.stop_drain) assert wait_until(lambda: not store.draining, 5) assert wait_until(lambda: not service.server_draining(), 5) - assert count(server, "GET", PROMPT_ROUTE) == count(server, "GET", LOGS_ROUTE) == 0 + assert polled(server) == [] finally: release.set() service.close() @@ -430,18 +467,14 @@ class Origin(BaseHTTPRequestHandler): self.wfile.write(b"{}") -@pytest.mark.parametrize("channel", ["socket", "polling"]) def test_server_request_records_never_reach_the_remote_client( server: SimpleNamespace, - channel: str, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, ) -> None: """The http_request entries of the service's requests stay in the server's JSONL, out of the session log.""" caplog.set_level(logging.DEBUG) - if channel == "polling": - monkeypatch.setattr(WebSocketChannel, "open", lambda self, timeout=0: False) origin = ThreadingHTTPServer(("127.0.0.1", 0), Origin) origin.daemon_threads = True Thread(target=origin.serve_forever, daemon=True).start() @@ -469,7 +502,6 @@ def test_server_request_records_never_reach_the_remote_client( try: service.authenticate() assert len(service.get_titles()) == 3 - service.drain_server_logs() assert wait_until(lambda: {"EXAMPLE init done", "EXAMPLE titles fetched"} <= set(example_messages(caplog)), 10) (entry,) = session_store.get_session_store()._sessions.values() buffered = [r["message"] for r in entry.log_buffer.since(0)] @@ -506,7 +538,7 @@ def test_an_open_channel_keeps_the_session_alive(server: SimpleNamespace, monkey assert on_loop(server, store.cleanup_expired()) == 0 assert store.peek(session_id) is entry assert count(server, "GET", SESSION_ROUTE, session_id) == 0 - assert count(server, "GET", LOGS_ROUTE) == count(server, "GET", PROMPT_ROUTE) == 0 + assert polled(server) == [] monkeypatch.setitem(config.serve, "session_ttl", 300) service.lifetime.close_channel() @@ -535,7 +567,7 @@ def gate_channel(monkeypatch: pytest.MonkeyPatch) -> threading.Event: return refuse -def test_a_dropped_channel_falls_back_to_polling_until_it_reconnects( +def test_a_dropped_channel_reconnects_and_nothing_polls_meanwhile( server: SimpleNamespace, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch ) -> None: caplog.set_level(logging.INFO) @@ -555,22 +587,20 @@ def test_a_dropped_channel_falls_back_to_polling_until_it_reconnects( on_loop(server, entry.channel.ws.close()) assert wait_until(lambda: not channel.connected.is_set(), 5) titles = service.get_titles() - assert count(server, "GET", LOGS_ROUTE, session_id) >= 1 - assert "Listing EXAMPLE titles" in example_messages(caplog) - assert wait_until(lambda: count(server, "GET", SESSION_ROUTE, session_id) >= 1, 5), "no keepalive took over" + assert "Listing EXAMPLE titles" not in example_messages(caplog) + assert count(server, "GET", SESSION_ROUTE, session_id) == 0 and polled(server) == [] refuse.clear() assert wait_until(lambda: channel.connected.is_set() and entry.channel.attached, 10) - assert wait_until(lambda: channel.fallback.keepalive_stop.is_set(), 5) - logs = count(server, "GET", LOGS_ROUTE, session_id) + assert wait_until(lambda: "Listing EXAMPLE titles" in example_messages(caplog), 5) assert service.get_tracks(titles[0]).audio - assert count(server, "GET", LOGS_ROUTE, session_id) == logs assert example_messages(caplog).count("Listing EXAMPLE titles") == 1 + assert count(server, "GET", SESSION_ROUTE, session_id) == 0 and polled(server) == [] finally: service.close() -def test_a_cdm_call_made_while_the_channel_is_down_goes_through_polling( +def test_a_cdm_call_made_while_the_channel_is_down_waits_for_the_reconnect( server: SimpleNamespace, monkeypatch: pytest.MonkeyPatch ) -> None: refuse = gate_channel(monkeypatch) @@ -584,6 +614,7 @@ def test_a_cdm_call_made_while_the_channel_is_down_goes_through_polling( entry = store.peek(service._session_id) asyncio.run_coroutine_threadsafe(entry.channel.ws.close(), server.loop).result(5) assert wait_until(lambda: not service.channel.connected.is_set() and not entry.channel.attached, 5) + refuse.clear() answers.append(stub._input_bridge.request_cdm({"op": "close", "session": "EXAMPLE"})) StubService.hooks["titles"] = titles @@ -592,7 +623,7 @@ def test_a_cdm_call_made_while_the_channel_is_down_goes_through_polling( assert isinstance(service.channel, WebSocketChannel) service.get_titles() assert answers == [{"op": "close"}] - assert count(server, "GET", PROMPT_ROUTE, service._session_id) >= 1 + assert polled(server) == [] finally: service.close() diff --git a/tests/remote/unit/test_remote_music_collection.py b/tests/remote/unit/test_remote_music_collection.py index e31ca86a1..06dfbc975 100644 --- a/tests/remote/unit/test_remote_music_collection.py +++ b/tests/remote/unit/test_remote_music_collection.py @@ -52,7 +52,6 @@ def client_of(answer: dict[str, Any]) -> RemoteService: """A client that gets ``answer`` from the titles route.""" service = make_service() service.session_call = lambda call: answer # type: ignore[method-assign] - service.drain_server_logs = lambda: None # type: ignore[method-assign] return service diff --git a/tests/remote/unit/test_remote_probes.py b/tests/remote/unit/test_remote_probes.py index d94855e0a..1588d9420 100644 --- a/tests/remote/unit/test_remote_probes.py +++ b/tests/remote/unit/test_remote_probes.py @@ -5,7 +5,7 @@ from __future__ import annotations import asyncio import json from collections.abc import Callable -from threading import Event, Thread +from threading import Thread from types import SimpleNamespace from typing import Any @@ -13,8 +13,8 @@ import pytest import responses from tests.remote.unit.test_session_reopen import SERVER, make_service -from unshackle.core import remote_channel, remote_service -from unshackle.core.remote_channel import PollingChannel, ServerMessages, WebSocketChannel +from unshackle.core import remote_service +from unshackle.core.remote_channel import ServerMessages, WebSocketChannel from unshackle.core.remote_protocol import ClientErrorKind from unshackle.core.remote_service import RemoteClient from unshackle.core.tunnel import TunnelClient, run_loop @@ -61,52 +61,6 @@ def test_recover_moves_to_the_next_auth_header() -> None: assert service._session_id == "s1" -@responses.activate -def test_server_draining_moves_to_the_next_auth_header() -> None: - service = make_service() - service.lifetime.channel = PollingChannel(ServerMessages(service)) - responses.add_callback(responses.GET, f"{SERVER}/api/session/s1", callback=second_header_only({"draining": True})) - - assert service.server_draining() - - -@responses.activate -def test_keepalive_moves_to_the_next_auth_header(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(remote_channel, "KEEPALIVE_MIN_INTERVAL", 0.01) - polling = PollingChannel(ServerMessages(make_service())) - pinged = Event() - info = {"valid": True, "expires_in": 0.03} - responses.add_callback(responses.GET, f"{SERVER}/api/session/s1", callback=second_header_only(info, pinged.set)) - - polling.keep_alive() - try: - assert pinged.wait(5) - finally: - polling.stop_keepalive() - assert [c.response.status_code for c in responses.calls[:2]] == [401, 200] - - -@responses.activate -def test_cdm_poller_moves_to_the_next_auth_header(monkeypatch: pytest.MonkeyPatch) -> None: - polling = PollingChannel(ServerMessages(make_service())) - stop = Event() - answered: list[dict] = [] - monkeypatch.setattr(polling.messages, "answer_cdm", lambda call: (answered.append(call), stop.set())) - monkeypatch.setattr(polling, "answer", lambda response: None) - call = {"id": "c1", "op": "open"} - reply = {"status": "pending_input", "cdm_call": call} - responses.add_callback(responses.GET, f"{SERVER}/api/session/s1/prompt", callback=second_header_only(reply)) - - poller = Thread(target=polling.poll_cdm_calls, args=(stop, 0.01), daemon=True) - poller.start() - try: - assert stop.wait(5) - finally: - stop.set() - poller.join(5) - assert answered == [call] - - @responses.activate def test_recover_waits_out_a_429_instead_of_reopening(monkeypatch: pytest.MonkeyPatch) -> None: waits: list[int] = [] @@ -147,7 +101,7 @@ def test_a_channel_closes_after_its_loop_has_closed() -> None: service = make_service() service.ctx = SimpleNamespace(obj=None) messages = ServerMessages(service) - channel = WebSocketChannel(messages, PollingChannel(messages)) + channel = WebSocketChannel(messages) loop = asyncio.new_event_loop() loop.close() channel.loop, channel.task = loop, SimpleNamespace(cancel=lambda: None) @@ -175,7 +129,7 @@ def test_a_channel_loop_ends_without_starting_a_thread(monkeypatch: pytest.Monke service = make_service() service.ctx = SimpleNamespace(obj=None) messages = ServerMessages(service) - channel = WebSocketChannel(messages, PollingChannel(messages)) + channel = WebSocketChannel(messages) channel.thread.run() diff --git a/tests/remote/unit/test_remote_protocol.py b/tests/remote/unit/test_remote_protocol.py index 11b1c4410..d58ba5c32 100644 --- a/tests/remote/unit/test_remote_protocol.py +++ b/tests/remote/unit/test_remote_protocol.py @@ -20,10 +20,8 @@ from unshackle.core.api.handlers import SESSION_TRANSPORT_KEYS ROUTE_NAMES = {name for name in vars(protocol) if name.endswith("_ROUTE")} CLIENT_METHODS = { "get": "GET", - "get_optional": "GET", "probe": "GET", "post": "POST", - "post_optional": "POST", "ws_connect": "GET", } SERVED = {(method, path): handler for method, path, handler, _ in routes.ROUTES} @@ -121,8 +119,8 @@ def test_the_protocol_page_lists_each_remote_route(): } -def test_the_wire_values_stay_what_older_peers_send(): - """Both halves read one record, so only this list catches a renamed value that an older peer still sends.""" +def test_the_wire_values_stay_pinned(): + """Both halves read one record, so only this list catches a renamed value on the wire.""" assert {name: getattr(protocol, name) for name in ROUTE_NAMES} == { "HEALTH_ROUTE": "/api/health", "SERVICES_ROUTE": "/api/services", @@ -137,14 +135,17 @@ def test_the_wire_values_stay_what_older_peers_send(): "LICENSE_ROUTE": "/api/session/{session_id}/license", "KEYS_ROUTE": "/api/session/{session_id}/keys", "BAD_KEY_ROUTE": "/api/session/{session_id}/keys/bad", - "LOGS_ROUTE": "/api/session/{session_id}/logs", - "PROMPT_ROUTE": "/api/session/{session_id}/prompt", "CHANNEL_ROUTE": "/api/session/{session_id}/channel", } assert [m.value for m in protocol.ChannelMessage] == ["prompt", "cdm_call", "log", "status", "drain", "answer"] assert protocol.CHANNEL_SESSION_GONE == 4404 - assert [s.value for s in protocol.AuthStatus] == ["authenticating", "pending_input", "authenticated", "failed"] - assert {c.name for c in protocol.APIErrorCode} >= {"SESSION_NOT_FOUND", "SERVER_CDM_CAPPED", "SERVER_DRAINING"} + assert [s.value for s in protocol.AuthStatus] == ["authenticating", "authenticated", "failed"] + assert {c.name for c in protocol.APIErrorCode} >= { + "SESSION_NOT_FOUND", + "SERVER_CDM_CAPPED", + "SERVER_DRAINING", + "CLIENT_OUTDATED", + } assert [k.value for k in protocol.ClientErrorKind] == [ "CONNECT", "TIMEOUT", @@ -177,7 +178,6 @@ def test_session_transport_keys_are_the_create_body(): "server_cdm", "cdm_type", "cdm_security_level", - "cdm_relay", "cdm_system_id", "cdm_device_type", "service_config", @@ -203,7 +203,7 @@ def test_session_transport_keys_are_the_create_body(): ], ) def test_the_channel_messages_keep_their_fields(shape, fields): - """A session channel message is a JSON text frame; an older peer reads these keys.""" + """A session channel message is a JSON text frame; the other side reads these keys.""" assert keys(shape) == fields @@ -230,9 +230,6 @@ def properties(schema: dict | None) -> set[str]: ("POST", protocol.LICENSE_ROUTE, protocol.LicenseRequest, protocol.LicenseReply), ("POST", protocol.KEYS_ROUTE, protocol.TrackKeys, None), ("POST", protocol.BAD_KEY_ROUTE, protocol.BadKeyReport, None), - ("GET", protocol.LOGS_ROUTE, None, protocol.LogsReply), - ("GET", protocol.PROMPT_ROUTE, None, protocol.PromptReply), - ("POST", protocol.PROMPT_ROUTE, protocol.PromptAnswer, None), ("GET", protocol.SESSION_ROUTE, None, protocol.SessionInfo), ], ) diff --git a/tests/remote/unit/test_remote_relay.py b/tests/remote/unit/test_remote_relay.py index e1c4fe970..3136cc50a 100644 --- a/tests/remote/unit/test_remote_relay.py +++ b/tests/remote/unit/test_remote_relay.py @@ -5,7 +5,6 @@ from types import SimpleNamespace import pytest -from tests.remote.sessions import hold_session from unshackle.core import remote_service from unshackle.core.api import handlers from unshackle.core.api.errors import APIError @@ -214,30 +213,21 @@ def test_a_quiet_remote_login_shows_its_last_server_lines_as_a_notice(monkeypatc shown = [] 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"]) - - class Client: - def get(self, endpoint): - return {"status": next(statuses)} - - def get_optional(self, endpoint): - batch = next(logs, []) - first = remote.seq + 1 - remote.seq += len(batch) - records = [{"seq": first + i, "level": "INFO", "message": m} for i, m in enumerate(batch)] - return {"logs": records, "last_seq": remote.seq} - remote = object.__new__(remote_service.RemoteService) - remote.seq = 0 - remote.client, remote.auth_notice, remote.auth_qr = Client(), None, None - hold_session(remote) + remote.auth_notice, remote.auth_qr, remote._input_bridge = None, None, None remote.log = logging.getLogger("test") monkeypatch.setattr(remote_service.RemoteService, "local_cdm", None) + messages = remote_channel.ServerMessages(remote) + lines = ["+ IP Region: CA", "+ Open URL: https://example.test/start\n+ Enter pair code: 9835-2503"] - remote_channel.PollingChannel(remote_channel.ServerMessages(remote)).wait_auth() - # silent while the remote was still logging; the pair code once it went quiet; cleared when done + for seq, line in enumerate(lines, 1): + seen = messages.log_seq + messages.show_logs([{"seq": seq, "level": "INFO", "message": line}]) + messages.note_waiting(seen) + messages.note_waiting(messages.log_seq) + messages.note_waiting(messages.log_seq) + messages.login_done() + # silent while the remote was still logging; the pair code once, when it went quiet; cleared when done assert shown == ["+ IP Region: CA\n+ Open URL: https://example.test/start\n+ Enter pair code: 9835-2503", None] assert remote.auth_notice is None @@ -280,7 +270,7 @@ async def test_a_remote_login_prompt_waits_for_its_owners_answer(monkeypatch): ) ) asker.start() - while login.bridge.get_pending_prompt() is None: + while login.bridge.get_pending_ask() is None: await asyncio.sleep(0.01) listed = json.loads((await handlers.remote_logins_handler(None)).text)["logins"] @@ -296,7 +286,7 @@ async def test_a_remote_login_prompt_waits_for_its_owners_answer(monkeypatch): caller["key"] = "owner" await handlers.remote_login_input_handler(login.id, {"response": "123456"}, None) asker.join(2) - assert got == ["123456"] and login.bridge.get_pending_prompt() is None + assert got == ["123456"] and login.bridge.get_pending_ask() is None with pytest.raises(APIError) as e: await handlers.remote_login_input_handler(login.id, {"response": "again"}, None) assert e.value.error_code == APIErrorCode.CONFLICT diff --git a/tests/remote/unit/test_remote_service_helpers.py b/tests/remote/unit/test_remote_service_helpers.py index 6bb7df2a5..e5cf10733 100644 --- a/tests/remote/unit/test_remote_service_helpers.py +++ b/tests/remote/unit/test_remote_service_helpers.py @@ -567,7 +567,7 @@ async def test_session_delete_returns_nested_cache_keys(tmp_path, monkeypatch) - session = session_entry(service_tag="TESTSVC", cache_tag=cache_tag, client_auth=True) - async def fake_validated(session_id, request): + async def fake_validated(session_id, request, needs_channel): return session monkeypatch.setattr(handlers, "get_validated_session", fake_validated) @@ -657,6 +657,7 @@ def test_write_client_cache_refuses_a_bad_map_before_it_writes_a_file(tmp_path, def test_a_session_create_that_fails_after_the_cache_write_leaves_no_cache_dir(tmp_path, monkeypatch, stop_at) -> None: import asyncio import logging + import uuid from types import SimpleNamespace from unshackle.core.api import handlers @@ -692,7 +693,7 @@ def test_a_session_create_that_fails_after_the_cache_write_leaves_no_cache_dir(t store = RefusingStore() monkeypatch.setattr("unshackle.core.api.session_store.get_session_store", lambda: store) - data = {"service": "TESTSVC", "title_id": "t", "cache": {"token": blob('"t"')}} + data = {"service": "TESTSVC", "title_id": "t", "session_id": str(uuid.uuid4()), "cache": {"token": blob('"t"')}} response = asyncio.run(handlers.session_create_handler(data)) assert response.status == 422 assert written == ["token.json"] diff --git a/tests/remote/unit/test_remote_service_server_cdm_license.py b/tests/remote/unit/test_remote_service_server_cdm_license.py index b00efd2d1..e2b7a0ab8 100644 --- a/tests/remote/unit/test_remote_service_server_cdm_license.py +++ b/tests/remote/unit/test_remote_service_server_cdm_license.py @@ -93,7 +93,6 @@ def test_response_type_refreshes_the_server_type(): def test_proxy_mode_keeps_the_callers_type(): svc = _service("widevine", {"license": "bGlj"}) svc.licensing = LicensingMode(Licensor.CLIENT_DEVICE) - svc.drain_server_logs = lambda: None track = SimpleNamespace(id="vid", drm=[_PlayReady(), _Widevine()]) licence = svc.proxy_license(b"chal", track, "playready") @@ -108,7 +107,6 @@ def test_a_refused_relayed_licence_raises_a_click_exception_with_the_server_mess svc = _service("widevine", {}) svc.licensing = LicensingMode(Licensor.CLIENT_DEVICE) - svc.drain_server_logs = lambda: None def refuse(endpoint, payload, expect=()): raise RemoteError("Licence request failed: refused", "SERVICE_ERROR") diff --git a/tests/remote/unit/test_route_error_replies.py b/tests/remote/unit/test_route_error_replies.py index 807b94119..624d78da0 100644 --- a/tests/remote/unit/test_route_error_replies.py +++ b/tests/remote/unit/test_route_error_replies.py @@ -32,8 +32,6 @@ from unshackle.core.remote_protocol import ( BAD_KEY_ROUTE, KEYS_ROUTE, LICENSE_ROUTE, - LOGS_ROUTE, - PROMPT_ROUTE, SAMPLES_ROUTE, SEARCH_ROUTE, SEGMENT_FILTER_ROUTE, @@ -55,6 +53,7 @@ KEY = "test-key" OTHER_KEY = "other-key" DASHBOARD_KEY = "dash-key" SESSION = "pinned-session" +CLIENT_SESSION = "00000000-0000-4000-8000-000000000001" RELEASE = threading.Event() SEEN: list[dict[str, Any]] = [] @@ -83,8 +82,6 @@ class Faulty: raise_fault(self.kind) get_titles = get_tracks = get_chapters = get_widevine_license = decrypts_samples = fail - get_pending_cdm_call = submit_response = since = fail - last_seq = 0 def cancel(self) -> None: """End of the session: nothing to unblock.""" @@ -108,14 +105,13 @@ def fill(route: str) -> str: BODIES: dict[str, Any] = { SEARCH_ROUTE: {"service": "EXAMPLE", "query": "film"}, - SESSION_CREATE_ROUTE: {"service": "EXAMPLE", "title_id": "title-0001"}, + SESSION_CREATE_ROUTE: {"service": "EXAMPLE", "title_id": "title-0001", "session_id": CLIENT_SESSION}, TRACKS_ROUTE: {"title_id": "title-0001"}, SEGMENTS_ROUTE: {"track_ids": ["v1"]}, SEGMENT_FILTER_ROUTE: {"track_id": "v1"}, LICENSE_ROUTE: {"track_id": "v1", "challenge": "AAAA"}, BAD_KEY_ROUTE: {"kid": "00" * 16, "key": "11" * 16}, KEYS_ROUTE: {"track_id": "v1", "keys": {"22" * 16: "33" * 16}}, - PROMPT_ROUTE: {"response": "1234"}, "/api/list-titles": {"service": "EXAMPLE", "title_id": "title-0001"}, "/api/list-tracks": {"service": "EXAMPLE", "title_id": "title-0001"}, "/api/download": {"service": "EXAMPLE", "title_id": "title-0001"}, @@ -144,6 +140,7 @@ class Case: session: Faulty | None = None owner: str = KEY status: AuthStatus = AuthStatus.AUTHENTICATED + attached: bool = True patch: dict[str, Any] = field(default_factory=dict) key: str | None = KEY @@ -226,14 +223,6 @@ def fault_cases() -> dict[str, Case]: session=Faulty(), patch={"server_keys.load_server_vaults": Faulty(kind).fail}, ) - cases[f"prompt get {kind}"] = Case("GET", fill(PROMPT_ROUTE), session=Faulty(input_bridge=Faulty(kind))) - cases[f"prompt submit {kind}"] = Case( - "POST", - fill(PROMPT_ROUTE), - BODIES[PROMPT_ROUTE], - session=Faulty(input_bridge=Faulty(kind, status=AuthStatus.PENDING_INPUT)), - ) - cases[f"logs {kind}"] = Case("GET", fill(LOGS_ROUTE), session=Faulty(log_buffer=Faulty(kind))) cases[f"search {kind}"] = Case( "POST", SEARCH_ROUTE, BODIES[SEARCH_ROUTE], patch={"run_service_search": Faulty(kind).fail} ) @@ -263,9 +252,15 @@ def fault_cases() -> dict[str, Case]: cases["search unknown service"] = Case("POST", SEARCH_ROUTE, {"service": "NOPE", "query": "film"}) cases["search no query"] = Case("POST", SEARCH_ROUTE, {"service": "EXAMPLE"}) cases["session create unknown service"] = Case( - "POST", SESSION_CREATE_ROUTE, {"service": "NOPE", "title_id": "title-0001"} + "POST", SESSION_CREATE_ROUTE, {**BODIES[SESSION_CREATE_ROUTE], "service": "NOPE"} ) - cases["session create no title"] = Case("POST", SESSION_CREATE_ROUTE, {"service": "EXAMPLE"}) + cases["session create no title"] = Case( + "POST", SESSION_CREATE_ROUTE, {"service": "EXAMPLE", "session_id": CLIENT_SESSION} + ) + cases["session create no session id"] = Case( + "POST", SESSION_CREATE_ROUTE, {"service": "EXAMPLE", "title_id": "title-0001"} + ) + cases["titles no channel"] = Case("GET", fill(TITLES_ROUTE), session=Faulty(), attached=False) cases["session create proxy refused"] = Case( "POST", SESSION_CREATE_ROUTE, BODIES[SESSION_CREATE_ROUTE], patch={"resolve_handler_proxy": Faulty("api").fail} ) @@ -275,8 +270,8 @@ def fault_cases() -> dict[str, Case]: return cases -async def open_session(stand_in: Faulty, owner: str, status: AuthStatus) -> None: - bridge = getattr(stand_in, "input_bridge", None) or InputBridge() +async def open_session(stand_in: Faulty, owner: str, status: AuthStatus, attached: bool) -> None: + bridge = InputBridge() bridge.login_status = status session = await get_session_store().create( "EXAMPLE", @@ -285,8 +280,9 @@ async def open_session(stand_in: Faulty, owner: str, status: AuthStatus) -> None owner_key=owner, licensing=LicensingMode(Licensor.SERVER_CDM), input_bridge=bridge, - log_buffer=getattr(stand_in, "log_buffer", None), ) + if attached: + session.presence.attached() session.title_map["title-0001"] = Movie(id_="title-0001", service=object, name="Film", year=2024, language=None) track = SimpleNamespace( id="v1", @@ -392,7 +388,7 @@ async def test_error_replies_match_the_snapshot( module, _, attr = target.rpartition(".") mp.setattr({"routes": routes, "server_keys": server_keys}.get(module, handlers), attr, value) if item.session is not None: - await open_session(item.session, item.owner, item.status) + await open_session(item.session, item.owner, item.status, item.attached) try: replies[name] = await send(client, item, caplog) finally: diff --git a/tests/remote/unit/test_routes.py b/tests/remote/unit/test_routes.py index 1d1addcbc..1ea2dadee 100644 --- a/tests/remote/unit/test_routes.py +++ b/tests/remote/unit/test_routes.py @@ -80,9 +80,6 @@ def test_setup_routes_full_mode_wires_all_endpoints(make_app) -> None: ("POST", "/api/session/{session_id}/tracks"), ("POST", "/api/session/{session_id}/segments"), ("POST", "/api/session/{session_id}/license"), - ("GET", "/api/session/{session_id}/logs"), - ("GET", "/api/session/{session_id}/prompt"), - ("POST", "/api/session/{session_id}/prompt"), ("GET", "/api/session/{session_id}"), ("DELETE", "/api/session/{session_id}"), } @@ -106,9 +103,6 @@ def test_setup_routes_remote_only_excludes_list_and_download(make_app) -> None: ("POST", "/api/session/{session_id}/tracks"), ("POST", "/api/session/{session_id}/segments"), ("POST", "/api/session/{session_id}/license"), - ("GET", "/api/session/{session_id}/logs"), - ("GET", "/api/session/{session_id}/prompt"), - ("POST", "/api/session/{session_id}/prompt"), ("GET", "/api/session/{session_id}"), ("DELETE", "/api/session/{session_id}"), } diff --git a/tests/remote/unit/test_run_cancel.py b/tests/remote/unit/test_run_cancel.py index 44877f846..256b22b67 100644 --- a/tests/remote/unit/test_run_cancel.py +++ b/tests/remote/unit/test_run_cancel.py @@ -28,10 +28,8 @@ from tests.remote.unit.test_process_exit import ( # noqa: F401 logins, posix, run, - saved, sessions, settings, - store_cache, wait_line, ) from tests.remote.unit.test_remote_loopback import StubService, count, forget, server # noqa: F401 @@ -42,13 +40,10 @@ from unshackle.core.constants import RunCancel from unshackle.core.proxies.controld import relay from unshackle.core.remote_channel import ServerMessages from unshackle.core.remote_protocol import ( - LOGS_ROUTE, - PROMPT_ROUTE, SESSION_CREATE_ROUTE, SESSION_ROUTE, TITLES_ROUTE, TRACKS_ROUTE, - AuthStatus, ) from unshackle.core.tracks import Audio, Tracks @@ -79,9 +74,6 @@ service = make_client(sys.argv[1]) keys = resolver() if phase == "push": remote_service.KEYS_TIMEOUT = 60 -if "polling" in sys.argv[4:]: - remote_channel.WebSocketChannel.open = lambda self, timeout=0: False - def say(line): print(line, flush=True) @@ -95,12 +87,12 @@ def hold(line): while not RunCancel.pressed: Event().wait(0.01) -def drain_logs(real=service.drain_server_logs): - real() +def open_session(credential, real=service.open_session): + real(credential) if phase == "login-done" and service._tracks_by_title: hold("login done") -service.drain_server_logs = drain_logs +service.open_session = open_session def login_material(profile, real=service.client_login): if phase == "login-material" and service._titles: @@ -383,29 +375,18 @@ def hold_login(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace: return login -@pytest.mark.parametrize("channel", ["socket", "polling"]) def test_a_ctrl_c_in_the_login_of_a_reopen_deletes_the_new_session( server: SimpleNamespace, # noqa: F811 client: Callable[..., Any], monkeypatch: pytest.MonkeyPatch, - tmp_path: Path, - channel: str, ) -> None: - """The client of the polling channel does not know yet that its login succeeded, so the DELETE returns a cache.""" - process = client("pool", channel) + process = client("pool") login = hold_login(monkeypatch) forget(server, sessions()[0].session_id) - polls = count(server, "GET", PROMPT_ROUTE) go(process) try: assert login.started.wait(DEADLINE) - if channel == "socket": - assert wait_until(lambda: sessions()[0].channel.attached, DEADLINE) - else: - assert wait_until(lambda: count(server, "GET", PROMPT_ROUTE) > polls, DEADLINE) - login.release.set() - assert wait_until(lambda: sessions()[0].auth_status == AuthStatus.AUTHENTICATED, DEADLINE) - store_cache() + assert wait_until(lambda: sessions()[0].channel.attached, DEADLINE) created, (entry,) = count(server, "POST", SESSION_CREATE_ROUTE), sessions() output = press(process) finally: @@ -414,7 +395,6 @@ def test_a_ctrl_c_in_the_login_of_a_reopen_deletes_the_new_session( assert "Download Cancelled" in output and "called" not in output and "error" not in output.lower() assert sessions() == [] and count(server, "POST", SESSION_CREATE_ROUTE) == created assert count(server, "DELETE", SESSION_ROUTE, entry.session_id) == 1 - assert channel == "socket" or saved(tmp_path / "client") def test_a_failed_track_does_not_stop_the_reopen_of_the_others( @@ -500,20 +480,6 @@ def test_a_track_whose_wait_was_cancelled_did_not_fail( assert sorted(lines) == ["Download Cancelled", "DownloadCancelled", "cancelled", "vault writes done"] -def test_a_cancelled_call_of_the_polling_channel_fetches_no_server_log( - server: SimpleNamespace, # noqa: F811 - client: Callable[..., Any], - monkeypatch: pytest.MonkeyPatch, -) -> None: - limit(monkeypatch, "session_segments_handler") - process = client("url", "polling") - fetched = count(server, "GET", LOGS_ROUTE) - go(process) - wait_line(process, LIMITED) - press(process) - assert count(server, "GET", LOGS_ROUTE) == fetched > 0 - - @pytest.mark.parametrize("cancelled", [False, True]) def test_a_cancelled_login_shows_no_notice(monkeypatch: pytest.MonkeyPatch, cancelled: bool) -> None: shown: list[Any] = [] diff --git a/tests/remote/unit/test_segment_filter.py b/tests/remote/unit/test_segment_filter.py index aa487bb08..09408239d 100644 --- a/tests/remote/unit/test_segment_filter.py +++ b/tests/remote/unit/test_segment_filter.py @@ -93,14 +93,6 @@ def test_client_filter_drops_only_the_unwanted_segments(): assert len(responses.calls) == 1 -@responses.activate -def test_client_filter_keeps_everything_when_the_server_has_no_route(): - service = make_service(None, status=404) - segment_filter = service.remote_segment_filter("t1") - - assert segment_filter(SimpleNamespace(absolute_uri="https://cdn.test/hls/ad1.ts")) is False - - @responses.activate def test_a_filter_that_fails_on_the_server_stops_the_track_and_caches_nothing(): error = {"status": "error", "error_code": "SERVICE_ERROR", "message": "Could not run the segment filter"} diff --git a/tests/remote/unit/test_serve_stop.py b/tests/remote/unit/test_serve_stop.py index fefb79b1e..1d52659e3 100644 --- a/tests/remote/unit/test_serve_stop.py +++ b/tests/remote/unit/test_serve_stop.py @@ -272,6 +272,7 @@ def entry( assert create(server.url, session_id(), cache={"token": blob('"EXAMPLE"')}).status_code == 200 (entry,) = sessions() assert logged_in(entry) + entry.presence.attached() return entry diff --git a/tests/remote/unit/test_server_cdm_key_verification.py b/tests/remote/unit/test_server_cdm_key_verification.py index e669aee5a..850d8a110 100644 --- a/tests/remote/unit/test_server_cdm_key_verification.py +++ b/tests/remote/unit/test_server_cdm_key_verification.py @@ -50,7 +50,7 @@ def test_a_reply_marks_the_keys_a_server_vault_served(): def test_server_vault_flag_posts_only_the_pair(): svc = remote_service() posted: list = [] - svc.client = SimpleNamespace(post_optional=lambda ep, data: posted.append((ep, data)) or {}) + svc.client = SimpleNamespace(post=lambda ep, data: posted.append((ep, data)) or {}) assert svc.server_vault.report_now svc.server_vault.flag_bad_key("SVC", KID, "v", "server_cdm") assert posted == [("/api/session/sess/keys/bad", {"kid": KID.hex, "key": "v"})] @@ -325,7 +325,6 @@ def test_a_cipher_the_server_does_not_license_raises(grants, answer, message): def test_track_url_asks_the_segments_route_for_the_url_of_one_track(): """A track the server sent with resolve_url gets its URL from the server when it is downloaded.""" svc = remote_service() - svc.drain_server_logs = lambda: None sent = [] svc.client = SimpleNamespace( post=lambda ep, data, **kw: sent.append((ep, data)) or {"tracks": {"a-1": {"url": "https://cdn.example/a"}}} @@ -349,7 +348,6 @@ def test_track_url_asks_the_segments_route_for_the_url_of_one_track(): def test_a_track_the_server_gives_no_url_raises(answer): """A track with no URL from the server stops at its download with one line.""" svc = remote_service() - svc.drain_server_logs = lambda: None def post(ep, data, **kw): if isinstance(answer, BaseException): diff --git a/tests/remote/unit/test_server_cdm_max_height.py b/tests/remote/unit/test_server_cdm_max_height.py index be9fe83e1..d6d2633b9 100644 --- a/tests/remote/unit/test_server_cdm_max_height.py +++ b/tests/remote/unit/test_server_cdm_max_height.py @@ -355,42 +355,6 @@ def test_a_client_device_session_builds_the_service_on_a_stub_of_that_device(mon assert built["cdm"].security_level == 3000 -def test_the_tracks_response_echoes_the_session_choice(monkeypatch): - import asyncio - - from unshackle.core.api import session_store as store_mod - from unshackle.core.tracks import Tracks - - monkeypatch.setattr(store_mod.bus, "publish", lambda topic, data: None) - - class StubService: - session = SimpleNamespace(headers={}, cookies=[]) - - def fairplay_bridge(self): - return None - - def get_tracks(self, title): - return Tracks() - - def get_chapters(self, title): - raise NotImplementedError - - async def run(): - store = store_mod.get_session_store() - entry = await store.create( - service_tag="EXAMPLE1", service_instance=StubService(), session_id="capped", owner_key=None - ) - entry.title_map = {"t1": "Title"} - entry.licensing = LicensingMode(Licensor.CLIENT_DEVICE) - try: - resp = await handlers.session_tracks_handler({"title_id": "t1"}, "capped") - return json.loads(resp.body) - finally: - await store.delete("capped") - - assert asyncio.run(run())["server_cdm"] is False - - class _LocalWidevine(Widevine): """Stops at the licence call and reports the device dl handed it.""" @@ -576,7 +540,6 @@ def test_server_cdm_true_outranks_the_services_cdm_entry(caplog): with caplog.at_level(logging.WARNING): svc, data = sent_create(True, cdm_entry=True, cdm_map={"EXAMPLE1": "my_device"}) assert "server_cdm" not in data - assert data["cdm_relay"] is True assert svc._server_cdm_request is True assert not caplog.text @@ -638,9 +601,8 @@ def created(answer, monkeypatch): """Run ``authenticate()`` to its end for a device the service's cdm entry loaded.""" svc, _ = sent_create(None, cdm_entry=True, cdm_map={"EXAMPLE1": "my_device"}) svc._server_cdm_request = None - svc.client = SimpleNamespace(post=lambda path, data: {"session_id": "sess", **answer}) - channel = SimpleNamespace(keep_alive=lambda: None, drain_logs=lambda: None, in_flight=None) - monkeypatch.setattr(remote_channel, "open_channel", lambda service: channel) + svc.client = SimpleNamespace(post=lambda path, data: {"session_id": data["session_id"], **answer}) + monkeypatch.setattr(remote_channel, "open_channel", lambda service: SimpleNamespace()) monkeypatch.setattr(remote_lifetime, "atexit", SimpleNamespace(register=id, unregister=atexit.unregister)) svc.authenticate() return svc diff --git a/tests/remote/unit/test_server_cdm_type_override.py b/tests/remote/unit/test_server_cdm_type_override.py index 9919ae291..0708cbdf5 100644 --- a/tests/remote/unit/test_server_cdm_type_override.py +++ b/tests/remote/unit/test_server_cdm_type_override.py @@ -281,6 +281,7 @@ def test_the_tracks_response_names_the_system_of_the_loaded_device(monkeypatch, entry = await store.create( service_tag="EXAMPLE1", service_instance=StubService(), session_id="both", owner_key=None ) + entry.presence.attached() entry.title_map = {"t1": "Title"} entry.licensing = LicensingMode(Licensor.SERVER_CDM) try: @@ -339,6 +340,7 @@ def _reply_then_licence(monkeypatch, track, drm_type, loaded=None): async def run(): store = store_mod.get_session_store() entry = await store.create(service_tag="EXAMPLE", service_instance=service, session_id="head", owner_key=None) + entry.presence.attached() entry.title_map = {"t1": "Title"} entry.licensing = LicensingMode(Licensor.SERVER_CDM) try: diff --git a/tests/remote/unit/test_server_vault_push.py b/tests/remote/unit/test_server_vault_push.py index c71ae8f89..f9732f725 100644 --- a/tests/remote/unit/test_server_vault_push.py +++ b/tests/remote/unit/test_server_vault_push.py @@ -300,13 +300,7 @@ def cdm_only_client(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, cdm: Any, c monkeypatch.setattr(config, "credentials", {}) monkeypatch.setattr(config.directories, "cookies", tmp_path / "cookies") monkeypatch.setattr(config.directories, "cache", tmp_path / "cache") - monkeypatch.setattr( - remote_channel, - "open_channel", - lambda service: SimpleNamespace( - in_flight=None, close=lambda: None, drain_logs=lambda: None, keep_alive=lambda: None - ), - ) + monkeypatch.setattr(remote_channel, "open_channel", lambda service: SimpleNamespace(close=lambda: None)) obj = SimpleNamespace(cdm=cdm, cdm_entry=False, proxy_providers=[]) parent = click.Context(click.Command("dl"), obj=obj) parent.params = {"no_proxy": True, "cdm_only": True} @@ -314,14 +308,16 @@ def cdm_only_client(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, cdm: Any, c svc = RemoteService(ctx, "EXAMPLE", "example-1", "http://server", "key", {"_server_cdm": True}) posts: list = [] svc.client = SimpleNamespace( - tunnel=None, post=lambda endpoint, data, expect=(): posts.append(data) or created, delete=lambda endpoint: {} + tunnel=None, + post=lambda endpoint, data, expect=(): posts.append(data) or {**created, "session_id": data["session_id"]}, + delete=lambda endpoint: {}, ) svc.posts = posts return svc def test_cdm_only_declines_the_server_cdm_and_its_vault(monkeypatch, tmp_path) -> None: - created = {"session_id": "sess", "server_cdm": False, "server_vault": True} + created = {"server_cdm": False, "server_vault": True} svc = cdm_only_client(monkeypatch, tmp_path, cdm_type_stub("widevine"), created) try: svc.authenticate() @@ -341,7 +337,7 @@ def test_cdm_only_without_a_local_cdm_fails_before_the_session(monkeypatch, tmp_ def test_cdm_only_on_the_server_device_fails(monkeypatch, tmp_path) -> None: - created = {"session_id": "sess", "server_cdm": True, "server_device": True} + created = {"server_cdm": True, "server_device": True} svc = cdm_only_client(monkeypatch, tmp_path, cdm_type_stub("widevine"), created) try: with pytest.raises(click.ClickException, match="runs on the server's device"): diff --git a/tests/remote/unit/test_session_channel.py b/tests/remote/unit/test_session_channel.py index 669078fcd..d6171638a 100644 --- a/tests/remote/unit/test_session_channel.py +++ b/tests/remote/unit/test_session_channel.py @@ -87,7 +87,15 @@ async def test_a_socket_that_cannot_send_is_closed_and_detached() -> None: assert not entry.channel.attached -async def test_a_detached_channel_hands_its_waiting_asks_back_to_the_prompt_routes() -> None: +async def sent_cdm_calls(socket: FakeSocket) -> list[dict[str, Any]]: + for _ in range(200): + if calls := [m for m in socket.sent if m["type"] == "cdm_call"]: + return calls + await asyncio.sleep(0.01) + return [] + + +async def test_a_detached_channel_keeps_its_waiting_asks_for_the_next_attach() -> None: entry = entry_with_logs(0) bridge = entry.input_bridge assert bridge is not None @@ -97,17 +105,17 @@ async def test_a_detached_channel_hands_its_waiting_asks_back_to_the_prompt_rout answers: list[Any] = [] worker = threading.Thread(target=lambda: answers.append(bridge.request_cdm({"op": "close"}, timeout=5))) worker.start() - for _ in range(200): - if any(m["type"] == "cdm_call" for m in socket.sent): - break - await asyncio.sleep(0.01) - assert bridge.get_pending_cdm_call() is None, "the channel carries the call, so polling must not see it" + (call,) = await sent_cdm_calls(socket) await socket.close() await serving - assert bridge.get_pending_cdm_call() == {"op": "close"} - assert bridge.submit_response('{"op": "close"}') - worker.join(5) + again = FakeSocket() + serving = asyncio.create_task(entry.channel.serve(again, entry, 0, False)) # type: ignore[arg-type] + assert await sent_cdm_calls(again) == [call] + assert bridge.answer(call["id"], '{"op": "close"}') + await asyncio.to_thread(worker.join, 5) assert answers == [{"op": "close"}] + await again.close() + await serving def test_a_prompt_the_client_refuses_stops_the_service_at_once() -> None: diff --git a/tests/remote/unit/test_session_lifetime.py b/tests/remote/unit/test_session_lifetime.py index 80ecba14d..cee6e8bba 100644 --- a/tests/remote/unit/test_session_lifetime.py +++ b/tests/remote/unit/test_session_lifetime.py @@ -33,9 +33,10 @@ from tests.remote.unit.test_tunnel import wait_until from unshackle.core import process_exit, remote_channel, remote_lifetime, remote_service from unshackle.core.api import handlers, routes, session_store from unshackle.core.api.download_manager import busy_services +from unshackle.core.api.errors import APIError from unshackle.core.api.session_store import SessionEntry from unshackle.core.config import config -from unshackle.core.remote_channel import PollingChannel, ServerMessages, WebSocketChannel +from unshackle.core.remote_channel import ServerMessages, WebSocketChannel from unshackle.core.remote_lifetime import Presses, RemoteSessionLifetime from unshackle.core.remote_protocol import SESSION_CREATE_ROUTE, SESSION_ROUTE, APIErrorCode, ClientErrorKind from unshackle.core.remote_service import RemoteError, RemoteService @@ -558,7 +559,9 @@ def test_an_id_that_is_not_a_canonical_uuid4_is_refused(server: SimpleNamespace, def test_the_server_takes_the_id_that_the_client_names() -> None: named = RemoteSessionLifetime(SimpleNamespace(), lambda cache: None).name() # type: ignore[arg-type] assert handlers.new_session_id({"session_id": named}) == named - assert uuid.UUID(handlers.new_session_id({})).version == 4 + with pytest.raises(APIError) as e: + handlers.new_session_id({}) + assert e.value.error_code == APIErrorCode.CLIENT_OUTDATED def test_a_create_that_times_out_is_deleted(build: SimpleNamespace) -> None: @@ -577,13 +580,9 @@ def test_a_create_that_times_out_is_deleted(build: SimpleNamespace) -> None: assert count(build.server, "DELETE", SESSION_ROUTE) == 1 -@pytest.mark.parametrize("older", [False, True], ids=["server", "older-server"]) def test_a_create_that_answers_after_the_end_leaves_no_session( - build: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, older: bool + build: SimpleNamespace, caplog: pytest.LogCaptureFixture ) -> None: - """An older server picks the id itself, so the DELETE of the named id finds nothing and the reply is deleted.""" - if older: - monkeypatch.setattr(handlers, "new_session_id", lambda data: str(uuid.uuid4())) service = make_client(build.server.url) opened = in_thread(service.authenticate) assert build.started.wait(DEADLINE) @@ -599,22 +598,6 @@ def test_a_create_that_answers_after_the_end_leaves_no_session( assert not [r for r in caplog.records if r.levelname == "ERROR"] -def test_the_client_takes_the_id_that_an_older_server_picks( - server: SimpleNamespace, # noqa: F811 - logins: list[Any], - monkeypatch: pytest.MonkeyPatch, -) -> None: - picked = str(uuid.uuid4()) - monkeypatch.setattr(handlers, "new_session_id", lambda data: picked) - service = make_client(server.url) - service.authenticate() - assert service._session_id == picked - - service.close() - assert sessions() == [] - assert count(server, "DELETE", SESSION_ROUTE) == 1 - - def test_an_ended_owner_never_opens_again(server: SimpleNamespace, logins: list[Any]) -> None: # noqa: F811 service = make_client(server.url) service.authenticate() @@ -779,12 +762,10 @@ def test_a_search_interrupted_in_its_tunnel_stops_it(monkeypatch: pytest.MonkeyP assert len(stopped) == 1 -@pytest.mark.parametrize("channel", ["socket", "polling"]) def test_an_end_during_the_login_is_silent( server: SimpleNamespace, # noqa: F811 monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, - channel: str, ) -> None: asked, release = Event(), Event() @@ -793,13 +774,11 @@ def test_an_end_during_the_login_is_silent( release.wait(DEADLINE) monkeypatch.setattr(StubService, "authenticate", login) - if channel == "polling": - monkeypatch.setattr(WebSocketChannel, "open", lambda self, timeout=0: False) service = make_client(server.url) opened = in_thread(service.authenticate) try: assert asked.wait(DEADLINE) - assert wait_until(lambda: isinstance(service.channel, WebSocketChannel | PollingChannel), DEADLINE) + assert wait_until(lambda: isinstance(service.channel, WebSocketChannel), DEADLINE) service.close() assert isinstance(opened(), RemoteError) finally: @@ -807,7 +786,6 @@ def test_an_end_during_the_login_is_silent( assert sessions() == [] assert not [seen for seen in server.seen if "/None" in seen[1]] assert not [r for r in caplog.records if r.levelname == "ERROR" and r.name.startswith("remote_")] - assert channel == "polling" or not service.client.no_channel def test_an_end_during_the_channel_open_is_silent( @@ -819,7 +797,7 @@ def test_an_end_during_the_channel_open_is_silent( service = make_client(server.url) connect = WebSocketChannel.open - def end_then_open(self: WebSocketChannel, timeout: float = 10) -> bool: + def end_then_open(self: WebSocketChannel, timeout: float = 10) -> None: assert in_thread(service.close)() is None self.stopped = False return connect(self, timeout) @@ -829,7 +807,6 @@ def test_an_end_during_the_channel_open_is_silent( service.authenticate() assert not [seen for seen in server.seen if "/None" in seen[1]] assert not [r for r in caplog.records if r.levelname == "ERROR"] - assert not service.client.no_channel def test_an_exit_in_the_channel_open_closes_the_channel( @@ -1002,9 +979,8 @@ def test_an_end_of_another_thread_stops_the_opening( elif at == "create": monkeypatch.setattr(remote_service, "launch_keys", end) else: - drain = service.drain_server_logs - monkeypatch.setattr(service, "drain_server_logs", lambda: (drain(), end())) - monkeypatch.setattr(WebSocketChannel, "keep_alive", lambda self: None) + opened = remote_channel.open_channel + monkeypatch.setattr(remote_channel, "open_channel", lambda service: (opened(service), end())[0]) with pytest.raises(RemoteError): service.authenticate() @@ -1034,7 +1010,7 @@ def test_a_stop_before_the_thread_runs_keeps_it_from_connecting(monkeypatch: pyt else: service = make_service() service.ctx = SimpleNamespace(obj=None) # type: ignore[assignment] - channel = WebSocketChannel(ServerMessages(service), PollingChannel(ServerMessages(service))) + channel = WebSocketChannel(ServerMessages(service)) monkeypatch.setattr(WebSocketChannel, "connect", connect) channel.close() channel.thread.run() @@ -1081,16 +1057,7 @@ def test_a_press_after_the_end_does_not_leave_its_handler(monkeypatch: pytest.Mo def test_a_channel_of_an_ended_owner_stops_by_itself() -> None: service = make_service() service.ctx = SimpleNamespace(obj=None) # type: ignore[assignment] - channel = WebSocketChannel(ServerMessages(service), PollingChannel(ServerMessages(service))) + channel = WebSocketChannel(ServerMessages(service)) service.lifetime.ended = True channel.thread.run() assert channel.attempted.is_set() and not channel.connected.is_set() - - -def test_a_create_of_a_reopen_passes_through_the_old_channel() -> None: - """The client's in_flight hook stays the one of the closed channel until the new channel is open.""" - service = make_service() - channel = PollingChannel(ServerMessages(service)) - service.lifetime.session_id = None - with channel.in_flight(SESSION_CREATE_ROUTE): - assert channel.cdm_requests == 0 diff --git a/tests/remote/unit/test_session_log.py b/tests/remote/unit/test_session_log.py index f7a6b2828..b0747ccdf 100644 --- a/tests/remote/unit/test_session_log.py +++ b/tests/remote/unit/test_session_log.py @@ -1,13 +1,10 @@ -"""Session log forwarding: buffer semantics, mirror wrapping, handler drain.""" +"""Session log forwarding: buffer semantics and mirror wrapping.""" import logging import pytest -from tests.remote.sessions import hold_session -from unshackle.core.api.handlers import session_logs_handler from unshackle.core.api.session_log import SessionLogBuffer, SessionLogMirror, capture_service_logs -from unshackle.core.api.session_store import get_session_store def test_buffer_sequences_and_since() -> None: @@ -57,43 +54,6 @@ def test_capture_service_logs_attaches_and_detaches() -> None: assert not logger.handlers -@pytest.mark.asyncio -async def test_session_logs_handler_drains_since() -> None: - store = get_session_store() - entry = await store.create("EXAMPLE", object(), session_id="log-test-session") - try: - entry.log_buffer = SessionLogBuffer() - entry.log_buffer.append(logging.INFO, "first") - entry.log_buffer.append(logging.ERROR, "second") - - resp = await session_logs_handler("log-test-session", since=0) - import json - - body = json.loads(resp.body) - assert [r["message"] for r in body["logs"]] == ["first", "second"] - assert body["last_seq"] == 2 - - resp = await session_logs_handler("log-test-session", since=2) - body = json.loads(resp.body) - assert body["logs"] == [] - assert body["last_seq"] == 2 - finally: - await store.delete("log-test-session") - - -@pytest.mark.asyncio -async def test_session_logs_handler_no_buffer() -> None: - store = get_session_store() - await store.create("EXAMPLE", object(), session_id="log-test-nobuf") - try: - resp = await session_logs_handler("log-test-nobuf", since=0) - import json - - assert json.loads(resp.body)["logs"] == [] - finally: - await store.delete("log-test-nobuf") - - def test_capture_service_logs_none_buffer_noop() -> None: logger = logging.getLogger("test-capture-none") with capture_service_logs("test-capture-none", None): @@ -164,55 +124,6 @@ def test_service_params_keyed_by_flag_reach_an_option_with_another_name() -> Non assert built == {"zone_code": "eu", "svc_lang": "de"} -def test_drain_server_logs_survives_client_systemexit() -> None: - """RemoteClient raises SystemExit on transport errors; the drain must swallow it.""" - from unshackle.core.remote_channel import PollingChannel, ServerMessages - from unshackle.core.remote_service import RemoteService - - svc = RemoteService.__new__(RemoteService) - hold_session(svc) - svc.lifetime.channel = PollingChannel(ServerMessages(svc)) - - class ExitingClient: - def get_optional(self, endpoint: str) -> dict: - raise SystemExit(1) - - svc.client = ExitingClient() - svc.drain_server_logs() # must not raise - assert svc.channel.messages.log_seq == 0 - - -def test_drain_server_logs_reemits_and_advances_seq() -> None: - from unshackle.core.remote_channel import PollingChannel, ServerMessages - from unshackle.core.remote_service import RemoteService - - svc = RemoteService.__new__(RemoteService) - hold_session(svc) - svc.lifetime.channel = PollingChannel(ServerMessages(svc)) - svc.log = logging.getLogger("test-drain-reemit") - - class StubClient: - def get_optional(self, endpoint: str) -> dict: - assert endpoint.endswith("since=0") - return {"logs": [{"seq": 1, "level": "WARNING", "message": "server says"}], "last_seq": 1} - - svc.client = StubClient() - records: list[logging.LogRecord] = [] - - class Capture(logging.Handler): - def emit(self, record: logging.LogRecord) -> None: - records.append(record) - - handler = Capture() - svc.log.addHandler(handler) - try: - svc.drain_server_logs() - finally: - svc.log.removeHandler(handler) - assert svc.channel.messages.log_seq == 1 - assert [(r.levelno, r.getMessage()) for r in records] == [(logging.WARNING, "server says")] - - def test_mirror_buffers_exception_cause() -> None: buf = SessionLogBuffer() mirror = SessionLogMirror(logging.getLogger("test-mirror-exc"), buf) diff --git a/tests/remote/unit/test_session_plugins.py b/tests/remote/unit/test_session_plugins.py index 3fac77db9..57c83f478 100644 --- a/tests/remote/unit/test_session_plugins.py +++ b/tests/remote/unit/test_session_plugins.py @@ -6,6 +6,7 @@ from __future__ import annotations import asyncio import json +import uuid from pathlib import Path from types import SimpleNamespace from typing import Any @@ -149,6 +150,7 @@ def tracks_reply(client_plugins: Any) -> tuple[Any, Any]: session_id="plugins", client_plugins=client_plugins, ) + entry.presence.attached() entry.title_map = {"t1": "EXAMPLE title"} try: resp = await handlers.session_tracks_handler({"title_id": "t1"}, "plugins") @@ -204,7 +206,8 @@ def test_the_create_route_keeps_the_client_plugin_list(monkeypatch: pytest.Monke listed = {"example": {"version": "1.0", "device": DEVICE_FACTS}} async def run() -> Any: - resp = await handlers.session_create_handler({"service": "EXAMPLE", "title_id": "t", "plugins": listed}) + body = {"service": "EXAMPLE", "title_id": "t", "session_id": str(uuid.uuid4()), "plugins": listed} + resp = await handlers.session_create_handler(body) session_id = json.loads(resp.body)["session_id"] entry = store_mod.get_session_store().peek(session_id) await store_mod.get_session_store().delete(session_id) diff --git a/tests/remote/unit/test_session_reporting.py b/tests/remote/unit/test_session_reporting.py index 575edfc29..1c2daa33a 100644 --- a/tests/remote/unit/test_session_reporting.py +++ b/tests/remote/unit/test_session_reporting.py @@ -2,6 +2,7 @@ import asyncio import shlex +import uuid from types import SimpleNamespace from typing import Any @@ -138,6 +139,7 @@ def test_tracks_handler_marks_the_title_live_before_it_fetches(monkeypatch: pyte entry = await store.create( service_tag="EXAMPLE", service_instance=StubService(), session_id="live", owner_key=None ) + entry.presence.attached() entry.title_map = {"t1": FakeTitle("Example Show 2024 S01E01"), "t3": FakeTitle("Example Show 2024 S01E03")} published.clear() resp = await session_tracks_handler({"title_id": "t3"}, "live") @@ -176,7 +178,7 @@ def test_the_create_event_carries_the_session_as_created(monkeypatch: pytest.Mon async def run() -> list: mark = bus.seq - body = {"service": "EXAMPLE", "title_id": "t", "client": {"version": "1.0"}} + body = {"service": "EXAMPLE", "title_id": "t", "session_id": str(uuid.uuid4()), "client": {"version": "1.0"}} resp = await handlers.session_create_handler(body) await store_mod.get_session_store().delete(json.loads(resp.body)["session_id"]) return [e["data"] for e in bus.since(mark) if e["event"] == "session" and e["data"]["action"] == "create"] diff --git a/tests/remote/unit/test_session_service_lock.py b/tests/remote/unit/test_session_service_lock.py index ced49cf22..220644cf2 100644 --- a/tests/remote/unit/test_session_service_lock.py +++ b/tests/remote/unit/test_session_service_lock.py @@ -127,6 +127,7 @@ async def test_two_track_requests_never_share_the_service() -> None: overlap = Overlap() store = get_session_store() session = await store.create("EXAMPLE", ServiceProbe(overlap), session_id="lock-test-tracks") + session.presence.attached() seed_titles(session) try: responses = await two_track_calls(session.session_id) @@ -142,6 +143,7 @@ async def test_the_track_lock_covers_the_chapters_call() -> None: overlap = Overlap() store = get_session_store() session = await store.create("EXAMPLE", ServiceProbe(overlap), session_id="lock-test-chapters") + session.presence.attached() seed_titles(session) try: responses = await two_track_calls(session.session_id) @@ -161,6 +163,7 @@ async def test_titles_and_tracks_never_overlap() -> None: overlap = Overlap() store = get_session_store() session = await store.create("EXAMPLE", ServiceProbe(overlap), session_id="lock-test-mixed") + session.presence.attached() seed_titles(session) try: responses = list( @@ -181,7 +184,9 @@ async def test_a_second_session_still_runs_in_parallel() -> None: overlap = Overlap() store = get_session_store() first = await store.create("EXAMPLE", ServiceProbe(overlap, "a"), session_id="lock-test-parallel-a") + first.presence.attached() second = await store.create("EXAMPLE", ServiceProbe(overlap, "b"), session_id="lock-test-parallel-b") + second.presence.attached() try: responses = list( await asyncio.gather( @@ -221,6 +226,7 @@ async def test_the_loop_stays_free_while_the_lock_is_held() -> None: service = BlockingTracks() store = get_session_store() session = await store.create("EXAMPLE", service, session_id="lock-test-loop") + session.presence.attached() seed_titles(session) try: task = asyncio.create_task(handlers.session_tracks_handler({"title_id": "movie-0001"}, session.session_id)) @@ -275,6 +281,7 @@ async def test_two_segment_requests_never_share_the_service() -> None: overlap = Overlap() store = get_session_store() session = await store.create("EXAMPLE", ServiceProbe(overlap), session_id="lock-test-segments") + session.presence.attached() session.authenticated = True session.tracks = {tid: LookupTrack(tid, overlap) for tid in ("v-1", "a-1")} try: diff --git a/tests/remote/unit/test_session_store.py b/tests/remote/unit/test_session_store.py index 8d384c28d..6d5cf3b69 100644 --- a/tests/remote/unit/test_session_store.py +++ b/tests/remote/unit/test_session_store.py @@ -364,7 +364,7 @@ def test_the_login_state_is_the_one_its_bridge_holds(monkeypatch: pytest.MonkeyP worker = threading.Thread(target=lambda: answers.append(bridge.request_input("Code?"))) worker.start() assert offered.wait(5) - assert bridge.status is AuthStatus.PENDING_INPUT + assert bridge.get_pending_ask().prompt == "Code?" assert entry.auth_status is AuthStatus.AUTHENTICATING assert bridge.submit_response("1234") worker.join(5) diff --git a/tests/test_client_session_auth.py b/tests/test_client_session_auth.py index d861a3a99..603bd0474 100644 --- a/tests/test_client_session_auth.py +++ b/tests/test_client_session_auth.py @@ -85,6 +85,7 @@ def call_session_handler(handler, body, service, **entry_fields): async def run(): store = store_mod.get_session_store() entry = await store.create(service_tag="EXAMPLE", service_instance=service, session_id="s", owner_key=None) + entry.presence.attached() for name, value in entry_fields.items(): setattr(entry, name, value) try: @@ -181,7 +182,6 @@ def test_remote_get_tracks_scopes_server_cookies(): service_tag="EXAMPLE", log=logging.getLogger("test"), client=SimpleNamespace(post=lambda path, body: {"session_cookie_jar": jar}, probe=lambda endpoint: {}), - drain_server_logs=lambda: None, ) hold_session(service) service.get_tracks(SimpleNamespace(id="t1")) @@ -333,6 +333,7 @@ def _run_session(monkeypatch, tmp_path, data, answer, server_account=False, fail import asyncio import base64 import json + import uuid import zlib from unshackle.core.api import handlers @@ -362,11 +363,13 @@ def _run_session(monkeypatch, tmp_path, data, answer, server_account=False, fail data["cache"] = {"tokens_default": base64.b64encode(zlib.compress(b"{}")).decode("ascii")} async def run(): - resp = await handlers.session_create_handler({"service": "EXAMPLE", "title_id": "t", **data}) + body = {"service": "EXAMPLE", "title_id": "t", "session_id": str(uuid.uuid4()), **data} + resp = await handlers.session_create_handler(body) session = get_session_store().peek(json.loads(resp.body)["session_id"]) for _ in range(200): - if answer is not None and session.input_bridge.status == AuthStatus.PENDING_INPUT: - await handlers.session_prompt_post_handler({"response": answer}, session.session_id) + if answer is not None: + for ask in session.input_bridge.claim_for_channel(): + session.input_bridge.answer(ask.id, answer) if session.auth_status in (AuthStatus.AUTHENTICATED, AuthStatus.FAILED): break await asyncio.sleep(0.01) @@ -399,27 +402,12 @@ def test_a_failed_login_reports_its_error(monkeypatch, tmp_path): assert (session.auth_status, session.auth_error) == (AuthStatus.FAILED, "bad code") -def test_prompt_post_rejects_response_the_bridge_refused(monkeypatch): - import asyncio - - from unshackle.core.api import handlers - from unshackle.core.remote_protocol import AuthStatus - - bridge = SimpleNamespace(status=AuthStatus.PENDING_INPUT, submit_response=lambda text: False) - - async def fake_get_session(session_id, request): - return SimpleNamespace(input_bridge=bridge) - - monkeypatch.setattr(handlers, "get_validated_session", fake_get_session) - with pytest.raises(APIError): - asyncio.run(handlers.session_prompt_post_handler({"response": ""}, "sess")) - - def test_login_that_outlives_its_session_leaves_no_cache(monkeypatch, tmp_path): """A login loop that finishes after DELETE must not leave its tokens on the server's disk.""" import asyncio import json import threading + import uuid from unshackle.core.api import handlers from unshackle.core.api.session_store import get_session_store @@ -446,7 +434,9 @@ def test_login_that_outlives_its_session_leaves_no_cache(monkeypatch, tmp_path): stub_service_build(monkeypatch, SlowPairingService) async def run(): - resp = await handlers.session_create_handler({"service": "EXAMPLE", "title_id": "t"}) + resp = await handlers.session_create_handler( + {"service": "EXAMPLE", "title_id": "t", "session_id": str(uuid.uuid4())} + ) session = get_session_store().peek(json.loads(resp.body)["session_id"]) await get_session_store().delete(session.session_id) paired.set() diff --git a/unshackle/core/api/client_presence.py b/unshackle/core/api/client_presence.py index ae562c3f8..a25539adb 100644 --- a/unshackle/core/api/client_presence.py +++ b/unshackle/core/api/client_presence.py @@ -3,10 +3,9 @@ The limits of the silence, each of which must be longer than the silence of a client that still works: - ``FIRST_CONTACT_LIMIT``: a client whose create reply got lost sends the DELETE after its request timeout (120 s). -- ``AWAY_LIMIT``: a client that lost its channel polls at once and then in each third of the TTL. When the first poll - gets no answer, the next one arrives 160 s after the server saw the loss. It reconnects with a backoff of 30 s at most. +- ``AWAY_LIMIT``: a client that lost its channel reconnects with a backoff of a few seconds at most. - ``LEFT_LIMIT``: the DELETE of a client that closed its channel arrives within 55 s, and its reply has the login cache. - A gateway can also close a working channel with 1000, and 61 s cover six tries to reconnect. + A gateway can also close a working channel with 1000, and 22 s cover six tries to reconnect. """ from __future__ import annotations @@ -21,10 +20,9 @@ LEFT_LIMIT = 90.0 class ClientState(Enum): - """AWAITED: the client named the id in its create and has sent nothing since. POLLING: it has had no channel.""" + """AWAITED: the client has not attached its channel since its create.""" AWAITED = auto() - POLLING = auto() PRESENT = auto() AWAY = auto() LEFT = auto() @@ -36,8 +34,8 @@ class ClientPresence: Only the event loop calls it. A sign of life is a request of the client for its remote session, or a new channel. """ - def __init__(self, named: bool = False) -> None: - self.state = ClientState.AWAITED if named else ClientState.POLLING + def __init__(self) -> None: + self.state = ClientState.AWAITED self.seen_at = time.monotonic() @property @@ -48,9 +46,7 @@ class ClientPresence: def seen(self) -> None: """Take a request of the client. One that arrives after the client left shows that it only left its channel.""" self.seen_at = time.monotonic() - if self.state is ClientState.AWAITED: - self.state = ClientState.POLLING - elif self.state is ClientState.LEFT: + if self.state is ClientState.LEFT: self.state = ClientState.AWAY def attached(self) -> None: diff --git a/unshackle/core/api/errors.py b/unshackle/core/api/errors.py index 364916f6f..d19762378 100644 --- a/unshackle/core/api/errors.py +++ b/unshackle/core/api/errors.py @@ -61,6 +61,7 @@ class APIError(Exception): APIErrorCode.INVALID_PARAMETERS: 400, APIErrorCode.AUTH_FAILED: 401, APIErrorCode.FORBIDDEN: 403, + APIErrorCode.CLIENT_OUTDATED: 426, APIErrorCode.SERVER_CDM_CAPPED: 403, APIErrorCode.GEOFENCE: 403, APIErrorCode.NOT_FOUND: 404, diff --git a/unshackle/core/api/handlers.py b/unshackle/core/api/handlers.py index 85bcee94e..a5e9641f9 100644 --- a/unshackle/core/api/handlers.py +++ b/unshackle/core/api/handlers.py @@ -23,6 +23,7 @@ from aiohttp import web from unshackle.core import login, plugins from unshackle.core.api import api_proxy, licence_cap, server_keys +from unshackle.core.api.client_presence import ClientState from unshackle.core.api.compression import InflateLimitError, safe_inflate from unshackle.core.api.errors import APIError, categorize_exception, handle_api_exception from unshackle.core.api.input_bridge import InputBridge, NoUserBridge @@ -68,9 +69,6 @@ from unshackle.core.remote_protocol import ( LicenseRequest, LicensingMode, Licensor, - LogsReply, - PromptAnswer, - PromptReply, SegmentFilterReply, SegmentFilterRequest, SessionClosed, @@ -1125,14 +1123,11 @@ def choose_session_cdm(policy: KeyPolicy, service: str, data: dict[str, Any]) -> def session_licensing(policy: KeyPolicy, service: str, data: dict[str, Any]) -> LicensingMode: - """The licensing mode of a new remote session, before the service is built. - - An older client that sends no ``cdm_relay`` gets no client device outside a capped session. - """ + """The licensing mode of a new remote session, before the service is built.""" use_server_cdm, max_height = choose_session_cdm(policy, service, data) if use_server_cdm: return LicensingMode(Licensor.SERVER_CDM, max_height) - if data.get("cdm_type") and (max_height is not None or data.get("cdm_relay") is True): + if data.get("cdm_type"): return LicensingMode(Licensor.CLIENT_DEVICE, max_height, policy.allows("server_vault", service)) return LicensingMode(Licensor.NO_DEVICE, max_height) @@ -2028,8 +2023,8 @@ async def dashboard_session_logs_handler(request: web.Request) -> web.Response: """One remote session's mirrored service log, for an operator watching a failing auth. Reads through ``peek``: a dashboard poll must not refresh the session's idle timer, and - ``SessionLogBuffer.since`` is a cursor read, so this never takes records from the client - draining the same buffer through ``/api/session/{id}/logs``. + ``SessionLogBuffer.since`` is a cursor read, so this never takes records from the client's + remote session channel. """ from unshackle.core.api.session_store import get_session_store @@ -2906,7 +2901,7 @@ def client_device_cdm( level = data.get("cdm_security_level") level = level if is_whole_number(level) else None - if not (data.get("cdm_relay") is True and input_bridge is not None) or plugins.get(data.get("cdm_type")): + if input_bridge is None or plugins.get(data.get("cdm_type")): return cdm_type_stub(str(data.get("cdm_type")), level) from pywidevine import DeviceTypes @@ -2927,10 +2922,13 @@ def client_device_cdm( ) +CLIENT_OUTDATED_MESSAGE = "This client is older than the server accepts: update unshackle to the current dev build" + + def new_session_id(data: dict[str, Any]) -> str: - """The id of the remote session to make: the one its client named, as a canonical UUID version 4, else a new one.""" + """The id of the remote session to make, which its client names as a canonical UUID version 4.""" if "session_id" not in data: - return str(uuid.uuid4()) + raise APIError(APIErrorCode.CLIENT_OUTDATED, CLIENT_OUTDATED_MESSAGE) named = data["session_id"] with suppress(ValueError): if isinstance(named, str) and str(uuid.UUID(named, version=4)) == named: @@ -2968,8 +2966,7 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No try: address = request.remote if request else None - named = "session_id" in data - pending = PendingCreate(session_id, normalized_service, caller_key(request), address, named) + pending = PendingCreate(session_id, normalized_service, caller_key(request), address) async with get_session_store().creating(pending): return await create_session(data, request, title_id, profile, pending) except APIError: @@ -3269,7 +3266,6 @@ async def session_tracks_handler( session_headers=session_headers, session_cookies=cookie_values(session_cookies), session_cookie_jar=session_cookies, - server_cdm=session.licensing.server_cdm, server_cdm_type=server_cdm_type, sample_decrypt_tracks=[ str(t.id) for t in [*tracks.videos, *tracks.audio] if service_instance.decrypts_samples(t) @@ -3404,79 +3400,13 @@ def require_authenticated(session: SessionEntry) -> None: ) -async def session_prompt_get_handler(session_id: str, request: web.Request | None = None) -> web.Response: - """Poll for pending interactive prompts during authentication, and for CDM calls at any time. - - Returns the current auth status and any pending prompt that the - remote client should display to the user. A CDM call comes first, because service code can - wait on the client's CDM after authentication too, for example in get_tracks. - """ - session = await get_validated_session(session_id, request) - - bridge = session.input_bridge - if bridge and (cdm_call := bridge.get_pending_cdm_call()): - return web.json_response( - PromptReply(status=AuthStatus.PENDING_INPUT, prompt=bridge.get_pending_prompt(), cdm_call=cdm_call) - ) - - if session.auth_status == AuthStatus.AUTHENTICATED: - return web.json_response(PromptReply(status=AuthStatus.AUTHENTICATED)) - - if session.auth_status == AuthStatus.FAILED: - return web.json_response(PromptReply(status=AuthStatus.FAILED, error=session.auth_error or "unknown error")) - - if bridge and (ask := bridge.get_pending_ask()) and ask.prompt: - reply = PromptReply(status=AuthStatus.PENDING_INPUT, prompt=ask.prompt) - if ask.qr: - reply["qr"] = ask.qr - return web.json_response(reply) - - return web.json_response(PromptReply(status=AuthStatus.AUTHENTICATING)) - - -async def session_prompt_post_handler( - data: PromptAnswer, session_id: str, request: web.Request | None = None -) -> web.Response: - """Submit a response to a pending interactive prompt. - - The remote client calls this after collecting user input (OTP code, - PIN, or device-code confirmation) to unblock the server auth thread. - """ - session = await get_validated_session(session_id, request) - - response_text = data.get("response") - if response_text is None: - raise APIError(APIErrorCode.INVALID_INPUT, "Missing required field: response") - - bridge = session.input_bridge - if bridge is None or bridge.status != AuthStatus.PENDING_INPUT: - raise APIError(APIErrorCode.INVALID_INPUT, "No prompt pending for this session") - - if not bridge.submit_response(str(response_text)): - raise APIError(APIErrorCode.INVALID_INPUT, "No prompt pending for this session") - return web.json_response({"status": "accepted"}) - - -async def session_logs_handler(session_id: str, since: int = 0, request: web.Request | None = None) -> web.Response: - """Drain the remote session's service log records newer than *since*. - - Gives a remote client the service's server-side ``self.log`` output for - its own remote session - the reason an auth, title, or manifest step - failed. Works in every auth state, because a failed session is exactly - when the client needs the logs. - """ - session = await get_validated_session(session_id, request) - buffer = session.log_buffer - logs = buffer.since(since) if buffer else [] - return web.json_response(LogsReply(session_id=session_id, logs=logs, last_seq=logs[-1]["seq"] if logs else since)) - - -async def get_validated_session(session_id: str, request: web.Request | None) -> Any: +async def get_validated_session(session_id: str, request: web.Request | None, needs_channel: bool = True) -> Any: """Fetch a remote session and make sure that the caller owns it. Ownership is bound to the authenticating X-Secret-Key rather than the source IP: behind a reverse proxy every caller shares the proxy's address, so the IP check - (kept as defence in depth) cannot distinguish users on its own. + (kept as defence in depth) cannot distinguish users on its own. With ``needs_channel``, the handler + refuses a remote session whose client never attached the remote session channel. """ from unshackle.core.api.session_store import get_session_store @@ -3486,6 +3416,8 @@ async def get_validated_session(session_id: str, request: web.Request | None) -> raise session_not_found(session_id) if request is not None and not holds(session, caller_key(request), request.remote): raise APIError(APIErrorCode.FORBIDDEN, "Session access denied") + if needs_channel and session.presence.state is ClientState.AWAITED: + raise APIError(APIErrorCode.CLIENT_OUTDATED, CLIENT_OUTDATED_MESSAGE) session.presence.seen() return session @@ -3949,17 +3881,12 @@ async def session_keys_handler(data: TrackKeys, session_id: str, request: web.Re async def session_info_handler(session_id: str, request: web.Request | None = None) -> web.Response: """Make sure that the remote session is valid, and get the remote session info.""" - session = await get_validated_session(session_id, request) - - from unshackle.core.api.session_store import get_session_store - + session = await get_validated_session(session_id, request, needs_channel=False) return web.json_response( SessionInfo( session_id=session.session_id, service=session.service_tag, valid=True, - expires_in=get_session_store().ttl, - draining=get_session_store().draining, track_count=len(session.tracks), title_count=len(session.title_map), ) @@ -3977,7 +3904,7 @@ async def session_delete_handler(session_id: str, request: web.Request | None = ended = store.end_pending(session_id, caller_key(request), request.remote if request else None) if ended and store.peek(session_id) is None: return web.json_response(SessionClosed(status="ok")) - session = await get_validated_session(session_id, request) + session = await get_validated_session(session_id, request, needs_channel=False) session.end() cache_tag = session.cache_tag @@ -3995,7 +3922,7 @@ async def session_channel_handler(session_id: str, request: web.Request) -> web. """Attach the caller's session channel, which carries the messages the server starts for the remote session.""" from unshackle.core.api.session_store import get_session_store - session = await get_validated_session(session_id, request) + session = await get_validated_session(session_id, request, needs_channel=False) ws = web.WebSocketResponse(heartbeat=HEARTBEAT) await ws.prepare(request) # a request that is not a WebSocket upgrade fails here await session.channel.serve(ws, session, _since(request), get_session_store().draining) diff --git a/unshackle/core/api/input_bridge.py b/unshackle/core/api/input_bridge.py index cc9486f98..0031ce5a9 100644 --- a/unshackle/core/api/input_bridge.py +++ b/unshackle/core/api/input_bridge.py @@ -1,9 +1,9 @@ """Thread-safe bridge for the prompts and CDM calls that service code on the server sends to the remote client. When a service calls ``request_input()`` or its client-device CDM makes a call, the InputBridge blocks the -service thread on an *ask* until the remote client answers it. The remote session channel carries an ask when one is -attached; otherwise the prompt routes serve it, one at a time. Each ask belongs to the path that carried it -first, and only that path can answer it. +service thread on an *ask* until the remote client answers it. The remote session channel carries an ask, at once +when one is attached, else when the client attaches it. A relay for a REST client serves its asks one at a time to +the remote login routes instead. """ from __future__ import annotations @@ -22,16 +22,10 @@ if TYPE_CHECKING: # Seconds the server waits for a remote client to answer an input prompt before giving up. AUTH_INPUT_TIMEOUT = 600.0 CDM_CALL_TIMEOUT = 60.0 -# A listening client polls every few seconds, so a CDM call nobody fetches in this time has no client behind it. +# A client whose channel dropped tries to attach it again every few seconds, so a CDM call nobody takes in this time +# has no client. CDM_PICKUP_TIMEOUT = 10.0 -CDM_CALL_FALLBACK_PROMPT = ( - "This service needs your local CDM during login, and your unshackle cannot answer it. Update unshackle" -) - -CHANNEL = "channel" -POLL = "poll" - @dataclass(eq=False) class Ask: @@ -41,7 +35,6 @@ class Ask: prompt: str cdm_call: dict[str, Any] | None = None qr: str | None = None - owner: str | None = None # CHANNEL or POLL: the path that carried the ask, and the only one that answers it response: str | None = None error: str | None = None # the client could not answer, and says why picked_up: threading.Event = field(default_factory=threading.Event) @@ -53,7 +46,7 @@ class InputBridge: """Thread-safe bridge between the service threads and the async HTTP layer. A service thread calls :meth:`request_input` or :meth:`request_cdm`, which block until the remote client - answers through the remote session channel or the prompt routes. ``cut`` is True once a call failed because of + answers through the remote session channel or the remote login routes. ``cut`` is True once a call failed because of :meth:`cancel`: the service can go on after the error. """ @@ -75,7 +68,6 @@ class InputBridge: self._require_active() ask = Ask(uuid.uuid4().hex, prompt, cdm_call, qr) if self.channel is not None and self.channel.offer(ask): - ask.owner = CHANNEL ask.picked_up.set() self._asks[ask.id] = ask return ask @@ -83,8 +75,7 @@ class InputBridge: def request_input(self, prompt: str, timeout: float = AUTH_INPUT_TIMEOUT, qr: str | None = None) -> str: """Block until the remote client submits a response for *prompt*. - After authentication only an attached session channel can carry a prompt, as a polling client stops - asking for prompts once it is logged in. + After authentication only an attached session channel can carry a prompt. Raises: TimeoutError: If the bridge gets no response within *timeout*. @@ -118,7 +109,7 @@ class InputBridge: service thread for seconds, not for the full ``timeout``. """ with self._lock: - ask = self._open(CDM_CALL_FALLBACK_PROMPT, call) + ask = self._open("", call) try: picked_up = ask.picked_up.wait(timeout=pickup) answered = picked_up and ask.answered.wait(timeout=timeout) @@ -142,56 +133,37 @@ class InputBridge: raise RuntimeError(f"The client's CDM refused the call: {result['error']}") return result - def _pollable(self) -> list[Ask]: - """The asks the prompt routes can serve: unanswered, and not carried by the channel; call it under the lock. + def _waiting(self) -> list[Ask]: + """The unanswered asks, oldest first; call it under the lock. An answered ask stops being pending at once, before the waiting thread wakes, so a client that polls again straight away never sees it twice. """ - return [a for a in self._asks.values() if not a.answered.is_set() and a.owner != CHANNEL] - - def get_pending_cdm_call(self) -> dict[str, Any] | None: - """Return the CDM call that service code waits on, if any, and mark it as fetched by a client.""" - with self._lock: - ask = next((a for a in self._pollable() if a.cdm_call is not None), None) - if ask is None: - return None - ask.owner = POLL - ask.picked_up.set() - return ask.cdm_call - - def get_pending_prompt(self) -> str | None: - """Return the prompt of the first ask the prompt routes can serve, and keep that ask on them.""" - ask = self.get_pending_ask() - return ask.prompt if ask else None + return [a for a in self._asks.values() if not a.answered.is_set()] def get_pending_ask(self) -> Ask | None: - """Return the first ask the prompt routes can serve, and keep that ask on them.""" + """Return the oldest unanswered ask, for the remote login routes.""" with self._lock: - ask = next(iter(self._pollable()), None) - if ask is not None: - ask.owner = POLL - return ask + return next(iter(self._waiting()), None) def submit_response(self, response: str) -> bool: - """Answer the oldest ask that the prompt routes served, else the oldest one they can serve. + """Answer the oldest unanswered ask, for the remote login routes. Returns: ``True`` if an ask was pending and the bridge accepted the response, ``False`` otherwise. """ with self._lock: - pending = self._pollable() - ask = next((a for a in pending if a.owner == POLL), pending[0] if pending else None) + ask = next(iter(self._waiting()), None) if ask is None: return False self._answer(ask, response) return True def answer(self, ask_id: str, response: str, error: str | None = None) -> bool: - """Answer the ask with this id that the remote session channel carried; False when no such ask waits.""" + """Answer the ask with this id, for the remote session channel; False when no such ask waits.""" with self._lock: ask = self._asks.get(ask_id) - if ask is None or ask.owner != CHANNEL or ask.answered.is_set(): + if ask is None or ask.answered.is_set(): return False ask.error = error self._answer(ask, response) @@ -204,25 +176,13 @@ class InputBridge: ask.answered.set() def claim_for_channel(self) -> list[Ask]: - """Give every unanswered ask that the prompt routes did not serve to a newly attached session channel.""" + """Give every unanswered ask to a newly attached remote session channel.""" with self._lock: - asks = [a for a in self._asks.values() if not a.answered.is_set() and a.owner != POLL] + asks = self._waiting() for ask in asks: - ask.owner = CHANNEL ask.picked_up.set() return asks - def release_channel_asks(self) -> None: - """Hand the unanswered asks of a detached channel back to the prompt routes, so none waits on a dead socket. - - A prompt after login stays with the channel, as a polling client asks for prompts only while it logs in. - """ - with self._lock: - for ask in self._asks.values(): - pollable = ask.cdm_call is not None or self._status != AuthStatus.AUTHENTICATED - if ask.owner == CHANNEL and pollable and not ask.answered.is_set(): - ask.owner = None - def cancel(self) -> None: """Cancel the bridge, unblocking any waiting service thread.""" with self._lock: @@ -237,17 +197,9 @@ class InputBridge: with self._lock: self._require_active() - @property - def status(self) -> AuthStatus: - """``pending_input`` while an ask waits for its answer, else the login state.""" - with self._lock: - if self._status != AuthStatus.FAILED and any(not a.answered.is_set() for a in self._asks.values()): - return AuthStatus.PENDING_INPUT - return self._status - @property def login_status(self) -> AuthStatus: - """The login state alone: a waiting ask does not make it ``pending_input``.""" + """The login state alone.""" with self._lock: return self._status diff --git a/unshackle/core/api/routes.py b/unshackle/core/api/routes.py index f5303f6c4..20c3ba787 100644 --- a/unshackle/core/api/routes.py +++ b/unshackle/core/api/routes.py @@ -68,9 +68,6 @@ from unshackle.core.api.handlers import ( session_info_handler, session_keys_handler, session_license_handler, - session_logs_handler, - session_prompt_get_handler, - session_prompt_post_handler, session_samples_handler, session_segment_filter_handler, session_segments_handler, @@ -88,8 +85,6 @@ from unshackle.core.remote_protocol import ( HEALTH_ROUTE, KEYS_ROUTE, LICENSE_ROUTE, - LOGS_ROUTE, - PROMPT_ROUTE, SAMPLES_ROUTE, SEARCH_ROUTE, SEGMENT_FILTER_ROUTE, @@ -2181,6 +2176,7 @@ async def session_create(request: web.Request) -> web.Response: required: - service - title_id + - session_id properties: service: type: string @@ -2192,9 +2188,9 @@ async def session_create(request: web.Request) -> web.Response: The ID that the client gives the remote session, so that it can delete the session before this request answers. The canonical text of a version 4 UUID; the server answers any other value with INVALID_INPUT. A create of the same API key and IP with the same ID replaces the remote session of - that ID. The server answers the ID of another API key or IP with FORBIDDEN. Without it the server - makes the ID. A remote session with this ID ends when its client sends no request and opens no - channel within 150 seconds. + that ID. The server answers the ID of another API key or IP with FORBIDDEN. A body without it gets + CLIENT_OUTDATED (426). A remote session with this ID ends when its client sends no request and opens + no channel within 150 seconds. credentials: type: object additionalProperties: true @@ -2276,11 +2272,6 @@ async def session_create(request: web.Request) -> web.Response: description: | Security level of the client's local CDM, in the device's own numbers (Widevine 1 to 3, PlayReady 150 to 3000) - cdm_relay: - type: boolean - description: | - True when the client answers CDM calls, so the service sees a stand-in for its - device instead of the server's. A plugin `cdm_type` gets no relay cdm_system_id: type: integer description: System ID of the client's Widevine device @@ -2368,6 +2359,8 @@ async def session_create(request: web.Request) -> web.Response: description: SESSION_NOT_FOUND when a DELETE or a newer create ended the `session_id` first '401': description: Authentication failed + '426': + description: CLIENT_OUTDATED when the body has no `session_id` """ data = await json_body(request, MAX_LOGIN_BODY_BYTES) return await session_create_handler(data, request) @@ -2452,6 +2445,8 @@ async def session_titles(request: web.Request) -> web.Response: arrives as the error body with status 200. '404': description: Remote session not found + '426': + description: CLIENT_OUTDATED when the client has not attached the remote session channel """ session_id = request.match_info["session_id"] return await session_titles_handler(session_id, request) @@ -2496,6 +2491,8 @@ async def session_tracks(request: web.Request) -> web.Response: description: >- DRM_ERROR when a track of the title needs a DRM plugin that the client did not list in `plugins` when it created the remote session, or the client sent no `plugins` list. + '426': + description: CLIENT_OUTDATED when the client has not attached the remote session channel """ session_id = request.match_info["session_id"] data = await json_body(request) @@ -2539,6 +2536,8 @@ async def session_segments(request: web.Request) -> web.Response: arrives as the error body with status 200. '404': description: Remote session or track not found + '426': + description: CLIENT_OUTDATED when the client has not attached the remote session channel """ session_id = request.match_info["session_id"] data = await json_body(request) @@ -2579,6 +2578,8 @@ async def session_segment_filter(request: web.Request) -> web.Response: Absolute URIs of the unwanted segments, or null when the track has no segment filter '404': description: Remote session or track not found + '426': + description: CLIENT_OUTDATED when the client has not attached the remote session channel """ session_id = request.match_info["session_id"] data = await json_body(request) @@ -2622,6 +2623,8 @@ async def session_samples(request: web.Request) -> web.Response: description: The API key has no server_cdm grant for the service '404': description: Remote session or track not found + '426': + description: CLIENT_OUTDATED when the client has not attached the remote session channel """ frame = await request.clone(client_max_size=2 * cbcs.SAMPLE_BATCH_BYTES).read() return await session_samples_handler( @@ -2692,6 +2695,8 @@ async def session_license(request: web.Request) -> web.Response: arrives as the error body with status 200. '404': description: Remote session or track not found + '426': + description: CLIENT_OUTDATED when the client has not attached the remote session channel """ session_id = request.match_info["session_id"] data = await json_body(request) @@ -2738,6 +2743,8 @@ async def session_bad_key(request: web.Request) -> web.Response: description: The remote session was not served that pair '404': description: Remote session not found + '426': + description: CLIENT_OUTDATED when the client has not attached the remote session channel """ session_id = request.match_info["session_id"] data = await json_body(request) @@ -2784,6 +2791,8 @@ async def session_keys(request: web.Request) -> web.Response: description: An empty object, whatever the server stored '404': description: Remote session not found + '426': + description: CLIENT_OUTDATED when the client has not attached the remote session channel """ session_id = request.match_info["session_id"] data = await json_body(request) @@ -2848,7 +2857,10 @@ async def session_channel(request: web.Request) -> web.StreamResponse: A WebSocket that a --remote client holds open for its remote session. The server sends each message it starts as a JSON text frame with a type field - prompt and cdm_call (each with an id), log, status, and drain (with draining true or false). - The client answers a prompt or a CDM call with {"type": "answer", "id": , "response": }. + The call of a cdm_call has an op - challenge (with drm, init_data, license_type, privacy_mode and + service_certificate), keys (with the CDM session and license) or close (with the CDM session). + The client answers a prompt or a CDM call with {"type": "answer", "id": , "response": }; a CDM + call's response is a JSON object as text, or {"error": ...} for an op the client does not know. On attach the server first sends the log records after since, the drain state, the waiting prompts and CDM calls, then the login state. The remote session does not expire while the channel is open. When the server removes the remote session, it closes the channel with code 4404. @@ -2875,154 +2887,6 @@ async def session_channel(request: web.Request) -> web.StreamResponse: return await session_channel_handler(request.match_info["session_id"], request) -@api_handler -@categorized -async def session_prompt_get(request: web.Request) -> web.Response: - """ - Poll for pending interactive prompts during authentication. - --- - summary: Get auth prompt - description: Poll for pending interactive prompts (OTP, device code, PIN) during remote session authentication - parameters: - - name: session_id - in: path - required: true - schema: - type: string - responses: - '200': - description: Auth status and optional prompt - content: - application/json: - schema: - type: object - properties: - status: - type: string - enum: [authenticating, pending_input, authenticated, failed] - prompt: - type: string - description: Prompt to display to the user (only when status is pending_input) - cdm_call: - type: object - additionalProperties: true - description: | - A call the service makes on the client's CDM, in any auth state: `op` is `challenge` - (with `drm`, `init_data`, `license_type`, `privacy_mode` and `service_certificate`), - `keys` (with `session` and `license`) or `close` (with `session`). The client answers - with a JSON object in the POST `response`, or `{"error": ...}` for an op it does not know. - error: - type: string - description: Error message (only for the failed status) - '404': - description: Remote session not found - """ - session_id = request.match_info["session_id"] - return await session_prompt_get_handler(session_id, request) - - -@api_handler -@categorized -async def session_logs(request: web.Request) -> web.Response: - """ - Drain the remote session's service log records. - --- - summary: Get session logs - description: The service's server-side log output for this remote session, newer than the given sequence number - parameters: - - name: session_id - in: path - required: true - schema: - type: string - - name: since - in: query - required: false - schema: - type: integer - default: 0 - description: Return only records with a sequence number greater than this - responses: - '200': - description: Log records, oldest first - content: - application/json: - schema: - type: object - properties: - logs: - type: array - items: - type: object - properties: - seq: - type: integer - level: - type: string - message: - type: string - ts: - type: number - last_seq: - type: integer - '404': - description: Remote session not found - """ - session_id = request.match_info["session_id"] - try: - since = int(request.query.get("since", 0)) - except ValueError: - since = 0 - return await session_logs_handler(session_id, since, request) - - -@api_handler -@categorized -async def session_prompt_submit(request: web.Request) -> web.Response: - """ - Submit a response to a pending interactive prompt. - --- - summary: Submit prompt response - description: Submit user input (OTP code, PIN, device code confirmation) to unblock server authentication - parameters: - - name: session_id - in: path - required: true - schema: - type: string - requestBody: - required: true - content: - application/json: - schema: - type: object - required: - - response - properties: - response: - type: string - description: User's response to the prompt - responses: - '200': - description: Response accepted - content: - application/json: - schema: - type: object - properties: - status: - type: string - example: accepted - '400': - description: No prompt pending or invalid request - '404': - description: Remote session not found - """ - session_id = request.match_info["session_id"] - data = await json_body(request) - return await session_prompt_post_handler(data, session_id, request) - - @api_handler async def dashboard_status(request: web.Request) -> web.Response: """ @@ -3127,7 +2991,7 @@ async def dashboard_sessions(request: web.Request) -> web.Response: type: integer auth_status: type: string - enum: [authenticated, authenticating, pending_input, failed] + enum: [authenticated, authenticating, failed] auth_error: type: string nullable: true @@ -3349,7 +3213,7 @@ async def dashboard_session_logs(request: web.Request) -> web.Response: server's log level. This is where the real reason for a failed authentication sits, in full, while the remote session summary carries only a truncated `auth_error`. Reading this does not refresh the remote session's idle timer and does not take records - from the client draining the same buffer through `/api/session/{session_id}/logs`. + from the client's session channel. Poll when the remote session summary's `log_seq` changes. tags: [Dashboard] parameters: @@ -3775,9 +3639,6 @@ ROUTES: list[tuple[str, str, Handler, bool]] = [ ("POST", LICENSE_ROUTE, session_license, True), ("POST", KEYS_ROUTE, session_keys, True), ("POST", BAD_KEY_ROUTE, session_bad_key, True), - ("GET", LOGS_ROUTE, session_logs, True), - ("GET", PROMPT_ROUTE, session_prompt_get, True), - ("POST", PROMPT_ROUTE, session_prompt_submit, True), ("GET", CHANNEL_ROUTE, session_channel, True), ("GET", SESSION_ROUTE, session_info, True), ("DELETE", SESSION_ROUTE, session_delete, True), diff --git a/unshackle/core/api/session_channel.py b/unshackle/core/api/session_channel.py index 930461abd..b38503a4f 100644 --- a/unshackle/core/api/session_channel.py +++ b/unshackle/core/api/session_channel.py @@ -2,8 +2,8 @@ Service threads (prompts and CDM calls in the input bridge, the session log mirror), the drain and the session store hand each message to the remote session's :class:`SessionChannel`. While the client holds the channel's -WebSocket open, the channel sends the message at once. Otherwise the message waits where the polling routes read -it (the input bridge, the log buffer of the remote session, the drain flag), as for a client without the channel. +WebSocket open, the channel sends the message at once. Otherwise the message waits (in the input bridge, the log +buffer of the remote session, the drain flag) until the client attaches the channel again. """ from __future__ import annotations @@ -41,7 +41,7 @@ def drain_message(draining: bool) -> ChannelDrain: def status_message(session: SessionEntry) -> ChannelStatus: - """The login state of the remote session, with the same redacted error that the prompt route gives.""" + """The login state of the remote session, with its redacted error.""" message = ChannelStatus(type=ChannelMessage.STATUS, status=session.auth_status.value) if session.auth_error: message["error"] = session.auth_error @@ -77,11 +77,11 @@ class SessionChannel: return True def offer(self, ask: Ask) -> bool: - """Send a prompt or CDM call that service code waits on; False when the polling routes must serve it.""" + """Send a prompt or CDM call that service code waits on; False when no WebSocket is attached.""" return self.send(ask_message(ask)) def log(self, record: LogRecord) -> None: - """Send one record of the service log mirror; the buffer keeps it for the logs route too.""" + """Send one record of the service log mirror; the buffer keeps it for the next attach too.""" if self.queue is not None: self.send(log_message(record)) @@ -93,8 +93,8 @@ class SessionChannel: async def serve(self, ws: web.WebSocketResponse, session: SessionEntry, since: int, draining: bool) -> None: """Attach *ws* until the client or the server closes it. - The client first gets what it missed: the log records after *since*, a drain notice, the prompts and CDM - calls the polling routes did not serve, then the login state. A log record can come twice; its ``seq`` + The client first gets what it missed: the log records after *since*, a drain notice, the waiting prompts + and CDM calls, then the login state. A log record can come twice; its ``seq`` tells the client. A close frame comes to the read loop only when the client starts the close; the loop of a socket that the server closes, or that the network loses, ends with another message. """ @@ -127,8 +127,6 @@ class SessionChannel: if self.ws is ws: self.ws = self.queue = None session.presence.detached(left) - if bridge is not None: - bridge.release_channel_asks() session.touch() @staticmethod diff --git a/unshackle/core/api/session_log.py b/unshackle/core/api/session_log.py index 69062a254..a5d634caf 100644 --- a/unshackle/core/api/session_log.py +++ b/unshackle/core/api/session_log.py @@ -4,7 +4,7 @@ A service running under ``serve`` logs to the server's console, so a remote client never sees why an auth or manifest step failed. Each remote session gets a bounded :class:`SessionLogBuffer`; the service instance's ``self.log`` is wrapped in a :class:`SessionLogMirror` that copies every call into the -buffer, and the client drains it through ``GET /api/session/{id}/logs``. +buffer, and the remote session channel sends each record to the client. Only ``self.log`` calls are mirrored. Output from module-level loggers (the manifest parsers, the downloader) stays server-side. diff --git a/unshackle/core/api/session_store.py b/unshackle/core/api/session_store.py index e1ec5ca64..0f0f53eca 100644 --- a/unshackle/core/api/session_store.py +++ b/unshackle/core/api/session_store.py @@ -196,7 +196,6 @@ class PendingCreate: service_tag: str owner_key: str = field(repr=False) creator_ip: str | None - named: bool = False ended: bool = False def require_live(self) -> None: @@ -351,7 +350,6 @@ class SessionStore: client_plugins=client_plugins, input_bridge=input_bridge, log_buffer=log_buffer, - presence=ClientPresence(named=pending is not None and pending.named), ) self._sessions[session_id] = entry _publish("create", entry) diff --git a/unshackle/core/remote_channel.py b/unshackle/core/remote_channel.py index c5c810b7e..d0c0604fd 100644 --- a/unshackle/core/remote_channel.py +++ b/unshackle/core/remote_channel.py @@ -1,9 +1,8 @@ """The messages a remote server starts for a remote session, on the client. The server starts some messages itself: a login prompt, a call on this machine's CDM, a service log record, a -login state change and a drain notice. :func:`open_channel` gives :class:`RemoteService` one of two adapters with -the same methods. :class:`WebSocketChannel` gets the messages on the remote session channel. :class:`PollingChannel` asks -the server for them, when the channel upgrade is refused or fails, and while the channel is down. +login state change and a drain notice. :func:`open_channel` gives :class:`RemoteService` the remote session channel, +a WebSocket that :class:`WebSocketChannel` holds open. """ from __future__ import annotations @@ -12,37 +11,29 @@ import asyncio import contextlib import json import logging +import random import time from collections import deque -from collections.abc import Callable, Iterator -from contextlib import AbstractContextManager from threading import Event, Lock, Thread from typing import TYPE_CHECKING, Any, cast import aiohttp -import requests from aiohttp import WSMsgType from unshackle.core.console import prompt_user, show_notice, show_qr from unshackle.core.remote_protocol import ( CHANNEL_ROUTE, CHANNEL_SESSION_GONE, - LOGS_ROUTE, - PROMPT_ROUTE, - SAMPLES_ROUTE, - SESSION_ROUTE, + APIErrorCode, AuthStatus, ChannelAnswer, ChannelMessage, ClientErrorKind, LogRecord, - LogsReply, - PromptAnswer, - PromptReply, - SessionInfo, ) from unshackle.core.remote_service import RemoteError, cancelled, pause, quiet, require_run, ws_headers -from unshackle.core.tunnel import HEARTBEAT, retry_after, run_loop +from unshackle.core.tunnel import HEARTBEAT, refusal, retry_after, run_loop +from unshackle.core.utils.redact import safe_display_url if TYPE_CHECKING: from unshackle.core.remote_service import RemoteService @@ -51,10 +42,10 @@ log = logging.getLogger("remote_channel") AUTH_TIMEOUT = 600.0 AUTH_POLL_INTERVAL = 2.0 -CDM_POLL_INTERVAL = 0.5 -KEEPALIVE_MIN_INTERVAL = 5.0 CONNECT_TIMEOUT = 10.0 RECONNECT_DELAY = 1.0 +RECONNECT_MAX = 5.0 # below CDM_PICKUP_TIMEOUT, so a CDM call made while the channel is down still reaches this client +RETRIED_STATUSES = (429, 502, 503, 504) # a gateway or a rate limit that can pass: the first open tries once more GONE_STATUSES = (401, 403, 404) # the API key or the remote session is gone, so a reconnect cannot help SEND_TIMEOUT = 10.0 CDM_CLOSE_TIMEOUT = 5.0 @@ -68,7 +59,7 @@ def server_qr(value: object) -> str | None: class ServerMessages: - """What this client does with each message the server starts, whichever adapter brought it.""" + """What this client does with each message the server starts.""" def __init__(self, service: RemoteService) -> None: self.service = service @@ -78,11 +69,8 @@ class ServerMessages: self.cdm_lock = Lock() self.cdm_sessions: dict[str, bytes] = {} - def route(self, route: str) -> str: - return route.format(session_id=self.service.lifetime.require_session()) - def show_logs(self, records: list[LogRecord]) -> None: - """Log the service's server-side records here, each once: a record that the other path brought is skipped.""" + """Log the service's server-side records here, each once: a record that a reconnect brought again is skipped.""" from unshackle.core.api.sanitize import sanitize_log with self.log_lock: @@ -103,7 +91,7 @@ class ServerMessages: self.log_seq = seq def answer_cdm(self, call: dict[str, Any]) -> dict[str, Any]: - """Run one of the server's CDM calls on this machine's device; both adapters share its CDM sessions.""" + """Run one of the server's CDM calls on this machine's device.""" from unshackle.core.cdm.client_relay import answer_cdm_call with self.cdm_lock: @@ -153,174 +141,16 @@ class ServerMessages: show_notice(None) -class PollingChannel: - """The fallback: the client asks the server for each message. +class WebSocketChannel: + """The remote session channel: the server sends its messages on a WebSocket that a daemon thread holds open. - The client uses it when a gateway or the server refuses the channel upgrade, when the connection fails, and while - the channel is down. It goes together with the polling routes. + While the WebSocket is down, the thread reconnects with a backoff. The thread never reopens a session: a close + with ``CHANNEL_SESSION_GONE`` ends it, and the next call finds the remote session gone. """ def __init__(self, messages: ServerMessages) -> None: self.messages = messages self.service = messages.service - self.keepalive_stop = Event() - self.keepalive_stop.set() - self.drain_lock = Lock() - self.cdm_lock = Lock() - self.cdm_requests = 0 - self.cdm_stop = Event() - self.paused: Callable[[], bool] = lambda: False - - def wait_auth(self, timeout: float = AUTH_TIMEOUT, step: Callable[[], bool] | None = None) -> None: - """Poll the server until authentication completes, and answer its prompts and CDM calls. - - ``step`` replaces :meth:`auth_step` for an adapter that learns the login state another way. - """ - deadline = time.monotonic() + timeout - try: - while time.monotonic() < deadline: - require_run() - if (step or self.auth_step)(): - return - raise RemoteError("Remote authentication timed out", ClientErrorKind.AUTH) - finally: - self.messages.login_done() - - def auth_step(self) -> bool: - """Poll the login state once: True when authenticated. Answer a prompt or a CDM call, or wait one interval.""" - resp = cast(PromptReply, self.service.client.get(self.messages.route(PROMPT_ROUTE))) - status = resp.get("status") - seen = self.messages.log_seq - self.drain_logs() - if status == AuthStatus.AUTHENTICATED: - return True - if status == AuthStatus.AUTHENTICATING: - self.messages.note_waiting(seen) - if status == AuthStatus.FAILED: - raise RemoteError( - f"Remote auth failed: {resp.get('error', 'Authentication failed on server')}", ClientErrorKind.AUTH - ) - if status == AuthStatus.PENDING_INPUT and isinstance(resp.get("cdm_call"), dict): - self.answer(json.dumps(self.messages.answer_cdm(resp["cdm_call"]))) - elif status == AuthStatus.PENDING_INPUT: - self.answer(self.messages.ask_user(resp.get("prompt") or "Enter input: ", resp.get("qr"))) - else: - pause(AUTH_POLL_INTERVAL) - return False - - def answer(self, response: str) -> None: - self.service.client.post(self.messages.route(PROMPT_ROUTE), PromptAnswer(response=response)) - - def keep_alive(self) -> None: - """Send keep-alive requests so that a long download or mux operation does not outlive the server's idle TTL. - - ``GET /api/session/{session_id}`` refreshes the idle timer and reports the TTL, so the thread sends a request - at an interval of one third of it, until :meth:`stop_keepalive`. A client that dies stops sending requests, - so the server still expires an abandoned remote session. - """ - if not self.keepalive_stop.is_set(): - return - stop = self.keepalive_stop = Event() - endpoint = self.messages.route(SESSION_ROUTE) - - def ping() -> None: - info = cast(SessionInfo, self.service.client.probe(endpoint)) - interval = max(float(info.get("expires_in") or 300) / 3, KEEPALIVE_MIN_INTERVAL) - while not stop.wait(interval): - self.service.client.probe(endpoint) - - Thread(target=ping, name=f"{self.service.service_tag}-keepalive", daemon=True).start() - - def stop_keepalive(self) -> None: - self.keepalive_stop.set() - - def runs_service_code(self, endpoint: str) -> bool: - """Whether a request to *endpoint* runs service code on the server, which can make CDM calls.""" - if self.service._session_id is None: - return False - own = {self.messages.route(route) for route in (PROMPT_ROUTE, LOGS_ROUTE, SAMPLES_ROUTE)} - return endpoint.startswith(self.messages.route(SESSION_ROUTE) + "/") and endpoint.partition("?")[0] not in own - - @contextlib.contextmanager - def in_flight(self, endpoint: str) -> Iterator[None]: - """Answer the server's CDM calls while a remote session request runs service code. - - One poller serves every concurrent request, and the local CDM sessions close when the last one ends. - """ - if not self.runs_service_code(endpoint): - yield - return - with self.cdm_lock: - self.cdm_requests += 1 - if self.cdm_requests == 1: - self.cdm_stop = Event() - Thread( - target=self.poll_cdm_calls, - args=(self.cdm_stop,), - name=f"{self.service.service_tag}-cdm", - daemon=True, - ).start() - try: - yield - finally: - with self.cdm_lock: - self.cdm_requests -= 1 - last = self.cdm_requests == 0 - if last: - self.cdm_stop.set() - if last: - self.messages.close_cdm_sessions() - - def poll_cdm_calls(self, stop: Event, interval: float | None = None) -> None: - endpoint = self.messages.route(PROMPT_ROUTE) - while not stop.wait(CDM_POLL_INTERVAL if interval is None else interval): - if self.paused(): - continue - try: - call = cast(PromptReply, self.service.client.probe(endpoint)).get("cdm_call") - if isinstance(call, dict): - with quiet(): - self.answer(json.dumps(self.messages.answer_cdm(call))) - except (requests.RequestException, ValueError, SystemExit) as e: - self.service.log.debug(f"CDM call poll failed: {e}") - - def drain_logs(self) -> None: - """Fetch the service's server-side log records for this remote session and log them here. - - A relay failure must never break the operation itself, so this method swallows every error. - """ - if not self.service._session_id or cancelled(): - return - with self.drain_lock: - try: - with quiet(): - endpoint = self.messages.route(LOGS_ROUTE) + f"?since={self.messages.log_seq}" - resp = cast(LogsReply, self.service.client.get_optional(endpoint)) - if resp: - self.messages.show_logs(resp.get("logs", [])) - except (Exception, SystemExit): - return - - def draining(self) -> bool: - """Whether the server announced a restart.""" - info = cast(SessionInfo, self.service.client.probe(self.messages.route(SESSION_ROUTE))) - return bool(info.get("draining")) - - def close(self) -> None: - self.stop_keepalive() - - -class WebSocketChannel: - """The remote session channel: the server sends its messages on a WebSocket that a daemon thread holds open. - - While the WebSocket is down, :attr:`fallback` polls and the thread reconnects with a backoff. The thread never - reopens a session: a close with ``CHANNEL_SESSION_GONE`` ends it, and the next call finds the session gone. - """ - - def __init__(self, messages: ServerMessages, fallback: PollingChannel) -> None: - self.messages = messages - self.service = messages.service - self.fallback = fallback self.headers = ws_headers(self.service.client) self.connected = Event() self.attempted = Event() @@ -328,23 +158,30 @@ class WebSocketChannel: self.status: str | None = None self.error = "" self.failure: RemoteError | None = None + self.refusal: str | None = None + self.cause = "no answer" self.draining_now = False self.answers: dict[str, ChannelAnswer | None] = {} # None while this client still works on the ask - fallback.paused = self.connected.is_set self.ws: aiohttp.ClientWebSocketResponse | None = None self.loop: asyncio.AbstractEventLoop | None = None self.task: asyncio.Task[None] | None = None self.stopped = False self.thread = Thread(target=run_loop, args=(self.run,), name=f"{self.service.service_tag}-channel", daemon=True) - def open(self, timeout: float = CONNECT_TIMEOUT) -> bool: - """Connect once; False when the server or a gateway refuses the channel, or the connection fails.""" + def open(self, timeout: float = CONNECT_TIMEOUT) -> None: + """Connect once, or raise when the server or a gateway refuses the channel or the connection fails.""" self.thread.start() pause(timeout, self.attempted) - if not self.connected.is_set(): - self.close() - return False - return True + if self.connected.is_set(): + return + self.close() + self.service.lifetime.require_open() + host = safe_display_url(self.service.client.server_url) + if self.refusal is not None: + raise RemoteError( + f"The remote server at {host} refused the session channel: {self.refusal}", ClientErrorKind.UNKNOWN + ) + raise RemoteError(f"Could not open the session channel to {host}: {self.cause}", ClientErrorKind.CONNECT) async def run(self) -> None: self.loop, self.task = asyncio.get_running_loop(), asyncio.current_task() @@ -360,12 +197,13 @@ class WebSocketChannel: async def connect(self) -> None: backoff = RECONNECT_DELAY + retried = False async with aiohttp.ClientSession(headers=self.headers) as http: while True: code = None url = ( self.service.client.server_url - + self.messages.route(CHANNEL_ROUTE) + + CHANNEL_ROUTE.format(session_id=self.service.lifetime.require_session()) + f"?since={self.messages.log_seq}" ) try: @@ -373,18 +211,23 @@ class WebSocketChannel: self.ws = ws self.connected.set() self.attempted.set() - self.fallback.stop_keepalive() backoff = RECONNECT_DELAY await self.read(ws) code = ws.close_code except aiohttp.WSServerHandshakeError as e: log.debug(f"The server refused the session channel: HTTP {e.status}") - if not self.attempted.is_set() or e.status in GONE_STATUSES: + if not self.attempted.is_set(): + self.refusal = refusal(e) + if retried or e.status not in RETRIED_STATUSES or (retry_after(e) or 0) >= CONNECT_TIMEOUT: + return + retried = True + elif e.status in GONE_STATUSES: return backoff = max(backoff, retry_after(e) or 0) except (TimeoutError, aiohttp.ClientError, OSError) as e: log.debug(f"The session channel could not connect: {e!r}") if not self.attempted.is_set(): + self.cause = " ".join(str(e).split()) or type(e).__name__ return finally: self.ws = None @@ -393,10 +236,10 @@ class WebSocketChannel: if code == CHANNEL_SESSION_GONE: log.debug("The server closed the session channel: the remote session is gone") return - self.fallback.keep_alive() log.debug(f"The session channel dropped, reconnecting in {backoff:.1f}s") - await asyncio.sleep(backoff) - backoff = min(backoff * 2, 30.0) + # jittered, so the clients of a restarted server do not all reconnect at the same moment + await asyncio.sleep(random.uniform(backoff / 2, backoff)) # nosec B311 + backoff = min(backoff * 2, RECONNECT_MAX) async def read(self, ws: aiohttp.ClientWebSocketResponse) -> None: async for msg in ws: @@ -456,15 +299,21 @@ class WebSocketChannel: asyncio.run_coroutine_threadsafe(ws.send_json(answer), loop).result(SEND_TIMEOUT) def wait_auth(self, timeout: float = AUTH_TIMEOUT) -> None: - """Wait for the login state on the channel, and poll while the channel is down.""" - self.fallback.wait_auth(timeout, self.auth_step) + """Wait for the login state on the channel, while another thread answers the server's prompts and CDM calls.""" + deadline = time.monotonic() + timeout + try: + while time.monotonic() < deadline: + require_run() + if self.auth_step(): + return + raise RemoteError("Remote authentication timed out", ClientErrorKind.AUTH) + finally: + self.messages.login_done() def auth_step(self) -> bool: """Wait one interval for the login state: True when authenticated.""" if self.failure is not None: raise self.failure - if not self.connected.is_set(): - return self.fallback.auth_step() self.changed.clear() if self.status == AuthStatus.AUTHENTICATED: return True @@ -472,49 +321,24 @@ class WebSocketChannel: raise RemoteError( f"Remote auth failed: {self.error or 'Authentication failed on server'}", ClientErrorKind.AUTH ) + if not self.thread.is_alive(): + raise RemoteError("The session channel closed before the login ended", APIErrorCode.SESSION_NOT_FOUND) seen = self.messages.log_seq if not pause(AUTH_POLL_INTERVAL, self.changed) and self.status == AuthStatus.AUTHENTICATING: self.messages.note_waiting(seen) return False - def keep_alive(self) -> None: - """An open channel keeps the remote session alive; the fallback pings while the channel is down.""" - if not self.connected.is_set(): - self.fallback.keep_alive() - - def in_flight(self, endpoint: str) -> AbstractContextManager[None]: - """The fallback's CDM call poller, which polls only while the channel is down.""" - return self.fallback.in_flight(endpoint) - - def drain_logs(self) -> None: - if not self.connected.is_set(): - self.fallback.drain_logs() - - def draining(self) -> bool: - return self.draining_now if self.connected.is_set() else self.fallback.draining() - def close(self) -> None: self.stopped = True if self.loop and self.task and self.thread.is_alive(): with contextlib.suppress(RuntimeError): # the loop closes before its thread ends self.loop.call_soon_threadsafe(self.task.cancel) self.thread.join(5) - self.fallback.close() self.messages.close_cdm_sessions() -Channel = PollingChannel | WebSocketChannel - - -def open_channel(service: RemoteService) -> Channel: - """The remote session channel when the server takes it, else the polling fallback, also for every later session.""" - messages = ServerMessages(service) - fallback = PollingChannel(messages) - if service.client.no_channel: - return fallback - channel = service.lifetime.channel = WebSocketChannel(messages, fallback) - if channel.open(): - return channel - service.lifetime.require_open() - service.client.no_channel = True - return fallback +def open_channel(service: RemoteService) -> WebSocketChannel: + """Open the remote session channel of ``service``; raise when it cannot open.""" + channel = service.lifetime.channel = WebSocketChannel(ServerMessages(service)) + channel.open() + return channel diff --git a/unshackle/core/remote_lifetime.py b/unshackle/core/remote_lifetime.py index a57bddbbb..c00596bf0 100644 --- a/unshackle/core/remote_lifetime.py +++ b/unshackle/core/remote_lifetime.py @@ -16,7 +16,7 @@ from unshackle.core.remote_protocol import SESSION_ROUTE, APIErrorCode, SessionC from unshackle.core.remote_service import RemoteClient, RemoteError, quiet, require_run if TYPE_CHECKING: - from unshackle.core.remote_channel import Channel + from unshackle.core.remote_channel import WebSocketChannel log = logging.getLogger("remote_lifetime") @@ -42,7 +42,7 @@ class RemoteSessionLifetime: self.client = client self.save_cache = save_cache self.session_id: str | None = None - self.channel: Channel | None = None + self.channel: WebSocketChannel | None = None self.ended = False self._held: set[str] = set() self._lock = RLock() @@ -93,10 +93,9 @@ class RemoteSessionLifetime: self._held.add(named) return named - def adopt(self, named: str, session_id: str) -> None: - """Take the id of the create reply, which an older server picks itself.""" + def adopt(self, session_id: str) -> None: + """Take the id of the remote session that the server made.""" with self._lock: - self._held = (self._held - {named}) | {session_id} self.session_id = session_id def release(self, gone: bool = False) -> None: diff --git a/unshackle/core/remote_protocol.py b/unshackle/core/remote_protocol.py index 563c0bd2e..6a985001e 100644 --- a/unshackle/core/remote_protocol.py +++ b/unshackle/core/remote_protocol.py @@ -2,8 +2,7 @@ ``dl --remote`` (:mod:`unshackle.core.remote_service`) and the server (:mod:`unshackle.core.api`) both read this record. Titles, tracks and DRM keep the form of :mod:`unshackle.core.wire`, and ``dl_params`` that of -:mod:`unshackle.core.dl_options`. Every name and value here is on the wire, so a change must stay readable by an -older peer. +:mod:`unshackle.core.dl_options`. Every name and value here is on the wire. """ from __future__ import annotations @@ -26,8 +25,6 @@ SAMPLES_ROUTE = SESSION_ROUTE + "/samples" LICENSE_ROUTE = SESSION_ROUTE + "/license" KEYS_ROUTE = SESSION_ROUTE + "/keys" BAD_KEY_ROUTE = SESSION_ROUTE + "/keys/bad" -LOGS_ROUTE = SESSION_ROUTE + "/logs" -PROMPT_ROUTE = SESSION_ROUTE + "/prompt" CHANNEL_ROUTE = SESSION_ROUTE + "/channel" CHANNEL_SESSION_GONE = 4404 @@ -35,10 +32,9 @@ CHANNEL_SESSION_GONE = 4404 class AuthStatus(StrEnum): - """Authentication lifecycle states for a remote session, as the ``status`` of a prompt reply.""" + """Authentication lifecycle states for a remote session, as the ``status`` of a session channel message.""" AUTHENTICATING = "authenticating" - PENDING_INPUT = "pending_input" AUTHENTICATED = "authenticated" FAILED = "failed" @@ -53,6 +49,7 @@ class APIErrorCode(str, Enum): AUTH_FAILED = "AUTH_FAILED" FORBIDDEN = "FORBIDDEN" + CLIENT_OUTDATED = "CLIENT_OUTDATED" SERVER_CDM_CAPPED = "SERVER_CDM_CAPPED" GEOFENCE = "GEOFENCE" @@ -155,7 +152,6 @@ class SessionCreate(ClientLogin, total=False): server_cdm: bool cdm_type: str cdm_security_level: int - cdm_relay: bool cdm_system_id: int cdm_device_type: str service_config: dict[str, Any] @@ -170,7 +166,7 @@ class SessionCreate(ClientLogin, total=False): class SessionCreated(TypedDict, total=False): - """The reply to a remote session creation. An older server leaves out the licensing fields.""" + """The reply to a remote session creation.""" session_id: str service: str @@ -199,7 +195,7 @@ class Licensor(StrEnum): class LicensingMode: """Who licenses a remote session, its licence cap and its access to the server vault, fixed at session create. - Only a client-device session, lent or not, can read the server vault. The wire keeps the older fields + Only a client-device session, lent or not, can read the server vault. On the wire it is the fields ``server_cdm``, ``server_cdm_max_height``, ``server_vault`` and ``server_device``. """ @@ -292,7 +288,6 @@ class TracksReply(TypedDict, total=False): session_headers: dict[str, str] session_cookies: dict[str, str] session_cookie_jar: list[dict[str, Any]] - server_cdm: bool | None server_cdm_type: str sample_decrypt_tracks: list[str] fairplay_bridge: bool @@ -356,20 +351,6 @@ class TrackKeys(TypedDict): keys: dict[str, str] -class PromptReply(TypedDict, total=False): - """The login state of a remote session, and the prompt or CDM call that waits for the client.""" - - status: str - prompt: str | None - qr: str - cdm_call: dict[str, Any] - error: str - - -class PromptAnswer(TypedDict): - response: str - - class LogRecord(TypedDict): """One service log record; ``qr`` is the text of a QR code the client draws below the message.""" @@ -380,12 +361,6 @@ class LogRecord(TypedDict): qr: NotRequired[str] -class LogsReply(TypedDict): - session_id: str - logs: list[LogRecord] - last_seq: int - - class TitlesReply(TypedDict): """The titles of a remote session, each in the form of ``core.wire``; ``collection`` only for a music collection.""" @@ -422,7 +397,7 @@ class ChannelPrompt(TypedDict): class ChannelCdmCall(TypedDict): - """A call the service makes on the client's CDM, in the shape of the prompt route's ``cdm_call``.""" + """A call the service makes on the client's CDM.""" type: str id: str @@ -430,7 +405,7 @@ class ChannelCdmCall(TypedDict): class ChannelLog(LogRecord): - """One service log record, as the logs route gives it.""" + """One service log record.""" type: str @@ -466,7 +441,5 @@ class SessionInfo(TypedDict, total=False): session_id: str service: str valid: bool - expires_in: int - draining: bool track_count: int title_count: int diff --git a/unshackle/core/remote_service.py b/unshackle/core/remote_service.py index 4e1b6a9de..df048bf1b 100644 --- a/unshackle/core/remote_service.py +++ b/unshackle/core/remote_service.py @@ -74,7 +74,6 @@ from unshackle.core.remote_protocol import ( LicenseReply, LicenseRequest, LicensingMode, - Licensor, SegmentFilterReply, SegmentFilterRequest, SegmentsRequest, @@ -108,7 +107,7 @@ from unshackle.core.wire import apply_tracks_reply, build_chapters, build_music, if TYPE_CHECKING: from pywidevine.pssh import PSSH - from unshackle.core.remote_channel import Channel + from unshackle.core.remote_channel import WebSocketChannel from unshackle.core.remote_lifetime import RemoteSessionLifetime log = logging.getLogger("remote_service") @@ -312,9 +311,6 @@ class RemoteClient: self._auth_header_found = False self._session: requests.Session | None = None self.tunnel: TunnelClient | None = None - self.no_channel = False # this server or a gateway in front of it refused the remote session channel - # wraps every request, so the service's CDM calls get answered while the server runs its code - self.in_flight: Callable[[str], contextlib.AbstractContextManager[Any]] = lambda _: contextlib.nullcontext() @property def session(self) -> requests.Session: @@ -347,7 +343,6 @@ class RemoteClient: method: str, endpoint: str, data: Mapping[str, Any] | None = None, - optional: bool = False, expect: tuple[str, ...] = (), body: bytes | None = None, ) -> dict[str, Any]: @@ -407,10 +402,6 @@ class RemoteClient: ) if error_code in expect: return detail - # an older server without the route answers aiohttp's own 404, which names no error code - if optional and resp.status_code == 404 and "error_code" not in detail: - log.debug(f"Optional endpoint {endpoint} is not on this server: {error_msg}") - return {} if self.tunnel and self.tunnel.lost: raise RemoteError( "The tunnel to the server closed", @@ -422,17 +413,16 @@ class RemoteClient: def send( self, method: str, endpoint: str, timeout: float, background: bool = False, **kwargs: Any ) -> requests.Response: - """Send one request through the ``in_flight`` hook and return the response; ``requests`` raises its own errors. + """Send one request and return the response; ``requests`` raises its own errors. A 401 moves the API key to the next candidate header, a gateway's error page goes once more, and a 429 with - Retry-After waits on the console. A ``background`` call skips the hook and the 429 wait. + Retry-After waits on the console. A ``background`` call skips the 429 wait. """ url = f"{self.server_url}{endpoint}" gateway_retried = False rate_waits = 0 while True: - with contextlib.nullcontext() if background else self.in_flight(endpoint): - resp = getattr(self.session, method)(url, timeout=timeout, **kwargs) + resp = getattr(self.session, method)(url, timeout=timeout, **kwargs) # servers differ on which header carries the key, so retry the rest before giving up if resp.status_code == 401 and self.next_auth_header(): continue @@ -478,17 +468,9 @@ class RemoteClient: def post(self, endpoint: str, data: Mapping[str, Any], expect: tuple[str, ...] = ()) -> dict[str, Any]: return self.request("post", endpoint, data, expect=expect) - def post_optional(self, endpoint: str, data: Mapping[str, Any]) -> dict[str, Any]: - """POST to an endpoint that an older server may not have. Empty dict when the route is missing.""" - return self.request("post", endpoint, data, optional=True) - def get(self, endpoint: str) -> dict[str, Any]: return self.request("get", endpoint) - def get_optional(self, endpoint: str) -> dict[str, Any]: - """GET an endpoint that an older server may not have. Empty dict when the route is missing.""" - return self.request("get", endpoint, optional=True) - def sample_batches(samples: list[bytes]) -> Iterator[list[bytes]]: """Split samples into consecutive batches of at most cbcs.SAMPLE_BATCH_BYTES (a larger sample goes alone).""" @@ -948,7 +930,7 @@ class RemoteService(TitleSource): server_cdm_type: str = "widevine" lifetime: RemoteSessionLifetime licensing: LicensingMode | None = None - """The server's answer to who licenses this remote session; an older server gives it in the tracks reply.""" + """The server's answer to who licenses this remote session.""" _server_cdm_request: bool | None = None """This client's own server CDM choice; None leaves it to the server.""" _fairplay_bridge = False @@ -1064,7 +1046,7 @@ class RemoteService(TitleSource): return self.lifetime.session_id @property - def channel(self) -> Channel | None: + def channel(self) -> WebSocketChannel | None: return self.lifetime.channel def search(self) -> Iterator[SearchResult]: @@ -1230,7 +1212,6 @@ class RemoteService(TitleSource): create_data["cdm_type"] = cdm_system(cdm) or "widevine" if isinstance(level := getattr(cdm, "security_level", None), int): create_data["cdm_security_level"] = level - create_data["cdm_relay"] = True if isinstance(system_id := getattr(cdm, "system_id", None), int): create_data["cdm_system_id"] = system_id if device_type := getattr(getattr(cdm, "device_type", None), "name", None): @@ -1256,13 +1237,11 @@ class RemoteService(TitleSource): create_data["session_id"] = self.lifetime.name() result = cast(SessionCreated, self.client.post(SESSION_CREATE_ROUTE, create_data)) - if not isinstance(result.get("session_id"), str): - raise RemoteError("The remote server sent malformed session: no session_id", ClientErrorKind.UNKNOWN) - self.lifetime.adopt(create_data["session_id"], result["session_id"]) - # an older server omits the field, and the tracks response settles it - if "server_cdm" in result: - answer = LicensingMode.from_created(result) - self.adopt_session_cdm(replace(answer, server_vault=False) if cdm_only else answer, expected) + if result.get("session_id") != create_data["session_id"]: + raise RemoteError("The remote server sent malformed session: another session_id", ClientErrorKind.UNKNOWN) + self.lifetime.adopt(create_data["session_id"]) + answer = LicensingMode.from_created(result) + self.adopt_session_cdm(replace(answer, server_vault=False) if cdm_only else answer, expected) lent = bool(self.licensing and self.licensing.server_device) if cdm_only and lent: raise click.ClickException( @@ -1279,13 +1258,9 @@ class RemoteService(TitleSource): from unshackle.core.remote_channel import open_channel - channel = self.lifetime.channel = open_channel(self) - channel.keep_alive() + channel = open_channel(self) if result.get("status", AuthStatus.AUTHENTICATED) == AuthStatus.AUTHENTICATING: channel.wait_auth() - if create_data.get("cdm_relay"): - self.client.in_flight = channel.in_flight - self.drain_server_logs() @property def local_cdm(self) -> Any: @@ -1476,27 +1451,17 @@ class RemoteService(TitleSource): ) def server_draining(self) -> bool: - """Whether the server announced a restart; asked once per title, as an episode can be shorter than the keepalive.""" - return bool(self._session_id and self.channel and self.channel.draining()) + """Whether the server announced a restart; asked once per title.""" + return bool(self._session_id and self.channel and self.channel.draining_now) def server_track_id(self, track_id: Any) -> str: """The id the current remote session knows the track with this client id by.""" return self._track_alias.get(str(track_id), str(track_id)) - def drain_server_logs(self) -> None: - """Show the service's server-side log records that the remote session channel has not brought already.""" - if self.channel: - self.channel.drain_logs() - def get_titles(self) -> Titles_T: if self._titles is not None: return self._titles - try: - result = cast( - TitlesReply, self.session_call(lambda sid: self.client.get(TITLES_ROUTE.format(session_id=sid))) - ) - finally: - self.drain_server_logs() + result = cast(TitlesReply, self.session_call(lambda sid: self.client.get(TITLES_ROUTE.format(session_id=sid)))) with malformed_answer("titles"): titles_list = [build_title(t, self.service_tag, self.title_id) for t in result.get("titles") or []] first = titles_list[0] if titles_list else None @@ -1525,28 +1490,15 @@ class RemoteService(TitleSource): self._current_title = title if title_id in self._tracks_by_title: return self._tracks_by_title[title_id] - try: - result = self.session_call( - lambda sid: self.client.post( - TRACKS_ROUTE.format(session_id=sid), - TracksRequest(title_id=self._title_alias.get(title_id, title_id)), - ) + result = self.session_call( + lambda sid: self.client.post( + TRACKS_ROUTE.format(session_id=sid), + TracksRequest(title_id=self._title_alias.get(title_id, title_id)), ) - finally: - self.drain_server_logs() + ) with malformed_answer("tracks"): tracks = apply_tracks_reply(result, title, self.session) session_fields = cast(TracksReply, result) - server_cdm = bool(session_fields.get("server_cdm", False)) - if self.licensing is None: - request = self._server_cdm_request - if request and not server_cdm: - self.report_local_fallback() - server_cdm = server_cdm and request is not False - self.licensing = LicensingMode(Licensor.SERVER_CDM if server_cdm else Licensor.CLIENT_DEVICE) - elif self.licensing.server_cdm and not server_cdm: - self.licensing = replace(self.licensing, licensor=Licensor.CLIENT_DEVICE) - self.report_local_fallback() self.server_cdm_type = session_fields.get("server_cdm_type", "widevine") self._sample_decrypt_tracks.update(session_fields.get("sample_decrypt_tracks") or []) self._fairplay_bridge = bool(session_fields.get("fairplay_bridge")) @@ -1592,7 +1544,6 @@ class RemoteService(TitleSource): """The server's ``OnSegmentFilter`` result for one HLS track, fetched on first use. The service keeps its filter; the client gets only the segment URIs to skip. - A server without the route returns nothing, so the client keeps every segment. """ def segment_filter(segment: Any) -> bool: @@ -1603,7 +1554,7 @@ class RemoteService(TitleSource): result = cast( SegmentFilterReply, self.track_call( - lambda sid: self.client.post_optional( + lambda sid: self.client.post( SEGMENT_FILTER_ROUTE.format(session_id=sid), SegmentFilterRequest(track_id=self.server_track_id(track_id)), ) @@ -1659,7 +1610,6 @@ class RemoteService(TitleSource): ) ), ) - self.drain_server_logs() capped = resp.get("capped_tracks") or {} batch = key_batch(resp, title.tracks, self.server_track_id, drm_type) for entry in batch.tracks.values(): @@ -1783,7 +1733,7 @@ class RemoteService(TitleSource): try: with quiet(): self.session_call( - lambda sid: self.client.post_optional( + lambda sid: self.client.post( BAD_KEY_ROUTE.format(session_id=sid), BadKeyReport(kid=kid.hex, key=key) ) ) @@ -1949,8 +1899,6 @@ class RemoteService(TitleSource): ) except RemoteError as e: raise coded(click.ClickException(e.message), APIErrorCode.DRM_ERROR) from None - finally: - self.drain_server_logs() if not (key := (resp.get("file_keys") or {}).get(self.server_track_id(track.id))): raise coded( click.ClickException(f"The server sent no content key for track {track.id}"), APIErrorCode.DRM_ERROR @@ -1969,8 +1917,6 @@ class RemoteService(TitleSource): ) except RemoteError as e: raise click.ClickException(e.message) from None - finally: - self.drain_server_logs() if not (url := ((resp.get("tracks") or {}).get(self.server_track_id(track.id)) or {}).get("url")): raise click.ClickException(f"The server sent no URL for track {track.id}") return str(url) @@ -2001,8 +1947,6 @@ class RemoteService(TitleSource): ) except RemoteError as e: raise click.ClickException(e.message) from None - finally: - self.drain_server_logs() try: return base64.b64decode(resp["license"]) except (KeyError, TypeError, ValueError):