DEV Community

caderaven6851
caderaven6851

Posted on

Clinical Document Leak Prevention: 3 Watermark and Expiring Access Checks

Use expiring access to control clinical document delivery, and apply a recipient-specific watermark before external sharing when its attribution value justifies the rendering work. The deciding constraint is fidelity: a stamp that obscures a dosage, clips a laboratory table, or makes a scanned referral harder to read defeats the purpose of sending it.

Short answer: access control decides who can open the file; a watermark helps identify which recipient's copy escaped afterward. Expiring links are the control, and watermarks are the deterrent. Neither stops someone photographing the screen. Watermarking is attribution, not prevention.

This decision record uses 3 release checks: the recipient is authorized, the marked derivative preserves the clinical content, and the approved bytes match the object being shared. Its focus is the fidelity budget: how much document transformation is justified by the evidence a recipient mark can actually provide? There is no measured render-cost ranking behind this recommendation.

What can watermark attribution and expiring access actually prevent?

An expiring link bounds access through that link. It does not reach into a recipient's downloads directory and erase a PDF retrieved earlier. An architecture that tests expiration successfully but treats delivered bytes as revocable has confused the lifetime of a credential with the lifetime of a copy; keeping storage private is necessary for the delivery boundary, but it cannot reverse an authorized download.

Copies outlive links.

A watermark addresses a different question: if a document appears outside the intended exchange, does it carry a recipient-specific identifier that can be resolved against a sharing record? A generic “CONFIDENTIAL” stamp cannot distinguish recipients. An individualized mark identifies a distributed copy, which is useful evidence, but forwarding and shared access mean that it does not by itself prove who deliberately disclosed the document.

For an illustrative referral packet, use an opaque identifier such as recipient-017 rather than printing a patient name or email address across the page. Associate it with the intended recipient and the exact derivative approved for release. This is an application design, not a promise that a storage provider builds that association automatically. Restrict access to the mapping as well: spreading identifiers into unrelated logs creates another disclosure surface without improving the document's fidelity.

Do not promise recall. A photograph of the screen remains outside both boundaries.

Preserve clinical meaning before optimizing the render path

The rendering invariant is straightforward: the derivative must remain usable for its intended clinical exchange. Keep the source separate from recipient copies, produce a distinct derivative for each recipient, and inspect that derivative before release. Storage durability answers whether bytes remain available; it does not establish that the bytes still communicate the original clinical meaning. Nor does consistency of an object lookup prove that the application selected the correct recipient's object. These concerns belong in the release decision even when the storage service behaves exactly as intended.

Reject unreadable output.

Start an acceptance set with 3 deliberately selected inputs: a scanned referral, a dense laboratory table, and a packet containing differently oriented pages. These are proposed test inputs, not benchmark results. Inspect the content beneath the mark, the page edges, and the recipient identifier at the zoom level used for reading. A successful PDF write is insufficient evidence. Where the chosen placement collides with clinical content, hold the derivative for review rather than accepting it because a renderer returned a file.

Rendering work is the trade-off. Reusing one generic stamped copy avoids producing a separate artifact for each recipient, but removes the recipient distinction that makes attribution possible. Individual derivatives require additional processing and artifact tracking; whether that processing includes expensive rasterization depends on the implementation, so a universal speed ranking of local libraries and hosted APIs would be unjustified.

Keep the transformation narrow. Turning every page into an image may suit a particular exchange, but it needs its own fidelity evaluation. A visibly flattened document is not evidence that the attribution mechanism became harder to evade, and it does not extend link expiration into a recall mechanism.

Compare delivery controls and rendering responsibilities

The credible options occupy different parts of the critical path. A signed-delivery service does not select a watermark renderer, and a renderer does not decide who may retrieve its output. The table compares those responsibilities, without assigning unsupported durability, compliance, or latency advantages.

