aboutsummaryrefslogtreecommitdiffstats
path: root/server/sonar-auth-gitlab/src/test/java/org/sonar/auth/gitlab/IntegrationTest.java
blob: 791bf552112eaa0afa6a7d5ff4055c830741601c (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
/*
 * SonarQube
 * Copyright (C) 2009-2025 SonarSource SA
 * mailto:info AT sonarsource DOT com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package org.sonar.auth.gitlab;

import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.server.authentication.OAuth2IdentityProvider;
import org.sonar.api.server.authentication.UnauthorizedException;
import org.sonar.api.server.authentication.UserIdentity;
import org.sonar.api.server.http.HttpRequest;

import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.sonar.auth.gitlab.GitLabSettings.GITLAB_AUTH_ALLOWED_GROUPS;
import static org.sonar.auth.gitlab.GitLabSettings.GITLAB_AUTH_ALLOW_USERS_TO_SIGNUP;
import static org.sonar.auth.gitlab.GitLabSettings.GITLAB_AUTH_APPLICATION_ID;
import static org.sonar.auth.gitlab.GitLabSettings.GITLAB_AUTH_ENABLED;
import static org.sonar.auth.gitlab.GitLabSettings.GITLAB_AUTH_SECRET;
import static org.sonar.auth.gitlab.GitLabSettings.GITLAB_AUTH_SYNC_USER_GROUPS;
import static org.sonar.auth.gitlab.GitLabSettings.GITLAB_AUTH_URL;

public class IntegrationTest {

  private static final String ANY_CODE_VALUE = "ANY_CODE";

  @Rule
  public MockWebServer gitlab = new MockWebServer();

  private final MapSettings mapSettings = new MapSettings();

  private final GitLabSettings gitLabSettings = new GitLabSettings(mapSettings.asConfig());

  private String gitLabUrl;

  private final GitLabIdentityProvider gitLabIdentityProvider = new GitLabIdentityProvider(gitLabSettings,
    new GitLabRestClient(gitLabSettings),
    new ScribeGitLabOauth2Api(gitLabSettings));

  @Before
  public void setUp() {
    this.gitLabUrl = format("http://%s:%d", gitlab.getHostName(), gitlab.getPort());
    mapSettings
      .setProperty(GITLAB_AUTH_ENABLED, "true")
      .setProperty(GITLAB_AUTH_ALLOW_USERS_TO_SIGNUP, "true")
      .setProperty(GITLAB_AUTH_URL, gitLabUrl)
      .setProperty(GITLAB_AUTH_APPLICATION_ID, "123")
      .setProperty(GITLAB_AUTH_SECRET, "456")
      .setProperty(GITLAB_AUTH_ALLOWED_GROUPS, "group1,group2")
      .setProperty(GITLAB_AUTH_SYNC_USER_GROUPS, "true");
  }

  @Test
  public void callback_whenAllowedUser_shouldAuthenticate() {
    OAuth2IdentityProvider.CallbackContext callbackContext = mockCallbackContext();

    mockAccessTokenResponse();
    mockUserResponse();
    mockSingleGroupReponse("group1");

    gitLabIdentityProvider.callback(callbackContext);

    ArgumentCaptor<UserIdentity> argument = ArgumentCaptor.forClass(UserIdentity.class);
    verify(callbackContext).authenticate(argument.capture());
    assertThat(argument.getValue()).isNotNull();
    assertThat(argument.getValue().getProviderId()).isEqualTo("123");
    assertThat(argument.getValue().getProviderLogin()).isEqualTo("toto");
    assertThat(argument.getValue().getName()).isEqualTo("Toto Toto");
    assertThat(argument.getValue().getEmail()).isEqualTo("toto@toto.com");
    verify(callbackContext).redirectToRequestedPage();
  }

  @Test
  public void callback_whenGroupNotAllowedAndGroupSyncEnabled_shouldThrow() {
    OAuth2IdentityProvider.CallbackContext callbackContext = mockCallbackContext();

    mockAccessTokenResponse();
    mockUserResponse();
    mockSingleGroupReponse("wrong-group");

    assertThatThrownBy(() -> gitLabIdentityProvider.callback(callbackContext))
      .isInstanceOf((UnauthorizedException.class))
      .hasMessage("You are not allowed to authenticate");
  }

  @Test
  public void callback_whenGroupNotAllowedAndGroupSyncDisabled_shouldThrow() {
    mapSettings.setProperty(GITLAB_AUTH_SYNC_USER_GROUPS, "false");
    OAuth2IdentityProvider.CallbackContext callbackContext = mockCallbackContext();

    mockAccessTokenResponse();
    mockUserResponse();
    mockSingleGroupReponse("wrong-group");

    gitLabIdentityProvider.callback(callbackContext);

    verify(callbackContext).authenticate(any());
    verify(callbackContext).redirectToRequestedPage();
  }

  @Test
  public void callback_whenAllowedUserBySubgroupMembership_shouldAuthenticate() {
    OAuth2IdentityProvider.CallbackContext callbackContext = mockCallbackContext();

    mockAccessTokenResponse();
    mockUserResponse();
    mockSingleGroupReponse("group1/subgroup");

    gitLabIdentityProvider.callback(callbackContext);

    verify(callbackContext).authenticate(any());
    verify(callbackContext).redirectToRequestedPage();
  }


  @Test
  public void callback_shouldSynchronizeGroups() throws InterruptedException {
    mapSettings.setProperty(GITLAB_AUTH_SYNC_USER_GROUPS, "true");
    OAuth2IdentityProvider.CallbackContext callbackContext = mockCallbackContext();

    mockAccessTokenResponse();
    mockUserResponse();
    // Response for /groups
    gitlab.enqueue(new MockResponse().setBody("""
      [
        {
          "id": 1,
          "full_path": "group1"
        },
        {
          "id": 2,
          "full_path": "group2"
        }
      ]
      """));

    gitLabIdentityProvider.callback(callbackContext);

    ArgumentCaptor<UserIdentity> captor = ArgumentCaptor.forClass(UserIdentity.class);
    verify(callbackContext).authenticate(captor.capture());
    UserIdentity value = captor.getValue();
    assertThat(value.getGroups()).contains("group1", "group2");
    assertThat(gitlab.takeRequest().getPath()).isEqualTo("/oauth/token");
    assertThat(gitlab.takeRequest().getPath()).isEqualTo("/api/v4/user");
    assertThat(gitlab.takeRequest().getPath()).isEqualTo("/api/v4/groups?min_access_level=10&per_page=100");
  }

  @Test
  public void callback_whenMultiplePagesOfGroups_shouldSynchronizeAllGroups() {
    mapSettings.setProperty(GITLAB_AUTH_SYNC_USER_GROUPS, "true");
    OAuth2IdentityProvider.CallbackContext callbackContext = mockCallbackContext();

    mockAccessTokenResponse();
    mockUserResponse();
    // Response for /groups, first page
    gitlab.enqueue(new MockResponse()
      .setBody("""
        [
          {
            "id": 1,
            "full_path": "group1"
          },
          {
            "id": 2,
            "full_path": "group2"
          }
        ]
        """)
      .setHeader("Link", format(" <%s/groups?per_page=100&page=2>; rel=\"next\"," +
        "  <%s/groups?per_page=100&&page=3>; rel=\"last\"," +
        "  <%s/groups?per_page=100&&page=1>; rel=\"first\"", gitLabUrl, gitLabUrl, gitLabUrl)));
    // Response for /groups, page 2
    gitlab.enqueue(new MockResponse()
      .setBody("""
        [
          {
            "id": 3,
            "full_path": "group3"
          },
          {
            "id": 4,
            "full_path": "group4"
          }
        ]
        """)
      .setHeader("Link", format("<%s/groups?per_page=100&page=3>; rel=\"next\"," +
        "  <%s/groups?per_page=100&&page=3>; rel=\"last\"," +
        "  <%s/groups?per_page=100&&page=1>; rel=\"first\"", gitLabUrl, gitLabUrl, gitLabUrl)));
    // Response for /groups, page 3
    gitlab.enqueue(new MockResponse()
      .setBody("""
        [
          {
            "id": 5,
            "full_path": "group5"
          },
          {
            "id": 6,
            "full_path": "group6"
          }
        ]
        """)
      .setHeader("Link", format("<%s/groups?per_page=100&&page=3>; rel=\"last\"," +
        "  <%s/groups?per_page=100&&page=1>; rel=\"first\"", gitLabUrl, gitLabUrl)));

    gitLabIdentityProvider.callback(callbackContext);

    ArgumentCaptor<UserIdentity> captor = ArgumentCaptor.forClass(UserIdentity.class);
    verify(callbackContext).authenticate(captor.capture());
    UserIdentity value = captor.getValue();
    assertThat(value.getGroups()).contains("group1", "group2", "group3", "group4", "group5", "group6");
  }

  @Test
  public void callback_whenNoUser_shouldThrow() {
    OAuth2IdentityProvider.CallbackContext callbackContext = mockCallbackContext();

    mockAccessTokenResponse();
    // Response for /user
    gitlab.enqueue(new MockResponse().setResponseCode(404).setBody("empty"));

    assertThatThrownBy(() -> gitLabIdentityProvider.callback(callbackContext))
      .hasMessage("Fail to execute request '" + gitLabSettings.url() + "/api/v4/user'. HTTP code: 404, response: empty")
      .isInstanceOf((IllegalStateException.class));
  }

  private static OAuth2IdentityProvider.CallbackContext mockCallbackContext() {
    OAuth2IdentityProvider.CallbackContext callbackContext = Mockito.mock(OAuth2IdentityProvider.CallbackContext.class);
    when(callbackContext.getCallbackUrl()).thenReturn("http://server/callback");

    HttpRequest httpRequest = Mockito.mock(HttpRequest.class);
    when(httpRequest.getParameter("code")).thenReturn(ANY_CODE_VALUE);
    when(callbackContext.getHttpRequest()).thenReturn(httpRequest);
    return callbackContext;
  }

  private void mockAccessTokenResponse() {
    // Response for OAuth access token
    gitlab.enqueue(new MockResponse().setBody("""
      {
        "access_token": "de6780bc506a0446309bd9362820ba8aed28aa506c71eedbe1c5c4f9dd350e54",
        "token_type": "bearer",
        "expires_in": 7200,
        "refresh_token": "8257e65c97202ed1726cf9571600918f3bffb2544b26e00a61df9897668c33a1"
      }
      """));
  }

  private void mockUserResponse() {
    // Response for /user
    gitlab.enqueue(new MockResponse().setBody("""
      {
        "id": 123,
        "username": "toto",
        "name": "Toto Toto",
        "email": "toto@toto.com"
      }
      """));
  }

  private void mockSingleGroupReponse(String group) {
    // Response for /groups
    gitlab.enqueue(new MockResponse().setBody("""
      [
        {
          "id": 1,
          "full_path": "%s"
        }
      ]
      """.formatted(group)));
  }

}