Skip to content

Commit

Permalink
Enable Content-Security-Policy (#394)
Browse files Browse the repository at this point in the history
  • Loading branch information
jlledom authored Jul 2, 2024
1 parent 2edfb48 commit 112eae6
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 10 deletions.
13 changes: 3 additions & 10 deletions lib/3scale/backend/cors.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
require '3scale/backend/headers/stringify'

# CORS support
#
# Please see references:
Expand All @@ -8,16 +10,7 @@
module ThreeScale
module Backend
module CORS
def self.stringify_consts(*consts)
consts.each do |k|
val = const_get k
val = val.respond_to?(:join) ? val.join(', ') : val.to_s
k_s = "#{k}_S".to_sym
const_set(k_s, val.freeze)
private_constant k_s
end
end
private_class_method :stringify_consts
extend Headers::Stringify

MAX_AGE = 86400
private_constant :MAX_AGE
Expand Down
31 changes: 31 additions & 0 deletions lib/3scale/backend/csp.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
require '3scale/backend/headers/stringify'

# CSP support
#
# Please see references:
#
# https://content-security-policy.com/
# https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/Sources
module ThreeScale
module Backend
module CSP
extend Headers::Stringify

CSP_VALUES = "default-src 'self'".freeze
private_constant :CSP_VALUES

CSP_HEADERS = {
'Content-Security-Policy'.freeze => CSP_VALUES
}.freeze
private_constant :CSP_HEADERS

stringify_consts :CSP_VALUES, :CSP_HEADERS

def self.headers
CSP_HEADERS
end
end
end
end
17 changes: 17 additions & 0 deletions lib/3scale/backend/headers/stringify.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
module ThreeScale
module Backend
module Headers
module Stringify
def stringify_consts(*consts)
consts.each do |k|
val = const_get k
val = val.respond_to?(:join) ? val.join(', ') : val.to_s
k_s = "#{k}_S".to_sym
const_set(k_s, val.freeze)
private_constant k_s
end
end
end
end
end
end
3 changes: 3 additions & 0 deletions lib/3scale/backend/listener.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
require '3scale/backend/version'
require '3scale/backend/cors'
require '3scale/backend/csp'
require 'json'

module ThreeScale
Expand Down Expand Up @@ -130,6 +131,8 @@ class Listener < Sinatra::Base
content_type 'application/vnd.3scale-v2.0+xml'.freeze
# enable CORS for all our endpoints
response.headers.merge!(CORS.headers)
# enable CSP for all our endpoints
response.headers.merge!(CSP.headers)
end

# Enable CORS pre-flight request for all our endpoints
Expand Down

0 comments on commit 112eae6

Please sign in to comment.