Upgraded Rails and RSpec
[monkeycharger.git] / vendor / rails / actionpack / lib / action_controller / request_forgery_protection.rb
blob035bad749800cad7853c1dc66fdabf8cd4abfb23
1 module ActionController #:nodoc:
2   class InvalidAuthenticityToken < ActionControllerError #:nodoc:
3   end
5   module RequestForgeryProtection
6     def self.included(base)
7       base.class_eval do
8         class_inheritable_accessor :request_forgery_protection_options
9         self.request_forgery_protection_options = {}
10         helper_method :form_authenticity_token
11         helper_method :protect_against_forgery?
12       end
13       base.extend(ClassMethods)
14     end
15     
16     module ClassMethods
17       # Protect a controller's actions from CSRF attacks by ensuring that all forms are coming from the current web application, not 
18       # a forged link from another site. This is done by embedding a token based on the session (which an attacker wouldn't know) in 
19       # all forms and Ajax requests generated by Rails and then verifying the authenticity of that token in the controller. Only
20       # HTML/JavaScript requests are checked, so this will not protect your XML API (presumably you'll have a different authentication
21       # scheme there anyway). Also, GET requests are not protected as these should be indempotent anyway.
22       #
23       # You turn this on with the #protect_from_forgery method, which will perform the check and raise 
24       # an ActionController::InvalidAuthenticityToken if the token doesn't match what was expected. And it will add 
25       # a _authenticity_token parameter to all forms that are automatically generated by Rails. You can customize the error message 
26       # given through public/422.html.
27       #
28       # Learn more about CSRF (Cross-Site Request Forgery) attacks:
29       #
30       # * http://isc.sans.org/diary.html?storyid=1750
31       # * http://en.wikipedia.org/wiki/Cross-site_request_forgery
32       #
33       # Keep in mind, this is NOT a silver-bullet, plug 'n' play, warm security blanket for your rails application.
34       # There are a few guidelines you should follow:
35       # 
36       # * Keep your GET requests safe and idempotent.  More reading material:
37       #   * http://www.xml.com/pub/a/2002/04/24/deviant.html
38       #   * http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1
39       # * Make sure the session cookies that Rails creates are non-persistent.  Check in Firefox and look for "Expires: at end of session"
40       #
41       # If you need to construct a request yourself, but still want to take advantage of forgery protection, you can grab the 
42       # authenticity_token using the form_authenticity_token helper method and make it part of the parameters yourself.
43       #
44       # Example:
45       #
46       #   class FooController < ApplicationController
47       #     # uses the cookie session store (then you don't need a separate :secret)
48       #     protect_from_forgery :except => :index
49       #
50       #     # uses one of the other session stores that uses a session_id value.
51       #     protect_from_forgery :secret => 'my-little-pony', :except => :index
52       #
53       #     # you can disable csrf protection on controller-by-controller basis:
54       #     skip_before_filter :verify_authenticity_token
55       #   end
56       #
57       # Valid Options:
58       #
59       # * <tt>:only/:except</tt> - passed to the before_filter call.  Set which actions are verified.
60       # * <tt>:secret</tt> - Custom salt used to generate the form_authenticity_token.
61       #   Leave this off if you are using the cookie session store.
62       # * <tt>:digest</tt> - Message digest used for hashing.  Defaults to 'SHA1'
63       def protect_from_forgery(options = {})
64         self.request_forgery_protection_token ||= :authenticity_token
65         before_filter :verify_authenticity_token, :only => options.delete(:only), :except => options.delete(:except)
66         request_forgery_protection_options.update(options)
67       end
68     end
70     protected
71       # The actual before_filter that is used.  Modify this to change how you handle unverified requests.
72       def verify_authenticity_token
73         verified_request? || raise(ActionController::InvalidAuthenticityToken)
74       end
75       
76       # Returns true or false if a request is verified.  Checks:
77       #
78       # * is the format restricted?  By default, only HTML and AJAX requests are checked.
79       # * is it a GET request?  Gets should be safe and idempotent
80       # * Does the form_authenticity_token match the given _token value from the params?
81       def verified_request?
82         !protect_against_forgery?     ||
83           request.method == :get      ||
84           !verifiable_request_format? ||
85           form_authenticity_token == params[request_forgery_protection_token]
86       end
87     
88       def verifiable_request_format?
89         request.format.html? || request.format.js?
90       end
91     
92       # Sets the token value for the current session.  Pass a :secret option in #protect_from_forgery to add a custom salt to the hash.
93       def form_authenticity_token
94         @form_authenticity_token ||= if request_forgery_protection_options[:secret]
95           authenticity_token_from_session_id
96         elsif session.respond_to?(:dbman) && session.dbman.respond_to?(:generate_digest)
97           authenticity_token_from_cookie_session
98         elsif session.nil?
99           raise InvalidAuthenticityToken, "Request Forgery Protection requires a valid session.  Use #allow_forgery_protection to disable it, or use a valid session."
100         else
101           raise InvalidAuthenticityToken, "No :secret given to the #protect_from_forgery call.  Set that or use a session store capable of generating its own keys (Cookie Session Store)."
102         end
103       end
104       
105       # Generates a unique digest using the session_id and the CSRF secret.
106       def authenticity_token_from_session_id
107         key = if request_forgery_protection_options[:secret].respond_to?(:call)
108           request_forgery_protection_options[:secret].call(@session)
109         else
110           request_forgery_protection_options[:secret]
111         end
112         digest = request_forgery_protection_options[:digest] ||= 'SHA1'
113         OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new(digest), key.to_s, session.session_id.to_s)
114       end
115       
116       # No secret was given, so assume this is a cookie session store.
117       def authenticity_token_from_cookie_session
118         session[:csrf_id] ||= CGI::Session.generate_unique_id
119         session.dbman.generate_digest(session[:csrf_id])
120       end
121       
122       def protect_against_forgery?
123         allow_forgery_protection && request_forgery_protection_token
124       end
125   end