summaryrefslogtreecommitdiff
path: root/spec/requests/api/invitations_spec.rb
blob: d093894720e9cb93f8d5895992d44518ade1f7e3 (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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe API::Invitations do
  let_it_be(:maintainer) { create(:user, username: 'maintainer_user') }
  let_it_be(:developer) { create(:user) }
  let_it_be(:access_requester) { create(:user) }
  let_it_be(:stranger) { create(:user) }
  let(:email) { 'email1@example.com' }
  let(:email2) { 'email2@example.com' }

  let_it_be(:project, reload: true) do
    create(:project, :public, creator_id: maintainer.id, namespace: maintainer.namespace) do |project|
      project.add_developer(developer)
      project.add_maintainer(maintainer)
      project.request_access(access_requester)
    end
  end

  let_it_be(:group, reload: true) do
    create(:group, :public) do |group|
      group.add_developer(developer)
      group.add_owner(maintainer)
      group.request_access(access_requester)
    end
  end

  def invitations_url(source, user)
    api("/#{source.model_name.plural}/#{source.id}/invitations", user)
  end

  def invite_member_by_email(source, source_type, email, created_by)
    create(:"#{source_type}_member", invite_token: '123', invite_email: email, source: source, user: nil, created_by: created_by)
  end

  shared_examples 'POST /:source_type/:id/invitations' do |source_type|
    context "with :source_type == #{source_type.pluralize}" do
      it_behaves_like 'a 404 response when source is private' do
        let(:route) do
          post invitations_url(source, stranger),
               params: { email: email, access_level: Member::MAINTAINER }
        end
      end

      context 'when authenticated as a non-member or member with insufficient rights' do
        %i[access_requester stranger developer].each do |type|
          context "as a #{type}" do
            it 'returns 403' do
              user = public_send(type)

              post invitations_url(source, user), params: { email: email, access_level: Member::MAINTAINER }

              expect(response).to have_gitlab_http_status(:forbidden)
            end
          end
        end
      end

      context 'when authenticated as a maintainer/owner' do
        context 'and new member is already a requester' do
          it 'does not transform the requester into a proper member' do
            expect do
              post invitations_url(source, maintainer),
                   params: { email: access_requester.email, access_level: Member::MAINTAINER }

              expect(response).to have_gitlab_http_status(:created)
            end.not_to change { source.members.count }
          end
        end

        it 'adds a new member by email' do
          expect do
            post invitations_url(source, maintainer),
                 params: { email: email, access_level: Member::DEVELOPER }

            expect(response).to have_gitlab_http_status(:created)
          end.to change { source.members.invite.count }.by(1)
        end

        it 'adds a new member by user_id' do
          expect do
            post invitations_url(source, maintainer),
                 params: { user_id: stranger.id, access_level: Member::DEVELOPER }

            expect(response).to have_gitlab_http_status(:created)
          end.to change { source.members.non_invite.count }.by(1)
        end

        it 'adds new members with email and user_id' do
          expect do
            post invitations_url(source, maintainer),
                 params: { email: email, user_id: stranger.id, access_level: Member::DEVELOPER }

            expect(response).to have_gitlab_http_status(:created)
          end.to change { source.members.invite.count }.by(1).and change { source.members.non_invite.count }.by(1)
        end

        it 'invites a list of new email addresses' do
          expect do
            email_list = [email, email2].join(',')

            post invitations_url(source, maintainer),
                 params: { email: email_list, access_level: Member::DEVELOPER }

            expect(response).to have_gitlab_http_status(:created)
          end.to change { source.members.invite.count }.by(2)
        end

        it 'invites a list of new email addresses and user ids' do
          expect do
            stranger2 = create(:user)
            email_list = [email, email2].join(',')
            user_id_list = "#{stranger.id},#{stranger2.id}"

            post invitations_url(source, maintainer),
                 params: { email: email_list, user_id: user_id_list, access_level: Member::DEVELOPER }

            expect(response).to have_gitlab_http_status(:created)
          end.to change { source.members.invite.count }.by(2).and change { source.members.non_invite.count }.by(2)
        end
      end

      context 'access levels' do
        it 'does not create the member if group level is higher' do
          parent = create(:group)

          group.update!(parent: parent)
          project.update!(group: group)
          parent.add_developer(stranger)

          post invitations_url(source, maintainer),
               params: { email: stranger.email, access_level: Member::REPORTER }

          expect(response).to have_gitlab_http_status(:created)
          expect(json_response['message'][stranger.email])
            .to eq("Access level should be greater than or equal to Developer inherited membership from group #{parent.name}")
        end

        it 'creates the member if group level is lower' do
          parent = create(:group)

          group.update!(parent: parent)
          project.update!(group: group)
          parent.add_developer(stranger)

          post invitations_url(source, maintainer),
               params: { email: stranger.email, access_level: Member::MAINTAINER }

          expect(response).to have_gitlab_http_status(:created)
        end
      end

      context 'access expiry date' do
        subject do
          post invitations_url(source, maintainer),
               params: { email: email, access_level: Member::DEVELOPER, expires_at: expires_at }
        end

        context 'when set to a date in the past' do
          let(:expires_at) { 2.days.ago.to_date }

          it 'does not create a member' do
            expect do
              subject
            end.not_to change { source.members.count }

            expect(response).to have_gitlab_http_status(:created)
            expect(json_response['message'][email]).to eq('Expires at cannot be a date in the past')
          end
        end

        context 'when set to a date in the future' do
          let(:expires_at) { 2.days.from_now.to_date }

          it 'invites a member' do
            expect do
              subject
            end.to change { source.members.invite.count }.by(1)

            expect(response).to have_gitlab_http_status(:created)
          end
        end
      end

      context 'with tasks_to_be_done and tasks_project_id in the params' do
        let(:project_id) { source_type == 'project' ? source.id : create(:project, namespace: source).id }

        context 'when there is 1 invitation' do
          it 'creates a member_task with the tasks_to_be_done and the project' do
            post invitations_url(source, maintainer),
                 params: { email: email, access_level: Member::DEVELOPER, tasks_to_be_done: %w(code ci), tasks_project_id: project_id }

            member = source.members.find_by(invite_email: email)
            expect(member.tasks_to_be_done).to match_array([:code, :ci])
            expect(member.member_task.project_id).to eq(project_id)
          end
        end

        context 'when there are multiple invitations' do
          it 'creates a member_task with the tasks_to_be_done and the project' do
            post invitations_url(source, maintainer),
                 params: { email: [email, email2].join(','), access_level: Member::DEVELOPER, tasks_to_be_done: %w(code ci), tasks_project_id: project_id }

            members = source.members.where(invite_email: [email, email2])
            members.each do |member|
              expect(member.tasks_to_be_done).to match_array([:code, :ci])
              expect(member.member_task.project_id).to eq(project_id)
            end
          end
        end
      end

      context 'with invite_source considerations', :snowplow do
        let(:params) { { email: email, access_level: Member::DEVELOPER } }

        it 'tracks the invite source as api' do
          post invitations_url(source, maintainer), params: params

          expect_snowplow_event(
            category: 'Members::InviteService',
            action: 'create_member',
            label: 'invitations-api',
            property: 'net_new_user',
            user: maintainer
          )
        end

        it 'tracks the invite source from params' do
          post invitations_url(source, maintainer), params: params.merge(invite_source: '_invite_source_')

          expect_snowplow_event(
            category: 'Members::InviteService',
            action: 'create_member',
            label: '_invite_source_',
            property: 'net_new_user',
            user: maintainer
          )
        end
      end

      context 'when adding project bot' do
        let_it_be(:project_bot) { create(:user, :project_bot) }

        before do
          unrelated_project = create(:project)
          unrelated_project.add_maintainer(project_bot)
        end

        it 'returns error' do
          expect do
            post invitations_url(source, maintainer),
                 params: { email: project_bot.email, access_level: Member::DEVELOPER }

            expect(json_response['status']).to eq 'error'
            expect(json_response['message'][project_bot.email]).to include('User project bots cannot be added to other groups / projects')
          end.not_to change { source.members.count }
        end
      end

      it "returns a message if member already exists" do
        post invitations_url(source, maintainer),
             params: { email: developer.email, access_level: Member::MAINTAINER }

        expect(response).to have_gitlab_http_status(:created)
        expect(json_response['message'][developer.email]).to eq("User already exists in source")
      end

      it 'returns 400 when the invite params of email and user_id are not sent' do
        post invitations_url(source, maintainer),
             params: { access_level: Member::MAINTAINER }

        expect(response).to have_gitlab_http_status(:bad_request)
        expect(json_response['message']).to eq('400 Bad request - Must provide either email or user_id as a parameter')
      end

      it 'returns 400 when the email is blank' do
        post invitations_url(source, maintainer),
             params: { email: '', access_level: Member::MAINTAINER }

        expect(response).to have_gitlab_http_status(:bad_request)
        expect(json_response['message']).to eq('400 Bad request - Must provide either email or user_id as a parameter')
      end

      it 'returns 400 when the user_id is blank' do
        post invitations_url(source, maintainer),
             params: { user_id: '', access_level: Member::MAINTAINER }

        expect(response).to have_gitlab_http_status(:bad_request)
        expect(json_response['message']).to eq('400 Bad request - Must provide either email or user_id as a parameter')
      end

      it 'returns 400 when the email list is not a valid format' do
        post invitations_url(source, maintainer),
             params: { email: 'email1@example.com,not-an-email', access_level: Member::MAINTAINER }

        expect(response).to have_gitlab_http_status(:bad_request)
        expect(json_response['error']).to eq('email contains an invalid email address')
      end

      it 'returns 400 when access_level is not given' do
        post invitations_url(source, maintainer),
             params: { email: email }

        expect(response).to have_gitlab_http_status(:bad_request)
      end

      it 'returns 400 when access_level is not valid' do
        post invitations_url(source, maintainer),
             params: { email: email, access_level: non_existing_record_access_level }

        expect(response).to have_gitlab_http_status(:bad_request)
      end
    end
  end

  describe 'POST /projects/:id/invitations' do
    it_behaves_like 'POST /:source_type/:id/invitations', 'project' do
      let(:source) { project }
    end

    it 'records queries', :request_store, :use_sql_query_cache do
      post invitations_url(project, maintainer), params: { email: email, access_level: Member::DEVELOPER }

      control = ActiveRecord::QueryRecorder.new(skip_cached: false) do
        post invitations_url(project, maintainer), params: { email: email2, access_level: Member::DEVELOPER }
      end

      emails = 'email3@example.com,email4@example.com,email5@example.com,email6@example.com,email7@example.com'

      unresolved_n_plus_ones = 44 # old 48 with 12 per new email, currently there are 11 queries added per email

      expect do
        post invitations_url(project, maintainer), params: { email: emails, access_level: Member::DEVELOPER }
      end.not_to exceed_all_query_limit(control.count).with_threshold(unresolved_n_plus_ones)
    end

    it 'records queries with secondary emails', :request_store, :use_sql_query_cache do
      create(:email, email: email, user: create(:user))

      post invitations_url(project, maintainer), params: { email: email, access_level: Member::DEVELOPER }

      create(:email, email: email2, user: create(:user))

      control = ActiveRecord::QueryRecorder.new(skip_cached: false) do
        post invitations_url(project, maintainer), params: { email: email2, access_level: Member::DEVELOPER }
      end

      create(:email, email: 'email4@example.com', user: create(:user))
      create(:email, email: 'email6@example.com', user: create(:user))

      emails = 'email3@example.com,email4@example.com,email5@example.com,email6@example.com,email7@example.com'

      unresolved_n_plus_ones = 67 # currently there are 11 queries added per email

      expect do
        post invitations_url(project, maintainer), params: { email: emails, access_level: Member::DEVELOPER }
      end.not_to exceed_all_query_limit(control.count).with_threshold(unresolved_n_plus_ones)
    end
  end

  describe 'POST /groups/:id/invitations' do
    it_behaves_like 'POST /:source_type/:id/invitations', 'group' do
      let(:source) { group }
    end

    it 'records queries', :request_store, :use_sql_query_cache do
      post invitations_url(group, maintainer), params: { email: email, access_level: Member::DEVELOPER }

      control = ActiveRecord::QueryRecorder.new(skip_cached: false) do
        post invitations_url(group, maintainer), params: { email: email2, access_level: Member::DEVELOPER }
      end

      emails = 'email3@example.com,email4@example.com,email5@example.com,email6@example.com,email7@example.com'

      unresolved_n_plus_ones = 36 # old 40 with 10 per new email, currently there are 9 queries added per email

      expect do
        post invitations_url(group, maintainer), params: { email: emails, access_level: Member::DEVELOPER }
      end.not_to exceed_all_query_limit(control.count).with_threshold(unresolved_n_plus_ones)
    end

    it 'records queries with secondary emails', :request_store, :use_sql_query_cache do
      create(:email, email: email, user: create(:user))

      post invitations_url(group, maintainer), params: { email: email, access_level: Member::DEVELOPER }

      create(:email, email: email2, user: create(:user))

      control = ActiveRecord::QueryRecorder.new(skip_cached: false) do
        post invitations_url(group, maintainer), params: { email: email2, access_level: Member::DEVELOPER }
      end

      create(:email, email: 'email4@example.com', user: create(:user))
      create(:email, email: 'email6@example.com', user: create(:user))

      emails = 'email3@example.com,email4@example.com,email5@example.com,email6@example.com,email7@example.com'

      unresolved_n_plus_ones = 62 # currently there are 9 queries added per email

      expect do
        post invitations_url(group, maintainer), params: { email: emails, access_level: Member::DEVELOPER }
      end.not_to exceed_all_query_limit(control.count).with_threshold(unresolved_n_plus_ones)
    end
  end

  shared_examples 'GET /:source_type/:id/invitations' do |source_type|
    context "with :source_type == #{source_type.pluralize}" do
      it_behaves_like 'a 404 response when source is private' do
        let(:route) { get invitations_url(source, stranger) }
      end

      context "when authenticated as a maintainer" do
        it 'returns 200' do
          get invitations_url(source, maintainer)

          expect(response).to have_gitlab_http_status(:ok)
          expect(response).to include_pagination_headers
          expect(json_response).to be_an Array
          expect(json_response.size).to eq(0)
        end
      end

      %i[developer access_requester stranger].each do |type|
        context "when authenticated as a #{type}" do
          it 'returns 403' do
            user = public_send(type)

            get invitations_url(source, user)

            expect(response).to have_gitlab_http_status(:forbidden)
          end
        end
      end

      it 'does not find confirmed members' do
        get invitations_url(source, maintainer)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(json_response.size).to eq(0)
        expect(json_response.map { |u| u['id'] }).not_to match_array [maintainer.id, developer.id]
      end

      it 'finds all members with no query string specified' do
        invite_member_by_email(source, source_type, email, maintainer)
        invite_member_by_email(source, source_type, email2, maintainer)

        get invitations_url(source, maintainer), params: { query: '' }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers

        expect(json_response).to be_an Array
        expect(json_response.count).to eq(2)
        expect(json_response.map { |u| u['invite_email'] }).to match_array [email, email2]
      end

      it 'finds the invitation by invite_email with query string' do
        invite_member_by_email(source, source_type, email, maintainer)
        invite_member_by_email(source, source_type, email2, maintainer)

        get invitations_url(source, maintainer), params: { query: email }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(json_response.count).to eq(1)
        expect(json_response.first['invite_email']).to eq(email)
        expect(json_response.first['created_by_name']).to eq(maintainer.name)
        expect(json_response.first['user_name']).to eq(nil)
      end
    end
  end

  describe 'GET /projects/:id/invitations' do
    it_behaves_like 'GET /:source_type/:id/invitations', 'project' do
      let(:source) { project }
    end
  end

  describe 'GET /groups/:id/invitations' do
    it_behaves_like 'GET /:source_type/:id/invitations', 'group' do
      let(:source) { group }
    end
  end

  shared_examples 'DELETE /:source_type/:id/invitations/:email' do |source_type|
    def invite_api(source, user, email)
      api("/#{source.model_name.plural}/#{source.id}/invitations/#{email}", user)
    end

    context "with :source_type == #{source_type.pluralize}" do
      let!(:invite) { invite_member_by_email(source, source_type, developer.email, developer) }

      it_behaves_like 'a 404 response when source is private' do
        let(:route) { delete api("/#{source_type.pluralize}/#{source.id}/invitations/#{invite.invite_email}", stranger) }
      end

      context 'when authenticated as a non-member or member with insufficient rights' do
        %i[access_requester stranger].each do |type|
          context "as a #{type}" do
            it 'returns 403' do
              user = public_send(type)

              delete invite_api(source, user, invite.invite_email)

              expect(response).to have_gitlab_http_status(:forbidden)
            end
          end
        end
      end

      context 'when authenticated as a member and deleting themself' do
        it 'does not delete the member' do
          expect do
            delete invite_api(source, developer, invite.invite_email)

            expect(response).to have_gitlab_http_status(:forbidden)
          end.not_to change { source.members.count }
        end
      end

      context 'when authenticated as a maintainer/owner' do
        it 'deletes the member and returns 204 with no content' do
          expect do
            delete invite_api(source, maintainer, invite.invite_email)

            expect(response).to have_gitlab_http_status(:no_content)
          end.to change { source.members.count }.by(-1)
        end
      end

      it 'returns 404 if member does not exist' do
        delete invite_api(source, maintainer, non_existing_record_id)

        expect(response).to have_gitlab_http_status(:not_found)
      end

      it 'returns 422 for a valid request if the resource was not destroyed' do
        allow_next_instance_of(::Members::DestroyService) do |instance|
          allow(instance).to receive(:execute).with(invite).and_return(invite)
        end

        delete invite_api(source, maintainer, invite.invite_email)

        expect(response).to have_gitlab_http_status(:unprocessable_entity)
      end
    end
  end

  describe 'DELETE /projects/:id/inviations/:email' do
    it_behaves_like 'DELETE /:source_type/:id/invitations/:email', 'project' do
      let(:source) { project }
    end
  end

  describe 'DELETE /groups/:id/inviations/:email' do
    it_behaves_like 'DELETE /:source_type/:id/invitations/:email', 'group' do
      let(:source) { group }
    end
  end

  shared_examples 'PUT /:source_type/:id/invitations/:email' do |source_type|
    def update_api(source, user, email)
      api("/#{source.model_name.plural}/#{source.id}/invitations/#{email}", user)
    end

    context "with :source_type == #{source_type.pluralize}" do
      let!(:invite) { invite_member_by_email(source, source_type, developer.email, maintainer) }

      it_behaves_like 'a 404 response when source is private' do
        let(:route) do
          put update_api(source, stranger, invite.invite_email), params: { access_level: Member::MAINTAINER }
        end
      end

      context 'when authenticated as a non-member or member with insufficient rights' do
        %i[access_requester stranger].each do |type|
          context "as a #{type}" do
            it 'returns 403' do
              user = public_send(type)

              put update_api(source, user, invite.invite_email), params: { access_level: Member::MAINTAINER }

              expect(response).to have_gitlab_http_status(:forbidden)
            end
          end
        end
      end

      context 'when authenticated as a maintainer/owner' do
        context 'updating access level' do
          it 'updates the invitation' do
            put update_api(source, maintainer, invite.invite_email), params: { access_level: Member::MAINTAINER }

            expect(response).to have_gitlab_http_status(:ok)
            expect(json_response['access_level']).to eq(Member::MAINTAINER)
            expect(invite.reload.access_level).to eq(Member::MAINTAINER)
          end
        end

        it 'returns 409 if member does not exist' do
          put update_api(source, maintainer, non_existing_record_id), params: { access_level: Member::MAINTAINER }

          expect(response).to have_gitlab_http_status(:not_found)
        end

        it 'returns 400 when access_level is not given and there are no other params' do
          put update_api(source, maintainer, invite.invite_email)

          expect(response).to have_gitlab_http_status(:bad_request)
        end

        it 'returns 400 when access level is not valid' do
          put update_api(source, maintainer, invite.invite_email), params: { access_level: non_existing_record_access_level }

          expect(response).to have_gitlab_http_status(:bad_request)
        end
      end

      context 'updating access expiry date' do
        subject do
          put update_api(source, maintainer, invite.invite_email), params: { expires_at: expires_at }
        end

        context 'when set to a date in the past' do
          let(:expires_at) { 2.days.ago.to_date }

          it 'does not update the member' do
            subject

            expect(response).to have_gitlab_http_status(:bad_request)
            expect(json_response['message']).to eq({ 'expires_at' => ['cannot be a date in the past'] })
          end
        end

        context 'when set to a date in the future' do
          let(:expires_at) { 2.days.from_now.to_date }

          it 'updates the member' do
            subject

            expect(response).to have_gitlab_http_status(:ok)
            expect(json_response['expires_at']).to eq(expires_at.to_s)
          end
        end
      end
    end
  end

  describe 'PUT /projects/:id/invitations' do
    it_behaves_like 'PUT /:source_type/:id/invitations/:email', 'project' do
      let(:source) { project }
    end
  end

  describe 'PUT /groups/:id/invitations' do
    it_behaves_like 'PUT /:source_type/:id/invitations/:email', 'group' do
      let(:source) { group }
    end
  end
end