Skip to content

Instantly share code, notes, and snippets.

View mctaylorpants's full-sized avatar

Alex Taylor mctaylorpants

View GitHub Profile
def call_external_api
rescue
end
@mctaylorpants
mctaylorpants / do_you_really_need_create_cop.rb
Created September 22, 2017 18:34
RuboCop Cop to replace FactoryGirl#create with FactoryGirl#build_stubbed
# FactoryGirl's #build_stubbed method can often be used in place of #create, and will increase the speed of your test suite
# Source: https://robots.thoughtbot.com/use-factory-girls-build-stubbed-for-a-faster-test
#
# You can run this cop to find usages of #create in your spec suite...
# rubocop --require ./do_you_really_need_create_cop.rb --only FactoryGirl/DoYouReallyNeedCreate spec/
#
# ... then, you can use the --auto-correct flag to have RuboCop automatically replace #create with #build_stubbed:
# rubocop --require ./do_you_really_need_create_cop.rb --only FactoryGirl/DoYouReallyNeedCreate --auto-correct spec/
#
module RuboCop
def compare_with_real_token(token, session) # :doc:
ActiveSupport::SecurityUtils.fixed_length_secure_compare(token, real_csrf_token(session))
end
def unmask_token(masked_token) # :doc:
one_time_pad = masked_token[0...AUTHENTICITY_TOKEN_LENGTH]
encrypted_csrf_token = masked_token[AUTHENTICITY_TOKEN_LENGTH..-1]
xor_byte_strings(one_time_pad, encrypted_csrf_token)
end
def valid_authenticity_token?(session, encoded_masked_token) # :doc:
# ...
begin
masked_token = Base64.strict_decode64(encoded_masked_token)
rescue ArgumentError # encoded_masked_token is invalid Base64
return false
end
if masked_token.length == AUTHENTICITY_TOKEN_LENGTH
def any_authenticity_token_valid? # :doc:
request_authenticity_tokens.any? do |token|
valid_authenticity_token?(session, token)
end
end
# actionpack/lib/action_controller/metal/request_forgery_protection.rb
def verify_authenticity_token # :doc:
  # ...
if !verified_request?
  # handle errors ...
  end
end
# ...
@mctaylorpants
mctaylorpants / index.html
Created July 31, 2017 00:09
rails csrf - example index.html
<meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="vtaJFQ38doX0b7wQpp0G3H7aUk9HZQni3jHET4yS8nSJRt85Tr6oH7nroQc01dM+C/dlDwt5xPff5LwyZcggeg==" />
one_time_pad = SecureRandom.random_bytes(AUTHENTICITY_TOKEN_LENGTH)
encrypted_csrf_token = xor_byte_strings(one_time_pad, raw_token)
masked_token = one_time_pad + encrypted_csrf_token
Base64.strict_encode64(masked_token)
# actionpack/lib/action_controller/metal/request_forgery_protection.rb
def real_csrf_token(session) # :doc:
session[:_csrf_token] ||= SecureRandom.base64(AUTHENTICITY_TOKEN_LENGTH)
Base64.strict_decode64(session[:_csrf_token])
end