T16.2: D19 uploaded files download safely

New server/files_http.py; get_wp_file uses it.
- PDF and raster images (png, jpeg, gif, webp, bmp, avif) open inline,
  as before; Cache-Control unchanged for the offline drawing cache.
- Every other type, SVG included, downloads as an attachment with
  Content-Security-Policy: sandbox; default-src 'none'.
- SVG uploads stay accepted (decided 2026-10-02: accept, download only).
- Content-Disposition: ASCII fallback + RFC 5987 filename*, control
  characters and quotes replaced. nosniff from the API too.

Security review SEC-01 (stored XSS through an SVG drawing) and SEC-15e
(non-Latin-1 names gave 500; CR/LF reached the header).

security_check.py D19: 20/20 total with D21. Against da1325c: 6 fails
(the findings); every inline/cache/access check passes on both.

(cherry picked from commit 14ecb75c88)
This commit is contained in:
2026-10-02 13:52:43 -07:00
parent d962ab2381
commit f4d74879cc
3 changed files with 121 additions and 6 deletions

View File

@@ -27,7 +27,7 @@ from sqlalchemy.orm import Session
from starlette.middleware.sessions import SessionMiddleware
from .db import Base, engine, get_db
from . import models, auth, notify, assets_db, okta_auth, okta_fake
from . import models, auth, notify, assets_db, okta_auth, okta_fake, files_http
log = logging.getLogger("wpsuite.app")
@@ -2910,10 +2910,9 @@ def get_wp_file(file_id: str, user: models.User = Depends(auth.get_current_user)
if not row:
raise HTTPException(status_code=404, detail="File not found")
require_project_access(db, user, row.project_id)
return Response(content=row.data, media_type=row.mime or "application/octet-stream",
headers={"Content-Disposition":
f'inline; filename="{(row.name or "file").replace(chr(34), "")}"',
"Cache-Control": "private, max-age=86400"})
# D19: PDF and raster images inline as before; anything else (SVG included)
# downloads as a sandboxed attachment, and every name is a valid header.
return files_http.file_response(row)
@app.patch("/api/files/{file_id}")

66
server/files_http.py Normal file
View File

@@ -0,0 +1,66 @@
"""Safe HTTP responses for uploaded drawings — D19 (T16.2).
Security review 2026-10-01, SEC-01 and SEC-15e.
WHY THIS EXISTS
Uploads accept `image/*`, which includes `image/svg+xml`. An SVG is a
document, not a picture: it can carry <script>. GET /api/files/{id} used to
return every file `inline` with the uploader's content type, on the app's own
origin, so a script inside an SVG ran as whoever opened the drawing - with
their session, and with an admin's power if an admin opened it.
The download name was built by hand with only `"` removed. A name outside
Latin-1 (`Plan é.pdf`) made the header unencodable, so the download failed
with 500; CR/LF in a name went into the header as typed.
THE RULE (D19, decided 2026-10-02)
* PDF and raster images open INLINE, exactly as before. That is what the
creator's drawing list, the printed package and Field View link to
(CR-007), and the offline drawing cache in sw.js stores.
* Every other type, SVG included, is an ATTACHMENT inside a sandbox: the
browser saves it instead of rendering it on our origin, and
`Content-Security-Policy: sandbox` strips script and same-origin access
even if someone opens the saved response directly.
* SVG UPLOADS STAY ACCEPTED (decided: accept, download only). The fix is on
the way out, so SVGs already in the database are covered too.
* `Cache-Control` is unchanged - the offline drawing cache depends on it.
"""
from __future__ import annotations
import re
from urllib.parse import quote
from fastapi.responses import Response
# Formats a browser shows as inert pixels, or in its own PDF viewer.
INLINE_SAFE_MIME = frozenset({
"application/pdf",
"image/png", "image/jpeg", "image/gif", "image/webp", "image/bmp", "image/avif",
})
# Control characters, and the characters that end or escape a quoted
# header parameter. Replaced, never passed through.
_UNSAFE_NAME = re.compile(r'[\x00-\x1f\x7f"\\;]')
def content_disposition(disposition: str, name: str) -> str:
"""A header value that is valid for ANY user-supplied file name: an ASCII
fallback for old clients plus RFC 5987 `filename*` with the real name."""
name = _UNSAFE_NAME.sub("_", name or "file").strip() or "file"
ascii_name = name.encode("ascii", "replace").decode("ascii").replace("?", "_")
return f"{disposition}; filename=\"{ascii_name}\"; filename*=UTF-8''{quote(name, safe='')}"
def file_response(row) -> Response:
"""The response for GET /api/files/{id}. `row` is a models.WpFile."""
mime = (row.mime or "application/octet-stream").lower()
headers = {
"Cache-Control": "private, max-age=86400", # unchanged: sw.js caches drawings offline
"X-Content-Type-Options": "nosniff", # NGINX adds it too; the dev server did not
}
if mime in INLINE_SAFE_MIME:
headers["Content-Disposition"] = content_disposition("inline", row.name)
else:
headers["Content-Disposition"] = content_disposition("attachment", row.name)
headers["Content-Security-Policy"] = "sandbox; default-src 'none'"
return Response(content=row.data, media_type=mime, headers=headers)

View File

@@ -118,7 +118,57 @@ def d21():
pin.group(1) if pin else "no pin")
SECTIONS = [d21]
# ── D19: uploaded files download safely ──────────────────────────────────────
def d19():
print("\nD19 uploaded files download safely")
r = as_member.post("/api/wps", json={"id": "wp_files", "project_id": "proj_a", "number": "F1"})
assert r.status_code == 200, r.text
def upload(name, mime, data):
r = as_member.post("/api/wps/wp_files/files", json={
"name": name, "mime": mime, "data_base64": base64.b64encode(data).decode()})
return r.status_code, (r.json().get("file") or {}).get("id")
code, svg = upload("route.svg", "image/svg+xml",
b'<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>')
check("D19", "an SVG upload is still accepted (decided: accept, download only)", code == 200, f"status {code}")
r = as_member.get(f"/api/files/{svg}")
disp, csp = r.headers.get("content-disposition", ""), r.headers.get("content-security-policy", "")
check("D19", "an SVG downloads as an attachment, never inline", disp.startswith("attachment"), disp)
check("D19", "an SVG download carries a sandbox CSP", "sandbox" in csp, csp or "no CSP")
check("D19", "file responses carry nosniff", r.headers.get("x-content-type-options") == "nosniff")
for name, mime, data in (("plan.png", "image/png", b"\x89PNG\r\n\x1a\n"),
("photo.jpg", "image/jpeg", b"\xff\xd8\xff"),
("sheet.pdf", "application/pdf", b"%PDF-1.4")):
_, fid = upload(name, mime, data)
r = as_member.get(f"/api/files/{fid}")
check("D19", f"{mime} still opens inline, no sandbox",
r.status_code == 200 and r.headers.get("content-disposition", "").startswith("inline")
and "content-security-policy" not in r.headers, r.headers.get("content-disposition", ""))
check("D19", f"{mime} keeps the offline cache header",
r.headers.get("cache-control") == "private, max-age=86400", r.headers.get("cache-control", ""))
_, fid = upload("Plan é – Nivel 2.pdf", "application/pdf", b"%PDF-1.4")
r = as_member.get(f"/api/files/{fid}")
check("D19", "a drawing with a non-Latin-1 name downloads (was 500)", r.status_code == 200,
f"status {r.status_code}")
check("D19", "the real name rides in filename*",
"filename*=UTF-8''Plan%20%C3%A9" in r.headers.get("content-disposition", ""),
r.headers.get("content-disposition", ""))
_, fid = upload('a\r\nSet-Cookie: x=1;".pdf', "application/pdf", b"%PDF-1.4")
r = as_member.get(f"/api/files/{fid}")
disp = r.headers.get("content-disposition", "")
check("D19", "CR/LF and quotes in a name cannot reach the header",
r.status_code == 200 and "\r" not in disp and "\n" not in disp and "set-cookie" not in r.headers,
repr(disp))
r = client(account("user_outsider")).get(f"/api/files/{svg}")
check("D19", "a non-member still gets 403 (access check unchanged)", r.status_code == 403,
f"status {r.status_code}")
SECTIONS = [d21, d19]
def main() -> int: