duck.http.middlewares.security.csrf¶
Module containing CSRFMiddleware class which mitigates against Cross-Site-Request-Forgery (CSRF) attacks.
Module Contents¶
Classes¶
Middleware for mitigating Cross-Site Request Forgery (CSRF) attacks. |
Functions¶
Generates a new CSRF secret and saves it in the request’s metadata. |
|
Returns a secure random CSRF secret containing only letters and digits. |
|
Dynamically generates a secure, consistent key based on system-specific data. |
|
Generates a new CSRF token and saves the CSRF secret in the request.META. |
|
Masks CSRF secret to produce a secure CSRF token. |
|
Unmasks a CSRF token to retrieve the original CSRF secret. |
Data¶
API¶
- duck.http.middlewares.security.csrf.ALLOWED_CHARACTERS¶
None
- exception duck.http.middlewares.security.csrf.CSRFCookieError¶
Bases:
ExceptionException class for CSRF cookie errors.
Initialization
Initialize self. See help(type(self)) for accurate signature.
- class duck.http.middlewares.security.csrf.CSRFMiddleware¶
Bases:
duck.http.middlewares.BaseMiddlewareMiddleware for mitigating Cross-Site Request Forgery (CSRF) attacks.
This middleware verifies the authenticity of requests by comparing the CSRF token included in the request body (for methods such as POST, PUT, etc.) with the one securely stored in the user’s session (
request.SESSION). This helps protect against unauthorized actions being performed using an authenticated user’s session.The middleware operates with the following behavior:
Conditional Activation: When
USE_DJANGO=True, this middleware is skipped unless the request path corresponds to a Duck explicit URL. Duck explicit URLs are listed inDUCK_EXPLICIT_URLSand should not be proxied to Django at any point.Prevention of CSRF Attacks: CSRF attacks exploit a user’s authenticated session to perform unauthorized actions on their behalf. By ensuring the CSRF token in the request body matches the one stored in the Session or Cookie, this middleware mitigates the risk of such attacks.
- Variables:
USE_DJANGO – Flag indicating whether to use Django for handling requests.
DUCK_EXPLICIT_URLS – List of URLs that should be handled by Duck and not proxied to Django.
Methods:
process_request(request): Verifies the
CSRF tokenin the request and compares it with theCsrf Cookie/Secretto ensure authenticity.
- classmethod _check_origin_ok(request)¶
Checks if request Origin is good origin
- Returns:
True if request origin is ok
- Raises:
OriginError – If origin provided is invalid in any way
- classmethod _check_referer_ok(request)¶
Checks if request Referer is good referer
- Returns:
True if request referer is ok
- Raises:
RefererError – If referer provided is invalid in any way
- classmethod check_csrf_cookie(request)¶
Checks for the csrf cookie sent in request.
- Raises:
CSRFCookieError – This is raised if there is any issue with the CSRF cookie sent by the client.
- debug_message: str¶
‘CSRFMiddleware: CSRF token missing or invalid’
- classmethod get_error_response(request)¶
- classmethod process_request(request: duck.http.request.HttpRequest)¶
- classmethod process_response(response, request)¶
- classmethod rotate_csrf_token()¶
Resets the request csrf secret and returns the rotated csrf secret.
- duck.http.middlewares.security.csrf.CSRF_SECRET_LENGTH¶
None
- duck.http.middlewares.security.csrf.CSRF_SESSION_KEY¶
None
- duck.http.middlewares.security.csrf.CSRF_TOKEN_LENGTH¶
None
- duck.http.middlewares.security.csrf.CSRF_USE_SESSIONS¶
None
- exception duck.http.middlewares.security.csrf.OriginError¶
Bases:
ExceptionException class for invalid HTTP Origin
Initialization
Initialize self. See help(type(self)) for accurate signature.
- exception duck.http.middlewares.security.csrf.RefererError¶
Bases:
ExceptionException class for invalid HTTP Referer
Initialization
Initialize self. See help(type(self)) for accurate signature.
- duck.http.middlewares.security.csrf.add_new_csrf_cookie(request)¶
Generates a new CSRF secret and saves it in the request’s metadata.
- Parameters:
request – The HTTP request object.
secret_key – The dynamic secret key used for signing the CSRF token.
- duck.http.middlewares.security.csrf.generate_csrf_secret() str¶
Returns a secure random CSRF secret containing only letters and digits.
- duck.http.middlewares.security.csrf.generate_dynamic_secret_key() bytes¶
Dynamically generates a secure, consistent key based on system-specific data.
- Returns:
A dynamic, secure key derived from system-specific data.
- Return type:
bytes
- duck.http.middlewares.security.csrf.get_csrf_token(request)¶
Generates a new CSRF token and saves the CSRF secret in the request.META.
- Parameters:
request – The http request.
This function performs the following actions:
Generates a new CSRF token (Csrf_Token), a scrambled/random token to be sent to the user.
Saves the CSRF secret (Csrf_Secret) in:
request.META under the key ‘CSRF_COOKIE’
The CSRF token (Csrf_Token) is sent to the client each time this function is called. (This is done by CSRFMiddleware)
- duck.http.middlewares.security.csrf.mask_cipher_secret(secret: str) str¶
Masks CSRF secret to produce a secure CSRF token.
- Parameters:
secret – The CSRF secret.
- Returns:
The CSRF token.
- Return type:
str
- Raises:
ValueError – If the secret contains invalid characters.
- duck.http.middlewares.security.csrf.unmask_cipher_token(token: str) str¶
Unmasks a CSRF token to retrieve the original CSRF secret.
- Parameters:
token – The CSRF token.
- Returns:
The original CSRF secret.
- Return type:
str
- Raises:
ValueError – If the token is invalid or tampered with.