OSINT Advanced

What Your Files Reveal: Auditing EXIF and Document Metadata and Stripping It from Django Uploads

Audit the hidden metadata in your organisation's own published images, PDFs and Office files with Python, then build a Django upload pipeline that detects types by content, strips EXIF, XMP and PDF history, rejects unsafe documents, and proves it with tests.

KC Ramo DjangoZen Team Dec 05, 2026 19 min read 4 views

Every photo, PDF and Word document your organisation publishes carries a second layer of information that nobody sees on screen: usernames, internal file paths, software versions, camera serial numbers and sometimes GPS coordinates. In this tutorial you audit your own published files for that layer with Python, then build a Django upload pipeline that detects file types by content, strips metadata, keeps an access-controlled original, and proves all of it with tests.

Scope and ethics

This is OSINT for defenders. The question is narrow: what does our own organisation reveal through the files it publishes? You audit files you own and are authorised to inspect, such as an export of your CMS media library or a download of your own public website made in line with your organisation's policy. The techniques here are not for examining files about or from private individuals, and nothing in this tutorial should be used to locate, profile or identify a person. Using EXIF GPS data to work out where someone lives or was photographed is exactly the harm this tutorial helps you prevent.

Metadata about your colleagues is personal data under the GDPR (in the Netherlands, the AVG). A document that publishes an employee's username, or a photo that publishes the location of a home office, is a data minimisation problem as well as a security problem. Treat the audit results themselves as confidential: a spreadsheet listing every username found in your public files is a useful target.

Setup and versions

The code targets Python 3.12 or newer and was run on Python 3.13 with the latest stable releases at the time of writing: Django 5.2.20 (the 5.2 LTS line), Pillow 13.0.0, pypdf 7.2.0 and pillow-heif 1.9.0.

python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install "Django>=5.2,<6.0" "Pillow>=13.0,<14.0" "pypdf>=7.2,<8.0" "pillow-heif>=1.9,<2.0"
django-admin startproject myproject .
python manage.py startapp uploads

Where metadata hides

Images: EXIF, XMP and PNG text chunks

A JPEG stores EXIF in an APP1 segment as a small TIFF structure with several directories (IFDs). IFD0 holds Make, Model, Software, Artist and Orientation. The Exif sub-IFD holds DateTimeOriginal, lens data and often BodySerialNumber. The GPS sub-IFD holds latitude, longitude, altitude and a timestamp. Many files also embed a reduced-size thumbnail in IFD1, which can survive a crop of the main image. XMP is a separate XML packet, written by editing tools, which can contain the creator, editing history and the original file name.

PNG has no EXIF segment in the classic sense, but it has tEXt, zTXt and iTXt chunks (diagram tools like to put the source file path there), an optional eXIf chunk, and XMP in an iTXt chunk named XML:com.adobe.xmp. HEIC, the default format of many phones, stores EXIF and XMP as items inside the HEIF container; Pillow reads it once pillow-heif registers its opener.

PDF: the Info dictionary, XMP and incremental updates

A PDF has a document Info dictionary (/Author, /Creator, /Producer, /Title, dates) and may also have an XMP stream referenced from the catalog. The two are independent: tools that edit one often leave the other alone. The bigger trap is the incremental update. When a PDF editor saves changes, it may append a new revision to the end of the file instead of rewriting it. The old objects, including the old Info dictionary and even removed page content, remain in the bytes. Each revision ends with its own %%EOF marker, which gives you a cheap way to spot them.

Office files: docProps, comments and tracked changes

A .docx, .xlsx or .pptx file is a ZIP archive of XML parts. docProps/core.xml holds dc:creator, cp:lastModifiedBy, cp:revision and timestamps. docProps/app.xml holds the application and version, company name, total editing time and the template path, which is often a UNC path on an internal file server. docProps/custom.xml holds whatever your document management system added. Then there is content that is invisible in a normal view: word/comments.xml, tracked insertions and deletions (w:ins, w:del) with author names and dates, and revision save IDs that link documents edited in the same session.

What an attacker learns from your files

