Files
dtf-system/app/scanning.py
Cauê Faleiros b329f76378
All checks were successful
Build and deploy / Validate source (push) Successful in 7s
Build and deploy / Integration suite on a real stack (push) Successful in 1m25s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images and notify Portainer (push) Successful in 1m31s
refactor: lay the repository out by role
local/ held six unrelated things under a name that stopped being true once it
became the production runtime: the service, the frontend, the tests, the ops
commands, the container definitions and the dependency lock, 65 files with
nothing to tell them apart.

  app/      the service: api/ routers, core/ for identity, database, models,
            prices and secret loading, and the worker, bootstrap and schema
  tests/    the twelve suites, no longer inside the shipped package
  ops/      backup, readiness, dependency audit, security summary
  infra/    Dockerfiles, gateway templates, ClamAV and storage configuration,
            the requirements and their hash lock
  web/      the Site, Kanban and portal pages with their scripts

deploy/Dockerfile.api now copies app/ alone, so the tests stop shipping to
production; the local image still carries them, because the suites run inside
the stack's network.

Five kinds of reference had to follow, and each was found by something different
rather than by reading. Imports of the form "from . import db" survived a rewrite
that only matched "from .db import". Tests kept relative imports of modules that
had left the package. A mock.patch target names its module in a string, where no
import rewriting can see it. The browser test resolves a fixture by path. And the
release gate's markers pointed at local/runtime.py and local/worker.py, which is
the decay its new marker test exists to catch — it caught it.

Verified from docker compose down -v: the stack starts, all six integration
suites, both browser suites and the twenty-nine unit tests pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 17:40:57 -03:00

82 lines
3.4 KiB
Python

"""Local ClamAV boundary. Unknown/error/over-limit results NEVER release artwork."""
import os
import socket
import struct
import time
from fastapi import HTTPException
from .core.auth import audit
from .core.db import connect
def require_clean(row):
if not row['complete'] or row['scan_state'] != 'clean':
raise HTTPException(409, 'Artwork is quarantined until the malware scan succeeds')
class ClamAV:
def command(self, command, timeout=2):
with socket.create_connection(('scanner',3310),timeout=timeout) as sock:
sock.settimeout(timeout)
sock.sendall(b'z'+command+b'\0')
reply=b''
while b'\0' not in reply and len(reply)<4096:
block=sock.recv(4096)
if not block:break
reply+=block
return reply.rstrip(b'\0\n')
def ping(self):
return self.command(b'PING') == b'PONG'
def version(self):
return self.command(b'VERSION').decode('utf-8','replace')
def scan(self, stream, size):
if size > min(134217728, int(os.environ.get('SCAN_MAX_BYTES','134217728'))):
return 'rejected', 'File exceeds the malware scan limit'
with socket.create_connection(('scanner',3310),timeout=10) as sock:
sock.settimeout(150)
sock.sendall(b'zINSTREAM\0')
sent=0
for chunk in stream.iter_chunks(chunk_size=65536):
sent+=len(chunk)
if sent>size: return 'rejected','Stored file size changed'
sock.sendall(struct.pack('!I',len(chunk))+chunk)
if sent!=size:return 'rejected','Stored file size changed'
sock.sendall(b'\0\0\0\0')
reply=b''
while b'\0' not in reply and len(reply)<4096:
block=sock.recv(4096)
if not block:break
reply+=block
result=reply.rstrip(b'\0\n')
if result==b'stream: OK':return 'clean',None
if result.endswith(b' FOUND'):return 'rejected','Malware or unsafe scan condition detected'
return 'error','Scanner could not verify this file'
def scan_one(storage, scanner=None):
scanner=scanner or ClamAV()
with connect() as c:
row=c.execute('''SELECT * FROM dtf_local.uploads WHERE complete AND purged_at IS NULL
AND expires_at>now() AND scan_state IN ('pending','error') AND scan_after<=now()
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 1''').fetchone()
if not row:return False
try:
stream=storage.client.get_object(Bucket=storage.bucket,Key=row['object_key'])['Body']
try:state,reason=scanner.scan(stream,row['size'])
finally:stream.close()
except Exception:
state,reason='error','Malware scanner unavailable; file remains blocked'
c.execute("""UPDATE dtf_local.uploads SET scan_state=%s,scan_reason=%s,scanned_at=now(),
scan_after=now()+interval '1 minute',
expires_at=CASE WHEN %s IN ('rejected','error') THEN LEAST(expires_at,now()+interval '3 days') ELSE expires_at END
WHERE id=%s""",(state,reason,state,row['id']))
audit('artwork_scan', upload=str(row['id']), result=state)
return True
def scan_loop(storage):
while True:
try:
if scan_one(storage):continue
except Exception:
audit('scanner_worker_error')
time.sleep(1)