summaryrefslogtreecommitdiff
path: root/spec/models/project_services/jira_service_spec.rb
blob: 02060699e9a3a8ff3674bf21c1f2c294eb7dfd14 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
# frozen_string_literal: true

require 'spec_helper'

describe JiraService do
  include Gitlab::Routing
  include AssetsHelpers

  describe '#options' do
    let(:service) do
      described_class.new(
        project: build_stubbed(:project),
        active: true,
        username: 'username',
        password: 'test',
        jira_issue_transition_id: 24,
        url: 'http://jira.test.com/path/'
      )
    end

    it 'sets the URL properly' do
      # jira-ruby gem parses the URI and handles trailing slashes
      # fine: https://github.com/sumoheavy/jira-ruby/blob/v1.4.1/lib/jira/http_client.rb#L59
      expect(service.options[:site]).to eq('http://jira.test.com/')
    end

    it 'leaves out trailing slashes in context' do
      expect(service.options[:context_path]).to eq('/path')
    end
  end

  describe 'Associations' do
    it { is_expected.to belong_to :project }
    it { is_expected.to have_one :service_hook }
    it { is_expected.to allow_value(nil).for(:jira_issue_transition_id) }
    it { is_expected.to allow_value('1,2,3').for(:jira_issue_transition_id) }
    it { is_expected.to allow_value('1;2;3').for(:jira_issue_transition_id) }
    it { is_expected.not_to allow_value('a,b,cd').for(:jira_issue_transition_id) }
  end

  describe 'Validations' do
    context 'when service is active' do
      before do
        subject.active = true
      end

      it { is_expected.to validate_presence_of(:url) }
      it_behaves_like 'issue tracker service URL attribute', :url
    end

    context 'when service is inactive' do
      before do
        subject.active = false
      end

      it { is_expected.not_to validate_presence_of(:url) }
      it { is_expected.not_to validate_presence_of(:username) }
      it { is_expected.not_to validate_presence_of(:password) }
    end

    context 'validating urls' do
      let(:service) do
        described_class.new(
          project: create(:project),
          active: true,
          username: 'username',
          password: 'test',
          jira_issue_transition_id: 24,
          url: 'http://jira.test.com'
        )
      end

      it 'is valid when all fields have required values' do
        expect(service).to be_valid
      end

      it 'is not valid when url is not a valid url' do
        service.url = 'not valid'

        expect(service).not_to be_valid
      end

      it 'is not valid when api url is not a valid url' do
        service.api_url = 'not valid'

        expect(service).not_to be_valid
      end

      it 'is not valid when username is missing' do
        service.username = nil

        expect(service).not_to be_valid
      end

      it 'is not valid when password is missing' do
        service.password = nil

        expect(service).not_to be_valid
      end

      it 'is valid when api url is a valid url' do
        service.api_url = 'http://jira.test.com/api'

        expect(service).to be_valid
      end
    end
  end

  describe '.reference_pattern' do
    it_behaves_like 'allows project key on reference pattern'

    it 'does not allow # on the code' do
      expect(described_class.reference_pattern.match('#123')).to be_nil
      expect(described_class.reference_pattern.match('1#23#12')).to be_nil
    end
  end

  describe '#create' do
    let(:params) do
      {
        project: create(:project), title: 'custom title', description: 'custom description'
      }
    end

    subject { described_class.create(params) }

    it 'does not store title & description into properties' do
      expect(subject.properties.keys).not_to include('title', 'description')
    end

    it 'sets title & description correctly' do
      service = subject

      expect(service.title).to eq('custom title')
      expect(service.description).to eq('custom description')
    end
  end

  context 'overriding properties' do
    let(:url) { 'http://issue_tracker.example.com' }
    let(:access_params) do
      { url: url, username: 'username', password: 'password' }
    end

    # this  will be removed as part of https://gitlab.com/gitlab-org/gitlab-ce/issues/63084
    context 'when data are stored in properties' do
      let(:properties) { access_params.merge(title: title, description: description) }
      let(:service) do
        create(:jira_service, :without_properties_callback, properties: properties)
      end

      include_examples 'issue tracker fields'
    end

    context 'when data are stored in separated fields' do
      let(:service) do
        create(:jira_service, title: title, description: description, properties: access_params)
      end

      include_examples 'issue tracker fields'
    end

    context 'when data are stored in both properties and separated fields' do
      let(:properties) { access_params.merge(title: 'wrong title', description: 'wrong description') }
      let(:service) do
        create(:jira_service, :without_properties_callback, title: title, description: description, properties: properties)
      end

      include_examples 'issue tracker fields'
    end

    context 'when no title & description are set' do
      let(:service) do
        create(:jira_service, properties: access_params)
      end

      it 'returns default values' do
        expect(service.title).to eq('Jira')
        expect(service.description).to eq('Jira issue tracker')
      end
    end
  end

  describe '#close_issue' do
    let(:custom_base_url) { 'http://custom_url' }
    let(:user)    { create(:user) }
    let(:project) { create(:project, :repository) }

    shared_examples 'close_issue' do
      before do
        @jira_service = described_class.new
        allow(@jira_service).to receive_messages(
          project_id: project.id,
          project: project,
          service_hook: true,
          url: 'http://jira.example.com',
          username: 'gitlab_jira_username',
          password: 'gitlab_jira_password',
          jira_issue_transition_id: '999'
        )

        # These stubs are needed to test JiraService#close_issue.
        # We close the issue then do another request to API to check if it got closed.
        # Here is stubbed the API return with a closed and an opened issues.
        open_issue   = JIRA::Resource::Issue.new(@jira_service.client, attrs: { 'id' => 'JIRA-123' })
        closed_issue = open_issue.dup
        allow(open_issue).to receive(:resolution).and_return(false)
        allow(closed_issue).to receive(:resolution).and_return(true)
        allow(JIRA::Resource::Issue).to receive(:find).and_return(open_issue, closed_issue)

        allow_any_instance_of(JIRA::Resource::Issue).to receive(:key).and_return('JIRA-123')
        allow(JIRA::Resource::Remotelink).to receive(:all).and_return([])

        @jira_service.save

        project_issues_url = 'http://jira.example.com/rest/api/2/issue/JIRA-123'
        @transitions_url   = 'http://jira.example.com/rest/api/2/issue/JIRA-123/transitions'
        @comment_url       = 'http://jira.example.com/rest/api/2/issue/JIRA-123/comment'
        @remote_link_url   = 'http://jira.example.com/rest/api/2/issue/JIRA-123/remotelink'

        WebMock.stub_request(:get, project_issues_url).with(basic_auth: %w(gitlab_jira_username gitlab_jira_password))
        WebMock.stub_request(:post, @transitions_url).with(basic_auth: %w(gitlab_jira_username gitlab_jira_password))
        WebMock.stub_request(:post, @comment_url).with(basic_auth: %w(gitlab_jira_username gitlab_jira_password))
        WebMock.stub_request(:post, @remote_link_url).with(basic_auth: %w(gitlab_jira_username gitlab_jira_password))
      end

      it 'calls Jira API' do
        @jira_service.close_issue(resource, ExternalIssue.new('JIRA-123', project))

        expect(WebMock).to have_requested(:post, @comment_url).with(
          body: /Issue solved with/
        ).once
      end

      it 'does not fail if remote_link.all on issue returns nil' do
        allow(JIRA::Resource::Remotelink).to receive(:all).and_return(nil)

        expect { @jira_service.close_issue(resource, ExternalIssue.new('JIRA-123', project)) }
            .not_to raise_error
      end

      # Check https://developer.atlassian.com/jiradev/jira-platform/guides/other/guide-jira-remote-issue-links/fields-in-remote-issue-links
      # for more information
      it 'creates Remote Link reference in Jira for comment' do
        @jira_service.close_issue(resource, ExternalIssue.new('JIRA-123', project))

        favicon_path = "http://localhost/assets/#{find_asset('favicon.png').digest_path}"

        # Creates comment
        expect(WebMock).to have_requested(:post, @comment_url)
        # Creates Remote Link in Jira issue fields
        expect(WebMock).to have_requested(:post, @remote_link_url).with(
          body: hash_including(
            GlobalID: 'GitLab',
            relationship: 'mentioned on',
            object: {
              url: "#{Gitlab.config.gitlab.url}/#{project.full_path}/commit/#{commit_id}",
              title: "Solved by commit #{commit_id}.",
              icon: { title: 'GitLab', url16x16: favicon_path },
              status: { resolved: true }
            }
          )
        ).once
      end

      it 'does not send comment or remote links to issues already closed' do
        allow_any_instance_of(JIRA::Resource::Issue).to receive(:resolution).and_return(true)

        @jira_service.close_issue(resource, ExternalIssue.new('JIRA-123', project))

        expect(WebMock).not_to have_requested(:post, @comment_url)
        expect(WebMock).not_to have_requested(:post, @remote_link_url)
      end

      it 'does not send comment or remote links to issues with unknown resolution' do
        allow_any_instance_of(JIRA::Resource::Issue).to receive(:respond_to?).with(:resolution).and_return(false)

        @jira_service.close_issue(resource, ExternalIssue.new('JIRA-123', project))

        expect(WebMock).not_to have_requested(:post, @comment_url)
        expect(WebMock).not_to have_requested(:post, @remote_link_url)
      end

      it 'references the GitLab commit' do
        stub_config_setting(base_url: custom_base_url)

        @jira_service.close_issue(resource, ExternalIssue.new('JIRA-123', project))

        expect(WebMock).to have_requested(:post, @comment_url).with(
          body: %r{#{custom_base_url}/#{project.full_path}/commit/#{commit_id}}
        ).once
      end

      it 'references the GitLab commit' do
        stub_config_setting(relative_url_root: '/gitlab')
        stub_config_setting(url: Settings.send(:build_gitlab_url))

        allow(described_class).to receive(:default_url_options) do
          { script_name: '/gitlab' }
        end

        @jira_service.close_issue(resource, ExternalIssue.new('JIRA-123', project))

        expect(WebMock).to have_requested(:post, @comment_url).with(
          body: %r{#{Gitlab.config.gitlab.url}/#{project.full_path}/commit/#{commit_id}}
        ).once
      end

      it 'logs exception when transition id is not valid' do
        allow(@jira_service).to receive(:log_error)
        WebMock.stub_request(:post, @transitions_url).with(basic_auth: %w(gitlab_jira_username gitlab_jira_password)).and_raise("Bad Request")

        @jira_service.close_issue(resource, ExternalIssue.new('JIRA-123', project))

        expect(@jira_service).to have_received(:log_error).with("Issue transition failed", error: "Bad Request", client_url: "http://jira.example.com")
      end

      it 'calls the api with jira_issue_transition_id' do
        @jira_service.close_issue(resource, ExternalIssue.new('JIRA-123', project))

        expect(WebMock).to have_requested(:post, @transitions_url).with(
          body: /999/
        ).once
      end

      context 'when have multiple transition ids' do
        it 'calls the api with transition ids separated by comma' do
          allow(@jira_service).to receive_messages(jira_issue_transition_id: '1,2,3')

          @jira_service.close_issue(resource, ExternalIssue.new('JIRA-123', project))

          1.upto(3) do |transition_id|
            expect(WebMock).to have_requested(:post, @transitions_url).with(
              body: /#{transition_id}/
            ).once
          end
        end

        it 'calls the api with transition ids separated by semicolon' do
          allow(@jira_service).to receive_messages(jira_issue_transition_id: '1;2;3')

          @jira_service.close_issue(resource, ExternalIssue.new('JIRA-123', project))

          1.upto(3) do |transition_id|
            expect(WebMock).to have_requested(:post, @transitions_url).with(
              body: /#{transition_id}/
            ).once
          end
        end
      end
    end

    context 'when resource is a merge request' do
      let(:resource) { create(:merge_request) }
      let(:commit_id) { resource.diff_head_sha }

      it_behaves_like 'close_issue'
    end

    context 'when resource is a commit' do
      let(:resource) { project.commit('master') }
      let(:commit_id) { resource.id }

      it_behaves_like 'close_issue'
    end
  end

  describe '#test_settings' do
    let(:jira_service) do
      described_class.new(
        project: create(:project),
        url: 'http://jira.example.com',
        username: 'jira_username',
        password: 'jira_password'
      )
    end

    def test_settings(api_url = nil)
      api_url ||= 'jira.example.com'
      test_url = "http://#{api_url}/rest/api/2/serverInfo"

      WebMock.stub_request(:get, test_url).with(basic_auth: %w(jira_username jira_password)).to_return(body: { url: 'http://url' }.to_json )

      jira_service.test(nil)
    end

    context 'when the test succeeds' do
      it 'tries to get Jira project with URL when API URL not set' do
        test_settings('jira.example.com')
      end

      it 'returns correct result' do
        expect(test_settings).to eq( { success: true, result: { 'url' => 'http://url' } })
      end

      it 'tries to get Jira project with API URL if set' do
        jira_service.update(api_url: 'http://jira.api.com')
        test_settings('jira.api.com')
      end
    end

    context 'when the test fails' do
      it 'returns result with the error' do
        test_url = 'http://jira.example.com/rest/api/2/serverInfo'
        WebMock.stub_request(:get, test_url).with(basic_auth: %w(jira_username jira_password))
          .to_raise(JIRA::HTTPError.new(double(message: 'Some specific failure.')))

        expect(jira_service.test(nil)).to eq( { success: false, result: 'Some specific failure.' })
      end
    end
  end

  describe 'Stored password invalidation' do
    let(:project) { create(:project) }

    context 'when a password was previously set' do
      before do
        @jira_service = described_class.create!(
          project: project,
          properties: {
            url: 'http://jira.example.com/web',
            username: 'mic',
            password: 'password'
          }
        )
      end

      context 'when only web url present' do
        it 'reset password if url changed' do
          @jira_service.url = 'http://jira_edited.example.com/rest/api/2'
          @jira_service.save

          expect(@jira_service.password).to be_nil
        end

        it 'reset password if url not changed but api url added' do
          @jira_service.api_url = 'http://jira_edited.example.com/rest/api/2'
          @jira_service.save

          expect(@jira_service.password).to be_nil
        end
      end

      context 'when both web and api url present' do
        before do
          @jira_service.api_url = 'http://jira.example.com/rest/api/2'
          @jira_service.password = 'password'

          @jira_service.save
        end
        it 'reset password if api url changed' do
          @jira_service.api_url = 'http://jira_edited.example.com/rest/api/2'
          @jira_service.save

          expect(@jira_service.password).to be_nil
        end

        it 'does not reset password if url changed' do
          @jira_service.url = 'http://jira_edited.example.com/rweb'
          @jira_service.save

          expect(@jira_service.password).to eq('password')
        end

        it 'reset password if api url set to empty' do
          @jira_service.api_url = ''
          @jira_service.save

          expect(@jira_service.password).to be_nil
        end
      end

      it 'does not reset password if username changed' do
        @jira_service.username = 'some_name'
        @jira_service.save

        expect(@jira_service.password).to eq('password')
      end

      it 'does not reset password if new url is set together with password, even if it\'s the same password' do
        @jira_service.url = 'http://jira_edited.example.com/rest/api/2'
        @jira_service.password = 'password'
        @jira_service.save

        expect(@jira_service.password).to eq('password')
        expect(@jira_service.url).to eq('http://jira_edited.example.com/rest/api/2')
      end

      it 'resets password if url changed, even if setter called multiple times' do
        @jira_service.url = 'http://jira1.example.com/rest/api/2'
        @jira_service.url = 'http://jira1.example.com/rest/api/2'
        @jira_service.save
        expect(@jira_service.password).to be_nil
      end
    end

    context 'when no password was previously set' do
      before do
        @jira_service = described_class.create(
          project: project,
          properties: {
            url: 'http://jira.example.com/rest/api/2',
            username: 'mic'
          }
        )
      end

      it 'saves password if new url is set together with password' do
        @jira_service.url = 'http://jira_edited.example.com/rest/api/2'
        @jira_service.password = 'password'
        @jira_service.save
        expect(@jira_service.password).to eq('password')
        expect(@jira_service.url).to eq('http://jira_edited.example.com/rest/api/2')
      end
    end
  end

  describe 'description and title' do
    let(:title) { 'Jira One' }
    let(:description) { 'Jira One issue tracker' }
    let(:properties) do
      {
        url: 'http://jira.example.com/web',
        username: 'mic',
        password: 'password',
        title: title,
        description: description
      }
    end

    context 'when it is not set' do
      it 'default values are returned' do
        service = create(:jira_service)

        expect(service.title).to eq('Jira')
        expect(service.description).to eq('Jira issue tracker')
      end
    end

    context 'when it is set in properties' do
      it 'values from properties are returned' do
        service = create(:jira_service, properties: properties)

        expect(service.title).to eq(title)
        expect(service.description).to eq(description)
      end
    end

    context 'when it is in title & description fields' do
      it 'values from title and description fields are returned' do
        service = create(:jira_service, title: title, description: description)

        expect(service.title).to eq(title)
        expect(service.description).to eq(description)
      end
    end

    context 'when it is in both properites & title & description fields' do
      it 'values from title and description fields are returned' do
        title2 = 'Jira 2'
        description2 = 'Jira description 2'

        service = create(:jira_service, title: title2, description: description2, properties: properties)

        expect(service.title).to eq(title2)
        expect(service.description).to eq(description2)
      end
    end
  end

  describe 'additional cookies' do
    let(:project) { create(:project) }

    context 'provides additional cookies to allow basic auth with oracle webgate' do
      before do
        @service = project.create_jira_service(
          active: true, properties: { url: 'http://jira.com' })
      end

      after do
        @service.destroy!
      end

      it 'is initialized' do
        expect(@service.options[:use_cookies]).to eq(true)
        expect(@service.options[:additional_cookies]).to eq(['OBBasicAuth=fromDialog'])
      end
    end
  end

  describe 'project and issue urls' do
    context 'when gitlab.yml was initialized' do
      it 'is prepopulated with the settings' do
        settings = {
          'jira' => {
            'url' => 'http://jira.sample/projects/project_a',
            'api_url' => 'http://jira.sample/api'
          }
        }
        allow(Gitlab.config).to receive(:issues_tracker).and_return(settings)

        project = create(:project)
        service = project.create_jira_service(active: true)

        expect(service.properties['url']).to eq('http://jira.sample/projects/project_a')
        expect(service.properties['api_url']).to eq('http://jira.sample/api')
      end
    end

    it 'removes trailing slashes from url' do
      service = described_class.new(url: 'http://jira.test.com/path/')

      expect(service.url).to eq('http://jira.test.com/path')
    end
  end

  describe 'favicon urls', :request_store do
    it 'includes the standard favicon' do
      props = described_class.new.send(:build_remote_link_props, url: 'http://example.com', title: 'title')
      expect(props[:object][:icon][:url16x16]).to match %r{^http://localhost/assets/favicon(?:-\h+).png$}
    end

    it 'includes returns the custom favicon' do
      create :appearance, favicon: fixture_file_upload('spec/fixtures/dk.png')

      props = described_class.new.send(:build_remote_link_props, url: 'http://example.com', title: 'title')
      expect(props[:object][:icon][:url16x16]).to match %r{^http://localhost/uploads/-/system/appearance/favicon/\d+/dk.png$}
    end
  end

  context 'generating external URLs' do
    let(:service) { described_class.new(url: 'http://jira.test.com/path/') }

    describe '#issues_url' do
      it 'handles trailing slashes' do
        expect(service.issues_url).to eq('http://jira.test.com/path/browse/:id')
      end
    end

    describe '#new_issue_url' do
      it 'handles trailing slashes' do
        expect(service.new_issue_url).to eq('http://jira.test.com/path/secure/CreateIssue.jspa')
      end
    end
  end
end