FieldExampleWhat it reveals
Author, lastModifiedBy, Artistj.devriesUsername convention, useful for password spraying and phishing
Template, PNG comment\\fs01.corp.example.com\templatesInternal host names, share layout, Windows user profile paths
Software, Producer, AppVersionPDFMaker 23.1Exact client software versions, so which exploits are worth trying
GPS, DateTimeOriginal52.37, 4.88Where and when a photo was taken, possibly an employee's home
BodySerialNumberSN-0042-7781Links photos from the same device across sites
Comments, tracked changesold price, reviewer remarksNegotiation positions and internal discussion

Generating sample files

To keep the tutorial self-contained, generate leaky files yourself instead of downloading any. The JPEG gets a full set of EXIF tags including GPS and an Orientation of 6 (rotate 90 degrees on display); the PDF gets a second, incremental revision that "fixes" the author.

import zipfile
from pathlib import Path

from PIL import Image, PngImagePlugin
from PIL.ExifTags import Base, GPS, IFD
from pypdf import PdfWriter

def make_jpeg(path: Path) -> None:
    img = Image.new("RGB", (64, 32), (200, 30, 30))
    exif = Image.Exif()
    exif[Base.Make] = "ExampleCam"
    exif[Base.Model] = "EC-100"
    exif[Base.Software] = "PhotoTool 4.2.1"
    exif[Base.Artist] = "j.devries"
    exif[Base.Orientation] = 6  # rotate 90 CW on display
    exif_ifd = exif.get_ifd(IFD.Exif)
    exif_ifd[Base.DateTimeOriginal] = "2026:03:14 09:26:53"
    exif_ifd[Base.BodySerialNumber] = "SN-0042-7781"
    gps = exif.get_ifd(IFD.GPSInfo)
    gps[GPS.GPSLatitudeRef] = "N"
    gps[GPS.GPSLatitude] = (52.0, 22.0, 30.5)
    gps[GPS.GPSLongitudeRef] = "E"
    gps[GPS.GPSLongitude] = (4.0, 53.0, 12.25)
    img.save(path, "JPEG", exif=exif, quality=90)

def make_pdf(path: Path) -> None:
    w = PdfWriter()
    w.add_blank_page(width=595, height=842)
    w.add_metadata({
        "/Author": "j.devries",
        "/Creator": "WordProcessor 16.0.18025",
        "/Producer": "PDFMaker 23.1 for Word",
        "/Title": "Draft - internal pricing v3",
    })
    w.write(path)
    # Incremental update: a later "cleanup" appends a new revision,
    # but the original bytes (and old metadata) stay in the file.
    w2 = PdfWriter(path, incremental=True)
    w2.add_metadata({"/Author": "Communications", "/Title": "Price list 2026"})
    w2.write(path)

The full script also writes a PNG with a Comment chunk containing a Windows path, and a .docx built with zipfile that contains core.xml, app.xml with a UNC template path, one comment and a tracked change. Note PdfWriter(path, incremental=True): it appends to the existing file, which is exactly what many desktop tools do.

Auditing your published files in bulk

The audit script walks a folder, dispatches on extension (fine here, because you are inspecting your own known exports, not untrusted uploads) and prints one CSV row per metadata field. A regular expression flags values that look like paths or initial.surname usernames, so a reviewer can sort on that column.

"""Audit metadata in a folder of files your organisation has published."""
import csv
import re
import sys
import zipfile
from pathlib import Path
from xml.etree import ElementTree as ET

from PIL import Image
from PIL.ExifTags import GPSTAGS, IFD, TAGS
from pypdf import PdfReader

W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
INTERESTING = re.compile(r"([A-Za-z]:\\|\\\\|/home/|/Users/|\b[a-z]\.[a-z]+\b)")


def image_meta(path: Path) -> dict:
    out = {}
    with Image.open(path) as img:
        exif = img.getexif()
        for tag, value in exif.items():
            out[TAGS.get(tag, tag)] = value
        for tag, value in exif.get_ifd(IFD.Exif).items():
            out[TAGS.get(tag, tag)] = value
        gps = exif.get_ifd(IFD.GPSInfo)
        if gps:
            out["GPS"] = {GPSTAGS.get(k, k): v for k, v in gps.items()}
        for key, value in img.info.items():  # PNG text chunks, XMP
            if isinstance(value, str):
                out[f"info:{key}"] = value
    out.pop("ExifOffset", None)
    out.pop("GPSInfo", None)
    return out


def pdf_meta(path: Path) -> dict:
    reader = PdfReader(path)
    out = {k.lstrip("/"): str(v) for k, v in (reader.metadata or {}).items()}
    out["xmp"] = reader.xmp_metadata is not None
    raw = path.read_bytes()
    out["revisions"] = raw.count(b"%%EOF")
    # Old Info dictionaries survive incremental updates:
    out["all_authors"] = sorted(set(re.findall(rb"/Author \(([^)]*)\)", raw)))
    return out


def docx_meta(path: Path) -> dict:
    out = {}
    with zipfile.ZipFile(path) as z:
        names = set(z.namelist())
        for part in ("docProps/core.xml", "docProps/app.xml"):
            if part in names:
                for el in ET.fromstring(z.read(part)):
                    if el.text and el.text.strip():
                        out[el.tag.split("}")[1]] = el.text.strip()
        if "word/comments.xml" in names:
            root = ET.fromstring(z.read("word/comments.xml"))
            out["comments"] = len(root.findall(f"{W}comment"))
        body = ET.fromstring(z.read("word/document.xml"))
        changes = body.findall(f".//{W}ins") + body.findall(f".//{W}del")
        out["tracked_changes"] = len(changes)
        out["change_authors"] = sorted({c.get(f"{W}author") for c in changes})
    return out


HANDLERS = {".jpg": image_meta, ".jpeg": image_meta, ".png": image_meta,
            ".heic": image_meta, ".pdf": pdf_meta, ".docx": docx_meta,
            ".xlsx": docx_meta, ".pptx": docx_meta}


def audit(folder: Path):
    for path in sorted(folder.rglob("*")):
        handler = HANDLERS.get(path.suffix.lower())
        if not handler:
            continue
        try:
            meta = handler(path)
        except Exception as exc:  # a broken file is a finding too
            meta = {"error": repr(exc)}
        for key, value in meta.items():
            flag = "!" if INTERESTING.search(str(value)) else ""
            yield path.name, key, str(value)[:90], flag


if __name__ == "__main__":
    writer = csv.writer(sys.stdout)
    writer.writerow(["file", "field", "value", "flag"])
    for row in audit(Path(sys.argv[1])):
        writer.writerow(row)

Running it against the samples (output shortened):

$ python audit.py published
file,field,value,flag
network-diagram.png,info:Software,DiagramPro 11.0 (build 2291),
network-diagram.png,info:Comment,Exported from C:\Users\j.devries\Projects\myproject\net.drawio,!
...
offer-template.docx,lastModifiedBy,a.bakker,!
offer-template.docx,Company,myproject internal,
offer-template.docx,Template,\\fs01.corp.example.com\templates\Letter.dotm,!
offer-template.docx,comments,1,
offer-template.docx,tracked_changes,2,
...
price-list.pdf,Author,Communications,
price-list.pdf,revisions,2,
price-list.pdf,all_authors,"[b'Communications', b'j\\056devries']",!
...
team-photo.jpg,Artist,j.devries,!
team-photo.jpg,BodySerialNumber,SN-0042-7781,
team-photo.jpg,GPS,"{'GPSLatitudeRef': 'N', 'GPSLatitude': (52.0, 22.0, 30.5), ...

Two details deserve attention. First, pypdf reports the current author as "Communications", but the raw bytes still contain the first revision's author. Second, that older value is stored as j\056devries: PDF string syntax allows octal escapes, so a naive grep for j.devries would miss it. Search parsed values, not just bytes. For a real audit, run the script on the export of your media library, sort by the flag column, and fix the source: change templates, document properties defaults and camera settings, not only the published copies.

A Django upload pipeline that strips metadata

Auditing finds the problem after publication. The durable fix is to make the publishing path clean by construction. Every file uploaded through your Django site goes through one function, sanitise(), which decides the type from the bytes, rebuilds the file without metadata, or rejects it.

The sanitiser module

"""Detect file types by content and strip metadata before publishing."""
import io
import zipfile
from dataclasses import dataclass
from xml.etree import ElementTree as ET

from PIL import Image, ImageOps
from pillow_heif import register_heif_opener
from pypdf import PdfReader, PdfWriter
from pypdf.generic import NameObject

register_heif_opener()
Image.MAX_IMAGE_PIXELS = 40_000_000  # decompression-bomb guard

HEIF_BRANDS = {b"heic", b"heix", b"hevc", b"mif1", b"msf1"}
MAX_ZIP_ENTRIES = 500
MAX_ZIP_UNCOMPRESSED = 50 * 1024 * 1024


class Rejected(ValueError):
    """The file cannot be published safely."""


@dataclass
class Clean:
    data: bytes
    kind: str
    extension: str
    removed: list[str]


def sniff(data: bytes) -> str | None:
    if data.startswith(b"\xff\xd8\xff"):
        return "jpeg"
    if data.startswith(b"\x89PNG\r\n\x1a\n"):
        return "png"
    if data[4:8] == b"ftyp" and data[8:12] in HEIF_BRANDS:
        return "heic"
    if data.startswith(b"%PDF-"):
        return "pdf"
    if data.startswith(b"PK\x03\x04"):
        try:
            with zipfile.ZipFile(io.BytesIO(data)) as z:
                names = set(z.namelist())
        except zipfile.BadZipFile:
            return None
        if "[Content_Types].xml" in names and "word/document.xml" in names:
            return "docx"
    return None


def clean_image(data: bytes, kind: str) -> Clean:
    with Image.open(io.BytesIO(data)) as img:
        img.load()
        removed = sorted(k for k in img.info if k not in ("dpi", "gamma"))
        if img.getexif():
            removed.append("EXIF")
        # Apply the Orientation tag to the pixels, or the picture
        # ends up sideways once the tag is gone.
        img = ImageOps.exif_transpose(img)
        out = io.BytesIO()
        if kind == "png":
            img.save(out, "PNG", optimize=True)  # no pnginfo, no exif
            return Clean(out.getvalue(), "png", ".png", removed)
        # JPEG and HEIC both leave as baseline JPEG.
        img.convert("RGB").save(out, "JPEG", quality=88)
        return Clean(out.getvalue(), "jpeg", ".jpg", removed)


DANGEROUS_ROOT_KEYS = ("/OpenAction", "/AA", "/AcroForm")
PAGE_PRIVATE_KEYS = ("/PieceInfo", "/Metadata", "/AA")


def clean_pdf(data: bytes) -> Clean:
    reader = PdfReader(io.BytesIO(data))
    if reader.is_encrypted:
        raise Rejected("encrypted PDF")
    root = reader.trailer["/Root"]
    names = root.get("/Names", {})
    for key in ("/JavaScript", "/EmbeddedFiles"):
        if key in names:
            raise Rejected(f"PDF contains {key}")
    removed = [k for k in (reader.metadata or {})]
    if reader.xmp_metadata is not None:
        removed.append("XMP")
    removed += [k for k in DANGEROUS_ROOT_KEYS if k in root]
    writer = PdfWriter()
    for page in reader.pages:
        for key in PAGE_PRIVATE_KEYS:
            if NameObject(key) in page:
                del page[NameObject(key)]
        writer.add_page(page)  # copies page content, not the old catalog
    writer.metadata = None  # no Info dictionary, not even "Producer: pypdf"
    out = io.BytesIO()
    writer.write(out)  # full rewrite: earlier revisions are not carried over
    return Clean(out.getvalue(), "pdf", ".pdf", removed)