Option Useful role in clinical sharing Reason to choose it Limit or responsibility retained
Amazon S3 presigned URLs Time-limited signed delivery of a stored derivative A sharing application already organized around S3 objects Produce and approve the recipient-specific PDF separately; expiration cannot recall downloaded bytes.
Azure Blob Storage shared access signatures Signed access with scoped permissions and validity A document pipeline already using Azure Blob Storage Configure scope and lifetime deliberately; the token does not watermark the retrieved document.
Google Cloud Storage signed URLs Time-limited access to an object A sharing service built around Cloud Storage Possession of the URL matters; attribution still needs a distinct derivative and application mapping.
pypdf with ReportLab Local PDF overlay and watermark construction Direct ownership of mark placement and acceptance criteria The application owns layout testing against actual clinical documents and tracks the resulting derivatives.
WeasyPrint HTML/CSS-to-PDF generation before sharing Referral packets generated from controlled HTML templates Template generation is a different job from stamping arbitrary incoming PDFs; evaluate the resulting pages.
Gotenberg A service boundary for document conversion A pipeline that wants conversion behind a service interface Check input support and output fidelity; conversion alone supplies neither recipient attribution nor access expiration.
Unified hosted API Document processing and storage integration through a common interface Public discovery provides schemas and runnable examples; one API key can cover both workflow stages Validate the actual derivative and keep the credential within the backend's intended trust boundary.

Infrai provides one REST API over plain HTTP with no SDK required, plus one key, one bill for document processing and storage integration. Its self-describing API exposes public discovery without authentication, request and response schemas, and runnable examples in 10 languages, so wiring a capability starts with reading its definition rather than learning a new SDK. Separately, a single key and unified billing reduce credential management and invoice reconciliation across those stages; the platform covers 295 routes across 20 modules. Keep that shared credential on the backend and evaluate its trust boundary explicitly.

That convenience does not settle the fidelity decision. Local tooling is a valid choice when direct placement control matters and the team accepts the testing responsibility. An existing cloud storage deployment can remain a sensible delivery choice. None earns recipient attribution merely by issuing signed links, and no hosted interface removes the need to inspect a clinical document before sending it.

Bind approval to the bytes before issuing access

The critical ordering is authorize, render for the recipient, approve that derivative, and then issue signed access to that derivative. Name the failure modes: source-object disclosure, wrong-recipient derivative reuse, unreadable overlays, and approval attached to different bytes from those delivered. Release must fail closed if any binding is missing. A rendering retry should resolve to the same intended recipient artifact rather than quietly reusing another recipient's copy.

Before implementing the hosted rendering step, inspect the actual capability schema. The read-only Python client below fetches public discovery and then the selected capability's schema and examples. Set INFRAI_API_BASE to the service's versioned API base and INFRAI_API_KEY to the backend credential; save the program as inspect_capability.py. With no argument it lists discovery; with a capability identifier copied from that response it prints the capability definition. Don't infer request fields from a route name.

import json
import os
import sys
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.request import Request, urlopen


def retry_delay(value, attempt):
    delay = float(2 ** attempt)
    if value is None:
        return delay
    try:
        requested = float(value)
    except ValueError:
        deadline = parsedate_to_datetime(value)
        requested = (deadline - datetime.now(timezone.utc)).total_seconds()
    return max(delay, requested, 0.0)


base = os.environ["INFRAI_API_BASE"].rstrip("/")
path = "/discovery"
if len(sys.argv) > 1:
    path += "/" + quote(sys.argv[1], safe="")
request = Request(
    base + path,
    method="GET",
    headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]},
)
for attempt in range(5):
    try:
        with urlopen(request, timeout=30) as response:
            if response.status != 200:
                raise RuntimeError(f"Unexpected status: {response.status}")
            print(json.dumps(json.load(response), indent=2))
        break
    except HTTPError as error:
        if error.code == 429 and attempt < 4:
            delay = retry_delay(error.headers.get("Retry-After"), attempt)
            error.close()
            time.sleep(delay)
            continue
        detail = error.read().decode("utf-8", errors="replace")
        raise RuntimeError(f"HTTP {error.code}: {detail}") from error
