Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

This file owns the release history for `ScanLink`.

## 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.

## 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.
Expand Down
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.8.0
0.8.1b1
26 changes: 25 additions & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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. |
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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`.

Expand Down Expand Up @@ -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

Expand Down
10 changes: 8 additions & 2 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
19 changes: 18 additions & 1 deletion docs/developer-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,18 +149,35 @@ 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://[email protected]`) 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
- `doc_id`: document ID from the original request, if provided
- `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/<job_id>/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
Expand Down
8 changes: 7 additions & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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}")

Expand Down
8 changes: 6 additions & 2 deletions server.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
normalize_origin,
)
from sites import LinkError, SiteRegistry
from worker import BusyError
from worker import BusyError, CallbackNotAllowedError

logger = get_logger()

Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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(
Expand Down
36 changes: 31 additions & 5 deletions sites.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading