Skip to main content

safeuploads

License Release PyPI version PyPI downloads Python Docs Stars

Secure file upload validation for Python 3.11+ applications. Catches dangerous filenames, malicious extensions, Windows reserved names, and compression-based attacks before you accept an upload.

Features

  • Framework-agnostic async and sync validation (FastAPI, generic)
  • Filename sanitization and Unicode security checks
  • Extension validation with configurable allow/block lists
  • ZIP bomb detection, nested archive inspection, and recursive structure protection
  • MIME type verification with file signature validation
  • Activity file support (.gpx, .tcx, .fit) with XXE-safe XML parsing and FIT structure validation
  • Gzip archive validation with decompression bomb detection
  • Streaming validation for memory-efficient large file processing
  • Resource monitoring (wall-clock time and memory limits)
  • Content analysis with malware signature and polyglot detection
  • Structured audit logging with correlation IDs
  • Rich exception hierarchy with machine-readable error codes
  • Zero configuration required—secure defaults out of the box

Installation

pip install safeuploads

safeuploads supports Python 3.11 and newer. A Python version stays supported until its CPython end of life and is dropped in the next minor release after that.

For FastAPI integration:

pip install safeuploads[fastapi]

Quick Start

from fastapi import FastAPI, UploadFile, HTTPException
from safeuploads import FileValidator
from safeuploads.exceptions import FileValidationError

app = FastAPI()
validator = FileValidator()

@app.post("/upload")
async def upload_image(file: UploadFile):
    try:
        await validator.validate_image_file(file)
    except FileValidationError as e:
        raise HTTPException(status_code=400, detail=str(e))
    
    return {"status": "success", "filename": file.filename}

For synchronous code or worker threads, use the *_sync methods. They block the calling thread and return the sanitized filename:

from safeuploads import FileValidator

validator = FileValidator()

with open("activity.gpx", "rb") as fh:
    safe_name = validator.validate_activity_file_sync(fh, "activity.gpx")

Calling a *_sync method on a thread running an asyncio event loop raises RuntimeError; await the async method there instead.

Configuration

from safeuploads import FileValidator, FileSecurityConfig

# Use default secure configuration
validator = FileValidator()

# Or customize limits
config = FileSecurityConfig()
config.limits.max_image_size = 10 * 1024 * 1024  # 10 MiB
config.limits.max_compression_ratio = 50

# Opt in to strict ZIP checking: decompress every entry to
# reject archives with forged central-directory metadata
config.limits.verify_zip_decompression = True

validator = FileValidator(config=config)

# Optionally offload blocking inspection to a bounded pool
from concurrent.futures import ThreadPoolExecutor

pooled_validator = FileValidator(
    config=config,
    executor=ThreadPoolExecutor(max_workers=4),
)

Exception Handling

from safeuploads.exceptions import (
    FileValidationError,      # Base exception
    FileSizeError,            # File too large
    ExtensionSecurityError,   # Dangerous extension
    ZipBombError,             # Compression attack
)
# FileProcessingError (internal errors, ResourceLimitError) is not a
# FileValidationError; catch it separately.

try:
    await validator.validate_image_file(file)
except FileSizeError as err:
    return {"error": "File too large", "max_size": err.max_size}
except ExtensionSecurityError as err:
    return {"error": "File type not allowed", "extension": err.extension}
except FileValidationError as err:
    return {"error": str(err), "code": err.error_code}

Current Status

Implemented

  • Filename Security: Unicode normalization, directory traversal prevention, Windows reserved names blocking
  • Extension Validation: Allow/block lists with configurable rules, dangerous extension detection
  • Compression Security: ZIP bomb detection, nested archive inspection, recursive structure and quine detection, size and ratio limits, optional strict decompression verification
  • Content Inspection: Deep ZIP content analysis with configurable depth and entry limits
  • MIME Type Verification: Magic number validation for images, ZIP, activity files, and gzip
  • Streaming Validation: Memory-efficient processing via SpooledTemporaryFile for large files
  • Resource Monitoring: wall-clock time and memory limits enforced via ResourceMonitor during the work
  • Activity File Support: GPX, TCX, and FIT file validation with XXE-safe XML parsing and FIT structure checks
  • Gzip Support: Gzip archive validation with decompression bomb detection
  • Content Analysis: Optional malware signature, web shell, and polyglot file detection
  • Audit Logging: Structured security event logging with correlation IDs via contextvars
  • Performance Optimizations: Pre-compiled pattern sets, frozenset lookups
  • Rich Exception System: Machine-readable error codes with detailed context
  • Fuzzing Tests: Hypothesis-based property testing for filenames, ZIP, images, and config

Known Limitations

  • No built-in rate limiting (application-level concern — see documentation)
  • MIME detection covers first 8 KB; advanced polyglot attacks may require enable_content_analysis
  • SpooledTemporaryFile uses the system default temp directory

Documentation

Full documentation is available at the safeuploads docs site.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Contributing

Contributions welcome! See Contributing Guidelines for guidelines.

Built with ❤️ from Portugal | Part of the Endurain ecosystem

Metadata

Release files for safeuploads 3.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for safeuploads 3.0.0
File Size Uploaded Provenance Actions
safeuploads-3.0.0.tar.gz 348.4 kB Without provenance Details for safeuploads-3.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for safeuploads 3.0.0
File Interpreter ABI Platform Actions
safeuploads-3.0.0-py3-none-any.whl Python 3 none any Details for safeuploads-3.0.0-py3-none-any.whl

Total release size: 431.0 kB

Release files / safeuploads-3.0.0.tar.gz

Download URL safeuploads-3.0.0.tar.gz
Size 348.4 kB
Tags Source
SHA-256 checksum
How to use checksums
dbce51a6a17773dc8fb47e5bb4d62a2b4b654e5bd04130edc28e6afe355f1738
BLAKE2b-256 checksum
How to use checksums
0d1b991d953b4b72ca00bced5c3f4b2ae0854d1637568f52ac56a34d0f544cde
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / safeuploads-3.0.0-py3-none-any.whl

Download URL safeuploads-3.0.0-py3-none-any.whl
Size 82.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0997f107435d80b74b75cc27bd001ff1d31ae608ff6ad0d36e853cdc9f2c3d15
BLAKE2b-256 checksum
How to use checksums
dbdda6c32fb7ae90539e2ba110ef1a572ad1e957bf4b458d0c5e30a09a58f2c2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for safeuploads 3.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page