From 8345a6e821edf2e872f9e571925d00bd4bc72b8b Mon Sep 17 00:00:00 2001 From: debeski Date: Wed, 25 Nov 2026 11:07:32 +0200 Subject: [PATCH 1/2] fix: deliver scan callbacks, to linked websites only A finished scan was never posted to its callback_url: since 36249b6 (2026-04-28) _process_job handed _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, no redirects, 2xx only). Delivery alone would let any page post a scanned document to a host of its choosing through a scanlink:// link, so 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; a local tool or scanlink:// link may name any linked or listed website. The worker checks at submission (400 callback_not_allowed; a refused scanlink:// launch never scans) and again before sending, and fails closed without a guard. Jobs report callback.state; the PDF stays available to poll either way. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + docs/api.md | 26 ++++- docs/architecture.md | 10 +- docs/developer-guide.md | 19 +++- main.py | 8 +- server.py | 8 +- sites.py | 36 ++++++- tests/test_callbacks.py | 209 ++++++++++++++++++++++++++++++++++++++++ utils.py | 17 ++++ worker.py | 133 ++++++++++++++++++------- 10 files changed, 424 insertions(+), 46 deletions(-) create mode 100644 tests/test_callbacks.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 64a6cc0..420325f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ This file owns the release history for `ScanLink`. +## Unreleased + +- **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. + ## v0.8.0 - **Stable 0.8.0 For DjangoLux 1.16 (security)**: Promote the published and accepted 0.8.0b3, which includes 0.8.0b1 and b2. No website can scan until the operator allows it once (`POST /link`; `cors_origins` ignores wildcards); the API answers only loopback hosts, refuses cross-site control requests, limits request bodies and keeps each scan to the origin that started it. Scans survive slow scanners and worker failures (deadline grace, atomic PDF completion, single-use results). Needs DjangoLux 1.16.0 or later. No changes from the beta. diff --git a/docs/api.md b/docs/api.md index cf27cbf..1241942 100644 --- a/docs/api.md +++ b/docs/api.md @@ -80,6 +80,12 @@ 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. +- 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. + +Anything else is refused before a scan starts. The [Developer Guide](developer-guide.md#callback-url) describes how the scan is delivered. + Response `202`: ```json @@ -96,6 +102,7 @@ Errors: | 400 | `invalid_json` | Body could not be parsed as JSON. | | 400 | `invalid_payload` | JSON root was not an object. | | 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. | | 409 | `busy` | Another scan job is queued or running. | | 413 | `payload_too_large` | Request body exceeded 64 KB. | @@ -139,6 +146,21 @@ Response: } ``` +A job started with a callback URL also reports how the callback went, without the URL itself: + +```json +"callback": {"state": "delivered", "status_code": 201} +``` + +| `state` | Meaning | +| --- | --- | +| `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. | +| `not_sent` | The scan ended without a PDF. | + Terminal failure response: ```json @@ -179,7 +201,7 @@ Errors: ## POST /internal/protocol/scan -Requires an `application/json` object and applies the same metadata/callback validation as `/scan`; malformed requests never queue a scan. The optional `action` must be `scan`. +Requires an `application/json` object and applies the same metadata/callback validation as `/scan`; malformed requests never queue a scan. A callback must point at an allowed website, as for a local tool on `/scan`; otherwise the request fails with `400 callback_not_allowed`. The optional `action` must be `scan`. Internal endpoint used by `scanlink://` launches to forward commands into an already-running ScanLink instance. Application integrations should normally use `POST /scan`. @@ -243,6 +265,8 @@ any work is done; only `POST /link` is open to every website. Preflights carryin Access requires for a public website calling the loopback helper. Job ownership keeps each allowed website away from scans started by others. +The same list decides where a finished scan may be posted: a `callback_url` +must point at an allowed website (see [`POST /scan`](#post-scan)). ## POST /link diff --git a/docs/architecture.md b/docs/architecture.md index e6869a9..74f5cd9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -236,8 +236,14 @@ the first enabled deadline terminates the child, even if it keeps reporting progress. The scan deadline includes a 15-second grace (`SCAN_TIMEOUT_GRACE_SECONDS` 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. Unparseable callback URLs are skipped without -affecting the stored PDF. Idle timeout remains an independent progress guard. Downloading frees +parent force-terminates it. + +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. +- **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. diff --git a/docs/developer-guide.md b/docs/developer-guide.md index c42a016..3f50029 100644 --- a/docs/developer-guide.md +++ b/docs/developer-guide.md @@ -149,11 +149,19 @@ Example with callback: If ScanLink is already running, a protocol launch forwards the command to the existing tray instance through the internal local endpoint. +Any web page can open a `scanlink://` link, so a link whose callback is not an allowed website is refused and never scans (see [Callback URL](#callback-url)). + ## Callback URL When `callback_url` is provided, ScanLink posts the completed PDF to that URL after a successful scan. -The callback request is `multipart/form-data` with: +**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. +- **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. + +**The request.** A `multipart/form-data` POST with: - `pdf`: scanned PDF file - `job_id`: ScanLink job ID @@ -161,6 +169,15 @@ The callback request is `multipart/form-data` with: - `page_count`: number of scanned pages - `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. +- 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)). + +**The receiving endpoint.** The request carries no session cookie or CSRF token. Accept it only for a `job_id` or `doc_id` your application issued, and exempt that one endpoint from CSRF. + Use callbacks when your backend can receive files directly and you do not want the browser to upload the PDF after polling. ## Status Lifecycle diff --git a/main.py b/main.py index d3a7fee..1e9eaf2 100644 --- a/main.py +++ b/main.py @@ -18,7 +18,7 @@ from sites import LINK_PROMPT_SECONDS, SiteRegistry from tray import TrayApp from utils import APP_VERSION, ensure_ssl_certificates, get_logger, load_config, setup_logging -from worker import ScanWorker, set_status_callback +from worker import CallbackNotAllowedError, ScanWorker, set_status_callback def main(): @@ -98,6 +98,7 @@ def confirm_link(origin, other_sites): config = load_config() sites = SiteRegistry(config["cors_origins"], config["linked_sites"], confirm=confirm_link) + worker.callback_guard = sites.allows_callback tray = TrayApp(worker, shutdown_event, https_retry_event, sites=sites) @@ -128,6 +129,11 @@ def queue_protocol_scan(): source="protocol", ) logger.info("Protocol-triggered scan queued locally") + except CallbackNotAllowedError: + logger.warning( + "Refused a scanlink:// scan whose callback %r is not a website linked to ScanLink", + protocol_command.get("callback_url"), + ) except Exception as exc: logger.error(f"Failed to queue protocol-triggered scan: {exc}") diff --git a/server.py b/server.py index f4d5e97..7d48cf2 100644 --- a/server.py +++ b/server.py @@ -22,7 +22,7 @@ normalize_origin, ) from sites import LinkError, SiteRegistry -from worker import BusyError +from worker import BusyError, CallbackNotAllowedError logger = get_logger() @@ -219,6 +219,8 @@ def start_scan(): source="api", origin=request.headers.get("Origin"), ) + except CallbackNotAllowedError as exc: + return error_response(400, "callback_not_allowed", str(exc)) except BusyError as exc: extra = {"active_job_id": exc.active_job_id} if exc.active_job_id else {} return error_response( @@ -301,10 +303,12 @@ def internal_protocol_scan(): try: job = worker.submit_job( doc_id=data.get("doc_id"), - callback_url=data.get("callback_url"), + callback_url=data.get("callback_url") or data.get("callback"), metadata=data.get("metadata"), source="protocol", ) + except CallbackNotAllowedError as exc: + return error_response(400, "callback_not_allowed", str(exc)) except BusyError as exc: return ( jsonify( diff --git a/sites.py b/sites.py index b81b6d8..a8af22d 100644 --- a/sites.py +++ b/sites.py @@ -12,7 +12,7 @@ import time from datetime import datetime, timezone -from utils import get_logger, load_config, normalize_origin, save_config +from utils import get_logger, load_config, normalize_origin, save_config, url_origin logger = get_logger() @@ -59,12 +59,38 @@ def __init__(self, listed=(), links=None, *, confirm=None, persist=save_links, c 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()) + return self._allowed_locked(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 + (``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. + """ + target = url_origin(callback_url) + if target is None: + return False + with self._lock: + if not self._allowed_locked(target): + return False + if requester is None: + return True + if not self._allowed_locked(requester): + return False + return target == requester or any( + requester in link["sites"] and target in link["sites"] + for link in self._links.values() ) + def _allowed_locked(self, origin): + 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) diff --git a/tests/test_callbacks.py b/tests/test_callbacks.py new file mode 100644 index 0000000..89e79d4 --- /dev/null +++ b/tests/test_callbacks.py @@ -0,0 +1,209 @@ +"""A finished scan reaches its callback URL, and only a linked website's.""" + +import io +import queue +import threading +import unittest +from unittest.mock import MagicMock, patch + +from sites import SiteRegistry +from worker import CallbackNotAllowedError, ScanWorker + +try: + import server +except ImportError: + server = None + +CRM = "https://crm.example" +SALES = "https://sales.example" +INTRANET = "https://intranet.example:8443" +EVIL = "https://evil.example" +PDF = b"%PDF-1.4\nscanned\n" + + +def registry(): + return SiteRegistry( + listed=[INTRANET], + links={CRM: {"sites": [SALES], "linked_at": "2026-11-25T00:00:00Z"}}, + persist=lambda links: None, + ) + + +def scan_worker(guard): + worker = ScanWorker(queue.Queue(), callback_guard=guard) + worker._run_scan_subprocess = lambda job_id, on_progress: io.BytesIO(PDF) + return worker + + +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) + if post_error is not None: + requests.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 + + +class AllowsCallbackTests(unittest.TestCase): + def test_local_callers_may_name_any_allowed_website(self): + sites = registry() + for url in (f"{CRM}/scans", f"{SALES}/upload?x=1", f"{INTRANET}/in"): + with self.subTest(url=url): + self.assertTrue(sites.allows_callback(url)) + self.assertFalse(sites.allows_callback(f"{EVIL}/steal")) + + def test_a_website_may_only_name_itself_or_the_sites_linked_with_it(self): + sites = registry() + self.assertTrue(sites.allows_callback(f"{CRM}/scans", CRM)) + self.assertTrue(sites.allows_callback(f"{SALES}/scans", CRM)) + self.assertTrue(sites.allows_callback(f"{CRM}/scans", SALES)) + self.assertFalse(sites.allows_callback(f"{INTRANET}/scans", CRM)) + self.assertTrue(sites.allows_callback(f"{INTRANET}/scans", INTRANET)) + self.assertFalse(sites.allows_callback(f"{CRM}/scans", INTRANET)) + self.assertFalse(sites.allows_callback(f"{EVIL}/scans", EVIL)) + + def test_disguised_and_malformed_urls_are_refused(self): + sites = registry() + for url in ( + "https://crm.example@evil.example/scans", + "https://user:pw@crm.example/scans", + "https://crm.example.evil.example/scans", + "http://crm.example/scans", + "https://crm.example:8443/scans", + "ftp://crm.example/scans", + "/relative/scans", + "http://[", + "", + None, + 5, + ): + with self.subTest(url=url): + self.assertFalse(sites.allows_callback(url)) + + +class CallbackDeliveryTests(unittest.TestCase): + def test_finished_scan_is_posted_to_its_callback(self): + worker = scan_worker(registry().allows_callback) + queued = worker.submit_job(doc_id="D-1", callback_url=f"{CRM}/scans/upload", origin=CRM) + + _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"]) + job = worker.get_job(queued["job_id"]) + self.assertEqual(job["callback"], {"state": "delivered", "status_code": 201}) + self.assertNotIn("callback_url", job) + _job, result = worker.consume_result(queued["job_id"]) + self.assertEqual(result, PDF) + + def test_unlinked_callback_is_refused_before_any_scan(self): + worker = scan_worker(registry().allows_callback) + with self.assertRaises(CallbackNotAllowedError): + worker.submit_job(callback_url=f"{EVIL}/steal") + with self.assertRaises(CallbackNotAllowedError): + worker.submit_job(callback_url=f"{INTRANET}/scans", origin=CRM) + self.assertTrue(worker.scan_queue.empty()) + self.assertEqual(worker.jobs, {}) + + def test_without_a_guard_every_callback_is_refused(self): + worker = scan_worker(None) + with self.assertRaises(CallbackNotAllowedError): + worker.submit_job(callback_url=f"{CRM}/scans") + self.assertIsNotNone(worker.submit_job(doc_id="no-callback")) + + def test_website_unlinked_during_the_scan_gets_nothing(self): + linked = {"now": True} + worker = scan_worker(lambda url, origin: linked["now"]) + queued = worker.submit_job(callback_url=f"{CRM}/scans", origin=CRM) + linked["now"] = False + + _job_id, post = run_queued_job(worker) + + 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): + 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) + + 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_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")) + + self.assertEqual(worker.get_job(queued["job_id"])["callback"], {"state": "failed", "reason": "unreachable"}) + _job, result = worker.consume_result(queued["job_id"]) + self.assertEqual(result, PDF) + + def test_failed_scan_reports_the_callback_as_not_sent(self): + worker = scan_worker(registry().allows_callback) + queued = worker.submit_job(callback_url=f"{CRM}/scans", origin=CRM) + self.assertEqual(worker.get_job(queued["job_id"])["callback"], {"state": "waiting"}) + + worker._fail_job(queued["job_id"], code="no_scanner", message="No scanner.") + + self.assertEqual(worker.get_job(queued["job_id"])["callback"], {"state": "not_sent"}) + + def test_slow_callback_does_not_hold_the_worker(self): + worker = scan_worker(registry().allows_callback) + 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) + 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) + + +@unittest.skipIf(server is None, "Flask is not installed in this environment") +class CallbackRequestTests(unittest.TestCase): + def setUp(self): + sites = registry() + self.worker = ScanWorker(queue.Queue(), callback_guard=sites.allows_callback) + self.client = server.create_app( + self.worker, threading.Event(), {"http_enabled": True, "https_enabled": False}, sites=sites + ).test_client() + + def test_browser_scan_with_a_foreign_callback_is_refused(self): + response = self.client.post( + "/scan", json={"callback_url": f"{EVIL}/steal"}, headers={"Origin": CRM} + ) + + self.assertEqual(response.status_code, 400) + self.assertEqual(response.get_json()["error"]["code"], "callback_not_allowed") + self.assertEqual(self.worker.jobs, {}) + + 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} + ) + + self.assertEqual(response.status_code, 202) + + def test_scanlink_link_with_a_foreign_callback_is_refused(self): + response = self.client.post("/internal/protocol/scan", json={"callback": f"{EVIL}/steal"}) + + self.assertEqual(response.status_code, 400) + self.assertEqual(response.get_json()["error"]["code"], "callback_not_allowed") + self.assertEqual(self.worker.jobs, {}) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils.py b/utils.py index 4203397..03d5523 100644 --- a/utils.py +++ b/utils.py @@ -161,6 +161,23 @@ def normalize_origin(value): default_port = 443 if parts.scheme == "https" else 80 return f"{parts.scheme}://{host}" + (f":{port}" if port and port != default_port else "") +def url_origin(url): + """The website origin an absolute http(s) URL points at; None for anything else. + + URLs carrying credentials are refused, so ``https://site@other.example`` can + never pass for ``site``. + """ + if not isinstance(url, str) or not url or len(url) > 2048: + return None + try: + parts = urlsplit(url.strip()) + parts.port # raises ValueError for a malformed port + except ValueError: + return None + if parts.username is not None or parts.password is not None or not parts.netloc: + return None + return normalize_origin(f"{parts.scheme}://{parts.netloc}") + def _origin_list(values): origins = [] for value in values if isinstance(values, list) else []: diff --git a/worker.py b/worker.py index e19932b..fcc4019 100644 --- a/worker.py +++ b/worker.py @@ -9,7 +9,6 @@ import threading import time import uuid -from urllib.parse import urlparse try: import requests @@ -27,6 +26,8 @@ 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) # Optional compatibility hook for future push-based status updates. _status_callback = None @@ -51,6 +52,11 @@ def __init__(self, active_job_id=None): self.active_job_id = active_job_id +class CallbackNotAllowedError(Exception): + def __init__(self): + super().__init__("callback_url must point to a website linked to ScanLink.") + + class GuiTaskTimeoutError(Exception): pass @@ -63,10 +69,15 @@ def __init__(self, code, message): class ScanWorker(threading.Thread): - def __init__(self, gui_task_queue): + def __init__(self, gui_task_queue, callback_guard=None): super().__init__(daemon=True) self.scan_queue = queue.Queue() self.gui_task_queue = gui_task_queue + # ``callback_guard(url, requester_origin)`` decides where finished scans + # may be posted (``SiteRegistry.allows_callback``); without one, every + # callback is refused. + self.callback_guard = callback_guard + self.callback_thread = None self.jobs = {} self.jobs_lock = threading.Lock() self.scanner_manager = ScannerManager() @@ -86,6 +97,9 @@ def __init__(self, gui_task_queue): def submit_job( self, doc_id=None, callback_url=None, metadata=None, source="api", origin=None ): + if callback_url and not self._callback_allowed(callback_url, origin): + raise CallbackNotAllowedError() + with self.jobs_lock: self._cleanup_expired_jobs_locked() active_job_id = self._find_active_job_id_locked() @@ -105,6 +119,8 @@ def submit_job( "completed_at": None, "doc_id": doc_id, "callback_url": callback_url, + "callback_state": "waiting" if callback_url else None, + "callback_detail": None, "metadata": metadata or {}, "page_count": 0, "result_bytes": None, @@ -207,7 +223,7 @@ def on_progress(status, **data): ) logger.info("Job %s completed with %s pages", job_id, job_snapshot.get("page_count", 0)) emit_status(job_id, "completed", page_count=job_snapshot.get("page_count", 0)) - self._send_callback(job_snapshot, pdf_bytes) + self._start_callback(job_id, pdf_bytes) except GuiTaskTimeoutError: self._fail_job( job_id, @@ -402,47 +418,91 @@ def _stop_active_scan_process(self): logger.warning("Stopping active scan subprocess during worker shutdown") self._terminate_scan_process(process) + def _callback_allowed(self, callback_url, origin): + guard = self.callback_guard + if guard is None: + return False + try: + return bool(guard(callback_url, origin)) + except Exception: + logger.exception("Could not check the callback destination %r", callback_url) + return False + + def _start_callback(self, job_id, pdf_bytes): + """Post a finished scan to its callback without holding up the next scan.""" + with self.jobs_lock: + job = self.jobs.get(job_id) + if not job or not job.get("callback_url"): + return + delivery = { + key: job.get(key) + 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]}", + ) + self.callback_thread = thread + thread.start() + def _send_callback(self, job, pdf_bytes): callback_url = job.get("callback_url") if not callback_url: return + job_id = job["job_id"] + # 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 + ) + self._record_callback(job_id, "refused", reason="not_linked") + return if requests is None: - logger.warning("requests is not installed; skipping callback delivery for job %s", job["job_id"]) + 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", + } try: - parsed = urlparse(callback_url) - except ValueError: - parsed = None - if not parsed or parsed.scheme not in {"http", "https"} or not parsed.netloc: - logger.warning("Skipping callback for job %s because callback_url is not absolute: %s", job["job_id"], callback_url) + # No redirects: a linked website must not hand the document on elsewhere. + response = requests.post( + callback_url, + files=files, + data=data, + timeout=CALLBACK_TIMEOUT_SECONDS, + allow_redirects=False, + ) + except Exception as exc: + logger.error("Could not send job %s to %s: %s", job_id, callback_url, exc) + self._record_callback(job_id, "failed", reason="unreachable") return - try: - files = { - "pdf": ( - f"scan_{job['job_id']}.pdf", - pdf_bytes, - "application/pdf", - ) - } - data = { - "job_id": job["job_id"], - "doc_id": job.get("doc_id"), - "page_count": job.get("page_count", 0), - "status": "completed", - } - response = requests.post(callback_url, files=files, data=data, timeout=30) - if response.ok: - logger.info("Callback sent to %s for job %s", callback_url, job["job_id"]) - else: - logger.warning( - "Callback for job %s failed with status %s", - job["job_id"], - response.status_code, - ) - except Exception as exc: - logger.error(f"Callback error for job {job['job_id']}: {exc}") + 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) + else: + logger.warning( + "Callback for job %s answered %s; the result stays available to poll", + job_id, + response.status_code, + ) + self._record_callback(job_id, "failed", status_code=response.status_code) + + def _record_callback(self, job_id, state, **detail): + with self.jobs_lock: + job = self.jobs.get(job_id) + if job: + job["callback_state"] = state + job["callback_detail"] = detail or None def _visible_job_locked(self, job_id, origin): job = self.jobs.get(job_id) @@ -486,6 +546,11 @@ def _serialize_job(self, job): response["metadata"] = job["metadata"] if job.get("error"): response["error"] = dict(job["error"]) + callback_state = job.get("callback_state") + if callback_state: + if callback_state == "waiting" and job["status"] in TERMINAL_STATUSES: + callback_state = "sending" if job["status"] == "completed" else "not_sent" + response["callback"] = {"state": callback_state, **(job.get("callback_detail") or {})} return response def _cleanup_expired_jobs(self): From cee82a8910cb1af89c71e40c4ba1c08ae6423f18 Mon Sep 17 00:00:00 2001 From: debeski Date: Wed, 25 Nov 2026 23:41:25 +0200 Subject: [PATCH 2/2] release: ScanLink 0.8.1b1 Callbacks delivered, to linked websites only (owner: "deliver callbacks"). Paired with the DjangoLux 1.17 fix line; DjangoLux never sends callback_url, so no client change. 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 420325f..9dd4210 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ This file owns the release history for `ScanLink`. -## Unreleased +## 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/VERSION b/VERSION index a3df0a6..2afe79a 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.8.0 +0.8.1b1