discourse/app/controllers/csp_reports_controller.rb
Sam 9361d9a587
FIX: stop logging blank and invalid CSP reports (#17144)
Certain rogue bots such as Yandex may send across invalid CSP reports
when CSP report collection is enabled.

This ensures that invalid reports will not cause log floods and simply
returns a 422 error.

Co-authored-by: Alan Guo Xiang Tan <gxtan1990@gmail.com>
2022-06-20 16:57:46 +10:00

51 lines
1.2 KiB
Ruby

# frozen_string_literal: true
class CspReportsController < ApplicationController
skip_before_action :check_xhr, :preload_json, :verify_authenticity_token, only: [:create]
def create
raise Discourse::NotFound unless report_collection_enabled?
report = parse_report
if report.blank?
render_json_error("empty CSP report", status: 422)
else
Logster.add_to_env(request.env, 'CSP Report', report)
Rails.logger.warn("CSP Violation: '#{report['blocked-uri']}' \n\n#{report['script-sample']}")
head :ok
end
rescue JSON::ParserError
render_json_error("invalid CSP report", status: 422)
end
private
def parse_report
obj = JSON.parse(request.body.read)
if Hash === obj
obj = obj['csp-report']
if Hash === obj
obj.slice(
'blocked-uri',
'disposition',
'document-uri',
'effective-directive',
'original-policy',
'referrer',
'script-sample',
'status-code',
'violated-directive',
'line-number',
'source-file'
)
end
end
end
def report_collection_enabled?
SiteSetting.content_security_policy_collect_reports
end
end