Class: Rack::Cors::CsrfPrevention

Inherits:
Object
  • Object
show all
Includes:
Logger
Defined in:
lib/rack/cors/csrf_prevention.rb,
lib/rack/cors/csrf_prevention/logger.rb,
lib/rack/cors/csrf_prevention/version.rb

Defined Under Namespace

Modules: Logger

Constant Summary collapse

APOLLO_CUSTOM_PREFLIGHT_HEADERS =
%w[
  X_APOLLO_OPERATION_NAME
  APOLLO_REQUIRE_PREFLIGHT
].freeze
NON_PREFLIGHTED_CONTENT_TYPES =
%w[
  application/x-www-form-urlencoded
  multipart/form-data
  text/plain
].freeze
ERROR_MESSAGE =
"This operation has been blocked as a potential Cross-Site Request Forgery (CSRF).\n\nPlease either specify a \"Content-Type\" header (with a mime-type that is not one of \#{NON_PREFLIGHTED_CONTENT_TYPES.join(', ')}) or provide one of the following headers: \#{APOLLO_CUSTOM_PREFLIGHT_HEADERS.join(', ').tr('_', '-')}.\n"
VERSION =
"0.3.0"

Instance Method Summary collapse

Methods included from Logger

#logger

Constructor Details

#initialize(app, path: nil, paths: [], required_headers: [], detailed_error: true) ⇒ CsrfPrevention

Returns a new instance of CsrfPrevention.



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rack/cors/csrf_prevention.rb', line 29

def initialize(
  app,
  path: nil,
  paths: [],
  required_headers: [],
  detailed_error: true
)
  @app = app
  @paths = path.nil? && paths.empty? ? ["/graphql"] : [path].compact + paths
  @required_headers = APOLLO_CUSTOM_PREFLIGHT_HEADERS + required_headers
  @detailed_error = detailed_error
end

Instance Method Details

#call(env) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/rack/cors/csrf_prevention.rb', line 42

def call(env)
  request = ::Rack::Request.new(env)

  return @app.call(env) unless protected_path?(request.path)

  if preflighted?(request)
    logger(env).debug { "Request is preflighted" }

    @app.call(env)
  else
    logger(env).debug { "Request isn't preflighted" }

    Rack::Response[400, { "Content-Type" => "text/plain" }, response_body].to_a
  end
end