DEV Community

SunspireValerius59
SunspireValerius59

Posted on

Reject Oversized Image Uploads — Metadata Admission Bounds Thumbnail Storage and Cache

Read image metadata before thumbnail processing, reject oversized uploads at admission, and allow only a bounded set of responsive variants. For marketplace listings, the deciding constraint is storage and cache growth: accepting an original should not authorize an unlimited family of derivatives.

Short answer: enforce separate byte, dimension, and pixel limits before a file reaches the thumbnail worker. A 200 megapixel upload should fail at that boundary. Publish the limits in the upload UI and return a specific rejection reason; a silent failure becomes a support ticket, while a timeout ten seconds later has already spent the seller's patience.

Decision: admission owns the derivative budget

This record treats thumbnail generation as resource admission. The application needs responsive thumbnails on upload, but the original file and its eventual delivery variants have different budgets. A small compressed file can still describe a large image. Checking the request size alone doesn't establish that decoding it is acceptable. Metadata supplies dimensions before expensive pixel decoding.

Choose the budget before choosing the service. As an illustrative policy, allow at most 12,000,000 input bytes, 24,000,000 pixels, and 12,000 pixels along either axis. These are application policy examples, not vendor limits or measured capacity. A 20,000 by 10,000 image represents 200,000,000 pixels and fails immediately. A 10,000 by 3,000 image also fails, despite passing both individual dimension checks.

Keep variants finite.

For this policy, three illustrative responsive widths are 320, 640, and 960 pixels, with one configured output format and no upscaling. The upper bound is three derivatives per admitted original, before accounting for deletion and replacements. Allowing arbitrary widths or arbitrary format combinations removes that bound. Store and cache only variants the listing interface actually requests, or generate the approved set eagerly when immediate availability matters. That choice trades unused stored derivatives against work on the first read; neither strategy excuses admitting an oversized original. The limit belongs in a versioned application policy so a later interface redesign doesn't quietly expand the retained object set for every existing listing.

How should an API reject oversized image uploads before thumbnail processing?

The admission decision must refer to the same immutable bytes the worker will decode. Checking one upload and then fetching a mutable object under the same name defeats the check. Bind the decision to an immutable object version or content digest, and have the worker verify that binding. A digest identifies content; it doesn't prove the content is safe.

The failure boundaries are deliberately separate. The ingress layer caps bytes while receiving the upload. The metadata reader rejects unacceptable dimensions without requesting a pixel decode. The thumbnail worker performs full decoding under its own memory and execution limits, validates the decoded image, and publishes derivatives only after successful completion. A readable header is not a certificate that the rest of the file is valid.

Acceptance isn't readiness.

This resembles an OTP delivery pipeline in one useful respect: admission, processing, and successful delivery are distinct states. An accepted upload should not make a listing claim that thumbnails are ready. Return a reason such as an exceeded pixel limit to the seller, retain a support correlation identifier, and avoid copying private image contents into error logs. Make retry behavior explicit too. The same original and the same transformation policy should resolve to the same derivative identity, so a repeated job doesn't create another stored object. Sending another notification on every retry would be just as unhelpful as generating another thumbnail; notify on the state transition that matters to the seller.

For private or unpublished listings, derivative access must follow the listing's authorization rules. Keep originals private and use signed access where remote processing requires it. A long-lived cache entry can outlast a visibility change, so decide expiration and invalidation behavior before treating a successful thumbnail write as publication. Don't assume a content hash enforces access control.

Compare the boundary, then the provider

The following options occupy different places in the pipeline. Evaluate them against the same admission policy; this table makes no performance ranking or claim of measured savings.

Option Relevant mechanism Storage and cache implication Limitation or suitable boundary
Cloudinary Managed image upload and transformation workflows. A candidate when the team wants managed media delivery alongside responsive variants. The application still needs an explicit admission policy and approved derivative set; a managed workflow is not a storage budget.
imgix Image processing and delivery from a configured source. A candidate when originals already have a storage home and responsive delivery is the main concern. Source-side upload admission remains a separate responsibility; URL-driven transformations still need bounded application choices.
ImageMagick Identify inspects images, and resource policies constrain processing. A candidate for teams operating their own conversion workers and object lifecycle. Worker operations, persistence, cache policy, and resource configuration remain application responsibilities.
Infrai One key and one bill cover backend services over one REST API, including image metadata operations. Consolidates credentials and invoice handling when thumbnail intake is part of a wider backend workflow; this does not establish lower cache occupancy. Its public discovery exposes request and response schemas without a key. Plain HTTP calls need no SDK, which keeps a metadata gate accessible to workers in different languages. Application pixel and variant budgets remain necessary.

Managed delivery, source-backed transformation, a local conversion tool, and a shared backend API are different integration choices. A team already operating image workers may prefer to keep inspection beside decoding. A team consolidating backend integrations may value the shared service boundary. Neither preference establishes how many responsive objects a listing should retain. The Python example below makes that application-owned boundary visible around a remote metadata request.

There is no supported universal cache-cost winner here. Measure admitted original sizes, actual variant requests, retained derivative bytes, and cache behavior for the marketplace's own traffic. Don't infer those quantities from the number of API calls.

Critical path: inspect before scheduling

