aiohttp-csrf2


Nameaiohttp-csrf2 JSON
Version 1.0.1 PyPI version JSON
download
home_pageNone
SummaryCross-site request forgery (CSRF) protection for aiohttp-server
upload_time2024-09-13 09:20:33
maintainerNone
docs_urlNone
authorTensorTom
requires_python>=3.9
licenseThe MIT License Copyright (c) Ocean S.A. https://ocean.io/ 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.
keywords asyncio aiohttp csrf webserver
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            aiohttp_csrf
=============

The library provides Cross-server request forgery (csrf/xsrf) protection for [aiohttp.web](https://docs.aiohttp.org/en/latest/web.html).

This is a fork of https://github.com/bitnom/aiohttp-csrf that adds modern python type annotations, switches to aiohttp `AppKey` tags, and fixes the historic test suite. 

**New in Version 1.0.0**

* Added type hinting throughout.
* The `aiohttp_csrf.setup()` and `@csrf_protect` decorators now take separate optional keyword arguments `exception=...` and `error_renderer=...` to allow customisation of csrf failures. Previously this was an overloaded single argument `error_renderer`.
* upgraded dependancy on `blake3`, `aiohttp` and `aiohttp-session`.
* dropped support for Python 3.8

**Version in 0.1.0**

* uses Blake3 hashes are used by default. This means you must pass `secret_phrase` to whichever storage backend is being used to generate tokens, e.g. `aiohttp_csrf.storage.SessionStorage`


Basic usage
-----------

The library allows you to implement csrf (xsrf) protection for requests

Basic usage example:

```python
import aiohttp_csrf
from aiohttp import web

FORM_FIELD_NAME = '_csrf_token'
COOKIE_NAME = 'csrf_token'


def make_app():
    csrf_policy = aiohttp_csrf.policy.FormPolicy(FORM_FIELD_NAME)

    csrf_storage = aiohttp_csrf.storage.CookieStorage(COOKIE_NAME)

    app = web.Application()

    aiohttp_csrf.setup(app, policy=csrf_policy, storage=csrf_storage)

    app.middlewares.append(aiohttp_csrf.csrf_middleware)

    async def handler_get_form_with_token(request):
        token = await aiohttp_csrf.generate_token(request)


        body = '''
            <html>
                <head><title>Form with csrf protection</title></head>
                <body>
                    <form method="POST" action="/">
                        <input type="hidden" name="{field_name}" value="{token}" />
                        <input type="text" name="name" />
                        <input type="submit" value="Say hello">
                    </form>
                </body>
            </html>
        '''  # noqa

        body = body.format(field_name=FORM_FIELD_NAME, token=token)

        return web.Response(
            body=body.encode('utf-8'),
            content_type='text/html',
        )

    async def handler_post_check(request):
        post = await request.post()

        body = 'Hello, {name}'.format(name=post['name'])

        return web.Response(
            body=body.encode('utf-8'),
            content_type='text/html',
        )

    app.router.add_route(
        'GET',
        '/',
        handler_get_form_with_token,
    )

    app.router.add_route(
        'POST',
        '/',
        handler_post_check,
    )

    return app


web.run_app(make_app())
```

### Initialize

First of all, you need to initialize `aiohttp_csrf` in your application:

```python
app = web.Application()

csrf_policy = aiohttp_csrf.policy.FormPolicy(FORM_FIELD_NAME)

csrf_storage = aiohttp_csrf.storage.CookieStorage(COOKIE_NAME)

aiohttp_csrf.setup(app, policy=csrf_policy, storage=csrf_storage)
```

### Middleware and decorators

After initialize you can use `@aiohttp_csrf.csrf_protect` for handlers, that you want to protect. Or you can
initialize `aiohttp_csrf.csrf_middleware` and do not disturb about using
decorator ([full middleware example here](demo/middleware.py)):

```python
# ...
app.middlewares.append(aiohttp_csrf.csrf_middleware)
# ...
```

In this case all your handlers will be protected.

**Note:** we strongly recommend to use `aiohttp_csrf.csrf_middleware` and `@aiohttp_csrf.csrf_exempt` instead of
manually managing with `@aiohttp_csrf.csrf_protect`. But if you prefer to use `@aiohttp_csrf.csrf_protect`, don't forget
to use `@aiohttp_csrf.csrf_protect` for both methods: GET and
POST ([manual protection example](demo/manual_protection.py))

If you want to use middleware, but need handlers without protection, you can use `@aiohttp_csrf.csrf_exempt`. Mark you
handler with this decorator and this handler will not check the token:

```python
@aiohttp_csrf.csrf_exempt
async def handler_post_not_check(request):
    ...
```

### Generate token

For generate token you need to call `aiohttp_csrf.generate_token` in your handler:

```python
@aiohttp_csrf.csrf_protect
async def handler_get(request):
    token = await aiohttp_csrf.generate_token(request)
    ...
```

Advanced usage
--------------

### Policies

You can use different policies for check tokens. Library provides 3 types of policy:

- **FormPolicy**. This policy will search token in the body of your POST request (Usually use for forms) or as a GET
  variable of the same name. You need to specify name of field that will be checked.
- **HeaderPolicy**. This policy will search token in headers of your POST request (Usually use for AJAX requests). You
  need to specify name of header that will be checked.
- **FormAndHeaderPolicy**. This policy combines behavior of **FormPolicy** and **HeaderPolicy**.

You can implement your custom policies if needed. But make sure that your custom policy
implements `aiohttp_csrf.policy.AbstractPolicy` interface.

### Storages

You can use different types of storages for storing token. Library provides 2 types of storage:

- **CookieStorage**. Your token will be stored in cookie variable. You need to specify cookie name.
- **SessionStorage**. Your token will be stored in session. You need to specify session variable name.

**Important:** If you want to use session storage, you need setup aiohttp\_session in your
application ([session storage example](demo/session_storage.py#L22))

You can implement your custom storages if needed. But make sure that your custom storage
implements `aiohttp_csrf.storage.AbstractStorage` interface.

### Token generators

You can use different token generator in your application. By default storages
using `aiohttp_csrf.token_generator.SimpleTokenGenerator`

But if you need more secure token generator - you can use `aiohttp_csrf.token_generator.HashedTokenGenerator`

And you can implement your custom token generators if needed. But make sure that your custom token generator
implements `aiohttp_csrf.token_generator.AbstractTokenGenerator` interface.

### Invalid token behavior

By default, if token is invalid, `aiohttp_csrf` will raise `aiohttp.web.HTTPForbidden` exception.

You have ability to specify your custom error handler. It can be:

- **callable instance. Input parameter - aiohttp request.**

```python
def custom_error_handler(request):
    # do something
    return aiohttp.web.Response(status=403)

# or

async def custom_async_error_handler(request):
    # await do something
    return aiohttp.web.Response(status=403)
```

It will be called instead of protected handler.

- **sub class of Exception**. In this case this Exception will be raised.

```python
class CustomException(Exception):
    pass
```

You can specify custom error handler globally, when initialize `aiohttp_csrf` in your application:

```python
...
class CustomException(Exception):
    pass

...
aiohttp_csrf.setup(app, policy=csrf_policy, storage=csrf_storage, error_renderer=CustomException)
...
```

In this case custom error handler will be applied to all protected handlers.

Or you can specify custom error handler locally, for specific handler:

```python
...
class CustomException(Exception):
    pass

...
@aiohttp_csrf.csrf_protect(error_renderer=CustomException)
def handler_with_custom_csrf_error(request):
    ...
```

In this case custom error handler will be applied to this handler only. For all other handlers will be applied global
error handler.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "aiohttp-csrf2",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "asyncio, aiohttp, csrf, webserver",
    "author": "TensorTom",
    "author_email": "shuckc <chris@shucksmith.co.uk>",
    "download_url": "https://files.pythonhosted.org/packages/de/cb/9320617254cc0c59dbe292c675f7d5150d41a895780caa829d8f000127c3/aiohttp_csrf2-1.0.1.tar.gz",
    "platform": null,
    "description": "aiohttp_csrf\n=============\n\nThe library provides Cross-server request forgery (csrf/xsrf) protection for [aiohttp.web](https://docs.aiohttp.org/en/latest/web.html).\n\nThis is a fork of https://github.com/bitnom/aiohttp-csrf that adds modern python type annotations, switches to aiohttp `AppKey` tags, and fixes the historic test suite. \n\n**New in Version 1.0.0**\n\n* Added type hinting throughout.\n* The `aiohttp_csrf.setup()` and `@csrf_protect` decorators now take separate optional keyword arguments `exception=...` and `error_renderer=...` to allow customisation of csrf failures. Previously this was an overloaded single argument `error_renderer`.\n* upgraded dependancy on `blake3`, `aiohttp` and `aiohttp-session`.\n* dropped support for Python 3.8\n\n**Version in 0.1.0**\n\n* uses Blake3 hashes are used by default. This means you must pass `secret_phrase` to whichever storage backend is being used to generate tokens, e.g. `aiohttp_csrf.storage.SessionStorage`\n\n\nBasic usage\n-----------\n\nThe library allows you to implement csrf (xsrf) protection for requests\n\nBasic usage example:\n\n```python\nimport aiohttp_csrf\nfrom aiohttp import web\n\nFORM_FIELD_NAME = '_csrf_token'\nCOOKIE_NAME = 'csrf_token'\n\n\ndef make_app():\n    csrf_policy = aiohttp_csrf.policy.FormPolicy(FORM_FIELD_NAME)\n\n    csrf_storage = aiohttp_csrf.storage.CookieStorage(COOKIE_NAME)\n\n    app = web.Application()\n\n    aiohttp_csrf.setup(app, policy=csrf_policy, storage=csrf_storage)\n\n    app.middlewares.append(aiohttp_csrf.csrf_middleware)\n\n    async def handler_get_form_with_token(request):\n        token = await aiohttp_csrf.generate_token(request)\n\n\n        body = '''\n            <html>\n                <head><title>Form with csrf protection</title></head>\n                <body>\n                    <form method=\"POST\" action=\"/\">\n                        <input type=\"hidden\" name=\"{field_name}\" value=\"{token}\" />\n                        <input type=\"text\" name=\"name\" />\n                        <input type=\"submit\" value=\"Say hello\">\n                    </form>\n                </body>\n            </html>\n        '''  # noqa\n\n        body = body.format(field_name=FORM_FIELD_NAME, token=token)\n\n        return web.Response(\n            body=body.encode('utf-8'),\n            content_type='text/html',\n        )\n\n    async def handler_post_check(request):\n        post = await request.post()\n\n        body = 'Hello, {name}'.format(name=post['name'])\n\n        return web.Response(\n            body=body.encode('utf-8'),\n            content_type='text/html',\n        )\n\n    app.router.add_route(\n        'GET',\n        '/',\n        handler_get_form_with_token,\n    )\n\n    app.router.add_route(\n        'POST',\n        '/',\n        handler_post_check,\n    )\n\n    return app\n\n\nweb.run_app(make_app())\n```\n\n### Initialize\n\nFirst of all, you need to initialize `aiohttp_csrf` in your application:\n\n```python\napp = web.Application()\n\ncsrf_policy = aiohttp_csrf.policy.FormPolicy(FORM_FIELD_NAME)\n\ncsrf_storage = aiohttp_csrf.storage.CookieStorage(COOKIE_NAME)\n\naiohttp_csrf.setup(app, policy=csrf_policy, storage=csrf_storage)\n```\n\n### Middleware and decorators\n\nAfter initialize you can use `@aiohttp_csrf.csrf_protect` for handlers, that you want to protect. Or you can\ninitialize `aiohttp_csrf.csrf_middleware` and do not disturb about using\ndecorator ([full middleware example here](demo/middleware.py)):\n\n```python\n# ...\napp.middlewares.append(aiohttp_csrf.csrf_middleware)\n# ...\n```\n\nIn this case all your handlers will be protected.\n\n**Note:** we strongly recommend to use `aiohttp_csrf.csrf_middleware` and `@aiohttp_csrf.csrf_exempt` instead of\nmanually managing with `@aiohttp_csrf.csrf_protect`. But if you prefer to use `@aiohttp_csrf.csrf_protect`, don't forget\nto use `@aiohttp_csrf.csrf_protect` for both methods: GET and\nPOST ([manual protection example](demo/manual_protection.py))\n\nIf you want to use middleware, but need handlers without protection, you can use `@aiohttp_csrf.csrf_exempt`. Mark you\nhandler with this decorator and this handler will not check the token:\n\n```python\n@aiohttp_csrf.csrf_exempt\nasync def handler_post_not_check(request):\n    ...\n```\n\n### Generate token\n\nFor generate token you need to call `aiohttp_csrf.generate_token` in your handler:\n\n```python\n@aiohttp_csrf.csrf_protect\nasync def handler_get(request):\n    token = await aiohttp_csrf.generate_token(request)\n    ...\n```\n\nAdvanced usage\n--------------\n\n### Policies\n\nYou can use different policies for check tokens. Library provides 3 types of policy:\n\n- **FormPolicy**. This policy will search token in the body of your POST request (Usually use for forms) or as a GET\n  variable of the same name. You need to specify name of field that will be checked.\n- **HeaderPolicy**. This policy will search token in headers of your POST request (Usually use for AJAX requests). You\n  need to specify name of header that will be checked.\n- **FormAndHeaderPolicy**. This policy combines behavior of **FormPolicy** and **HeaderPolicy**.\n\nYou can implement your custom policies if needed. But make sure that your custom policy\nimplements `aiohttp_csrf.policy.AbstractPolicy` interface.\n\n### Storages\n\nYou can use different types of storages for storing token. Library provides 2 types of storage:\n\n- **CookieStorage**. Your token will be stored in cookie variable. You need to specify cookie name.\n- **SessionStorage**. Your token will be stored in session. You need to specify session variable name.\n\n**Important:** If you want to use session storage, you need setup aiohttp\\_session in your\napplication ([session storage example](demo/session_storage.py#L22))\n\nYou can implement your custom storages if needed. But make sure that your custom storage\nimplements `aiohttp_csrf.storage.AbstractStorage` interface.\n\n### Token generators\n\nYou can use different token generator in your application. By default storages\nusing `aiohttp_csrf.token_generator.SimpleTokenGenerator`\n\nBut if you need more secure token generator - you can use `aiohttp_csrf.token_generator.HashedTokenGenerator`\n\nAnd you can implement your custom token generators if needed. But make sure that your custom token generator\nimplements `aiohttp_csrf.token_generator.AbstractTokenGenerator` interface.\n\n### Invalid token behavior\n\nBy default, if token is invalid, `aiohttp_csrf` will raise `aiohttp.web.HTTPForbidden` exception.\n\nYou have ability to specify your custom error handler. It can be:\n\n- **callable instance. Input parameter - aiohttp request.**\n\n```python\ndef custom_error_handler(request):\n    # do something\n    return aiohttp.web.Response(status=403)\n\n# or\n\nasync def custom_async_error_handler(request):\n    # await do something\n    return aiohttp.web.Response(status=403)\n```\n\nIt will be called instead of protected handler.\n\n- **sub class of Exception**. In this case this Exception will be raised.\n\n```python\nclass CustomException(Exception):\n    pass\n```\n\nYou can specify custom error handler globally, when initialize `aiohttp_csrf` in your application:\n\n```python\n...\nclass CustomException(Exception):\n    pass\n\n...\naiohttp_csrf.setup(app, policy=csrf_policy, storage=csrf_storage, error_renderer=CustomException)\n...\n```\n\nIn this case custom error handler will be applied to all protected handlers.\n\nOr you can specify custom error handler locally, for specific handler:\n\n```python\n...\nclass CustomException(Exception):\n    pass\n\n...\n@aiohttp_csrf.csrf_protect(error_renderer=CustomException)\ndef handler_with_custom_csrf_error(request):\n    ...\n```\n\nIn this case custom error handler will be applied to this handler only. For all other handlers will be applied global\nerror handler.\n",
    "bugtrack_url": null,
    "license": "The MIT License  Copyright (c) Ocean S.A. https://ocean.io/  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. ",
    "summary": "Cross-site request forgery (CSRF) protection for aiohttp-server",
    "version": "1.0.1",
    "project_urls": {
        "Homepage": "https://github.com/shuckc/aiohttp-csrf"
    },
    "split_keywords": [
        "asyncio",
        " aiohttp",
        " csrf",
        " webserver"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "27d49501fd89e91ba631d309f590dd01203e4af9e14ae44ccc167c3f39aaf168",
                "md5": "c44144ecf6f4c2fae7c5dbde4b0df4a4",
                "sha256": "32e670387a9b6ffc9b25d27693fa5de3372d88670d42be72143644730d6a7407"
            },
            "downloads": -1,
            "filename": "aiohttp_csrf2-1.0.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "c44144ecf6f4c2fae7c5dbde4b0df4a4",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 9110,
            "upload_time": "2024-09-13T09:20:32",
            "upload_time_iso_8601": "2024-09-13T09:20:32.958175Z",
            "url": "https://files.pythonhosted.org/packages/27/d4/9501fd89e91ba631d309f590dd01203e4af9e14ae44ccc167c3f39aaf168/aiohttp_csrf2-1.0.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "decb9320617254cc0c59dbe292c675f7d5150d41a895780caa829d8f000127c3",
                "md5": "e766632163362ca45b8ff67a1f7feb63",
                "sha256": "725004bf826c485249420629baa85fb80b38b327ed61161f65e98733feb613e1"
            },
            "downloads": -1,
            "filename": "aiohttp_csrf2-1.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "e766632163362ca45b8ff67a1f7feb63",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 15974,
            "upload_time": "2024-09-13T09:20:33",
            "upload_time_iso_8601": "2024-09-13T09:20:33.875941Z",
            "url": "https://files.pythonhosted.org/packages/de/cb/9320617254cc0c59dbe292c675f7d5150d41a895780caa829d8f000127c3/aiohttp_csrf2-1.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-09-13 09:20:33",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "shuckc",
    "github_project": "aiohttp-csrf",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "aiohttp-csrf2"
}
        
Elapsed time: 0.31122s