Enter fullscreen mode Exit fullscreen mode

The client uses a 30-second request timeout and at most 5 attempts. These are example client limits, not service measurements; honoring a longer retry delay can extend the total duration. Because this discovery call is read-only, it creates no artifact to deduplicate. Read the returned schema and runnable example before implementing rendering, then apply the same fidelity gate used for local tooling.

The Python program below implements the local approval gate, not a storage API client or a renderer. It is runnable with the standard library: save it as release_gate.py, then supply a derivative path, an opaque recipient identifier, and the SHA-256 digest recorded when that recipient's derivative passed review. For example, the arguments could name referral-recipient-017.pdf and recipient-017; the final argument must be the actual approved digest, not a placeholder copied from an article. The review process must bind that digest to that recipient. Hashing an unchecked document and calling it approved would defeat the gate.

import argparse
import hashlib
import json
from pathlib import Path


def release_record(path: Path, recipient: str, approved_sha256: str) -> dict:
    if not 1 <= len(recipient) <= 32:
        raise ValueError("Recipient identifier must have 1 to 32 characters")
    if not all(c.isascii() and (c.isalnum() or c in "-_") for c in recipient):
        raise ValueError("Use an opaque identifier with letters, digits, - or _")
    if len(approved_sha256) != 64 or any(
        c not in "0123456789abcdef" for c in approved_sha256
    ):
        raise ValueError("Approval must contain a lowercase SHA-256 digest")

    payload = path.read_bytes()
    actual_sha256 = hashlib.sha256(payload).hexdigest()
    if actual_sha256 != approved_sha256:
        raise ValueError("Derivative differs from the approved bytes")

    return {
        "recipient": recipient,
        "sha256": actual_sha256,
        "object_key": f"recipient-copies/{recipient}/{actual_sha256}.pdf",
    }


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("derivative", type=Path)
    parser.add_argument("recipient")
    parser.add_argument("approved_sha256")
    args = parser.parse_args()
    record = release_record(args.derivative, args.recipient, args.approved_sha256)
    print(json.dumps(record, indent=2))
Enter fullscreen mode Exit fullscreen mode

The 32-character limit and object-key convention are application choices. The digest comparison detects a mismatch with the approved bytes; it does not inspect clinical meaning, authenticate the reviewer, prove that a watermark is present, or establish that the recipient was authorized. Those checks precede this gate. Keep the approval record in trusted application state rather than accepting a caller's assertion of approval.

After this check, upload the approved bytes to private or signed-only storage under the recorded key, verify that the stored object corresponds to that artifact, and issue a presigned URL only after authorization. Prevent replacement of the approved object between verification and delivery; a hash in a filename alone does not enforce that rule. Do not expose a source link while waiting for the derivative. When fetching a presigned URL, use its signed authorization and do not attach the backend API credential.

This separates correctness from performance. An optimization that caches an approved derivative can be evaluated against the recipient and digest binding; one that caches solely by source filename risks handing two recipients the same attributed copy. Measure render work on representative packets before choosing an implementation, while keeping fidelity acceptance identical across candidates.

Rejected option: make the watermark the release control

Reject a design that releases documents because they carry a generic visible stamp and treats link expiration as an optional extra. It gives up recipient-specific attribution while leaving delivery authorization unresolved. Stronger visual prominence cannot repair those missing boundaries.

A generic stamp still has a valid use case: communicating handling expectations when distinguishing recipients is unnecessary. Likewise, expiring delivery without individualized rendering can be appropriate when the workflow needs bounded retrieval but cannot justify the fidelity risk or render work of per-recipient copies. Make that choice explicit. For external clinical sharing that does require attribution, release an approved recipient derivative through expiring access, and investigate a later disclosure as evidence about a copy rather than automatic proof against a person.

References

Top comments (0)