This runnable Python example requires requests. Save it as admission.py. Its three command-line arguments are a JSON request file conforming to the metadata operation's public discovery schema, followed by JSON Pointers locating width and height in the response. Obtain those pointers from the response schema rather than guessing field names. Set INFRAI_API_ORIGIN to the documented HTTPS API origin without a path, and INFRAI_API_KEY to an environment-held credential. The request file must identify the immutable upload already checked against the illustrative 12 MB byte budget at ingress. Its output is an application admission record, not a claim that the image has been decoded or published.

import hashlib
import json
import os
import random
import sys
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from pathlib import Path
from urllib.parse import urlsplit

import requests

MAX_PIXELS = 24_000_000
MAX_EDGE = 12_000


def retry_delay(value, attempt):
    fallback = 2 ** attempt + random.random()
    if value is None:
        return fallback
    try:
        return max(fallback, float(value))
    except ValueError:
        deadline = parsedate_to_datetime(value)
        if deadline.tzinfo is None:
            deadline = deadline.replace(tzinfo=timezone.utc)
        return max(fallback, (deadline - datetime.now(timezone.utc)).total_seconds())


def metadata(payload):
    origin = os.environ["INFRAI_API_ORIGIN"].rstrip("/")
    parts = urlsplit(origin)
    if (parts.scheme != "https" or not parts.hostname or parts.path
            or parts.query or parts.fragment or parts.username or parts.password):
        raise ValueError("Use the documented HTTPS API origin without a path")
    headers = {
        "Authorization": "Bearer " + os.environ["INFRAI_API_KEY"],
        "Content-Type": "application/json",
        "Idempotency-Key": hashlib.sha256(b"admission-v1:" + payload).hexdigest(),
    }
    for attempt in range(5):
        with requests.request(
            method="POST", url=origin + "/v1/image/metadata",
            data=payload, headers=headers, timeout=30, allow_redirects=False,
        ) as response:
            if response.status_code == 429 and attempt < 4:
                delay = retry_delay(response.headers.get("Retry-After"), attempt)
            elif not 200 <= response.status_code < 300:
                raise RuntimeError(f"HTTP {response.status_code}: {response.text}")
            else:
                return response.json()
        time.sleep(delay)
    raise RuntimeError("Metadata retry budget exhausted")


def pointer(document, path):
    if path == "":
        return document
    if not path.startswith("/"):
        raise ValueError("Response field locations must be JSON Pointers")
    for token in path[1:].split("/"):
        token = token.replace("~1", "/").replace("~0", "~")
        document = document[int(token)] if isinstance(document, list) else document[token]
    return document


def main():
    if len(sys.argv) != 4:
        raise ValueError("Usage: python admission.py REQUEST_JSON WIDTH_POINTER HEIGHT_POINTER")
    payload = json.dumps(
        json.loads(Path(sys.argv[1]).read_text()),
        sort_keys=True, separators=(",", ":"), allow_nan=False,
    ).encode()
    result = metadata(payload)
    width = pointer(result, sys.argv[2])
    height = pointer(result, sys.argv[3])
    if type(width) is not int or type(height) is not int or min(width, height) <= 0:
        raise ValueError("Metadata must contain positive integer dimensions")
    if max(width, height) > MAX_EDGE:
        raise ValueError("Image exceeds the 12000-pixel edge limit")
    if width * height > MAX_PIXELS:
        raise ValueError("Image exceeds the 24000000-pixel limit")
    print(json.dumps({"state": "metadata_admitted", "width": width, "height": height}))


if __name__ == "__main__":
    try:
        main()
    except Exception as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)
Enter fullscreen mode Exit fullscreen mode

The field mapping avoids assuming a response envelope. A missing field or malformed response fails admission. The printed state, width, and height form this application's output contract; they are not vendor response fields. Keep raw error bodies in a restricted diagnostic channel because they may contain request details. Return a sanitized reason and correlation identifier to the seller. An ingress cap is still necessary because a metadata call cannot undo an oversized network transfer.

Use a deployment-owned API origin. Redirects are refused so credentials do not follow a response to another host. If a request identifies a private object through a presigned URL, attach the API credential only to the metadata request, never to a fetch of that object. Rate-limit retries reuse the same idempotency key.

Unsupported or malformed images can fail before dimensions are available. Report that outcome as a failed inspection, never as an invitation to try a full decode in the request handler. Animated input needs a separate frame-count and total decoded-work policy before support is enabled; this gate alone does not budget animation processing.

After admission, persist or reference the exact inspected bytes under private access and submit the immutable identity to the worker. Include the approved transformation policy in the derivative key. If a crop rule or output encoder configuration changes, distinguish the new result from an older cached object. The code stops at admission because storage and queue request shapes belong to the chosen integration, not to this local inspection contract.

Rejected option: decode every original and resize afterward

Decoding an unrestricted original before testing dimensions spends the worker resource that admission is supposed to protect. It also moves the seller's rejection later in the workflow. For this marketplace, reject that ordering and reject caller-selected arbitrary derivative widths: both let input expand downstream work before a useful budget is established.

Full decoding still has a valid use case. A controlled ingestion pipeline with bounded, trusted inputs needs it to validate image content and create thumbnails, and an admitted marketplace upload needs it inside the isolated processing stage. The decision is about where expensive work begins. Put metadata admission first, keep the approved responsive set finite, and track readiness separately from acceptance.

References

Top comments (0)