fastapi-secure-errors


Namefastapi-secure-errors JSON
Version 0.1.2 PyPI version JSON
download
home_pageNone
SummarySecurity-first HTTP error handling for FastAPI.
upload_time2025-07-31 21:28:24
maintainerNone
docs_urlNone
authorRyan Mullins
requires_python>=3.9
licenseNone
keywords api error-handling fastapi http security
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # fastapi-secure-errors

**Security-first HTTP error handling for FastAPI.**

[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/fastapi-secure-errors)](https://pypi.org/project/fastapi-secure-errors/)
[![PyPI](https://img.shields.io/pypi/v/fastapi-secure-errors)](https://pypi.org/project/fastapi-secure-errors/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

---

## Overview

`fastapi-secure-errors` is a plug-and-play library for FastAPI that enforces security best practices in your API’s error responses. By default, FastAPI and Starlette can expose detailed error information—such as allowed HTTP methods, validation details, or internal exception traces—that can unintentionally leak information about your application’s structure or logic.

This library provides a unified, security-focused approach to HTTP error handling, ensuring your API only returns generic, minimal error messages and never exposes sensitive details. It's designed for teams and organizations that want to harden their FastAPI applications against information disclosure vulnerabilities, while maintaining a consistent and professional API experience.

---

## Features

* **Removes sensitive headers:** Automatically strips headers like `Allow` from 405 Method Not Allowed responses, preventing enumeration of allowed methods.
* **Generic, minimal error messages:** Provides simplified, non-descriptive error messages for common HTTP status codes (e.g., 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 405 Method Not Allowed, 422 Unprocessable Entity, 500 Internal Server Error).
* **Consistent error response format:** Ensures all handled errors return a predictable JSON structure, typically `{"detail": "Error message"}`.
* **Easy integration:** Secure your entire FastAPI application with a single function call.
* **Customizable:** While providing secure defaults, the underlying exception handlers can be extended or modified for specific needs.
* **Works seamlessly with FastAPI and Starlette.**

---

## Why use `fastapi-secure-errors`?

* **Reduce information leakage:** Prevent attackers from gaining insights into your backend architecture, endpoint existence, or allowed operations.
* **Meet compliance requirements:** Adhere to security best practices and compliance standards (e.g., OWASP Top 10, PCI DSS) that recommend generic error handling.
* **Professional API design:** Offer a clean, consistent, and secure error experience to your API consumers.
* **Save development time:** Avoid writing repetitive custom exception handlers for every potential error scenario across your application.

---

## Installation

Install from PyPI using pip:

```bash
pip install fastapi-secure-errors
```

Or using uv:

```bash
uv add fastapi-secure-errors
```

### Development Installation

For development or to get the latest changes, you can install directly from the repository:

```bash
pip install git+https://github.com/ciscomonkey/fastapi-secure-errors.git
```

Or clone the repository and install locally:

```bash
git clone https://github.com/ciscomonkey/fastapi-secure-errors.git
cd fastapi-secure-errors
pip install -e .
```

---

## Quick Start

To secure your FastAPI application, simply import `setup_secure_error_handlers` and call it with your `FastAPI` app instance:

```python
# examples/demo.py
from fastapi import FastAPI
from fastapi_secure_errors import setup_secure_error_handlers, SecureNotFound, SecureMethodNotAllowed
import os

# Create app with debug mode (can be set via environment or config)
debug_mode = os.getenv("DEBUG", "false").lower() == "true"
app = FastAPI(debug=debug_mode)

# Setup secure error handlers
# Will automatically detect debug mode from app.debug
setup_secure_error_handlers(app)

# Or explicitly control debug mode:
# setup_secure_error_handlers(app, debug=False)  # Force secure mode
# setup_secure_error_handlers(app, debug=True)   # Force debug mode

@app.get("/users/{user_id}")
async def get_user(user_id: int):
    # Use custom exceptions when needed
    if user_id < 1:
        raise SecureNotFound()
    
    return {"user_id": user_id}

@app.get("/protected")
async def protected_route():
    # This will automatically use secure error handling in production
    # but detailed error messages in debug mode
    return {"message": "Protected data"}
```

### Debug Mode vs Production Mode

By default, `fastapi-secure-errors` automatically detects whether your FastAPI app is running in debug mode:

- **Debug Mode (`app.debug=True`)**: Uses FastAPI's default error handlers, providing detailed error information for development
- **Production Mode (`app.debug=False`)**: Uses secure error handlers that provide minimal, generic error messages

This ensures you get helpful debugging information during development while maintaining security in production.

### Running the example:

1. For **development** (with detailed errors): `DEBUG=true fastapi dev examples/demo.py`
2. For **production** (with secure errors): `fastapi dev examples/demo.py` (DEBUG defaults to false)
3. Test with `http` or your browser:
    * `http GET :8000/users/0` -> In debug: detailed info, In production: `{"detail":"Resource not found"}`
    * `http POST :8000/users/1` (Method Not Allowed) -> In debug: detailed info, In production: `{"detail":"Method not allowed"}` (no `Allow` header)
    * `http GET :8000/nonexistent-path` -> In debug: FastAPI's default 404, In production: `{"detail":"Resource not found"}`

---

---

## Configuration

### Debug Mode Detection

The `setup_secure_error_handlers` function accepts an optional `debug` parameter:

```python
from fastapi import FastAPI
from fastapi_secure_errors import setup_secure_error_handlers

app = FastAPI()

# Auto-detect debug mode from app.debug (default behavior)
setup_secure_error_handlers(app)

# Explicitly set debug mode
setup_secure_error_handlers(app, debug=True)   # Force debug mode
setup_secure_error_handlers(app, debug=False)  # Force secure mode
```

**Auto-detection behavior:**
- If `debug=None` (default), the function checks `app.debug`
- If `app.debug=True`, uses FastAPI's default error handlers (detailed errors for development)
- If `app.debug=False`, uses secure error handlers (minimal errors for production)

**Common patterns:**
```python
import os

# Set debug based on environment variable
app = FastAPI(debug=os.getenv("DEBUG", "false").lower() == "true")
setup_secure_error_handlers(app)

# Or control directly via environment
debug_mode = os.getenv("DEBUG", "false").lower() == "true"
setup_secure_error_handlers(app, debug=debug_mode)
```

### CLI Usage with `fastapi dev` and `fastapi run`

**Important Note**: The FastAPI CLI commands (`fastapi dev` and `fastapi run`) do **not** automatically set `app.debug=True/False`. They only control Uvicorn's behavior (like auto-reload). To use debug mode with CLI commands, you need to explicitly control the debug setting:

**Method 1: Using Environment Variables (Recommended)**
```python
import os
from fastapi import FastAPI
from fastapi_secure_errors import setup_secure_error_handlers

# Control debug mode via environment variable
debug_mode = os.getenv("DEBUG", "false").lower() == "true"
app = FastAPI(debug=debug_mode)
setup_secure_error_handlers(app)
```

Then run with:
```bash
# Development with detailed errors
DEBUG=true fastapi dev app.py

# Production with secure errors  
fastapi dev app.py
# or explicitly: DEBUG=false fastapi dev app.py
```

**Method 2: Separate App Configurations**
```python
# dev_app.py
from fastapi import FastAPI
from fastapi_secure_errors import setup_secure_error_handlers

app = FastAPI(debug=True)  # Explicit debug mode
setup_secure_error_handlers(app)

# prod_app.py  
from fastapi import FastAPI
from fastapi_secure_errors import setup_secure_error_handlers

app = FastAPI(debug=False)  # Explicit production mode
setup_secure_error_handlers(app)
```

Then run with:
```bash
fastapi dev dev_app.py    # Uses debug mode
fastapi dev prod_app.py   # Uses production mode
```

---

## Custom Exceptions

The library also provides custom `SecurityHTTPException` classes for convenience, allowing you to raise specific secure errors directly:

```python
from fastapi_secure_errors import SecureMethodNotAllowed, SecureNotFound, SecureForbidden, SecureUnauthorized, SecureInternalServerError

# Example usage:
raise SecureNotFound(detail="The requested resource could not be found.")
raise SecureForbidden() # Uses default detail "Access denied"
```

These custom exceptions are automatically handled by `setup_secure_error_handlers` to ensure they conform to the secure response format.

---

## Development

Contributions are welcome! Please see the [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

---

## License

This project is licensed under the **MIT License**.

```
MIT License

Copyright (c) 2025 Ryan Mullins

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "fastapi-secure-errors",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "api, error-handling, fastapi, http, security",
    "author": "Ryan Mullins",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/60/29/017e676ae1b76e7e9205eb2351262c6f338a08f409b71dafa3d5b0dda82b/fastapi_secure_errors-0.1.2.tar.gz",
    "platform": null,
    "description": "# fastapi-secure-errors\n\n**Security-first HTTP error handling for FastAPI.**\n\n[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/fastapi-secure-errors)](https://pypi.org/project/fastapi-secure-errors/)\n[![PyPI](https://img.shields.io/pypi/v/fastapi-secure-errors)](https://pypi.org/project/fastapi-secure-errors/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\n---\n\n## Overview\n\n`fastapi-secure-errors` is a plug-and-play library for FastAPI that enforces security best practices in your API\u2019s error responses. By default, FastAPI and Starlette can expose detailed error information\u2014such as allowed HTTP methods, validation details, or internal exception traces\u2014that can unintentionally leak information about your application\u2019s structure or logic.\n\nThis library provides a unified, security-focused approach to HTTP error handling, ensuring your API only returns generic, minimal error messages and never exposes sensitive details. It's designed for teams and organizations that want to harden their FastAPI applications against information disclosure vulnerabilities, while maintaining a consistent and professional API experience.\n\n---\n\n## Features\n\n* **Removes sensitive headers:** Automatically strips headers like `Allow` from 405 Method Not Allowed responses, preventing enumeration of allowed methods.\n* **Generic, minimal error messages:** Provides simplified, non-descriptive error messages for common HTTP status codes (e.g., 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 405 Method Not Allowed, 422 Unprocessable Entity, 500 Internal Server Error).\n* **Consistent error response format:** Ensures all handled errors return a predictable JSON structure, typically `{\"detail\": \"Error message\"}`.\n* **Easy integration:** Secure your entire FastAPI application with a single function call.\n* **Customizable:** While providing secure defaults, the underlying exception handlers can be extended or modified for specific needs.\n* **Works seamlessly with FastAPI and Starlette.**\n\n---\n\n## Why use `fastapi-secure-errors`?\n\n* **Reduce information leakage:** Prevent attackers from gaining insights into your backend architecture, endpoint existence, or allowed operations.\n* **Meet compliance requirements:** Adhere to security best practices and compliance standards (e.g., OWASP Top 10, PCI DSS) that recommend generic error handling.\n* **Professional API design:** Offer a clean, consistent, and secure error experience to your API consumers.\n* **Save development time:** Avoid writing repetitive custom exception handlers for every potential error scenario across your application.\n\n---\n\n## Installation\n\nInstall from PyPI using pip:\n\n```bash\npip install fastapi-secure-errors\n```\n\nOr using uv:\n\n```bash\nuv add fastapi-secure-errors\n```\n\n### Development Installation\n\nFor development or to get the latest changes, you can install directly from the repository:\n\n```bash\npip install git+https://github.com/ciscomonkey/fastapi-secure-errors.git\n```\n\nOr clone the repository and install locally:\n\n```bash\ngit clone https://github.com/ciscomonkey/fastapi-secure-errors.git\ncd fastapi-secure-errors\npip install -e .\n```\n\n---\n\n## Quick Start\n\nTo secure your FastAPI application, simply import `setup_secure_error_handlers` and call it with your `FastAPI` app instance:\n\n```python\n# examples/demo.py\nfrom fastapi import FastAPI\nfrom fastapi_secure_errors import setup_secure_error_handlers, SecureNotFound, SecureMethodNotAllowed\nimport os\n\n# Create app with debug mode (can be set via environment or config)\ndebug_mode = os.getenv(\"DEBUG\", \"false\").lower() == \"true\"\napp = FastAPI(debug=debug_mode)\n\n# Setup secure error handlers\n# Will automatically detect debug mode from app.debug\nsetup_secure_error_handlers(app)\n\n# Or explicitly control debug mode:\n# setup_secure_error_handlers(app, debug=False)  # Force secure mode\n# setup_secure_error_handlers(app, debug=True)   # Force debug mode\n\n@app.get(\"/users/{user_id}\")\nasync def get_user(user_id: int):\n    # Use custom exceptions when needed\n    if user_id < 1:\n        raise SecureNotFound()\n    \n    return {\"user_id\": user_id}\n\n@app.get(\"/protected\")\nasync def protected_route():\n    # This will automatically use secure error handling in production\n    # but detailed error messages in debug mode\n    return {\"message\": \"Protected data\"}\n```\n\n### Debug Mode vs Production Mode\n\nBy default, `fastapi-secure-errors` automatically detects whether your FastAPI app is running in debug mode:\n\n- **Debug Mode (`app.debug=True`)**: Uses FastAPI's default error handlers, providing detailed error information for development\n- **Production Mode (`app.debug=False`)**: Uses secure error handlers that provide minimal, generic error messages\n\nThis ensures you get helpful debugging information during development while maintaining security in production.\n\n### Running the example:\n\n1. For **development** (with detailed errors): `DEBUG=true fastapi dev examples/demo.py`\n2. For **production** (with secure errors): `fastapi dev examples/demo.py` (DEBUG defaults to false)\n3. Test with `http` or your browser:\n    * `http GET :8000/users/0` -> In debug: detailed info, In production: `{\"detail\":\"Resource not found\"}`\n    * `http POST :8000/users/1` (Method Not Allowed) -> In debug: detailed info, In production: `{\"detail\":\"Method not allowed\"}` (no `Allow` header)\n    * `http GET :8000/nonexistent-path` -> In debug: FastAPI's default 404, In production: `{\"detail\":\"Resource not found\"}`\n\n---\n\n---\n\n## Configuration\n\n### Debug Mode Detection\n\nThe `setup_secure_error_handlers` function accepts an optional `debug` parameter:\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_secure_errors import setup_secure_error_handlers\n\napp = FastAPI()\n\n# Auto-detect debug mode from app.debug (default behavior)\nsetup_secure_error_handlers(app)\n\n# Explicitly set debug mode\nsetup_secure_error_handlers(app, debug=True)   # Force debug mode\nsetup_secure_error_handlers(app, debug=False)  # Force secure mode\n```\n\n**Auto-detection behavior:**\n- If `debug=None` (default), the function checks `app.debug`\n- If `app.debug=True`, uses FastAPI's default error handlers (detailed errors for development)\n- If `app.debug=False`, uses secure error handlers (minimal errors for production)\n\n**Common patterns:**\n```python\nimport os\n\n# Set debug based on environment variable\napp = FastAPI(debug=os.getenv(\"DEBUG\", \"false\").lower() == \"true\")\nsetup_secure_error_handlers(app)\n\n# Or control directly via environment\ndebug_mode = os.getenv(\"DEBUG\", \"false\").lower() == \"true\"\nsetup_secure_error_handlers(app, debug=debug_mode)\n```\n\n### CLI Usage with `fastapi dev` and `fastapi run`\n\n**Important Note**: The FastAPI CLI commands (`fastapi dev` and `fastapi run`) do **not** automatically set `app.debug=True/False`. They only control Uvicorn's behavior (like auto-reload). To use debug mode with CLI commands, you need to explicitly control the debug setting:\n\n**Method 1: Using Environment Variables (Recommended)**\n```python\nimport os\nfrom fastapi import FastAPI\nfrom fastapi_secure_errors import setup_secure_error_handlers\n\n# Control debug mode via environment variable\ndebug_mode = os.getenv(\"DEBUG\", \"false\").lower() == \"true\"\napp = FastAPI(debug=debug_mode)\nsetup_secure_error_handlers(app)\n```\n\nThen run with:\n```bash\n# Development with detailed errors\nDEBUG=true fastapi dev app.py\n\n# Production with secure errors  \nfastapi dev app.py\n# or explicitly: DEBUG=false fastapi dev app.py\n```\n\n**Method 2: Separate App Configurations**\n```python\n# dev_app.py\nfrom fastapi import FastAPI\nfrom fastapi_secure_errors import setup_secure_error_handlers\n\napp = FastAPI(debug=True)  # Explicit debug mode\nsetup_secure_error_handlers(app)\n\n# prod_app.py  \nfrom fastapi import FastAPI\nfrom fastapi_secure_errors import setup_secure_error_handlers\n\napp = FastAPI(debug=False)  # Explicit production mode\nsetup_secure_error_handlers(app)\n```\n\nThen run with:\n```bash\nfastapi dev dev_app.py    # Uses debug mode\nfastapi dev prod_app.py   # Uses production mode\n```\n\n---\n\n## Custom Exceptions\n\nThe library also provides custom `SecurityHTTPException` classes for convenience, allowing you to raise specific secure errors directly:\n\n```python\nfrom fastapi_secure_errors import SecureMethodNotAllowed, SecureNotFound, SecureForbidden, SecureUnauthorized, SecureInternalServerError\n\n# Example usage:\nraise SecureNotFound(detail=\"The requested resource could not be found.\")\nraise SecureForbidden() # Uses default detail \"Access denied\"\n```\n\nThese custom exceptions are automatically handled by `setup_secure_error_handlers` to ensure they conform to the secure response format.\n\n---\n\n## Development\n\nContributions are welcome! Please see the [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.\n\n---\n\n## License\n\nThis project is licensed under the **MIT License**.\n\n```\nMIT License\n\nCopyright (c) 2025 Ryan Mullins\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n```",
    "bugtrack_url": null,
    "license": null,
    "summary": "Security-first HTTP error handling for FastAPI.",
    "version": "0.1.2",
    "project_urls": {
        "Changelog": "https://github.com/ciscomonkey/fastapi-secure-errors/releases",
        "Homepage": "https://github.com/ciscomonkey/fastapi-secure-errors",
        "Issues": "https://github.com/ciscomonkey/fastapi-secure-errors/issues",
        "Repository": "https://github.com/ciscomonkey/fastapi-secure-errors"
    },
    "split_keywords": [
        "api",
        " error-handling",
        " fastapi",
        " http",
        " security"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "9a9245c43c80f7595dabcb9d1054e49dcfa49f87f32c443bfe11a4bfe5412fe9",
                "md5": "575ffba7ae76c2b2a732e7f60f38df03",
                "sha256": "ee6e028b87741a8e03ef051066ca0f7bdf908944b27f94ff20aa822d4481e5d4"
            },
            "downloads": -1,
            "filename": "fastapi_secure_errors-0.1.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "575ffba7ae76c2b2a732e7f60f38df03",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 8353,
            "upload_time": "2025-07-31T21:28:23",
            "upload_time_iso_8601": "2025-07-31T21:28:23.226132Z",
            "url": "https://files.pythonhosted.org/packages/9a/92/45c43c80f7595dabcb9d1054e49dcfa49f87f32c443bfe11a4bfe5412fe9/fastapi_secure_errors-0.1.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "6029017e676ae1b76e7e9205eb2351262c6f338a08f409b71dafa3d5b0dda82b",
                "md5": "ad9aecc044adb41e2df176403d7b32f9",
                "sha256": "c21b1f25511015c03a3067d388875ef598ff20e2ba5cbb7ea6f687db1f9ccfae"
            },
            "downloads": -1,
            "filename": "fastapi_secure_errors-0.1.2.tar.gz",
            "has_sig": false,
            "md5_digest": "ad9aecc044adb41e2df176403d7b32f9",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 19845,
            "upload_time": "2025-07-31T21:28:24",
            "upload_time_iso_8601": "2025-07-31T21:28:24.335240Z",
            "url": "https://files.pythonhosted.org/packages/60/29/017e676ae1b76e7e9205eb2351262c6f338a08f409b71dafa3d5b0dda82b/fastapi_secure_errors-0.1.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-07-31 21:28:24",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "ciscomonkey",
    "github_project": "fastapi-secure-errors",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "fastapi-secure-errors"
}
        
Elapsed time: 2.67613s