Skip to content

Commit

Permalink
Merge pull request #1394 from alphagov/raise-exception-on-forged-requ…
Browse files Browse the repository at this point in the history
…ests

Raise exception on CSRF failure
  • Loading branch information
AgaDufrat authored May 20, 2024
2 parents 27ca329 + 201b97b commit cad067f
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
2 changes: 1 addition & 1 deletion app/controllers/application_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ class ApplicationController < ActionController::Base

before_action :authenticate_user!

protect_from_forgery
protect_from_forgery with: :exception

def error_400
error 400
Expand Down
6 changes: 6 additions & 0 deletions app/controllers/deployments_controller.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
class DeploymentsController < ApplicationController
class ApplicationConflictError < RuntimeError; end

skip_forgery_protection if: :api_request_to_create_deployment?

rescue_from ApplicationConflictError do
head :conflict
end
Expand Down Expand Up @@ -73,4 +75,8 @@ def recent_deployment_params
:environment_filter,
)
end

def api_request_to_create_deployment?
GDS::SSO::ApiAccess.api_call?(request.env) && action_name == "create"
end
end
19 changes: 19 additions & 0 deletions test/functional/deployments_controller_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,25 @@ class DeploymentsControllerTest < ActionController::TestCase
end

context "POST create" do
context "when forgery protection is enabled" do
setup do
@controller.allow_forgery_protection = true
end

should "enable forgery protection for non-API requests" do
assert_raises(ActionController::InvalidAuthenticityToken) do
post :create, params: { repo: "org/app", deployment: { version: "1", environment: "env" } }
end
end

should "skip forgery protection for API requests" do
request.headers["Authorization"] = "Bearer <token>"
post :create, params: { repo: "org/app", deployment: { version: "1", environment: "env" } }

assert_response :ok
end
end

setup do
stub_request(:get, "http://docs.publishing.service.gov.uk/apps.json").to_return(status: 200, body: "", headers: {})
end
Expand Down

0 comments on commit cad067f

Please sign in to comment.