ЛР 7: Безопасность, mTLS и OpenBao
Skeleton contracts / contracts (pull_request) Blocked by required conditions

This commit is contained in:
2026-12-05 18:23:13 +03:00
parent 20afc2c790
commit e7d7bbbe77
66 changed files with 4865 additions and 81 deletions
+466
View File
@@ -0,0 +1,466 @@
#!/usr/bin/env python3
"""Durable RabbitMQ consumer for image attachment processing."""
import hashlib
import io
import json
import logging
import os
import re
import signal
import threading
import time
import warnings
import uuid
from datetime import datetime
from opentelemetry import trace
from opentelemetry.propagate import extract
import observability as telemetry
from service_secrets import load_service_secrets
import pika
from PIL import Image, ImageOps, UnidentifiedImageError
from psycopg.rows import dict_row
from psycopg.types.json import Jsonb
import psycopg
from psycopg_pool import ConnectionPool, PoolTimeout
from botocore.exceptions import BotoCoreError, ClientError
from app import (
MAX_IMAGE_PIXELS,
MAX_UPLOAD_BYTES,
create_s3_client,
database_conninfo,
)
from queueing import (
JOB_QUEUE,
BrokerUnavailable,
connection_parameters,
declare_topology,
publish_pending_job,
)
LOG = logging.getLogger("attachment-worker")
STOP_REQUESTED = threading.Event()
POOL = None
S3_CLIENT = None
S3_BUCKET = None
class InvalidImage(Exception):
pass
def parse_event(raw):
try:
event = json.loads(raw.decode("utf-8"))
except (UnicodeError, ValueError):
raise ValueError("invalid job JSON") from None
required = {
"schema_version",
"job_id",
"type",
"attachment_id",
"pipeline_version",
"attempt",
"created_at",
}
optional = {"traceparent", "tracestate"}
if not isinstance(event, dict) or not required.issubset(event) or set(event) - required - optional:
raise ValueError("invalid job fields")
if (not isinstance(event["schema_version"], int)
or isinstance(event["schema_version"], bool)
or event["schema_version"] != 1
or event["type"] != "attachment.process.v1"
or not isinstance(event["pipeline_version"], int)
or isinstance(event["pipeline_version"], bool)
or event["pipeline_version"] != 1
or not isinstance(event["attempt"], int)
or isinstance(event["attempt"], bool)
or event["attempt"] < 1
or not isinstance(event["created_at"], str)):
raise ValueError("invalid job metadata")
try:
created_at = datetime.fromisoformat(event["created_at"].replace("Z", "+00:00"))
if created_at.tzinfo is None:
raise ValueError("created_at must include a timezone")
except ValueError:
raise ValueError("invalid job timestamp") from None
if "traceparent" in event and (
not isinstance(event["traceparent"], str)
or not re.fullmatch(
r"00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}",
event["traceparent"],
)
):
raise ValueError("invalid traceparent")
if "tracestate" in event and (
not isinstance(event["tracestate"], str) or len(event["tracestate"]) > 512
):
raise ValueError("invalid tracestate")
try:
event["job_id"] = uuid.UUID(event["job_id"])
event["attachment_id"] = uuid.UUID(event["attachment_id"])
except (ValueError, TypeError, AttributeError):
raise ValueError("invalid job identifier") from None
return event
def thumbnail_jpeg(data, content_type):
expected_format = {"image/png": "PNG", "image/jpeg": "JPEG"}.get(content_type)
if expected_format is None:
raise InvalidImage("unsupported source type")
try:
with warnings.catch_warnings():
warnings.simplefilter("error", Image.DecompressionBombWarning)
with Image.open(io.BytesIO(data)) as source:
if source.format != expected_format:
raise InvalidImage("source format mismatch")
if source.width * source.height > MAX_IMAGE_PIXELS:
raise InvalidImage("source image exceeds pixel limit")
source.load()
image = ImageOps.exif_transpose(source)
width, height = image.size
scale = min(256 / width, 256 / height, 1.0)
target_size = (max(1, int(width * scale)), max(1, int(height * scale)))
if image.mode in ("RGBA", "LA") or "transparency" in image.info:
rgba = image.convert("RGBA")
rgb = Image.new("RGB", rgba.size, "white")
rgb.paste(rgba, mask=rgba.getchannel("A"))
else:
rgb = image.convert("RGB")
if target_size != rgb.size:
rgb = rgb.resize(target_size, Image.Resampling.LANCZOS)
output = io.BytesIO()
rgb.save(output, format="JPEG", quality=85, optimize=True)
return output.getvalue(), target_size[0], target_size[1]
except InvalidImage:
raise
except (Image.DecompressionBombError, Image.DecompressionBombWarning,
OSError, SyntaxError, UnidentifiedImageError, ValueError):
raise InvalidImage("image decoding failed") from None
def fail_job(conn, job_id, attachment_id, error_code):
conn.execute(
"""UPDATE image_jobs
SET status = 'failed', last_error_code = %s, updated_at = now()
WHERE id = %s""",
(error_code, job_id),
)
conn.execute(
"""UPDATE attachments
SET status = 'failed', error_code = %s, updated_at = now()
WHERE id = %s""",
(error_code, attachment_id),
)
conn.commit()
def process_locked_job(conn, event):
job = conn.execute(
"""SELECT j.id, j.attachment_id, j.pipeline_version, j.attempt,
j.max_attempts, j.status AS job_status, j.created_at,
a.content_type, a.size_bytes, a.sha256, a.object_key, a.staging_key
FROM image_jobs j
JOIN attachments a ON a.id = j.attachment_id
WHERE j.id = %s AND j.attachment_id = %s""",
(event["job_id"], event["attachment_id"]),
).fetchone()
if job is None or job["job_status"] in ("ready", "failed"):
conn.commit()
return "ack"
if event["attempt"] < job["attempt"]:
conn.commit()
publish_pending_job(POOL, job["id"])
return "ack"
if event["attempt"] != job["attempt"]:
LOG.warning("job attempt mismatch job_id=%s", job["id"])
conn.commit()
return "ack"
conn.execute(
"""UPDATE image_jobs SET status = 'processing', updated_at = now()
WHERE id = %s""",
(job["id"],),
)
conn.execute(
"""UPDATE attachments
SET status = 'processing', error_code = NULL, updated_at = now()
WHERE id = %s""",
(job["attachment_id"],),
)
conn.commit()
if not job["staging_key"]:
raise InvalidImage("staging object missing")
response = S3_CLIENT.get_object(Bucket=S3_BUCKET, Key=job["staging_key"])
with response["Body"] as body:
original = body.read(MAX_UPLOAD_BYTES + 1)
if (len(original) != job["size_bytes"] or len(original) > MAX_UPLOAD_BYTES
or hashlib.sha256(original).hexdigest() != job["sha256"]):
raise InvalidImage("staging integrity check failed")
thumbnail, width, height = thumbnail_jpeg(original, job["content_type"])
thumbnail_sha256 = hashlib.sha256(thumbnail).hexdigest()
thumbnail_key = (
"attachments/" + str(job["attachment_id"]) + "/variants/thumbnail.jpg"
)
S3_CLIENT.put_object(
Bucket=S3_BUCKET,
Key=job["object_key"],
Body=original,
ContentType=job["content_type"],
Metadata={"sha256": job["sha256"]},
)
S3_CLIENT.put_object(
Bucket=S3_BUCKET,
Key=thumbnail_key,
Body=thumbnail,
ContentType="image/jpeg",
Metadata={"sha256": thumbnail_sha256},
)
variants = [{
"name": "thumbnail",
"content_type": "image/jpeg",
"size_bytes": len(thumbnail),
"width": width,
"height": height,
"sha256": thumbnail_sha256,
}]
conn.execute(
"""UPDATE attachments
SET status = 'ready', variants = %s, error_code = NULL, updated_at = now()
WHERE id = %s""",
(Jsonb(variants), job["attachment_id"]),
)
conn.execute(
"""UPDATE image_jobs SET status = 'ready', last_error_code = NULL, updated_at = now()
WHERE id = %s""",
(job["id"],),
)
conn.commit()
try:
S3_CLIENT.delete_object(Bucket=S3_BUCKET, Key=job["staging_key"])
except (BotoCoreError, ClientError) as error:
LOG.warning(
"staging cleanup deferred attachment_id=%s error_type=%s",
job["attachment_id"],
type(error).__name__,
)
return "ack"
def process_job(event):
with POOL.connection() as conn:
lock_key = str(event["job_id"])
conn.execute(
"SELECT pg_advisory_lock(hashtextextended(%s, 0))",
(lock_key,),
)
conn.commit()
try:
try:
return process_locked_job(conn, event)
except BrokerUnavailable:
conn.rollback()
raise
except InvalidImage:
conn.rollback()
row = conn.execute(
"""SELECT attachment_id FROM image_jobs WHERE id = %s""",
(event["job_id"],),
).fetchone()
if row is not None:
fail_job(conn, event["job_id"], row["attachment_id"], "invalid_image")
else:
conn.commit()
return "ack"
except Exception as error:
conn.rollback()
LOG.warning(
"job processing failed job_id=%s error_type=%s",
event["job_id"],
type(error).__name__,
)
row = conn.execute(
"""SELECT j.attachment_id, j.attempt, j.max_attempts, j.status
FROM image_jobs j WHERE j.id = %s""",
(event["job_id"],),
).fetchone()
if row is None or row["status"] in ("ready", "failed"):
conn.commit()
return "ack"
if event["attempt"] < row["attempt"]:
conn.commit()
publish_pending_job(POOL, event["job_id"])
return "ack"
if row["attempt"] >= row["max_attempts"]:
fail_job(
conn,
event["job_id"],
row["attachment_id"],
"retry_exhausted",
)
return "ack"
next_attempt = row["attempt"] + 1
conn.execute(
"""UPDATE image_jobs
SET status = 'queued', attempt = %s,
last_error_code = 'processing_failed', updated_at = now()
WHERE id = %s""",
(next_attempt, event["job_id"]),
)
conn.execute(
"""UPDATE attachments
SET status = 'queued', error_code = NULL, updated_at = now()
WHERE id = %s""",
(row["attachment_id"],),
)
conn.commit()
publish_pending_job(POOL, event["job_id"])
return "ack"
finally:
conn.rollback()
try:
conn.execute(
"SELECT pg_advisory_unlock(hashtextextended(%s, 0))",
(lock_key,),
)
conn.commit()
except psycopg.Error:
LOG.warning("failed to release job lock job_id=%s", event["job_id"])
def on_message(channel, method, _properties, body):
try:
event = parse_event(body)
except ValueError as error:
LOG.warning("invalid broker message error=%s", str(error))
channel.basic_nack(delivery_tag=method.delivery_tag, requeue=False)
return
carrier = {}
if "traceparent" in event:
carrier["traceparent"] = event["traceparent"]
if "tracestate" in event:
carrier["tracestate"] = event["tracestate"]
context = extract(carrier)
started = time.monotonic()
outcome = "success"
if telemetry.TRACER is not None:
with telemetry.TRACER.start_as_current_span(
"process attachment",
context=context,
kind=trace.SpanKind.CONSUMER,
attributes={
"messaging.system": "rabbitmq",
"messaging.destination.name": JOB_QUEUE,
"messaging.operation.name": "process",
"attachment.job_id": str(event["job_id"]),
"attachment.pipeline_version": event["pipeline_version"],
},
) as span:
try:
process_job(event)
except (BrokerUnavailable, psycopg.Error, PoolTimeout,
BotoCoreError, ClientError, OSError) as error:
outcome = "deferred"
span.set_status(trace.Status(trace.StatusCode.ERROR))
LOG.warning(
"job deferred job_id=%s error_type=%s",
event["job_id"],
type(error).__name__,
)
channel.basic_nack(delivery_tag=method.delivery_tag, requeue=True)
else:
span.set_status(trace.Status(trace.StatusCode.OK))
channel.basic_ack(delivery_tag=method.delivery_tag)
else:
try:
process_job(event)
except (BrokerUnavailable, psycopg.Error, PoolTimeout,
BotoCoreError, ClientError, OSError):
outcome = "deferred"
channel.basic_nack(delivery_tag=method.delivery_tag, requeue=True)
else:
channel.basic_ack(delivery_tag=method.delivery_tag)
duration = time.monotonic() - started
if telemetry.JOBS_PROCESSED is not None:
telemetry.JOBS_PROCESSED.add(
1,
{"job_type": "attachment.process.v1", "outcome": outcome},
)
if telemetry.JOB_DURATION is not None:
telemetry.JOB_DURATION.record(
duration,
{"job_type": "attachment.process.v1", "outcome": outcome},
)
def run_worker():
global POOL, S3_CLIENT, S3_BUCKET
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
try:
load_service_secrets("worker")
except Exception as error:
raise SystemExit("OpenBao service authentication failed") from error
telemetry.setup_observability(
os.environ.get("OTEL_SERVICE_NAME", "messenger-worker")
)
if not 1 <= int(os.environ.get("WORKER_PREFETCH", "1")) <= 8:
raise SystemExit("WORKER_PREFETCH must be between 1 and 8")
max_connections = int(os.environ.get("DB_POOL_MAX_SIZE", "5"))
if not 2 <= max_connections <= 100:
raise SystemExit("DB_POOL_MAX_SIZE must be between 2 and 100 for the worker")
S3_CLIENT, S3_BUCKET = create_s3_client()
POOL = ConnectionPool(
conninfo=database_conninfo(),
min_size=1,
max_size=max_connections,
timeout=5,
kwargs={"row_factory": dict_row},
open=False,
)
POOL.open(wait=True, timeout=15)
with POOL.connection() as conn:
conn.execute("SELECT 1")
def request_shutdown(_signum, _frame):
STOP_REQUESTED.set()
signal.signal(signal.SIGTERM, request_shutdown)
signal.signal(signal.SIGINT, request_shutdown)
try:
while not STOP_REQUESTED.is_set():
connection = None
try:
connection = pika.BlockingConnection(connection_parameters())
channel = connection.channel()
declare_topology(channel)
channel.basic_qos(
prefetch_count=int(os.environ.get("WORKER_PREFETCH", "1"))
)
channel.basic_consume(
queue=JOB_QUEUE,
on_message_callback=on_message,
auto_ack=False,
)
LOG.info("worker consuming durable attachment queue")
while connection.is_open and not STOP_REQUESTED.is_set():
connection.process_data_events(time_limit=1)
except (pika.exceptions.AMQPError, OSError, TimeoutError) as error:
LOG.warning("broker connection interrupted error_type=%s", type(error).__name__)
finally:
if connection is not None and connection.is_open:
connection.close()
if not STOP_REQUESTED.is_set():
STOP_REQUESTED.wait(2)
finally:
POOL.close()
LOG.info("worker stopped")
if __name__ == "__main__":
run_worker()