Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[6-0-stable] Forward compatible CSRF token decoder #41805

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -329,7 +329,7 @@ def valid_authenticity_token?(session, encoded_masked_token) # :doc:
end

begin
masked_token = Base64.strict_decode64(encoded_masked_token)
masked_token = decode_csrf_token(encoded_masked_token)
rescue ArgumentError # encoded_masked_token is invalid Base64
return false
end
Expand Down Expand Up @@ -394,7 +394,7 @@ def valid_per_form_csrf_token?(token, session) # :doc:

def real_csrf_token(session) # :doc:
session[:_csrf_token] ||= SecureRandom.base64(AUTHENTICITY_TOKEN_LENGTH)
Base64.strict_decode64(session[:_csrf_token])
decode_csrf_token(session[:_csrf_token])
end

def per_form_csrf_token(session, action_path, method) # :doc:
Expand Down Expand Up @@ -462,5 +462,11 @@ def normalize_action_path(action_path) # :doc:
uri = URI.parse(action_path)
uri.path.chomp("/")
end

def decode_csrf_token(encoded_csrf_token)
Base64.strict_decode64(encoded_csrf_token)
rescue ArgumentError
Base64.urlsafe_decode64(encoded_csrf_token)
end
end
end
9 changes: 9 additions & 0 deletions actionpack/test/controller/request_forgery_protection_test.rb
Expand Up @@ -377,6 +377,15 @@ def test_should_allow_post_with_token
end
end

def test_should_allow_post_with_urlsafe_token_when_migrating
token_length = (ActionController::RequestForgeryProtection::AUTHENTICITY_TOKEN_LENGTH * 4.0 / 3).ceil
token_including_url_safe_chars = "-_".ljust(token_length, "A")
session[:_csrf_token] = token_including_url_safe_chars
@controller.stub :form_authenticity_token, token_including_url_safe_chars do
assert_not_blocked { post :index, params: { custom_authenticity_token: token_including_url_safe_chars } }
end
end

def test_should_allow_patch_with_token
session[:_csrf_token] = @token
@controller.stub :form_authenticity_token, @token do
Expand Down