|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright (C) 2020-2025 All rights reserved. |
| 3 | +# FILENAME: ~~/src/fastapi_csrf_protect/flexible/core.py |
| 4 | +# VERSION: 1.0.4 |
| 5 | +# CREATED: 2025-08-11 16:02:06+02:00 |
| 6 | +# AUTHOR: Eliam Lotonga <[email protected]> |
| 7 | +# DESCRIPTION: https://www.w3docs.com/snippets/python/what-is-init-py-for.html |
| 8 | +# |
| 9 | +# HISTORY: |
| 10 | +# ************************************************************* |
| 11 | + |
| 12 | +### Standard packages ### |
| 13 | +from hashlib import sha1 |
| 14 | +from os import urandom |
| 15 | +from re import match |
| 16 | +from typing import Dict, Tuple, Optional, Union |
| 17 | + |
| 18 | +### Third-party packages ### |
| 19 | +from itsdangerous import BadData, SignatureExpired, URLSafeTimedSerializer |
| 20 | +from pydantic import create_model |
| 21 | +from starlette.datastructures import Headers |
| 22 | +from starlette.requests import Request |
| 23 | +from starlette.responses import Response |
| 24 | + |
| 25 | +### Local modules ### |
| 26 | +from fastapi_csrf_protect.exceptions import ( |
| 27 | + MissingTokenError, |
| 28 | + TokenValidationError, |
| 29 | +) |
| 30 | +from fastapi_csrf_protect.flexible.csrf_config import CsrfConfig |
| 31 | + |
| 32 | + |
| 33 | +class CsrfProtect(CsrfConfig): |
| 34 | + """Flexible CSRF validation: accepts token from either header or form body. |
| 35 | +
|
| 36 | + Priority: |
| 37 | + 1. Header |
| 38 | + 2. Body |
| 39 | + """ |
| 40 | + |
| 41 | + def generate_csrf_tokens(self, secret_key: Optional[str] = None) -> Tuple[str, str]: |
| 42 | + """ |
| 43 | + Generate a CSRF token and a signed CSRF token using server's secret key to be stored in cookie. |
| 44 | +
|
| 45 | + --- |
| 46 | + :param secret_key: (Optional) the secret key used when generating tokens for users |
| 47 | + :type secret_key: (str | None) Defaults to None. |
| 48 | + """ |
| 49 | + secret_key = secret_key or self._secret_key |
| 50 | + if secret_key is None: |
| 51 | + raise RuntimeError("A secret key is required to use CsrfProtect extension.") |
| 52 | + serializer = URLSafeTimedSerializer(secret_key, salt="fastapi-csrf-token") |
| 53 | + token = sha1(urandom(64)).hexdigest() |
| 54 | + signed = serializer.dumps(token) |
| 55 | + return token, signed |
| 56 | + |
| 57 | + def get_csrf_from_body(self, data: bytes) -> str: |
| 58 | + """ |
| 59 | + Get token from the request body |
| 60 | +
|
| 61 | + --- |
| 62 | + :param data: attached request body containing cookie data with configured `token_key` |
| 63 | + :type data: bytes |
| 64 | + """ |
| 65 | + fields: Dict[str, Tuple[type, str]] = {self._token_key: (str, "csrf-token")} |
| 66 | + Body = create_model("Body", **fields) |
| 67 | + content: str = '{"' + data.decode("utf-8").replace("&", '","').replace("=", '":"') + '"}' |
| 68 | + body = Body.model_validate_json(content) |
| 69 | + token: str = body.model_dump()[self._token_key] |
| 70 | + return token |
| 71 | + |
| 72 | + def get_csrf_from_headers(self, headers: Headers) -> Union[None, str]: |
| 73 | + """ |
| 74 | + Get token from the request headers |
| 75 | +
|
| 76 | + --- |
| 77 | + :param headers: Headers containing header with configured `header_name` |
| 78 | + :type headers: starlette.datastructures.Headers |
| 79 | + """ |
| 80 | + header_name, header_type = self._header_name, self._header_type |
| 81 | + header_parts = None |
| 82 | + try: |
| 83 | + header_parts = headers[header_name].split() |
| 84 | + except KeyError: |
| 85 | + return None |
| 86 | + token: Union[None, str] = None |
| 87 | + if not header_type: |
| 88 | + # <HeaderName>: <Token> |
| 89 | + if len(header_parts) != 1: |
| 90 | + return token |
| 91 | + token = header_parts[0] |
| 92 | + else: |
| 93 | + # <HeaderName>: <HeaderType> <Token> |
| 94 | + if not match(r"{}\s".format(header_type), headers[header_name]) or len(header_parts) != 2: |
| 95 | + return token |
| 96 | + token = header_parts[1] |
| 97 | + return token |
| 98 | + |
| 99 | + def set_csrf_cookie(self, csrf_signed_token: str, response: Response) -> None: |
| 100 | + """ |
| 101 | + Sets Csrf Protection token to the response cookies |
| 102 | +
|
| 103 | + --- |
| 104 | + :param csrf_signed_token: signed CSRF token from `generate_csrf_token` method |
| 105 | + :type csrf_signed_token: str |
| 106 | + :param response: The FastAPI response object to sets the access cookies in. |
| 107 | + :type response: fastapi.responses.Response |
| 108 | + """ |
| 109 | + if not isinstance(response, Response): |
| 110 | + raise TypeError("The response must be an object response FastAPI") |
| 111 | + response.set_cookie( |
| 112 | + self._cookie_key, |
| 113 | + csrf_signed_token, |
| 114 | + max_age=self._max_age, |
| 115 | + path=self._cookie_path, |
| 116 | + domain=self._cookie_domain, |
| 117 | + secure=self._cookie_secure, |
| 118 | + httponly=self._httponly, |
| 119 | + samesite=self._cookie_samesite, |
| 120 | + ) |
| 121 | + |
| 122 | + def unset_csrf_cookie(self, response: Response) -> None: |
| 123 | + """ |
| 124 | + Remove Csrf Protection token from the response cookies |
| 125 | +
|
| 126 | + --- |
| 127 | + :param response: The FastAPI response object to delete the access cookies in. |
| 128 | + :type response: fastapi.responses.Response |
| 129 | + """ |
| 130 | + if not isinstance(response, Response): |
| 131 | + raise TypeError("The response must be an object response FastAPI") |
| 132 | + response.delete_cookie( |
| 133 | + self._cookie_key, |
| 134 | + path=self._cookie_path, |
| 135 | + domain=self._cookie_domain, |
| 136 | + secure=self._cookie_secure, |
| 137 | + httponly=self._httponly, |
| 138 | + samesite=self._cookie_samesite, |
| 139 | + ) |
| 140 | + |
| 141 | + async def validate_csrf( |
| 142 | + self, |
| 143 | + request: Request, |
| 144 | + cookie_key: Optional[str] = None, |
| 145 | + secret_key: Optional[str] = None, |
| 146 | + time_limit: Optional[int] = None, |
| 147 | + ) -> None: |
| 148 | + """ |
| 149 | + Check if the given data is a valid CSRF token. This compares the given |
| 150 | + signed token to the one stored in the session. |
| 151 | +
|
| 152 | + --- |
| 153 | + :param request: incoming Request instance |
| 154 | + :type request: fastapi.requests.Request |
| 155 | + :param cookie_key: (Optional) field name for the CSRF token field stored in cookies |
| 156 | + Default is set in CsrfConfig when `load_config` was called; |
| 157 | + :type cookie_key: str |
| 158 | + :param secret_key: (Optional) secret key used to decrypt the token |
| 159 | + Default is set in CsrfConfig when `load_config` was called; |
| 160 | + :type secret_key: str |
| 161 | + :param time_limit: (Optional) Number of seconds that the token is valid. |
| 162 | + Default is set in CsrfConfig when `load_config` was called; |
| 163 | + :type time_limit: int |
| 164 | + :raises TokenValidationError: Contains the reason that validation failed. |
| 165 | + """ |
| 166 | + secret_key = secret_key or self._secret_key |
| 167 | + if secret_key is None: |
| 168 | + raise RuntimeError("A secret key is required to use CsrfProtect extension.") |
| 169 | + cookie_key = cookie_key or self._cookie_key |
| 170 | + signed_token = request.cookies.get(cookie_key) |
| 171 | + if signed_token is None: |
| 172 | + raise MissingTokenError(f"Missing Cookie: `{cookie_key}`.") |
| 173 | + time_limit = time_limit or self._max_age |
| 174 | + token: None | str = self.get_csrf_from_headers(request.headers) |
| 175 | + if not token: |
| 176 | + token = self.get_csrf_from_body(await request.body()) |
| 177 | + serializer = URLSafeTimedSerializer(secret_key, salt="fastapi-csrf-token") |
| 178 | + try: |
| 179 | + signature: str = serializer.loads(signed_token, max_age=time_limit) |
| 180 | + if token != signature: |
| 181 | + raise TokenValidationError("The CSRF signatures submitted do not match.") |
| 182 | + except SignatureExpired: |
| 183 | + raise TokenValidationError("The CSRF token has expired.") |
| 184 | + except BadData: |
| 185 | + raise TokenValidationError("The CSRF token is invalid.") |
| 186 | + |
| 187 | + |
| 188 | +__all__: Tuple[str, ...] = ("CsrfProtect",) |
0 commit comments