From 29b79db8060bb5caa4dfc107f6df5b7c45abd0d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Tue, 10 Nov 2026 10:47:08 -0300 Subject: [PATCH 1/2] fix: a PDF's resolution is worked out at the scan, not at checkout create_quote downloaded every PDF sheet (up to 150 MB) and parsed it inside the customer's request, behind nginx's 30 s. The worker's scan already reads every upload before the Site lets the customer continue, so it now stores the PDF's DPI on the upload (uploads.pdf_checked, pdf_dpi) and the checkout reads the number. An upload scanned before this, or whose work-out failed, is read at checkout as before (Critical Corrections 2, step 2). Co-Authored-By: Claude Opus 5.5 (1M context) --- app/grade_check.py | 25 +++++++++++++------ .../202611101200_upload-pdf-dpi.sql | 4 +++ app/scanning.py | 15 ++++++++++- tests/scanning_test.py | 20 ++++++++++++++- tests/test_grade_check.py | 11 ++++++++ 5 files changed, 65 insertions(+), 10 deletions(-) create mode 100644 app/migrations/202611101200_upload-pdf-dpi.sql diff --git a/app/grade_check.py b/app/grade_check.py index 6c46521..cd9686d 100644 --- a/app/grade_check.py +++ b/app/grade_check.py @@ -15,8 +15,10 @@ again, by the Site's own rules: is only vectors (web/site-pdf.js, dpiDasImagens and resumoDpi). Images are measured from their first bytes, never decoded. A PDF is opened -only up to PDF_MAX_BYTES, the size the Site itself analyses. A grade that -cannot be recomputed is None; the caller decides what that means. +only up to PDF_MAX_BYTES, the size the Site itself analyses. Its DPI is worked +out when the scan finishes and stored on the upload row (pdf_checked), so +checkout uses the stored number and opens the file only when it is absent. A +grade that cannot be recomputed is None; the caller decides what that means. """ import math import os @@ -130,6 +132,16 @@ def pdf_dpi(path): return js_round(sum(dpi * area for dpi, area in found) / total) +def stored_pdf_dpi(storage, row): + """A stored PDF's DPI, read once; None when it is above PDF_MAX_BYTES.""" + if row['size'] > PDF_MAX_BYTES: + return None + with tempfile.NamedTemporaryFile(suffix='.pdf') as handle: + storage.client.download_fileobj(storage.bucket, row['object_key'], handle) + handle.flush() + return pdf_dpi(handle.name) + + class Files: """The uploaded files, read from storage as little as needed.""" @@ -150,13 +162,10 @@ class Files: def pdf_dpi(self, row): key = row['object_key'] if key not in self._dpis: - if row['size'] > PDF_MAX_BYTES: - self._dpis[key] = None + if row.get('pdf_checked'): + self._dpis[key] = row['pdf_dpi'] else: - with tempfile.NamedTemporaryFile(suffix='.pdf') as handle: - self.storage.client.download_fileobj(self.storage.bucket, key, handle) - handle.flush() - self._dpis[key] = pdf_dpi(handle.name) + self._dpis[key] = stored_pdf_dpi(self.storage, row) return self._dpis[key] diff --git a/app/migrations/202611101200_upload-pdf-dpi.sql b/app/migrations/202611101200_upload-pdf-dpi.sql new file mode 100644 index 0000000..f932b68 --- /dev/null +++ b/app/migrations/202611101200_upload-pdf-dpi.sql @@ -0,0 +1,4 @@ +-- The PDF's resolution, worked out at the scan (Critical Corrections 2): pdf_checked +-- false = not worked out yet (checkout reads as before), NULL pdf_dpi with it true = unreadable. +ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS pdf_checked boolean NOT NULL DEFAULT false; +ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS pdf_dpi integer; diff --git a/app/scanning.py b/app/scanning.py index 9f48193..a796bc9 100644 --- a/app/scanning.py +++ b/app/scanning.py @@ -8,6 +8,7 @@ are those of the format its name claims (a PNG that really is a PNG, not a program renamed .png). That is the check the client chose for large files; it does not look for malware inside a valid file. """ +import logging import re import socket import struct @@ -16,6 +17,7 @@ from fastapi import HTTPException from .core.auth import audit from .core.db import connect from .core.limits import scan_limit_bytes +from .grade_check import stored_pdf_dpi def require_clean(row): if not row['complete'] or row['scan_state'] != 'clean': @@ -144,10 +146,21 @@ def scan_one(storage, scanner=None): finally:stream.close() except Exception: state,reason='error','Malware scanner unavailable; file remains blocked' + # A PDF's resolution is worked out here, once, so checkout never reads + # it (Critical Corrections 2). A failure leaves it for the fallback. + checked,pdf_dpi_value=False,None + if state=='clean' and name.lower().endswith('.pdf'): + try: + pdf_dpi_value=stored_pdf_dpi(storage,row) + checked=True + except Exception: + logging.exception('Could not work out the PDF DPI of upload %s',row['id']) c.execute("""UPDATE dtf_local.uploads SET name=%s,scan_state=%s,scan_reason=%s,scanned_at=now(), scan_after=now()+interval '1 minute', + pdf_checked=CASE WHEN %s THEN true ELSE pdf_checked END, + pdf_dpi=CASE WHEN %s THEN %s ELSE pdf_dpi END, expires_at=CASE WHEN %s IN ('rejected','error') THEN LEAST(expires_at,now()+interval '3 days') ELSE expires_at END - WHERE id=%s""",(name,state,reason,state,row['id'])) + WHERE id=%s""",(name,state,reason,checked,checked,pdf_dpi_value,state,row['id'])) audit('artwork_scan', upload=str(row['id']), result=state, c=c) return True diff --git a/tests/scanning_test.py b/tests/scanning_test.py index cca8757..2426faa 100644 --- a/tests/scanning_test.py +++ b/tests/scanning_test.py @@ -1,5 +1,10 @@ """Harmless EICAR anti-malware test and blocked download/quote regressions.""" +import io from uuid import uuid4 + +from PIL import Image + +from app.core import db from tests.smoke_test import Client, upload_bytes, item_spec def run(): @@ -12,6 +17,19 @@ def run(): 'items':[item_spec('file','1',0,uid)],'freight':{'service':'pickup'}},expected=409) clean=upload_bytes(customer,b'Harmless local artwork fixture',name='SECURITY-CLEAN.cdr') customer.call('/operator/uploads/'+clean+'/download',operator=True) - print('PASS: real ClamAV detects EICAR; rejected artwork cannot be downloaded or quoted; clean artwork is released.') + # A PDF is measured when the scan finishes, so checkout never downloads it. + out=io.BytesIO() + Image.new('RGB',(600,300),'white').save(out,'PDF',resolution=150) + pdf=upload_bytes(customer,out.getvalue(),name='SCAN-PDF.cdr') + with db.connect() as c: + rows={str(row['id']):row for row in c.execute( + 'SELECT id,name,pdf_checked,pdf_dpi FROM dtf_local.uploads WHERE id::text=ANY(%s)', + ([pdf,uid,clean],)).fetchall()} + assert rows[pdf]['name'].lower().endswith('.pdf'),rows[pdf] + assert rows[pdf]['pdf_checked'] is True,rows[pdf] + assert isinstance(rows[pdf]['pdf_dpi'],int) and rows[pdf]['pdf_dpi']>0,rows[pdf] + for not_pdf in (uid,clean): + assert rows[not_pdf]['pdf_checked'] is False,rows[not_pdf] + print('PASS: real ClamAV detects EICAR; rejected artwork cannot be downloaded or quoted; clean artwork is released; the scanned PDF carries its DPI.') if __name__=='__main__':run() diff --git a/tests/test_grade_check.py b/tests/test_grade_check.py index 70aafba..f35b2fc 100644 --- a/tests/test_grade_check.py +++ b/tests/test_grade_check.py @@ -114,6 +114,17 @@ class GradeCheckTests(unittest.TestCase): self.assertEqual(files.head(png_row)[:8], b'\x89PNG\r\n\x1a\n') self.assertEqual(storage.heads, 1) + def test_a_scanned_pdf_is_not_read_again(self): + storage = CountingStorage({'k.pdf': b'%PDF-1.4 test'}) + files = grade_check.Files(storage) + self.assertEqual(files.pdf_dpi({'object_key': 'k.pdf', 'size': 15, 'name': 'a.pdf', + 'pdf_checked': True, 'pdf_dpi': 150}), 150) + self.assertIsNone(files.pdf_dpi({'object_key': 'unreadable.pdf', 'size': 1, 'name': 'b.pdf', + 'pdf_checked': True, 'pdf_dpi': None})) + self.assertIsNone(files.pdf_dpi({'object_key': 'big.pdf', 'size': grade_check.PDF_MAX_BYTES + 1, + 'name': 'big.pdf'})) + self.assertEqual(storage.downloads, 0) + def test_resolution_boundaries_and_consent(self): width = lambda dpi: int(dpi * 57 / 2.54) + 1 files = FakeFiles({f'{dpi}.png': encoded('PNG', (width(dpi), 20)) From 55419d83642a95550f6c24c7e210e84611a5e4fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Wed, 11 Nov 2026 15:59:27 -0300 Subject: [PATCH 2/2] feat: each error in Sentry names the commit it came from The API image keeps the commit it was built from (RELEASE, from VCS_REF); the API, the worker and the browser report it as the Sentry release unless the stack sets IMAGE_TAG. Co-Authored-By: Claude Opus 5.5 (1M context) --- app/api/health.py | 4 ++-- app/api/users.py | 4 ++-- app/observability.py | 9 ++++++++- deploy/Dockerfile.api | 2 ++ 4 files changed, 14 insertions(+), 5 deletions(-) diff --git a/app/api/health.py b/app/api/health.py index 3ef97bc..6e505a2 100644 --- a/app/api/health.py +++ b/app/api/health.py @@ -6,7 +6,7 @@ import httpx from fastapi import APIRouter, HTTPException, Request, Response from ..core import db -from .. import catalog, grade_rules, mail +from .. import catalog, grade_rules, mail, observability from ..core.auth import client_ip, owner, new_session, rate_limit from ..core.limits import upload_limit_bytes from ..core.pricing import manual_extra_cents @@ -66,7 +66,7 @@ def session(request: Request, response: Response): # Public by design: the browser initialises Sentry with these; empty is off. 'sentry_dsn_web': os.environ.get('SENTRY_DSN_WEB', '').strip(), 'sentry_environment': os.environ.get('SENTRY_ENVIRONMENT') or ENVIRONMENT, - 'sentry_release': os.environ.get('IMAGE_TAG', ''), + 'sentry_release': observability.release() or '', # Public by design: Mercado Pago's card form needs it in the browser. 'payment_public_key': os.environ.get('MP_PUBLIC_KEY', '') if payment.name == 'mercadopago' else '', # The delivery options the cart quotes, or none: pickup only. diff --git a/app/api/users.py b/app/api/users.py index 8a52e42..1a9e41b 100644 --- a/app/api/users.py +++ b/app/api/users.py @@ -14,7 +14,7 @@ from uuid import UUID, uuid4 from fastapi import APIRouter, Depends, HTTPException, Request from pydantic import Field, field_validator -from .. import machines, mail +from .. import machines, mail, observability from ..core import db from ..core.auth import (CAPABILITIES, MACHINE_QUESTION, audit, can, may_move, may_reorder, password_hash, password_matches, signed_in) @@ -72,7 +72,7 @@ def me(request: Request): # Public by design: the Kanban browser initialises Sentry with these. 'sentry_dsn_web': os.environ.get('SENTRY_DSN_WEB', '').strip(), 'sentry_environment': os.environ.get('SENTRY_ENVIRONMENT') or ENVIRONMENT, - 'sentry_release': os.environ.get('IMAGE_TAG', ''), + 'sentry_release': observability.release() or '', # The machine this session is on, and whether to ask (item 12). 'machine': account['machine'], 'machine_question': MACHINE_QUESTION.get(role), 'machine_answered': account['machine_answered'], diff --git a/app/observability.py b/app/observability.py index bc16dd7..1eab87e 100644 --- a/app/observability.py +++ b/app/observability.py @@ -117,6 +117,13 @@ def _traces_rate(): return 0.0 +def release(): + """The deploy this process runs: IMAGE_TAG when the stack sets one, else the + commit the image was built from (RELEASE, from deploy/Dockerfile.api).""" + value = os.environ.get('IMAGE_TAG') or os.environ.get('RELEASE') or '' + return None if value in ('', 'unknown', 'latest') else value + + def init(component): """Start Sentry for this process; False (and no imports) without a DSN.""" dsn = os.environ.get('SENTRY_DSN_API', '').strip() @@ -130,7 +137,7 @@ def init(component): sentry_sdk.init( dsn=dsn, environment=environment, - release=os.environ.get('IMAGE_TAG') or None, + release=release(), send_default_pii=False, traces_sample_rate=_traces_rate(), before_send=scrub, diff --git a/deploy/Dockerfile.api b/deploy/Dockerfile.api index 591d62d..8b7bb66 100644 --- a/deploy/Dockerfile.api +++ b/deploy/Dockerfile.api @@ -6,6 +6,8 @@ ARG PYTHON_BASE_IMAGE=python:3.12-slim@sha256:2f17fc044b579bab302c2e8054d3a686e2 FROM ${PYTHON_BASE_IMAGE} ARG VCS_REF=unknown +# The commit this image was built from, as the Sentry release (app/observability.py). +ENV RELEASE=$VCS_REF LABEL org.opencontainers.image.title="DTF Portal/API" \ org.opencontainers.image.revision="$VCS_REF" \ org.opencontainers.image.source="DTF System repository"