diff --git a/CHANGELOG.md b/CHANGELOG.md index cf96abc..f6b9c5d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,22 @@ This file owns the release history for `ScanLink`. +## Unreleased + +- **No Website Can Scan Until Allowed (security)**: `cors_origins` defaults to `[]` and wildcards are ignored, so a saved `["*"]` no longer lets every website the operator opens start a scan and download it (silently once a default scanner is saved). New `POST /link` (`sites.SiteRegistry`): a website asks to link, naming the sites its administrator allows; an unlinked one opens an approval window in ScanLink (`gui.dialogs.confirm_site_link`) naming the requesting origin as the browser sent it, waits up to 120 s, one window at a time, and a declined site cannot ask again for 10 minutes. A linked site replaces its list without asking. Links persist in `config.json` `linked_sites`; the tray menu's **Linked Websites** lists and unlinks them. `GET /health` reports `link` for the requesting site. The bundled `scanlink.js` adds `link(sites)` and reports `origin_not_allowed` from `checkHealth()`. Upgrading operators approve each website once. +- **Loopback Host Check**: `server.create_app()` refuses every request whose `Host` header is not `localhost`, `127.0.0.1` or `[::1]` with `403 invalid_host`, so a DNS-rebound page cannot reach the API as a same-origin client. +- **Local-Only Control Endpoints**: `POST /shutdown` and `POST /internal/protocol/scan` refuse any request carrying `Origin` or `Sec-Fetch-Site` with `403 local_only`, so a cross-site form post can no longer shut ScanLink down; the protocol forwarder and local scripts send neither header. +- **Scan Ownership By Origin**: `ScanWorker.submit_job()` records the requesting `Origin`; `GET /scan/` and `/result` answer `404 job_not_found` to any other origin, and `409 busy` includes `active_job_id` only for the job's own origin, so a website can no longer learn, follow and download another website's scan. +- **Server-Side Origin Allow-List**: Browser-endpoint requests from a website that is not allowed are refused with `403 origin_not_allowed` before any work, instead of only omitting CORS headers; the refusal carries CORS headers so the page can read it and offer to link. +- **Request Body Limit**: `MAX_CONTENT_LENGTH` is 64 KB, answered as `413 payload_too_large`; a 64 MB `metadata` body was previously accepted, kept with the job for its 15-minute TTL and returned by every status poll. HTTP errors (`404`, `405`, `413`, `500`) now use the JSON error shape with CORS headers. +- **Private Network Access Preflight**: Preflights carrying `Access-Control-Request-Private-Network: true` receive `Access-Control-Allow-Private-Network: true`. +- **Non-Blocking TLS Accept**: `LoopbackServer` accepts HTTPS connections without handshaking and `LoopbackRequestHandler` completes the handshake in the connection's own thread; one TCP client that never sent a TLS hello previously stalled every HTTPS request indefinitely. +- **Connection Timeout**: `LoopbackRequestHandler` sets a 30-second socket timeout (`REQUEST_TIMEOUT_SECONDS`), so half-sent or idle connections no longer hold a server thread forever. +- **Compressed Page Capture**: `ScannerManager` encodes each captured page to JPEG on arrival (`_encode_page`) and `_create_pdf` embeds the JPEG files through `drawImage(path)` instead of decoding them again through `ImageReader`; the scan child's peak memory for 20 pages at 300 DPI drops from about 2 GB to 0.2 GB, which previously exhausted x86 builds. Image streams in the PDF are unchanged. +- **Scan Worker Directory Check**: `scan_runtime.run_scan_job()` refuses any `--scan-worker-dir` that is not a `scanlink-job-*` directory directly inside the temp directory, so an argument injected through an unescaped `scanlink://` launch cannot read a request from, or write a scanned PDF to, another folder or a network share. +- **Helper Identity Check**: `protocol_handler.is_existing_instance_running()` and `forward_protocol_command()` accept only ScanLink-shaped answers, so another program returning `200` on port 5000 no longer makes a new ScanLink exit as a duplicate or swallow a protocol scan. +- **Protocol Log Lines**: `parse_protocol_url()` logs URLs and parsed values with `%r`, so a `scanlink://` URL with encoded line breaks cannot forge `scanner.log` entries. + ## v0.8.0b2 - **Scan Deadline Grace**: `ScanWorker` adds `SCAN_TIMEOUT_GRACE_SECONDS` (15s) to the parent's `scan_timeout_seconds` kill limit so the child's own deadline closes TWAIN and reports its error before forced termination; `gui_task_timeout_seconds` is unchanged. diff --git a/build_exe.py b/build_exe.py index a859a32..887fae2 100644 --- a/build_exe.py +++ b/build_exe.py @@ -172,6 +172,7 @@ def build_pyinstaller_args(build_name): "--hidden-import=PIL.Image", "--hidden-import=PIL.ImageDraw", "--hidden-import=protocol_handler", + "--hidden-import=sites", "--hidden-import=flask", "--hidden-import=werkzeug", "--hidden-import=jinja2", diff --git a/docs/api.md b/docs/api.md index bf9cbe8..cf27cbf 100644 --- a/docs/api.md +++ b/docs/api.md @@ -11,6 +11,8 @@ ScanLink exposes a browser-friendly local API for starting scans, polling status The JavaScript helper also defaults to `http://localhost:5000` and `https://localhost:5443`. The server binds to `127.0.0.1`. +Every request must address the helper as `localhost`, `127.0.0.1` or `[::1]` in its `Host` header (any port). Other host names, such as a DNS name rebound to `127.0.0.1`, receive `403 invalid_host`. + ## Error Shape Errors use this shape: @@ -24,7 +26,9 @@ Errors use this shape: } ``` -Some errors include extra fields such as `active_job_id` or `current_status`. +Some errors include extra fields such as `active_job_id` or `current_status`. Protocol-level errors (unknown route `404`, wrong method `405`, oversized body `413`, internal error `500`) use the same shape, with CORS headers on browser endpoints. + +Request bodies are limited to 64 KB. ## GET /health @@ -39,10 +43,16 @@ Response: "busy": false, "http_enabled": true, "https_enabled": false, - "twain_available": true + "twain_available": true, + "link": {"linked": true, "sites": ["https://archive.example", "https://crm.example"]} } ``` +`link` describes the requesting website: whether it is linked itself and, if so, +the sites its link allows. A website allowed only through `cors_origins` or +another site's list reports `{"linked": false, "sites": []}`. Requests without +`Origin` receive no `link`. + ## POST /scan Starts a scan job. @@ -88,6 +98,7 @@ Errors: | 400 | `invalid_callback` | Callback URL was not a string or could not be parsed. | | 400 | `invalid_metadata` | `metadata` was provided but is not an object. | | 409 | `busy` | Another scan job is queued or running. | +| 413 | `payload_too_large` | Request body exceeded 64 KB. | | 415 | `json_required` | Request did not use JSON. | Busy response: @@ -102,10 +113,14 @@ Busy response: } ``` +`active_job_id` is included only when the request comes from the same `Origin` that started the active job (or, for jobs started without an `Origin`, from a local tool that sends none). + ## GET /scan/ Returns job status. +A job belongs to the `Origin` that started it. Status and result requests from any other `Origin`, or without an `Origin` for a browser-started job, receive `404 job_not_found`, so one website cannot follow or download another website's scan. + Response: ```json @@ -172,6 +187,8 @@ 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. + ## Scan Error Codes Errors from the scanner/runtime layer can appear inside the job `error` object: @@ -193,24 +210,78 @@ Errors from the scanner/runtime layer can appear inside the job `error` object: | `scan_worker_crashed` | Child scan process exited unexpectedly. | | `unexpected_error` | Unhandled worker exception. | -## CORS +## Allowed websites + +A website may use the browser endpoints when it is listed in +`%LOCALAPPDATA%\ScanLink\config.json` or linked: + +```json +{ + "cors_origins": ["https://archive.example"], + "linked_sites": { + "https://archive.example": { + "sites": ["https://archive.example", "https://crm.example"], + "linked_at": "2026-11-14T12:00:00Z" + } + } +} +``` + +- `cors_origins` is set by hand or by IT and needs a restart. It is empty by + default. Entries must be website origins (`scheme://host[:port]`); `"*"` and + other wildcards are ignored, so no setting lets every website scan. +- `linked_sites` is written by [`POST /link`](#post-link) after the operator + approves a website, and by the tray menu's **Linked Websites → Unlink**. Each + linked website allows itself and the sites in its `sites` list. + +Every browser endpoint answers CORS for any well-formed `Origin`, including +preflights, so an unlinked website can read why it was refused. Requests from a +website that is neither listed nor linked receive `403 origin_not_allowed` before +any work is done; only `POST /link` is open to every website. Preflights carrying +`Access-Control-Request-Private-Network: true` are answered with +`Access-Control-Allow-Private-Network: true`, as Chromium's Private Network +Access requires for a public website calling the loopback helper. -Browser endpoints support CORS for: +Job ownership keeps each allowed website away from scans started by others. -- `/health` -- `/scan` -- `/scan/` -- `/scan//result` +## POST /link -Allowed origins come from `%LOCALAPPDATA%\ScanLink\config.json`: +Asks to link the requesting website, named by the browser's `Origin` header. + +Request: ```json { - "cors_origins": ["*"] + "sites": ["https://crm.example"] } ``` -When `cors_origins` is not `["*"]`, the request `Origin` must exactly match an entry in the list. +`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. + +Success: + +```json +{ + "linked": true, + "prompted": true, + "sites": ["https://archive.example", "https://crm.example"] +} +``` + +Errors: + +| Status | Code | Meaning | +| --- | --- | --- | +| `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. | +| `408` | `link_timeout` | Nobody answered the window within two minutes. | +| `409` | `link_pending` | Another website's approval window is open. | +| `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 115c3e3..e6869a9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -67,6 +67,17 @@ worker.py This subprocess boundary protects the tray/API process from scanner driver crashes, stuck TWAIN calls, and long-running acquisition operations. +`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 +`scanlink://` launch or a network share path, exits with code 1 before reading +or writing anything. + +The child compresses each page to JPEG (quality 85) as soon as it is captured and +embeds those JPEG files in the PDF unchanged, so its memory grows with the +compressed page size rather than with decoded images (about 26 MB per A4 page at +300 DPI color). Long ADF batches therefore fit in a 32-bit (x86) build. + ## Thread Model Main process: @@ -125,7 +136,8 @@ Defaults are provided in `utils.load_config()`: "default_scanner": null, "show_scanner_ui": false, "paper_protection": false, - "cors_origins": ["*"], + "cors_origins": [], + "linked_sites": {}, "job_ttl_seconds": 900, "result_ttl_seconds": 300, "scan_timeout_seconds": 600, @@ -158,6 +170,13 @@ HTTPS: 127.0.0.1:5443 ``` +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. + On normal startup the server thread starts HTTP first, then prepares a trusted HTTPS identity automatically. A one-year self-signed **server** certificate (`BasicConstraints CA=False`, serverAuth EKU, no certificate-signing usage) @@ -200,8 +219,8 @@ When launched with a `scanlink://` URL: 1. `main.py` parses the URL with `protocol_handler.parse_protocol_url()`. 2. It tries to forward the command to `http://127.0.0.1:5000/internal/protocol/scan`. -3. If forwarding succeeds, the new process exits. -4. If no instance is running, the new process becomes the tray instance and queues the protocol scan after startup. +3. If forwarding succeeds, the new process exits. Forwarding succeeds only on a ScanLink answer: `202` with a `job_id`, or `409` with error code `busy`. +4. If no instance is running, the new process becomes the tray instance and queues the protocol scan after startup. An instance counts as running only when `/health` returns ScanLink's JSON (`status: ok` with `version` and `twain_available`), so another program answering on port 5000 does not make ScanLink exit. This prevents duplicate tray apps and competing scanner sessions. diff --git a/docs/developer-guide.md b/docs/developer-guide.md index 9d39c6e..c42a016 100644 --- a/docs/developer-guide.md +++ b/docs/developer-guide.md @@ -191,8 +191,9 @@ Downloading `/scan//result` consumes the stored PDF. A second download f ## Operational Notes -- The API is bound to `127.0.0.1`, not a public network interface. -- CORS defaults to `["*"]` in `%LOCALAPPDATA%\ScanLink\config.json`. +- The API is bound to `127.0.0.1`, not a public network interface, and answers only requests whose `Host` is `localhost`, `127.0.0.1` or `[::1]`. +- No website can scan until it is allowed: the operator approves a website once through [`POST /link`](api.md#post-link), or IT lists it in `cors_origins` in `%LOCALAPPDATA%\ScanLink\config.json`; see [Allowed websites](api.md#allowed-websites). The bundled client's `link(sites)` sends the request, and its `checkHealth()` reports `origin_not_allowed` for a website that is not allowed yet. +- A scan job belongs to the `Origin` that started it; poll status and download the result from the same page origin. - The first scan may show a scanner selection dialog. - If the user selects "Set as default scanner", later scans skip scanner selection. - Tray settings control source, side, color mode, resolution, scanner UI visibility, paper protection, startup, and diagnostics. diff --git a/gui/dialogs.py b/gui/dialogs.py index c4007e8..a7cb12e 100644 --- a/gui/dialogs.py +++ b/gui/dialogs.py @@ -124,3 +124,66 @@ def show_text_dialog(title, body, width=760, height=520): dlg.focus_force() dlg.grab_set() 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.""" + 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?") + 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="Its administrator also allows these websites:", + wraplength=440, + 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) + 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, + justify=tk.LEFT, + ).pack(anchor=tk.W, pady=(10, 0)) + + def finish(value): + answer["value"] = value + if dlg.winfo_exists(): + dlg.destroy() + + 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) + deny = tk.Button(buttons, text="Don't allow", command=lambda: finish(False), width=12) + deny.pack(side=tk.LEFT, padx=8) + dlg.protocol("WM_DELETE_WINDOW", lambda: finish(False)) + dlg.bind("", lambda event: finish(False)) + dlg.after(int(timeout_seconds * 1000), lambda: finish(None)) + + dlg.update_idletasks() + width, height = dlg.winfo_reqwidth(), dlg.winfo_reqheight() + x = max((dlg.winfo_screenwidth() // 2) - (width // 2), 0) + y = max((dlg.winfo_screenheight() // 2) - (height // 2), 0) + dlg.geometry(f"+{x}+{y}") + dlg.deiconify() + dlg.wait_visibility() + 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 cd30170..d3a7fee 100644 --- a/main.py +++ b/main.py @@ -15,8 +15,9 @@ ) from scan_runtime import run_scan_job from server import run_server +from sites import LINK_PROMPT_SECONDS, SiteRegistry from tray import TrayApp -from utils import APP_VERSION, ensure_ssl_certificates, get_logger, setup_logging +from utils import APP_VERSION, ensure_ssl_certificates, get_logger, load_config, setup_logging from worker import ScanWorker, set_status_callback @@ -87,13 +88,24 @@ def show_setup_message(): set_status_callback(None) - tray = TrayApp(worker, shutdown_event, https_retry_event) + def confirm_link(origin, other_sites): + from gui.dialogs import confirm_site_link + + return worker.run_gui_task( + lambda: confirm_site_link(origin, other_sites, LINK_PROMPT_SECONDS), + timeout=LINK_PROMPT_SECONDS + 15, + ) + + config = load_config() + sites = SiteRegistry(config["cors_origins"], config["linked_sites"], confirm=confirm_link) + + tray = TrayApp(worker, shutdown_event, https_retry_event, sites=sites) worker.start() server_thread = threading.Thread( target=run_server, - args=(worker, shutdown_event, https_retry_event, offer_https_retry), + args=(worker, shutdown_event, https_retry_event, offer_https_retry, sites), daemon=True, name="LoopbackServerManager", ) diff --git a/protocol_handler.py b/protocol_handler.py index 07df043..48c91c8 100644 --- a/protocol_handler.py +++ b/protocol_handler.py @@ -42,10 +42,10 @@ def parse_protocol_url(url): "doc_id": doc_id, "callback_url": callback_url, } - logger.info(f"Parsed protocol URL: {result}") + logger.info("Parsed protocol URL: %r", result) return result except Exception as exc: - logger.error(f"Failed to parse protocol URL '{url}': {exc}") + logger.error("Failed to parse protocol URL %r: %s", url, exc) return None @@ -64,6 +64,14 @@ def extract_protocol_url_from_args(args): return None +def _json_object(response): + try: + payload = response.json() + except ValueError: + return {} + return payload if isinstance(payload, dict) else {} + + def is_existing_instance_running(timeout=1.0): """Probe the loopback HTTP health endpoint for an already-running helper.""" if requests is None: @@ -72,9 +80,16 @@ def is_existing_instance_running(timeout=1.0): try: response = requests.get(HEALTH_ENDPOINT, timeout=timeout) - return response.ok except requests.RequestException: return False + # Another program on port 5000 must not make ScanLink exit as a duplicate. + health = _json_object(response) + return ( + response.ok + and health.get("status") == "ok" + and "version" in health + and "twain_available" in health + ) def forward_protocol_command(command, timeout=3.0): @@ -90,7 +105,13 @@ def forward_protocol_command(command, timeout=3.0): try: response = requests.post(INTERNAL_PROTOCOL_ENDPOINT, json=command, timeout=timeout) - if response.ok or response.status_code == 409: + payload = _json_object(response) + error = payload.get("error") + if (response.status_code == 202 and payload.get("job_id")) or ( + response.status_code == 409 + and isinstance(error, dict) + and error.get("code") == "busy" + ): logger.info( "Forwarded protocol command to existing instance with response %s", response.status_code, diff --git a/scan_runtime.py b/scan_runtime.py index 9a785a8..fd090ae 100644 --- a/scan_runtime.py +++ b/scan_runtime.py @@ -1,12 +1,13 @@ import json import os import sys +import tempfile import time import tkinter as tk from gui.dialogs import init_gui from scanner import ScanError, ScannerManager -from utils import get_logger +from utils import SCAN_JOB_DIRECTORY_PREFIX, get_logger REQUEST_FILE = "request.json" STATE_FILE = "state.json" @@ -43,7 +44,23 @@ def _write_result(work_dir, pdf_buffer): result_file.write(pdf_buffer.getvalue()) +def is_job_directory(work_dir): + """True only for a directory ScanWorker created with tempfile.mkdtemp().""" + path = os.path.abspath(work_dir) + return ( + os.path.basename(path).startswith(SCAN_JOB_DIRECTORY_PREFIX) + and os.path.normcase(os.path.dirname(path)) + == os.path.normcase(os.path.abspath(tempfile.gettempdir())) + and os.path.isdir(path) + ) + + def run_scan_job(work_dir): + # A launcher that passes an unescaped scanlink:// URL could inject + # --scan-worker-dir pointing at another folder or a remote share. + if not is_job_directory(work_dir): + logger.error("Refusing scan worker directory outside ScanLink's temp jobs: %r", work_dir) + return 1 root = None try: request = _read_request(work_dir) diff --git a/scanner.py b/scanner.py index 248dc52..f224f6b 100644 --- a/scanner.py +++ b/scanner.py @@ -34,6 +34,8 @@ logger = get_logger() +PAGE_JPEG_QUALITY = 85 + class ScanError(Exception): def __init__(self, code, message, status="failed"): @@ -256,12 +258,6 @@ def scan_to_pdf(self, request_id, progress_callback=None, deadline=None): return self._create_pdf(images) except Exception as exc: raise ScanError("pdf_generation_failed", f"Failed to generate PDF: {exc}") from exc - finally: - for image in images: - try: - image.close() - except Exception: - pass def _open_source(self, sm, config, progress_callback=None, deadline=None): default_scanner = config.get("default_scanner") @@ -451,10 +447,7 @@ def after_transfer(twain_image, _more): code="acquire_timeout", message="Timed out while processing the scanned page.", ) - image = self._twain_image_to_pil(twain_image) - if image.mode != "RGB": - image = image.convert("RGB") - images.append(image) + images.append(self._encode_page(self._twain_image_to_pil(twain_image))) logger.info("Captured page %s via native transfer", len(images)) if progress_callback: progress_callback("page_scanned", page_count=len(images)) @@ -498,8 +491,7 @@ def after_transfer(_more): try: with PilImage.open(temp_path) as pil_image: pil_image.load() - image = pil_image.convert("RGB") if pil_image.mode != "RGB" else pil_image.copy() - images.append(image) + images.append(self._encode_page(pil_image)) logger.info("Captured page %s via file transfer", len(images)) if progress_callback: progress_callback("page_scanned", page_count=len(images)) @@ -642,33 +634,52 @@ def _check_deadline(self, deadline, code, message): if deadline and time.monotonic() > deadline: raise ScanError(code, message, status="timed_out") - def _create_pdf(self, images): + def _encode_page(self, image): + """Compress a captured page at once; decoded A4 pages cost ~26 MB each at 300 DPI.""" + rgb = image if image.mode == "RGB" else image.convert("RGB") + try: + buffer = io.BytesIO() + rgb.save(buffer, format="JPEG", quality=PAGE_JPEG_QUALITY, optimize=True) + return buffer.getvalue() + finally: + rgb.close() + if rgb is not image: + image.close() + + def _create_pdf(self, pages): buffer = io.BytesIO() document = canvas.Canvas(buffer, pagesize=A4) a4_width, a4_height = A4 + # drawImage(filename) embeds a JPEG file as-is; an ImageReader would be + # decoded to raw RGB and kept until save() for image de-duplication. + with tempfile.TemporaryDirectory(prefix="scanlink-pages-") as directory: + for index, page in enumerate(pages): + path = os.path.join(directory, f"page-{index:04d}.jpg") + with open(path, "wb") as page_file: + page_file.write(page) + try: + self._draw_page(document, path, page, a4_width, a4_height) + finally: + os.remove(path) + document.showPage() - for image in images: - image_buffer = io.BytesIO() - image.save(image_buffer, format="JPEG", quality=85, optimize=True) - image_buffer.seek(0) - - rl_image = reportlab_utils.ImageReader(image_buffer) - image_width, image_height = rl_image.getSize() - aspect = image_height / float(image_width) + document.save() + buffer.seek(0) + return buffer - draw_width = a4_width - draw_height = a4_width * aspect + def _draw_page(self, document, path, page, a4_width, a4_height): + with PilImage.open(io.BytesIO(page)) as header: + image_width, image_height = header.size + aspect = image_height / float(image_width) - if draw_height > a4_height: - draw_height = a4_height - draw_width = a4_height / aspect + draw_width = a4_width + draw_height = a4_width * aspect - x = (a4_width - draw_width) / 2.0 - y = (a4_height - draw_height) / 2.0 + if draw_height > a4_height: + draw_height = a4_height + draw_width = a4_height / aspect - document.drawImage(rl_image, x, y, width=draw_width, height=draw_height) - document.showPage() + x = (a4_width - draw_width) / 2.0 + y = (a4_height - draw_height) / 2.0 - document.save() - buffer.seek(0) - return buffer + document.drawImage(path, x, y, width=draw_width, height=draw_height) diff --git a/server.py b/server.py index 1f2a6fc..f4d5e97 100644 --- a/server.py +++ b/server.py @@ -3,10 +3,11 @@ import ssl import threading import time -from urllib.parse import urlparse +from urllib.parse import urlparse, urlsplit from flask import Flask, Response, jsonify, request, send_file -from werkzeug.serving import make_server +from werkzeug.exceptions import HTTPException +from werkzeug.serving import WSGIRequestHandler, make_server from utils import ( APP_ARCH, @@ -18,26 +19,49 @@ get_ssl_context, ensure_ssl_certificates, load_config, + normalize_origin, ) +from sites import LinkError, SiteRegistry from worker import BusyError logger = get_logger() +# DNS rebinding makes a foreign page same-origin with the helper, bypassing CORS, +# so the Host header must name the loopback interface itself. +LOOPBACK_HOSTNAMES = {"localhost", "127.0.0.1", "::1"} +# Scan requests carry a few identifiers; larger bodies would be kept with the job. +MAX_REQUEST_BYTES = 64 * 1024 +# Per-connection socket timeout, including the TLS handshake. +REQUEST_TIMEOUT_SECONDS = 30 -def create_app(worker, shutdown_event, transport_state): + +def is_loopback_host(host): + try: + return urlsplit(f"//{host}").hostname in LOOPBACK_HOSTNAMES + except ValueError: + return False + + +def create_app(worker, shutdown_event, transport_state, sites=None): app = Flask(__name__) - config = load_config() - allowed_origins = config.get("cors_origins", ["*"]) + app.config["MAX_CONTENT_LENGTH"] = MAX_REQUEST_BYTES + if sites is None: + config = load_config() + sites = SiteRegistry(config.get("cors_origins"), config.get("linked_sites")) def is_browser_endpoint(path): - return path == "/health" or path == "/scan" or path.startswith("/scan/") + return path in ("/health", "/scan", "/link") or path.startswith("/scan/") - def is_origin_allowed(origin): - return "*" in allowed_origins or origin in allowed_origins + def web_origin(): + """The request's Origin when it is a well-formed website origin.""" + origin = request.headers.get("Origin") + return origin if origin and normalize_origin(origin) == origin else None def apply_cors(response): - origin = request.headers.get("Origin") - if not origin or not is_origin_allowed(origin): + # Every website may read answers, so an unlinked one can see + # origin_not_allowed and offer to link; the work itself is gated. + origin = web_origin() + if origin is None: return response response.headers["Access-Control-Allow-Origin"] = origin @@ -45,6 +69,8 @@ def apply_cors(response): response.headers["Access-Control-Allow-Headers"] = "Content-Type" response.headers["Access-Control-Expose-Headers"] = "Content-Disposition" response.headers["Vary"] = "Origin" + if request.headers.get("Access-Control-Request-Private-Network") == "true": + response.headers["Access-Control-Allow-Private-Network"] = "true" return response def empty_options_response(): @@ -93,6 +119,36 @@ def scan_payload(): ) return data, None + @app.before_request + def reject_foreign_host(): + if not is_loopback_host(request.host): + return error_response( + 403, "invalid_host", "ScanLink only answers requests addressed to localhost." + ) + origin = request.headers.get("Origin") + if is_browser_endpoint(request.path): + gated = request.method != "OPTIONS" and request.path != "/link" + if gated and origin is not None and not sites.is_allowed(origin): + return error_response( + 403, "origin_not_allowed", "This website is not linked to ScanLink." + ) + # Browsers send Origin or Sec-Fetch-Site; form posts need no CORS preflight. + elif origin is not None or "Sec-Fetch-Site" in request.headers: + return error_response( + 403, "local_only", "This endpoint only accepts requests from this computer's ScanLink tools." + ) + return None + + @app.errorhandler(HTTPException) + def http_error(exc): + if exc.code == 413: + return error_response( + 413, "payload_too_large", "Scan requests must be smaller than 64 KB." + ) + return error_response( + exc.code, exc.name.lower().replace(" ", "_"), exc.description + ) + @app.after_request def add_cors_headers(response): if is_browser_endpoint(request.path): @@ -104,21 +160,44 @@ def health(): if request.method == "OPTIONS": return empty_options_response() - return jsonify( - { - "status": "ok", - "version": APP_VERSION, - "arch": APP_ARCH, - "busy": worker.is_busy(), - "http_enabled": transport_state.get("http_enabled", False), - "https_enabled": transport_state.get("https_enabled", False), - "twain_available": worker.is_twain_available(), - "https_setup": transport_state.get( - "https_setup", - "ready" if transport_state.get("https_enabled") else "unavailable", - ), - } - ) + payload = { + "status": "ok", + "version": APP_VERSION, + "arch": APP_ARCH, + "busy": worker.is_busy(), + "http_enabled": transport_state.get("http_enabled", False), + "https_enabled": transport_state.get("https_enabled", False), + "twain_available": worker.is_twain_available(), + "https_setup": transport_state.get( + "https_setup", + "ready" if transport_state.get("https_enabled") else "unavailable", + ), + } + origin = web_origin() + if origin is not None: + link = sites.link_for(origin) + payload["link"] = {"linked": link is not None, "sites": link["sites"] if link else []} + return jsonify(payload) + + @app.route("/link", methods=["POST", "OPTIONS"]) + def link_site(): + if request.method == "OPTIONS": + return empty_options_response() + origin = web_origin() + if origin is None: + return error_response( + 400, "origin_required", "Only a website can link itself, and its origin must be sent." + ) + data = request.get_json(silent=True) if request.is_json else None + if not isinstance(data, dict): + return error_response( + 400, "invalid_payload", "Link requests must contain a JSON object with a sites list." + ) + try: + result = sites.link(origin, data.get("sites")) + except LinkError as exc: + return error_response(exc.status, exc.code, exc.message) + return jsonify(result) @app.route("/scan", methods=["POST", "OPTIONS"]) def start_scan(): @@ -138,13 +217,15 @@ def start_scan(): callback_url=callback_url, metadata=data.get("metadata"), source="api", + origin=request.headers.get("Origin"), ) except BusyError as exc: + extra = {"active_job_id": exc.active_job_id} if exc.active_job_id else {} return error_response( 409, "busy", "Another scan job is already queued or running.", - active_job_id=exc.active_job_id, + **extra, ) return jsonify({"job_id": job["job_id"], "status": "queued"}), 202 @@ -154,7 +235,7 @@ def get_scan_status(job_id): if request.method == "OPTIONS": return empty_options_response() - job = worker.get_job(job_id) + job = worker.get_job(job_id, origin=request.headers.get("Origin")) if not job: return error_response( 404, "job_not_found", "The requested scan job was not found." @@ -166,7 +247,8 @@ def get_scan_result(job_id): if request.method == "OPTIONS": return empty_options_response() - job = worker.get_job(job_id) + origin = request.headers.get("Origin") + job = worker.get_job(job_id, origin=origin) if not job: return error_response( 404, "job_not_found", "The requested scan job was not found." @@ -179,7 +261,7 @@ def get_scan_result(job_id): current_status=job["status"], ) - updated_job, result_bytes = worker.consume_result(job_id) + updated_job, result_bytes = worker.consume_result(job_id, origin=origin) if not updated_job: return error_response( 404, "job_not_found", "The requested scan job was not found." @@ -254,6 +336,23 @@ def emit_scan_status(job_id, status, **kwargs): return None +class LoopbackRequestHandler(WSGIRequestHandler): + def setup(self): + self.timeout = REQUEST_TIMEOUT_SECONDS + super().setup() + + 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. + if isinstance(self.connection, ssl.SSLSocket): + try: + self.connection.do_handshake() + except OSError as exc: + logger.debug("TLS handshake from %s failed: %s", self.client_address, exc) + return + super().handle() + + class LoopbackServer(threading.Thread): def __init__(self, app, host, port, ssl_context=None, label="HTTP"): super().__init__(daemon=True) @@ -278,8 +377,11 @@ def run(self): self.port, self.app, threaded=True, + request_handler=LoopbackRequestHandler, ssl_context=self.ssl_context, ) + if self.ssl_context is not None: + self.httpd.socket.do_handshake_on_connect = False logger.info("%s listener ready on %s:%s", self.label, self.host, self.port) except Exception as exc: self.error = exc @@ -306,14 +408,14 @@ def shutdown(self): self.httpd.shutdown() -def run_server(worker, shutdown_event, https_retry_event=None, on_https_error=None): +def run_server(worker, shutdown_event, https_retry_event=None, on_https_error=None, sites=None): retry = https_retry_event or threading.Event() transport_state = { "http_enabled": False, "https_enabled": False, "https_setup": "preparing", } - app = create_app(worker, shutdown_event, transport_state) + app = create_app(worker, shutdown_event, transport_state, sites) listeners = [] http_listener = LoopbackServer(app, HTTP_HOST, HTTP_PORT, label="HTTP") http_listener.start() diff --git a/sites.py b/sites.py new file mode 100644 index 0000000..b81b6d8 --- /dev/null +++ b/sites.py @@ -0,0 +1,153 @@ +"""Websites allowed to use ScanLink's browser API. + +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. +""" + +import threading +import time +from datetime import datetime, timezone + +from utils import get_logger, load_config, normalize_origin, save_config + +logger = get_logger() + +MAX_SITES_PER_LINK = 20 +MAX_LINKS = 50 +# A declined website cannot open the approval window again for this long. +DECLINE_COOLDOWN_SECONDS = 600 +LINK_PROMPT_SECONDS = 120 + + +class LinkError(Exception): + def __init__(self, status, code, message): + super().__init__(message) + self.status = status + self.code = code + self.message = message + + +def save_links(links): + config = load_config() + config["linked_sites"] = links + save_config(config) + + +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.""" + self._listed = frozenset(origin for origin in map(normalize_origin, listed or ()) if origin) + self._links = {} + for origin, link in (links or {}).items(): + origin = normalize_origin(origin) + if origin and isinstance(link, dict): + sites = [site for site in map(normalize_origin, link.get("sites") or ()) if site] + self._links[origin] = { + "sites": list(dict.fromkeys([origin, *sites])), + "linked_at": str(link.get("linked_at") or ""), + } + self._confirm = confirm + self._persist = persist + self._clock = clock + self._lock = threading.Lock() + self._prompting = threading.Lock() + self._declined = {} + + def is_allowed(self, origin): + with self._lock: + return ( + origin in self._listed + or origin in self._links + or any(origin in link["sites"] for link in self._links.values()) + ) + + def link_for(self, origin): + with self._lock: + link = self._links.get(origin) + return {"sites": list(link["sites"]), "linked_at": link["linked_at"]} if link else None + + def links(self): + with self._lock: + return {origin: list(link["sites"]) for origin, link in self._links.items()} + + def link(self, origin, sites): + sites = self._clean_sites(origin, sites) + with self._lock: + link = self._links.get(origin) + 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: + 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.") + with self._lock: + if not answer: + self._declined[origin] = self._clock() + logger.info("The operator declined linking %r", origin) + raise LinkError(403, "link_declined", "Linking this website was declined on this computer.") + self._declined.pop(origin, None) + self._links[origin] = { + "sites": sites, + "linked_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + } + self._save() + logger.info("The operator linked %r; allowed sites %r", origin, sites) + return {"linked": True, "prompted": True, "sites": sites} + + def unlink(self, origin): + with self._lock: + removed = self._links.pop(origin, None) is not None + if removed: + self._save() + if removed: + logger.info("The operator unlinked %r", origin) + return removed + + def _ask(self, origin, other_sites): + if self._confirm is None: + return None + try: + return self._confirm(origin, other_sites) + except Exception: + logger.exception("Could not show the link approval window") + return None + + def _save(self): + try: + self._persist({origin: dict(link) for origin, link in self._links.items()}) + except Exception: + logger.exception("Could not save the linked websites") + + @staticmethod + def _clean_sites(origin, sites): + if sites is None: + sites = [] + if not isinstance(sites, list): + raise LinkError(400, "invalid_sites", "sites must be a list of website origins.") + cleaned = [origin] + for value in sites: + site = normalize_origin(value) + if site is None: + raise LinkError(400, "invalid_site", f"{str(value)[:80]!r} is not a website origin such as https://example.org.") + if site not in cleaned: + cleaned.append(site) + if len(cleaned) > MAX_SITES_PER_LINK: + raise LinkError(400, "too_many_sites", f"A website can allow at most {MAX_SITES_PER_LINK} sites.") + return cleaned diff --git a/static/scanlink.js b/static/scanlink.js index 425e5e8..3201101 100644 --- a/static/scanlink.js +++ b/static/scanlink.js @@ -49,6 +49,13 @@ class ScanLink { this.connectionError = null; return health; } catch (error) { + if (error instanceof ScanLinkError && error.code === "origin_not_allowed") { + // ScanLink answered, but this website is not linked: link() can fix that. + this._setPreferredUrl(baseUrl); + this.onConnectionChange(false); + this.connectionError = error; + return null; + } continue; } } @@ -66,6 +73,11 @@ class ScanLink { method: "GET", mode: "cors", signal: controller.signal, }); // Read the body before clearing the timeout, including stalled responses. + if (response.status === 403) { + const refusal = await this._responseToError(response, "ScanLink refused this website."); + if (refusal.code === "origin_not_allowed") throw refusal; + return null; + } return response.ok ? await response.json() : null; } finally { clearTimeout(timer); @@ -225,6 +237,28 @@ class ScanLink { window.location.href = url; } + async link(sites = []) { + // Resolves once the operator approves in ScanLink's own window (or at once + // for a website that is already linked); rejects with link_declined, + // link_pending or link_timeout otherwise. + if (!this.preferredUrl) await this.checkHealth(true); + let response; + try { + response = await this._fetchResponse("/link", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ sites }), + mode: "cors", + }); + } catch (error) { + throw this._connectionFailure(error); + } + if (!response.ok) { + throw await this._responseToError(response, "ScanLink did not link this website."); + } + return response.json(); + } + _uncertainRequest(cause) { return new ScanLinkError("The scan request lost its connection. Check ScanLink before starting another scan.", "scan_request_uncertain", { cause }); } diff --git a/tests/test_browser_security.py b/tests/test_browser_security.py new file mode 100644 index 0000000..e94e9b7 --- /dev/null +++ b/tests/test_browser_security.py @@ -0,0 +1,274 @@ +import queue +import threading +import time +import unittest +from unittest.mock import patch + +from tests.test_server import FakeWorker +from worker import ScanWorker + +LEGIT = {"Origin": "https://archive.example"} + +try: + import server +except ImportError: + server = None + + +@unittest.skipIf(server is None, "Flask is not installed in this environment") +class BrowserSecurityTests(unittest.TestCase): + cors_origins = ["https://archive.example"] + + def setUp(self): + self.worker = FakeWorker() + self.shutdown_event = threading.Event() + config = patch( + "server.load_config", return_value={"cors_origins": self.cors_origins} + ) + config.start() + self.addCleanup(config.stop) + self.app = server.create_app( + self.worker, self.shutdown_event, {"http_enabled": True} + ) + self.client = self.app.test_client() + + def test_rebound_host_names_are_refused(self): + for host in ( + "evil.example:5000", + "127.0.0.1.nip.io:5000", + "localhost.evil.example", + "evil.localhost:5443", + "a b", + ): + with self.subTest(host=host): + health = self.client.get("/health", headers={"Host": host}) + scan = self.client.post("/scan", json={}, headers={"Host": host}) + shutdown = self.client.post("/shutdown", headers={"Host": host}) + for response in (health, scan, shutdown): + self.assertEqual(response.status_code, 403) + self.assertEqual( + response.get_json()["error"]["code"], "invalid_host" + ) + self.assertEqual(self.worker.jobs, {}) + self.assertFalse(self.shutdown_event.is_set()) + + def test_loopback_host_names_are_served(self): + for host in ( + "localhost:5000", + "localhost:5443", + "127.0.0.1:5000", + "[::1]:5443", + "LOCALHOST:5443", + "127.0.0.1", + ): + with self.subTest(host=host): + response = self.client.get("/health", headers={"Host": host}) + self.assertEqual(response.status_code, 200) + + def test_browser_requests_cannot_use_local_control_endpoints(self): + browser_headers = ( + {"Origin": "https://evil.example", "Sec-Fetch-Site": "cross-site"}, + {"Origin": "null"}, + {"Sec-Fetch-Site": "cross-site", "Sec-Fetch-Mode": "navigate"}, + ) + for headers in browser_headers: + with self.subTest(headers=headers): + shutdown = self.client.post( + "/shutdown", + data="x=1", + content_type="application/x-www-form-urlencoded", + headers=headers, + ) + protocol = self.client.post( + "/internal/protocol/scan", json={"action": "scan"}, headers=headers + ) + for response in (shutdown, protocol): + self.assertEqual(response.status_code, 403) + self.assertEqual( + response.get_json()["error"]["code"], "local_only" + ) + self.assertFalse(self.shutdown_event.is_set()) + self.assertEqual(self.worker.jobs, {}) + + def test_oversized_scan_bodies_are_refused_without_a_job(self): + body = '{"metadata": {"blob": "%s"}}' % ("x" * (1024 * 1024)) + for endpoint in ("/scan", "/internal/protocol/scan"): + with self.subTest(endpoint=endpoint): + headers = LEGIT if endpoint == "/scan" else {} + response = self.client.post( + endpoint, + data=body, + content_type="application/json", + headers=headers, + ) + self.assertEqual(response.status_code, 413) + self.assertEqual( + response.get_json()["error"]["code"], "payload_too_large" + ) + self.assertEqual( + response.headers.get("Access-Control-Allow-Origin"), None + ) + self.assertEqual(self.worker.jobs, {}) + small = self.client.post( + "/scan", json={"metadata": {"path": "/x" * 1000}}, headers=LEGIT + ) + self.assertEqual(small.status_code, 202) + + def test_http_errors_keep_the_json_error_shape(self): + refused = self.client.post( + "/scan", + data="x" * (1024 * 1024), + content_type="application/json", + headers=LEGIT, + ) + self.assertEqual( + refused.headers["Access-Control-Allow-Origin"], LEGIT["Origin"] + ) + for response, status in ( + (refused, 413), + (self.client.delete("/scan", headers=LEGIT), 405), + (self.client.get("/scan/a/b/c", headers=LEGIT), 404), + ): + self.assertEqual(response.status_code, status) + self.assertEqual(response.mimetype, "application/json") + self.assertTrue(response.get_json()["error"]["message"]) + + def test_private_network_preflight_is_answered_for_allowed_origins(self): + for path in ("/health", "/scan", "/scan/job-1", "/scan/job-1/result"): + with self.subTest(path=path): + response = self.client.options( + path, + headers={ + **LEGIT, + "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "content-type", + "Access-Control-Request-Private-Network": "true", + }, + ) + self.assertEqual(response.status_code, 204) + self.assertEqual( + response.headers["Access-Control-Allow-Private-Network"], "true" + ) + self.assertEqual( + response.headers["Access-Control-Allow-Origin"], LEGIT["Origin"] + ) + plain = self.client.options( + "/scan", headers={**LEGIT, "Access-Control-Request-Method": "POST"} + ) + self.assertNotIn("Access-Control-Allow-Private-Network", plain.headers) + + def test_local_tools_keep_local_control_endpoints(self): + protocol = self.client.post("/internal/protocol/scan", json={"action": "scan"}) + shutdown = self.client.post("/shutdown") + self.assertEqual(protocol.status_code, 202) + self.assertEqual(shutdown.status_code, 200) + self.assertTrue(self.shutdown_event.is_set()) + + +OTHER = {"Origin": "https://crm.example"} +EVIL = {"Origin": "https://evil.example"} + + +@unittest.skipIf(server is None, "Flask is not installed in this environment") +class JobOwnershipTests(unittest.TestCase): + cors_origins = ["https://archive.example", "https://crm.example"] + + def setUp(self): + config = patch( + "server.load_config", return_value={"cors_origins": self.cors_origins} + ) + config.start() + self.addCleanup(config.stop) + # Not started: submitted jobs stay queued until a test completes them. + self.worker = ScanWorker(queue.Queue()) + self.app = server.create_app( + self.worker, threading.Event(), {"http_enabled": True} + ) + self.client = self.app.test_client() + + def complete(self, job_id): + self.worker._update_job( + job_id, + status="completed", + completed_at=time.time(), + result_bytes=b"%PDF-1.4\nsecret\n", + ) + + def test_another_origin_cannot_find_or_take_a_scan(self): + job_id = self.client.post("/scan", json={}, headers=LEGIT).get_json()["job_id"] + + other_busy = self.client.post("/scan", json={}, headers=OTHER) + self.assertEqual(other_busy.status_code, 409) + self.assertNotIn("active_job_id", other_busy.get_json()["error"]) + owner_busy = self.client.post("/scan", json={}, headers=LEGIT) + self.assertEqual(owner_busy.get_json()["error"]["active_job_id"], job_id) + + self.complete(job_id) + for headers in (OTHER, {}, {"Sec-Fetch-Site": "cross-site"}): + with self.subTest(headers=headers): + for path in (f"/scan/{job_id}", f"/scan/{job_id}/result"): + response = self.client.get(path, headers=headers) + self.assertEqual(response.status_code, 404) + self.assertEqual( + response.get_json()["error"]["code"], "job_not_found" + ) + + self.assertEqual( + self.client.get(f"/scan/{job_id}", headers=LEGIT).get_json()["status"], + "completed", + ) + result = self.client.get(f"/scan/{job_id}/result", headers=LEGIT) + self.assertEqual(result.status_code, 200) + self.assertEqual(result.data, b"%PDF-1.4\nsecret\n") + + def test_jobs_started_without_an_origin_stay_with_local_tools(self): + job_id = self.client.post("/scan", json={}).get_json()["job_id"] + self.assertEqual(self.client.post("/scan", json={}).get_json()["error"]["active_job_id"], job_id) + self.assertNotIn( + "active_job_id", + self.client.post("/scan", json={}, headers=LEGIT).get_json()["error"], + ) + self.assertEqual( + self.client.get(f"/scan/{job_id}", headers=LEGIT).status_code, 404 + ) + self.complete(job_id) + self.assertEqual(self.client.get(f"/scan/{job_id}/result").status_code, 200) + + +class AllowListTests(JobOwnershipTests): + def test_unlisted_origin_is_refused_before_any_work(self): + preflight = self.client.options( + "/scan", + headers={**EVIL, "Access-Control-Request-Method": "POST", "Access-Control-Request-Private-Network": "true"}, + ) + self.assertEqual(preflight.status_code, 204) + self.assertEqual(preflight.headers["Access-Control-Allow-Private-Network"], "true") + for response in ( + self.client.get("/health", headers=EVIL), + self.client.post("/scan", json={}, headers=EVIL), + self.client.get("/scan/anything", headers=EVIL), + ): + self.assertEqual(response.status_code, 403) + self.assertEqual( + response.get_json()["error"]["code"], "origin_not_allowed" + ) + # Readable, so the page can offer to link instead of seeing a network error. + self.assertEqual(response.headers["Access-Control-Allow-Origin"], EVIL["Origin"]) + self.assertEqual(self.worker.jobs, {}) + + accepted = self.client.post("/scan", json={}, headers=LEGIT) + self.assertEqual(accepted.status_code, 202) + self.assertEqual( + accepted.headers["Access-Control-Allow-Origin"], LEGIT["Origin"] + ) + + def test_the_wildcard_no_longer_allows_every_website(self): + with patch("server.load_config", return_value={"cors_origins": ["*"]}): + app = server.create_app(self.worker, threading.Event(), {"http_enabled": True}) + refused = app.test_client().post("/scan", json={}, headers=LEGIT) + self.assertEqual(refused.status_code, 403) + self.assertEqual(refused.get_json()["error"]["code"], "origin_not_allowed") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_loopback_listener.py b/tests/test_loopback_listener.py new file mode 100644 index 0000000..99469d9 --- /dev/null +++ b/tests/test_loopback_listener.py @@ -0,0 +1,141 @@ +import datetime +import http.client +import ipaddress +import json +from pathlib import Path +import socket +import ssl +import threading +import time +import unittest +from unittest.mock import patch +import uuid + +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.x509.oid import NameOID + +from tests.test_server import FakeWorker + +try: + import server +except ImportError: + server = None + + +def localhost_tls(): + key = ec.generate_private_key(ec.SECP256R1()) + name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "localhost")]) + now = datetime.datetime.now(datetime.timezone.utc) + certificate = ( + x509.CertificateBuilder() + .subject_name(name) + .issuer_name(name) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - datetime.timedelta(minutes=5)) + .not_valid_after(now + datetime.timedelta(days=1)) + .add_extension( + x509.SubjectAlternativeName( + [ + x509.DNSName("localhost"), + x509.IPAddress(ipaddress.ip_address("127.0.0.1")), + ] + ), + critical=False, + ) + .sign(key, hashes.SHA256()) + ) + directory = Path(".xclude/test-output/listener") / uuid.uuid4().hex + directory.mkdir(parents=True) + bundle = directory / "localhost.pem" + bundle.write_bytes( + certificate.public_bytes(serialization.Encoding.PEM) + + key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) + ) + server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + server_context.load_cert_chain(str(bundle)) + return server_context, ssl.create_default_context(cafile=str(bundle)) + + +@unittest.skipIf(server is None, "Flask is not installed in this environment") +class LoopbackListenerTests(unittest.TestCase): + def setUp(self): + timeout = patch("server.REQUEST_TIMEOUT_SECONDS", 1) + timeout.start() + self.addCleanup(timeout.stop) + config = patch("server.load_config", return_value={"cors_origins": ["*"]}) + config.start() + self.addCleanup(config.stop) + app = server.create_app(FakeWorker(), threading.Event(), {"http_enabled": True}) + self.server_context, self.client_context = localhost_tls() + self.http = server.LoopbackServer(app, "127.0.0.1", 0, label="HTTP") + self.https = server.LoopbackServer( + app, "127.0.0.1", 0, ssl_context=self.server_context, label="HTTPS" + ) + for listener in (self.http, self.https): + listener.start() + self.assertTrue(listener.started.wait(5)) + self.assertIsNone(listener.error) + self.addCleanup(listener.join, 5) + self.addCleanup(listener.shutdown) + + def health(self, secure, timeout=3): + if secure: + raw = socket.create_connection( + ("127.0.0.1", self.https.httpd.server_port), timeout=timeout + ) + connection = http.client.HTTPConnection("localhost", timeout=timeout) + connection.sock = self.client_context.wrap_socket( + raw, server_hostname="localhost" + ) + else: + connection = http.client.HTTPConnection( + "127.0.0.1", self.http.httpd.server_port, timeout=timeout + ) + try: + connection.request("GET", "/health") + response = connection.getresponse() + return response.status, json.loads(response.read()) + finally: + connection.close() + + def test_a_client_that_never_starts_tls_does_not_block_https(self): + idle = [ + socket.create_connection(("127.0.0.1", self.https.httpd.server_port)) + for _ in range(3) + ] + self.addCleanup(lambda: [sock.close() for sock in idle]) + time.sleep(0.2) + started = time.monotonic() + status, payload = self.health(secure=True) + self.assertEqual(status, 200) + self.assertEqual(payload["status"], "ok") + self.assertLess(time.monotonic() - started, 1) + + def test_idle_connections_are_closed_after_the_request_timeout(self): + for port in (self.http.httpd.server_port, self.https.httpd.server_port): + with self.subTest(port=port): + sock = socket.create_connection(("127.0.0.1", port)) + self.addCleanup(sock.close) + if port == self.http.httpd.server_port: + sock.sendall(b"GET /health HTTP/1.1\r\nHost: 127.0.0.1\r\n") + sock.settimeout(10) + started = time.monotonic() + try: + data = sock.recv(1024) + except ConnectionResetError: + data = b"" + self.assertLess(time.monotonic() - started, 5) + self.assertFalse(data.startswith(b"HTTP/1.1 200")) + self.assertEqual(self.health(secure=False)[0], 200) + self.assertEqual(self.health(secure=True)[0], 200) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_protocol_handler.py b/tests/test_protocol_handler.py index 9adf151..607f672 100644 --- a/tests/test_protocol_handler.py +++ b/tests/test_protocol_handler.py @@ -16,7 +16,11 @@ def test_parse_protocol_url_extracts_known_fields(self): @patch.object(protocol_handler, "requests") def test_forward_protocol_command_accepts_busy_response(self, mock_requests): - mock_requests.post.return_value = Mock(ok=False, status_code=409) + mock_requests.post.return_value = Mock( + ok=False, + status_code=409, + json=Mock(return_value={"error": {"code": "busy", "message": "Busy"}}), + ) forwarded = protocol_handler.forward_protocol_command( {"action": "scan", "doc_id": "42", "callback_url": None} @@ -26,10 +30,54 @@ def test_forward_protocol_command_accepts_busy_response(self, mock_requests): @patch.object(protocol_handler, "requests") def test_is_existing_instance_running_checks_health(self, mock_requests): - mock_requests.get.return_value = Mock(ok=True) + mock_requests.get.return_value = Mock( + ok=True, + json=Mock( + return_value={"status": "ok", "version": "0.8.0", "twain_available": True} + ), + ) self.assertTrue(protocol_handler.is_existing_instance_running()) + @patch.object(protocol_handler, "requests") + def test_another_program_on_the_port_is_not_scanlink(self, mock_requests): + mock_requests.RequestException = Exception + for payload in (ValueError("not json"), {"status": "ok"}, ["ok"]): + with self.subTest(payload=payload): + foreign = Mock(ok=True, status_code=200) + if isinstance(payload, Exception): + foreign.json.side_effect = payload + else: + foreign.json.return_value = payload + mock_requests.get.return_value = foreign + mock_requests.post.return_value = foreign + self.assertFalse(protocol_handler.is_existing_instance_running()) + self.assertFalse( + protocol_handler.forward_protocol_command({"action": "scan"}) + ) + + @patch.object(protocol_handler, "requests") + def test_forward_protocol_command_accepts_a_queued_job(self, mock_requests): + mock_requests.post.return_value = Mock( + ok=True, + status_code=202, + json=Mock(return_value={"job_id": "job-1", "status": "queued"}), + ) + + self.assertTrue(protocol_handler.forward_protocol_command({"action": "scan"})) + + def test_parse_failures_are_logged_on_one_line(self): + with self.assertLogs("ScanLink", level="DEBUG") as captured: + self.assertIsNone( + protocol_handler.parse_protocol_url( + "scanlink://[\n2026-11-14 09:00:00,000 - INFO - forged" + ) + ) + protocol_handler.parse_protocol_url("scanlink://scan?docId=a%0D%0Aforged") + for line in captured.output: + self.assertNotIn("\n", line) + self.assertNotIn("\r", line) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_scan_pages.py b/tests/test_scan_pages.py new file mode 100644 index 0000000..a90900a --- /dev/null +++ b/tests/test_scan_pages.py @@ -0,0 +1,90 @@ +import tracemalloc +import unittest + +try: + from PIL import Image, ImageDraw +except ImportError: + Image = None + +import scanner + +DPI = 150 +SIZE = (int(8.27 * DPI), int(11.69 * DPI)) +DECODED_PAGE_BYTES = SIZE[0] * SIZE[1] * 3 + + +def printed_page(): + page = Image.new("L", SIZE, 255) + draw = ImageDraw.Draw(page) + for y in range(0, SIZE[1], DPI // 6): + draw.line((DPI // 2, y, SIZE[0] - DPI // 2, y), fill=0, width=2) + return page + + +class FakeTwainImage: + def save(self, path): + printed_page().save(path, format="BMP") + + def close(self): + pass + + +class FakeSource: + def __init__(self, pages): + self.pages = pages + + def acquire_natively(self, after, before, show_ui, modal): + for index in range(self.pages): + before(None) + after(FakeTwainImage(), index < self.pages - 1) + + def acquire_file(self, before, after, show_ui, modal): + for index in range(self.pages): + path = before(None) + printed_page().save(path, format="BMP") + after(index < self.pages - 1) + + +@unittest.skipIf(Image is None or scanner.canvas is None, "Pillow/ReportLab missing") +class ScanPageMemoryTests(unittest.TestCase): + def acquire(self, mode, pages=3): + manager = scanner.ScannerManager() + captured = [] + progress = [] + acquire = getattr(manager, f"_acquire_via_{mode}_transfer") + acquire( + FakeSource(pages), + captured, + lambda status, **data: progress.append((status, data["page_count"])), + None, + False, + ) + self.assertEqual(progress[-1], ("page_scanned", pages)) + return manager, captured + + def test_captured_pages_are_kept_compressed(self): + for mode in ("native", "file"): + with self.subTest(mode=mode): + _, captured = self.acquire(mode) + self.assertEqual(len(captured), 3) + for page in captured: + self.assertIsInstance(page, bytes) + self.assertTrue(page.startswith(b"\xff\xd8")) + self.assertLess(len(page), DECODED_PAGE_BYTES // 10) + + def test_pdf_embeds_page_jpegs_without_decoding_them(self): + manager, captured = self.acquire("native", pages=4) + tracemalloc.start() + try: + pdf = manager._create_pdf(captured).getvalue() + peak = tracemalloc.get_traced_memory()[1] + finally: + tracemalloc.stop() + self.assertLess(peak, DECODED_PAGE_BYTES) + self.assertTrue(pdf.startswith(b"%PDF")) + self.assertEqual(pdf.count(b"/DCTDecode"), 4) + self.assertEqual(pdf.count(b"/Type /Page\n"), 4) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_scan_runtime.py b/tests/test_scan_runtime.py new file mode 100644 index 0000000..d6fb856 --- /dev/null +++ b/tests/test_scan_runtime.py @@ -0,0 +1,68 @@ +import io +import json +import os +from pathlib import Path +import shutil +import tempfile +import unittest +from unittest.mock import MagicMock, patch +import uuid + +import scan_runtime + + +class ScanRuntimeDirectoryTests(unittest.TestCase): + def setUp(self): + self.scanner = MagicMock() + self.scanner.return_value.scan_to_pdf.side_effect = ( + lambda *args, **kwargs: io.BytesIO(b"%PDF-1.4\n") + ) + for target, replacement in ( + ("scan_runtime.ScannerManager", self.scanner), + ("scan_runtime.tk.Tk", MagicMock()), + ("scan_runtime.init_gui", MagicMock()), + ): + patcher = patch(target, replacement) + patcher.start() + self.addCleanup(patcher.stop) + + def prepared(self, directory): + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + (directory / "request.json").write_text( + json.dumps({"job_id": "job", "scan_timeout_seconds": 5}) + ) + return directory + + def test_injected_worker_directories_are_refused(self): + outside = Path(".xclude/test-output/runtime") / uuid.uuid4().hex + job_named_outside = outside / "scanlink-job-injected" + temp_job = Path(tempfile.mkdtemp(prefix="scanlink-job-")) + self.addCleanup(shutil.rmtree, temp_job, ignore_errors=True) + other_temp = Path(tempfile.mkdtemp(prefix="not-scanlink-")) + self.addCleanup(shutil.rmtree, other_temp, ignore_errors=True) + for directory in ( + self.prepared(outside), + self.prepared(job_named_outside), + self.prepared(other_temp), + os.path.join(temp_job, "..", other_temp.name), + r"\\attacker.example\share\scanlink-job-x", + ): + with self.subTest(directory=str(directory)): + self.assertNotEqual(scan_runtime.run_scan_job(str(directory)), 0) + for name in ("state.json", "result.pdf"): + self.assertFalse(Path(directory, name).exists()) + self.scanner.return_value.scan_to_pdf.assert_not_called() + + def test_parent_created_job_directory_runs(self): + directory = self.prepared(tempfile.mkdtemp(prefix="scanlink-job-")) + self.addCleanup(shutil.rmtree, directory, ignore_errors=True) + self.assertEqual(scan_runtime.run_scan_job(str(directory)), 0) + self.assertEqual((directory / "result.pdf").read_bytes(), b"%PDF-1.4\n") + self.assertEqual( + json.loads((directory / "state.json").read_text())["status"], "completed" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_server.py b/tests/test_server.py index 6586b18..78f38a5 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -24,7 +24,9 @@ def is_busy(self): def is_twain_available(self): return self.twain_available - def submit_job(self, doc_id=None, callback_url=None, metadata=None, source="api"): + def submit_job( + self, doc_id=None, callback_url=None, metadata=None, source="api", origin=None + ): if self.busy: raise BusyError(active_job_id="busy-job") @@ -47,14 +49,14 @@ def submit_job(self, doc_id=None, callback_url=None, metadata=None, source="api" } return job - def get_job(self, job_id): + def get_job(self, job_id, origin=None): job = self.jobs.get(job_id) if not job: return None return {key: value for key, value in job.items() if key != "result_bytes"} - def consume_result(self, job_id): + def consume_result(self, job_id, origin=None): job = self.jobs.get(job_id) if not job: return None, None @@ -71,7 +73,7 @@ def setUp(self): self.transport_state = {"http_enabled": True, "https_enabled": False} self.shutdown_event = threading.Event() self.config_patch = patch( - "server.load_config", return_value={"cors_origins": ["*"]} + "server.load_config", return_value={"cors_origins": ["http://localhost:82"]} ) self.config_patch.start() self.app = server.create_app( diff --git a/tests/test_site_links.py b/tests/test_site_links.py new file mode 100644 index 0000000..f32ee22 --- /dev/null +++ b/tests/test_site_links.py @@ -0,0 +1,211 @@ +import threading +import unittest +from unittest.mock import patch + +from tests.test_server import FakeWorker +from utils import _normalize_config, normalize_origin + +try: + import server + from sites import DECLINE_COOLDOWN_SECONDS, MAX_SITES_PER_LINK, SiteRegistry +except ImportError: + server = None + +ARCHIVE = {"Origin": "https://archive.example"} +CRM = {"Origin": "https://crm.example"} +EVIL = {"Origin": "https://evil.example"} + + +class OriginTests(unittest.TestCase): + def test_only_plain_website_origins_are_accepted(self): + for value, expected in ( + ("https://archive.example", "https://archive.example"), + ("https://Archive.Example:443/", "https://archive.example"), + ("http://intranet:8080", "http://intranet:8080"), + ("http://[::1]:8000", "http://[::1]:8000"), + ): + 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://"): + with self.subTest(value=value): + self.assertIsNone(normalize_origin(value)) + + def test_saved_wildcard_and_bad_links_are_dropped_on_load(self): + config = _normalize_config({ + "cors_origins": ["*", "https://archive.example", "https://archive.example/"], + "linked_sites": { + "https://crm.example": {"sites": ["https://sales.example", "*"], "linked_at": "2026-11-14T00:00:00Z"}, + "*": {"sites": []}, + "https://bad.example": "not a link", + }, + }) + self.assertEqual(config["cors_origins"], ["https://archive.example"]) + self.assertEqual(config["linked_sites"], { + "https://crm.example": {"sites": ["https://crm.example", "https://sales.example"], + "linked_at": "2026-11-14T00:00:00Z"}, + }) + + +@unittest.skipIf(server is None, "Flask is not installed in this environment") +class LinkTests(unittest.TestCase): + def setUp(self): + self.answers = [] + self.asked = [] + self.saved = [] + self.now = [1000.0] + self.sites = SiteRegistry( + ["https://listed.example"], + confirm=self.confirm, + persist=self.saved.append, + clock=lambda: self.now[0], + ) + self.worker = FakeWorker() + self.client = server.create_app( + self.worker, threading.Event(), {"http_enabled": True}, self.sites + ).test_client() + + def confirm(self, origin, other_sites): + self.asked.append((origin, other_sites)) + return self.answers.pop(0) if self.answers else None + + def link(self, headers, sites=()): + return self.client.post("/link", json={"sites": list(sites)}, headers=headers) + + def test_an_unlinked_site_can_read_why_it_is_refused(self): + health = self.client.get("/health", headers=EVIL) + self.assertEqual(health.status_code, 403) + self.assertEqual(health.get_json()["error"]["code"], "origin_not_allowed") + self.assertEqual(health.headers["Access-Control-Allow-Origin"], EVIL["Origin"]) + preflight = self.client.options("/link", headers={**EVIL, "Access-Control-Request-Method": "POST"}) + self.assertEqual(preflight.status_code, 204) + self.assertEqual(preflight.headers["Access-Control-Allow-Origin"], EVIL["Origin"]) + + def test_an_approved_link_allows_the_site_and_the_sites_its_admin_lists(self): + self.answers.append(True) + response = self.link(ARCHIVE, ["https://crm.example", "https://archive.example", "https://CRM.example/"]) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.get_json(), { + "linked": True, "prompted": True, "sites": ["https://archive.example", "https://crm.example"], + }) + self.assertEqual(self.asked, [("https://archive.example", ["https://crm.example"])]) + self.assertEqual(list(self.saved[-1]), ["https://archive.example"]) + + health = self.client.get("/health", headers=ARCHIVE).get_json() + self.assertEqual(health["link"], {"linked": True, "sites": ["https://archive.example", "https://crm.example"]}) + self.assertEqual(self.client.get("/health", headers=CRM).get_json()["link"], {"linked": False, "sites": []}) + 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): + self.answers.append(True) + self.link(ARCHIVE, ["https://crm.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_listed_site_cannot_change_another_sites_link(self): + self.answers.append(True) + self.link(ARCHIVE, ["https://crm.example"]) + self.answers.append(False) + response = self.link(CRM, ["https://evil.example"]) + self.assertEqual(response.status_code, 403) + self.assertEqual(len(self.asked), 2) + self.assertEqual(self.client.get("/health", headers=EVIL).status_code, 403) + + def test_a_declined_site_cannot_ask_again_until_the_cooldown_ends(self): + self.answers.append(False) + first = self.link(EVIL) + self.assertEqual((first.status_code, first.get_json()["error"]["code"]), (403, "link_declined")) + self.assertEqual(first.headers["Access-Control-Allow-Origin"], EVIL["Origin"]) + again = self.link(EVIL) + self.assertEqual(again.get_json()["error"]["code"], "link_declined") + self.assertEqual(len(self.asked), 1) + self.now[0] += DECLINE_COOLDOWN_SECONDS + 1 + self.answers.append(True) + self.assertEqual(self.link(EVIL).status_code, 200) + self.assertEqual(len(self.asked), 2) + + def test_an_unanswered_window_links_nothing(self): + response = self.link(EVIL) + self.assertEqual((response.status_code, response.get_json()["error"]["code"]), (408, "link_timeout")) + self.assertEqual(self.client.get("/health", headers=EVIL).status_code, 403) + self.assertEqual(self.saved, []) + + def test_one_approval_window_at_a_time(self): + opened, release = threading.Event(), threading.Event() + + def slow_confirm(origin, other_sites): + opened.set() + release.wait(5) + return True + + self.sites._confirm = slow_confirm + results = {} + thread = threading.Thread(target=lambda: results.setdefault("first", self.link(ARCHIVE))) + thread.start() + self.assertTrue(opened.wait(5)) + try: + second = self.link(EVIL) + finally: + release.set() + thread.join(5) + self.assertEqual((second.status_code, second.get_json()["error"]["code"]), (409, "link_pending")) + self.assertEqual(results["first"].status_code, 200) + self.assertEqual(self.client.get("/health", headers=EVIL).status_code, 403) + + def test_bad_link_requests_are_refused_without_a_window(self): + too_many = [f"https://s{n}.example" for n in range(MAX_SITES_PER_LINK)] + for headers, body, code in ( + ({}, {"sites": []}, "origin_required"), + ({"Origin": "null"}, {"sites": []}, "origin_required"), + (ARCHIVE, ["https://a.example"], "invalid_payload"), + (ARCHIVE, {"sites": "https://a.example"}, "invalid_sites"), + (ARCHIVE, {"sites": ["https://*.example"]}, "invalid_site"), + (ARCHIVE, {"sites": ["*"]}, "invalid_site"), + (ARCHIVE, {"sites": too_many}, "too_many_sites"), + ): + with self.subTest(code=code, headers=headers): + response = self.client.post("/link", json=body, headers=headers) + self.assertEqual(response.status_code, 400) + self.assertEqual(response.get_json()["error"]["code"], code) + self.assertEqual(self.asked, []) + + def test_link_keeps_the_loopback_host_check(self): + response = self.client.post("/link", json={"sites": []}, headers={**EVIL, "Host": "evil.example:5000"}) + self.assertEqual(response.get_json()["error"]["code"], "invalid_host") + self.assertEqual(self.asked, []) + + def test_unlinking_removes_the_site_and_its_list(self): + self.answers.append(True) + self.link(ARCHIVE, ["https://crm.example"]) + self.assertTrue(self.sites.unlink("https://archive.example")) + self.assertEqual(self.saved[-1], {}) + for headers in (ARCHIVE, CRM): + self.assertEqual(self.client.get("/health", headers=headers).status_code, 403) + self.assertEqual(self.client.get("/health", headers={"Origin": "https://listed.example"}).status_code, 200) + + def test_saved_links_are_restored(self): + self.answers.append(True) + self.link(ARCHIVE, ["https://crm.example"]) + restored = SiteRegistry([], self.saved[-1]) + self.assertTrue(restored.is_allowed("https://crm.example")) + self.assertEqual(restored.link_for("https://archive.example")["sites"], + ["https://archive.example", "https://crm.example"]) + + def test_config_wiring_links_from_the_saved_file(self): + with patch("server.load_config", return_value=_normalize_config({ + "cors_origins": ["*"], + "linked_sites": {"https://archive.example": {"sites": ["https://crm.example"]}}, + })): + client = server.create_app(FakeWorker(), threading.Event(), {"http_enabled": True}).test_client() + self.assertEqual(client.post("/scan", json={}, headers=CRM).status_code, 202) + self.assertEqual(client.post("/scan", json={}, headers=EVIL).status_code, 403) + self.assertEqual(client.post("/link", json={"sites": []}, headers=EVIL).get_json()["error"]["code"], + "link_timeout") + + +if __name__ == "__main__": + unittest.main() diff --git a/tracker.md b/tracker.md index f994a7e..7a9235e 100644 --- a/tracker.md +++ b/tracker.md @@ -3,6 +3,7 @@ ## Part 1: Project-specific ### Current Snapshot - Published 0.8.0b1 on `0.8/stress_fixes` (2026-10-25): real worker completion/deadline, public/internal input validation, single POST transport behavior and result-race fixes. Published0.7.5b1 (tagd74bf90) and stable Latest0.7.4 unchanged; owner authorized publication2026-10-25; PR2 merged as a82aab7; v0.8.0b1 published, release40233617433 PASS, x64/x86 asset digests verified; stable Latest stays0.7.4. +- Branch `0.8/stress_fixes` (2026-11-14, local only, unpushed, VERSION still 0.8.0b2): browser-security and transport hardening under `## Unreleased` — loopback Host check, local-only `/shutdown` and protocol endpoint, scans bound to their Origin, server-side allow-list refusal, 64 KB bodies + JSON HTTP errors, PNA preflight, TLS handshake off the accept loop + 30 s socket timeout, JPEG page capture (x86 memory), scan worker directory check, helper identity check. - Windows tray app uses TWAIN/pytwain; scan jobs run through child `main.py --scan-worker-dir` / `scan_runtime.py`. - Normal startup serves HTTP :5000 while automatically provisioning trusted localhost HTTPS :5443; failed setup offers native Retry and a tray repair action. - `certificates.py`: per-user localhost-only self-signed server identity, Windows CurrentUser Root trust, encrypted PKCS#8 key with DPAPI-protected password; hourly checks/30-day renewal and live TLS context selection. @@ -21,10 +22,13 @@ - Windows x64/x86 unit/build/install gates passed, including real certificate consent, DPAPI/trust, 120 verified HTTPS requests per architecture and restart identity reuse. Real Windows browser/scanner and enterprise-policy acceptance remain manual. - Target PaperStream fi-6230Z may expose only 32-bit TWAIN; live driver compliance/output quality remain unverified. Back-only and blank-page discard remain unsupported. - Organization/browser policies may refuse user-installed trust. A denied setup is reported as failure and retried with the same identity, without repeated automatic dialogs. -- Callbacks are never delivered (since 36249b6, 2026-04-28): `_process_job` passes the serialized job, which omits `callback_url`, to `_send_callback`. Docs promise delivery; enabling it changes production behavior and needs an owner decision. +- Owner decision 2026-11-14: DjangoLux supplies its sites (admin's choice). Done on `0.8/stress_fixes`: no wildcard, `POST /link` with a one-time approval window naming the browser's origin, tray **Linked Websites** to unlink; paired DjangoLux `1.16/scanlink_sites` sends the admin's list. Every upgrading operator approves each site once. The window is English-only, like the rest of ScanLink's UI. +- Contract gaps on the DjangoLux side: `scan_button.js` gives up after 5 min while ScanLink's deadline is 600+15 s (no cancel endpoint; retry reports busy, PDF orphaned 300 s); `no_pages_scanned`, `scan_idle_timeout`, `acquire_failed`, `scan_worker_crashed`, `origin_not_allowed`, `payload_too_large` show ScanLink's English message. +- Callbacks are never delivered (since 36249b6, 2026-04-28): `_process_job` passes the serialized job, which omits `callback_url`, to `_send_callback`. Docs promise delivery; enabling it changes production behavior and needs an owner decision. Any re-enable must restrict callback hosts: any page or `scanlink://` link can set `callback_url`. ### Active & Pending Tasks - [x] 0.8.0b2 merged to main via PR3 (063269b, 2026-10-30; CI 3/3 PASS): 15s parent scan-deadline grace, callback parse guard, per-scan `/health` in `scanlink.js`. Untagged; tagging/publishing needs owner OK. +- [ ] Review/merge `0.8/stress_fixes` (PR #5: 10 fix commits + site linking, 78 tests) with DjangoLux #71 and `1.16/scanlink_sites`; then ScanLink 0.8.0b3 (owner OK to tag). - [ ] Mirror the per-scan health check in DjangoLux `scan_button.js` if it shares the stale-transport logic. - [x] 2026-10-30: retired `0.7/automatic_https`, `0.8/stress_fixes`, `0.8/stress_followups` (checkouts removed, branches deleted locally/GitHub; leftovers in `.xclude/retired-worktrees/2026-10-30/`). Only `main` remains. - [x] Paired deeper stress and real-worker regressions pass; candidate0.8.0b1 prepared locally. Owner authorized next beta; PR2 merged after x86/x64 native CI PASS, release gates PASS, both installers published. @@ -38,6 +42,7 @@ - [x] Verified real TLS handshakes, hostname rejection and live identity renewal; setup failure preserves HTTP and Retry recovers HTTPS. ### Validation & Docs Log +- 2026-11-14 `0.8/stress_fixes`, macOS scratch venv (py3.13, Flask 3.1.3): 63 tests OK/1 Windows skip; live stack 20×50 concurrent POSTs (1 accepted each), 50k mixed requests flat RSS, 150 scan cycles, 200 idle HTTP + 200 idle TLS sockets, 7k connect/close, 126 MB result over HTTP/HTTPS, 50k fuzzed `scanlink://` URLs; DjangoLux `main.js`+`scan_button.js` end-to-end against the live stack; dlux `scenarios.mjs` 34/34. Docs: api/architecture, CHANGELOG Unreleased. Evidence `.xclude/validation/stress-2026-11-14/`. No Windows/TWAIN run. - 2026-10-30: 0.8.0b2 changes, macOS: 42 unit tests OK/1 Windows skip (scratch venv). New grace/callback tests fail on 0.8.0b1 code; Node harness for `scanlink.js` 4/4 (old: 2/4). Docs: api/architecture/developer guide, CHANGELOG v0.8.0b2, VERSION 0.8.0b2. Windows/native gates not run. - 2026-10-25: 40 local unit tests OK/1 Windows skip; Windows CI/release PASS x64+x86 including consent/120 HTTPS/restart; pairedJS24 PASS; real worker1000 health (500 verified TLS)/100 hashed PDFs/50 busy/40 result races PASS; timeouts/crash/cancel/callback/shutdown recovery PASS.8097 UI300 health/30 scans/20 simultaneous, PDF save/Arabic lost-response guidance/one POST PASS. Dlux3064 OK/6skips +79 focused; doctor0error. Native candidate gates now PASS; physical hardware/Windows browser policies unverified. - 2026-10-25: API/architecture/developer guide, VERSION0.8.0b1 and CHANGELOG document parent-owned completion, hard deadline, strict payloads, retained metadata and scan_request_uncertain. Local report `.xclude/retired-worktrees/2026-10-30/stress_fixes/.xclude/validation/paired-stress-2026-10-25.md`. diff --git a/tray.py b/tray.py index df1b31d..f7a0f9d 100644 --- a/tray.py +++ b/tray.py @@ -96,8 +96,9 @@ def format_color_mode(value): class TrayApp: - def __init__(self, worker, shutdown_event, https_retry_event=None): + def __init__(self, worker, shutdown_event, https_retry_event=None, sites=None): self.worker = worker + self.sites = sites self.shutdown_event = shutdown_event self.icon = None self.https_retry_event = https_retry_event or threading.Event() @@ -246,6 +247,25 @@ def on_startup_toggle(icon, item): if self.icon: self.icon.update_menu() + def unlink_site(origin): + def handler(icon, item): + if self.sites: + self.sites.unlink(origin) + if self.icon: + self.icon.update_menu() + + return handler + + def linked_site_items(): + links = self.sites.links() if self.sites else {} + if not links: + yield MenuItem("No linked websites", None, enabled=False) + return + for origin, allowed in sorted(links.items()): + others = len(allowed) - 1 + label = origin if not others else f"{origin} (+{others} site{'s' if others != 1 else ''})" + yield MenuItem(label, Menu(MenuItem("Unlink", unlink_site(origin)))) + resolution_menu = Menu( MenuItem("160 DPI", set_resolution(160), checked=resolution_checked(160), radio=True, enabled=resolution_enabled), MenuItem("200 DPI", set_resolution(200), checked=resolution_checked(200), radio=True, enabled=resolution_enabled), @@ -317,6 +337,7 @@ def on_startup_toggle(icon, item): ), MenuItem("Clear Default Scanner", clear_default_scanner, enabled=lambda item: not self.worker.is_busy()), MenuItem("Diagnostics", diagnostics_menu), + MenuItem("Linked Websites", Menu(linked_site_items)), Menu.SEPARATOR, MenuItem("Run on Startup", on_startup_toggle, checked=lambda item: is_startup_enabled()), MenuItem("Quit", on_quit), diff --git a/utils.py b/utils.py index 23ffd3a..4203397 100644 --- a/utils.py +++ b/utils.py @@ -7,6 +7,7 @@ import io import tempfile from logging.handlers import RotatingFileHandler +from urllib.parse import urlsplit try: from PIL import Image as PilImage @@ -49,6 +50,7 @@ def load_app_version(): DEFAULT_SCAN_TIMEOUT_SECONDS = 600 DEFAULT_GUI_TASK_TIMEOUT_SECONDS = 900 DEFAULT_SCAN_IDLE_TIMEOUT_SECONDS = 45 +SCAN_JOB_DIRECTORY_PREFIX = "scanlink-job-" DEFAULT_RESOLUTION = 200 DEFAULT_SCAN_SOURCE = "adf" DEFAULT_SCAN_SIDE = "front" @@ -135,7 +137,53 @@ def _apply_scan_profile_migration(config): config["color_mode"] = DEFAULT_COLOR_MODE config["paper_protection"] = False +def normalize_origin(value): + """``scheme://host[:port]`` for an http(s) website origin, as browsers send it; else None. + + Wildcards, paths, credentials and the opaque ``null`` origin are refused. + """ + if not isinstance(value, str) or not value or len(value) > 255: + return None + try: + parts = urlsplit(value.strip()) + port = parts.port + except ValueError: + return None + if parts.scheme not in ("http", "https") or not parts.hostname: + 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): + return None + if ":" in host: + host = f"[{host}]" + default_port = 443 if parts.scheme == "https" else 80 + return f"{parts.scheme}://{host}" + (f":{port}" if port and port != default_port else "") + +def _origin_list(values): + origins = [] + for value in values if isinstance(values, list) else []: + origin = normalize_origin(value) + if origin and origin not in origins: + origins.append(origin) + return origins + +def _linked_sites(value): + links = {} + for origin, link in (value.items() if isinstance(value, dict) else ()): + origin = normalize_origin(origin) + if not origin or not isinstance(link, dict): + continue + sites = _origin_list(link.get("sites")) + if origin not in sites: + sites.insert(0, origin) + links[origin] = {"sites": sites, "linked_at": str(link.get("linked_at") or "")} + return links + def _normalize_config(config): + config["cors_origins"] = _origin_list(config.get("cors_origins")) + config["linked_sites"] = _linked_sites(config.get("linked_sites")) config["scan_profile_version"] = int(config.get("scan_profile_version") or SCAN_PROFILE_VERSION) config["scan_source"] = _coerce_choice(config.get("scan_source"), SCAN_SOURCE_OPTIONS, DEFAULT_SCAN_SOURCE) config["scan_side"] = _coerce_choice(config.get("scan_side"), SCAN_SIDE_OPTIONS, DEFAULT_SCAN_SIDE) @@ -159,7 +207,8 @@ def load_config(): "default_scanner": None, "show_scanner_ui": False, "paper_protection": False, - "cors_origins": ["*"], + "cors_origins": [], + "linked_sites": {}, "job_ttl_seconds": DEFAULT_JOB_TTL_SECONDS, "result_ttl_seconds": DEFAULT_RESULT_TTL_SECONDS, "scan_timeout_seconds": DEFAULT_SCAN_TIMEOUT_SECONDS, diff --git a/worker.py b/worker.py index 455597e..e19932b 100644 --- a/worker.py +++ b/worker.py @@ -17,11 +17,14 @@ requests = None from scanner import ScanError, ScannerManager -from utils import get_logger, load_config +from utils import SCAN_JOB_DIRECTORY_PREFIX, get_logger, load_config logger = get_logger() TERMINAL_STATUSES = {"completed", "failed", "cancelled", "timed_out"} +# get_job()/consume_result() default for in-process callers; the server always +# passes the requesting browser Origin (None for local tools). +ANY_ORIGIN = object() # Covers child startup and a graceful TWAIN close after the child's own deadline. SCAN_TIMEOUT_GRACE_SECONDS = 15 @@ -80,12 +83,16 @@ def __init__(self, gui_task_queue): self.scan_idle_timeout_seconds = int(config.get("scan_idle_timeout_seconds", 45)) self.scan_timeout_grace_seconds = SCAN_TIMEOUT_GRACE_SECONDS - def submit_job(self, doc_id=None, callback_url=None, metadata=None, source="api"): + def submit_job( + self, doc_id=None, callback_url=None, metadata=None, source="api", origin=None + ): with self.jobs_lock: self._cleanup_expired_jobs_locked() active_job_id = self._find_active_job_id_locked() if active_job_id: - raise BusyError(active_job_id=active_job_id) + active_job = self.jobs.get(active_job_id) or {} + owned = active_job.get("origin") == origin + raise BusyError(active_job_id=active_job_id if owned else None) job_id = str(uuid.uuid4()) now = time.time() @@ -103,6 +110,7 @@ def submit_job(self, doc_id=None, callback_url=None, metadata=None, source="api" "result_bytes": None, "result_retrieved_at": None, "source": source, + "origin": origin, "error": None, } @@ -111,16 +119,16 @@ def submit_job(self, doc_id=None, callback_url=None, metadata=None, source="api" emit_status(job_id, "queued", doc_id=doc_id) return self.get_job(job_id) - def get_job(self, job_id): + def get_job(self, job_id, origin=ANY_ORIGIN): with self.jobs_lock: self._cleanup_expired_jobs_locked() - job = self.jobs.get(job_id) + job = self._visible_job_locked(job_id, origin) return self._serialize_job(job) if job else None - def consume_result(self, job_id): + def consume_result(self, job_id, origin=ANY_ORIGIN): with self.jobs_lock: self._cleanup_expired_jobs_locked() - job = self.jobs.get(job_id) + job = self._visible_job_locked(job_id, origin) if not job: return None, None @@ -255,7 +263,7 @@ def run_gui_task(self, func, timeout=30): return self._execute_gui(func, timeout=timeout) def _run_scan_subprocess(self, job_id, on_progress): - work_dir = tempfile.mkdtemp(prefix="scanlink-job-") + work_dir = tempfile.mkdtemp(prefix=SCAN_JOB_DIRECTORY_PREFIX) state_path = os.path.join(work_dir, "state.json") result_path = os.path.join(work_dir, "result.pdf") request_path = os.path.join(work_dir, "request.json") @@ -436,6 +444,12 @@ def _send_callback(self, job, pdf_bytes): except Exception as exc: logger.error(f"Callback error for job {job['job_id']}: {exc}") + def _visible_job_locked(self, job_id, origin): + job = self.jobs.get(job_id) + if job and origin is not ANY_ORIGIN and job.get("origin") != origin: + return None + return job + def _find_active_job_id_locked(self): if self.current_job_id: return self.current_job_id