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.

GitHubIdentityProvider.java 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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.github;
  21. import com.github.scribejava.core.builder.ServiceBuilder;
  22. import com.github.scribejava.core.model.OAuth2AccessToken;
  23. import com.github.scribejava.core.oauth.OAuth20Service;
  24. import java.io.IOException;
  25. import java.util.List;
  26. import java.util.Optional;
  27. import java.util.concurrent.ExecutionException;
  28. import org.sonar.api.server.authentication.Display;
  29. import org.sonar.api.server.authentication.OAuth2IdentityProvider;
  30. import org.sonar.api.server.authentication.UnauthorizedException;
  31. import org.sonar.api.server.authentication.UserIdentity;
  32. import org.sonar.api.server.http.HttpRequest;
  33. import org.sonar.auth.github.client.GithubApplicationClient;
  34. import org.sonar.auth.github.scribe.ScribeServiceBuilder;
  35. import static com.google.common.base.Preconditions.checkState;
  36. import static java.lang.Long.parseLong;
  37. import static java.lang.String.format;
  38. import static org.sonar.auth.github.GitHubSettings.DEFAULT_API_URL;
  39. public class GitHubIdentityProvider implements OAuth2IdentityProvider {
  40. public static final String KEY = "github";
  41. private final GitHubSettings settings;
  42. private final UserIdentityFactory userIdentityFactory;
  43. private final ScribeGitHubApi scribeApi;
  44. private final GitHubRestClient gitHubRestClient;
  45. private final GithubApplicationClient githubAppClient;
  46. private final ScribeServiceBuilder scribeServiceBuilder;
  47. public GitHubIdentityProvider(GitHubSettings settings, UserIdentityFactory userIdentityFactory, ScribeGitHubApi scribeApi, GitHubRestClient gitHubRestClient,
  48. GithubApplicationClient githubAppClient, ScribeServiceBuilder scribeServiceBuilder) {
  49. this.settings = settings;
  50. this.userIdentityFactory = userIdentityFactory;
  51. this.scribeApi = scribeApi;
  52. this.gitHubRestClient = gitHubRestClient;
  53. this.githubAppClient = githubAppClient;
  54. this.scribeServiceBuilder = scribeServiceBuilder;
  55. }
  56. @Override
  57. public String getKey() {
  58. return KEY;
  59. }
  60. @Override
  61. public String getName() {
  62. return "GitHub";
  63. }
  64. @Override
  65. public Display getDisplay() {
  66. return Display.builder()
  67. .setIconPath("/images/alm/github.svg")
  68. .setBackgroundColor("#444444")
  69. .build();
  70. }
  71. @Override
  72. public boolean isEnabled() {
  73. return settings.isEnabled();
  74. }
  75. @Override
  76. public boolean allowsUsersToSignUp() {
  77. return settings.allowUsersToSignUp();
  78. }
  79. @Override
  80. public void init(InitContext context) {
  81. String state = context.generateCsrfState();
  82. OAuth20Service scribe = newScribeBuilder(context)
  83. .defaultScope(getScope())
  84. .build(scribeApi);
  85. String url = scribe.getAuthorizationUrl(state);
  86. context.redirectTo(url);
  87. }
  88. String getScope() {
  89. return (settings.syncGroups() || isOrganizationMembershipRequired()) ? "user:email,read:org" : "user:email";
  90. }
  91. @Override
  92. public void callback(CallbackContext context) {
  93. try {
  94. onCallback(context);
  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) throws InterruptedException, ExecutionException, IOException {
  103. context.verifyCsrfState();
  104. HttpRequest request = context.getHttpRequest();
  105. OAuth20Service scribe = scribeServiceBuilder.buildScribeService(settings.clientId(), settings.clientSecret(), context.getCallbackUrl(), scribeApi);
  106. String code = request.getParameter("code");
  107. OAuth2AccessToken accessToken = scribe.getAccessToken(code);
  108. GsonUser user = gitHubRestClient.getUser(scribe, accessToken);
  109. check(scribe, accessToken, user);
  110. final String email;
  111. if (user.getEmail() == null) {
  112. // if the user has not specified a public email address in their profile
  113. email = gitHubRestClient.getEmail(scribe, accessToken);
  114. } else {
  115. email = user.getEmail();
  116. }
  117. UserIdentity userIdentity = userIdentityFactory.create(user, email,
  118. settings.syncGroups() ? gitHubRestClient.getTeams(scribe, accessToken) : null);
  119. context.authenticate(userIdentity);
  120. context.redirectToRequestedPage();
  121. }
  122. private void check(OAuth20Service scribe, OAuth2AccessToken accessToken, GsonUser user) throws InterruptedException, ExecutionException, IOException {
  123. if (!isUserAuthorized(scribe, accessToken, user.getLogin())) {
  124. String message = settings.getOrganizations().isEmpty()
  125. ? format("'%s' must be a member of at least one organization which has installed the SonarQube GitHub app", user.getLogin())
  126. : format("'%s' must be a member of at least one organization: '%s'", user.getLogin(), String.join("', '", settings.getOrganizations().stream().sorted().toList()));
  127. throw new UnauthorizedException(message);
  128. }
  129. }
  130. private boolean isUserAuthorized(OAuth20Service scribe, OAuth2AccessToken accessToken, String login) throws IOException, ExecutionException, InterruptedException {
  131. if (isOrganizationMembershipRequired()) {
  132. return isOrganizationsMember(scribe, accessToken, login);
  133. } else {
  134. return isMemberOfInstallationOrganization(scribe, accessToken, login);
  135. }
  136. }
  137. private boolean isOrganizationMembershipRequired() {
  138. return !settings.getOrganizations().isEmpty();
  139. }
  140. private boolean isOrganizationsMember(OAuth20Service scribe, OAuth2AccessToken accessToken, String login) throws IOException, ExecutionException, InterruptedException {
  141. for (String organization : settings.getOrganizations()) {
  142. if (gitHubRestClient.isOrganizationMember(scribe, accessToken, organization, login)) {
  143. return true;
  144. }
  145. }
  146. return false;
  147. }
  148. private boolean isMemberOfInstallationOrganization(OAuth20Service scribe, OAuth2AccessToken accessToken, String login)
  149. throws IOException, ExecutionException, InterruptedException {
  150. GithubAppConfiguration githubAppConfiguration = githubAppConfiguration();
  151. List<GithubAppInstallation> githubAppInstallations = githubAppClient.getWhitelistedGithubAppInstallations(githubAppConfiguration);
  152. for (GithubAppInstallation installation : githubAppInstallations) {
  153. if (gitHubRestClient.isOrganizationMember(scribe, accessToken, installation.organizationName(), login)) {
  154. return true;
  155. }
  156. }
  157. return false;
  158. }
  159. private GithubAppConfiguration githubAppConfiguration() {
  160. String apiEndpoint = Optional.ofNullable(settings.apiURL()).orElse(DEFAULT_API_URL);
  161. try {
  162. return new GithubAppConfiguration(parseLong(settings.appId()), settings.privateKey(), apiEndpoint);
  163. } catch (NumberFormatException numberFormatException) {
  164. throw new IllegalStateException("Github configuration is not complete. Please check your configuration under the Authentication > GitHub tab");
  165. }
  166. }
  167. private ServiceBuilder newScribeBuilder(OAuth2IdentityProvider.OAuth2Context context) {
  168. checkState(isEnabled(), "GitHub authentication is disabled");
  169. return new ServiceBuilder(settings.clientId())
  170. .apiSecret(settings.clientSecret())
  171. .callback(context.getCallbackUrl());
  172. }
  173. }