W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
CP = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"
EP = "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"
CU = "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties"
BLANK = {
    "docProps/core.xml": f'<cp:coreProperties xmlns:cp="{CP}"/>',
    "docProps/app.xml": f'<Properties xmlns="{EP}"/>',
    "docProps/custom.xml": f'<Properties xmlns="{CU}"/>',
}


def clean_docx(data: bytes) -> Clean:
    src = zipfile.ZipFile(io.BytesIO(data))
    infos = src.infolist()
    if len(infos) > MAX_ZIP_ENTRIES:
        raise Rejected("too many entries in archive")
    if sum(i.file_size for i in infos) > MAX_ZIP_UNCOMPRESSED:
        raise Rejected("archive expands too much")
    names = {i.filename for i in infos}
    if any(n.startswith("word/vbaProject") for n in names):
        raise Rejected("document contains macros")
    if "word/comments.xml" in names:
        raise Rejected("document contains comments")
    body = ET.fromstring(src.read("word/document.xml"))
    if body.find(f".//{W}ins") is not None or body.find(f".//{W}del") is not None:
        raise Rejected("document contains tracked changes")
    out, removed = io.BytesIO(), []
    with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as dst:
        for info in infos:
            payload = src.read(info.filename)
            if info.filename in BLANK:
                payload = BLANK[info.filename].encode()
                removed.append(info.filename)
            dst.writestr(info.filename, payload)
    return Clean(out.getvalue(), "docx", ".docx", removed)


def sanitise(data: bytes) -> Clean:
    kind = sniff(data)
    if kind in ("jpeg", "png", "heic"):
        try:
            return clean_image(data, kind)
        except (OSError, Image.DecompressionBombError) as exc:
            raise Rejected(f"unreadable image: {exc}") from exc
    if kind == "pdf":
        return clean_pdf(data)
    if kind == "docx":
        return clean_docx(data)
    raise Rejected("file type not allowed")

The design choices, in order of importance:

  • Type by content. sniff() reads magic bytes. The file name and the browser-supplied content_type are both attacker-controlled, so neither is used. A ZIP is only treated as docx if it has the parts a Word document needs. Anything unrecognised, including SVG and HTML, is rejected, which closes the stored cross-site scripting route as well.
  • Re-encode, do not edit. Removing known tags leaves unknown ones behind. Decoding to pixels and encoding a fresh file discards EXIF, XMP, PNG text chunks, the embedded thumbnail and any trailing data in one step.
  • Orientation first. ImageOps.exif_transpose() applies the Orientation tag to the pixels before the tag disappears. Skip it and portrait photos appear sideways. HEIC input leaves as JPEG, which browsers can display.
  • Decompression bombs. Image.MAX_IMAGE_PIXELS makes Pillow raise DecompressionBombError for images over twice the limit (and warn above it), so a tiny file cannot expand into gigabytes of memory.
  • Rewrite PDFs fully. Copying pages into a new PdfWriter does not carry over the old catalog, XMP stream or earlier revisions; writer.metadata = None also drops pypdf's own Producer entry. Page-level /PieceInfo and /Metadata are removed, and PDFs with JavaScript or embedded files are refused.
  • Office files: reject what you cannot clean. Blanking docProps is safe. Removing comments or accepting tracked changes correctly is not something to do with string edits, so those documents are rejected with a clear message. Sizes and entry counts are checked before anything is extracted, to stop ZIP bombs.

Some losses are deliberate. The ICC colour profile is dropped, which can shift colours slightly on wide-gamut photos; if that matters, pass icc_profile through explicitly, since it describes a colour space rather than a person or device in most cases. A PDF with fillable forms loses interactivity when /AcroForm is not copied.

Model, storage and originals

import hashlib
import uuid

from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.db import models

# Originals live outside MEDIA_ROOT and are never served by the web server.
private_storage = FileSystemStorage(location=settings.PRIVATE_MEDIA_ROOT)


def original_path(instance, filename):
    return f"originals/{instance.pk}.bin"  # no user-supplied name on disk


def public_path(instance, filename):
    return f"public/{instance.pk}{instance.extension}"


