From efc6aef6b423daedda04b59eeda7ddebd743f386 Mon Sep 17 00:00:00 2001 From: debeski Date: Fri, 27 Nov 2026 13:26:44 +0200 Subject: [PATCH 1/2] security: harden callback delivery, link approval and the scan lifecycle Break-it round 2 fixes for ScanLink 0.8.1: - R2-010: callbacks go to public https websites only; the connected address is checked after resolving (DNS rebinding), never loopback, private, link-local/metadata or this computer; deliveries carry X-ScanLink-Delivery and every endpoint refuses them. - R2-054: a linked site whose list gains a site asks the operator again. - R2-055: callback answers are never read; 120 s whole-delivery deadline; at most two callbacks in flight. - R2-056: per-domain cooldowns after decline or no answer, an interval between unknown websites' windows, known websites pre-empt; no focus grab. - R2-115 (ScanLink half): the approval window lists every site in full; origins with invisible/bidi characters or a trailing dot are refused, non-ASCII hosts are stored as IDNA. - R2-118..R2-125: final page_count, orphaned child cleanup (job object, parent watch, temp sweep), HEAD and one retry keep the result, monotonic TTLs, doc_id validation and %r logging, strict JSON, mid-acquisition deadline stays a timeout, whole-request deadline and connection cap. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 16 ++ build_exe.py | 1 + callback_transport.py | 351 +++++++++++++++++++++++++++++++ docs/api.md | 55 +++-- docs/architecture.md | 51 ++++- docs/developer-guide.md | 14 +- gui/dialogs.py | 91 ++++++-- main.py | 4 +- scan_runtime.py | 72 ++++++- scanner.py | 3 + server.py | 129 +++++++++++- sites.py | 160 +++++++++++--- tests/test_callback_transport.py | 246 ++++++++++++++++++++++ tests/test_callbacks.py | 78 +++++-- tests/test_round2_regressions.py | 350 ++++++++++++++++++++++++++++++ tests/test_site_links.py | 98 ++++++++- tests/test_stress_regressions.py | 7 +- tests/test_worker.py | 7 +- utils.py | 24 ++- worker.py | 325 ++++++++++++++++++++++------ 20 files changed, 1895 insertions(+), 187 deletions(-) create mode 100644 callback_transport.py create mode 100644 tests/test_callback_transport.py create mode 100644 tests/test_round2_regressions.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 9dd4210..879825f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,22 @@ This file owns the release history for `ScanLink`. +## Unreleased + +- **Callbacks Reach Public HTTPS Websites Only (security, R2-010)**: a linked website could list `http://127.0.0.1:…`, `localhost`, private, link-local or metadata addresses, or ScanLink itself, and every scan was then posted there from the operator's computer without `Origin` or `Sec-Fetch-*`; a callback to `http://localhost:5000/shutdown` stopped ScanLink. New `callback_transport` module: `check_callback_url` requires `https` and refuses `localhost`, `*.localhost` and non-public address literals in any spelling (`127.1`, `2130706433`, `[::ffff:127.0.0.1]`) at submission (`400 callback_not_allowed`); `post_scan` resolves the host itself, refuses the delivery if any address is loopback, private, CGNAT, link-local, unique-local, multicast, reserved, unspecified, an embedded IPv4 of those (mapped, NAT64, 6to4, Teredo) or one of this computer's own, connects to the checked address with TLS verified for the host name and re-checks the peer, so DNS rebinding cannot reach this computer (`callback.state: refused`, `reason: blocked_address`). Deliveries carry `X-ScanLink-Delivery`, and every endpoint answers such a request with `403 local_only`. Callbacks use the standard library instead of `requests` and never a proxy. +- **Widening A Linked List Asks Again (security, R2-054)**: `SiteRegistry.link` replaced a linked website's list without a window, so one approval let XSS on that site grant the scanner to any origin. A list that gains a site now opens the approval window again, naming the added sites (`confirm(..., added_sites=…)`); until the operator allows them the website stays linked with its approved list, and a declined widening answers `403 link_declined`. Shortening a list stays silent. +- **Bounded Callback Responses (R2-055)**: the callback answer was read in full with a per-read timeout, so a 1 GB body or a gzip bomb was buffered and a body dripping a byte every 20 s held a thread and the PDF forever. `post_scan` sends `Accept-Encoding: identity`, reads only the status line and headers, and a watchdog closes the connection 120 s (`DELIVERY_DEADLINE_SECONDS`) after the delivery started; at most two callbacks are in flight (`MAX_CALLBACKS_IN_FLIGHT`), a third is `failed` with `reason: busy`. +- **Rationed Approval Windows (security, R2-056)**: any website could reopen ScanLink's approval window at once from a sibling subdomain or another port, or forever after leaving it unanswered. Cooldowns now apply to the registrable domain (`sites.cooldown_key`): 10 minutes after **Don't allow** (`403 link_declined`), 5 minutes after an unanswered window (`429 link_rate_limited`). After an unknown website's window closes without **Allow**, other unknown websites wait 2 minutes (`429 link_rate_limited`). A website ScanLink already knows is exempt from that wait and closes an unknown website's open window to ask its own (that request answers `409 link_pending`). The window no longer takes keyboard focus or a grab. +- **Approval Window Shows Every Site In Full (security, R2-115)**: the other-sites list showed 6 rows of 56 characters, so long or numerous sites were approved unseen, and hosts with bidi overrides, zero-width characters or look-alike letters were shown verbatim. `gui.dialogs.confirm_site_link` lists every site (up to 20 rows, as wide as the longest, with scrollbars beyond that) and `utils.normalize_origin` refuses hosts with control, format or separator characters or a trailing dot and stores non-ASCII hosts in their `xn--` form, as browsers send them. +- **Correct Page Count (R2-118)**: the parent polled `state.json` every 250 ms and the child's final `completed` state had no `page_count`, so 5-page scans reported 1 or 2. `scan_runtime.run_scan_job` writes `page_count` into the final state and `ScanWorker._run_scan_subprocess` applies the final state after the child exits. +- **No Orphaned Scans (R2-119)**: killing ScanLink mid-scan left the child scanning, holding the scanner, and its `scanlink-job-*` folder with the PDF in `%TEMP%`. On Windows each child joins a kill-on-close job object; `request.json` carries `parent_pid` and the child (`scan_runtime.watch_parent`) removes its folder and exits when that process ends; `worker.sweep_stale_directories` removes `scanlink-job-*`/`scanlink-pages-*` folders older than 30 s at worker start and every 10 minutes while idle. +- **HEAD And Cut-Off Downloads Keep The Result (R2-120)**: `HEAD /scan//result` ran the download view and spent the single-use PDF, and a dropped download lost the scan. `HEAD` now answers from `ScanWorker.peek_result` without counting; `consume_result` answers one retry within 30 s of the first download (`RESULT_RETRY_GRACE_SECONDS`) before freeing the bytes. +- **Monotonic Result Lifetimes (R2-121)**: job and result TTLs used `time.time()`, so a clock jump forward deleted an unread result and one backwards kept the PDF in memory for days. `_cleanup_expired_jobs_locked` measures from `time.monotonic()` stamps; wall-clock fields remain for display. +- **Safe `doc_id` (R2-122)**: a CR/LF in `doc_id` (also through `scanlink://scan?docId=…%0a…`) forged `scanner.log` lines, and any JSON type was accepted. `worker.clean_doc_id` accepts text of at most 200 characters without control, format or line-separator characters, or a whole number; anything else is `400 invalid_doc_id` on `/scan` and `/internal/protocol/scan`. Job log lines use `%r`. +- **Standard JSON Only (R2-123)**: `{"doc_id": NaN}` was stored and every status poll echoed invalid JSON. The app's `StrictJSONProvider` rejects `NaN`, `Infinity` and `-Infinity` as `400 invalid_json`. +- **Mid-Acquisition Deadline Is A Timeout (R2-124)**: a scan deadline reached while pages were still arriving was re-wrapped as `acquire_failed`/`failed`. `ScannerManager.scan_to_pdf` re-raises `ScanError` unchanged, so it stays `acquire_timeout`/`timed_out`. +- **Whole-Request Deadline And Connection Cap (R2-125)**: the 30 s socket timeout restarted on every byte, so a client sending one byte every 20 s held its thread for good and about 200 such sockets filled the listen queue. `LoopbackRequestHandler` reads through a deadline reader: line, headers and body must arrive within 30 s (`REQUEST_DEADLINE_SECONDS`), and the TLS handshake within the same time; `BoundedThreadedWSGIServer` serves at most 64 connections (`MAX_CONCURRENT_CONNECTIONS`) and closes the rest at accept. + ## v0.8.1b1 - **Callbacks Delivered, To Linked Websites Only (security)**: a finished scan was never posted to its `callback_url`. Since 2026-04-28, `_process_job` passed `_send_callback` the public job snapshot, which carries no URL. `ScanWorker._start_callback` now posts the stored PDF on its own thread (connect 5 s, read 30 s, redirects not followed, only 2xx counts). `SiteRegistry.allows_callback` limits the destination to an allowed website: a browser request may name only its own website or the sites linked with it, and a local tool or `scanlink://` link may name any linked or listed website. The check runs at submission (`400 callback_not_allowed` on `/scan` and `/internal/protocol/scan`; a refused `scanlink://` launch never scans) and again before sending. Each job reports `callback.state` (`waiting`, `sending`, `delivered`, `failed`, `refused`, `not_sent`), and the PDF stays available to poll either way. Without the rule, delivery would have let any page post a scanned document to a host of its choosing through a `scanlink://` link. diff --git a/build_exe.py b/build_exe.py index 887fae2..11e5dbb 100644 --- a/build_exe.py +++ b/build_exe.py @@ -173,6 +173,7 @@ def build_pyinstaller_args(build_name): "--hidden-import=PIL.ImageDraw", "--hidden-import=protocol_handler", "--hidden-import=sites", + "--hidden-import=callback_transport", "--hidden-import=flask", "--hidden-import=werkzeug", "--hidden-import=jinja2", diff --git a/callback_transport.py b/callback_transport.py new file mode 100644 index 0000000..a93c6fb --- /dev/null +++ b/callback_transport.py @@ -0,0 +1,351 @@ +"""Posting a finished scan to a callback URL on the public internet only. + +A callback leaves the operator's computer with a scanned document, so its +destination is checked twice: the URL itself when the scan is requested +(``check_callback_url``), and the address ScanLink actually connects to when it +sends (``post_scan``). The second check resolves the host name itself, refuses +the delivery if any address it resolves to is not a public one, and connects to +the checked address, so a host name re-pointed between the check and the +connection (DNS rebinding) cannot reach this computer or its network. + +Refused destinations: anything but ``https``; ``localhost`` and ``*.localhost``; +loopback, private, carrier-grade NAT, link-local (cloud metadata), unique-local, +multicast, reserved, unspecified and documentation addresses, including IPv4 +addresses embedded in IPv6 (mapped, NAT64, 6to4, Teredo); and every address of +this computer itself. +""" + +import http.client +import ipaddress +import socket +import ssl +import threading +import time +import unicodedata +import uuid +from urllib.parse import urlsplit + +try: + import certifi +except ImportError: + certifi = None + +CONNECT_TIMEOUT_SECONDS = 5 +READ_TIMEOUT_SECONDS = 30 +# Whole delivery, from resolving the host to reading the status line and headers. +DELIVERY_DEADLINE_SECONDS = 120 +DELIVERY_HEADER = "X-ScanLink-Delivery" + +_NAT64 = ipaddress.ip_network("64:ff9b::/96") +_LOCAL_NAT64 = ipaddress.ip_network("64:ff9b:1::/48") + + +class CallbackRefused(Exception): + """The destination is not a public https website.""" + + def __init__(self, reason, detail=""): + super().__init__(detail or reason) + self.reason = reason + + +class CallbackFailed(Exception): + """The destination could not be reached or did not answer in time.""" + + +def _embedded_ipv4(address): + if address.version != 6: + return None + if address.ipv4_mapped is not None: + return address.ipv4_mapped + if address in _NAT64 or address in _LOCAL_NAT64: + return ipaddress.IPv4Address(int(address) & 0xFFFFFFFF) + if address.sixtofour is not None: + return address.sixtofour + if address.teredo is not None: + return address.teredo[1] + # IPv4-compatible ::a.b.c.d (deprecated, still routed by some stacks). + if int(address) >> 32 == 0 and int(address) > 1: + return ipaddress.IPv4Address(int(address)) + return None + + +def is_public_address(value): + """True only for a globally routable unicast address.""" + try: + address = ipaddress.ip_address(value.split("%", 1)[0] if isinstance(value, str) else value) + except ValueError: + return False + embedded = _embedded_ipv4(address) + if embedded is not None and not is_public_address(embedded): + return False + return bool( + address.is_global + and not address.is_multicast + and not address.is_reserved + and not address.is_loopback + and not address.is_link_local + and not address.is_unspecified + and not address.is_private + ) + + +def _literal_address(host): + """The address a host spelled as a number means, in any notation the resolver accepts.""" + try: + return ipaddress.ip_address(host.strip("[]")) + except ValueError: + pass + try: + # Shorthand, decimal, octal and hex spellings such as 127.1 or 0x7f000001. + return ipaddress.IPv4Address(socket.inet_aton(host)) + except (OSError, ValueError): + return None + + +def _clean_host(host): + if not host: + return None + host = host.rstrip(".").lower() + if not host or any(unicodedata.category(ch)[0] in "CZ" for ch in host): + return None + return host + + +def check_callback_url(url): + """``(host, port, path)`` for a callback URL ScanLink may post to; else ``CallbackRefused``. + + Host names are only checked here; their addresses are checked when sending. + """ + if not isinstance(url, str) or not url or len(url) > 2048: + raise CallbackRefused("invalid_url") + try: + parts = urlsplit(url.strip()) + port = parts.port or 443 + except ValueError as exc: + raise CallbackRefused("invalid_url") from exc + if parts.scheme != "https": + raise CallbackRefused("https_required") + if parts.username is not None or parts.password is not None: + raise CallbackRefused("invalid_url") + host = _clean_host(parts.hostname) + if host is None: + raise CallbackRefused("invalid_url") + if host == "localhost" or host.endswith(".localhost"): + raise CallbackRefused("blocked_address") + literal = _literal_address(host) + if literal is not None and not is_public_address(literal): + raise CallbackRefused("blocked_address") + path = parts.path or "/" + if parts.query: + path = f"{path}?{parts.query}" + if any(ord(ch) < 0x21 or ord(ch) == 0x7F for ch in path): + raise CallbackRefused("invalid_url") + return host, port, path + + +def _own_addresses(): + addresses = set() + for name in {socket.gethostname(), socket.getfqdn()}: + try: + for info in socket.getaddrinfo(name, None): + addresses.add(ipaddress.ip_address(info[4][0].split("%", 1)[0])) + except (OSError, ValueError): + continue + return addresses + + +def resolve_public(host, port, resolver=None, own_addresses=None): + """Every address ``host`` resolves to, refusing the host if any of them is not public.""" + resolver = resolver or socket.getaddrinfo + own_addresses = own_addresses or _own_addresses + try: + infos = resolver(host, port, type=socket.SOCK_STREAM) + except OSError as exc: + raise CallbackFailed(f"Could not resolve {host!r}: {exc}") from exc + own = own_addresses() + candidates = [] + for family, socktype, proto, _canonname, sockaddr in infos: + address = sockaddr[0] + if not is_public_address(address): + raise CallbackRefused("blocked_address", f"{host!r} resolves to {address}") + try: + if ipaddress.ip_address(address.split("%", 1)[0]) in own: + raise CallbackRefused("blocked_address", f"{host!r} resolves to this computer") + except ValueError: + raise CallbackRefused("blocked_address", f"{host!r} resolves to {address!r}") + candidates.append((family, socktype, proto, sockaddr)) + if not candidates: + raise CallbackFailed(f"{host!r} has no address") + return candidates + + +class _Watchdog: + """Closes the connection when the whole delivery runs past its deadline.""" + + def __init__(self, seconds): + self.deadline = time.monotonic() + seconds + self.expired = False + self._sock = None + self._lock = threading.Lock() + self._timer = threading.Timer(seconds, self._expire) + self._timer.daemon = True + self._timer.start() + + def remaining(self): + return self.deadline - time.monotonic() + + def watch(self, sock): + with self._lock: + self._sock = sock + if self.expired: + self._close() + + def _expire(self): + with self._lock: + self.expired = True + self._close() + + def _close(self): + if self._sock is None: + return + try: + self._sock.shutdown(socket.SHUT_RDWR) + except OSError: + pass + try: + self._sock.close() + except OSError: + pass + + def cancel(self): + self._timer.cancel() + + +def _ssl_context(): + context = ssl.create_default_context() + if certifi is not None: + try: + context.load_verify_locations(certifi.where()) + except OSError: + pass + return context + + +class _PinnedHTTPSConnection(http.client.HTTPSConnection): + """Connects only to addresses ``resolve_public`` approved; verifies TLS for the host name.""" + + def __init__(self, host, port, watchdog, resolver, own_addresses, context): + super().__init__(host, port, timeout=READ_TIMEOUT_SECONDS, context=context) + self._watchdog = watchdog + self._resolver = resolver + self._own_addresses = own_addresses + self._ssl_context = context + self.peer_address = None + + def connect(self): + candidates = resolve_public(self.host, self.port, self._resolver, self._own_addresses) + last_error = None + for family, socktype, proto, sockaddr in candidates: + remaining = self._watchdog.remaining() + if remaining <= 0: + break + sock = socket.socket(family, socktype, proto) + self._watchdog.watch(sock) + try: + sock.settimeout(min(CONNECT_TIMEOUT_SECONDS, remaining)) + sock.connect(sockaddr) + peer = sock.getpeername()[0] + if not is_public_address(peer): + raise CallbackRefused("blocked_address", f"connected to {peer}") + sock.settimeout(READ_TIMEOUT_SECONDS) + self.sock = self._ssl_context.wrap_socket(sock, server_hostname=self.host) + self._watchdog.watch(self.sock) + self.peer_address = peer + return + except CallbackRefused: + sock.close() + raise + except OSError as exc: + last_error = exc + sock.close() + raise CallbackFailed(f"Could not connect to {self.host!r}: {last_error or 'deadline reached'}") + + +def encode_multipart(fields, files): + boundary = f"scanlink-{uuid.uuid4().hex}" + chunks = [] + for name, value in fields: + chunks.append( + f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n'.encode("ascii") + + str(value).encode("utf-8") + + b"\r\n" + ) + for name, (filename, content, content_type) in files: + chunks.append( + ( + f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"; filename="{filename}"\r\n' + f"Content-Type: {content_type}\r\n\r\n" + ).encode("ascii") + + content + + b"\r\n" + ) + chunks.append(f"--{boundary}--\r\n".encode("ascii")) + return b"".join(chunks), f"multipart/form-data; boundary={boundary}" + + +def post_scan( + url, + fields, + files, + *, + delivery_id, + user_agent="ScanLink", + deadline_seconds=DELIVERY_DEADLINE_SECONDS, + resolver=None, + own_addresses=None, + context=None, +): + """POST a multipart scan to ``url``; returns the HTTP status code. + + The response body is never read, redirects are never followed, proxies are + never used, and the whole exchange ends at ``deadline_seconds``. + """ + host, port, path = check_callback_url(url) + body, content_type = encode_multipart(fields, files) + watchdog = _Watchdog(deadline_seconds) + connection = _PinnedHTTPSConnection( + host, port, watchdog, resolver, own_addresses, context or _ssl_context() + ) + try: + connection.putrequest("POST", path, skip_accept_encoding=True) + connection.putheader("Accept-Encoding", "identity") + connection.putheader("Content-Type", content_type) + connection.putheader("Content-Length", str(len(body))) + connection.putheader("User-Agent", user_agent) + connection.putheader(DELIVERY_HEADER, delivery_id) + connection.endheaders(body) + response = connection.getresponse() + return response.status + except (CallbackRefused, CallbackFailed): + raise + except (OSError, http.client.HTTPException, ValueError) as exc: + if watchdog.expired: + raise CallbackFailed(f"No answer within {deadline_seconds} seconds") from exc + raise CallbackFailed(str(exc) or exc.__class__.__name__) from exc + finally: + watchdog.cancel() + try: + connection.close() + except Exception: + pass + + +__all__ = [ + "CallbackFailed", + "CallbackRefused", + "DELIVERY_HEADER", + "check_callback_url", + "is_public_address", + "post_scan", + "resolve_public", +] diff --git a/docs/api.md b/docs/api.md index 1241942..9c923fa 100644 --- a/docs/api.md +++ b/docs/api.md @@ -80,11 +80,14 @@ Accepted aliases: - `doc_id` or `docId` - `callback_url` or `callback` -`callback_url` must point at a website the operator allowed: one linked with `POST /link`, or one listed in `cors_origins`. Its scheme, host and port must match that website exactly. +`doc_id` is optional: text of at most 200 characters without control, line-separator or invisible formatting characters (such as bidi overrides), or a whole number. JSON request bodies must be standard JSON; `NaN` and `Infinity` are refused as `invalid_json`. + +`callback_url` must be an `https` URL on a website the operator allowed: one linked with `POST /link`, or one listed in `cors_origins`. Its scheme, host and port must match that website exactly. - A request from a browser `Origin` may only name its own website or the sites linked together with it. - A local tool with no `Origin` may name any allowed website. +- The host must not be `localhost`, `*.localhost` or an address on this computer or a private network: loopback, private, carrier-grade NAT, link-local (including cloud metadata addresses), unique-local, multicast, reserved and unspecified addresses are refused, in any spelling (`127.1`, `2130706433`, `[::ffff:127.0.0.1]`). -Anything else is refused before a scan starts. The [Developer Guide](developer-guide.md#callback-url) describes how the scan is delivered. +Anything else is refused before a scan starts. When the scan is sent, ScanLink resolves the host name itself and refuses the delivery if any address it resolves to falls in those ranges or belongs to this computer (see the `refused` callback state below). The [Developer Guide](developer-guide.md#callback-url) describes how the scan is delivered. Response `202`: @@ -101,6 +104,7 @@ Errors: | --- | --- | --- | | 400 | `invalid_json` | Body could not be parsed as JSON. | | 400 | `invalid_payload` | JSON root was not an object. | +| 400 | `invalid_doc_id` | `doc_id` is not short text or a whole number, or contains control characters. | | 400 | `invalid_callback` | Callback URL was not a string or could not be parsed. | | 400 | `callback_not_allowed` | Callback URL does not point at a website this request may name (see above). | | 400 | `invalid_metadata` | `metadata` was provided but is not an object. | @@ -157,8 +161,8 @@ A job started with a callback URL also reports how the callback went, without th | `waiting` | The scan has not finished. | | `sending` | The PDF is being posted. | | `delivered` | The callback answered with a 2xx `status_code`. | -| `failed` | The callback answered with another `status_code` (redirects are not followed), or `reason` is `unreachable` or `unavailable`. | -| `refused` | `reason: not_linked`: the website was unlinked while the scanner ran, so nothing was sent. | +| `failed` | The callback answered with another `status_code` (redirects are not followed), or `reason` is `unreachable` (no connection, or no answer within two minutes) or `busy` (two other callbacks were still being sent). | +| `refused` | Nothing was sent. `reason` is `not_linked` (the website was unlinked while the scanner ran) or `blocked_address` (its host resolved to this computer or a private network address). | | `not_sent` | The scan ended without a PDF. | Terminal failure response: @@ -183,7 +187,9 @@ Errors: ## GET /scan//result -Downloads the scanned PDF for a completed job. `completed` is published only after the child has exited and the parent has stored the PDF. Concurrent downloads are single-use: exactly one receives the bytes; later requests return `410` until the job metadata expires. PDF bytes are freed immediately after retrieval, while metadata remains until `job_ttl_seconds` from completion. +Downloads the scanned PDF for a completed job. `completed` is published only after the child has exited and the parent has stored the PDF. The PDF can be downloaded twice, the second time within 30 seconds of the first, so a client whose first download was cut off can retry once (on either transport). Then its bytes are freed, and later requests return `410` until the job metadata expires `job_ttl_seconds` after completion. An unread PDF is kept for `result_ttl_seconds`. Both lifetimes are measured on a monotonic clock, so changing the computer's clock does not shorten or extend them. + +`HEAD` answers `200` with the PDF's `Content-Length`, or `410`, without counting as a download. Response: @@ -197,7 +203,7 @@ Errors: | --- | --- | --- | | 404 | `job_not_found` | Job does not exist or expired. | | 409 | `result_not_ready` | Job is not completed yet. | -| 410 | `result_unavailable` | Result was already consumed. | +| 410 | `result_unavailable` | The PDF was already downloaded twice, or its retry window has passed. | ## POST /internal/protocol/scan @@ -209,7 +215,7 @@ Internal endpoint used by `scanlink://` launches to forward commands into an alr Requests ScanLink shutdown. This is intended for local control, not browser integrations. -`/shutdown` and `/internal/protocol/scan` refuse browser requests: any request carrying an `Origin` or `Sec-Fetch-Site` header receives `403 local_only`. Local tools such as the protocol forwarder, PowerShell or `curl` send neither header. +`/shutdown` and `/internal/protocol/scan` refuse browser requests: any request carrying an `Origin` or `Sec-Fetch-Site` header receives `403 local_only`. Local tools such as the protocol forwarder, PowerShell or `curl` send neither header. Every endpoint also answers `403 local_only` to a request carrying `X-ScanLink-Delivery`, the header ScanLink's own callback deliveries send. ## Scan Error Codes @@ -220,7 +226,7 @@ Errors from the scanner/runtime layer can appear inside the job `error` object: | `twain_unavailable` | `pytwain` or TWAIN support is unavailable. | | `scanner_selection_cancelled` | User cancelled scanner selection. | | `open_source_failed` | Selected scanner could not be opened. | -| `acquire_timeout` | Scanner acquisition exceeded the scan deadline. | +| `acquire_timeout` | Scanner acquisition exceeded the scan deadline, including while pages were still arriving (status `timed_out`). | | `acquire_failed` | Scanner acquisition failed. | | `no_pages_scanned` | Scan ended without captured pages. | | `image_runtime_unavailable` | Pillow is unavailable. | @@ -281,10 +287,30 @@ Request: ``` `sites` lists the other websites the requesting site's administrator allows, at -most 19; the requesting site is always included. An unlinked website opens an -approval window in ScanLink naming it and its list, and the request waits up to -two minutes for the operator's answer. A website that is already linked replaces -its list without asking again. +most 19; the requesting site is always included. Origins are compared in their +ASCII form: a non-ASCII host name becomes its `xn--` (IDNA) form, and hosts with +invisible or bidi control characters or a trailing dot are refused as +`invalid_site`. An unlinked website opens an approval window in ScanLink naming +it and every site on its list, and the request waits up to two minutes for the +operator's answer. + +A website that is already linked may drop sites from its list without asking. A +list that gains a site opens the window again, naming the sites it adds; until +the operator allows them, the website stays linked with the list approved +before. + +Approval windows are rationed: +- A website whose window was declined cannot ask again for 10 minutes; one whose + window went unanswered, for 5 minutes. The wait applies to its whole domain + (`evil1.example.org` and `evil2.example.org:8443` share `example.org`). +- After a window for a website ScanLink does not know yet closes without + **Allow**, other unknown websites wait 2 minutes before opening one. +- A website ScanLink already knows (linked, on a linked site's list, or in + `cors_origins`) is not held up by that wait, and closes an open window of an + unknown website to ask its own question; the closed window's request answers + `409 link_pending`. +- The window shows above other windows without taking the keyboard; its default + button is **Don't allow**. Success: @@ -302,9 +328,10 @@ Errors: | --- | --- | --- | | `400` | `origin_required` | No well-formed `Origin` (local tools and `Origin: null` cannot link). | | `400` | `invalid_payload`, `invalid_sites`, `invalid_site`, `too_many_sites` | The body is not `{"sites": [origins]}` with at most 19 website origins. | -| `403` | `link_declined` | The operator chose **Don't allow**; the website cannot ask again for 10 minutes. | +| `403` | `link_declined` | The operator chose **Don't allow**; websites of this domain cannot ask again for 10 minutes. A linked website keeps its previous list. | | `408` | `link_timeout` | Nobody answered the window within two minutes. | -| `409` | `link_pending` | Another website's approval window is open. | +| `409` | `link_pending` | Another website's approval window is open, or this request's window was closed for a website ScanLink already knows. | +| `429` | `link_rate_limited` | A window for this domain went unanswered in the last 5 minutes, or one for another unknown website closed without **Allow** in the last 2 minutes. | | `409` | `too_many_links` | 50 websites are linked; unlink one first. | ## Automatic HTTPS setup status (0.7.5b1) diff --git a/docs/architecture.md b/docs/architecture.md index 74f5cd9..d40673e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -9,13 +9,15 @@ ScanLink is a Windows tray application that exposes a local browser API and isol | `main.py` | Main entry point. Handles CLI modes, initializes Tk, starts the worker, server, and tray threads. | | `server.py` | Flask app for local REST endpoints. Starts HTTP and optional HTTPS loopback listeners. | | `worker.py` | Owns scan job state, enforces one active job, launches scan subprocesses, stores results, and sends callbacks. | +| `callback_transport.py` | Checks callback destinations (public `https` only) and posts a finished scan to the address it checked, with an overall deadline. | +| `sites.py` | Websites allowed to scan: `cors_origins`, linked websites, their lists, and the rationing of approval windows. | | `scan_runtime.py` | Runs inside the child scan process. Reads job request files, calls the scanner, writes progress state and result PDF. | | `scanner.py` | TWAIN scanner manager. Lists sources, opens the selected scanner, acquires pages, and generates PDFs. | | `tray.py` | System tray icon and menu actions. Controls source, side, color mode, resolution, diagnostics, startup, scanner UI, paper protection, and quit. | | `protocol_handler.py` | Parses `scanlink://` URLs and forwards protocol launches to an existing local instance. | | `certificates.py` | Per-user localhost identity, Windows trust, DPAPI key-password protection, and renewal. | | `utils.py` | Shared logging, config, version, SSL certificate, startup, and resource helpers. | -| `gui/dialogs.py` | Tk dialogs for scanner selection and diagnostics output. | +| `gui/dialogs.py` | Tk dialogs for scanner selection, diagnostics output and website approval. | ## Non-Runtime Project Files @@ -67,6 +69,19 @@ worker.py This subprocess boundary protects the tray/API process from scanner driver crashes, stuck TWAIN calls, and long-running acquisition operations. +The child does not outlive ScanLink. On Windows, `ScanWorker` places every child +in a job object that ends it when ScanLink's own process ends (kill-on-close), +which also releases the TWAIN source. `request.json` carries `parent_pid`, and +the child watches that process: when it disappears, the child removes its job +directory and exits. When the worker starts, and every 10 minutes while it is +idle, it removes `scanlink-job-*` and `scanlink-pages-*` folders older than 30 +seconds from the temp directory, which an earlier ScanLink killed mid-scan left +with the scanned pages inside. + +The child writes `page_count` into its final `completed` state, and the parent +applies that last state after the child exits, so the reported page count does +not depend on which progress states its 250 ms polls happened to see. + `scan_runtime.run_scan_job()` only runs in a `scanlink-job-*` directory directly inside the user's temp directory, the only kind `ScanWorker` creates. Any other `--scan-worker-dir` value, such as one injected through an unescaped @@ -171,11 +186,17 @@ HTTPS: ``` Each listener is a threaded werkzeug server that serves one connection per -thread. Its `LoopbackRequestHandler` applies a 30-second socket timeout -(`REQUEST_TIMEOUT_SECONDS` in `server.py`) to every connection, and the HTTPS -listener performs the TLS handshake in that connection's thread rather than in -the accept loop, so an idle or slow client only holds its own thread until the -timeout and never blocks other clients. +thread, at most 64 at once (`MAX_CONCURRENT_CONNECTIONS` in `server.py`); a +connection beyond that is closed when it is accepted. Its +`LoopbackRequestHandler` applies a 30-second socket timeout +(`REQUEST_TIMEOUT_SECONDS`) to every connection and a 30-second deadline +(`REQUEST_DEADLINE_SECONDS`) to each request: its line, headers and body must +all arrive within 30 seconds, however slowly the bytes trickle in, and the TLS +handshake must finish within the same time. The HTTPS listener performs the +handshake in that connection's thread rather than in the accept loop, so an idle +or slow client only holds its own thread until the deadline and never blocks +other clients. Time a request spends being answered, such as `POST /link` +waiting for the operator, does not count. On normal startup the server thread starts HTTP first, then prepares a trusted HTTPS identity automatically. A one-year self-signed **server** certificate @@ -238,14 +259,22 @@ in `worker.py`) covering child startup, so a child that honours its own `scan_timeout_seconds` closes the TWAIN source and reports its error before the parent force-terminates it. +A deadline the child reaches while pages are still arriving is reported as +`acquire_timeout` with status `timed_out`, like any other scan deadline. + Once the PDF is stored, the parent posts it to the job's callback URL on a -separate thread (`ScanWorker._start_callback`). -- **Destination check:** `SiteRegistry.allows_callback` decides where it may go. `main.py` gives it to the worker as `callback_guard`, and without one every callback is refused. It runs when the job is submitted and again before sending. +separate thread (`ScanWorker._start_callback`), at most two at a time +(`MAX_CALLBACKS_IN_FLIGHT`). +- **Destination check:** `SiteRegistry.allows_callback` decides where it may go: an `https` URL on an allowed website whose host is not `localhost` or a non-public address literal (`callback_transport.check_callback_url`). `main.py` gives it to the worker as `callback_guard`, and without one every callback is refused. It runs when the job is submitted and again before sending. +- **Connection check:** `callback_transport.post_scan` resolves the host itself, refuses it if any address is not public or belongs to this computer, connects to the checked address with TLS verified for the host name, and checks the connected peer again. No proxy is used, redirects are not followed, the answer's body is never read, and a watchdog closes the connection 120 seconds after the delivery started. - **Failures:** a refused or failed callback never affects the stored PDF. -Idle timeout remains an independent progress guard. Downloading frees -the PDF immediately and retains consumed-job metadata until the normal job TTL, -so repeated or racing downloads report `410` while that metadata exists. +Idle timeout remains an independent progress guard. A PDF can be downloaded +twice, the second time within `RESULT_RETRY_GRACE_SECONDS` (30) of the first; +then its bytes are freed and the job's metadata stays until the job TTL, so +later downloads report `410` while that metadata exists. `HEAD` does not count +as a download. Job and result lifetimes run on `time.monotonic()`; the +wall-clock stamps in job snapshots are for display only. ## 0.8.0b1 release acceptance diff --git a/docs/developer-guide.md b/docs/developer-guide.md index 3f50029..bd607ca 100644 --- a/docs/developer-guide.md +++ b/docs/developer-guide.md @@ -155,11 +155,12 @@ Any web page can open a `scanlink://` link, so a link whose callback is not an a When `callback_url` is provided, ScanLink posts the completed PDF to that URL after a successful scan. -**Where a callback may go.** Only to a website the operator allowed, by linking it (`POST /link`) or listing it in `cors_origins`. The URL's scheme, host and port must match that website exactly. A URL with credentials (`https://site@other.example`) never matches. +**Where a callback may go.** Only to an `https` URL on a website the operator allowed, by linking it (`POST /link`) or listing it in `cors_origins`. The URL's scheme, host and port must match that website exactly. A URL with credentials (`https://site@other.example`) never matches. The website must be on the public internet: a callback never reaches this computer (`localhost`, loopback, ScanLink itself) or a private network (private, carrier-grade NAT, link-local and cloud metadata, unique-local addresses), whatever the allowed list says. - **Browser request:** a scan started from a page (`POST /scan` with an `Origin`) may only name its own website or the sites linked together with it. - **Local tool or `scanlink://` link:** may name any allowed website. - **Refused before scanning:** anything else gets `400 callback_not_allowed`, and the scanner never starts. - **Re-checked before sending:** if the website was unlinked while the scanner ran, nothing is sent. +- **Checked where it connects:** ScanLink resolves the host name itself when sending, refuses the delivery if any of its addresses is not a public one or belongs to this computer, and connects to the address it checked. A name re-pointed to `127.0.0.1` after the scan was requested (DNS rebinding) is refused (`refused`, `blocked_address`). **The request.** A `multipart/form-data` POST with: @@ -170,8 +171,9 @@ When `callback_url` is provided, ScanLink posts the completed PDF to that URL af - `status`: `completed` **How it is sent.** -- On its own thread, so a slow server never holds up the next scan. -- Connect timeout 5 s, read timeout 30 s. +- On its own thread, so a slow server never holds up the next scan. At most two callbacks are sent at once; a scan that finishes while two are still being sent is not sent (`failed`, `busy`). +- Directly, never through a proxy. Connect timeout 5 s, and the whole delivery, up to the answer's status line and headers, ends after 120 s however slowly the server answers. +- With `Accept-Encoding: identity` and an `X-ScanLink-Delivery: ` header. The answer's body is never read. - Redirects are not followed, so a website cannot pass the document on to another host. - Only a 2xx answer counts as delivered. - The PDF stays available to `GET /scan//result` either way. The job's `callback` field reports the outcome (see the [API Reference](api.md#get-scanjob_id)). @@ -199,12 +201,12 @@ Only one scan job can be queued or running at a time. If another request arrives ## Result Retention -Completed results are kept in memory temporarily. Defaults: +Completed results are kept in memory temporarily, measured on a monotonic clock so a change to the computer's clock does not affect them. Defaults: - Job metadata TTL: 900 seconds. -- Result PDF TTL: 300 seconds. +- Result PDF TTL: 300 seconds while it is not downloaded. -Downloading `/scan//result` consumes the stored PDF. A second download for the same job can return `410 result_unavailable`. +Downloading `/scan//result` spends the stored PDF: one retry is answered within 30 seconds of the first download, for a download that was cut off, and later downloads return `410 result_unavailable`. `HEAD` on the result does not count as a download. ## Operational Notes diff --git a/gui/dialogs.py b/gui/dialogs.py index a7cb12e..345bcc8 100644 --- a/gui/dialogs.py +++ b/gui/dialogs.py @@ -126,36 +126,87 @@ def show_text_dialog(title, body, width=760, height=520): dlg.wait_window() -def confirm_site_link(origin, other_sites, timeout_seconds): - """Ask whether ``origin`` may use the scanner: True, False, or None if unanswered.""" +# The approval window lists every site in full: a site cut off at the edge, or +# scrolled out of view, would be approved without the operator seeing it. +SITE_LIST_MAX_ROWS = 20 +SITE_LIST_MIN_WIDTH = 40 +SITE_LIST_MAX_WIDTH = 90 + + +def site_list_size(sites): + """``(rows, characters)`` for a listing that shows every site without scrolling when it fits.""" + rows = max(1, min(len(sites), SITE_LIST_MAX_ROWS)) + width = max([SITE_LIST_MIN_WIDTH, *(len(site) + 2 for site in sites)]) + return rows, min(width, SITE_LIST_MAX_WIDTH) + + +def _site_listing(parent, sites): + rows, width = site_list_size(sites) + holder = tk.Frame(parent) + listing = tk.Listbox(holder, height=rows, width=width, activestyle=tk.NONE) + for site in sites: + listing.insert(tk.END, site) + listing.grid(row=0, column=0, sticky="ew") + if max(len(site) for site in sites) + 2 > width: + scroll_x = tk.Scrollbar(holder, orient=tk.HORIZONTAL, command=listing.xview) + listing.configure(xscrollcommand=scroll_x.set) + scroll_x.grid(row=1, column=0, sticky="ew") + if len(sites) > rows: + scroll_y = tk.Scrollbar(holder, orient=tk.VERTICAL, command=listing.yview) + listing.configure(yscrollcommand=scroll_y.set) + scroll_y.grid(row=0, column=1, sticky="ns") + holder.columnconfigure(0, weight=1) + holder.pack(anchor=tk.W, fill=tk.X) + return listing + + +def confirm_site_link(origin, other_sites, timeout_seconds, added_sites=None, cancel=None): + """Ask whether ``origin`` may use the scanner: True, False, or None if unanswered. + + ``added_sites`` names what an already linked website's list gains; ``cancel`` + (a ``threading.Event``) closes the window unanswered when set. + """ if not _root: logging.error("GUI not initialized with root window") return None answer = {"value": None} dlg = tk.Toplevel() - dlg.title("Allow a website to use ScanLink?") + widening = bool(added_sites) + dlg.title("Allow more websites to use ScanLink?" if widening else "Allow a website to use ScanLink?") dlg.resizable(False, False) frame = tk.Frame(dlg, padx=16, pady=14) frame.pack(fill=tk.BOTH, expand=True) - tk.Label(frame, text=origin, font=("TkDefaultFont", 11, "bold"), wraplength=440, justify=tk.LEFT).pack(anchor=tk.W) - tk.Label(frame, text="wants to use the scanner on this computer.", wraplength=440, justify=tk.LEFT).pack(anchor=tk.W) - if other_sites: + tk.Label(frame, text=origin, font=("TkDefaultFont", 11, "bold"), wraplength=560, justify=tk.LEFT).pack(anchor=tk.W) + if widening: + tk.Label( + frame, + text="is already linked, and now asks to let these websites use the scanner on this computer too:", + wraplength=560, + justify=tk.LEFT, + ).pack(anchor=tk.W) + _site_listing(frame, list(added_sites)) tk.Label( frame, - text="Its administrator also allows these websites:", - wraplength=440, + text="If you choose Don't allow, it stays linked with the websites you allowed before.", + wraplength=560, justify=tk.LEFT, ).pack(anchor=tk.W, pady=(10, 0)) - listing = tk.Listbox(frame, height=min(len(other_sites), 6), width=56) - for site in other_sites: - listing.insert(tk.END, site) - listing.pack(anchor=tk.W, fill=tk.X) + else: + tk.Label(frame, text="wants to use the scanner on this computer.", wraplength=560, justify=tk.LEFT).pack(anchor=tk.W) + if other_sites: + tk.Label( + frame, + text=f"Its administrator also allows these {len(other_sites)} websites:", + wraplength=560, + justify=tk.LEFT, + ).pack(anchor=tk.W, pady=(10, 0)) + _site_listing(frame, list(other_sites)) tk.Label( frame, - text="Only allow a website you use for your work. You can unlink it later from the ScanLink tray menu.", - wraplength=440, + text="Only allow websites you use for your work. You can unlink a website later from the ScanLink tray menu.", + wraplength=560, justify=tk.LEFT, ).pack(anchor=tk.W, pady=(10, 0)) @@ -164,6 +215,12 @@ def finish(value): if dlg.winfo_exists(): dlg.destroy() + def watch_cancel(): + if cancel is not None and cancel.is_set(): + finish(None) + elif dlg.winfo_exists(): + dlg.after(200, watch_cancel) + buttons = tk.Frame(frame) buttons.pack(pady=(14, 0)) tk.Button(buttons, text="Allow", command=lambda: finish(True), width=12).pack(side=tk.LEFT, padx=8) @@ -172,6 +229,8 @@ def finish(value): dlg.protocol("WM_DELETE_WINDOW", lambda: finish(False)) dlg.bind("", lambda event: finish(False)) dlg.after(int(timeout_seconds * 1000), lambda: finish(None)) + if cancel is not None: + dlg.after(200, watch_cancel) dlg.update_idletasks() width, height = dlg.winfo_reqwidth(), dlg.winfo_reqheight() @@ -180,10 +239,10 @@ def finish(value): dlg.geometry(f"+{x}+{y}") dlg.deiconify() dlg.wait_visibility() + # Shown above other windows, but without taking the keyboard from what the + # operator is typing in; "Don't allow" is the default once it is clicked. dlg.attributes("-topmost", True) dlg.lift() - dlg.focus_force() deny.focus_set() - dlg.grab_set() dlg.wait_window() return answer["value"] diff --git a/main.py b/main.py index 1e9eaf2..240defe 100644 --- a/main.py +++ b/main.py @@ -88,11 +88,11 @@ def show_setup_message(): set_status_callback(None) - def confirm_link(origin, other_sites): + def confirm_link(origin, other_sites, added_sites=None, cancel=None): from gui.dialogs import confirm_site_link return worker.run_gui_task( - lambda: confirm_site_link(origin, other_sites, LINK_PROMPT_SECONDS), + lambda: confirm_site_link(origin, other_sites, LINK_PROMPT_SECONDS, added_sites, cancel), timeout=LINK_PROMPT_SECONDS + 15, ) diff --git a/scan_runtime.py b/scan_runtime.py index fd090ae..520eb2a 100644 --- a/scan_runtime.py +++ b/scan_runtime.py @@ -1,7 +1,9 @@ import json import os +import shutil import sys import tempfile +import threading import time import tkinter as tk @@ -44,6 +46,69 @@ def _write_result(work_dir, pdf_buffer): result_file.write(pdf_buffer.getvalue()) +def _parent_alive_check(parent_pid): + """A function telling whether ``parent_pid`` still runs, or None when it cannot be watched.""" + if not isinstance(parent_pid, int) or parent_pid <= 0 or parent_pid == os.getpid(): + return None + if os.name == "nt": + try: + import ctypes + from ctypes import wintypes + + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.OpenProcess.restype = wintypes.HANDLE + kernel32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD) + kernel32.WaitForSingleObject.argtypes = (wintypes.HANDLE, wintypes.DWORD) + # Opened once, now: a handle keeps naming this process even if its id is reused. + handle = kernel32.OpenProcess(0x00100000, False, parent_pid) # SYNCHRONIZE + except Exception: + return None + if not handle: + return lambda: False + return lambda: kernel32.WaitForSingleObject(handle, 0) != 0 # WAIT_OBJECT_0: ended + + direct_child = os.getppid() == parent_pid + + def alive(): + # A direct child is re-parented when its parent ends, even while the + # parent is still an unreaped zombie. + if direct_child and os.getppid() != parent_pid: + return False + try: + os.kill(parent_pid, 0) + except ProcessLookupError: + return False + except OSError: + return True + return True + + return alive + + +def watch_parent(parent_pid, on_gone, interval=1.0): + """Call ``on_gone`` from a daemon thread once ``parent_pid`` has ended; returns the thread.""" + alive = _parent_alive_check(parent_pid) + if alive is None: + return None + + def loop(): + while alive(): + time.sleep(interval) + on_gone() + + thread = threading.Thread(target=loop, daemon=True, name="ScanLinkParentWatch") + thread.start() + return thread + + +def _abandon(work_dir): + # ScanLink itself is gone: nobody will collect this scan, so drop it and + # end the process, which also releases the scanner. + logger.warning("ScanLink ended during a scan; the scan child stops and removes %r", work_dir) + shutil.rmtree(work_dir, ignore_errors=True) + os._exit(4) + + def is_job_directory(work_dir): """True only for a directory ScanWorker created with tempfile.mkdtemp().""" path = os.path.abspath(work_dir) @@ -66,6 +131,7 @@ def run_scan_job(work_dir): request = _read_request(work_dir) job_id = request.get("job_id") or "scan-job" timeout_seconds = int(request.get("scan_timeout_seconds") or 0) + watch_parent(request.get("parent_pid"), lambda: _abandon(work_dir)) root = tk.Tk() root.withdraw() @@ -78,7 +144,11 @@ def run_scan_job(work_dir): if timeout_seconds > 0: deadline = time.monotonic() + timeout_seconds + pages = {"count": 0} + def on_progress(status, **data): + if isinstance(data.get("page_count"), int): + pages["count"] = data["page_count"] _write_state(work_dir, status, **data) _write_state(work_dir, "processing") @@ -89,7 +159,7 @@ def on_progress(status, **data): ) _write_result(work_dir, pdf_buffer) pdf_buffer.close() - _write_state(work_dir, "completed") + _write_state(work_dir, "completed", page_count=pages["count"]) return 0 except ScanError as exc: _write_state( diff --git a/scanner.py b/scanner.py index f224f6b..e304e7d 100644 --- a/scanner.py +++ b/scanner.py @@ -212,6 +212,9 @@ def scan_to_pdf(self, request_id, progress_callback=None, deadline=None): deadline, show_ui=show_scanner_ui, ) + except ScanError: + # A deadline reached mid-acquisition stays a timeout, not acquire_failed. + raise except Exception as exc: exc_name = exc.__class__.__name__ if exc_name == "DSTransferCancelled": diff --git a/server.py b/server.py index 7d48cf2..2aec76c 100644 --- a/server.py +++ b/server.py @@ -1,4 +1,5 @@ import io +import json import socket import ssl import threading @@ -6,8 +7,9 @@ from urllib.parse import urlparse, urlsplit from flask import Flask, Response, jsonify, request, send_file +from flask.json.provider import DefaultJSONProvider from werkzeug.exceptions import HTTPException -from werkzeug.serving import WSGIRequestHandler, make_server +from werkzeug.serving import ThreadedWSGIServer, WSGIRequestHandler from utils import ( APP_ARCH, @@ -21,8 +23,9 @@ load_config, normalize_origin, ) +from callback_transport import DELIVERY_HEADER from sites import LinkError, SiteRegistry -from worker import BusyError, CallbackNotAllowedError +from worker import BusyError, CallbackNotAllowedError, InvalidDocIdError logger = get_logger() @@ -33,6 +36,23 @@ MAX_REQUEST_BYTES = 64 * 1024 # Per-connection socket timeout, including the TLS handshake. REQUEST_TIMEOUT_SECONDS = 30 +# A request's line, headers and body must all arrive within this many seconds +# of the connection asking for it, however slowly the bytes trickle in. +REQUEST_DEADLINE_SECONDS = 30 +# Connections served at once per listener; further ones are closed at accept. +MAX_CONCURRENT_CONNECTIONS = 64 + + +def _reject_constant(name): + raise ValueError(f"{name} is not valid JSON") + + +class StrictJSONProvider(DefaultJSONProvider): + """Standard JSON only: ``NaN`` and ``Infinity`` would be echoed back as invalid JSON.""" + + def loads(self, s, **kwargs): + kwargs.setdefault("parse_constant", _reject_constant) + return json.loads(s, **kwargs) def is_loopback_host(host): @@ -44,6 +64,7 @@ def is_loopback_host(host): def create_app(worker, shutdown_event, transport_state, sites=None): app = Flask(__name__) + app.json = StrictJSONProvider(app) app.config["MAX_CONTENT_LENGTH"] = MAX_REQUEST_BYTES if sites is None: config = load_config() @@ -125,6 +146,12 @@ def reject_foreign_host(): return error_response( 403, "invalid_host", "ScanLink only answers requests addressed to localhost." ) + # ScanLink's own callback deliveries never reach public hosts only, but + # if one ever arrived here it must not act on this computer. + if DELIVERY_HEADER in request.headers: + return error_response( + 403, "local_only", "ScanLink does not accept its own scan deliveries." + ) origin = request.headers.get("Origin") if is_browser_endpoint(request.path): gated = request.method != "OPTIONS" and request.path != "/link" @@ -208,7 +235,9 @@ def start_scan(): if error is not None: return error - doc_id = data.get("doc_id") or data.get("docId") + doc_id = data.get("doc_id") + if doc_id is None: + doc_id = data.get("docId") callback_url = data.get("callback_url") or data.get("callback") try: @@ -219,6 +248,8 @@ def start_scan(): source="api", origin=request.headers.get("Origin"), ) + except InvalidDocIdError as exc: + return error_response(400, "invalid_doc_id", str(exc)) except CallbackNotAllowedError as exc: return error_response(400, "callback_not_allowed", str(exc)) except BusyError as exc: @@ -244,7 +275,7 @@ def get_scan_status(job_id): ) return jsonify(job) - @app.route("/scan//result", methods=["GET", "OPTIONS"]) + @app.route("/scan//result", methods=["GET", "HEAD", "OPTIONS"]) def get_scan_result(job_id): if request.method == "OPTIONS": return empty_options_response() @@ -263,6 +294,18 @@ def get_scan_result(job_id): current_status=job["status"], ) + if request.method == "HEAD": + # Asking about the result must not spend the download. + _job, size = worker.peek_result(job_id, origin=origin) + if not size: + return error_response( + 410, "result_unavailable", "The scan result is no longer available." + ) + response = Response(status=200, mimetype="application/pdf") + response.headers["Content-Length"] = str(size) + response.headers["Content-Disposition"] = f"attachment; filename=scan_{job_id}.pdf" + return response + updated_job, result_bytes = worker.consume_result(job_id, origin=origin) if not updated_job: return error_response( @@ -307,6 +350,8 @@ def internal_protocol_scan(): metadata=data.get("metadata"), source="protocol", ) + except InvalidDocIdError as exc: + return error_response(400, "invalid_doc_id", str(exc)) except CallbackNotAllowedError as exc: return error_response(400, "callback_not_allowed", str(exc)) except BusyError as exc: @@ -340,22 +385,91 @@ def emit_scan_status(job_id, status, **kwargs): return None +class _DeadlineReader(io.RawIOBase): + """Socket reads that end at the handler's request deadline, not per byte.""" + + def __init__(self, handler): + super().__init__() + self._handler = handler + + def readable(self): + return True + + def readinto(self, buffer): + remaining = self._handler.read_deadline - time.monotonic() + if remaining <= 0: + raise TimeoutError("The request was not received in time.") + connection = self._handler.connection + connection.settimeout(min(REQUEST_TIMEOUT_SECONDS, remaining)) + try: + return connection.recv_into(buffer) + finally: + connection.settimeout(REQUEST_TIMEOUT_SECONDS) + + class LoopbackRequestHandler(WSGIRequestHandler): def setup(self): self.timeout = REQUEST_TIMEOUT_SECONDS + self.read_deadline = time.monotonic() + REQUEST_DEADLINE_SECONDS super().setup() + self.rfile = io.BufferedReader(_DeadlineReader(self)) + + def handle_one_request(self): + # Waiting for the next request on a kept-alive connection counts too. + self.read_deadline = time.monotonic() + REQUEST_DEADLINE_SECONDS + try: + return super().handle_one_request() + except TimeoutError: + self.close_connection = True def handle(self): # The listener accepts without handshaking, so a client that never sends - # a TLS hello only holds its own thread, and only until the timeout. + # a TLS hello only holds its own thread, and only until the deadline. if isinstance(self.connection, ssl.SSLSocket): + timer = threading.Timer(REQUEST_DEADLINE_SECONDS, self._abort) + timer.daemon = True + timer.start() try: self.connection.do_handshake() except OSError as exc: logger.debug("TLS handshake from %s failed: %s", self.client_address, exc) return + finally: + timer.cancel() super().handle() + def _abort(self): + try: + self.connection.shutdown(socket.SHUT_RDWR) + except OSError: + pass + + +class BoundedThreadedWSGIServer(ThreadedWSGIServer): + """Serves at most ``MAX_CONCURRENT_CONNECTIONS`` connections at once; closes the rest.""" + + def __init__(self, *args, max_connections=None, **kwargs): + self.max_connections = max_connections or MAX_CONCURRENT_CONNECTIONS + self._slots = threading.BoundedSemaphore(self.max_connections) + super().__init__(*args, **kwargs) + + def process_request(self, request, client_address): + if not self._slots.acquire(blocking=False): + logger.warning("Refusing a connection from %s: %s are open", client_address, self.max_connections) + self.shutdown_request(request) + return + try: + super().process_request(request, client_address) + except Exception: + self._slots.release() + raise + + def process_request_thread(self, request, client_address): + try: + super().process_request_thread(request, client_address) + finally: + self._slots.release() + class LoopbackServer(threading.Thread): def __init__(self, app, host, port, ssl_context=None, label="HTTP"): @@ -376,12 +490,11 @@ def run(self): try: if self.ssl_context is not None: self.ssl_context.sni_callback = self._select_context - self.httpd = make_server( + self.httpd = BoundedThreadedWSGIServer( self.host, self.port, self.app, - threaded=True, - request_handler=LoopbackRequestHandler, + LoopbackRequestHandler, ssl_context=self.ssl_context, ) if self.ssl_context is not None: diff --git a/sites.py b/sites.py index a8af22d..c5a6f36 100644 --- a/sites.py +++ b/sites.py @@ -2,25 +2,58 @@ A website may scan when it is listed in ``cors_origins`` (set by hand or by IT) or linked. A DjangoLux site links itself with ``POST /link``, naming the sites -its administrator allows; the operator approves the link once, in ScanLink's -own window, which names the requesting site as the browser reported it. A -linked site may later change its list without asking again, and the operator -unlinks it from the tray menu. +its administrator allows; the operator approves the link in ScanLink's own +window, which names the requesting site as the browser reported it. A linked +site may shorten its list without asking; a list that gains a site opens the +window again, naming the new sites. The operator unlinks a site from the tray +menu. + +Approval windows are rationed: a declined or unanswered website's domain waits +before it can ask again, a website ScanLink does not know yet cannot open a +window shortly after another unknown website's window closed unanswered or +declined, and a website ScanLink already knows (linked, or allowed by a list) +closes an unknown website's open window to ask its own question. """ +import ipaddress import threading import time +from collections import namedtuple from datetime import datetime, timezone +from urllib.parse import urlsplit +from callback_transport import CallbackRefused, check_callback_url from utils import get_logger, load_config, normalize_origin, save_config, url_origin logger = get_logger() MAX_SITES_PER_LINK = 20 MAX_LINKS = 50 -# A declined website cannot open the approval window again for this long. +# A declined website's domain cannot open the approval window again for this long. DECLINE_COOLDOWN_SECONDS = 600 +# Nor can an unanswered one's, for this long. +UNANSWERED_COOLDOWN_SECONDS = 300 +# After an unknown website's window closes without Allow, other unknown websites wait this long. +UNKNOWN_PROMPT_INTERVAL_SECONDS = 120 +# How long a known website waits for an unknown website's window to close. +PREEMPT_WAIT_SECONDS = 5 LINK_PROMPT_SECONDS = 120 +# Second-level labels under which a registrable domain has three labels (example.co.uk). +_SHARED_SECOND_LEVEL = {"ac", "co", "com", "edu", "gov", "mil", "net", "nic", "org", "sch"} + +_Prompt = namedtuple("_Prompt", "origin known cancel") + + +def cooldown_key(origin): + """The part of an origin a cooldown applies to: its registrable domain, or its address.""" + host = (urlsplit(origin).hostname or "").rstrip(".") + try: + return str(ipaddress.ip_address(host)) + except ValueError: + pass + labels = host.split(".") + keep = 3 if len(labels) >= 3 and len(labels[-1]) == 2 and labels[-2] in _SHARED_SECOND_LEVEL else 2 + return ".".join(labels[-keep:]) class LinkError(Exception): @@ -39,7 +72,12 @@ def save_links(links): class SiteRegistry: def __init__(self, listed=(), links=None, *, confirm=None, persist=save_links, clock=time.monotonic): - """``confirm(origin, other_sites)`` returns True, False, or None when unanswered.""" + """``confirm(origin, other_sites, added_sites=None, cancel=None)`` returns True, False, + or None when unanswered or cancelled. + + ``added_sites`` lists what a linked website's list gains (None for a new link); + ``cancel`` is a ``threading.Event`` that closes the window unanswered when set. + """ self._listed = frozenset(origin for origin in map(normalize_origin, listed or ()) if origin) self._links = {} for origin, link in (links or {}).items(): @@ -55,7 +93,10 @@ def __init__(self, listed=(), links=None, *, confirm=None, persist=save_links, c self._clock = clock self._lock = threading.Lock() self._prompting = threading.Lock() - self._declined = {} + self._prompt = None + # cooldown key -> (clock value it ends at, error code) + self._cooldowns = {} + self._unknown_prompt_after = None def is_allowed(self, origin): with self._lock: @@ -64,11 +105,17 @@ def is_allowed(self, origin): def allows_callback(self, callback_url, requester=None): """Whether ScanLink may post a finished scan to ``callback_url``. - The URL must point at a website the operator allowed. A browser request + The URL must be ``https`` on a public host (``check_callback_url``) and + point at a website the operator allowed. A browser request (``requester`` is its Origin) may only name its own website or a site linked together with it; a local tool or a ``scanlink://`` link, which - has no Origin, may name any allowed website. + has no Origin, may name any allowed website. The address the host + resolves to is checked again when the scan is sent. """ + try: + check_callback_url(callback_url) + except CallbackRefused: + return False target = url_origin(callback_url) if target is None: return False @@ -104,39 +151,84 @@ def link(self, origin, sites): sites = self._clean_sites(origin, sites) with self._lock: link = self._links.get(origin) + added = None if link is not None: - if link["sites"] != sites: - self._links[origin] = {**link, "sites": sites} - self._save() - logger.info("Linked website %r changed its allowed sites to %r", origin, sites) - return {"linked": True, "prompted": False, "sites": sites} - if len(self._links) >= MAX_LINKS: + added = [site for site in sites if site not in link["sites"]] + if not added: + if link["sites"] != sites: + self._links[origin] = {**link, "sites": sites} + self._save() + logger.info("Linked website %r shortened its allowed sites to %r", origin, sites) + return {"linked": True, "prompted": False, "sites": sites} + elif len(self._links) >= MAX_LINKS: raise LinkError(409, "too_many_links", "ScanLink is linked to too many websites. Unlink one from the tray menu first.") - declined_at = self._declined.get(origin) - if declined_at is not None and self._clock() - declined_at < DECLINE_COOLDOWN_SECONDS: - raise LinkError(403, "link_declined", "Linking this website was declined on this computer.") - if not self._prompting.acquire(blocking=False): - raise LinkError(409, "link_pending", "Another website is waiting for approval in ScanLink.") - try: - answer = self._ask(origin, sites[1:]) - finally: - self._prompting.release() - if answer is None: - raise LinkError(408, "link_timeout", "Nobody answered ScanLink's approval window.") + known = link is not None or self._allowed_locked(origin) + self._check_cooldown_locked(origin, known) + + answer = self._ask_once(origin, sites[1:], added, known) + with self._lock: - if not answer: - self._declined[origin] = self._clock() - logger.info("The operator declined linking %r", origin) + if answer is not True: + self._record_refusal_locked(origin, known, answered=answer is False) + if answer is None: + raise LinkError(408, "link_timeout", "Nobody answered ScanLink's approval window.") + if answer is False: + logger.info("The operator declined %s %r", "widening" if added else "linking", origin) raise LinkError(403, "link_declined", "Linking this website was declined on this computer.") - self._declined.pop(origin, None) + self._cooldowns.pop(cooldown_key(origin), None) + previous = self._links.get(origin) self._links[origin] = { "sites": sites, - "linked_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "linked_at": (previous or {}).get("linked_at") + or datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), } self._save() - logger.info("The operator linked %r; allowed sites %r", origin, sites) + if added: + logger.info("The operator allowed %r to add %r; allowed sites %r", origin, added, sites) + else: + logger.info("The operator linked %r; allowed sites %r", origin, sites) return {"linked": True, "prompted": True, "sites": sites} + def _check_cooldown_locked(self, origin, known): + now = self._clock() + ends_at, code = self._cooldowns.get(cooldown_key(origin), (None, None)) + if ends_at is not None and now < ends_at: + if code == "link_declined": + raise LinkError(403, "link_declined", "Linking this website was declined on this computer.") + raise LinkError(429, "link_rate_limited", "ScanLink asked about this website recently. Try again in a few minutes.") + if not known and self._unknown_prompt_after is not None and now < self._unknown_prompt_after: + raise LinkError(429, "link_rate_limited", "ScanLink asked about another website recently. Try again in a few minutes.") + + def _record_refusal_locked(self, origin, known, answered): + now = self._clock() + if answered: + self._cooldowns[cooldown_key(origin)] = (now + DECLINE_COOLDOWN_SECONDS, "link_declined") + else: + self._cooldowns[cooldown_key(origin)] = (now + UNANSWERED_COOLDOWN_SECONDS, "link_rate_limited") + if not known: + self._unknown_prompt_after = now + UNKNOWN_PROMPT_INTERVAL_SECONDS + + def _ask_once(self, origin, other_sites, added, known): + """One approval window at a time; a known website closes an unknown website's window.""" + if not self._prompting.acquire(blocking=False): + holder = self._prompt + if not (known and holder is not None and not holder.known): + raise LinkError(409, "link_pending", "Another website is waiting for approval in ScanLink.") + holder.cancel.set() + if not self._prompting.acquire(timeout=PREEMPT_WAIT_SECONDS): + raise LinkError(409, "link_pending", "Another website is waiting for approval in ScanLink.") + logger.info("Closed the approval window for %r to ask about %r", holder.origin, origin) + prompt = _Prompt(origin, known, threading.Event()) + self._prompt = prompt + try: + answer = self._ask(origin, other_sites, added, prompt.cancel) + finally: + self._prompt = None + self._prompting.release() + if prompt.cancel.is_set(): + raise LinkError(409, "link_pending", "ScanLink closed this window to ask about a website it already knows.") + return answer + def unlink(self, origin): with self._lock: removed = self._links.pop(origin, None) is not None @@ -146,11 +238,11 @@ def unlink(self, origin): logger.info("The operator unlinked %r", origin) return removed - def _ask(self, origin, other_sites): + def _ask(self, origin, other_sites, added, cancel): if self._confirm is None: return None try: - return self._confirm(origin, other_sites) + return self._confirm(origin, other_sites, added_sites=added, cancel=cancel) except Exception: logger.exception("Could not show the link approval window") return None diff --git a/tests/test_callback_transport.py b/tests/test_callback_transport.py new file mode 100644 index 0000000..b48718c --- /dev/null +++ b/tests/test_callback_transport.py @@ -0,0 +1,246 @@ +"""Callbacks reach public https websites only, and cannot hold ScanLink up (R2-010, R2-055).""" + +import socket +import socketserver +import ssl +import threading +import time +import unittest +from unittest.mock import patch + +import callback_transport +from callback_transport import ( + CallbackFailed, + CallbackRefused, + check_callback_url, + is_public_address, + post_scan, + resolve_public, +) + +try: + from tests.test_loopback_listener import localhost_tls +except ImportError: # cryptography is not installed + localhost_tls = None + +PDF = b"%PDF-1.4\nscanned\n" + + +def resolving_to(*addresses): + def resolver(host, port, type=0): + return [ + (socket.AF_INET6 if ":" in address else socket.AF_INET, socket.SOCK_STREAM, 6, "", (address, port)) + for address in addresses + ] + + return resolver + + +class AddressClassificationTests(unittest.TestCase): + def test_only_public_unicast_addresses_pass(self): + for address in ("93.184.215.14", "8.8.8.8", "2606:4700:4700::1111"): + with self.subTest(address=address): + self.assertTrue(is_public_address(address)) + for address in ( + "127.0.0.1", "127.8.9.10", "0.0.0.0", "10.0.0.5", "172.16.3.4", "192.168.1.10", + "100.64.0.1", "100.100.100.200", "169.254.169.254", "224.0.0.1", "255.255.255.255", + "192.0.2.1", "198.18.0.1", "::1", "::", "fe80::1", "fd00:ec2::254", "fc00::1", + "::ffff:127.0.0.1", "::ffff:10.0.0.1", "64:ff9b::7f00:1", "2002:7f00:1::", + "2001:0:4136:e378:8000:63bf:80ff:fffe", "::127.0.0.1", "ff02::1", "2001:db8::1", + "not-an-address", + ): + with self.subTest(address=address): + self.assertFalse(is_public_address(address)) + + def test_callback_urls_must_be_https_to_a_public_looking_host(self): + self.assertEqual(check_callback_url("https://crm.example/scans?x=1"), ("crm.example", 443, "/scans?x=1")) + self.assertEqual(check_callback_url("https://crm.example:8443"), ("crm.example", 8443, "/")) + for url, reason in ( + ("http://crm.example/scans", "https_required"), + ("ftp://crm.example/scans", "https_required"), + ("https://localhost/x", "blocked_address"), + ("https://LOCALHOST./x", "blocked_address"), + ("https://scanner.localhost/x", "blocked_address"), + ("https://127.0.0.1:5443/shutdown", "blocked_address"), + ("https://127.1/x", "blocked_address"), + ("https://2130706433/x", "blocked_address"), + ("https://0x7f000001/x", "blocked_address"), + ("https://0177.0.0.1/x", "blocked_address"), + ("https://[::1]/x", "blocked_address"), + ("https://[::ffff:127.0.0.1]/x", "blocked_address"), + ("https://10.1.2.3/x", "blocked_address"), + ("https://169.254.169.254/latest/meta-data", "blocked_address"), + ("https://user@crm.example/x", "invalid_url"), + ("https://crm.example/a b", "invalid_url"), + ("https://crm​.example/x", "invalid_url"), + ("https://[/x", "invalid_url"), + (None, "invalid_url"), + ): + with self.subTest(url=url): + with self.assertRaises(CallbackRefused) as caught: + check_callback_url(url) + self.assertEqual(caught.exception.reason, reason) + + def test_a_host_is_refused_if_any_address_it_resolves_to_is_not_public(self): + no_own = lambda: set() + self.assertEqual(len(resolve_public("crm.example", 443, resolving_to("93.184.215.14"), no_own)), 1) + for addresses in (("127.0.0.1",), ("93.184.215.14", "10.0.0.5"), ("::ffff:192.168.0.1",)): + with self.subTest(addresses=addresses): + with self.assertRaises(CallbackRefused): + resolve_public("crm.example", 443, resolving_to(*addresses), no_own) + + def test_this_computers_own_addresses_are_refused(self): + import ipaddress + + own = lambda: {ipaddress.ip_address("93.184.215.14")} + with self.assertRaises(CallbackRefused): + resolve_public("me.example", 443, resolving_to("93.184.215.14"), own) + + +class _Handler(socketserver.BaseRequestHandler): + def handle(self): + server = self.server + server.connections += 1 + data = b"" + self.request.settimeout(5) + try: + while b"\r\n\r\n" not in data: + chunk = self.request.recv(65536) + if not chunk: + return + data += chunk + head, _, body = data.partition(b"\r\n\r\n") + length = int(next( + line.split(b":", 1)[1] for line in head.split(b"\r\n") if line.lower().startswith(b"content-length") + )) + while len(body) < length: + body += self.request.recv(65536) + server.requests.append((head.decode("latin-1"), body)) + mode = server.mode + if mode == "huge": + self.request.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: 1073741824\r\nContent-Encoding: gzip\r\n\r\n") + while not server.stop.is_set(): + self.request.sendall(b"\0" * 65536) + elif mode == "drip": + for byte in b"HTTP/1.1 200 OK\r\n\r\n": + if server.stop.wait(0.4): + return + self.request.sendall(bytes([byte])) + elif mode == "redirect": + self.request.sendall(b"HTTP/1.1 302 Found\r\nLocation: https://127.0.0.1/\r\nContent-Length: 0\r\n\r\n") + else: + self.request.sendall(b"HTTP/1.1 201 Created\r\nContent-Length: 2\r\n\r\nok") + except OSError: + return + + +class _TLSServer(socketserver.ThreadingTCPServer): + daemon_threads = True + allow_reuse_address = True + + def __init__(self, context, mode): + self.context, self.mode = context, mode + self.requests, self.connections, self.stop = [], 0, threading.Event() + super().__init__(("127.0.0.1", 0), _Handler) + + def get_request(self): + sock, address = super().get_request() + return self.context.wrap_socket(sock, server_side=True), address + + +@unittest.skipIf(localhost_tls is None, "cryptography is not installed") +class PostScanTests(unittest.TestCase): + def serve(self, mode): + server_context, _client_context = localhost_tls() + server = _TLSServer(server_context, mode) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + self.addCleanup(thread.join, 5) + self.addCleanup(server.server_close) + self.addCleanup(server.shutdown) + self.addCleanup(server.stop.set) + return server + + @staticmethod + def client_context(): + context = ssl.create_default_context() + context.check_hostname = False + context.verify_mode = ssl.CERT_NONE + return context + + def post(self, url, **kwargs): + return post_scan( + url, + [("job_id", "job-1"), ("doc_id", "D-1")], + [("pdf", ("scan_job-1.pdf", PDF, "application/pdf"))], + delivery_id="job-1", + resolver=resolving_to("127.0.0.1"), + own_addresses=lambda: set(), + context=self.client_context(), + **kwargs, + ) + + def test_a_host_rebound_to_this_computer_is_never_connected(self): + server = self.serve("ok") + with patch("callback_transport.socket.getaddrinfo", resolving_to("127.0.0.1")): + with self.assertRaises(CallbackRefused) as caught: + post_scan( + f"https://rebound.example:{server.server_address[1]}/api/admin/reset?all=1", + [("job_id", "job-1")], + [("pdf", ("scan.pdf", PDF, "application/pdf"))], + delivery_id="job-1", + context=self.client_context(), + ) + self.assertEqual(caught.exception.reason, "blocked_address") + time.sleep(0.2) + self.assertEqual(server.connections, 0) + + def _as_public(self): + # Stand in for a public website: loopback is the only reachable test host. + real = callback_transport.is_public_address + patcher = patch( + "callback_transport.is_public_address", + side_effect=lambda value: str(value).split("%")[0] == "127.0.0.1" or real(value), + ) + patcher.start() + self.addCleanup(patcher.stop) + + def test_delivery_sends_the_scan_without_browser_headers(self): + self._as_public() + server = self.serve("ok") + status = self.post(f"https://callback.example:{server.server_address[1]}/in?x=1") + self.assertEqual(status, 201) + head, body = server.requests[0] + self.assertTrue(head.startswith("POST /in?x=1 HTTP/1.1")) + self.assertIn("Accept-Encoding: identity", head) + self.assertIn("X-ScanLink-Delivery: job-1", head) + self.assertIn(f"Host: callback.example:{server.server_address[1]}", head) + self.assertNotIn("Origin:", head) + self.assertIn(PDF, body) + self.assertIn(b'name="doc_id"\r\n\r\nD-1', body) + + def test_a_huge_response_is_never_read(self): + self._as_public() + server = self.serve("huge") + started = time.monotonic() + status = self.post(f"https://callback.example:{server.server_address[1]}/huge") + self.assertEqual(status, 200) + self.assertLess(time.monotonic() - started, 5) + + def test_a_dripping_response_ends_at_the_deadline(self): + self._as_public() + server = self.serve("drip") + started = time.monotonic() + with self.assertRaises(CallbackFailed): + self.post(f"https://callback.example:{server.server_address[1]}/drip", deadline_seconds=1) + self.assertLess(time.monotonic() - started, 4) + + def test_a_redirect_is_reported_not_followed(self): + self._as_public() + server = self.serve("redirect") + self.assertEqual(self.post(f"https://callback.example:{server.server_address[1]}/r"), 302) + self.assertEqual(len(server.requests), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_callbacks.py b/tests/test_callbacks.py index 89e79d4..9df8df8 100644 --- a/tests/test_callbacks.py +++ b/tests/test_callbacks.py @@ -6,6 +6,7 @@ import unittest from unittest.mock import MagicMock, patch +from callback_transport import CallbackFailed, CallbackRefused from sites import SiteRegistry from worker import CallbackNotAllowedError, ScanWorker @@ -37,14 +38,14 @@ def scan_worker(guard): def run_queued_job(worker, status_code=200, post_error=None): job_id = worker.scan_queue.get_nowait() - with patch("worker.requests") as requests: - requests.post.return_value = MagicMock(status_code=status_code) + with patch("worker.post_scan") as post: + post.return_value = status_code if post_error is not None: - requests.post.side_effect = post_error + post.side_effect = post_error worker._process_job(job_id) if worker.callback_thread is not None: worker.callback_thread.join(5) - return job_id, requests.post + return job_id, post class AllowsCallbackTests(unittest.TestCase): @@ -72,6 +73,7 @@ def test_disguised_and_malformed_urls_are_refused(self): "https://user:pw@crm.example/scans", "https://crm.example.evil.example/scans", "http://crm.example/scans", + "https://127.0.0.1/scans", "https://crm.example:8443/scans", "ftp://crm.example/scans", "/relative/scans", @@ -92,12 +94,12 @@ def test_finished_scan_is_posted_to_its_callback(self): _job_id, post = run_queued_job(worker, status_code=201) post.assert_called_once() - args, kwargs = post.call_args - self.assertEqual(args, (f"{CRM}/scans/upload",)) - self.assertIs(kwargs["allow_redirects"], False) - self.assertEqual(kwargs["files"]["pdf"][1], PDF) - self.assertEqual(kwargs["data"]["doc_id"], "D-1") - self.assertEqual(kwargs["data"]["job_id"], queued["job_id"]) + (url, fields, files), kwargs = post.call_args + self.assertEqual(url, f"{CRM}/scans/upload") + self.assertEqual(files, [("pdf", (f"scan_{queued['job_id']}.pdf", PDF, "application/pdf"))]) + self.assertEqual(dict(fields)["doc_id"], "D-1") + self.assertEqual(dict(fields)["job_id"], queued["job_id"]) + self.assertEqual(kwargs["delivery_id"], queued["job_id"]) job = worker.get_job(queued["job_id"]) self.assertEqual(job["callback"], {"state": "delivered", "status_code": 201}) self.assertNotIn("callback_url", job) @@ -130,20 +132,29 @@ def test_website_unlinked_during_the_scan_gets_nothing(self): post.assert_not_called() self.assertEqual(worker.get_job(queued["job_id"])["callback"], {"state": "refused", "reason": "not_linked"}) - def test_a_redirect_is_not_followed(self): + def test_a_redirect_counts_as_failed(self): worker = scan_worker(registry().allows_callback) queued = worker.submit_job(callback_url=f"{CRM}/scans", origin=CRM) - _job_id, post = run_queued_job(worker, status_code=302) + run_queued_job(worker, status_code=302) - self.assertIs(post.call_args.kwargs["allow_redirects"], False) self.assertEqual(worker.get_job(queued["job_id"])["callback"], {"state": "failed", "status_code": 302}) + def test_a_destination_that_resolves_to_a_private_address_is_refused(self): + worker = scan_worker(registry().allows_callback) + queued = worker.submit_job(callback_url=f"{CRM}/scans", origin=CRM) + + run_queued_job(worker, post_error=CallbackRefused("blocked_address")) + + self.assertEqual(worker.get_job(queued["job_id"])["callback"], {"state": "refused", "reason": "blocked_address"}) + _job, result = worker.consume_result(queued["job_id"]) + self.assertEqual(result, PDF) + def test_unreachable_callback_keeps_the_result_for_polling(self): worker = scan_worker(registry().allows_callback) queued = worker.submit_job(callback_url=f"{CRM}/scans", origin=CRM) - run_queued_job(worker, post_error=ConnectionError("refused")) + run_queued_job(worker, post_error=CallbackFailed("refused")) self.assertEqual(worker.get_job(queued["job_id"])["callback"], {"state": "failed", "reason": "unreachable"}) _job, result = worker.consume_result(queued["job_id"]) @@ -163,14 +174,33 @@ def test_slow_callback_does_not_hold_the_worker(self): worker.submit_job(callback_url=f"{CRM}/scans", origin=CRM) job_id = worker.scan_queue.get_nowait() release = threading.Event() - with patch("worker.requests") as requests: - requests.post.side_effect = lambda *a, **k: release.wait(5) and MagicMock(status_code=200) + with patch("worker.post_scan") as post: + post.side_effect = lambda *a, **k: release.wait(5) and 200 worker._process_job(job_id) self.assertTrue(worker.callback_thread.is_alive()) self.assertIsNotNone(worker.submit_job(doc_id="next")) release.set() worker.callback_thread.join(5) + def test_callbacks_in_flight_are_capped(self): + # R2-055: every hanging callback used to keep its own thread and PDF. + worker = scan_worker(registry().allows_callback) + release = threading.Event() + threads = [] + with patch("worker.post_scan") as post: + post.side_effect = lambda *a, **k: release.wait(5) and 200 + jobs = [] + for _ in range(3): + jobs.append(worker.submit_job(callback_url=f"{CRM}/scans", origin=CRM)["job_id"]) + worker._process_job(worker.scan_queue.get_nowait()) + threads.append(worker.callback_thread) + self.assertEqual(worker.get_job(jobs[2])["callback"], {"state": "failed", "reason": "busy"}) + release.set() + for thread in threads[:2]: + thread.join(5) + self.assertEqual(post.call_count, 2) + self.assertEqual(worker.get_job(jobs[0])["callback"], {"state": "delivered", "status_code": 200}) + @unittest.skipIf(server is None, "Flask is not installed in this environment") class CallbackRequestTests(unittest.TestCase): @@ -190,6 +220,22 @@ def test_browser_scan_with_a_foreign_callback_is_refused(self): self.assertEqual(response.get_json()["error"]["code"], "callback_not_allowed") self.assertEqual(self.worker.jobs, {}) + def test_callbacks_to_this_computer_or_its_network_are_refused(self): + # R2-010: a linked site could list loopback, private or metadata + # addresses, or ScanLink itself, and receive the scan there. + local = "http://127.0.0.1:18702" + sites = SiteRegistry(listed=[CRM], links={ + CRM: {"sites": [local, "http://localhost:5000", "https://10.0.0.5", "https://169.254.169.254", + "https://[::ffff:127.0.0.1]", "https://2130706433", "https://localhost", + "https://scanner.localhost"]}, + }, persist=lambda links: None) + for url in (f"{local}/api/admin/reset?all=1", "http://localhost:5000/shutdown", "https://10.0.0.5/in", + "https://169.254.169.254/latest/meta-data", "https://[::ffff:127.0.0.1]/x", + "https://2130706433/x", "https://localhost/x", "https://scanner.localhost/x"): + with self.subTest(url=url): + self.assertFalse(sites.allows_callback(url, CRM)) + self.assertFalse(sites.allows_callback(url)) + def test_browser_scan_may_call_back_to_its_linked_site(self): response = self.client.post( "/scan", json={"callback_url": f"{SALES}/scans"}, headers={"Origin": CRM} diff --git a/tests/test_round2_regressions.py b/tests/test_round2_regressions.py new file mode 100644 index 0000000..cabdfa5 --- /dev/null +++ b/tests/test_round2_regressions.py @@ -0,0 +1,350 @@ +"""Break-it round 2 regressions: jobs, results, the scan child and the listener (R2-118 … R2-125).""" + +import io +import json +import os +from pathlib import Path +import queue +import shutil +import socket +import subprocess +import sys +import tempfile +import threading +import time +import unittest +import uuid +from unittest.mock import MagicMock, patch + +import scan_runtime +import scanner +from gui.dialogs import site_list_size +from scanner import ScanError +from worker import ScanWorker, sweep_stale_directories + +try: + import server +except ImportError: + server = None + +ORIGIN = "https://crm.example" +PDF = b"%PDF-1.4\nscanned\n" + + +def completed_worker(): + worker = ScanWorker(queue.Queue()) + worker._run_scan_subprocess = lambda job_id, on_progress: io.BytesIO(PDF) + job = worker.submit_job(doc_id="D-1", origin=ORIGIN) + worker._process_job(worker.scan_queue.get_nowait()) + return worker, job["job_id"] + + +@unittest.skipIf(server is None, "Flask is not installed in this environment") +class RequestValidationTests(unittest.TestCase): + def setUp(self): + self.worker = ScanWorker(queue.Queue()) + self.shutdown = threading.Event() + self.client = server.create_app( + self.worker, self.shutdown, {"http_enabled": True}, sites=MagicMock(is_allowed=lambda origin: True) + ).test_client() + + def post(self, endpoint, body, **headers): + return self.client.post(endpoint, data=body, content_type="application/json", headers=headers) + + def test_doc_ids_that_could_forge_log_lines_are_refused(self): + # R2-122 + for endpoint in ("/scan", "/internal/protocol/scan"): + for doc_id in ("D-1\n2026-11-27 - INFO - The operator linked 'https://forged.example'", + "D\r1", "D‮1", {"a": 1}, ["x"], True, 1.5, "x" * 201, 2 ** 70): + with self.subTest(endpoint=endpoint, doc_id=doc_id): + response = self.post(endpoint, json.dumps({"doc_id": doc_id})) + self.assertEqual(response.status_code, 400) + self.assertEqual(response.get_json()["error"]["code"], "invalid_doc_id") + self.assertEqual(self.worker.jobs, {}) + + def test_doc_ids_as_text_or_whole_numbers_are_kept(self): + for doc_id in ("DOC-123", "وثيقة ١٢", 42): + with self.subTest(doc_id=doc_id): + self.worker.jobs.clear() + self.worker.current_job_id = None + response = self.post("/scan", json.dumps({"doc_id": doc_id}), Origin=ORIGIN) + self.assertEqual(response.status_code, 202) + status = self.client.get(f"/scan/{response.get_json()['job_id']}", headers={"Origin": ORIGIN}) + self.assertEqual(status.get_json()["doc_id"], doc_id) + + def test_nan_and_infinity_are_not_json(self): + # R2-123: they were stored and echoed back as invalid JSON. + for body in ('{"doc_id": NaN}', '{"doc_id": Infinity}', '{"metadata": {"n": -Infinity}}'): + with self.subTest(body=body): + response = self.post("/scan", body) + self.assertEqual(response.status_code, 400) + self.assertEqual(response.get_json()["error"]["code"], "invalid_json") + self.assertEqual(self.worker.jobs, {}) + + def test_scanlinks_own_deliveries_cannot_reach_its_control_endpoints(self): + # R2-010: a callback once shut ScanLink down through /shutdown. + for endpoint in ("/shutdown", "/internal/protocol/scan", "/scan"): + with self.subTest(endpoint=endpoint): + response = self.client.post(endpoint, data=b"x", headers={"X-ScanLink-Delivery": "job-1"}) + self.assertEqual(response.status_code, 403) + self.assertEqual(response.get_json()["error"]["code"], "local_only") + self.assertFalse(self.shutdown.is_set()) + + +@unittest.skipIf(server is None, "Flask is not installed in this environment") +class ResultDownloadTests(unittest.TestCase): + def setUp(self): + self.worker, self.job_id = completed_worker() + self.client = server.create_app( + self.worker, threading.Event(), {"http_enabled": True}, sites=MagicMock(is_allowed=lambda origin: True) + ).test_client() + self.url = f"/scan/{self.job_id}/result" + + def test_head_does_not_spend_the_result(self): + # R2-120 + head = self.client.head(self.url, headers={"Origin": ORIGIN}) + self.assertEqual(head.status_code, 200) + self.assertEqual(head.headers["Content-Length"], str(len(PDF))) + self.assertEqual(head.data, b"") + self.assertEqual(self.client.get(self.url, headers={"Origin": ORIGIN}).data, PDF) + self.assertEqual(self.client.head(self.url, headers={"Origin": "https://evil.example"}).status_code, 404) + + def test_a_cut_off_download_can_be_retried_once(self): + # R2-120: one dropped connection used to lose the scan. + first = self.client.get(self.url, headers={"Origin": ORIGIN}) + retry = self.client.get(self.url, headers={"Origin": ORIGIN}) + third = self.client.get(self.url, headers={"Origin": ORIGIN}) + self.assertEqual((first.data, retry.data), (PDF, PDF)) + self.assertEqual(third.status_code, 410) + self.assertIsNone(self.worker.jobs[self.job_id]["result_bytes"]) + + def test_the_retry_window_closes(self): + self.client.get(self.url, headers={"Origin": ORIGIN}) + later = time.monotonic() + 31 + with patch("worker.time.monotonic", return_value=later): + self.assertEqual(self.client.get(self.url, headers={"Origin": ORIGIN}).status_code, 410) + + +class ResultLifetimeTests(unittest.TestCase): + def test_wall_clock_jumps_do_not_decide_result_lifetime(self): + # R2-121 + worker, job_id = completed_worker() + with patch("worker.time.time", return_value=time.time() + 301): + self.assertIsNotNone(worker.get_job(job_id)) + with patch("worker.time.time", return_value=time.time() - 86400): + self.assertIsNotNone(worker.get_job(job_id)) + with patch("worker.time.monotonic", return_value=time.monotonic() + worker.result_ttl_seconds + 1): + self.assertIsNone(worker.get_job(job_id)) + + +class PageCountTests(unittest.TestCase): + def test_the_child_reports_the_page_count_when_it_completes(self): + # R2-118: the final state carried no page count, so short scans reported 0 or 1. + directory = Path(tempfile.mkdtemp(prefix="scanlink-job-")) + self.addCleanup(shutil.rmtree, directory, ignore_errors=True) + (directory / "request.json").write_text(json.dumps({"job_id": "job", "scan_timeout_seconds": 5})) + + def scan(job_id, progress_callback, deadline): + for page in range(1, 6): + progress_callback("page_scanned", page_count=page) + progress_callback("generating_pdf", page_count=5) + return io.BytesIO(PDF) + + manager = MagicMock() + manager.return_value.scan_to_pdf.side_effect = scan + with patch("scan_runtime.ScannerManager", manager), patch("scan_runtime.tk.Tk", MagicMock()), \ + patch("scan_runtime.init_gui", MagicMock()): + self.assertEqual(scan_runtime.run_scan_job(str(directory)), 0) + state = json.loads((directory / "state.json").read_text()) + self.assertEqual((state["status"], state["page_count"]), ("completed", 5)) + + def test_the_parent_applies_the_final_page_count(self): + worker = ScanWorker(queue.Queue()) + seen = [] + process = MagicMock(returncode=0) + process.poll.return_value = 0 + states = iter([None, {"status": "completed", "page_count": 7}]) + + with patch("worker.subprocess.Popen", return_value=process), \ + patch.object(worker, "_read_state_file", side_effect=lambda path: next(states)), \ + patch("worker.os.path.exists", return_value=True), \ + patch("builtins.open", unittest.mock.mock_open(read_data=PDF)): + worker._run_scan_subprocess("job", lambda status, **data: seen.append((status, data))) + self.assertEqual(seen, [("completed", {"page_count": 7})]) + + +class OrphanedScanTests(unittest.TestCase): + def test_stale_scan_folders_are_removed(self): + # R2-119: a killed ScanLink left the scanned document in %TEMP%. + root = Path(".xclude/test-output/sweep") / uuid.uuid4().hex + root.mkdir(parents=True) + self.addCleanup(shutil.rmtree, root, ignore_errors=True) + old = time.time() - 3600 + for name in ("scanlink-job-old", "scanlink-pages-old", "scanlink-job-fresh", "other-folder"): + (root / name).mkdir() + (root / name / "result.pdf").write_bytes(PDF) + if name.endswith("old") or name == "other-folder": + os.utime(root / name, (old, old)) + (root / "scanlink-job-file").write_bytes(b"not a folder") + os.utime(root / "scanlink-job-file", (old, old)) + + removed = sweep_stale_directories(str(root)) + + self.assertEqual(sorted(removed), ["scanlink-job-old", "scanlink-pages-old"]) + self.assertEqual(sorted(p.name for p in root.iterdir()), + ["other-folder", "scanlink-job-file", "scanlink-job-fresh"]) + + def test_the_child_stops_when_scanlink_ends(self): + parent = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"]) + self.addCleanup(lambda: parent.poll() is None and parent.kill()) + gone = threading.Event() + self.assertIsNotNone(scan_runtime.watch_parent(parent.pid, gone.set, interval=0.1)) + time.sleep(0.3) + self.assertFalse(gone.is_set()) + parent.kill() + parent.wait(5) + self.assertTrue(gone.wait(3)) + + def test_the_worker_tells_the_child_who_its_parent_is(self): + worker = ScanWorker(queue.Queue()) + written = {} + real_dump = json.dump + + def capture(payload, handle, **kwargs): + written.update(payload) + return real_dump(payload, handle, **kwargs) + + with patch("worker.json.dump", side_effect=capture), \ + patch("worker.subprocess.Popen", side_effect=OSError("no child")): + with self.assertRaises(OSError): + worker._run_scan_subprocess("job", lambda *a, **k: None) + self.assertEqual(written["parent_pid"], os.getpid()) + + +class _TimingOutSource: + def acquire_natively(self, after, before, show_ui, modal): + for index in range(11): + before(None) + after(object(), index < 10) + + +class ScanDeadlineTests(unittest.TestCase): + def test_a_deadline_reached_while_pages_arrive_is_a_timeout(self): + # R2-124: it was re-wrapped as acquire_failed / failed. + manager = scanner.ScannerManager() + pages = [] + + def check(deadline, code, message): + if "processing" in message and len(pages) >= 3: + raise ScanError(code, message, status="timed_out") + + with patch.object(scanner, "twain", MagicMock()), \ + patch.object(manager, "_get_parent_window", return_value=0), \ + patch.object(manager, "_get_configs", return_value={}), \ + patch.object(manager, "_open_source", return_value=(MagicMock(), _TimingOutSource())), \ + patch.object(manager, "_configure_source"), \ + patch.object(manager, "_choose_transfer_mode", return_value="native"), \ + patch.object(manager, "_check_deadline", side_effect=check), \ + patch.object(manager, "_twain_image_to_pil", return_value=None), \ + patch.object(manager, "_encode_page", side_effect=lambda image: pages.append(1) or b"jpeg"): + with self.assertRaises(ScanError) as caught: + manager.scan_to_pdf("job", deadline=1) + self.assertEqual((caught.exception.code, caught.exception.status), ("acquire_timeout", "timed_out")) + + +@unittest.skipIf(server is None, "Flask is not installed in this environment") +class SlowClientTests(unittest.TestCase): + def listener(self, **patches): + for name, value in patches.items(): + patcher = patch(f"server.{name}", value) + patcher.start() + self.addCleanup(patcher.stop) + from tests.test_server import FakeWorker + + app = server.create_app(FakeWorker(), threading.Event(), {"http_enabled": True}, + sites=MagicMock(is_allowed=lambda origin: True)) + listener = server.LoopbackServer(app, "127.0.0.1", 0, label="HTTP") + listener.start() + self.assertTrue(listener.started.wait(5)) + self.addCleanup(listener.join, 5) + self.addCleanup(listener.shutdown) + return listener.httpd.server_port + + def test_a_dripping_request_is_closed_at_the_deadline(self): + # R2-125: the timeout restarted on every byte. + port = self.listener(REQUEST_TIMEOUT_SECONDS=2, REQUEST_DEADLINE_SECONDS=1) + sock = socket.create_connection(("127.0.0.1", port)) + self.addCleanup(sock.close) + started = time.monotonic() + closed = False + for byte in b"GET /health HTTP/1.1\r\nHost: 127.0.0.1\r\nX-Slow: " + b"a" * 40: + try: + sock.sendall(bytes([byte])) + except OSError: + closed = True + break + sock.settimeout(0.4) + try: + if sock.recv(1024) == b"": + closed = True + break + except socket.timeout: + continue + except OSError: + closed = True + break + self.assertTrue(closed) + self.assertLess(time.monotonic() - started, 4) + + def test_connections_beyond_the_cap_are_closed(self): + port = self.listener(MAX_CONCURRENT_CONNECTIONS=2, REQUEST_TIMEOUT_SECONDS=5, REQUEST_DEADLINE_SECONDS=5) + held = [socket.create_connection(("127.0.0.1", port)) for _ in range(2)] + self.addCleanup(lambda: [sock.close() for sock in held]) + time.sleep(0.2) + extra = socket.create_connection(("127.0.0.1", port)) + self.addCleanup(extra.close) + extra.settimeout(2) + try: + self.assertEqual(extra.recv(1024), b"") + except ConnectionResetError: + pass + for sock in held: + sock.close() + time.sleep(0.2) + probe = socket.create_connection(("127.0.0.1", port)) + self.addCleanup(probe.close) + probe.sendall(b"GET /health HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n") + probe.settimeout(3) + self.assertTrue(probe.recv(1024).startswith(b"HTTP/1.1 200")) + + +class ApprovalWindowTests(unittest.TestCase): + def test_every_listed_site_is_shown_in_full(self): + # R2-115: 6 rows of 56 characters cut off long or many sites. + sites = [f"https://archive.office.test.{'a' * 40}.attacker{n}.example" for n in range(19)] + rows, width = site_list_size(sites) + self.assertEqual(rows, 19) + self.assertGreaterEqual(width, max(len(site) for site in sites)) + self.assertEqual(site_list_size(["https://a.example"]), (1, 40)) + + def test_the_listing_widget_has_every_row(self): + import tkinter as tk + + from gui import dialogs + + try: + root = tk.Tk() + except tk.TclError: + self.skipTest("no display for Tk") + root.withdraw() + self.addCleanup(root.destroy) + sites = [f"https://archive.office.test.{'a' * 60}.attacker{n}.example" for n in range(19)] + listing = dialogs._site_listing(tk.Frame(root), sites) + self.assertEqual(listing.size(), 19) + self.assertEqual(int(listing.cget("height")), 19) + self.assertEqual(int(listing.cget("width")), dialogs.SITE_LIST_MAX_WIDTH) + self.assertTrue(listing.cget("xscrollcommand")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_site_links.py b/tests/test_site_links.py index f32ee22..9f12d8b 100644 --- a/tests/test_site_links.py +++ b/tests/test_site_links.py @@ -23,11 +23,15 @@ def test_only_plain_website_origins_are_accepted(self): ("https://Archive.Example:443/", "https://archive.example"), ("http://intranet:8080", "http://intranet:8080"), ("http://[::1]:8000", "http://[::1]:8000"), + # R2-115: look-alike names are shown as the browser sends them. + ("https://\u0430pple.example", "https://xn--pple-43d.example"), ): with self.subTest(value=value): self.assertEqual(normalize_origin(value), expected) for value in ("*", "null", "", None, 5, "file:///c:/x", "https://*.example", "https://a.example/path", - "https://user:pw@a.example", "https://a.example?x=1", "javascript:alert(1)", "https://"): + "https://user:pw@a.example", "https://a.example?x=1", "javascript:alert(1)", "https://", + "https://archive.office.test\u202eelpmaxe.evil", "https://arch\u200bive.example", + "https://archive.example."): with self.subTest(value=value): self.assertIsNone(normalize_origin(value)) @@ -52,6 +56,7 @@ class LinkTests(unittest.TestCase): def setUp(self): self.answers = [] self.asked = [] + self.added = [] self.saved = [] self.now = [1000.0] self.sites = SiteRegistry( @@ -65,8 +70,9 @@ def setUp(self): self.worker, threading.Event(), {"http_enabled": True}, self.sites ).test_client() - def confirm(self, origin, other_sites): + def confirm(self, origin, other_sites, added_sites=None, cancel=None): self.asked.append((origin, other_sites)) + self.added.append(added_sites) return self.answers.pop(0) if self.answers else None def link(self, headers, sites=()): @@ -97,15 +103,97 @@ def test_an_approved_link_allows_the_site_and_the_sites_its_admin_lists(self): self.assertEqual(self.client.post("/scan", json={}, headers=CRM).status_code, 202) self.assertEqual(self.client.post("/scan", json={}, headers=EVIL).status_code, 403) - def test_a_linked_site_changes_its_list_without_asking_again(self): + def test_a_linked_site_shortens_its_list_without_asking_again(self): self.answers.append(True) - self.link(ARCHIVE, ["https://crm.example"]) + self.link(ARCHIVE, ["https://crm.example", "https://sales.example"]) response = self.link(ARCHIVE, ["https://sales.example"]) self.assertEqual(response.get_json()["prompted"], False) self.assertEqual(len(self.asked), 1) self.assertEqual(self.client.get("/health", headers=CRM).status_code, 403) self.assertEqual(self.client.get("/health", headers={"Origin": "https://sales.example"}).status_code, 200) + def test_a_linked_site_that_widens_its_list_asks_again(self): + # R2-054: one approval used to allow any later list without a window. + self.answers.append(True) + self.link(ARCHIVE, ["https://crm.example"]) + self.answers.append(True) + response = self.link(ARCHIVE, ["https://crm.example", "https://sales.example"]) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.get_json()["prompted"], True) + self.assertEqual(self.added, [None, ["https://sales.example"]]) + self.assertEqual(self.client.get("/health", headers={"Origin": "https://sales.example"}).status_code, 200) + + def test_a_declined_widening_keeps_the_approved_list(self): + self.answers.append(True) + self.link(ARCHIVE, ["https://crm.example"]) + self.answers.append(False) + response = self.link(ARCHIVE, ["https://crm.example", "https://evil.example"]) + self.assertEqual((response.status_code, response.get_json()["error"]["code"]), (403, "link_declined")) + self.assertEqual(self.client.get("/health", headers=EVIL).status_code, 403) + self.assertEqual(self.client.get("/health", headers=CRM).status_code, 200) + self.assertEqual(self.sites.link_for("https://archive.example")["sites"], + ["https://archive.example", "https://crm.example"]) + unanswered = self.link(ARCHIVE, ["https://crm.example", "https://evil.example"]) + self.assertEqual(unanswered.get_json()["error"]["code"], "link_declined") + self.assertEqual(len(self.asked), 2) + + def test_unanswered_windows_cool_down_too(self): + # R2-056: an unanswered window could be reopened at once, forever. + first = self.link(EVIL) + self.assertEqual(first.get_json()["error"]["code"], "link_timeout") + again = self.link(EVIL) + self.assertEqual((again.status_code, again.get_json()["error"]["code"]), (429, "link_rate_limited")) + self.assertEqual(len(self.asked), 1) + + def test_cooldowns_cover_the_whole_domain(self): + self.answers.append(False) + self.link({"Origin": "https://evil1.attacker.test"}) + for origin in ("https://evil2.attacker.test", "https://evil1.attacker.test:8443", "http://attacker.test"): + with self.subTest(origin=origin): + response = self.link({"Origin": origin}) + self.assertEqual(response.get_json()["error"]["code"], "link_declined") + self.assertEqual(len(self.asked), 1) + + def test_unknown_websites_wait_between_windows(self): + self.link(EVIL) + response = self.link({"Origin": "https://other.example.net"}) + self.assertEqual((response.status_code, response.get_json()["error"]["code"]), (429, "link_rate_limited")) + self.now[0] += 121 + self.answers.append(True) + self.assertEqual(self.link({"Origin": "https://other.example.net"}).status_code, 200) + self.assertEqual(len(self.asked), 2) + + def test_a_known_website_is_not_held_up_by_an_unknown_one(self): + self.answers.append(True) + self.link(ARCHIVE, ["https://crm.example"]) + self.link(EVIL) # unanswered: unknown websites now wait + self.answers.append(True) + self.assertEqual(self.link(CRM).status_code, 200) + + def test_a_known_website_closes_an_unknown_websites_window(self): + self.answers.append(True) + self.link(ARCHIVE, ["https://crm.example"]) + opened, cancelled = threading.Event(), {} + + def confirm(origin, other_sites, added_sites=None, cancel=None): + if origin == EVIL["Origin"]: + opened.set() + cancelled["seen"] = cancel.wait(5) + return None + return True + + self.sites._confirm = confirm + results = {} + thread = threading.Thread(target=lambda: results.setdefault("evil", self.link(EVIL))) + thread.start() + self.assertTrue(opened.wait(5)) + crm = self.link(CRM) + thread.join(5) + self.assertTrue(cancelled["seen"]) + self.assertEqual(crm.status_code, 200) + self.assertEqual(results["evil"].get_json()["error"]["code"], "link_pending") + self.assertEqual(self.client.get("/health", headers=EVIL).status_code, 403) + def test_a_listed_site_cannot_change_another_sites_link(self): self.answers.append(True) self.link(ARCHIVE, ["https://crm.example"]) @@ -137,7 +225,7 @@ def test_an_unanswered_window_links_nothing(self): def test_one_approval_window_at_a_time(self): opened, release = threading.Event(), threading.Event() - def slow_confirm(origin, other_sites): + def slow_confirm(origin, other_sites, added_sites=None, cancel=None): opened.set() release.wait(5) return True diff --git a/tests/test_stress_regressions.py b/tests/test_stress_regressions.py index c2c2b38..220a39d 100644 --- a/tests/test_stress_regressions.py +++ b/tests/test_stress_regressions.py @@ -92,7 +92,7 @@ def test_child_reports_its_own_timeout_within_parent_grace(self): self.assertEqual(job["status"], "timed_out") self.assertEqual(job["error"]["message"], "Child closed the scanner.") - def test_parallel_result_downloads_consume_pdf_once(self): + def test_parallel_result_downloads_get_the_pdf_at_most_twice(self): job_id = self.client.post("/scan", json={}).get_json()["job_id"] self.finish(job_id) self.worker.scan_queue.join() @@ -103,8 +103,9 @@ def download(_): with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool: statuses = list(pool.map(download, range(24))) - self.assertEqual(statuses.count(200), 1) - self.assertEqual(statuses.count(410), 23) + # One download, plus one retry for a client whose first download was cut off. + self.assertEqual(statuses.count(200), 2) + self.assertEqual(statuses.count(410), 22) self.assertIsNone(self.worker.jobs[job_id]["result_bytes"]) self.worker.job_ttl_seconds = 0 self.assertIsNone(self.worker.get_job(job_id)) diff --git a/tests/test_worker.py b/tests/test_worker.py index 64a2eba..69aa732 100644 --- a/tests/test_worker.py +++ b/tests/test_worker.py @@ -71,16 +71,19 @@ def test_consumed_result_keeps_metadata_until_job_ttl(self): _job, result_bytes = worker.consume_result("job-1") self.assertEqual(result_bytes, b"pdf") + _job, retried = worker.consume_result("job-1") + self.assertEqual(retried, b"pdf") self.assertIsNone(worker.jobs["job-1"]["result_bytes"]) + self.assertEqual(worker.consume_result("job-1")[1], None) self.assertEqual(worker.get_job("job-1")["status"], "completed") worker.job_ttl_seconds = 0 self.assertIsNone(worker.get_job("job-1")) def test_unparseable_callback_is_skipped(self): worker = ScanWorker(queue.Queue()) - with patch("worker.requests") as requests: + with patch("worker.post_scan") as post: worker._send_callback({"job_id": "job-1", "callback_url": "http://["}, b"pdf") - requests.post.assert_not_called() + post.assert_not_called() if __name__ == "__main__": diff --git a/utils.py b/utils.py index 03d5523..0f04a21 100644 --- a/utils.py +++ b/utils.py @@ -1,4 +1,5 @@ import os +import unicodedata import sys import json import logging @@ -137,6 +138,25 @@ def _apply_scan_profile_migration(config): config["color_mode"] = DEFAULT_COLOR_MODE config["paper_protection"] = False +def _ascii_host(host): + """A host name in its ASCII (IDNA) form, as browsers send it; None when it cannot be shown honestly. + + Bidi overrides, zero-width and other invisible characters, wildcards and a + trailing dot are refused; other non-ASCII names become ``xn--`` labels, so + the approval window shows a look-alike name the way the browser sends it. + """ + host = host.lower() + if not host or host.endswith(".") or "*" in host: + return None + if any(unicodedata.category(ch)[0] in "CZ" for ch in host): + return None + if host.isascii(): + return host + try: + return host.encode("idna").decode("ascii") + except UnicodeError: + return None + def normalize_origin(value): """``scheme://host[:port]`` for an http(s) website origin, as browsers send it; else None. @@ -153,8 +173,8 @@ def normalize_origin(value): return None if parts.username or parts.password or parts.query or parts.fragment or parts.path not in ("", "/"): return None - host = parts.hostname.lower() - if "*" in host or any(ch.isspace() for ch in host): + host = _ascii_host(parts.hostname) + if host is None: return None if ":" in host: host = f"[{host}]" diff --git a/worker.py b/worker.py index fcc4019..9beb6ff 100644 --- a/worker.py +++ b/worker.py @@ -8,15 +8,12 @@ import tempfile import threading import time +import unicodedata import uuid -try: - import requests -except ImportError: - requests = None - +from callback_transport import CallbackFailed, CallbackRefused, post_scan from scanner import ScanError, ScannerManager -from utils import SCAN_JOB_DIRECTORY_PREFIX, get_logger, load_config +from utils import APP_VERSION, SCAN_JOB_DIRECTORY_PREFIX, get_logger, load_config logger = get_logger() @@ -26,8 +23,17 @@ ANY_ORIGIN = object() # Covers child startup and a graceful TWAIN close after the child's own deadline. SCAN_TIMEOUT_GRACE_SECONDS = 15 -# (connect, read) for posting a finished scan to its callback URL. -CALLBACK_TIMEOUT_SECONDS = (5, 30) +# Callbacks being sent at once; a scan finished while both are busy is not sent. +MAX_CALLBACKS_IN_FLIGHT = 2 +# A downloaded result may be downloaded once more within this many seconds, for +# a client whose first download was cut off; then it is freed. +RESULT_RETRY_GRACE_SECONDS = 30 +MAX_RESULT_DOWNLOADS = 2 +MAX_DOC_ID_LENGTH = 200 +# Folders a scan child leaves behind when ScanLink itself was killed. +STALE_DIRECTORY_PREFIXES = (SCAN_JOB_DIRECTORY_PREFIX, "scanlink-pages-") +STALE_DIRECTORY_MIN_AGE_SECONDS = 30 +STALE_SWEEP_INTERVAL_SECONDS = 600 # Optional compatibility hook for future push-based status updates. _status_callback = None @@ -54,7 +60,127 @@ def __init__(self, active_job_id=None): class CallbackNotAllowedError(Exception): def __init__(self): - super().__init__("callback_url must point to a website linked to ScanLink.") + super().__init__("callback_url must be an https URL on a website linked to ScanLink.") + + +class InvalidDocIdError(ValueError): + def __init__(self): + super().__init__( + f"doc_id must be a whole number or text of at most {MAX_DOC_ID_LENGTH} characters without control characters." + ) + + +def clean_doc_id(value): + """A ``doc_id`` that is safe to store, log and echo as JSON; raises ``InvalidDocIdError``.""" + if value is None or value == "": + return None + if isinstance(value, bool): + raise InvalidDocIdError() + if isinstance(value, int): + if abs(value) >= 2 ** 63: + raise InvalidDocIdError() + return value + if not isinstance(value, str) or len(value) > MAX_DOC_ID_LENGTH: + raise InvalidDocIdError() + if any(unicodedata.category(ch) in ("Cc", "Cf", "Cs", "Zl", "Zp") for ch in value): + raise InvalidDocIdError() + return value + + +def sweep_stale_directories(temp_dir=None, min_age_seconds=STALE_DIRECTORY_MIN_AGE_SECONDS, now=None): + """Remove scan folders a killed ScanLink left in the temp directory; returns their names.""" + temp_dir = temp_dir or tempfile.gettempdir() + now = time.time() if now is None else now + removed = [] + try: + names = os.listdir(temp_dir) + except OSError: + return removed + for name in names: + if not name.startswith(STALE_DIRECTORY_PREFIXES): + continue + path = os.path.join(temp_dir, name) + try: + if not os.path.isdir(path) or os.path.islink(path): + continue + if now - os.path.getmtime(path) < min_age_seconds: + continue + except OSError: + continue + shutil.rmtree(path, ignore_errors=True) + if not os.path.exists(path): + removed.append(name) + if removed: + logger.info("Removed %s scan folder(s) left by an earlier ScanLink: %r", len(removed), removed) + return removed + + +class _KillOnCloseJob: + """A Windows job object that ends every scan child when ScanLink's own process ends.""" + + def __init__(self): + self._handle = None + self._kernel32 = None + if os.name != "nt": + return + try: + import ctypes + from ctypes import wintypes + + class BasicLimits(ctypes.Structure): + _fields_ = [ + ("PerProcessUserTimeLimit", ctypes.c_int64), + ("PerJobUserTimeLimit", ctypes.c_int64), + ("LimitFlags", wintypes.DWORD), + ("MinimumWorkingSetSize", ctypes.c_size_t), + ("MaximumWorkingSetSize", ctypes.c_size_t), + ("ActiveProcessLimit", wintypes.DWORD), + ("Affinity", ctypes.c_size_t), + ("PriorityClass", wintypes.DWORD), + ("SchedulingClass", wintypes.DWORD), + ] + + class IoCounters(ctypes.Structure): + _fields_ = [(name, ctypes.c_uint64) for name in ( + "ReadOperationCount", "WriteOperationCount", "OtherOperationCount", + "ReadTransferCount", "WriteTransferCount", "OtherTransferCount", + )] + + class ExtendedLimits(ctypes.Structure): + _fields_ = [ + ("BasicLimitInformation", BasicLimits), + ("IoInfo", IoCounters), + ("ProcessMemoryLimit", ctypes.c_size_t), + ("JobMemoryLimit", ctypes.c_size_t), + ("PeakProcessMemoryUsed", ctypes.c_size_t), + ("PeakJobMemoryUsed", ctypes.c_size_t), + ] + + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.CreateJobObjectW.restype = wintypes.HANDLE + kernel32.CreateJobObjectW.argtypes = (wintypes.LPVOID, wintypes.LPCWSTR) + kernel32.SetInformationJobObject.argtypes = (wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD) + kernel32.AssignProcessToJobObject.argtypes = (wintypes.HANDLE, wintypes.HANDLE) + handle = kernel32.CreateJobObjectW(None, None) + if not handle: + return + limits = ExtendedLimits() + limits.BasicLimitInformation.LimitFlags = 0x2000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE + if not kernel32.SetInformationJobObject(handle, 9, ctypes.byref(limits), ctypes.sizeof(limits)): + kernel32.CloseHandle(handle) + return + self._handle, self._kernel32 = handle, kernel32 + except Exception: + logger.warning("Could not create the scan child job object", exc_info=True) + + def assign(self, process): + if self._handle is None: + return False + try: + return bool(self._kernel32.AssignProcessToJobObject(self._handle, int(process._handle))) + except Exception: + logger.warning("Could not tie the scan child to ScanLink's lifetime", exc_info=True) + return False class GuiTaskTimeoutError(Exception): @@ -78,6 +204,9 @@ def __init__(self, gui_task_queue, callback_guard=None): # callback is refused. self.callback_guard = callback_guard self.callback_thread = None + self._callback_slots = threading.BoundedSemaphore(MAX_CALLBACKS_IN_FLIGHT) + self._child_job = _KillOnCloseJob() + self._next_sweep_at = 0.0 self.jobs = {} self.jobs_lock = threading.Lock() self.scanner_manager = ScannerManager() @@ -97,6 +226,7 @@ def __init__(self, gui_task_queue, callback_guard=None): def submit_job( self, doc_id=None, callback_url=None, metadata=None, source="api", origin=None ): + doc_id = clean_doc_id(doc_id) if callback_url and not self._callback_allowed(callback_url, origin): raise CallbackNotAllowedError() @@ -131,7 +261,7 @@ def submit_job( } self.scan_queue.put(job_id) - logger.info("Job %s queued (source=%s, doc_id=%s)", job_id, source, doc_id) + logger.info("Job %s queued (source=%r, doc_id=%r)", job_id, source, doc_id) emit_status(job_id, "queued", doc_id=doc_id) return self.get_job(job_id) @@ -142,6 +272,12 @@ def get_job(self, job_id, origin=ANY_ORIGIN): return self._serialize_job(job) if job else None def consume_result(self, job_id, origin=ANY_ORIGIN): + """The job and its PDF, counting a download. + + The PDF can be downloaded twice within ``RESULT_RETRY_GRACE_SECONDS`` of + the first download, so a download cut off mid-way can be retried; then + its bytes are freed and later downloads get no bytes. + """ with self.jobs_lock: self._cleanup_expired_jobs_locked() job = self._visible_job_locked(job_id, origin) @@ -150,12 +286,27 @@ def consume_result(self, job_id, origin=ANY_ORIGIN): result_bytes = job.get("result_bytes") if result_bytes: - job["result_bytes"] = None - job["result_retrieved_at"] = time.time() + downloads = job.get("result_downloads", 0) + 1 + job["result_downloads"] = downloads + if downloads == 1: + job["result_retrieved_at"] = time.time() + job["result_retrieved_mono"] = time.monotonic() + if downloads >= MAX_RESULT_DOWNLOADS: + job["result_bytes"] = None job["updated_at"] = time.time() return self._serialize_job(job), result_bytes + def peek_result(self, job_id, origin=ANY_ORIGIN): + """The job and its PDF's size (None when gone) without counting a download.""" + with self.jobs_lock: + self._cleanup_expired_jobs_locked() + job = self._visible_job_locked(job_id, origin) + if not job: + return None, None + result_bytes = job.get("result_bytes") + return self._serialize_job(job), len(result_bytes) if result_bytes else None + def is_busy(self): with self.jobs_lock: return self._find_active_job_id_locked() is not None @@ -165,11 +316,13 @@ def is_twain_available(self): def run(self): logger.info("ScanWorker started") + self._sweep_when_idle(min_age_seconds=0) while self.running: try: job_id = self.scan_queue.get(timeout=0.5) except queue.Empty: self._cleanup_expired_jobs() + self._sweep_when_idle() continue if job_id is None: @@ -184,6 +337,16 @@ def run(self): logger.info("ScanWorker stopped") + def _sweep_when_idle(self, min_age_seconds=STALE_DIRECTORY_MIN_AGE_SECONDS): + now = time.monotonic() + if now < self._next_sweep_at or self.current_job_id is not None: + return + with self.active_scan_process_lock: + if self.active_scan_process is not None: + return + self._next_sweep_at = now + STALE_SWEEP_INTERVAL_SECONDS + sweep_stale_directories(min_age_seconds=min_age_seconds) + def stop(self): self.running = False self._stop_active_scan_process() @@ -302,6 +465,8 @@ def _run_scan_subprocess(self, job_id, on_progress): request_payload = { "job_id": job_id, "scan_timeout_seconds": self.scan_timeout_seconds, + # The child stops and removes this folder if this process disappears. + "parent_pid": os.getpid(), } with open(request_path, "w", encoding="utf-8") as request_file: json.dump(request_payload, request_file, indent=2) @@ -312,30 +477,36 @@ def _run_scan_subprocess(self, job_id, on_progress): self._build_scan_subprocess_command(work_dir), cwd=os.path.dirname(os.path.abspath(__file__)), ) + self._child_job.assign(process) with self.active_scan_process_lock: self.active_scan_process = process + def apply_state(state): + nonlocal last_state_signature, last_progress_at, last_state_status + if not state or not isinstance(state.get("status"), str): + return + signature = json.dumps( + [ + state.get("status"), + state.get("page_count", 0), + (state.get("error") or {}).get("code"), + ], + sort_keys=True, + ) + if signature == last_state_signature: + return + last_state_signature = signature + last_progress_at = time.monotonic() + last_state_status = state.get("status") + progress_payload = {} + if isinstance(state.get("page_count"), int): + progress_payload["page_count"] = state["page_count"] + if "error" in state: + progress_payload["error"] = state["error"] + on_progress(state["status"], **progress_payload) + while True: - state = self._read_state_file(state_path) - if state: - signature = json.dumps( - [ - state.get("status"), - state.get("page_count", 0), - (state.get("error") or {}).get("code"), - ], - sort_keys=True, - ) - if signature != last_state_signature: - last_state_signature = signature - last_progress_at = time.monotonic() - last_state_status = state.get("status") - progress_payload = {} - if "page_count" in state: - progress_payload["page_count"] = state["page_count"] - if "error" in state: - progress_payload["error"] = state["error"] - on_progress(state["status"], **progress_payload) + apply_state(self._read_state_file(state_path)) return_code = process.poll() if return_code is not None: @@ -362,6 +533,8 @@ def _run_scan_subprocess(self, job_id, on_progress): time.sleep(0.25) final_state = self._read_state_file(state_path) + # The child's last state carries the page count the 250 ms polls may have missed. + apply_state(final_state) if process.returncode == 0 and os.path.exists(result_path): with open(result_path, "rb") as result_file: return io.BytesIO(result_file.read()) @@ -439,12 +612,18 @@ def _start_callback(self, job_id, pdf_bytes): for key in ("job_id", "doc_id", "page_count", "callback_url", "origin") } job["callback_state"] = "sending" - thread = threading.Thread( - target=self._send_callback, - args=(delivery, pdf_bytes), - daemon=True, - name=f"ScanLinkCallback-{job_id[:8]}", - ) + if not self._callback_slots.acquire(blocking=False): + logger.warning("Not sending job %s: %s callbacks are already being sent", job_id, MAX_CALLBACKS_IN_FLIGHT) + self._record_callback(job_id, "failed", reason="busy") + return + + def deliver(): + try: + self._send_callback(delivery, pdf_bytes) + finally: + self._callback_slots.release() + + thread = threading.Thread(target=deliver, daemon=True, name=f"ScanLinkCallback-{job_id[:8]}") self.callback_thread = thread thread.start() @@ -456,46 +635,47 @@ def _send_callback(self, job, pdf_bytes): # The website may have been unlinked while the scanner ran. if not self._callback_allowed(callback_url, job.get("origin")): logger.warning( - "Not sending job %s to %s: that website is not linked to ScanLink", job_id, callback_url + "Not sending job %s to %r: that website is not linked to ScanLink", job_id, callback_url ) self._record_callback(job_id, "refused", reason="not_linked") return - if requests is None: - logger.warning("requests is not installed; cannot send job %s to its callback", job_id) - self._record_callback(job_id, "failed", reason="unavailable") - return - files = {"pdf": (f"scan_{job_id}.pdf", pdf_bytes, "application/pdf")} - data = { - "job_id": job_id, - "doc_id": job.get("doc_id"), - "page_count": job.get("page_count", 0), - "status": "completed", - } + fields = [("job_id", job_id)] + if job.get("doc_id") is not None: + fields.append(("doc_id", job["doc_id"])) + fields += [("page_count", job.get("page_count", 0)), ("status", "completed")] + files = [("pdf", (f"scan_{job_id}.pdf", pdf_bytes, "application/pdf"))] try: - # No redirects: a linked website must not hand the document on elsewhere. - response = requests.post( + status_code = post_scan( callback_url, - files=files, - data=data, - timeout=CALLBACK_TIMEOUT_SECONDS, - allow_redirects=False, + fields, + files, + delivery_id=job_id, + user_agent=f"ScanLink/{APP_VERSION}", ) - except Exception as exc: - logger.error("Could not send job %s to %s: %s", job_id, callback_url, exc) + except CallbackRefused as exc: + logger.warning("Not sending job %s to %r: %s", job_id, callback_url, exc) + self._record_callback(job_id, "refused", reason=exc.reason) + return + except CallbackFailed as exc: + logger.error("Could not send job %s to %r: %s", job_id, callback_url, exc) + self._record_callback(job_id, "failed", reason="unreachable") + return + except Exception: + logger.exception("Could not send job %s to %r", job_id, callback_url) self._record_callback(job_id, "failed", reason="unreachable") return - if 200 <= response.status_code < 300: - logger.info("Sent job %s to %s", job_id, callback_url) - self._record_callback(job_id, "delivered", status_code=response.status_code) + if 200 <= status_code < 300: + logger.info("Sent job %s to %r", job_id, callback_url) + self._record_callback(job_id, "delivered", status_code=status_code) else: logger.warning( "Callback for job %s answered %s; the result stays available to poll", job_id, - response.status_code, + status_code, ) - self._record_callback(job_id, "failed", status_code=response.status_code) + self._record_callback(job_id, "failed", status_code=status_code) def _record_callback(self, job_id, state, **detail): with self.jobs_lock: @@ -526,6 +706,8 @@ def _update_job(self, job_id, **updates): return None job.update(updates) job["updated_at"] = updates.get("updated_at", time.time()) + if updates.get("completed_at") is not None: + job["finished_mono"] = time.monotonic() return self._serialize_job(job) def _serialize_job(self, job): @@ -558,7 +740,9 @@ def _cleanup_expired_jobs(self): self._cleanup_expired_jobs_locked() def _cleanup_expired_jobs_locked(self): - now = time.time() + # Monotonic, so a wall-clock jump (time sync, resume) neither deletes an + # unread result nor keeps one in memory for days. + now = time.monotonic() expired_job_ids = [] for job_id, job in self.jobs.items(): @@ -566,13 +750,20 @@ def _cleanup_expired_jobs_locked(self): if status not in TERMINAL_STATUSES: continue - completed_at = job.get("completed_at") or job.get("updated_at") or now - age_seconds = now - completed_at + finished = job.setdefault("finished_mono", now) + retrieved = job.get("result_retrieved_mono") + if ( + job.get("result_bytes") is not None + and retrieved is not None + and now - retrieved >= RESULT_RETRY_GRACE_SECONDS + ): + job["result_bytes"] = None + ttl_seconds = self.job_ttl_seconds if status == "completed" and job.get("result_bytes") is not None: ttl_seconds = self.result_ttl_seconds - if age_seconds >= ttl_seconds: + if now - finished >= ttl_seconds: expired_job_ids.append(job_id) for job_id in expired_job_ids: From 851b1ae22649f439583975102aa107d1838332ad Mon Sep 17 00:00:00 2001 From: debeski Date: Fri, 27 Nov 2026 22:58:22 +0200 Subject: [PATCH 2/2] release: ScanLink 0.8.1b2 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- VERSION | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 879825f..819be96 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ This file owns the release history for `ScanLink`. -## Unreleased +## v0.8.1b2 - **Callbacks Reach Public HTTPS Websites Only (security, R2-010)**: a linked website could list `http://127.0.0.1:…`, `localhost`, private, link-local or metadata addresses, or ScanLink itself, and every scan was then posted there from the operator's computer without `Origin` or `Sec-Fetch-*`; a callback to `http://localhost:5000/shutdown` stopped ScanLink. New `callback_transport` module: `check_callback_url` requires `https` and refuses `localhost`, `*.localhost` and non-public address literals in any spelling (`127.1`, `2130706433`, `[::ffff:127.0.0.1]`) at submission (`400 callback_not_allowed`); `post_scan` resolves the host itself, refuses the delivery if any address is loopback, private, CGNAT, link-local, unique-local, multicast, reserved, unspecified, an embedded IPv4 of those (mapped, NAT64, 6to4, Teredo) or one of this computer's own, connects to the checked address with TLS verified for the host name and re-checks the peer, so DNS rebinding cannot reach this computer (`callback.state: refused`, `reason: blocked_address`). Deliveries carry `X-ScanLink-Delivery`, and every endpoint answers such a request with `403 local_only`. Callbacks use the standard library instead of `requests` and never a proxy. - **Widening A Linked List Asks Again (security, R2-054)**: `SiteRegistry.link` replaced a linked website's list without a window, so one approval let XSS on that site grant the scanner to any origin. A list that gains a site now opens the approval window again, naming the added sites (`confirm(..., added_sites=…)`); until the operator allows them the website stays linked with its approved list, and a declined widening answers `403 link_declined`. Shortening a list stays silent. diff --git a/VERSION b/VERSION index 2afe79a..a3f6317 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.8.1b1 +0.8.1b2