{"id":13468100,"url":"https://github.com/TypeError/secure","last_synced_at":"2025-03-26T03:31:34.703Z","repository":{"id":40738555,"uuid":"159254159","full_name":"TypeError/secure","owner":"TypeError","description":"Lightweight modern Python library to add security headers (CSP, HSTS, etc.) to Django, Flask, FastAPI, and more. Secure defaults or fully customizable.","archived":false,"fork":false,"pushed_at":"2024-10-18T09:29:34.000Z","size":300,"stargazers_count":929,"open_issues_count":5,"forks_count":29,"subscribers_count":15,"default_branch":"main","last_synced_at":"2025-03-19T06:44:46.107Z","etag":null,"topics":["content-security-policy","django","fastapi","flask","headers","headers-security","http-headers","python","python-security","referrer-policy","secure-headers","security","security-headers","strict-transport-security","web-security"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/TypeError.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"docs/security_considerations.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-11-27T00:59:09.000Z","updated_at":"2025-03-18T21:49:03.000Z","dependencies_parsed_at":"2024-05-09T10:56:55.021Z","dependency_job_id":"14174dbe-b32e-4997-8881-4feb47301e91","html_url":"https://github.com/TypeError/secure","commit_stats":{"total_commits":80,"total_committers":10,"mean_commits":8.0,"dds":0.575,"last_synced_commit":"9a96837e365c0dc28eaf76cc35bc9fc8ea74cd68"},"previous_names":["typeerror/secure"],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TypeError%2Fsecure","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TypeError%2Fsecure/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TypeError%2Fsecure/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TypeError%2Fsecure/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/TypeError","download_url":"https://codeload.github.com/TypeError/secure/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245144964,"owners_count":20568056,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["content-security-policy","django","fastapi","flask","headers","headers-security","http-headers","python","python-security","referrer-policy","secure-headers","security","security-headers","strict-transport-security","web-security"],"created_at":"2024-07-31T15:01:05.526Z","updated_at":"2025-03-26T03:31:34.696Z","avatar_url":"https://github.com/TypeError.png","language":"Python","readme":"# secure.py\n\n_A simple, yet powerful way to secure your Python web applications across multiple frameworks._\n\n[![PyPI Version](https://img.shields.io/pypi/v/secure.svg)](https://pypi.org/project/secure/)\n[![Python Versions](https://img.shields.io/pypi/pyversions/secure.svg)](https://pypi.org/project/secure/)\n[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)\n[![Downloads](https://pepy.tech/badge/secure)](https://pepy.tech/project/secure)\n[![License](https://img.shields.io/pypi/l/secure.svg)](https://github.com/TypeError/secure/blob/main/LICENSE)\n[![GitHub Stars](https://img.shields.io/github/stars/TypeError/secure.svg)](https://github.com/TypeError/secure/stargazers)\n\n## **Introduction**\n\nIn today's web landscape, security is paramount. **secure.py** is a lightweight Python library designed to effortlessly add **security headers** to your web applications, protecting them from common vulnerabilities. Whether you're using **Django**, **Flask**, **FastAPI**, or any other popular framework, `secure.py` provides a unified API to enhance your application's security posture.\n\n---\n\n## **Why Use secure.py?**\n\n- 🔒 **Apply Essential Security Headers**: Implement headers like CSP, HSTS, and more with minimal effort.\n- 🛠️ **Consistent API Across Frameworks**: A unified approach for different web frameworks.\n- ⚙️ **Customizable with Secure Defaults**: Start secure out-of-the-box and customize as needed.\n- 🚀 **Easy Integration**: Compatible with Python's most-used frameworks.\n- 🐍 **Modern Pythonic Design**: Leverages Python 3.10+ features for cleaner and more efficient code.\n\n---\n\n## **Supported Frameworks**\n\n**secure.py** supports the following Python web frameworks:\n\n| Framework                                             | Documentation                                                                                    |\n| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------ |\n| [aiohttp](https://docs.aiohttp.org)                   | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#aiohttp)    |\n| [Bottle](https://bottlepy.org)                        | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#bottle)     |\n| [CherryPy](https://cherrypy.dev/)                     | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#cherrypy)   |\n| [Django](https://www.djangoproject.com)               | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#django)     |\n| [Falcon](https://falconframework.org)                 | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#falcon)     |\n| [FastAPI](https://fastapi.tiangolo.com)               | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#fastapi)    |\n| [Flask](http://flask.pocoo.org)                       | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#flask)      |\n| [Masonite](https://docs.masoniteproject.com/)         | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#masonite)   |\n| [Morepath](https://morepath.readthedocs.io)           | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#morepath)   |\n| [Pyramid](https://trypyramid.com)                     | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#pyramid)    |\n| [Quart](https://quart.palletsprojects.com/en/latest/) | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#quart)      |\n| [Responder](https://responder.kennethreitz.org/)      | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#responder)  |\n| [Sanic](https://sanicframework.org)                   | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#sanic)      |\n| [Starlette](https://www.starlette.io/)                | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#starlette)  |\n| [Tornado](https://www.tornadoweb.org/)                | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#tornado)    |\n| [TurboGears](https://turbogears.org/)                 | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#turbogears) |\n\n---\n\n## **Features**\n\n- 🔒 **Secure Headers**: Automatically apply headers like `Strict-Transport-Security`, `X-Frame-Options`, and more.\n- 🛠️ **Customizable Policies**: Flexibly build your own security policies using method chaining.\n- 🌐 **Framework Integration**: Compatible with various frameworks, ensuring cross-compatibility.\n- 🚀 **No External Dependencies**: Lightweight and easy to include in any project.\n- 🧩 **Easy to Use**: Integrate security headers in just a few lines of code.\n- ⚡ **Asynchronous Support**: Async support for modern frameworks like **FastAPI** and **Starlette**.\n- 📝 **Enhanced Type Hinting**: Complete type annotations for better developer experience.\n- 📚 **Attribution to Trusted Sources**: Implements recommendations from MDN and OWASP.\n\n---\n\n## **Requirements**\n\n- **Python 3.10** or higher\n\n  This library leverages modern Python features introduced in Python 3.10 and 3.11, such as:\n\n  - **Union Type Operator (`|`)**: Simplifies type annotations.\n  - **Structural Pattern Matching (`match` statement)**: Enhances control flow.\n  - **Improved Type Hinting and Annotations**: Provides better code clarity and maintenance.\n  - **`cached_property`**: Optimize memory usage and performance.\n\n  **Note:** If you're using an older version of Python (3.6 to 3.9), please use version **0.3.0** of this library, which maintains compatibility with those versions.\n\n- **Dependencies**\n\n  This library has no external dependencies outside of the Python Standard Library.\n\n---\n\n## **Installation**\n\nYou can install secure.py using pip, pipenv, or poetry:\n\n**pip**:\n\n```bash\npip install secure\n```\n\n**Pipenv**:\n\n```bash\npipenv install secure\n```\n\n**Poetry**:\n\n```bash\npoetry add secure\n```\n\n---\n\n## **Getting Started**\n\nOnce installed, you can quickly integrate `secure.py` into your project:\n\n### Synchronous Usage\n\n```python\nimport secure\n\n# Initialize secure headers with default settings\nsecure_headers = secure.Secure.with_default_headers()\n\n# Apply the headers to your framework response object\nsecure_headers.set_headers(response)\n```\n\n### Asynchronous Usage\n\nFor frameworks like **FastAPI** and **Starlette** that support asynchronous operations, use the async method:\n\n```python\nimport secure\n\n# Initialize secure headers with default settings\nsecure_headers = secure.Secure.with_default_headers()\n\n# Apply the headers asynchronously to your framework response object\nawait secure_headers.set_headers_async(response)\n```\n\n### **Example Usage**\n\n```python\nimport secure\n\n# Create a Secure instance with default headers\nsecure_headers = secure.Secure.with_default_headers()\n\n# Apply default secure headers to a response object\nsecure_headers.set_headers(response)\n```\n\n---\n\n## **Default Secure Headers**\n\nBy default, `secure.py` applies the following headers when using `with_default_headers()`:\n\n```http\nCache-Control: no-store\nCross-Origin-Opener-Policy: same-origin\nContent-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'; object-src 'none'\nStrict-Transport-Security: max-age=31536000\nPermissions-Policy: geolocation=(), microphone=(), camera=()\nReferrer-Policy: strict-origin-when-cross-origin\nServer:\nX-Content-Type-Options: nosniff\n```\n\n---\n\n## **Policy Builders**\n\n`secure.py` allows you to customize headers such as **Content-Security-Policy** and **Permissions-Policy** with ease:\n\n### **Content-Security-Policy Example**\n\n```python\nimport secure\n\n# Build a custom CSP policy\ncsp = (\n    secure.ContentSecurityPolicy()\n    .default_src(\"'self'\")\n    .script_src(\"'self'\", \"cdn.example.com\")\n    .style_src(\"'unsafe-inline'\")\n    .img_src(\"'self'\", \"images.example.com\")\n    .connect_src(\"'self'\", \"api.example.com\")\n)\n\n# Apply it to secure headers\nsecure_headers = secure.Secure(csp=csp)\n```\n\n**Resulting HTTP headers:**\n\n```http\nContent-Security-Policy: default-src 'self'; script-src 'self' cdn.example.com; style-src 'unsafe-inline'; img-src 'self' images.example.com; connect-src 'self' api.example.com\n```\n\n### **Permissions-Policy Example**\n\n```python\nimport secure\n\n# Build a custom Permissions Policy\npermissions = (\n    secure.PermissionsPolicy()\n    .geolocation(\"'self'\")\n    .camera(\"'none'\")\n    .microphone(\"'none'\")\n)\n\n# Apply it to secure headers\nsecure_headers = secure.Secure(permissions=permissions)\n```\n\n**Resulting HTTP headers:**\n\n```http\nPermissions-Policy: geolocation=('self'), camera=('none'), microphone=('none')\n```\n\n---\n\n## **Framework Examples**\n\n### **FastAPI**\n\n```python\nfrom fastapi import FastAPI\n\nfrom secure import Secure\n\napp = FastAPI()\nsecure_headers = Secure.with_default_headers()\n\n\n@app.middleware(\"http\")\nasync def add_security_headers(request, call_next):\n    response = await call_next(request)\n    await secure_headers.set_headers_async(response)\n    return response\n\n\n@app.get(\"/\")\ndef read_root():\n    return {\"Hello\": \"World\"}\n```\n\n### Flask\n\n```python\nfrom flask import Flask, Response\n\nfrom secure import Secure\n\napp = Flask(__name__)\nsecure_headers = Secure.with_default_headers()\n\n\n@app.after_request\ndef add_security_headers(response: Response):\n    secure_headers.set_headers(response)\n    return response\n\n\n@app.route(\"/\")\ndef home():\n    return \"Hello, world\"\n\n\nif __name__ == \"__main__\":\n    app.run()\n```\n\n---\n\n## **Documentation**\n\nFor more details, including advanced configurations and integration examples, please visit the **[full documentation](https://github.com/TypeError/secure/tree/main/docs)**.\n\n---\n\n## **Attribution**\n\nThis library implements security recommendations from trusted sources:\n\n- [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) (licensed under [CC-BY-SA 2.5](https://creativecommons.org/licenses/by-sa/2.5/))\n- [OWASP Secure Headers Project](https://owasp.org/www-project-secure-headers/) (licensed under [CC-BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/))\n\nWe have included attribution comments in the source code where appropriate.\n\n---\n\n## **Resources**\n\n- [OWASP - Secure Headers Project](https://owasp.org/www-project-secure-headers/)\n- [Mozilla Web Security Guidelines](https://infosec.mozilla.org/guidelines/web_security)\n- [MDN Web Docs: Security Headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers#security)\n- [web.dev: Security Best Practices](https://web.dev)\n- [The World Wide Web Consortium (W3C)](https://www.w3.org)\n\n---\n\n### **License**\n\nThis project is licensed under the terms of the **[MIT License](https://opensource.org/licenses/MIT)**.\n\n---\n\n## **Contributing**\n\nContributions are welcome! If you'd like to contribute to `secure.py`, please feel free to open an issue or submit a pull request on **[GitHub](https://github.com/TypeError/secure)**.\n\n---\n\n## **Changelog**\n\nFor a detailed list of changes, please refer to the **[CHANGELOG](https://github.com/TypeError/secure/blob/main/CHANGELOG.md)**.\n\n---\n\n## **Acknowledgements**\n\nWe would like to thank the contributors of MDN Web Docs and OWASP Secure Headers Project for their invaluable resources and guidelines that help make the web a safer place.\n","funding_links":[],"categories":["Python"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FTypeError%2Fsecure","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FTypeError%2Fsecure","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FTypeError%2Fsecure/lists"}