On this page:
current-csrf-error-handler
7.1 Header-based Approach
wrap-corf
7.2 Token-based Approach
current-csrf-token-generator
current-csrf-token
current-csrf-token-reader
wrap-csrf

7 CSRF🔗

 (require koyo/csrf) package: koyo-lib

This module provides wrapper procedures for protecting your application against CSRF attacks.

parameter

(current-csrf-error-handler)  (-> request? response?)

(current-csrf-error-handler handler)  void?
  handler : (-> request? response?)
Holds the request handler that is invoked when the request fails CSRF validation. The default implementation returns a 403 Forbidden response along with some HTML describing the issue.

This parameter is used by both wrap-corf and wrap-cors.

7.1 Header-based Approach🔗

The cross-origin request forgery wrapper protects a handler from CSRF attacks by inspecting the Sec-Fetch-Site and Origin headers. This method is preferred over the older Token-based Approach since it involves fewer moving parts and does not require the developer to pass a token with every form submission.

procedure

(wrap-corf handler)  (-> request? any/c ... response?)

  handler : procedure?
Wraps a handler such that any incoming DELETE, PATCH, POST or PUT request whose Sec-Fetch-Site header is not either same-site or none and whose Origin header differs from its Host header is rejected by passing the request to the value of current-csrf-error-handler.

Browsers that don’t pass either a Sec-Fetch-Site header or an Origin header are treated the same as non-browser clients. That is, validation passes.

7.2 Token-based Approach🔗

Contains the procedure that is used to generate new CSRF tokens.

parameter

(current-csrf-token)  (or/c #f non-empty-string?)

(current-csrf-token token)  void?
  token : (or/c #f non-empty-string?)
Holds the CSRF token for the current request. If the current request handler was wrapped with wrap-csrf, then this is guaranteed to contain a non-empty string.

parameter

(current-csrf-token-reader)

  (-> request? (or/c #f non-empty-string?))
(current-csrf-token-reader reader)  void?
  reader : (-> request? (or/c #f non-empty-string?))
Contains the procedure that is used to extract the current CSRF token from the request. The default implementation tries to extract the CSRF token from a header called x-csrf-token and, if that fails, then it tries to get it from a binding called csrf-token.

procedure

((wrap-csrf sessions) handler)

  (-> request? any/c ... response?)
  sessions : session-manager?
  handler : procedure?
Wraps a handler such that any incoming DELETE, PATCH, POST or PUT request that doesn’t contain a valid CSRF token is rejected by passing the request to the value of current-csrf-error-handler.

CSRF tokens are automatically generated and stored in each users’ sessions. If a user’s session already contains a CSRF token, then it is reused until the session expires.

This wrapper must be applied after wrap-session.