何かやってみるブログ

興味をもったこと、趣味のこと、技術について色々書きます。

[Railsメモ] report-uriディレクティブでCSPに違反がある場合にJSONがpostされるかどうかを確かめる。

developer.mozilla.org

CSPのreport-uriディレクティブに設定したURLにPOSTしてくれるらしいので確かめる。 今回も自分のsandboxのリポジトリで試した。

Railsガイドに書いてあるように設定をして、違反がある場合は /csp-violation-report にリクエストをするように設定した。CSPのdefault-srcなどのディレクティブはデフォルトでコメントアウトしてあるものをそのままコメントインした。

準備

diff --git a/app/controllers/csp_violation_report_controller.rb b/app/controllers/csp_violation_report_controller.rb
new file mode 100644
index 0000000..143b9a7
--- /dev/null
+++ b/app/controllers/csp_violation_report_controller.rb
@@ -0,0 +1,7 @@
+class CspViolationReportController < ApplicationController
+  skip_before_action :verify_authenticity_token
+  def receive
+    logger.debug(request.body.to_json)
+    head :no_content
+  end
+end
diff --git a/config/initializers/content_security_policy.rb b/config/initializers/content_security_policy.rb
index 497f566..e6f679e 100644
--- a/config/initializers/content_security_policy.rb
+++ b/config/initializers/content_security_policy.rb
@@ -5,17 +5,17 @@
 # For further information see the following documentation
 # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy

-# Rails.application.config.content_security_policy do |policy|
-#   policy.default_src :self, :https
-#   policy.font_src    :self, :https, :data
-#   policy.img_src     :self, :https, :data
-#   policy.object_src  :none
-#   policy.script_src  :self, :https
-#   policy.style_src   :self, :https
+ Rails.application.config.content_security_policy do |policy|
+   policy.default_src :self, :https
+   policy.font_src    :self, :https, :data
+   policy.img_src     :self, :https, :data
+   policy.object_src  :none
+   policy.script_src  :self, :https
+   policy.style_src   :self, :https

-#   # Specify URI for violation reports
-#   # policy.report_uri "/csp-violation-report-endpoint"
-# end
+   # Specify URI for violation reports
+   policy.report_uri "/csp-violation-report"
+ end

 # If you are using UJS then enable automatic nonce generation
 # Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
diff --git a/config/routes.rb b/config/routes.rb
index 88645f2..8bce20a 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -21,6 +21,7 @@ Rails.application.routes.draw do
     invitations: 'users/invitations'
   }
   resources :users, only: %i[show edit update destroy]
+  post '/csp-violation-report', to: 'csp_violation_report#receive'
   get '/services', to: 'home#service'
   get '/privacys', to: 'home#privacy'
 end

CSP違反が発生した。

確認

curlでリクエストしてHTTPヘッダーを確認したところContent-Security-Policyヘッダーが設定されていることを確認した。

curl -I http://localhost:3001
HTTP/1.1 200 OK
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Download-Options: noopen
X-Permitted-Cross-Domain-Policies: none
Referrer-Policy: strict-origin-when-cross-origin
Content-Type: text/html; charset=utf-8
Vary: Accept
Cache-Control: no-store, must-revalidate, private, max-age=0
Content-Security-Policy: default-src 'self' https:; font-src 'self' https: data:; img-src 'self' https: data:; object-src 'none'; script-src 'self' https:; style-src 'self' https:; report-uri /csp-violation-report
Set-Cookie: _accouts_keeper_session=IqIWrSfidV4YY%2FrEqZMl2tseyCVhSoSskREliNSRSPqKcjV%2FXDx6zDDiOsD27G4svaZPM1YlnuxkLqy2n18VsNPcUo9RgQeY%2BXhG8ZtfJAsV5S8heS9MUfRdk9TMY1npHsts8k9efohTUprirqIkSKJtHo4RLLwLTqS%2F9b04VJCQqAhq35AoBkdkMt9Dp66mAbyVMr2nHQmVhWfJ6xUgerAoir45mKrHl0P0vP74r3hdg9VCuJt%2FHljKv4jpuxVUMfWjLtUpWgEB8h%2B79pWQr6pgSisPya0BfwfXuqBHYDxD4mVBKDk3vzGWGJmj3gWrjy7gZJI1aA%3D%3D--8SPcsgX%2BI2o9ttsP--pkqJILQwuzpi1o05sR%2FkNw%3D%3D; path=/; HttpOnly
Set-Cookie: __profilin=p%3Dt; path=/; HttpOnly; SameSite=Lax
X-Request-Id: 6152515d-8e6e-43cb-8acf-ff88b18c531d[f:id:s-takaya1027:20230729202750p:plain]
X-Runtime: 0.175956
X-MiniProfiler-Original-Cache-Control: max-age=0, private, must-revalidate
X-MiniProfiler-Ids: 9uchrof6nx49n6sps0vy,fqxzp8o8xpnl05n5bocv,r007a5frkdjmi8pvdxn1,jg0nr9q46z39gliy8yu8,h7oytqja0hn04c2s55kj,xkptcb94itkj3vwh4fyp

RailsのログでPOSTリクエストがあったことを確認した。 下記はログの一部

accounts_keepr-web-1  | Processing by CspViolationReportController#receive as */*
accounts_keepr-web-1  | ["{\"csp-report\":{\"document-uri\":\"http://localhost:3001/\",\"referrer\":\"\",\"violated-directive\":\"style-src-elem\",\"effective-directive\":\"style-src-elem\",\"original-policy\":\"default-src 'self' https:; font-src 'self' https: data:; img-src 'self' https: data:; object-src 'none'; script-src 'self' https:; style-src 'self' https:; report-uri /csp-violation-report\",\"disposition\":\"enforce\",\"blocked-uri\":\"http://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css\",\"line-number\":63,\"source-file\":\"http://localhost:3001/\",\"status-code\":200,\"script-sample\":\"\"}}"]
accounts_keepr-web-1  | Processing by CspViolationReportController#receive as */*
accounts_keepr-web-1  | Completed 204 No Content in 1ms (Allocations: 734)