AI image API SSRF protection: Safe Python Downloads
Your image-generation worker receives a completed result URL and downloads it into storage. If that URL points to an internal service instead of an image, the worker becomes a network client for an attacker. AI image API SSRF protection starts by treating every result URL as untrusted input, even when it arrives inside an otherwise legitimate job response.
Server-side request forgery (SSRF) is an attack that causes a server to make unintended network requests using its own connectivity and privileges. This API tutorial builds an application-owned download boundary after generation. The GenRelay image API is the generation integration; the Python functions below belong to your application, not to an asserted provider security feature.
What should an image-download security boundary enforce?
Require an exact approved HTTPS hostname, refuse redirects, cap downloaded bytes, and enforce connection, read, and worker-runtime limits behind a restrictive network policy.
HTTPS is HTTP protected by Transport Layer Security (TLS), which authenticates the server certificate and encrypts the connection. It does not prove that a URL is appropriate for your worker to fetch. An attacker-controlled HTTPS service can still return malicious content or direct traffic toward another destination.
Implement the ingestion sequence in this order:
- Associate the completed generation result with an authenticated tenant and saved job.
- Validate the returned URL against a server-managed destination policy.
- Download through restricted outbound networking without generation credentials.
- Validate the image structure and decoded dimensions.
- Store accepted bytes under an application-owned asset identifier.
An allowlist is a configured set of explicitly permitted values. Populate it from documented result-storage destinations and operational review, not from the URL being evaluated. Neither example discovers allowed hosts automatically. The reserved hostname images.example.com is a configuration placeholder, not a GenRelay endpoint.
Reject wildcard and suffix policies such as accepting anything that contains an approved domain. images.example.com.attacker.test must not match images.example.com. Avoid accepting arbitrary customer URLs in the same worker that handles trusted result ingestion.
How do I implement a bounded Python image downloader?
Use a strict URL validator and a streamed HTTP client with explicit limits; the following module implements both without sending API authorization headers.
Install requests in your application environment and save this example as safe_download.py. It uses Python 3.10 or later. Configure the approved hostname before a real download. Calling download_bytes(result_url) returns a bounded byte string for subsequent image validation; it does not submit a generation request.
import time
from urllib.parse import urlsplit
import requests
ALLOWED_HOSTS = frozenset({"images.example.com"})
MAX_BYTES = 12 * 1024 * 1024
BUDGET_SECONDS = 20
CHUNK_BYTES = 64 * 1024
def validate_url(url):
if not isinstance(url, str) or not 1 <= len(url) <= 8192:
raise ValueError("invalid URL length")
if not url.isascii() or any(ord(c) <= 32 or ord(c) == 127 for c in url):
raise ValueError("invalid URL characters")
if "\\" in url or "#" in url:
raise ValueError("unsupported URL syntax")
parts = urlsplit(url)
if parts.scheme != "https":
raise ValueError("HTTPS required")
if parts.username is not None or parts.password is not None:
raise ValueError("userinfo forbidden")
if parts.hostname not in ALLOWED_HOSTS:
raise ValueError("host not approved")
# Exact authority also rejects encoded hosts, trailing dots,
# empty ports, and unexpected port spellings.
allowed_authorities = {parts.hostname, parts.hostname + ":443"}
if parts.netloc.lower() not in allowed_authorities:
raise ValueError("authority not approved")
return url
def stream_to(url, sink):
validate_url(url)
started = time.monotonic()
total = 0
with requests.Session() as session:
# Do not inherit environment proxies or .netrc credentials.
session.trust_env = False
with session.get(
url, stream=True, allow_redirects=False,
timeout=(3, 4),
headers={"Accept-Encoding": "identity"},
) as response:
if response.status_code != 200:
raise ValueError("expected HTTP 200")
if response.headers.get("Content-Encoding", "identity").lower() != "identity":
raise ValueError("encoded response rejected")
length = response.headers.get("Content-Length")
if length is not None:
if not length.isascii() or not length.isdecimal():
raise ValueError("invalid content length")
if int(length) > MAX_BYTES:
raise ValueError("declared size exceeds limit")
for chunk in response.iter_content(chunk_size=CHUNK_BYTES):
if time.monotonic() - started > BUDGET_SECONDS:
raise TimeoutError("download budget exceeded")
if not chunk:
continue
total += len(chunk)
if total > MAX_BYTES:
raise ValueError("stream exceeds limit")
sink.write(chunk)
if time.monotonic() - started > BUDGET_SECONDS:
raise TimeoutError("download budget exceeded")
if total == 0:
raise ValueError("empty response")
if length is not None and total != int(length):
raise ValueError("content length mismatch")
return total
def download_bytes(url):
from io import BytesIO
sink = BytesIO()
stream_to(url, sink)
return sink.getvalue()
The (3, 4) timeout tuple sets connection and read-inactivity timeouts in seconds. It is not a total transaction deadline. The monotonic clock measures elapsed time without being affected by wall-clock adjustments, but its checks run between library operations. DNS resolution, a blocked system call, or a slow peer can exceed that cooperative budget. Enforce a hard runtime limit by terminating an isolated worker process or using your job platform's execution deadline.
The streaming counter remains authoritative when Content-Length is missing or dishonest. Rejecting content encoding avoids accepting a small compressed transfer that expands unexpectedly inside the HTTP client. This does not limit the decoded image's pixel memory; image validation needs its own resource budget.
The module disables inherited proxies deliberately. If your deployment requires an approved egress proxy, configure that proxy explicitly and prevent direct connections at the network layer. An egress proxy is a controlled intermediary for outbound requests, not a reason to inherit arbitrary process-environment settings.
How can I download into quarantine without exposing partial files?
Stream into a private temporary file and return its path after transfer checks, deleting the file whenever an exception occurs.
Quarantine is storage that downstream serving and processing systems cannot treat as an accepted asset. This second runnable example reuses safe_download.py, so the same exact-host HTTPS policy, redirect refusal, timeouts, and byte limits apply. Save it as quarantine_download.py. Call download_to_quarantine(result_url, private_directory) from your ingestion job; choose the directory in server configuration, never from a request parameter.
import os
import tempfile
from pathlib import Path
from safe_download import stream_to
def download_to_quarantine(url, directory):
directory = Path(directory)
if not directory.is_dir():
raise ValueError("quarantine directory must exist")
fd, filename = tempfile.mkstemp(
prefix="image-", suffix=".pending", dir=directory
)
path = Path(filename)
try:
# mkstemp creates the file with restrictive permissions.
with os.fdopen(fd, "wb") as sink:
stream_to(url, sink)
sink.flush()
os.fsync(sink.fileno())
return path
except BaseException:
path.unlink(missing_ok=True)
raise
Keep the directory private and outside the web root. A successful return means the transport policy accepted the transfer, not that the bytes are an image. Apply the image output validation checklist, including a supported-format decoder, maximum dimensions, and decoded-memory limits, before promoting the file into serving storage.
A hard process termination cannot execute Python cleanup. Run a scheduled application cleanup process for abandoned .pending files, using age and job-state checks. Apply filesystem quotas and worker-concurrency limits as well: twelve megabytes per transfer still accumulates across many simultaneous jobs.
Do not derive filenames from response headers or URL paths. Do not log full result URLs, because query strings can contain access credentials. Store a job identifier, approved hostname, byte count, and a categorized failure instead.
Why do hostname checks not solve DNS rebinding?
Hostname checks cannot control which IP address the HTTP connection ultimately reaches, so production SSRF defenses also require enforced network egress restrictions.
The Domain Name System (DNS) maps names to IP addresses. DNS rebinding changes those answers over time, potentially making an approved hostname resolve to an internal address during a later lookup. A separate preflight lookup creates a time-of-check/time-of-use gap: the application checks one answer, while the HTTP library connects using another.
The examples intentionally do not present a preflight lookup as complete protection. TLS certificate verification stays enabled, but it is not a substitute for destination authorization. A compromised approved service, DNS change, or internal service configuration can invalidate assumptions about where requests land.
Deploy the downloader in an isolated network segment and enforce these controls:
- Deny access to internal networks, loopback, link-local destinations, cloud metadata services, and other non-public address ranges across IPv4 and IPv6.
- Use an approved egress proxy or firewall that validates actual connection destinations and handles DNS resolution consistently with its policy.
- Prevent direct outbound connections that would evade that controlled path.
- Keep the destination hostname policy narrow, require port 443, and preserve certificate and hostname verification.
- Remove cloud credentials and unrelated service secrets from download workers.
A firewall is a network traffic enforcement mechanism; a hostname string comparison is application validation. They address different parts of the threat. Test both with deployment-level denied-destination checks, not just mocked HTTP tests.
How should download failures affect generation costs?
Retry an eligible download against the saved generation result rather than automatically purchasing another generation.
For budgeting with the supplied GenRelay rates, Nano Banana Pro costs $0.030 per image at 1K or 2K and $0.042 at 4K. Nano Banana 2 costs $0.020 at 1K and $0.036 at 4K. GPT-image-2 costs $0.014 per image. These are generation prices, not claims about storage, delivery, or security services.
For example, 1,000 Nano Banana Pro 1K generations total $30 before separate infrastructure costs. A blocked download does not establish that generation failed or that its charge disappeared. Track generation status and ingestion status separately, cap retries, and investigate policy failures rather than widening the allowlist automatically.
Does a signed result URL make an image download safe?
No. A signed URL grants time-limited access under its issuer's policy; it does not authorize your server to contact every destination named in a URL.
Apply identical destination checks to signed and unsigned links. Preserve the query string without logging it. The signed image URL guide explains application delivery access separately from outbound network safety.
Should the downloader follow a redirect to another approved host?
No, not in these examples: every non-200 response is rejected, including redirects to an approved host.
If storage routing changes, review and update the configured integration instead of silently following locations. Request a fresh documented result URL when appropriate.
Is checking Content-Type enough to trust a downloaded image?
No. Content-Type is response metadata and cannot prove that a file decodes safely or meets your image policy.
Validate the bytes with a maintained decoder in a resource-limited process. Reject unexpected formats, oversized dimensions, and malformed or truncated image data before publication.
Which tests should run before enabling production ingestion?
Test rejected URLs, redirect refusal, oversize streams, missing size headers, timeout failures, and partial-file cleanup before enabling ingestion.
Mock HTTP responses for deterministic application tests without paid generation calls. Separately verify IPv4 and IPv6 egress restrictions, cloud metadata denial, and enforced worker termination in your deployment. Passing unit tests validates the downloader's logic, not the surrounding network boundary.