Sub topic 15
Serving user content safely: headers, domains, and download behavior
This chapter covers what happens after a file is stored and a viewer requests it. A file that passed validation can still harm your users if you serve it carelessly. It assumes you know HTTP headers, the browser same-origin policy, and the upload flow from earlier chapters (presigned uploads, validation, scanning).
Why serving is a separate security problem
Validation decides whether to store a file. Serving decides how a browser will interpret it. Browsers act on the response headers and, in some cases, on the bytes themselves. A file you accepted as "an image" can be served in a way that makes the browser run it as a web page.
The main risk is stored cross-site scripting (XSS). Suppose a user uploads profile.html or an SVG containing <script>. If your site serves it from https://app.example.com/files/... and the browser renders it, the script runs with the origin app.example.com. It can read cookies that are not HttpOnly, call your API with the visitor's session, and read local storage. The attacker only needs the victim to open a link.
Three controls address this, and they work best together:
- Serve with correct, fixed headers so the browser does not guess.
- Serve user content from a different origin than your application.
- Control whether the browser displays or downloads the file.
Set the content type yourself
The Content-Type header tells the browser how to treat the bytes. Never copy a value that the uploader chose without checking it. Store the type you determined during validation (from the content signature, not the filename) and serve exactly that.
Browsers also practice MIME sniffing: when the declared type looks wrong, they inspect the bytes and may pick another type. A file labeled text/plain that contains HTML could be rendered as HTML in older or lenient clients. Turn this off with:
X-Content-Type-Options: nosniffWith nosniff, the browser trusts the declared Content-Type. It also refuses to run a script or stylesheet whose type is not a script or stylesheet type. Send this header on every response for user content.
Choose which types may display inline
Keep a small allowlist of types that are safe to show inside a page, and download everything else.
| Type | Inline display | Reason |
|---|---|---|
| `image/jpeg`, `image/png`, `image/webp`, `image/gif` | Yes | Decoded as pixels, cannot run script |
| `video/mp4`, `audio/mpeg` | Yes | Played by the media stack, not parsed as a document |
| `application/pdf` | Usually download | PDF viewers have had vulnerabilities; inline is acceptable only by choice |
| `image/svg+xml` | No, or sandboxed | SVG is XML and can contain script |
| `text/html`, `application/xhtml+xml` | No | Executes as a page |
| Unknown or `application/octet-stream` | No | Force download |
SVG is the common trap. It is "an image" to most upload forms, yet it can carry <script> and event handlers. If you must accept SVG, either rasterize it to PNG in your processing pipeline and serve the PNG, or serve it with the sandboxing headers shown below.
Control download behavior
The Content-Disposition header tells the browser whether to show the response or save it.
HTTP/1.1 200 OK
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="report.pdf"
X-Content-Type-Options: nosniffattachment makes top-level navigation download the file instead of rendering it. Use it for every type outside your inline allowlist. Two details matter:
attachmentdoes not stop a file from being used as a subresource. An<img>or<script src>on another site can still load it. That is whynosniffand the allowlist still matter.- The filename is attacker-controlled. Sanitize it before placing it in a header. Remove quotes, slashes, control characters, and newlines. Better, use your own generated name or encode with the
filename*=UTF-8''...form from RFC 6266. Header injection through a newline in a filename is a real bug class.
With S3 you can set these headers at serve time without changing the stored object. A presigned GET URL accepts response overrides:
import boto3
s3 = boto3.client("s3")
url = s3.generate_presigned_url(
"get_object",
Params={
"Bucket": "example-uploads",
"Key": "media/9b1c4e/original.bin",
"ResponseContentType": "application/octet-stream",
"ResponseContentDisposition": 'attachment; filename="download.bin"',
},
ExpiresIn=300,
)
print(url)The override values are part of the signature, so a viewer cannot remove or change them.
Serve from a separate domain
Headers reduce the risk, but a mistake in one of them would put user content in your application's origin. A separate domain removes that exposure by construction. The browser's same-origin policy treats https://usercontent.example-cdn.com and https://app.example.com as unrelated origins. A script that runs on the content domain cannot read your application's cookies, storage, or DOM, and cannot make credentialed requests as the user.
Practical rules:
- Use a different registrable domain, not just a subdomain.
example.comandexample-usercontent.comare separate sites. A subdomain such asfiles.example.comis the same site, and cookies set withDomain=example.comare sent to it. Browsers also group subdomains for some features such asSameSitecookies. - Never set application cookies on the content domain, and keep it free of login or API endpoints.
- If you list the content domain in the Public Suffix List, as large platforms do for user-hosted sites, browsers isolate each subdomain from the others. Most teams do not need this.
- Give each tenant its own subdomain only if tenants must be isolated from one another. Otherwise one shared content domain is enough.
This is why many platforms host user files on names such as githubusercontent.com rather than on their main domain.
Add defensive response headers
Configure these at the CDN or storage layer so every object gets them, not only those your code remembers to set.
HTTP/1.1 200 OK
Content-Type: image/png
X-Content-Type-Options: nosniff
Content-Disposition: inline
Content-Security-Policy: default-src 'none'; sandbox
Cross-Origin-Resource-Policy: same-site
Referrer-Policy: no-referrer
Cache-Control: public, max-age=31536000, immutableContent-Security-Policy: default-src 'none'; sandboxmakes the browser treat the response as a unique opaque origin with no script, no plugins, and no network requests. If someone does open a hostile SVG or HTML file directly, it cannot do anything. This is the strongest safety net for the documents you decide to serve inline.Cross-Origin-Resource-Policylimits which sites may embed the file. Usesame-siteorsame-originfor private-feeling assets, andcross-originfor assets meant to be embedded anywhere.Referrer-Policy: no-referrerstops signed URLs from leaking through theRefererheader when a viewer clicks a link from a page that loaded them.
Configure CORS narrowly
CORS (cross-origin resource sharing) controls whether JavaScript on another origin can read the response. Do not send Access-Control-Allow-Origin: * on private or credentialed content. For a canvas or fetch use case, allow the specific application origin only. Plain <img> and <video> tags do not need CORS at all.
Failure modes and gotchas
- Cache serves the wrong headers. If the CDN caches a response before you add a header, old copies lack it. Change headers at the CDN with a response-headers policy so they apply on every response, and invalidate or version the URL when you fix a mistake.
- Content type from the extension. Serving
x.pngasimage/pngbecause of its name, without checking the bytes, defeats validation. Use the stored, verified type. - Polyglot files. A file can be valid as two formats at once, such as an image that is also a script or HTML.
nosniff, the separate domain, andsandboxare what protect you here, because content checks alone cannot rule it out. - Signed URLs in logs and referrers. A long-lived signed URL is a bearer credential. Keep lifetimes short and send
no-referrer. - Open redirects and path tricks. Build object keys on the server from generated IDs. Never place a user-supplied path into a key without normalizing it.
A checklist for the serving layer
- Content lives on a separate registrable domain with no cookies and no application endpoints.
- Every response carries
X-Content-Type-Options: nosniffand the verifiedContent-Type. - Only allowlisted media types use
inline. Everything else usesattachment. - A restrictive CSP with
sandboxis applied to all user content. - Filenames in headers are sanitized or generated.
- CORS and
Cross-Origin-Resource-Policyare as narrow as the use case allows. - Private media uses short-lived signed URLs or cookies, covered in the previous chapter, and
Referrer-Policy: no-referrer.
Exercise
A user uploads logo.svg that contains a <script> tag. Your site serves it from https://app.example.com/u/logo.svg with Content-Type: image/svg+xml. Describe what an attacker gains, and name two changes that would remove the risk.
Show answer
If a victim opens the link directly, the browser renders the SVG as a document in the origin app.example.com, so the script can read non-HttpOnly cookies, call the API with the victim's session, and read storage. Fixes: serve user content from a separate registrable domain so the script has no access to the app origin, and add Content-Security-Policy: default-src 'none'; sandbox (or force Content-Disposition: attachment, or rasterize the SVG to PNG in the pipeline). Adding X-Content-Type-Options: nosniff alone does not help, because the declared type is already SVG.
Exercise
Why is files.example.com a weaker isolation choice than example-usercontent.com for hosting user uploads?
Show answer
A subdomain belongs to the same site as example.com. Cookies set with Domain=example.com are sent to it, and browsers treat it as same-site for SameSite cookie rules, so script on it has a path to attack the main application. A different registrable domain is a different site and origin, so cookies and storage are not shared.