Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Raise exception on CSRF failure #1394

Merged
merged 1 commit into from
May 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@
: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