Skip to content

Commit 2345477

Browse files
Copilotfletchto99
andcommitted
Refactor: Extract helper method for removing upgrade_insecure_requests
Co-authored-by: fletchto99 <[email protected]>
1 parent 6595233 commit 2345477

File tree

1 file changed

+19
-13
lines changed

1 file changed

+19
-13
lines changed

lib/secure_headers.rb

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -150,19 +150,8 @@ def header_hash_for(request)
150150

151151
# Remove upgrade_insecure_requests from CSP headers for HTTP requests
152152
# as it doesn't make sense to upgrade requests when the page itself is served over HTTP
153-
if !config.csp.opt_out? && config.csp.directive_value(ContentSecurityPolicy::UPGRADE_INSECURE_REQUESTS)
154-
modified_csp_config = config.csp.dup
155-
modified_csp_config.update_directive(ContentSecurityPolicy::UPGRADE_INSECURE_REQUESTS, false)
156-
header_name, value = ContentSecurityPolicy.make_header(modified_csp_config)
157-
headers[header_name] = value if header_name && value
158-
end
159-
160-
if !config.csp_report_only.opt_out? && config.csp_report_only.directive_value(ContentSecurityPolicy::UPGRADE_INSECURE_REQUESTS)
161-
modified_csp_report_only_config = config.csp_report_only.dup
162-
modified_csp_report_only_config.update_directive(ContentSecurityPolicy::UPGRADE_INSECURE_REQUESTS, false)
163-
header_name, value = ContentSecurityPolicy.make_header(modified_csp_report_only_config)
164-
headers[header_name] = value if header_name && value
165-
end
153+
remove_upgrade_insecure_requests_from_csp!(headers, config.csp)
154+
remove_upgrade_insecure_requests_from_csp!(headers, config.csp_report_only)
166155
end
167156
headers
168157
end
@@ -259,6 +248,23 @@ def content_security_policy_nonce(request, script_or_style)
259248
def override_secure_headers_request_config(request, config)
260249
request.env[SECURE_HEADERS_CONFIG] = config
261250
end
251+
252+
# Private: removes upgrade_insecure_requests directive from a CSP config
253+
# if it's present, and updates the headers hash with the modified CSP.
254+
#
255+
# headers - the headers hash to update
256+
# csp_config - the CSP config to check and potentially modify
257+
#
258+
# Returns nothing (modifies headers in place)
259+
def remove_upgrade_insecure_requests_from_csp!(headers, csp_config)
260+
return if csp_config.opt_out?
261+
return unless csp_config.directive_value(ContentSecurityPolicy::UPGRADE_INSECURE_REQUESTS)
262+
263+
modified_config = csp_config.dup
264+
modified_config.update_directive(ContentSecurityPolicy::UPGRADE_INSECURE_REQUESTS, false)
265+
header_name, value = ContentSecurityPolicy.make_header(modified_config)
266+
headers[header_name] = value if header_name && value
267+
end
262268
end
263269

264270
# These methods are mixed into controllers and delegate to the class method

0 commit comments

Comments
 (0)