class Upload(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    kind = models.CharField(max_length=10)
    extension = models.CharField(max_length=8)
    original = models.FileField(storage=private_storage, upload_to=original_path,
                                blank=True)
    sanitised = models.FileField(upload_to=public_path)
    original_sha256 = models.CharField(max_length=64)
    removed = models.JSONField(default=list)
    created_at = models.DateTimeField(auto_now_add=True)

    @staticmethod
    def digest(data: bytes) -> str:
        return hashlib.sha256(data).hexdigest()

Whether you keep the original at all is a policy decision. Keeping it lets you answer "what did the uploader actually send?" during an incident, and the SHA-256 lets you prove a later copy is the same file. But the original is exactly the file with the GPS coordinates in it. If you keep originals, store them outside MEDIA_ROOT so the web server can never serve them, name them by UUID instead of by user-supplied file name, restrict access, and set a retention period. If you do not need them, set KEEP_ORIGINALS = False and keep only the hash.

from django.conf import settings
from django.core.files.base import ContentFile
from django.db import transaction

from .models import Upload
from .sanitise import Clean


@transaction.atomic
def store(raw: bytes, clean: Clean) -> Upload:
    upload = Upload(kind=clean.kind, extension=clean.extension,
                    original_sha256=Upload.digest(raw), removed=clean.removed)
    upload.sanitised.save("x", ContentFile(clean.data), save=False)
    if settings.KEEP_ORIGINALS:
        upload.original.save("x", ContentFile(raw), save=False)
    upload.save()
    return upload

Form, view and size limits

from django import forms
from django.conf import settings

from .sanitise import Rejected, sanitise


class UploadForm(forms.Form):
    file = forms.FileField()

    def clean_file(self):
        f = self.cleaned_data["file"]
        if f.size > settings.MAX_UPLOAD_BYTES:
            raise forms.ValidationError("File too large.")
        data = f.read()
        try:
            self.cleaned_data["clean"] = sanitise(data)
        except Rejected as exc:
            raise forms.ValidationError(f"Rejected: {exc}") from exc
        self.cleaned_data["raw"] = data
        return f
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.views.decorators.http import require_POST

from .forms import UploadForm
from .services import store


@login_required
@require_POST
def upload(request):
    form = UploadForm(request.POST, request.FILES)
    if not form.is_valid():
        return JsonResponse({"errors": form.errors}, status=400)
    obj = store(form.cleaned_data["raw"], form.cleaned_data["clean"])
    return JsonResponse({"id": str(obj.id), "url": obj.sanitised.url,
                         "removed": obj.removed}, status=201)
# myproject/settings.py (additions)
INSTALLED_APPS += ["uploads"]
MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media"
PRIVATE_MEDIA_ROOT = BASE_DIR / "private"
MAX_UPLOAD_BYTES = 10 * 1024 * 1024
FILE_UPLOAD_MAX_MEMORY_SIZE = MAX_UPLOAD_BYTES
DATA_UPLOAD_MAX_MEMORY_SIZE = 1024 * 1024
KEEP_ORIGINALS = True

Note what each limit does. DATA_UPLOAD_MAX_MEMORY_SIZE limits the request body excluding file uploads; Django itself does not cap file size, it only decides whether to buffer in memory or in a temporary file. The form check rejects large files before they are read and parsed, but the bytes have already been received by then, so also set a request body limit in your reverse proxy that is slightly above MAX_UPLOAD_BYTES.

Tests

The tests build their own inputs, so they run offline and in CI. They assert on bytes, not just on what Pillow or pypdf reports, because a parser can hide data that is still in the file.

class SanitiseTests(TestCase):
    def test_jpeg_exif_removed_and_orientation_applied(self):
        clean = sanitise(jpeg_with_exif())
        img = Image.open(io.BytesIO(clean.data))
        self.assertEqual(img.size, (32, 64))  # rotated, not just untagged
        self.assertEqual(len(img.getexif()), 0)
        self.assertNotIn(b"j.devries", clean.data)
        self.assertNotIn(b"SN-0042", clean.data)

    def test_png_text_chunks_removed(self):
        clean = sanitise(png_with_text())
        self.assertNotIn(b"tEXt", clean.data)
        self.assertNotIn(b"devries", clean.data)

    def test_pdf_metadata_and_old_revisions_removed(self):
        raw = pdf_with_history()
        self.assertEqual(raw.count(b"%%EOF"), 2)
        clean = sanitise(raw)
        self.assertEqual(clean.data.count(b"%%EOF"), 1)
        self.assertNotIn(b"devries", clean.data)
        self.assertNotIn(b"/Author", clean.data)
        self.assertIsNone(PdfReader(io.BytesIO(clean.data)).metadata)

The view tests patch the private storage, because a storage object passed to a FileField is bound when the model class is created and override_settings cannot reach it:

@override_settings(MEDIA_ROOT=TMP, PRIVATE_MEDIA_ROOT=TMP, MAX_UPLOAD_BYTES=50_000)
class UploadViewTests(TestCase):
    def setUp(self):
        self.client.force_login(User.objects.create_user("editor"))
        field = Upload._meta.get_field("original")  # storage is bound at import
        patcher = mock.patch.object(field, "storage", FileSystemStorage(TMP))
        patcher.start()
        self.addCleanup(patcher.stop)

    def post(self, name, data):
        return self.client.post("/upload/", {"file": SimpleUploadedFile(name, data)})

    def test_upload_stores_clean_copy_and_hash(self):
        raw = jpeg_with_exif()
        resp = self.post("holiday.png", raw)  # wrong extension on purpose
        self.assertEqual(resp.status_code, 201)
        obj = Upload.objects.get()
        self.assertEqual(obj.kind, "jpeg")
        self.assertTrue(obj.sanitised.name.endswith(".jpg"))
        self.assertEqual(obj.original_sha256, Upload.digest(raw))
        self.assertIn("EXIF", obj.removed)
        self.assertEqual(obj.original.read(), raw)  # private copy kept
$ python manage.py test uploads
Found 9 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.........
----------------------------------------------------------------------
Ran 9 tests in 0.056s

OK

Running sanitise() on the four sample files shows the policy at work:

network-diagram.png: png 488 -> 99 bytes, removed=['Comment', 'Software', 'XML:com.adobe.xmp', 'xmp']
offer-template.docx: REJECTED (document contains comments)
price-list.pdf: pdf 894 -> 380 bytes, removed=['/Producer', '/Author', '/Creator', '/Title']
team-photo.jpg: jpeg 982 -> 662 bytes, removed=['exif', 'jfif', 'jfif_density', 'jfif_unit', 'jfif_version', 'EXIF']

What this does not catch

Metadata stripping removes the hidden layer, not the visible one. A screenshot that shows a file path, a photo of a whiteboard, a PDF where text was "redacted" with a black rectangle drawn over it, or a spreadsheet with a hidden sheet all pass through untouched. Font subset names and embedded objects in Office files can also carry information. Treat the pipeline as one control among several: editorial review for content, templates and device settings that do not add metadata in the first place, and a periodic re-run of the audit script on what is actually live.

Checklist

  1. Confirm the audit is authorised and limited to files your organisation published; treat results as confidential personal data.
  2. Export your media library and run the audit script; sort by the flag column and record which templates, tools and devices produced the leaks.
  3. Fix the sources: document templates, default author names, camera and phone location settings, PDF export options.
  4. Route every upload through one sanitiser that detects types by magic bytes and rejects everything else, including SVG and HTML.
  5. Re-encode images after exif_transpose(); set Image.MAX_IMAGE_PIXELS.
  6. Rebuild PDFs page by page with metadata = None; refuse JavaScript and embedded files; verify a single %%EOF.
  7. Reject Office files with comments, tracked changes or macros; blank docProps otherwise; check ZIP sizes before reading.
  8. Decide on originals: private storage, UUID names, access control and retention, or hash only.
  9. Enforce size limits in both Django and the reverse proxy.
  10. Keep byte-level tests for every file type in CI, and re-run the audit on the live site on a schedule.

Found a mistake in this tutorial? Let us know and we will fix it.