You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

GitLabIdentityProvider.java 6.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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.auth.gitlab;
  21. import com.github.scribejava.core.builder.ServiceBuilder;
  22. import com.github.scribejava.core.model.OAuth2AccessToken;
  23. import com.github.scribejava.core.model.OAuthConstants;
  24. import com.github.scribejava.core.oauth.OAuth20Service;
  25. import com.google.common.annotations.VisibleForTesting;
  26. import java.io.IOException;
  27. import java.util.Collection;
  28. import java.util.List;
  29. import java.util.Set;
  30. import java.util.concurrent.ExecutionException;
  31. import java.util.stream.Stream;
  32. import javax.inject.Inject;
  33. import org.sonar.api.server.authentication.Display;
  34. import org.sonar.api.server.authentication.OAuth2IdentityProvider;
  35. import org.sonar.api.server.authentication.UnauthorizedException;
  36. import org.sonar.api.server.authentication.UserIdentity;
  37. import org.sonar.api.server.http.HttpRequest;
  38. import static com.google.common.base.Preconditions.checkState;
  39. import static java.util.stream.Collectors.toSet;
  40. public class GitLabIdentityProvider implements OAuth2IdentityProvider {
  41. public static final String KEY = "gitlab";
  42. private final GitLabSettings gitLabSettings;
  43. private final ScribeGitLabOauth2Api scribeApi;
  44. private final GitLabRestClient gitLabRestClient;
  45. private final ScribeFactory scribeFactory;
  46. @Inject
  47. public GitLabIdentityProvider(GitLabSettings gitLabSettings, GitLabRestClient gitLabRestClient, ScribeGitLabOauth2Api scribeApi) {
  48. this(gitLabSettings, gitLabRestClient, scribeApi, new ScribeFactory());
  49. }
  50. @VisibleForTesting
  51. GitLabIdentityProvider(GitLabSettings gitLabSettings, GitLabRestClient gitLabRestClient, ScribeGitLabOauth2Api scribeApi,
  52. ScribeFactory scribeFactory) {
  53. this.gitLabSettings = gitLabSettings;
  54. this.scribeApi = scribeApi;
  55. this.gitLabRestClient = gitLabRestClient;
  56. this.scribeFactory = scribeFactory;
  57. }
  58. @Override
  59. public String getKey() {
  60. return KEY;
  61. }
  62. @Override
  63. public String getName() {
  64. return "GitLab";
  65. }
  66. @Override
  67. public Display getDisplay() {
  68. return Display.builder()
  69. .setIconPath("/images/alm/gitlab.svg")
  70. .setBackgroundColor("#6a4fbb")
  71. .build();
  72. }
  73. @Override
  74. public boolean isEnabled() {
  75. return gitLabSettings.isEnabled();
  76. }
  77. @Override
  78. public boolean allowsUsersToSignUp() {
  79. return gitLabSettings.allowUsersToSignUp();
  80. }
  81. @Override
  82. public void init(InitContext context) {
  83. String state = context.generateCsrfState();
  84. try (OAuth20Service scribe = scribeFactory.newScribe(gitLabSettings, context.getCallbackUrl(), scribeApi)) {
  85. String url = scribe.getAuthorizationUrl(state);
  86. context.redirectTo(url);
  87. } catch (IOException e) {
  88. throw new IllegalStateException(e);
  89. }
  90. }
  91. @Override
  92. public void callback(CallbackContext context) {
  93. try (OAuth20Service scribe = scribeFactory.newScribe(gitLabSettings, context.getCallbackUrl(), scribeApi)) {
  94. onCallback(context, scribe);
  95. } catch (IOException | ExecutionException e) {
  96. throw new IllegalStateException(e);
  97. } catch (InterruptedException e) {
  98. Thread.currentThread().interrupt();
  99. throw new IllegalStateException(e);
  100. }
  101. }
  102. private void onCallback(CallbackContext context, OAuth20Service scribe) throws InterruptedException, ExecutionException, IOException {
  103. HttpRequest request = context.getHttpRequest();
  104. String code = request.getParameter(OAuthConstants.CODE);
  105. OAuth2AccessToken accessToken = scribe.getAccessToken(code);
  106. GsonUser user = gitLabRestClient.getUser(scribe, accessToken);
  107. UserIdentity.Builder builder = UserIdentity.builder()
  108. .setProviderId(Long.toString(user.getId()))
  109. .setProviderLogin(user.getUsername())
  110. .setName(user.getName())
  111. .setEmail(user.getEmail());
  112. if (gitLabSettings.syncUserGroups()) {
  113. Set<String> userGroups = getGroups(scribe, accessToken);
  114. validateUserInAllowedGroups(userGroups, gitLabSettings.allowedGroups());
  115. builder.setGroups(userGroups);
  116. }
  117. context.authenticate(builder.build());
  118. context.redirectToRequestedPage();
  119. }
  120. private void validateUserInAllowedGroups(Set<String> userGroups, Set<String> allowedGroups) {
  121. if (gitLabSettings.allowedGroups().isEmpty()) {
  122. return;
  123. }
  124. boolean allowedUser = userGroups.stream()
  125. .anyMatch(userGroup -> isAllowedGroup(userGroup, allowedGroups));
  126. if (!allowedUser) {
  127. throw new UnauthorizedException("You are not allowed to authenticate");
  128. }
  129. }
  130. private static boolean isAllowedGroup(String group, Set<String> allowedGroups) {
  131. return allowedGroups.stream().anyMatch(group::startsWith);
  132. }
  133. private Set<String> getGroups(OAuth20Service scribe, OAuth2AccessToken accessToken) {
  134. List<GsonGroup> groups = gitLabRestClient.getGroups(scribe, accessToken);
  135. return Stream.of(groups)
  136. .flatMap(Collection::stream)
  137. .map(GsonGroup::getFullPath)
  138. .collect(toSet());
  139. }
  140. static class ScribeFactory {
  141. private static final String API_SCOPE = "api";
  142. private static final String READ_USER_SCOPE = "read_user";
  143. OAuth20Service newScribe(GitLabSettings gitLabSettings, String callbackUrl, ScribeGitLabOauth2Api scribeApi) {
  144. checkState(gitLabSettings.isEnabled(), "GitLab authentication is disabled");
  145. return new ServiceBuilder(gitLabSettings.applicationId())
  146. .apiSecret(gitLabSettings.secret())
  147. .defaultScope(gitLabSettings.syncUserGroups() ? API_SCOPE : READ_USER_SCOPE)
  148. .callback(callbackUrl)
  149. .build(scribeApi);
  150. }
  151. }
  152. }