Class: Apigatewayv2Rack::Middlewares::CloudfrontVerify

Inherits:
Object
  • Object
show all
Defined in:
lib/apigatewayv2_rack/middlewares/cloudfront_verify.rb

Overview

Compare X-Origin-Verify header matches the expected value and otherwise returns 403. This is useful to use with CloudFront’s origin custom request header to protect from direct access to function.

See also: www.wellarchitectedlabs.com/security/300_labs/300_multilayered_api_security_with_cognito_and_waf/3_prevent_requests_from_accessing_api_directly/

Instance Method Summary collapse

Constructor Details

#initialize(app, value) ⇒ CloudfrontVerify

value is an expected string value of x-origin-verify.



12
13
14
15
# File 'lib/apigatewayv2_rack/middlewares/cloudfront_verify.rb', line 12

def initialize(app, value)
  @app = app
  @value = value
end

Instance Method Details

#call(env) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/apigatewayv2_rack/middlewares/cloudfront_verify.rb', line 21

def call(env)
  given = env[env_name]

  unless given && Rack::Utils.secure_compare(given, @value)
    env['rack.logger']&.warn("#{self.class.name} protected unwanted access from #{env['REMOTE_ADDR'].inspect}")
    return [401, {'Content-Type' => 'text/plain'}, ['Unauthorized']]
  end

  @app.call(env)
end

#env_nameObject



17
18
19
# File 'lib/apigatewayv2_rack/middlewares/cloudfront_verify.rb', line 17

def env_name
  'HTTP_X_ORIGIN_VERIFY'
end