= Rack::Csrf {<img src="https://circleci.com/gh/baldowl/rack_csrf.svg?style=svg" alt="CircleCI" />}[https://circleci.com/gh/baldowl/rack_csrf] {<img src="https://github.com/baldowl/rack_csrf/actions/workflows/ci.yml/badge.svg?branch=master" alt="Actions Status: CI" />}[https://github.com/baldowl/rack_csrf/actions?query=workflow%3ACI+branch%3Amaster] {<img src="https://badge.fury.io/rb/rack_csrf.svg" alt="Gem Version" />}[http://badge.fury.io/rb/rack_csrf]

This is just a small Rack middleware whose only goal is to lessen the hazards
posed by CSRF attacks by trying to ensure that all requests of particular
types come from the right client, not from a mischievous impersonator.

Rack::Csrf is not tailored to any particular web framework, so it can be used
with your preferred Rack-based framework.

== Usage

First of all, beyond Rack itself, there is only one prerequisite: you must set
up your rack with a session middleware, inserted anywhere before Rack::Csrf.

Every POST, PUT, DELETE and PATCH request will be searched for the
anti-forging token, randomly generated by Rack::Csrf and stored inside the
session. If there's a token and it matches with the stored one, then the
request is handed over to the next rack component; if not, Rack::Csrf
immediately replies with an empty response.

The anti-forging token can be passed as a request parameter or a header.

== Options

The following options allow you to tweak Rack::Csrf.

[<tt>:raise</tt>]
  Set it to true to change the handling of bad requests: instead of producing
  an empty response, Rack::Csrf will raise an exception of class
  Rack::Csrf::InvalidCsrfToken.

    use Rack::Csrf, :raise => true

  Default value: false.

[<tt>:check_only</tt>]
  By default, Rack::Csrf checks every POST, PUT, DELETE and PATCH request;
  passing an array of HTTP method/URL (regular expressions allowed) to this
  option you can change this behavior to *only* check the items on this list.

    use Rack::Csrf, :check_only => ['POST:/checking', 'PUT:/me_too',
      'DELETE:/cars/.*\.xml', 'PATCH:/this/.*/too']

  Please, note that the regular expressions are not escaped and it is your
  duty to write them correctly. Empty PATH_INFO (see Rack's spec for details)
  is treated as '/' for this check.

  Default value: empty.

[<tt>:skip</tt>]
  By default, Rack::Csrf checks every POST, PUT, DELETE and PATCH request;
  passing an array of HTTP method/URL (regular expressions allowed) to this
  option you can choose what to let pass unchecked:

    use Rack::Csrf, :skip => ['POST:/not_checking', 'PUT:/me_too',
      'DELETE:/cars/.*\.xml', 'PATCH:/this/.*/too']

  Please, note that the regular expressions are not escaped and it is your
  duty to write them correctly. Empty PATH_INFO (see Rack's spec for details)
  is treated as '/' for this check.

  Default value: empty.

[<tt>:skip_if</tt>]
  Sets a lambda/Proc executed on every request to determine if that request
  should be let pass untouched:

    use Rack::Csrf, :skip_if => lambda { |request|
      request.env.key?('HTTP_X_VERY_SPECIAL_HEADER')
    }

  Your code will receive a request object (see Rack's documentation for
  details); if it returns anything but nil or false, no further checking is
  performed and the request is let pass.

  This option is useful if a guarded resource can be accessed by clients who
  support CSRF token (e.g. browsers) and by ones who don't (e.g. API clients).

  Don't try to check the CSRF token: it could exist or not at this stage and
  you should always let it alone.

  Default value: empty.

[<tt>:field</tt>]
  Default field name (see below) is <tt>_csrf</tt>; you can adapt it to
  specific needs.

    use Rack::Csrf, :field => '_my_own_csrf_field'

  Default value: _csrf

[<tt>:key</tt>]
  The key used to store/retrieve the token from the Rack session; you can
  adapt it to specific needs.

    use Rack::Csrf, :key => 'my.own_session.key'

  Default value: csrf.token

[<tt>:header</tt>]
  Default header name (see below) is <tt>X_CSRF_TOKEN</tt>; you can adapt it
  to specific needs.

    use Rack::Csrf, :header => 'MY_CSRF_TOKEN_HEADER'

  This is useful if we want to configure our application to send the CSRF
  token in all of our AJAX requests via a header. We could implement something
  along the lines of the following:

    (function(jQuery) {
      /*
       * Set the CSRF token for each AJAX request, Rack::Csrf handle the rest.
       * Assumes your layout has a metatag with name of "_csrf" and you're
       * using the default Rack:Csrf header setup.
       */
      jQuery.ajaxSetup({
        beforeSend: function(xhr) {
          var token = jQuery('meta[name="_csrf"]').attr('content');
          xhr.setRequestHeader('X_CSRF_TOKEN', token);
        }
      });
    }(jQuery));

  Default value: X_CSRF_TOKEN

  Note that Rack will append "HTTP_" to this value.

[<tt>:check_also</tt>]
  By passing an array of uppercase strings to this option you can add them to
  the list of HTTP methods which "mark" requests that must be searched for the
  anti-forging token.

    use Rack::Csrf, :check_also => %w(WHATEVER YOU WANT EVEN GET)

  Default value: empty

The <tt>:browser_only</tt> option has been removed; you do not need to edit
any rackup file because Rack::Csrf simply ignores unknown options. Changes
introduced in Rack version 1.1.0 tightened the parsing of POST params, so
requests need to have the right Content-Type (or none at all); these
Content-Types are exactly those used also by browsers and so there is no use
for <tt>:browser_only</tt> anymore.

The ill devised <tt>:browser_only</tt> option could have been used to
"protect" an API, but I think it might be better to use a combination of
<tt>:skip</tt> and formatted URLs.

== Helpers

The following class methods try to ease the insertion of the anti-forging
token.

[<tt>Rack::Csrf.key</tt> (also <tt>Rack::Csrf.csrf_key</tt>)]
  Returns the name of the key used to store/retrieve the token from the Rack
  session.

  Despite this class method, you should never try to retrieve the token with
  code like <tt>env['rack.session'][Rack::Csrf.key]</tt>. See the `token`
  method below.

[<tt>Rack::Csrf.field</tt> (also <tt>Rack::Csrf.csrf_field</tt>)]
  Returns the name of the field that must be present in the request.

[<tt>Rack::Csrf.header</tt> (also <tt>Rack::Csrf.csrf_header</tt>)]
  Returns the name of the header that must be present in the request.

[<tt>Rack::Csrf.token(env)</tt> (also <tt>Rack::Csrf.csrf_token(env)</tt>)]
  Given the request's environment, it generates a random token, stuffs it in
  the session and returns it to the caller or simply retrieves the already
  stored one.

[<tt>Rack::Csrf.tag(env)</tt> (also <tt>Rack::Csrf.csrf_tag(env)</tt>)]
  Given the request's environment, it generates a small HTML fragment to
  insert the token in a standard form like an hidden input field with the
  right value already entered for you.

[<tt>Rack::Csrf.metatag(env, options = {})</tt> (also <tt>Rack::Csrf.csrf_metatag(env, options = {})</tt>)]
  Given the request's environment, it generates a small HTML fragment to
  insert the token in a standard metatag within your layout's head with the
  right value already entered for you.

  <tt>options</tt> is an optional hash that can currently take a +name+
  setting, which will alter the metatag's name attribute.

  Default name: _csrf

== Working examples

In the +examples+ directory there are some small, working web applications
written with different Rack-based frameworks. They are named after the used
framework; see the various README files for other details.

== Supported Rubies and Racks

The gemspec shows the minimum Ruby and Rack versions, but Rack::Csrf is
tested only with the Rubies and Racks you can see in
<tt>.circleci/config.yml</tt> and/or <tt>.github/workflows/ci.yml</tt>. It
could work also with older versions, but I decided not to test it against
unsupported Rubies and Racks.

== Contributing

If you want to help:

* fork the project[https://github.com/baldowl/rack_csrf] on GitHub;
* work in a topic branch;
* add features/specs for your additions or bug fixes;
* write your additions/bug fixes;
* commit;
* send me a pull request for the topic branch.

If you have any issue, please post them on the {project's issue
list}[https://github.com/baldowl/rack_csrf] on GitHub.

== Warning! Warning! Warning!

I cannot stress enough that this middleware is not a bulletproof vest or a
panacea for the CSRF plague; it is just an *aid* and by using it you cannot
forgo responsibilities for keeping your application as safe as possible.

== Copyright

Copyright (c) 2009, 2010, 2011, 2012, 2014, 2016, 2022 Emanuele Vicentini. 
See LICENSE.rdoc for details.
