From f74f42386029077d0f12ac407fc6ee39aaeeaf53 Mon Sep 17 00:00:00 2001
From: Lin Jen-Shin <godfat@godfat.org>
Date: Tue, 14 Jun 2016 22:17:01 +0800
Subject: [PATCH] Give 409 Conflict whenever the runner was already enabled

---
 CHANGELOG                         | 1 +
 app/models/ci/runner.rb           | 2 +-
 lib/api/runners.rb                | 7 +++++--
 spec/requests/api/runners_spec.rb | 2 +-
 4 files changed, 8 insertions(+), 4 deletions(-)

diff --git a/CHANGELOG b/CHANGELOG
index 3387394de5b..7abe41bc81d 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -40,6 +40,7 @@ v 8.9.0 (unreleased)
   - Added artifacts:when to .gitlab-ci.yml - this requires GitLab Runner 1.3
   - Todos will display target state if issuable target is 'Closed' or 'Merged'
   - Fix bug when sorting issues by milestone due date and filtering by two or more labels
+  - POST to API /projects/:id/runners/:runner_id would give 409 if the runner was already enabled for this project
   - Add support for using Yubikeys (U2F) for two-factor authentication
   - Link to blank group icon doesn't throw a 404 anymore
   - Remove 'main language' feature
diff --git a/app/models/ci/runner.rb b/app/models/ci/runner.rb
index 288e044fb86..a5a55e0a2cd 100644
--- a/app/models/ci/runner.rb
+++ b/app/models/ci/runner.rb
@@ -56,7 +56,7 @@ module Ci
     def assign_to(project, current_user = nil)
       self.is_shared = false if shared?
       self.save
-      project.runner_projects.create(runner_id: self.id)
+      project.runner_projects.create(runner_id: self.id).persisted?
     end
 
     def display_name
diff --git a/lib/api/runners.rb b/lib/api/runners.rb
index be92355d9a6..7bea4386e03 100644
--- a/lib/api/runners.rb
+++ b/lib/api/runners.rb
@@ -96,9 +96,12 @@ module API
 
         runner = get_runner(params[:runner_id])
         authenticate_enable_runner!(runner)
-        runner.assign_to(user_project)
 
-        present runner, with: Entities::Runner
+        if runner.assign_to(user_project)
+          present runner, with: Entities::Runner
+        else
+          conflict!("Runner was already enabled for this project")
+        end
       end
 
       # Disable project's runner
diff --git a/spec/requests/api/runners_spec.rb b/spec/requests/api/runners_spec.rb
index 73ae8ef631c..7aae0192fcb 100644
--- a/spec/requests/api/runners_spec.rb
+++ b/spec/requests/api/runners_spec.rb
@@ -375,7 +375,7 @@ describe API::Runners, api: true  do
         expect do
           post api("/projects/#{project.id}/runners", user), runner_id: specific_runner.id
         end.to change{ project.runners.count }.by(0)
-        expect(response.status).to eq(201)
+        expect(response.status).to eq(409)
       end
 
       it 'should not enable shared runner' do
-- 
GitLab