diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 57b38081c..011728793 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -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 diff --git a/app/controllers/deployments_controller.rb b/app/controllers/deployments_controller.rb index 16f6516a8..6e877b638 100644 --- a/app/controllers/deployments_controller.rb +++ b/app/controllers/deployments_controller.rb @@ -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 @@ -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 diff --git a/test/functional/deployments_controller_test.rb b/test/functional/deployments_controller_test.rb index 3bf2c8ea2..e8343232a 100644 --- a/test/functional/deployments_controller_test.rb +++ b/test/functional/deployments_controller_test.rb @@ -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 " + 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