starlette-securecookies


Namestarlette-securecookies JSON
Version 1.1.1 PyPI version JSON
download
home_pagehttps://securecookies.thearchitector.dev
SummarySecure cookie middleware for Starlette applications.
upload_time2023-07-10 05:11:04
maintainer
docs_urlNone
author
requires_python~=3.7
licenseBSD 3-Clause License Copyright (c) 2022, Elias Gabriel All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
keywords starlette fastapi middleware encryption cookies
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # starlette-securecookies

![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/thearchitector/starlette-securecookies/CI.yaml?label=tests&style=flat-square)
![PyPI - Downloads](https://img.shields.io/pypi/dw/starlette-securecookies?style=flat-square)
![GitHub](https://img.shields.io/github/license/thearchitector/starlette-securecookies?style=flat-square)
[![Buy a tree](https://img.shields.io/badge/Treeware-%F0%9F%8C%B3-lightgreen?style=flat-square)](https://ecologi.com/eliasgabriel?r=6128126916bfab8bd051026c)

Customizable middleware for adding automatic cookie encryption and decryption to Starlette applications.

Tested support on Python 3.7, 3.8, 3.9, and 3.10, 3.11 on macOS, Windows, and Linux.

## How it works?

```mermaid
sequenceDiagram
    Browser->>+Middleware: Encrypted 'Cookie' headers
    Middleware->>+Application: Decrypted cookies
    Application->>-Middleware: Plaintext cookies
    Middleware->>-Browser: Encrypted 'Set-Cookie' headers
    Note over Application: *The Application may be your service<br />or any additional middleware.
```

For any incoming cookies:

1. Requests sent from the client's browser to your application are intercepted by `SecureCookiesMiddleware`.
2. All `Cookie` headers are filtered and parsed. Only cookies in the `included_cookies` and `excluded_cookies` parameters are parsed. All cookies are included by default.
3. The cookies are decrypted. If a cookie cannot be decrypted, or is otherwise invalid, it is discarded by default (`discard_invalid=True`).
4. Any included and valid encrypted cookies in the ASGI request scope are replaced by the decrypted ones.
5. The request scope is passed to any future middleware, and eventually your application. Cookies can be read normally anywhere downstream.

For any outgoing cookies:

7. Your application sets cookies with `response.set_cookie`, or by any other means of creating `Set-Cookie` headers.
8. Other middleware run and add additional cookies, like [SessionMiddleware](https://www.starlette.io/middleware/#sessionmiddleware).
9. All responses returned by your application are intercepted by `SecureCookiesMiddleware`.
10. Cookies in the `included_cookies` and not in the `excluded_cookies` parameters are re-encrypted, and their attributes (like `"SameSite"` and `"HttpOnly"`) are overridden by any parameters set in `SecureCookiesMiddleware`.
11. The cookies in the response are replaced by the re-encrypted cookies, and the response is eventually propagated to the client's browser.

## Installation

```sh
$ pdm add starlette-securecookies
# or
$ python -m pip install --user starlette-securecookies
```

## Usage

This is a Starlette-based middleware, so it can be used in any Starlette application or Starlette-based framework (like [FastAPI](https://fastapi.tiangolo.com/advanced/middleware/)).

For example,

```python
from starlette.applications import Starlette
from starlette.middleware import Middleware

from securecookies import SecureCookiesMiddleware

middleware = [
    Middleware(
        SecureCookiesMiddleware, secrets=["SUPER SECRET SECRET"],
        # your other middleware
    )
]

app = Starlette(routes=..., middleware=middleware)
```

Note that if you're using another middleware that injects cookies into the response (such as [SessionMiddleware](https://www.starlette.io/middleware/#sessionmiddleware)), you have to make sure `SecureCookiesMiddleware` executes _after_ it so the cookie is present at encryption-time. Counter intuitively, in practice this means ensuring `SecureCookiesMiddleware` is _first_ in the list of middleware.

### Extras

`starlette-securecookies` provides some extras that introduce or patch secure cookie functionality into existing tools. They all reside in the `securecookies.extras` module. Currently there is only one, but more are welcome by recommendation or Pull Request!

- **`csrf.SecureCSRFMiddleware`**: Adds compatibility to the CSRF middleware provided by [starlette_csrf](https://github.com/frankie567/starlette-csrf). To use it, simply add it to your list of middleware (keep in mind the ordering). If you don't want to specify `starlette_csrf` as a direct dependency, you can also install it through the `[csrf]` package extra.

## License

This software is licensed under the [BSD 3-Clause License](LICENSE).

This package is Treeware. If you use it in production, consider buying the world a tree to thank me for my work. By contributing to my forest, you’ll be creating employment for local families and restoring wildlife habitats.

            

Raw data

            {
    "_id": null,
    "home_page": "https://securecookies.thearchitector.dev",
    "name": "starlette-securecookies",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "~=3.7",
    "maintainer_email": "",
    "keywords": "starlette fastapi middleware encryption cookies",
    "author": "",
    "author_email": "Elias Gabriel <me@eliasfgabriel.com>",
    "download_url": "https://files.pythonhosted.org/packages/63/e4/2a9c4e928c8eb629876c13da0f768860dea7450f95302dc9af3fb6ccead2/starlette_securecookies-1.1.1.tar.gz",
    "platform": null,
    "description": "# starlette-securecookies\n\n![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/thearchitector/starlette-securecookies/CI.yaml?label=tests&style=flat-square)\n![PyPI - Downloads](https://img.shields.io/pypi/dw/starlette-securecookies?style=flat-square)\n![GitHub](https://img.shields.io/github/license/thearchitector/starlette-securecookies?style=flat-square)\n[![Buy a tree](https://img.shields.io/badge/Treeware-%F0%9F%8C%B3-lightgreen?style=flat-square)](https://ecologi.com/eliasgabriel?r=6128126916bfab8bd051026c)\n\nCustomizable middleware for adding automatic cookie encryption and decryption to Starlette applications.\n\nTested support on Python 3.7, 3.8, 3.9, and 3.10, 3.11 on macOS, Windows, and Linux.\n\n## How it works?\n\n```mermaid\nsequenceDiagram\n    Browser->>+Middleware: Encrypted 'Cookie' headers\n    Middleware->>+Application: Decrypted cookies\n    Application->>-Middleware: Plaintext cookies\n    Middleware->>-Browser: Encrypted 'Set-Cookie' headers\n    Note over Application: *The Application may be your service<br />or any additional middleware.\n```\n\nFor any incoming cookies:\n\n1. Requests sent from the client's browser to your application are intercepted by `SecureCookiesMiddleware`.\n2. All `Cookie` headers are filtered and parsed. Only cookies in the `included_cookies` and `excluded_cookies` parameters are parsed. All cookies are included by default.\n3. The cookies are decrypted. If a cookie cannot be decrypted, or is otherwise invalid, it is discarded by default (`discard_invalid=True`).\n4. Any included and valid encrypted cookies in the ASGI request scope are replaced by the decrypted ones.\n5. The request scope is passed to any future middleware, and eventually your application. Cookies can be read normally anywhere downstream.\n\nFor any outgoing cookies:\n\n7. Your application sets cookies with `response.set_cookie`, or by any other means of creating `Set-Cookie` headers.\n8. Other middleware run and add additional cookies, like [SessionMiddleware](https://www.starlette.io/middleware/#sessionmiddleware).\n9. All responses returned by your application are intercepted by `SecureCookiesMiddleware`.\n10. Cookies in the `included_cookies` and not in the `excluded_cookies` parameters are re-encrypted, and their attributes (like `\"SameSite\"` and `\"HttpOnly\"`) are overridden by any parameters set in `SecureCookiesMiddleware`.\n11. The cookies in the response are replaced by the re-encrypted cookies, and the response is eventually propagated to the client's browser.\n\n## Installation\n\n```sh\n$ pdm add starlette-securecookies\n# or\n$ python -m pip install --user starlette-securecookies\n```\n\n## Usage\n\nThis is a Starlette-based middleware, so it can be used in any Starlette application or Starlette-based framework (like [FastAPI](https://fastapi.tiangolo.com/advanced/middleware/)).\n\nFor example,\n\n```python\nfrom starlette.applications import Starlette\nfrom starlette.middleware import Middleware\n\nfrom securecookies import SecureCookiesMiddleware\n\nmiddleware = [\n    Middleware(\n        SecureCookiesMiddleware, secrets=[\"SUPER SECRET SECRET\"],\n        # your other middleware\n    )\n]\n\napp = Starlette(routes=..., middleware=middleware)\n```\n\nNote that if you're using another middleware that injects cookies into the response (such as [SessionMiddleware](https://www.starlette.io/middleware/#sessionmiddleware)), you have to make sure `SecureCookiesMiddleware` executes _after_ it so the cookie is present at encryption-time. Counter intuitively, in practice this means ensuring `SecureCookiesMiddleware` is _first_ in the list of middleware.\n\n### Extras\n\n`starlette-securecookies` provides some extras that introduce or patch secure cookie functionality into existing tools. They all reside in the `securecookies.extras` module. Currently there is only one, but more are welcome by recommendation or Pull Request!\n\n- **`csrf.SecureCSRFMiddleware`**: Adds compatibility to the CSRF middleware provided by [starlette_csrf](https://github.com/frankie567/starlette-csrf). To use it, simply add it to your list of middleware (keep in mind the ordering). If you don't want to specify `starlette_csrf` as a direct dependency, you can also install it through the `[csrf]` package extra.\n\n## License\n\nThis software is licensed under the [BSD 3-Clause License](LICENSE).\n\nThis package is Treeware. If you use it in production, consider buying the world a tree to thank me for my work. By contributing to my forest, you\u2019ll be creating employment for local families and restoring wildlife habitats.\n",
    "bugtrack_url": null,
    "license": "BSD 3-Clause License\n        \n        Copyright (c) 2022, Elias Gabriel\n        All rights reserved.\n        \n        Redistribution and use in source and binary forms, with or without\n        modification, are permitted provided that the following conditions are met:\n        \n        1. Redistributions of source code must retain the above copyright notice, this\n           list of conditions and the following disclaimer.\n        \n        2. Redistributions in binary form must reproduce the above copyright notice,\n           this list of conditions and the following disclaimer in the documentation\n           and/or other materials provided with the distribution.\n        \n        3. Neither the name of the copyright holder nor the names of its\n           contributors may be used to endorse or promote products derived from\n           this software without specific prior written permission.\n        \n        THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n        AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n        IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n        DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n        FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n        DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n        SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n        CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n        OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n        OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
    "summary": "Secure cookie middleware for Starlette applications.",
    "version": "1.1.1",
    "project_urls": {
        "Changelog": "https://github.com/thearchitector/starlette-securecookies/blob/main/CHANGELOG.md",
        "Documentation": "https://securecookies.thearchitector.dev",
        "Homepage": "https://securecookies.thearchitector.dev",
        "Repository": "https://github.com/thearchitector/starlette-securecookies"
    },
    "split_keywords": [
        "starlette",
        "fastapi",
        "middleware",
        "encryption",
        "cookies"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "d9818e1e7bfff99f5ddea7a25333e5ba5f8e21355e985b6899786c260ef6c633",
                "md5": "30c126ab2c508657f37290efe899ca97",
                "sha256": "0f54615ee2f01649729442bb06cd4831b377fd0617b8f734bba9e5893a24e2b0"
            },
            "downloads": -1,
            "filename": "starlette_securecookies-1.1.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "30c126ab2c508657f37290efe899ca97",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "~=3.7",
            "size": 10172,
            "upload_time": "2023-07-10T05:11:02",
            "upload_time_iso_8601": "2023-07-10T05:11:02.923102Z",
            "url": "https://files.pythonhosted.org/packages/d9/81/8e1e7bfff99f5ddea7a25333e5ba5f8e21355e985b6899786c260ef6c633/starlette_securecookies-1.1.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "63e42a9c4e928c8eb629876c13da0f768860dea7450f95302dc9af3fb6ccead2",
                "md5": "edbcca4a511fdbdf92e4e6ad9062d65a",
                "sha256": "28d3a888a02f02abb8a25674254456cda5028b45c68c1e4697fcefe7461a3642"
            },
            "downloads": -1,
            "filename": "starlette_securecookies-1.1.1.tar.gz",
            "has_sig": false,
            "md5_digest": "edbcca4a511fdbdf92e4e6ad9062d65a",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "~=3.7",
            "size": 12196,
            "upload_time": "2023-07-10T05:11:04",
            "upload_time_iso_8601": "2023-07-10T05:11:04.278963Z",
            "url": "https://files.pythonhosted.org/packages/63/e4/2a9c4e928c8eb629876c13da0f768860dea7450f95302dc9af3fb6ccead2/starlette_securecookies-1.1.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-07-10 05:11:04",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "thearchitector",
    "github_project": "starlette-securecookies",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "starlette-securecookies"
}
        
Elapsed time: 0.11996s