]> source.dussan.org Git - sonarqube.git/blob
6086c2cdcdd0e47cc193e60105c35fffcfeca46c
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2024 SonarSource SA
4  * mailto:info AT sonarsource DOT com
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 3 of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19  */
20 package org.sonar.server.common.gitlab.config;
21
22 import com.google.common.base.Strings;
23 import java.util.LinkedHashSet;
24 import java.util.List;
25 import java.util.Optional;
26 import java.util.Set;
27 import javax.annotation.Nullable;
28 import org.junit.Before;
29 import org.junit.Rule;
30 import org.junit.Test;
31 import org.junit.runner.RunWith;
32 import org.mockito.Mock;
33 import org.mockito.junit.MockitoJUnitRunner;
34 import org.sonar.alm.client.gitlab.GitlabGlobalSettingsValidator;
35 import org.sonar.auth.gitlab.GitLabIdentityProvider;
36 import org.sonar.db.DbSession;
37 import org.sonar.db.DbTester;
38 import org.sonar.db.user.ExternalGroupDto;
39 import org.sonar.server.exceptions.BadRequestException;
40 import org.sonar.server.exceptions.NotFoundException;
41 import org.sonar.server.management.ManagedInstanceService;
42
43 import static org.assertj.core.api.Assertions.assertThat;
44 import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
45 import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
46 import static org.assertj.core.api.Assertions.assertThatThrownBy;
47 import static org.mockito.Mockito.clearInvocations;
48 import static org.mockito.Mockito.mock;
49 import static org.mockito.Mockito.reset;
50 import static org.mockito.Mockito.times;
51 import static org.mockito.Mockito.verify;
52 import static org.mockito.Mockito.verifyNoInteractions;
53 import static org.mockito.Mockito.verifyNoMoreInteractions;
54 import static org.mockito.Mockito.when;
55 import static org.sonar.alm.client.gitlab.GitlabGlobalSettingsValidator.ValidationMode.AUTH_ONLY;
56 import static org.sonar.alm.client.gitlab.GitlabGlobalSettingsValidator.ValidationMode.COMPLETE;
57 import static org.sonar.auth.gitlab.GitLabSettings.GITLAB_AUTH_ALLOW_USERS_TO_SIGNUP;
58 import static org.sonar.auth.gitlab.GitLabSettings.GITLAB_AUTH_APPLICATION_ID;
59 import static org.sonar.auth.gitlab.GitLabSettings.GITLAB_AUTH_ENABLED;
60 import static org.sonar.auth.gitlab.GitLabSettings.GITLAB_AUTH_PROVISIONING_ENABLED;
61 import static org.sonar.auth.gitlab.GitLabSettings.GITLAB_AUTH_PROVISIONING_GROUPS;
62 import static org.sonar.auth.gitlab.GitLabSettings.GITLAB_AUTH_PROVISIONING_TOKEN;
63 import static org.sonar.auth.gitlab.GitLabSettings.GITLAB_AUTH_SECRET;
64 import static org.sonar.auth.gitlab.GitLabSettings.GITLAB_AUTH_SYNC_USER_GROUPS;
65 import static org.sonar.auth.gitlab.GitLabSettings.GITLAB_AUTH_URL;
66 import static org.sonar.server.common.NonNullUpdatedValue.withValueOrThrow;
67 import static org.sonar.server.common.UpdatedValue.withValue;
68 import static org.sonar.server.common.gitlab.config.GitlabConfigurationService.UNIQUE_GITLAB_CONFIGURATION_ID;
69 import static org.sonar.server.common.gitlab.config.ProvisioningType.AUTO_PROVISIONING;
70 import static org.sonar.server.common.gitlab.config.ProvisioningType.JIT;
71 import static org.sonar.server.common.gitlab.config.UpdateGitlabConfigurationRequest.builder;
72
73 @RunWith(MockitoJUnitRunner.class)
74 public class GitlabConfigurationServiceIT {
75
76   @Rule
77   public DbTester dbTester = DbTester.create();
78
79   @Mock
80   private ManagedInstanceService managedInstanceService;
81
82   @Mock
83   private GitlabGlobalSettingsValidator gitlabGlobalSettingsValidator;
84
85   private GitlabConfigurationService gitlabConfigurationService;
86
87   @Before
88   public void setUp() {
89     when(managedInstanceService.getProviderName()).thenReturn("gitlab");
90     gitlabConfigurationService = new GitlabConfigurationService(
91       dbTester.getDbClient(),
92       managedInstanceService,
93       gitlabGlobalSettingsValidator);
94   }
95
96   @Test
97   public void getConfiguration_whenIdIsNotGitlabConfiguration_throwsException() {
98     assertThatExceptionOfType(NotFoundException.class)
99       .isThrownBy(() -> gitlabConfigurationService.getConfiguration("not-gitlab-configuration"))
100       .withMessage("Gitlab configuration with id not-gitlab-configuration not found");
101   }
102
103   @Test
104   public void getConfiguration_whenNoConfiguration_throwsNotFoundException() {
105     assertThatThrownBy(() -> gitlabConfigurationService.getConfiguration("gitlab-configuration"))
106       .isInstanceOf(NotFoundException.class)
107       .hasMessage("GitLab configuration doesn't exist.");
108
109   }
110
111   @Test
112   public void getConfiguration_whenConfigurationSet_returnsConfig() {
113     gitlabConfigurationService.createConfiguration(buildGitlabConfiguration(AUTO_PROVISIONING));
114
115     GitlabConfiguration configuration = gitlabConfigurationService.getConfiguration("gitlab-configuration");
116
117     assertConfigurationFields(configuration);
118   }
119
120   @Test
121   public void getConfiguration_whenConfigurationSetAndEmpty_returnsConfig() {
122     dbTester.properties().insertProperty(GITLAB_AUTH_ENABLED, "true", null);
123     dbTester.properties().insertProperty(GITLAB_AUTH_PROVISIONING_GROUPS, "", null);
124
125     GitlabConfiguration configuration = gitlabConfigurationService.getConfiguration("gitlab-configuration");
126
127     assertThat(configuration.id()).isEqualTo("gitlab-configuration");
128     assertThat(configuration.enabled()).isTrue();
129     assertThat(configuration.applicationId()).isEmpty();
130     assertThat(configuration.url()).isEmpty();
131     assertThat(configuration.secret()).isEmpty();
132     assertThat(configuration.synchronizeGroups()).isFalse();
133     assertThat(configuration.provisioningType()).isEqualTo(JIT);
134     assertThat(configuration.allowUsersToSignUp()).isFalse();
135     assertThat(configuration.provisioningToken()).isNull();
136     assertThat(configuration.provisioningGroups()).isEmpty();
137   }
138
139   @Test
140   public void updateConfiguration_whenIdIsNotGitlabConfiguration_throwsException() {
141     gitlabConfigurationService.createConfiguration(buildGitlabConfiguration(AUTO_PROVISIONING));
142     UpdateGitlabConfigurationRequest updateGitlabConfigurationRequest = builder().gitlabConfigurationId("not-gitlab-configuration").build();
143     assertThatExceptionOfType(NotFoundException.class)
144       .isThrownBy(() -> gitlabConfigurationService.updateConfiguration(updateGitlabConfigurationRequest))
145       .withMessage("Gitlab configuration with id not-gitlab-configuration not found");
146   }
147
148   @Test
149   public void updateConfiguration_whenConfigurationDoesntExist_throwsException() {
150     UpdateGitlabConfigurationRequest updateGitlabConfigurationRequest = builder().gitlabConfigurationId("gitlab-configuration").build();
151     assertThatExceptionOfType(NotFoundException.class)
152       .isThrownBy(() -> gitlabConfigurationService.updateConfiguration(updateGitlabConfigurationRequest))
153       .withMessage("GitLab configuration doesn't exist.");
154   }
155
156   @Test
157   public void updateConfiguration_whenAllUpdateFieldDefined_updatesEverything() {
158     gitlabConfigurationService.createConfiguration(buildGitlabConfiguration(JIT));
159
160     UpdateGitlabConfigurationRequest updateRequest = builder()
161       .gitlabConfigurationId(UNIQUE_GITLAB_CONFIGURATION_ID)
162       .enabled(withValueOrThrow(true))
163       .applicationId(withValueOrThrow("applicationId"))
164       .url(withValueOrThrow("url"))
165       .secret(withValueOrThrow("secret"))
166       .synchronizeGroups(withValueOrThrow(true))
167       .provisioningType(withValueOrThrow(AUTO_PROVISIONING))
168       .allowUserToSignUp(withValueOrThrow(true))
169       .provisioningToken(withValueOrThrow("provisioningToken"))
170       .provisioningGroups(withValueOrThrow(new LinkedHashSet<>(List.of("group1", "group2", "group3"))))
171       .build();
172
173     GitlabConfiguration gitlabConfiguration = gitlabConfigurationService.updateConfiguration(updateRequest);
174
175     verifySettingWasSet(GITLAB_AUTH_ENABLED, "true");
176     verifySettingWasSet(GITLAB_AUTH_APPLICATION_ID, "applicationId");
177     verifySettingWasSet(GITLAB_AUTH_URL, "url");
178     verifySettingWasSet(GITLAB_AUTH_SECRET, "secret");
179     verifySettingWasSet(GITLAB_AUTH_SYNC_USER_GROUPS, "true");
180     verifySettingWasSet(GITLAB_AUTH_PROVISIONING_ENABLED, "true");
181     verifySettingWasSet(GITLAB_AUTH_ALLOW_USERS_TO_SIGNUP, "true");
182     verifySettingWasSet(GITLAB_AUTH_PROVISIONING_TOKEN, "provisioningToken");
183     verifySettingWasSet(GITLAB_AUTH_PROVISIONING_GROUPS, "group1,group2,group3");
184     verify(managedInstanceService).queueSynchronisationTask();
185
186     assertConfigurationFields(gitlabConfiguration);
187   }
188
189   @Test
190   public void updateConfiguration_whenAllUpdateFieldDefinedAndSetToFalse_updatesEverything() {
191     gitlabConfigurationService.createConfiguration(buildGitlabConfiguration(AUTO_PROVISIONING));
192     verify(managedInstanceService).queueSynchronisationTask();
193     clearInvocations(managedInstanceService);
194
195     UpdateGitlabConfigurationRequest updateRequest = builder()
196       .gitlabConfigurationId(UNIQUE_GITLAB_CONFIGURATION_ID)
197       .enabled(withValueOrThrow(false))
198       .synchronizeGroups(withValueOrThrow(false))
199       .provisioningType(withValueOrThrow(JIT))
200       .allowUserToSignUp(withValueOrThrow(false))
201       .build();
202
203     gitlabConfigurationService.updateConfiguration(updateRequest);
204
205     verifySettingWasSet(GITLAB_AUTH_ENABLED, "false");
206     verifySettingWasSet(GITLAB_AUTH_SYNC_USER_GROUPS, "false");
207     verifySettingWasSet(GITLAB_AUTH_PROVISIONING_ENABLED, "false");
208     verifySettingWasSet(GITLAB_AUTH_ALLOW_USERS_TO_SIGNUP, "false");
209     verifyNoMoreInteractions(managedInstanceService);
210
211   }
212
213   @Test
214   public void updateConfiguration_whenSwitchingFromAutoToJit_shouldNotScheduleSyncAndCallManagedInstanceChecker() {
215     DbSession dbSession = dbTester.getSession();
216     dbTester.getDbClient().externalGroupDao().insert(dbSession, new ExternalGroupDto("12", "12", GitLabIdentityProvider.KEY));
217     dbTester.getDbClient().externalGroupDao().insert(dbSession, new ExternalGroupDto("34", "34", GitLabIdentityProvider.KEY));
218     dbSession.commit();
219
220     gitlabConfigurationService.createConfiguration(buildGitlabConfiguration(AUTO_PROVISIONING));
221     verify(managedInstanceService).queueSynchronisationTask();
222     reset(managedInstanceService);
223
224     UpdateGitlabConfigurationRequest updateRequest = builder()
225       .gitlabConfigurationId(UNIQUE_GITLAB_CONFIGURATION_ID)
226       .provisioningToken(withValue(null))
227       .provisioningType(withValueOrThrow(JIT))
228       .build();
229
230     gitlabConfigurationService.updateConfiguration(updateRequest);
231
232     verifyNoMoreInteractions(managedInstanceService);
233     assertThat(dbTester.getDbClient().externalGroupDao().selectByIdentityProvider(dbTester.getSession(), GitLabIdentityProvider.KEY)).isEmpty();
234   }
235
236   @Test
237   public void updateConfiguration_whenSwitchingToAutoProvisioningAndTheConfigIsNotEnabled_shouldThrow() {
238     gitlabConfigurationService.createConfiguration(buildGitlabConfiguration(JIT));
239
240     UpdateGitlabConfigurationRequest disableRequest = builder()
241       .gitlabConfigurationId(UNIQUE_GITLAB_CONFIGURATION_ID)
242       .enabled(withValueOrThrow(false))
243       .build();
244
245     gitlabConfigurationService.updateConfiguration(disableRequest);
246
247     UpdateGitlabConfigurationRequest updateRequest = builder()
248       .gitlabConfigurationId(UNIQUE_GITLAB_CONFIGURATION_ID)
249       .provisioningType(withValueOrThrow(AUTO_PROVISIONING))
250       .build();
251
252     assertThatThrownBy(() -> gitlabConfigurationService.updateConfiguration(updateRequest))
253       .isInstanceOf(IllegalStateException.class)
254       .hasMessage("GitLab authentication must be turned on to enable GitLab provisioning.");
255     verify(managedInstanceService, times(0)).queueSynchronisationTask();
256   }
257
258   @Test
259   public void updateConfiguration_whenSwitchingToAutoProvisioningAndProvisioningTokenIsNotDefined_shouldThrow() {
260     gitlabConfigurationService.createConfiguration(buildGitlabConfiguration(JIT));
261
262     UpdateGitlabConfigurationRequest removeTokenRequest = builder()
263       .gitlabConfigurationId(UNIQUE_GITLAB_CONFIGURATION_ID)
264       .provisioningToken(withValue(null))
265       .build();
266
267     gitlabConfigurationService.updateConfiguration(removeTokenRequest);
268
269     UpdateGitlabConfigurationRequest updateRequest = builder()
270       .gitlabConfigurationId(UNIQUE_GITLAB_CONFIGURATION_ID)
271       .provisioningType(withValueOrThrow(AUTO_PROVISIONING))
272       .build();
273
274     assertThatThrownBy(() -> gitlabConfigurationService.updateConfiguration(updateRequest))
275       .isInstanceOf(IllegalStateException.class)
276       .hasMessage("Provisioning token must be set to enable GitLab provisioning.");
277     verify(managedInstanceService, times(0)).queueSynchronisationTask();
278   }
279
280   private static void assertConfigurationFields(GitlabConfiguration configuration) {
281     assertThat(configuration).isNotNull();
282     assertThat(configuration.id()).isEqualTo("gitlab-configuration");
283     assertThat(configuration.enabled()).isTrue();
284     assertThat(configuration.applicationId()).isEqualTo("applicationId");
285     assertThat(configuration.url()).isEqualTo("url");
286     assertThat(configuration.secret()).isEqualTo("secret");
287     assertThat(configuration.synchronizeGroups()).isTrue();
288     assertThat(configuration.provisioningType()).isEqualTo(AUTO_PROVISIONING);
289     assertThat(configuration.allowUsersToSignUp()).isTrue();
290     assertThat(configuration.provisioningToken()).isEqualTo("provisioningToken");
291     assertThat(configuration.provisioningGroups()).containsExactlyInAnyOrder("group1", "group2", "group3");
292   }
293
294   @Test
295   public void createConfiguration_whenConfigurationAlreadyExists_shouldThrow() {
296     GitlabConfiguration gitlabConfiguration = buildGitlabConfiguration(AUTO_PROVISIONING);
297     gitlabConfigurationService.createConfiguration(gitlabConfiguration);
298
299     assertThatThrownBy(() -> gitlabConfigurationService.createConfiguration(gitlabConfiguration))
300       .isInstanceOf(BadRequestException.class)
301       .hasMessage("GitLab configuration already exists. Only one Gitlab configuration is supported.");
302   }
303
304   @Test
305   public void createConfiguration_whenAutoProvisioning_shouldCreateCorrectConfigurationAndScheduleSync() {
306     GitlabConfiguration configuration = buildGitlabConfiguration(AUTO_PROVISIONING);
307
308     GitlabConfiguration createdConfiguration = gitlabConfigurationService.createConfiguration(configuration);
309
310     assertConfigurationIsCorrect(configuration, createdConfiguration);
311
312     verifyCommonSettings(configuration);
313
314     verify(managedInstanceService).queueSynchronisationTask();
315
316   }
317
318   @Test
319   public void createConfiguration_whenAutoProvisioningConfigIsIncorrect_shouldThrow() {
320     GitlabConfiguration configuration = new GitlabConfiguration(
321       UNIQUE_GITLAB_CONFIGURATION_ID,
322       true,
323       "applicationId",
324       "url",
325       "secret",
326       true,
327       AUTO_PROVISIONING,
328       true,
329       null,
330       Set.of("group1", "group2", "group3"));
331
332     assertThatThrownBy(() -> gitlabConfigurationService.createConfiguration(configuration))
333       .isInstanceOf(IllegalStateException.class)
334       .hasMessage("Provisioning token must be set to enable GitLab provisioning.");
335
336   }
337
338   @Test
339   public void createConfiguration_whenInstanceIsExternallyManaged_shouldThrow() {
340     GitlabConfiguration configuration = buildGitlabConfiguration(AUTO_PROVISIONING);
341
342     when(managedInstanceService.isInstanceExternallyManaged()).thenReturn(true);
343     when(managedInstanceService.getProviderName()).thenReturn("not-gitlab");
344
345     assertThatIllegalStateException()
346       .isThrownBy(() -> gitlabConfigurationService.createConfiguration(configuration))
347       .withMessage("It is not possible to synchronize SonarQube using GitLab, as it is already managed by not-gitlab.");
348
349   }
350
351   @Test
352   public void createConfiguration_whenJitProvisioning_shouldCreateCorrectConfiguration() {
353     GitlabConfiguration configuration = buildGitlabConfiguration(JIT);
354
355     GitlabConfiguration createdConfiguration = gitlabConfigurationService.createConfiguration(configuration);
356
357     assertConfigurationIsCorrect(configuration, createdConfiguration);
358
359     verifyCommonSettings(configuration);
360     verifyNoInteractions(managedInstanceService);
361
362   }
363
364   @Test
365   public void createConfiguration_whenJitProvisioningAndProvisioningTokenNotSet_shouldCreateCorrectConfiguration() {
366     GitlabConfiguration configuration = new GitlabConfiguration(
367       UNIQUE_GITLAB_CONFIGURATION_ID,
368       true,
369       "applicationId",
370       "url",
371       "secret",
372       true,
373       JIT,
374       true,
375       null,
376       Set.of("group1", "group2", "group3"));
377
378     GitlabConfiguration createdConfiguration = gitlabConfigurationService.createConfiguration(configuration);
379
380     assertConfigurationIsCorrect(configuration, createdConfiguration);
381
382     verifyCommonSettings(configuration);
383     verifyNoInteractions(managedInstanceService);
384
385   }
386
387   private void verifyCommonSettings(GitlabConfiguration configuration) {
388     verifySettingWasSet(GITLAB_AUTH_ENABLED, String.valueOf(configuration.enabled()));
389     verifySettingWasSet(GITLAB_AUTH_APPLICATION_ID, configuration.applicationId());
390     verifySettingWasSet(GITLAB_AUTH_URL, configuration.url());
391     verifySettingWasSet(GITLAB_AUTH_SECRET, configuration.secret());
392     verifySettingWasSet(GITLAB_AUTH_SYNC_USER_GROUPS, String.valueOf(configuration.synchronizeGroups()));
393     verifySettingWasSet(GITLAB_AUTH_ALLOW_USERS_TO_SIGNUP, String.valueOf(configuration.allowUsersToSignUp()));
394     verifySettingWasSet(GITLAB_AUTH_PROVISIONING_TOKEN, Strings.nullToEmpty(configuration.provisioningToken()));
395     verifySettingWasSet(GITLAB_AUTH_PROVISIONING_GROUPS, String.join(",", configuration.provisioningGroups()));
396     verifySettingWasSet(GITLAB_AUTH_PROVISIONING_ENABLED,
397       String.valueOf(configuration.provisioningType().equals(AUTO_PROVISIONING)));
398   }
399
400   private void verifySettingWasSet(String setting, @Nullable String value) {
401     assertThat(dbTester.getDbClient().propertiesDao().selectGlobalProperty(setting).getValue()).isEqualTo(value);
402   }
403
404   @Test
405   public void deleteConfiguration_whenIdIsNotGitlabConfiguration_throwsException() {
406     assertThatThrownBy(() -> gitlabConfigurationService.deleteConfiguration("not-gitlab-configuration"))
407       .isInstanceOf(NotFoundException.class)
408       .hasMessage("Gitlab configuration with id not-gitlab-configuration not found");
409   }
410
411   @Test
412   public void deleteConfiguration_whenConfigurationDoesntExist_throwsException() {
413     assertThatThrownBy(() -> gitlabConfigurationService.deleteConfiguration("gitlab-configuration"))
414       .isInstanceOf(NotFoundException.class)
415       .hasMessage("GitLab configuration doesn't exist.");
416   }
417
418   @Test
419   public void deleteConfiguration_whenConfigurationExists_shouldDeleteConfiguration() {
420     DbSession dbSession = dbTester.getSession();
421     dbTester.getDbClient().externalGroupDao().insert(dbSession, new ExternalGroupDto("12", "12", GitLabIdentityProvider.KEY));
422     dbTester.getDbClient().externalGroupDao().insert(dbSession, new ExternalGroupDto("34", "34", GitLabIdentityProvider.KEY));
423     dbSession.commit();
424     gitlabConfigurationService.createConfiguration(buildGitlabConfiguration(AUTO_PROVISIONING));
425     gitlabConfigurationService.deleteConfiguration("gitlab-configuration");
426
427     assertPropertyIsDeleted(GITLAB_AUTH_ENABLED);
428     assertPropertyIsDeleted(GITLAB_AUTH_APPLICATION_ID);
429     assertPropertyIsDeleted(GITLAB_AUTH_URL);
430     assertPropertyIsDeleted(GITLAB_AUTH_SECRET);
431     assertPropertyIsDeleted(GITLAB_AUTH_SYNC_USER_GROUPS);
432     assertPropertyIsDeleted(GITLAB_AUTH_PROVISIONING_ENABLED);
433     assertPropertyIsDeleted(GITLAB_AUTH_ALLOW_USERS_TO_SIGNUP);
434     assertPropertyIsDeleted(GITLAB_AUTH_PROVISIONING_TOKEN);
435     assertPropertyIsDeleted(GITLAB_AUTH_PROVISIONING_GROUPS);
436
437     assertThat(dbTester.getDbClient().externalGroupDao().selectByIdentityProvider(dbTester.getSession(), GitLabIdentityProvider.KEY)).isEmpty();
438   }
439
440   private void assertPropertyIsDeleted(String property) {
441     assertThat(dbTester.getDbClient().propertiesDao().selectGlobalProperty(property)).isNull();
442   }
443
444   @Test
445   public void triggerRun_whenConfigIsCorrect_shouldTriggerSync() {
446     gitlabConfigurationService.createConfiguration(buildGitlabConfiguration(AUTO_PROVISIONING));
447     reset(managedInstanceService);
448
449     gitlabConfigurationService.triggerRun();
450
451     verify(managedInstanceService).queueSynchronisationTask();
452   }
453
454   @Test
455   public void triggerRun_whenConfigIsForJit_shouldThrow() {
456     gitlabConfigurationService.createConfiguration(buildGitlabConfiguration(JIT));
457
458     assertThatIllegalStateException()
459       .isThrownBy(() -> gitlabConfigurationService.triggerRun())
460       .withMessage("Auto provisioning must be activated");
461   }
462
463   @Test
464   public void triggerRun_whenConfigIsDisabled_shouldThrow() {
465     GitlabConfiguration gitlabConfiguration = buildGitlabConfiguration(AUTO_PROVISIONING);
466     gitlabConfigurationService.createConfiguration(gitlabConfiguration);
467     gitlabConfigurationService.updateConfiguration(builder().gitlabConfigurationId(UNIQUE_GITLAB_CONFIGURATION_ID).enabled(withValueOrThrow(false)).build());
468
469     assertThatIllegalStateException()
470       .isThrownBy(() -> gitlabConfigurationService.triggerRun())
471       .withMessage("GitLab authentication must be turned on to enable GitLab provisioning.");
472   }
473
474   @Test
475   public void triggerRun_whenProvisioningTokenIsNotSet_shouldThrow() {
476     GitlabConfiguration gitlabConfiguration = buildGitlabConfiguration(AUTO_PROVISIONING);
477     gitlabConfigurationService.createConfiguration(gitlabConfiguration);
478     gitlabConfigurationService.updateConfiguration(builder().gitlabConfigurationId(UNIQUE_GITLAB_CONFIGURATION_ID).provisioningToken(withValue(null)).build());
479
480     assertThatIllegalStateException()
481       .isThrownBy(() -> gitlabConfigurationService.triggerRun())
482       .withMessage("Provisioning token must be set to enable GitLab provisioning.");
483   }
484
485   @Test
486   public void validate_whenConfigurationIsDisabled_shouldNotValidate() {
487     GitlabConfiguration gitlabConfiguration = buildGitlabConfiguration(AUTO_PROVISIONING);
488     when(gitlabConfiguration.enabled()).thenReturn(false);
489
490     gitlabConfigurationService.validate(gitlabConfiguration);
491
492     verifyNoInteractions(gitlabGlobalSettingsValidator);
493   }
494
495   @Test
496   public void validate_whenConfigurationIsValidAndJIT_returnEmptyOptional() {
497     GitlabConfiguration gitlabConfiguration = buildGitlabConfiguration(JIT);
498     when(gitlabConfiguration.enabled()).thenReturn(true);
499
500     gitlabConfigurationService.validate(gitlabConfiguration);
501
502     verify(gitlabGlobalSettingsValidator).validate(AUTH_ONLY, gitlabConfiguration.url() + "/api/v4", gitlabConfiguration.provisioningToken());
503   }
504
505   @Test
506   public void validate_whenConfigurationIsValidAndAutoProvisioning_returnEmptyOptional() {
507     GitlabConfiguration gitlabConfiguration = buildGitlabConfiguration(AUTO_PROVISIONING);
508     when(gitlabConfiguration.enabled()).thenReturn(true);
509
510     gitlabConfigurationService.validate(gitlabConfiguration);
511
512     verify(gitlabGlobalSettingsValidator).validate(COMPLETE, gitlabConfiguration.url() + "/api/v4", gitlabConfiguration.provisioningToken());
513   }
514
515   @Test
516   public void validate_whenConfigurationIsInValid_returnsExceptionMessage() {
517     GitlabConfiguration gitlabConfiguration = buildGitlabConfiguration(AUTO_PROVISIONING);
518     when(gitlabConfiguration.enabled()).thenReturn(true);
519
520     Exception exception = new IllegalStateException("Invalid configuration");
521     when(gitlabConfigurationService.validate(gitlabConfiguration)).thenThrow(exception);
522
523     Optional<String> message =  gitlabConfigurationService.validate(gitlabConfiguration);
524
525     assertThat(message).contains("Invalid configuration");
526   }
527
528   private static GitlabConfiguration buildGitlabConfiguration(ProvisioningType provisioningType) {
529     GitlabConfiguration gitlabConfiguration = mock();
530     when(gitlabConfiguration.id()).thenReturn("gitlab-configuration");
531     when(gitlabConfiguration.enabled()).thenReturn(true);
532     when(gitlabConfiguration.applicationId()).thenReturn("applicationId");
533     when(gitlabConfiguration.url()).thenReturn("url");
534     when(gitlabConfiguration.secret()).thenReturn("secret");
535     when(gitlabConfiguration.synchronizeGroups()).thenReturn(true);
536     when(gitlabConfiguration.provisioningType()).thenReturn(provisioningType);
537     when(gitlabConfiguration.allowUsersToSignUp()).thenReturn(true);
538     when(gitlabConfiguration.provisioningToken()).thenReturn("provisioningToken");
539     when(gitlabConfiguration.provisioningGroups()).thenReturn(new LinkedHashSet<>(Set.of("group1", "group2", "group3")));
540     return gitlabConfiguration;
541   }
542
543   private static void assertConfigurationIsCorrect(GitlabConfiguration expectedConfiguration, GitlabConfiguration actualConfiguration) {
544     assertThat(actualConfiguration.id()).isEqualTo(expectedConfiguration.id());
545     assertThat(actualConfiguration.enabled()).isEqualTo(expectedConfiguration.enabled());
546     assertThat(actualConfiguration.applicationId()).isEqualTo(expectedConfiguration.applicationId());
547     assertThat(actualConfiguration.url()).isEqualTo(expectedConfiguration.url());
548     assertThat(actualConfiguration.secret()).isEqualTo(expectedConfiguration.secret());
549     assertThat(actualConfiguration.synchronizeGroups()).isEqualTo(expectedConfiguration.synchronizeGroups());
550     assertThat(actualConfiguration.provisioningType()).isEqualTo(expectedConfiguration.provisioningType());
551     assertThat(actualConfiguration.allowUsersToSignUp()).isEqualTo(expectedConfiguration.allowUsersToSignUp());
552     assertThat(actualConfiguration.provisioningToken()).isEqualTo(expectedConfiguration.provisioningToken());
553     assertThat(actualConfiguration.provisioningGroups()).containsExactlyInAnyOrderElementsOf(expectedConfiguration.provisioningGroups());
554   }
555 }