repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
sonarqube
sonarqube-master/server/sonar-auth-github/src/test/java/org/sonar/auth/github/GsonTeamTest.java
/* * SonarQube * Copyright (C) 2009-2023 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.github; import java.util.List; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class GsonTeamTest { @Test public void parse_one_team() { List<GsonTeam> underTest = GsonTeam.parse( "[\n" + " {\n" + " \"name\": \"Developers\",\n" + " \"slug\": \"developers\",\n" + " \"organization\": {\n" + " \"login\": \"SonarSource\"\n" + " }\n" + " }\n" + "]"); assertThat(underTest).hasSize(1); assertThat(underTest.get(0).getId()).isEqualTo("developers"); assertThat(underTest.get(0).getOrganizationId()).isEqualTo("SonarSource"); } @Test public void parse_two_teams() { List<GsonTeam> underTest = GsonTeam.parse( "[\n" + " {\n" + " \"name\": \"Developers\",\n" + " \"slug\": \"developers\",\n" + " \"organization\": {\n" + " \"login\": \"SonarSource\"\n" + " }\n" + " },\n" + " {\n" + " \"login\": \"SonarSource Developers\",\n" + " \"organization\": {\n" + " \"login\": \"SonarQubeCommunity\"\n" + " }\n" + " }\n" + "]"); assertThat(underTest).hasSize(2); } @Test public void should_have_no_arg_constructor() { assertThat(new GsonTeam().getId()).isEmpty(); assertThat(new GsonTeam.GsonOrganization().getLogin()).isEmpty(); } }
2,323
29.986667
78
java
sonarqube
sonarqube-master/server/sonar-auth-github/src/test/java/org/sonar/auth/github/GsonUserTest.java
/* * SonarQube * Copyright (C) 2009-2023 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.github; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class GsonUserTest { @Test public void parse_json() { GsonUser user = GsonUser.parse( "{\n" + " \"login\": \"octocat\",\n" + " \"id\": 1,\n" + " \"name\": \"monalisa octocat\",\n" + " \"email\": \"octocat@github.com\"\n" + "}"); assertThat(user.getId()).isEqualTo("1"); assertThat(user.getLogin()).isEqualTo("octocat"); assertThat(user.getName()).isEqualTo("monalisa octocat"); assertThat(user.getEmail()).isEqualTo("octocat@github.com"); } @Test public void name_can_be_null() { GsonUser underTest = GsonUser.parse("{login:octocat, email:octocat@github.com}"); assertThat(underTest.getLogin()).isEqualTo("octocat"); assertThat(underTest.getName()).isNull(); } @Test public void email_can_be_null() { GsonUser underTest = GsonUser.parse("{login:octocat}"); assertThat(underTest.getLogin()).isEqualTo("octocat"); assertThat(underTest.getEmail()).isNull(); } }
1,939
33.035088
85
java
sonarqube
sonarqube-master/server/sonar-auth-github/src/test/java/org/sonar/auth/github/IntegrationTest.java
/* * SonarQube * Copyright (C) 2009-2023 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.github; import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicBoolean; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.PropertyDefinitions; 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 org.sonar.api.server.http.HttpResponse; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.server.http.JavaxHttpRequest; import org.sonar.server.property.InternalProperties; import org.sonar.server.property.InternalPropertiesImpl; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class IntegrationTest { private static final String CALLBACK_URL = "http://localhost/oauth/callback/github"; @Rule public MockWebServer github = new MockWebServer(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); // load settings with default values private MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, GitHubSettings.definitions())); private InternalProperties internalProperties = new InternalPropertiesImpl(db.getDbClient()); private GitHubSettings gitHubSettings = new GitHubSettings(settings.asConfig(), internalProperties, db.getDbClient()); private UserIdentityFactoryImpl userIdentityFactory = new UserIdentityFactoryImpl(); private ScribeGitHubApi scribeApi = new ScribeGitHubApi(gitHubSettings); private GitHubRestClient gitHubRestClient = new GitHubRestClient(gitHubSettings); private String gitHubUrl; private GitHubIdentityProvider underTest = new GitHubIdentityProvider(gitHubSettings, userIdentityFactory, scribeApi, gitHubRestClient); @Before public void enable() { gitHubUrl = format("http://%s:%d", github.getHostName(), github.getPort()); settings.setProperty("sonar.auth.github.clientId.secured", "the_id"); settings.setProperty("sonar.auth.github.clientSecret.secured", "the_secret"); settings.setProperty("sonar.auth.github.enabled", true); settings.setProperty("sonar.auth.github.apiUrl", gitHubUrl); settings.setProperty("sonar.auth.github.webUrl", gitHubUrl); } /** * First phase: SonarQube redirects browser to GitHub authentication form, requesting the * minimal access rights ("scope") to get user profile (login, name, email and others). */ @Test public void redirect_browser_to_github_authentication_form() throws Exception { DumbInitContext context = new DumbInitContext("the-csrf-state"); underTest.init(context); assertThat(context.redirectedTo).isEqualTo( gitHubSettings.webURL() + "login/oauth/authorize" + "?response_type=code" + "&client_id=the_id" + "&redirect_uri=" + URLEncoder.encode(CALLBACK_URL, StandardCharsets.UTF_8.name()) + "&scope=" + URLEncoder.encode("user:email", StandardCharsets.UTF_8.name()) + "&state=the-csrf-state"); } /** * Second phase: GitHub redirects browser to SonarQube at /oauth/callback/github?code={the verifier code}. * This SonarQube web service sends two requests to GitHub: * <ul> * <li>get an access token</li> * <li>get the profile of the authenticated user</li> * </ul> */ @Test public void callback_on_successful_authentication() throws IOException, InterruptedException { github.enqueue(newSuccessfulAccessTokenResponse()); // response of api.github.com/user github.enqueue(new MockResponse().setBody("{\"id\":\"ABCD\", \"login\":\"octocat\", \"name\":\"monalisa octocat\",\"email\":\"octocat@github.com\"}")); HttpServletRequest request = newRequest("the-verifier-code"); DumbCallbackContext callbackContext = new DumbCallbackContext(request); underTest.callback(callbackContext); assertThat(callbackContext.csrfStateVerified.get()).isTrue(); assertThat(callbackContext.userIdentity.getProviderId()).isEqualTo("ABCD"); assertThat(callbackContext.userIdentity.getProviderLogin()).isEqualTo("octocat"); assertThat(callbackContext.userIdentity.getName()).isEqualTo("monalisa octocat"); assertThat(callbackContext.userIdentity.getEmail()).isEqualTo("octocat@github.com"); assertThat(callbackContext.redirectedToRequestedPage.get()).isTrue(); // Verify the requests sent to GitHub RecordedRequest accessTokenGitHubRequest = github.takeRequest(); assertThat(accessTokenGitHubRequest.getMethod()).isEqualTo("POST"); assertThat(accessTokenGitHubRequest.getPath()).isEqualTo("/login/oauth/access_token"); assertThat(accessTokenGitHubRequest.getBody().readUtf8()).isEqualTo( "code=the-verifier-code" + "&redirect_uri=" + URLEncoder.encode(CALLBACK_URL, StandardCharsets.UTF_8.name()) + "&grant_type=authorization_code"); RecordedRequest profileGitHubRequest = github.takeRequest(); assertThat(profileGitHubRequest.getMethod()).isEqualTo("GET"); assertThat(profileGitHubRequest.getPath()).isEqualTo("/user"); } @Test public void should_retrieve_private_primary_verified_email_address() { github.enqueue(newSuccessfulAccessTokenResponse()); // response of api.github.com/user github.enqueue(new MockResponse().setBody("{\"id\":\"ABCD\", \"login\":\"octocat\", \"name\":\"monalisa octocat\",\"email\":null}")); // response of api.github.com/user/emails github.enqueue(new MockResponse().setBody( "[\n" + " {\n" + " \"email\": \"support@github.com\",\n" + " \"verified\": false,\n" + " \"primary\": false\n" + " },\n" + " {\n" + " \"email\": \"octocat@github.com\",\n" + " \"verified\": true,\n" + " \"primary\": true\n" + " },\n" + "]")); HttpServletRequest request = newRequest("the-verifier-code"); DumbCallbackContext callbackContext = new DumbCallbackContext(request); underTest.callback(callbackContext); assertThat(callbackContext.csrfStateVerified.get()).isTrue(); assertThat(callbackContext.userIdentity.getProviderId()).isEqualTo("ABCD"); assertThat(callbackContext.userIdentity.getProviderLogin()).isEqualTo("octocat"); assertThat(callbackContext.userIdentity.getName()).isEqualTo("monalisa octocat"); assertThat(callbackContext.userIdentity.getEmail()).isEqualTo("octocat@github.com"); assertThat(callbackContext.redirectedToRequestedPage.get()).isTrue(); } @Test public void should_not_fail_if_no_email() { github.enqueue(newSuccessfulAccessTokenResponse()); // response of api.github.com/user github.enqueue(new MockResponse().setBody("{\"id\":\"ABCD\", \"login\":\"octocat\", \"name\":\"monalisa octocat\",\"email\":null}")); // response of api.github.com/user/emails github.enqueue(new MockResponse().setBody("[]")); HttpServletRequest request = newRequest("the-verifier-code"); DumbCallbackContext callbackContext = new DumbCallbackContext(request); underTest.callback(callbackContext); assertThat(callbackContext.csrfStateVerified.get()).isTrue(); assertThat(callbackContext.userIdentity.getProviderId()).isEqualTo("ABCD"); assertThat(callbackContext.userIdentity.getProviderLogin()).isEqualTo("octocat"); assertThat(callbackContext.userIdentity.getName()).isEqualTo("monalisa octocat"); assertThat(callbackContext.userIdentity.getEmail()).isNull(); assertThat(callbackContext.redirectedToRequestedPage.get()).isTrue(); } @Test public void redirect_browser_to_github_authentication_form_with_group_sync() throws Exception { settings.setProperty("sonar.auth.github.groupsSync", true); DumbInitContext context = new DumbInitContext("the-csrf-state"); underTest.init(context); assertThat(context.redirectedTo).isEqualTo( gitHubSettings.webURL() + "login/oauth/authorize" + "?response_type=code" + "&client_id=the_id" + "&redirect_uri=" + URLEncoder.encode(CALLBACK_URL, StandardCharsets.UTF_8.name()) + "&scope=" + URLEncoder.encode("user:email,read:org", StandardCharsets.UTF_8.name()) + "&state=the-csrf-state"); } @Test public void callback_on_successful_authentication_with_group_sync() { settings.setProperty("sonar.auth.github.groupsSync", true); github.enqueue(newSuccessfulAccessTokenResponse()); // response of api.github.com/user github.enqueue(new MockResponse().setBody("{\"id\":\"ABCD\", \"login\":\"octocat\", \"name\":\"monalisa octocat\",\"email\":\"octocat@github.com\"}")); // response of api.github.com/user/teams github.enqueue(new MockResponse().setBody("[\n" + " {\n" + " \"slug\": \"developers\",\n" + " \"organization\": {\n" + " \"login\": \"SonarSource\"\n" + " }\n" + " }\n" + "]")); HttpServletRequest request = newRequest("the-verifier-code"); DumbCallbackContext callbackContext = new DumbCallbackContext(request); underTest.callback(callbackContext); assertThat(callbackContext.userIdentity.getGroups()).containsOnly("SonarSource/developers"); } @Test public void callback_on_successful_authentication_with_group_sync_on_many_pages() { settings.setProperty("sonar.auth.github.groupsSync", true); github.enqueue(newSuccessfulAccessTokenResponse()); // response of api.github.com/user github.enqueue(new MockResponse().setBody("{\"id\":\"ABCD\", \"login\":\"octocat\", \"name\":\"monalisa octocat\",\"email\":\"octocat@github.com\"}")); // responses of api.github.com/user/teams github.enqueue(new MockResponse() .setHeader("Link", "<" + gitHubUrl + "/user/teams?per_page=100&page=2>; rel=\"next\", <" + gitHubUrl + "/user/teams?per_page=100&page=2>; rel=\"last\"") .setBody("[\n" + " {\n" + " \"slug\": \"developers\",\n" + " \"organization\": {\n" + " \"login\": \"SonarSource\"\n" + " }\n" + " }\n" + "]")); github.enqueue(new MockResponse() .setHeader("Link", "<" + gitHubUrl + "/user/teams?per_page=100&page=1>; rel=\"prev\", <" + gitHubUrl + "/user/teams?per_page=100&page=1>; rel=\"first\"") .setBody("[\n" + " {\n" + " \"slug\": \"sonarsource-developers\",\n" + " \"organization\": {\n" + " \"login\": \"SonarQubeCommunity\"\n" + " }\n" + " }\n" + "]")); HttpServletRequest request = newRequest("the-verifier-code"); DumbCallbackContext callbackContext = new DumbCallbackContext(request); underTest.callback(callbackContext); assertThat(new TreeSet<>(callbackContext.userIdentity.getGroups())).containsOnly("SonarQubeCommunity/sonarsource-developers", "SonarSource/developers"); } @Test public void redirect_browser_to_github_authentication_form_with_organizations() throws Exception { settings.setProperty("sonar.auth.github.organizations", "example0, example1"); DumbInitContext context = new DumbInitContext("the-csrf-state"); underTest.init(context); assertThat(context.redirectedTo).isEqualTo( gitHubSettings.webURL() + "login/oauth/authorize" + "?response_type=code" + "&client_id=the_id" + "&redirect_uri=" + URLEncoder.encode(CALLBACK_URL, StandardCharsets.UTF_8.name()) + "&scope=" + URLEncoder.encode("user:email,read:org", StandardCharsets.UTF_8.name()) + "&state=the-csrf-state"); } @Test public void callback_on_successful_authentication_with_organizations_with_membership() { settings.setProperty("sonar.auth.github.organizations", "example0, example1"); github.enqueue(newSuccessfulAccessTokenResponse()); // response of api.github.com/user github.enqueue(new MockResponse().setBody("{\"id\":\"ABCD\", \"login\":\"octocat\", \"name\":\"monalisa octocat\",\"email\":\"octocat@github.com\"}")); // response of api.github.com/orgs/example0/members/user github.enqueue(new MockResponse().setResponseCode(204)); HttpServletRequest request = newRequest("the-verifier-code"); DumbCallbackContext callbackContext = new DumbCallbackContext(request); underTest.callback(callbackContext); assertThat(callbackContext.csrfStateVerified.get()).isTrue(); assertThat(callbackContext.userIdentity).isNotNull(); assertThat(callbackContext.redirectedToRequestedPage.get()).isTrue(); } @Test public void callback_on_successful_authentication_with_organizations_without_membership() { settings.setProperty("sonar.auth.github.organizations", "first_org,second_org"); github.enqueue(newSuccessfulAccessTokenResponse()); // response of api.github.com/user github.enqueue(new MockResponse().setBody("{\"id\":\"ABCD\", \"login\":\"octocat\", \"name\":\"monalisa octocat\",\"email\":\"octocat@github.com\"}")); // response of api.github.com/orgs/first_org/members/user github.enqueue(new MockResponse().setResponseCode(404).setBody("{}")); // response of api.github.com/orgs/second_org/members/user github.enqueue(new MockResponse().setResponseCode(404).setBody("{}")); HttpServletRequest request = newRequest("the-verifier-code"); DumbCallbackContext callbackContext = new DumbCallbackContext(request); try { underTest.callback(callbackContext); fail("exception expected"); } catch (UnauthorizedException e) { assertThat(e.getMessage()).contains("'octocat' must be a member of at least one organization:", "'first_org'", "'second_org'"); } } @Test public void callback_throws_ISE_if_error_when_requesting_user_profile() { github.enqueue(newSuccessfulAccessTokenResponse()); // api.github.com/user crashes github.enqueue(new MockResponse().setResponseCode(500).setBody("{error}")); DumbCallbackContext callbackContext = new DumbCallbackContext(newRequest("the-verifier-code")); try { underTest.callback(callbackContext); fail("exception expected"); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Fail to execute request '" + gitHubSettings.apiURL() + "user'. HTTP code: 500, response: {error}"); } assertThat(callbackContext.csrfStateVerified.get()).isTrue(); assertThat(callbackContext.userIdentity).isNull(); assertThat(callbackContext.redirectedToRequestedPage.get()).isFalse(); } @Test public void callback_throws_ISE_if_error_when_checking_membership() { settings.setProperty("sonar.auth.github.organizations", "example"); github.enqueue(newSuccessfulAccessTokenResponse()); // response of api.github.com/user github.enqueue(new MockResponse().setBody("{\"id\":\"ABCD\", \"login\":\"octocat\", \"name\":\"monalisa octocat\",\"email\":\"octocat@github.com\"}")); // crash of api.github.com/orgs/example/members/user github.enqueue(new MockResponse().setResponseCode(500).setBody("{error}")); HttpServletRequest request = newRequest("the-verifier-code"); DumbCallbackContext callbackContext = new DumbCallbackContext(request); try { underTest.callback(callbackContext); fail("exception expected"); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Fail to execute request '" + gitHubSettings.apiURL() + "orgs/example/members/octocat'. HTTP code: 500, response: {error}"); } } /** * Response sent by GitHub to SonarQube when generating an access token */ private static MockResponse newSuccessfulAccessTokenResponse() { // github does not return the standard JSON format but plain-text // see https://developer.github.com/v3/oauth/ return new MockResponse().setBody("access_token=e72e16c7e42f292c6912e7710c838347ae178b4a&scope=user%2Cgist&token_type=bearer"); } private static HttpServletRequest newRequest(String verifierCode) { HttpServletRequest request = mock(HttpServletRequest.class); when(request.getParameter("code")).thenReturn(verifierCode); return request; } private static class DumbCallbackContext implements OAuth2IdentityProvider.CallbackContext { final HttpServletRequest request; final AtomicBoolean csrfStateVerified = new AtomicBoolean(false); final AtomicBoolean redirectedToRequestedPage = new AtomicBoolean(false); UserIdentity userIdentity = null; public DumbCallbackContext(HttpServletRequest request) { this.request = request; } @Override public void verifyCsrfState() { this.csrfStateVerified.set(true); } @Override public void verifyCsrfState(String parameterName) { throw new UnsupportedOperationException("not used"); } @Override public void redirectToRequestedPage() { redirectedToRequestedPage.set(true); } @Override public void authenticate(UserIdentity userIdentity) { this.userIdentity = userIdentity; } @Override public String getCallbackUrl() { return CALLBACK_URL; } @Override public HttpRequest getHttpRequest() { return new JavaxHttpRequest(request); } @Override public HttpResponse getHttpResponse() { throw new UnsupportedOperationException("not used"); } @Override public HttpServletRequest getRequest() { throw new UnsupportedOperationException("deprecated"); } @Override public HttpServletResponse getResponse() { throw new UnsupportedOperationException("deprecated"); } } private static class DumbInitContext implements OAuth2IdentityProvider.InitContext { String redirectedTo = null; private final String generatedCsrfState; public DumbInitContext(String generatedCsrfState) { this.generatedCsrfState = generatedCsrfState; } @Override public String generateCsrfState() { return generatedCsrfState; } @Override public void redirectTo(String url) { this.redirectedTo = url; } @Override public String getCallbackUrl() { return CALLBACK_URL; } @Override public HttpRequest getHttpRequest() { return null; } @Override public HttpResponse getHttpResponse() { return null; } @Override public HttpServletRequest getRequest() { return null; } @Override public HttpServletResponse getResponse() { return null; } } }
19,854
40.278586
167
java
sonarqube
sonarqube-master/server/sonar-auth-github/src/test/java/org/sonar/auth/github/UserIdentityFactoryImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 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.github; import org.junit.Test; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.authentication.UserIdentity; import org.sonar.api.utils.System2; import static org.assertj.core.api.Assertions.assertThat; public class UserIdentityFactoryImplTest { private MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, GitHubSettings.definitions())); private UserIdentityFactoryImpl underTest = new UserIdentityFactoryImpl(); @Test public void no_email() { GsonUser gson = new GsonUser("ABCD", "octocat", "monalisa octocat", null); UserIdentity identity = underTest.create(gson, null, null); assertThat(identity.getProviderLogin()).isEqualTo("octocat"); assertThat(identity.getName()).isEqualTo("monalisa octocat"); assertThat(identity.getEmail()).isNull(); } @Test public void empty_name_is_replaced_by_provider_login() { GsonUser gson = new GsonUser("ABCD", "octocat", "", "octocat@github.com"); UserIdentity identity = underTest.create(gson, null, null); assertThat(identity.getName()).isEqualTo("octocat"); } @Test public void null_name_is_replaced_by_provider_login() { GsonUser gson = new GsonUser("ABCD", "octocat", null, "octocat@github.com"); UserIdentity identity = underTest.create(gson, null, null); assertThat(identity.getName()).isEqualTo("octocat"); } }
2,309
34.538462
122
java
sonarqube
sonarqube-master/server/sonar-auth-gitlab/src/main/java/org/sonar/auth/gitlab/GitLabIdentityProvider.java
/* * SonarQube * Copyright (C) 2009-2023 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 com.github.scribejava.core.builder.ServiceBuilder; import com.github.scribejava.core.builder.ServiceBuilderOAuth20; import com.github.scribejava.core.model.OAuth2AccessToken; import com.github.scribejava.core.model.OAuthConstants; import com.github.scribejava.core.oauth.OAuth20Service; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.stream.Stream; import org.sonar.api.server.authentication.Display; import org.sonar.api.server.authentication.OAuth2IdentityProvider; import org.sonar.api.server.authentication.UserIdentity; import org.sonar.api.server.http.HttpRequest; import static com.google.common.base.Preconditions.checkState; import static java.util.stream.Collectors.toSet; public class GitLabIdentityProvider implements OAuth2IdentityProvider { public static final String API_SCOPE = "api"; public static final String READ_USER_SCOPE = "read_user"; private final GitLabSettings gitLabSettings; private final ScribeGitLabOauth2Api scribeApi; private final GitLabRestClient gitLabRestClient; public GitLabIdentityProvider(GitLabSettings gitLabSettings, GitLabRestClient gitLabRestClient, ScribeGitLabOauth2Api scribeApi) { this.gitLabSettings = gitLabSettings; this.scribeApi = scribeApi; this.gitLabRestClient = gitLabRestClient; } @Override public String getKey() { return "gitlab"; } @Override public String getName() { return "GitLab"; } @Override public Display getDisplay() { return Display.builder() .setIconPath("/images/alm/gitlab.svg") .setBackgroundColor("#6a4fbb") .build(); } @Override public boolean isEnabled() { return gitLabSettings.isEnabled(); } @Override public boolean allowsUsersToSignUp() { return gitLabSettings.allowUsersToSignUp(); } @Override public void init(InitContext context) { String state = context.generateCsrfState(); OAuth20Service scribe = newScribeBuilder(context, gitLabSettings.syncUserGroups()).build(scribeApi); String url = scribe.getAuthorizationUrl(state); context.redirectTo(url); } private ServiceBuilderOAuth20 newScribeBuilder(OAuth2Context context, boolean syncUserGroups) { checkState(isEnabled(), "GitLab authentication is disabled"); return new ServiceBuilder(gitLabSettings.applicationId()) .apiSecret(gitLabSettings.secret()) .defaultScope(syncUserGroups ? API_SCOPE : READ_USER_SCOPE) .callback(context.getCallbackUrl()); } @Override public void callback(CallbackContext context) { try { onCallback(context); } catch (IOException | ExecutionException e) { throw new IllegalStateException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException(e); } } private void onCallback(CallbackContext context) throws InterruptedException, ExecutionException, IOException { HttpRequest request = context.getHttpRequest(); OAuth20Service scribe = newScribeBuilder(context, gitLabSettings.syncUserGroups()).build(scribeApi); String code = request.getParameter(OAuthConstants.CODE); OAuth2AccessToken accessToken = scribe.getAccessToken(code); GsonUser user = gitLabRestClient.getUser(scribe, accessToken); UserIdentity.Builder builder = UserIdentity.builder() .setProviderId(Long.toString(user.getId())) .setProviderLogin(user.getUsername()) .setName(user.getName()) .setEmail(user.getEmail()); if (gitLabSettings.syncUserGroups()) { builder.setGroups(getGroups(scribe, accessToken)); } context.authenticate(builder.build()); context.redirectToRequestedPage(); } private Set<String> getGroups(OAuth20Service scribe, OAuth2AccessToken accessToken) { List<GsonGroup> groups = gitLabRestClient.getGroups(scribe, accessToken); return Stream.of(groups) .flatMap(Collection::stream) .map(GsonGroup::getFullPath) .collect(toSet()); } }
4,950
33.866197
132
java
sonarqube
sonarqube-master/server/sonar-auth-gitlab/src/main/java/org/sonar/auth/gitlab/GitLabModule.java
/* * SonarQube * Copyright (C) 2009-2023 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 java.util.List; import org.sonar.api.config.PropertyDefinition; import org.sonar.core.platform.Module; import static org.sonar.auth.gitlab.GitLabSettings.definitions; public class GitLabModule extends Module { @Override protected void configureModule() { add( GitLabIdentityProvider.class, GitLabRestClient.class, GitLabSettings.class, ScribeGitLabOauth2Api.class); List<PropertyDefinition> definitions = definitions(); add(definitions.toArray(new Object[definitions.size()])); } }
1,410
32.595238
75
java
sonarqube
sonarqube-master/server/sonar-auth-gitlab/src/main/java/org/sonar/auth/gitlab/GitLabRestClient.java
/* * SonarQube * Copyright (C) 2009-2023 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 com.github.scribejava.core.model.OAuth2AccessToken; import com.github.scribejava.core.model.Response; import com.github.scribejava.core.oauth.OAuth20Service; import java.io.IOException; import java.util.List; import org.sonar.auth.OAuthRestClient; public class GitLabRestClient { private static final String API_SUFFIX = "/api/v4"; private final GitLabSettings settings; public GitLabRestClient(GitLabSettings settings) { this.settings = settings; } GsonUser getUser(OAuth20Service scribe, OAuth2AccessToken accessToken) { try (Response response = OAuthRestClient.executeRequest(settings.url() + API_SUFFIX + "/user", scribe, accessToken)) { String responseBody = response.getBody(); return GsonUser.parse(responseBody); } catch (IOException e) { throw new IllegalStateException("Failed to get gitlab user", e); } } List<GsonGroup> getGroups(OAuth20Service scribe, OAuth2AccessToken accessToken) { return OAuthRestClient.executePaginatedRequest(settings.url() + API_SUFFIX + "/groups?min_access_level=10", scribe, accessToken, GsonGroup::parse); } }
1,992
37.326923
151
java
sonarqube
sonarqube-master/server/sonar-auth-gitlab/src/main/java/org/sonar/auth/gitlab/GitLabSettings.java
/* * SonarQube * Copyright (C) 2009-2023 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 java.util.Arrays; import java.util.List; import org.sonar.api.PropertyType; import org.sonar.api.config.Configuration; import org.sonar.api.config.PropertyDefinition; import static java.lang.String.valueOf; import static org.sonar.api.PropertyType.BOOLEAN; import static org.sonar.api.PropertyType.PASSWORD; public class GitLabSettings { public static final String GITLAB_AUTH_ENABLED = "sonar.auth.gitlab.enabled"; public static final String GITLAB_AUTH_URL = "sonar.auth.gitlab.url"; public static final String GITLAB_AUTH_APPLICATION_ID = "sonar.auth.gitlab.applicationId.secured"; public static final String GITLAB_AUTH_SECRET = "sonar.auth.gitlab.secret.secured"; public static final String GITLAB_AUTH_ALLOW_USERS_TO_SIGNUP = "sonar.auth.gitlab.allowUsersToSignUp"; public static final String GITLAB_AUTH_SYNC_USER_GROUPS = "sonar.auth.gitlab.groupsSync"; private static final String CATEGORY = "authentication"; private static final String SUBCATEGORY = "gitlab"; private final Configuration configuration; public GitLabSettings(Configuration configuration) { this.configuration = configuration; } public String url() { String url = configuration.get(GITLAB_AUTH_URL).orElse(null); if (url != null && url.endsWith("/")) { return url.substring(0, url.length() - 1); } return url; } public String applicationId() { return configuration.get(GITLAB_AUTH_APPLICATION_ID).orElse(null); } public String secret() { return configuration.get(GITLAB_AUTH_SECRET).orElse(null); } public boolean isEnabled() { return configuration.getBoolean(GITLAB_AUTH_ENABLED).orElse(false) && applicationId() != null && secret() != null; } public boolean allowUsersToSignUp() { return configuration.getBoolean(GITLAB_AUTH_ALLOW_USERS_TO_SIGNUP).orElse(false); } public boolean syncUserGroups() { return configuration.getBoolean(GITLAB_AUTH_SYNC_USER_GROUPS).orElse(false); } static List<PropertyDefinition> definitions() { return Arrays.asList( PropertyDefinition.builder(GITLAB_AUTH_ENABLED) .name("Enabled") .description("Enable Gitlab users to login. Value is ignored if URL, Application ID, and Secret are not set.") .category(CATEGORY) .subCategory(SUBCATEGORY) .type(BOOLEAN) .defaultValue(valueOf(false)) .index(1) .build(), PropertyDefinition.builder(GITLAB_AUTH_URL) .name("GitLab URL") .description("URL to access GitLab.") .category(CATEGORY) .subCategory(SUBCATEGORY) .defaultValue("https://gitlab.com") .index(2) .build(), PropertyDefinition.builder(GITLAB_AUTH_APPLICATION_ID) .name("Application ID") .description("Application ID provided by GitLab when registering the application.") .category(CATEGORY) .subCategory(SUBCATEGORY) .index(3) .build(), PropertyDefinition.builder(GITLAB_AUTH_SECRET) .name("Secret") .description("Secret provided by GitLab when registering the application.") .category(CATEGORY) .subCategory(SUBCATEGORY) .type(PASSWORD) .index(4) .build(), PropertyDefinition.builder(GITLAB_AUTH_ALLOW_USERS_TO_SIGNUP) .name("Allow users to sign up") .description("Allow new users to authenticate. When set to 'false', only existing users will be able to authenticate to the server.") .category(CATEGORY) .subCategory(SUBCATEGORY) .type(BOOLEAN) .defaultValue(valueOf(true)) .index(5) .build(), PropertyDefinition.builder(GITLAB_AUTH_SYNC_USER_GROUPS) .deprecatedKey("sonar.auth.gitlab.sync_user_groups") .name("Synchronize user groups") .description("For each GitLab group they belong to, the user will be associated to a group with the same name (if it exists) in SonarQube." + " If enabled, the GitLab Oauth2 application will need to provide the api scope.") .category(CATEGORY) .subCategory(SUBCATEGORY) .type(PropertyType.BOOLEAN) .defaultValue(valueOf(false)) .index(6) .build()); } }
5,102
37.08209
149
java
sonarqube
sonarqube-master/server/sonar-auth-gitlab/src/main/java/org/sonar/auth/gitlab/GsonGroup.java
/* * SonarQube * Copyright (C) 2009-2023 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 com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.Collection; import java.util.List; /** * Lite representation of JSON response of GET https://docs.gitlab.com/ee/api/groups.html */ public class GsonGroup { @SerializedName("full_path") private String fullPath; public GsonGroup() { // http://stackoverflow.com/a/18645370/229031 this(""); } GsonGroup(String fullPath) { this.fullPath = fullPath; } String getFullPath() { return fullPath; } static List<GsonGroup> parse(String json) { Type collectionType = new TypeToken<Collection<GsonGroup>>() { }.getType(); Gson gson = new Gson(); return gson.fromJson(json, collectionType); } }
1,686
28.086207
89
java
sonarqube
sonarqube-master/server/sonar-auth-gitlab/src/main/java/org/sonar/auth/gitlab/GsonUser.java
/* * SonarQube * Copyright (C) 2009-2023 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 com.google.gson.Gson; /** * Lite representation of JSON response of GET https://gitlab.com/api/v4/user */ public class GsonUser { private long id; private String username; private String name; private String email; public GsonUser() { // even if empty constructor is not required for Gson, it is strongly // recommended: // http://stackoverflow.com/a/18645370/229031 } public long getId() { return id; } public String getUsername() { return username; } public String getName() { return name; } public String getEmail() { return email; } public static GsonUser parse(String json) { Gson gson = new Gson(); return gson.fromJson(json, GsonUser.class); } }
1,612
25.883333
77
java
sonarqube
sonarqube-master/server/sonar-auth-gitlab/src/main/java/org/sonar/auth/gitlab/ScribeGitLabOauth2Api.java
/* * SonarQube * Copyright (C) 2009-2023 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 com.github.scribejava.core.builder.api.DefaultApi20; public class ScribeGitLabOauth2Api extends DefaultApi20 { private final GitLabSettings settings; public ScribeGitLabOauth2Api(GitLabSettings settings) { this.settings = settings; } @Override public String getAccessTokenEndpoint() { return settings.url() + "/oauth/token"; } @Override protected String getAuthorizationBaseUrl() { return settings.url() + "/oauth/authorize"; } }
1,348
30.372093
75
java
sonarqube
sonarqube-master/server/sonar-auth-gitlab/src/main/java/org/sonar/auth/gitlab/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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. */ @ParametersAreNonnullByDefault package org.sonar.auth.gitlab; import javax.annotation.ParametersAreNonnullByDefault;
961
39.083333
75
java
sonarqube
sonarqube-master/server/sonar-auth-gitlab/src/test/java/org/sonar/auth/gitlab/GitLabIdentityProviderTest.java
/* * SonarQube * Copyright (C) 2009-2023 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 org.assertj.core.api.Assertions; import org.junit.Test; import org.sonar.api.server.authentication.Display; import org.sonar.api.server.authentication.OAuth2IdentityProvider; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class GitLabIdentityProviderTest { @Test public void test_identity_provider() { GitLabSettings gitLabSettings = mock(GitLabSettings.class); when(gitLabSettings.isEnabled()).thenReturn(true); when(gitLabSettings.allowUsersToSignUp()).thenReturn(true); GitLabIdentityProvider gitLabIdentityProvider = new GitLabIdentityProvider(gitLabSettings, new GitLabRestClient(gitLabSettings), new ScribeGitLabOauth2Api(gitLabSettings)); assertThat(gitLabIdentityProvider.getKey()).isEqualTo("gitlab"); assertThat(gitLabIdentityProvider.getName()).isEqualTo("GitLab"); Display display = gitLabIdentityProvider.getDisplay(); assertThat(display.getIconPath()).isEqualTo("/images/alm/gitlab.svg"); assertThat(display.getBackgroundColor()).isEqualTo("#6a4fbb"); assertThat(gitLabIdentityProvider.isEnabled()).isTrue(); assertThat(gitLabIdentityProvider.allowsUsersToSignUp()).isTrue(); } @Test public void test_init() { GitLabSettings gitLabSettings = mock(GitLabSettings.class); when(gitLabSettings.isEnabled()).thenReturn(true); when(gitLabSettings.allowUsersToSignUp()).thenReturn(true); when(gitLabSettings.applicationId()).thenReturn("123"); when(gitLabSettings.secret()).thenReturn("456"); when(gitLabSettings.url()).thenReturn("http://server"); when(gitLabSettings.syncUserGroups()).thenReturn(true); GitLabIdentityProvider gitLabIdentityProvider = new GitLabIdentityProvider(gitLabSettings, new GitLabRestClient(gitLabSettings), new ScribeGitLabOauth2Api(gitLabSettings)); OAuth2IdentityProvider.InitContext initContext = mock(OAuth2IdentityProvider.InitContext.class); when(initContext.getCallbackUrl()).thenReturn("http://server/callback"); gitLabIdentityProvider.init(initContext); verify(initContext).redirectTo("http://server/oauth/authorize?response_type=code&client_id=123&redirect_uri=http%3A%2F%2Fserver%2Fcallback&scope=api"); } @Test public void test_init_without_sync() { GitLabSettings gitLabSettings = mock(GitLabSettings.class); when(gitLabSettings.isEnabled()).thenReturn(true); when(gitLabSettings.allowUsersToSignUp()).thenReturn(true); when(gitLabSettings.applicationId()).thenReturn("123"); when(gitLabSettings.secret()).thenReturn("456"); when(gitLabSettings.url()).thenReturn("http://server"); when(gitLabSettings.syncUserGroups()).thenReturn(false); GitLabIdentityProvider gitLabIdentityProvider = new GitLabIdentityProvider(gitLabSettings, new GitLabRestClient(gitLabSettings), new ScribeGitLabOauth2Api(gitLabSettings)); OAuth2IdentityProvider.InitContext initContext = mock(OAuth2IdentityProvider.InitContext.class); when(initContext.getCallbackUrl()).thenReturn("http://server/callback"); gitLabIdentityProvider.init(initContext); verify(initContext).redirectTo("http://server/oauth/authorize?response_type=code&client_id=123&redirect_uri=http%3A%2F%2Fserver%2Fcallback&scope=read_user"); } @Test public void fail_to_init() { GitLabSettings gitLabSettings = mock(GitLabSettings.class); when(gitLabSettings.isEnabled()).thenReturn(false); when(gitLabSettings.allowUsersToSignUp()).thenReturn(true); when(gitLabSettings.applicationId()).thenReturn("123"); when(gitLabSettings.secret()).thenReturn("456"); when(gitLabSettings.url()).thenReturn("http://server"); GitLabIdentityProvider gitLabIdentityProvider = new GitLabIdentityProvider(gitLabSettings, new GitLabRestClient(gitLabSettings), new ScribeGitLabOauth2Api(gitLabSettings)); OAuth2IdentityProvider.InitContext initContext = mock(OAuth2IdentityProvider.InitContext.class); when(initContext.getCallbackUrl()).thenReturn("http://server/callback"); Assertions.assertThatThrownBy(() -> gitLabIdentityProvider.init(initContext)) .hasMessage("GitLab authentication is disabled") .isInstanceOf(IllegalStateException.class); } }
5,193
46.218182
161
java
sonarqube
sonarqube-master/server/sonar-auth-gitlab/src/test/java/org/sonar/auth/gitlab/GitLabModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 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 java.util.ArrayList; import java.util.List; import java.util.Optional; import org.junit.Test; import org.sonar.core.platform.Container; import static java.util.Collections.unmodifiableList; import static org.assertj.core.api.Assertions.assertThat; public class GitLabModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new GitLabModule().configure(container); assertThat(container.getAddedObjects()).hasSize(10); } private static class ListContainer implements Container { private final List<Object> objects = new ArrayList<>(); @Override public Container add(Object... objects) { this.objects.add(objects); return this; } public List<Object> getAddedObjects() { return unmodifiableList(new ArrayList<>(objects)); } @Override public <T> T getComponentByType(Class<T> type) { throw new UnsupportedOperationException(); } @Override public <T> Optional<T> getOptionalComponentByType(Class<T> type) { throw new UnsupportedOperationException(); } @Override public <T> List<T> getComponentsByType(Class<T> type) { throw new UnsupportedOperationException(); } @Override public Container getParent() { throw new UnsupportedOperationException(); } } }
2,233
29.60274
75
java
sonarqube
sonarqube-master/server/sonar-auth-gitlab/src/test/java/org/sonar/auth/gitlab/GitLabSettingsTest.java
/* * SonarQube * Copyright (C) 2009-2023 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 org.junit.Before; import org.junit.Test; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import static org.assertj.core.api.Assertions.assertThat; 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 GitLabSettingsTest { private MapSettings settings; private GitLabSettings config; @Before public void prepare() { settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, GitLabSettings.definitions())); config = new GitLabSettings(settings.asConfig()); } @Test public void test_settings() { assertThat(config.url()).isEqualTo("https://gitlab.com"); settings.setProperty(GITLAB_AUTH_URL, "https://gitlab.com/api/"); assertThat(config.url()).isEqualTo("https://gitlab.com/api"); settings.setProperty(GITLAB_AUTH_URL, "https://gitlab.com/api"); assertThat(config.url()).isEqualTo("https://gitlab.com/api"); assertThat(config.isEnabled()).isFalse(); settings.setProperty(GITLAB_AUTH_ENABLED, "true"); assertThat(config.isEnabled()).isFalse(); settings.setProperty(GITLAB_AUTH_APPLICATION_ID, "1234"); assertThat(config.isEnabled()).isFalse(); settings.setProperty(GITLAB_AUTH_SECRET, "5678"); assertThat(config.isEnabled()).isTrue(); assertThat(config.applicationId()).isEqualTo("1234"); assertThat(config.secret()).isEqualTo("5678"); assertThat(config.allowUsersToSignUp()).isTrue(); settings.setProperty(GITLAB_AUTH_ALLOW_USERS_TO_SIGNUP, "false"); assertThat(config.allowUsersToSignUp()).isFalse(); assertThat(config.syncUserGroups()).isFalse(); settings.setProperty(GITLAB_AUTH_SYNC_USER_GROUPS, true); assertThat(config.syncUserGroups()).isTrue(); } }
3,067
38.333333
104
java
sonarqube
sonarqube-master/server/sonar-auth-gitlab/src/test/java/org/sonar/auth/gitlab/GsonGroupTest.java
/* * SonarQube * Copyright (C) 2009-2023 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 java.util.List; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class GsonGroupTest { @Test public void test_parse() { List<GsonGroup> groups = GsonGroup.parse("[{\n" + "\"id\": 123456789,\n" + "\"web_url\": \"https://gitlab.com/groups/my-awesome-group/my-project\",\n" + "\"name\": \"my-project\",\n" + "\"path\": \"my-project\",\n" + "\"description\": \"\",\n" + "\"visibility\": \"private\",\n" + "\"lfs_enabled\": true,\n" + "\"avatar_url\": null,\n" + "\"request_access_enabled\": false,\n" + "\"full_name\": \"my-awesome-group / my-project\",\n" + "\"full_path\": \"my-awesome-group/my-project\",\n" + "\"parent_id\": 987654321,\n" + "\"ldap_cn\": null,\n" + "\"ldap_access\": null\n" + "}]"); assertThat(groups).isNotNull(); assertThat(groups.size()).isOne(); assertThat(groups.get(0).getFullPath()).isEqualTo("my-awesome-group/my-project"); } }
1,891
34.698113
85
java
sonarqube
sonarqube-master/server/sonar-auth-gitlab/src/test/java/org/sonar/auth/gitlab/GsonUserTest.java
/* * SonarQube * Copyright (C) 2009-2023 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 org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class GsonUserTest { @Test public void test_parse() { GsonUser gsonUser = GsonUser.parse("{\n" + "\"id\": 4418804,\n" + "\"name\": \"Pierre Guillot\",\n" + "\"username\": \"pierre-guillot-sonarsource\",\n" + "\"state\": \"active\",\n" + "\"avatar_url\": \"https://secure.gravatar.com/avatar/fe075537af1b94fd1cea160e5359e178?s=80&d=identicon\",\n" + "\"web_url\": \"https://gitlab.com/pierre-guillot-sonarsource\",\n" + "\"created_at\": \"2019-08-06T08:36:09.031Z\",\n" + "\"bio\": null,\n" + "\"location\": null,\n" + "\"public_email\": \"\",\n" + "\"skype\": \"\",\n" + "\"linkedin\": \"\",\n" + "\"twitter\": \"\",\n" + "\"website_url\": \"\",\n" + "\"organization\": null,\n" + "\"last_sign_in_at\": \"2019-08-19T11:53:15.041Z\",\n" + "\"confirmed_at\": \"2019-08-06T08:36:08.246Z\",\n" + "\"last_activity_on\": \"2019-08-23\",\n" + "\"email\": \"pierre.guillot@sonarsource.com\",\n" + "\"theme_id\": 1,\n" + "\"color_scheme_id\": 1,\n" + "\"projects_limit\": 100000,\n" + "\"current_sign_in_at\": \"2019-08-23T09:27:42.853Z\",\n" + "\"identities\": [\n" + "{\n" + "\"provider\": \"github\",\n" + "\"extern_uid\": \"50145663\",\n" + "\"saml_provider_id\": null\n" + "}\n" + "],\n" + "\"can_create_group\": true,\n" + "\"can_create_project\": true,\n" + "\"two_factor_enabled\": false,\n" + "\"external\": false,\n" + "\"private_profile\": false,\n" + "\"shared_runners_minutes_limit\": 50000,\n" + "\"extra_shared_runners_minutes_limit\": null\n" + "}"); assertThat(gsonUser).isNotNull(); assertThat(gsonUser.getUsername()).isEqualTo("pierre-guillot-sonarsource"); assertThat(gsonUser.getName()).isEqualTo("Pierre Guillot"); assertThat(gsonUser.getEmail()).isEqualTo("pierre.guillot@sonarsource.com"); } }
2,930
37.565789
117
java
sonarqube
sonarqube-master/server/sonar-auth-gitlab/src/test/java/org/sonar/auth/gitlab/IntegrationTest.java
/* * SonarQube * Copyright (C) 2009-2023 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.assertj.core.api.Assertions; 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.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.mockito.Mockito.verify; import static org.mockito.Mockito.when; 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"); } @Test public void authenticate_user() { 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); gitlab.enqueue(new MockResponse().setBody( "{\n" + " \"access_token\": \"de6780bc506a0446309bd9362820ba8aed28aa506c71eedbe1c5c4f9dd350e54\",\n" + " \"token_type\": \"bearer\",\n" + " \"expires_in\": 7200,\n" + " \"refresh_token\": \"8257e65c97202ed1726cf9571600918f3bffb2544b26e00a61df9897668c33a1\"\n" + "}")); // response of /user gitlab.enqueue(new MockResponse().setBody("{\"id\": 123, \"username\":\"toto\", \"name\":\"Toto Toto\",\"email\":\"toto@toto.com\"}")); 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 synchronize_groups() throws InterruptedException { mapSettings.setProperty(GITLAB_AUTH_SYNC_USER_GROUPS, "true"); 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); gitlab.enqueue(new MockResponse().setBody( "{\n" + " \"access_token\": \"de6780bc506a0446309bd9362820ba8aed28aa506c71eedbe1c5c4f9dd350e54\",\n" + " \"token_type\": \"bearer\",\n" + " \"expires_in\": 7200,\n" + " \"refresh_token\": \"8257e65c97202ed1726cf9571600918f3bffb2544b26e00a61df9897668c33a1\"\n" + "}")); // response of /user gitlab.enqueue(new MockResponse().setBody("{\"id\": 123, \"username\": \"username\", \"name\": \"name\"}")); // response of /groups gitlab.enqueue(new MockResponse().setBody("[{\"full_path\": \"group1\"}, {\"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 synchronize_groups_on_many_pages() { mapSettings.setProperty(GITLAB_AUTH_SYNC_USER_GROUPS, "true"); 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); gitlab.enqueue(new MockResponse().setBody( "{\n" + " \"access_token\": \"de6780bc506a0446309bd9362820ba8aed28aa506c71eedbe1c5c4f9dd350e54\",\n" + " \"token_type\": \"bearer\",\n" + " \"expires_in\": 7200,\n" + " \"refresh_token\": \"8257e65c97202ed1726cf9571600918f3bffb2544b26e00a61df9897668c33a1\"\n" + "}")); // response of /user gitlab.enqueue(new MockResponse().setBody("{\"id\": 123, \"username\": \"username\", \"name\": \"name\"}")); // response of /groups, first page gitlab.enqueue(new MockResponse() .setBody("[{\"full_path\": \"group1\"}, {\"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 of /groups, page 2 gitlab.enqueue(new MockResponse() .setBody("[{\"full_path\": \"group3\"}, {\"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 of /groups, page 3 gitlab.enqueue(new MockResponse() .setBody("[{\"full_path\": \"group5\"}, {\"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 fail_to_authenticate() { 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); gitlab.enqueue(new MockResponse().setBody( "{\n" + " \"access_token\": \"de6780bc506a0446309bd9362820ba8aed28aa506c71eedbe1c5c4f9dd350e54\",\n" + " \"token_type\": \"bearer\",\n" + " \"expires_in\": 7200,\n" + " \"refresh_token\": \"8257e65c97202ed1726cf9571600918f3bffb2544b26e00a61df9897668c33a1\"\n" + "}")); gitlab.enqueue(new MockResponse().setResponseCode(404).setBody("empty")); Assertions.assertThatThrownBy(() -> gitLabIdentityProvider.callback(callbackContext)) .hasMessage("Fail to execute request '" + gitLabSettings.url() + "/api/v4/user'. HTTP code: 404, response: empty") .isInstanceOf((IllegalStateException.class)); } }
9,799
50.308901
170
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/it/java/org/sonar/auth/ldap/DefaultLdapAuthenticatorIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import org.junit.ClassRule; import org.junit.Test; import org.sonar.api.server.http.HttpRequest; import org.sonar.auth.ldap.server.LdapServer; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class DefaultLdapAuthenticatorIT { /** * A reference to the original ldif file */ public static final String USERS_EXAMPLE_ORG_LDIF = "/users.example.org.ldif"; /** * A reference to an additional ldif file. */ public static final String USERS_INFOSUPPORT_COM_LDIF = "/users.infosupport.com.ldif"; @ClassRule public static LdapServer exampleServer = new LdapServer(USERS_EXAMPLE_ORG_LDIF); @ClassRule public static LdapServer infosupportServer = new LdapServer(USERS_INFOSUPPORT_COM_LDIF, "infosupport.com", "dc=infosupport,dc=com"); @Test public void testNoConnection() { exampleServer.disableAnonymousAccess(); try { LdapSettingsManager settingsManager = new LdapSettingsManager( LdapSettingsFactory.generateAuthenticationSettings(exampleServer, null, LdapContextFactory.AUTH_METHOD_SIMPLE).asConfig()); DefaultLdapAuthenticator authenticator = new DefaultLdapAuthenticator(settingsManager.getContextFactories(), settingsManager.getUserMappings()); boolean isAuthenticationSuccessful = authenticator.doAuthenticate(createContext("godin", "secret1")).isSuccess(); assertThat(isAuthenticationSuccessful).isTrue(); } finally { exampleServer.enableAnonymousAccess(); } } @Test public void testSimple() { LdapSettingsManager settingsManager = new LdapSettingsManager( LdapSettingsFactory.generateAuthenticationSettings(exampleServer, null, LdapContextFactory.AUTH_METHOD_SIMPLE).asConfig()); DefaultLdapAuthenticator authenticator = new DefaultLdapAuthenticator(settingsManager.getContextFactories(), settingsManager.getUserMappings()); LdapAuthenticationResult user1Success = authenticator.doAuthenticate(createContext("godin", "secret1")); assertThat(user1Success.isSuccess()).isTrue(); assertThat(user1Success.getServerKey()).isEqualTo("default"); assertThat(authenticator.doAuthenticate(createContext("godin", "wrong")).isSuccess()).isFalse(); LdapAuthenticationResult user2Success = authenticator.doAuthenticate(createContext("tester", "secret2")); assertThat(user2Success.isSuccess()).isTrue(); assertThat(user2Success.getServerKey()).isEqualTo("default"); assertThat(authenticator.doAuthenticate(createContext("tester", "wrong")).isSuccess()).isFalse(); assertThat(authenticator.doAuthenticate(createContext("notfound", "wrong")).isSuccess()).isFalse(); // SONARPLUGINS-2493 assertThat(authenticator.doAuthenticate(createContext("godin", "")).isSuccess()).isFalse(); assertThat(authenticator.doAuthenticate(createContext("godin", null)).isSuccess()).isFalse(); } @Test public void testSimpleMultiLdap() { LdapSettingsManager settingsManager = new LdapSettingsManager( LdapSettingsFactory.generateAuthenticationSettings(exampleServer, infosupportServer, LdapContextFactory.AUTH_METHOD_SIMPLE).asConfig()); DefaultLdapAuthenticator authenticator = new DefaultLdapAuthenticator(settingsManager.getContextFactories(), settingsManager.getUserMappings()); LdapAuthenticationResult user1Success = authenticator.doAuthenticate(createContext("godin", "secret1")); assertThat(user1Success.isSuccess()).isTrue(); assertThat(user1Success.getServerKey()).isEqualTo("example"); assertThat(authenticator.doAuthenticate(createContext("godin", "wrong")).isSuccess()).isFalse(); LdapAuthenticationResult user2Server1Success = authenticator.doAuthenticate(createContext("tester", "secret2")); assertThat(user2Server1Success.isSuccess()).isTrue(); assertThat(user2Server1Success.getServerKey()).isEqualTo("example"); LdapAuthenticationResult user2Server2Success = authenticator.doAuthenticate(createContext("tester", "secret3")); assertThat(user2Server2Success.isSuccess()).isTrue(); assertThat(user2Server2Success.getServerKey()).isEqualTo("infosupport"); assertThat(authenticator.doAuthenticate(createContext("tester", "wrong")).isSuccess()).isFalse(); assertThat(authenticator.doAuthenticate(createContext("notfound", "wrong")).isSuccess()).isFalse(); // SONARPLUGINS-2493 assertThat(authenticator.doAuthenticate(createContext("godin", "")).isSuccess()).isFalse(); assertThat(authenticator.doAuthenticate(createContext("godin", null)).isSuccess()).isFalse(); // SONARPLUGINS-2793 LdapAuthenticationResult user3Success = authenticator.doAuthenticate(createContext("robby", "secret1")); assertThat(user3Success.isSuccess()).isTrue(); assertThat(user3Success.getServerKey()).isEqualTo("infosupport"); assertThat(authenticator.doAuthenticate(createContext("robby", "wrong")).isSuccess()).isFalse(); } @Test public void testSasl() { LdapSettingsManager settingsManager = new LdapSettingsManager( LdapSettingsFactory.generateAuthenticationSettings(exampleServer, null, LdapContextFactory.AUTH_METHOD_CRAM_MD5).asConfig()); DefaultLdapAuthenticator authenticator = new DefaultLdapAuthenticator(settingsManager.getContextFactories(), settingsManager.getUserMappings()); LdapAuthenticationResult user1Success = authenticator.doAuthenticate(createContext("godin", "secret1")); assertThat(user1Success.isSuccess()).isTrue(); assertThat(user1Success.getServerKey()).isEqualTo("default"); assertThat(authenticator.doAuthenticate(createContext("godin", "wrong")).isSuccess()).isFalse(); LdapAuthenticationResult user2Success = authenticator.doAuthenticate(createContext("tester", "secret2")); assertThat(user2Success.isSuccess()).isTrue(); assertThat(user2Success.getServerKey()).isEqualTo("default"); assertThat(authenticator.doAuthenticate(createContext("tester", "wrong")).isSuccess()).isFalse(); assertThat(authenticator.doAuthenticate(createContext("notfound", "wrong")).isSuccess()).isFalse(); } @Test public void testSaslMultipleLdap() { LdapSettingsManager settingsManager = new LdapSettingsManager( LdapSettingsFactory.generateAuthenticationSettings(exampleServer, infosupportServer, LdapContextFactory.AUTH_METHOD_CRAM_MD5).asConfig()); DefaultLdapAuthenticator authenticator = new DefaultLdapAuthenticator(settingsManager.getContextFactories(), settingsManager.getUserMappings()); LdapAuthenticationResult user1Success = authenticator.doAuthenticate(createContext("godin", "secret1")); assertThat(user1Success.isSuccess()).isTrue(); assertThat(authenticator.doAuthenticate(createContext("godin", "wrong")).isSuccess()).isFalse(); LdapAuthenticationResult user2Server1Success = authenticator.doAuthenticate(createContext("tester", "secret2")); assertThat(user2Server1Success.isSuccess()).isTrue(); assertThat(user2Server1Success.getServerKey()).isEqualTo("example"); LdapAuthenticationResult user2Server2Success = authenticator.doAuthenticate(createContext("tester", "secret3")); assertThat(user2Server2Success.isSuccess()).isTrue(); assertThat(user2Server2Success.getServerKey()).isEqualTo("infosupport"); assertThat(authenticator.doAuthenticate(createContext("tester", "wrong")).isSuccess()).isFalse(); assertThat(authenticator.doAuthenticate(createContext("notfound", "wrong")).isSuccess()).isFalse(); LdapAuthenticationResult user3Success = authenticator.doAuthenticate(createContext("robby", "secret1")); assertThat(user3Success.isSuccess()).isTrue(); assertThat(authenticator.doAuthenticate(createContext("robby", "wrong")).isSuccess()).isFalse(); } private static LdapAuthenticator.Context createContext(String username, String password) { return new LdapAuthenticator.Context(username, password, mock(HttpRequest.class)); } }
8,766
50.570588
150
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/it/java/org/sonar/auth/ldap/DefaultLdapGroupsProviderIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import java.util.Collection; import org.junit.ClassRule; import org.junit.Test; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.http.HttpRequest; import org.sonar.auth.ldap.server.LdapServer; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class DefaultLdapGroupsProviderIT { /** * A reference to the original ldif file */ public static final String USERS_EXAMPLE_ORG_LDIF = "/users.example.org.ldif"; /** * A reference to an aditional ldif file. */ public static final String USERS_INFOSUPPORT_COM_LDIF = "/users.infosupport.com.ldif"; @ClassRule public static LdapServer exampleServer = new LdapServer(USERS_EXAMPLE_ORG_LDIF); @ClassRule public static LdapServer infosupportServer = new LdapServer(USERS_INFOSUPPORT_COM_LDIF, "infosupport.com", "dc=infosupport,dc=com"); @Test public void doGetGroups_when_single_server_without_key() { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, null); LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapGroupsProvider groupsProvider = new DefaultLdapGroupsProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings(), settingsManager.getGroupMappings()); Collection<String> groups = getGroupsForContext(createContextForDefaultServer("tester"), groupsProvider); assertThat(groups).containsOnly("sonar-users"); groups = getGroupsForContext(createContextForDefaultServer("godin"), groupsProvider); assertThat(groups).containsOnly("sonar-users", "sonar-developers"); groups = getGroupsForContext(createContextForDefaultServer("unknown_user"), groupsProvider); assertThat(groups).isEmpty(); } @Test public void doGetGroups_when_two_ldap_servers() { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, infosupportServer); LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapGroupsProvider groupsProvider = new DefaultLdapGroupsProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings(), settingsManager.getGroupMappings()); Collection<String> groups = getGroupsForContext(createContextForExampleServer("tester"), groupsProvider); assertThat(groups).containsOnly("sonar-users"); groups = getGroupsForContext(createContextForExampleServer("godin"), groupsProvider); assertThat(groups).containsOnly("sonar-users", "sonar-developers"); groups = getGroupsForContext(createContextForExampleServer("unknown_user"), groupsProvider); assertThat(groups).isEmpty(); groups = getGroupsForContext(createContextForInfoSupportServer("testerInfo"), groupsProvider); assertThat(groups).containsOnly("sonar-users"); groups = getGroupsForContext(createContextForInfoSupportServer("robby"), groupsProvider); assertThat(groups).containsOnly("sonar-users", "sonar-developers"); } @Test public void doGetGroups_when_two_ldap_servers_with_same_username_resolves_groups_from_right_server() { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, infosupportServer); LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapGroupsProvider groupsProvider = new DefaultLdapGroupsProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings(), settingsManager.getGroupMappings()); Collection<String> groups = getGroupsForContext(createContextForExampleServer("duplicated"), groupsProvider); assertThat(groups).containsOnly("sonar-users"); groups = getGroupsForContext(createContextForInfoSupportServer("duplicated"), groupsProvider); assertThat(groups).containsOnly("sonar-developers"); } @Test public void posix() { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, null); settings.setProperty("ldap.group.request", "(&(objectClass=posixGroup)(memberUid={uid}))"); LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapGroupsProvider groupsProvider = new DefaultLdapGroupsProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings(), settingsManager.getGroupMappings()); Collection<String> groups = getGroupsForContext(createContextForDefaultServer("godin"), groupsProvider); assertThat(groups).containsOnly("linux-users"); } @Test public void posixMultipleLdap() { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, infosupportServer); settings.setProperty("ldap.example.group.request", "(&(objectClass=posixGroup)(memberUid={uid}))"); settings.setProperty("ldap.infosupport.group.request", "(&(objectClass=posixGroup)(memberUid={uid}))"); LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapGroupsProvider groupsProvider = new DefaultLdapGroupsProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings(), settingsManager.getGroupMappings()); Collection<String> groups = getGroupsForContext(createContextForExampleServer("godin"), groupsProvider); assertThat(groups).containsOnly("linux-users"); groups = getGroupsForContext(createContextForInfoSupportServer("robby"), groupsProvider); assertThat(groups).containsOnly("linux-users"); } private static Collection<String> getGroupsForContext(LdapGroupsProvider.Context context, DefaultLdapGroupsProvider groupsProvider) { return groupsProvider.doGetGroups(context); } @Test public void mixed() { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, infosupportServer); settings.setProperty("ldap.example.group.request", "(&(|(objectClass=groupOfUniqueNames)(objectClass=posixGroup))(|(uniqueMember={dn})(memberUid={uid})))"); LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapGroupsProvider groupsProvider = new DefaultLdapGroupsProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings(), settingsManager.getGroupMappings()); Collection<String> groups = getGroupsForContext(createContextForExampleServer("godin"), groupsProvider); assertThat(groups).containsOnly("sonar-users", "sonar-developers", "linux-users"); } @Test public void mixedMultipleLdap() { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, infosupportServer); settings.setProperty("ldap.example.group.request", "(&(|(objectClass=groupOfUniqueNames)(objectClass=posixGroup))(|(uniqueMember={dn})(memberUid={uid})))"); settings.setProperty("ldap.infosupport.group.request", "(&(|(objectClass=groupOfUniqueNames)(objectClass=posixGroup))(|(uniqueMember={dn})(memberUid={uid})))"); LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapGroupsProvider groupsProvider = new DefaultLdapGroupsProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings(), settingsManager.getGroupMappings()); Collection<String> groups = getGroupsForContext(createContextForExampleServer("godin"), groupsProvider); assertThat(groups).containsOnly("sonar-users", "sonar-developers", "linux-users"); groups = getGroupsForContext(createContextForInfoSupportServer("robby"), groupsProvider); assertThat(groups).containsOnly("sonar-users", "sonar-developers", "linux-users"); } private static LdapGroupsProvider.Context createContextForDefaultServer(String userName) { return createContext("default", userName); } private static LdapGroupsProvider.Context createContextForExampleServer(String userName) { return createContext("example", userName); } private static LdapGroupsProvider.Context createContextForInfoSupportServer(String userName) { return createContext("infosupport", userName); } private static LdapGroupsProvider.Context createContext(String serverName, String userName) { return new LdapGroupsProvider.Context(serverName, userName, mock(HttpRequest.class)); } }
9,212
49.620879
164
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/it/java/org/sonar/auth/ldap/DefaultLdapUsersProviderIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import org.junit.ClassRule; import org.junit.Test; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.http.HttpRequest; import org.sonar.auth.ldap.server.LdapServer; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class DefaultLdapUsersProviderIT { /** * A reference to the original ldif file */ public static final String USERS_EXAMPLE_ORG_LDIF = "/users.example.org.ldif"; /** * A reference to an additional ldif file. */ public static final String USERS_INFOSUPPORT_COM_LDIF = "/users.infosupport.com.ldif"; @ClassRule public static LdapServer exampleServer = new LdapServer(USERS_EXAMPLE_ORG_LDIF); @ClassRule public static LdapServer infosupportServer = new LdapServer(USERS_INFOSUPPORT_COM_LDIF, "infosupport.com", "dc=infosupport,dc=com"); @Test public void test_user_from_first_server() { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, infosupportServer); LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapUsersProvider usersProvider = new DefaultLdapUsersProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings()); LdapUserDetails details = usersProvider.doGetUserDetails(createContext("example", "godin")); assertThat(details.getName()).isEqualTo("Evgeny Mandrikov"); assertThat(details.getEmail()).isEqualTo("godin@example.org"); } @Test public void test_user_from_second_server() { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, infosupportServer); LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapUsersProvider usersProvider = new DefaultLdapUsersProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings()); LdapUserDetails details = usersProvider.doGetUserDetails(createContext("infosupport", "robby")); assertThat(details.getName()).isEqualTo("Robby Developer"); assertThat(details.getEmail()).isEqualTo("rd@infosupport.com"); } @Test public void test_user_on_multiple_servers() { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, infosupportServer); LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapUsersProvider usersProvider = new DefaultLdapUsersProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings()); LdapUserDetails detailsExample = usersProvider.doGetUserDetails(createContext("example", "tester")); assertThat(detailsExample.getName()).isEqualTo("Tester Testerovich"); assertThat(detailsExample.getEmail()).isEqualTo("tester@example.org"); LdapUserDetails detailsInfoSupport = usersProvider.doGetUserDetails(createContext("infosupport", "tester")); assertThat(detailsInfoSupport.getName()).isEqualTo("Tester Testerovich Testerov"); assertThat(detailsInfoSupport.getEmail()).isEqualTo("tester@example2.org"); } @Test public void test_user_doesnt_exist() { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, infosupportServer); LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapUsersProvider usersProvider = new DefaultLdapUsersProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings()); LdapUserDetails details = usersProvider.doGetUserDetails(createContext("example", "notfound")); assertThat(details).isNull(); } private static LdapUsersProvider.Context createContext(String serverKey, String username) { return new LdapUsersProvider.Context(serverKey, username, mock(HttpRequest.class)); } }
4,722
47.193878
148
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/it/java/org/sonar/auth/ldap/KerberosIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import java.io.File; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.mockito.Mockito; import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.http.HttpRequest; import org.sonar.auth.ldap.server.LdapServer; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.process.ProcessProperties.Property.SONAR_SECURITY_REALM; public class KerberosIT { static { System.setProperty("java.security.krb5.conf", new File("target/krb5.conf").getAbsolutePath()); } @ClassRule public static LdapServer server = new LdapServer("/krb.ldif"); LdapAuthenticator authenticator; LdapRealm ldapRealm; @Before public void before() { MapSettings settings = configure(); ldapRealm = new LdapRealm(new LdapSettingsManager(settings.asConfig()), settings.asConfig()); authenticator = ldapRealm.getAuthenticator(); } @Test public void test_wrong_password() { LdapAuthenticator.Context wrongPasswordContext = new LdapAuthenticator.Context("Godin@EXAMPLE.ORG", "wrong_user_password", Mockito.mock(HttpRequest.class)); assertThat(authenticator.doAuthenticate(wrongPasswordContext).isSuccess()).isFalse(); } @Test public void test_correct_password() { LdapAuthenticator.Context correctPasswordContext = new LdapAuthenticator.Context("Godin@EXAMPLE.ORG", "user_password", Mockito.mock(HttpRequest.class)); assertThat(authenticator.doAuthenticate(correctPasswordContext).isSuccess()).isTrue(); } @Test public void test_default_realm() { // Using default realm from krb5.conf: LdapAuthenticator.Context defaultRealmContext = new LdapAuthenticator.Context("Godin", "user_password", Mockito.mock(HttpRequest.class)); assertThat(authenticator.doAuthenticate(defaultRealmContext).isSuccess()).isTrue(); } @Test public void test_groups() { LdapGroupsProvider groupsProvider = ldapRealm.getGroupsProvider(); LdapGroupsProvider.Context groupsContext = new LdapGroupsProvider.Context("default", "godin", Mockito.mock(HttpRequest.class)); assertThat(groupsProvider.doGetGroups(groupsContext)) .containsOnly("sonar-users"); } @Test public void wrong_bind_password() { MapSettings settings = configure() .setProperty("ldap.bindPassword", "wrong_bind_password"); Configuration config = settings.asConfig(); LdapSettingsManager settingsManager = new LdapSettingsManager(config); assertThatThrownBy(() -> new LdapRealm(settingsManager, config)) .isInstanceOf(LdapException.class) .hasMessage("LDAP realm failed to start: Unable to open LDAP connection"); } private static MapSettings configure() { return new MapSettings() .setProperty("ldap.url", server.getUrl()) .setProperty("ldap.authentication", LdapContextFactory.AUTH_METHOD_GSSAPI) .setProperty("ldap.bindDn", "SonarQube@EXAMPLE.ORG") .setProperty("ldap.bindPassword", "bind_password") .setProperty("ldap.user.baseDn", "ou=users,dc=example,dc=org") .setProperty("ldap.group.baseDn", "ou=groups,dc=example,dc=org") .setProperty("ldap.group.request", "(&(objectClass=groupOfUniqueNames)(uniqueMember={dn}))") .setProperty(SONAR_SECURITY_REALM.getKey(), LdapRealm.LDAP_SECURITY_REALM); } }
4,282
37.585586
160
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/it/java/org/sonar/auth/ldap/LdapRealmIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import org.junit.ClassRule; import org.junit.Test; import org.mockito.Mockito; import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.http.HttpRequest; import org.sonar.auth.ldap.server.LdapServer; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.process.ProcessProperties.Property.SONAR_AUTHENTICATOR_IGNORE_STARTUP_FAILURE; import static org.sonar.process.ProcessProperties.Property.SONAR_SECURITY_REALM; public class LdapRealmIT { @ClassRule public static LdapServer server = new LdapServer("/users.example.org.ldif"); @Test public void normal() { MapSettings settings = new MapSettings() .setProperty("ldap.url", server.getUrl()) .setProperty("ldap.user.baseDn", "cn=users") .setProperty(SONAR_SECURITY_REALM.getKey(), LdapRealm.LDAP_SECURITY_REALM); LdapRealm realm = new LdapRealm(new LdapSettingsManager(settings.asConfig()), settings.asConfig()); assertThat(realm.getAuthenticator()).isInstanceOf(DefaultLdapAuthenticator.class); assertThat(realm.getUsersProvider()).isInstanceOf(LdapUsersProvider.class).isInstanceOf(DefaultLdapUsersProvider.class); assertThat(realm.getGroupsProvider()).isNull(); } @Test public void noConnection() { MapSettings settings = new MapSettings() .setProperty("ldap.url", "ldap://no-such-host") .setProperty("ldap.group.baseDn", "cn=groups,dc=example,dc=org") .setProperty("ldap.user.baseDn", "cn=users,dc=example,dc=org") .setProperty(SONAR_SECURITY_REALM.getKey(), LdapRealm.LDAP_SECURITY_REALM); Configuration config = settings.asConfig(); LdapSettingsManager settingsManager = new LdapSettingsManager(config); assertThatThrownBy(() -> new LdapRealm(settingsManager, config)).isInstanceOf(LdapException.class) .hasMessage("LDAP realm failed to start: Unable to open LDAP connection"); } @Test public void noConnection_ignore_ignoreStartupFailure_is_false() { MapSettings settings = new MapSettings() .setProperty("ldap.url", "ldap://no-such-host") .setProperty("ldap.group.baseDn", "cn=groups,dc=example,dc=org") .setProperty("ldap.user.baseDn", "cn=users,dc=example,dc=org") .setProperty(SONAR_SECURITY_REALM.getKey(), LdapRealm.LDAP_SECURITY_REALM) .setProperty(SONAR_AUTHENTICATOR_IGNORE_STARTUP_FAILURE.getKey(), false); ; Configuration config = settings.asConfig(); LdapSettingsManager settingsManager = new LdapSettingsManager(config); assertThatThrownBy(() -> new LdapRealm(settingsManager, config)).isInstanceOf(LdapException.class) .hasMessage("LDAP realm failed to start: Unable to open LDAP connection"); } @Test public void noConnection_ignore_ignoreStartupFailure_is_true() { MapSettings settings = new MapSettings() .setProperty("ldap.url", "ldap://no-such-host") .setProperty("ldap.group.baseDn", "cn=groups,dc=example,dc=org") .setProperty("ldap.user.baseDn", "cn=users,dc=example,dc=org") .setProperty(SONAR_SECURITY_REALM.getKey(), LdapRealm.LDAP_SECURITY_REALM) .setProperty(SONAR_AUTHENTICATOR_IGNORE_STARTUP_FAILURE.getKey(), true); LdapRealm realm = new LdapRealm(new LdapSettingsManager(settings.asConfig()), settings.asConfig()); verifyRealm(realm); } @Test public void should_not_activate_ldap_if_realm_is_not_set() { MapSettings settings = new MapSettings(); LdapRealm realm = new LdapRealm(new LdapSettingsManager(settings.asConfig()), settings.asConfig()); verifyDeactivatedRealm(realm); } @Test public void should_not_activate_ldap_if_realm_is_not_ldap() { MapSettings settings = new MapSettings() .setProperty(SONAR_SECURITY_REALM.getKey(), "not_ldap"); LdapRealm realm = new LdapRealm(new LdapSettingsManager(settings.asConfig()), settings.asConfig()); verifyDeactivatedRealm(realm); } private static void verifyRealm(LdapRealm realm) { assertThat(realm.getAuthenticator()).isInstanceOf(DefaultLdapAuthenticator.class); LdapUsersProvider usersProvider = realm.getUsersProvider(); assertThat(usersProvider).isInstanceOf(LdapUsersProvider.class).isInstanceOf(DefaultLdapUsersProvider.class); LdapGroupsProvider groupsProvider = realm.getGroupsProvider(); assertThat(groupsProvider).isInstanceOf(LdapGroupsProvider.class).isInstanceOf(DefaultLdapGroupsProvider.class); LdapUsersProvider.Context userContext = new DefaultLdapUsersProvider.Context("<default>", "tester", Mockito.mock(HttpRequest.class)); assertThatThrownBy(() -> usersProvider.doGetUserDetails(userContext)) .isInstanceOf(LdapException.class) .hasMessage("Unable to retrieve details for user tester and server key <default>: No user mapping found."); LdapGroupsProvider.Context groupsContext = new DefaultLdapGroupsProvider.Context("default", "tester", Mockito.mock(HttpRequest.class)); assertThatThrownBy(() -> groupsProvider.doGetGroups(groupsContext)) .isInstanceOf(LdapException.class) .hasMessage("Unable to retrieve groups for user tester in server with key <default>"); assertThat(realm.isLdapAuthActivated()).isTrue(); } private static void verifyDeactivatedRealm(LdapRealm realm) { assertThat(realm.getAuthenticator()).isNull(); assertThat(realm.getUsersProvider()).isNull(); assertThat(realm.getGroupsProvider()).isNull(); assertThat(realm.isLdapAuthActivated()).isFalse(); } }
6,422
44.232394
139
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/it/java/org/sonar/auth/ldap/LdapReferralsIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import java.util.Map; import javax.annotation.Nullable; import org.junit.ClassRule; import org.junit.Test; import org.sonar.api.config.internal.MapSettings; import org.sonar.auth.ldap.server.LdapServer; import static org.assertj.core.api.Assertions.assertThat; public class LdapReferralsIT { @ClassRule public static LdapServer server = new LdapServer("/users.example.org.ldif"); Map<String, LdapContextFactory> underTest; @Test public void referral_is_set_to_follow_when_followReferrals_setting_is_set_to_true() { underTest = createFactories("ldap.followReferrals", "true"); LdapContextFactory contextFactory = underTest.values().iterator().next(); assertThat(contextFactory.getReferral()).isEqualTo("follow"); } @Test public void referral_is_set_to_ignore_when_followReferrals_setting_is_set_to_false() { underTest = createFactories("ldap.followReferrals", "false"); LdapContextFactory contextFactory = underTest.values().iterator().next(); assertThat(contextFactory.getReferral()).isEqualTo("ignore"); } @Test public void referral_is_set_to_follow_when_no_followReferrals_setting() { underTest = createFactories(null, null); LdapContextFactory contextFactory = underTest.values().iterator().next(); assertThat(contextFactory.getReferral()).isEqualTo("follow"); } private static Map<String, LdapContextFactory> createFactories(@Nullable String propertyKey, @Nullable String propertyValue) { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(server, null); if (propertyKey != null) { settings.setProperty(propertyKey, propertyValue); } return new LdapSettingsManager(settings.asConfig()).getContextFactories(); } }
2,617
36.4
128
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/it/java/org/sonar/auth/ldap/LdapSearchIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import java.util.ArrayList; import java.util.Enumeration; import java.util.Map; import javax.naming.NamingException; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.sonar.auth.ldap.server.LdapServer; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class LdapSearchIT { @ClassRule public static LdapServer server = new LdapServer("/users.example.org.ldif"); private static Map<String, LdapContextFactory> contextFactories; @BeforeClass public static void init() { contextFactories = new LdapSettingsManager(LdapSettingsFactory.generateSimpleAnonymousAccessSettings(server, null).asConfig()).getContextFactories(); } @Test public void subtreeSearch() throws Exception { LdapSearch search = new LdapSearch(contextFactories.values().iterator().next()) .setBaseDn("dc=example,dc=org") .setRequest("(objectClass={0})") .setParameters("inetOrgPerson") .returns("objectClass"); assertThat(search.getBaseDn()).isEqualTo("dc=example,dc=org"); assertThat(search.getScope()).isEqualTo(SearchControls.SUBTREE_SCOPE); assertThat(search.getRequest()).isEqualTo("(objectClass={0})"); assertThat(search.getParameters()).isEqualTo(new String[] {"inetOrgPerson"}); assertThat(search.getReturningAttributes()).isEqualTo(new String[] {"objectClass"}); assertThat(search).hasToString("LdapSearch{baseDn=dc=example,dc=org, scope=subtree, request=(objectClass={0}), parameters=[inetOrgPerson], attributes=[objectClass]}"); assertThat(enumerationToArrayList(search.find())) .extracting(SearchResult::getName) .containsExactlyInAnyOrder( "cn=Without Email,ou=users", "cn=Evgeny Mandrikov,ou=users", "cn=Tester Testerovich,ou=users", "cn=duplicated,ou=users" ); assertThatThrownBy(search::findUnique) .isInstanceOf(NamingException.class) .hasMessage("Non unique result for " + search); } @Test public void oneLevelSearch() throws Exception { LdapSearch search = new LdapSearch(contextFactories.values().iterator().next()) .setBaseDn("dc=example,dc=org") .setScope(SearchControls.ONELEVEL_SCOPE) .setRequest("(objectClass={0})") .setParameters("inetOrgPerson") .returns("cn"); assertThat(search.getBaseDn()).isEqualTo("dc=example,dc=org"); assertThat(search.getScope()).isEqualTo(SearchControls.ONELEVEL_SCOPE); assertThat(search.getRequest()).isEqualTo("(objectClass={0})"); assertThat(search.getParameters()).isEqualTo(new String[] {"inetOrgPerson"}); assertThat(search.getReturningAttributes()).isEqualTo(new String[] {"cn"}); assertThat(search).hasToString("LdapSearch{baseDn=dc=example,dc=org, scope=onelevel, request=(objectClass={0}), parameters=[inetOrgPerson], attributes=[cn]}"); assertThat(enumerationToArrayList(search.find())).isEmpty(); assertThat(search.findUnique()).isNull(); } @Test public void objectSearch() throws Exception { LdapSearch search = new LdapSearch(contextFactories.values().iterator().next()) .setBaseDn("cn=bind,ou=users,dc=example,dc=org") .setScope(SearchControls.OBJECT_SCOPE) .setRequest("(objectClass={0})") .setParameters("uidObject") .returns("uid"); assertThat(search.getBaseDn()).isEqualTo("cn=bind,ou=users,dc=example,dc=org"); assertThat(search.getScope()).isEqualTo(SearchControls.OBJECT_SCOPE); assertThat(search.getRequest()).isEqualTo("(objectClass={0})"); assertThat(search.getParameters()).isEqualTo(new String[] {"uidObject"}); assertThat(search.getReturningAttributes()).isEqualTo(new String[] {"uid"}); assertThat(search).hasToString( "LdapSearch{baseDn=cn=bind,ou=users,dc=example,dc=org, scope=object, request=(objectClass={0}), parameters=[uidObject], attributes=[uid]}"); assertThat(enumerationToArrayList(search.find())).hasSize(1); assertThat(search.findUnique()).isNotNull(); } private static <E> ArrayList<E> enumerationToArrayList(Enumeration<E> enumeration) { ArrayList<E> result = new ArrayList<>(); while (enumeration.hasMoreElements()) { result.add(enumeration.nextElement()); } return result; } }
5,262
41.443548
171
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/it/java/org/sonar/auth/ldap/LdapSettingsFactory.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import javax.annotation.Nullable; import org.sonar.api.config.internal.MapSettings; import org.sonar.auth.ldap.server.LdapServer; /** * Create Settings for most used test cases. */ public class LdapSettingsFactory { /** * Generate simple settings for 2 ldap servers that allows anonymous access. * * @return The specific settings. */ public static MapSettings generateSimpleAnonymousAccessSettings(LdapServer exampleServer, @Nullable LdapServer infosupportServer) { MapSettings settings = new MapSettings(); if (infosupportServer != null) { settings.setProperty("ldap.servers", "example,infosupport"); settings.setProperty("ldap.example.url", exampleServer.getUrl()) .setProperty("ldap.example.user.baseDn", "ou=users,dc=example,dc=org") .setProperty("ldap.example.group.baseDn", "ou=groups,dc=example,dc=org"); settings.setProperty("ldap.infosupport.url", infosupportServer.getUrl()) .setProperty("ldap.infosupport.user.baseDn", "ou=users,dc=infosupport,dc=com") .setProperty("ldap.infosupport.group.baseDn", "ou=groups,dc=infosupport,dc=com"); } else { settings.setProperty("ldap.url", exampleServer.getUrl()) .setProperty("ldap.user.baseDn", "ou=users,dc=example,dc=org") .setProperty("ldap.group.baseDn", "ou=groups,dc=example,dc=org"); } return settings; } /** * Generate settings for 2 ldap servers. * * @param exampleServer The first ldap server. * @param infosupportServer The second ldap server. * @return The specific settings. */ public static MapSettings generateAuthenticationSettings(LdapServer exampleServer, @Nullable LdapServer infosupportServer, String authMethod) { MapSettings settings = new MapSettings(); if (infosupportServer != null) { settings.setProperty("ldap.servers", "example,infosupport"); settings.setProperty("ldap.example.url", exampleServer.getUrl()) .setProperty("ldap.example.bindDn", LdapContextFactory.AUTH_METHOD_SIMPLE.equals(authMethod) ? "cn=bind,ou=users,dc=example,dc=org" : "bind") .setProperty("ldap.example.bindPassword", "bindpassword") .setProperty("ldap.example.authentication", authMethod) .setProperty("ldap.example.realm", "example.org") .setProperty("ldap.example.user.baseDn", "ou=users,dc=example,dc=org") .setProperty("ldap.example.group.baseDn", "ou=groups,dc=example,dc=org"); settings.setProperty("ldap.infosupport.url", infosupportServer.getUrl()) .setProperty("ldap.infosupport.bindDn", LdapContextFactory.AUTH_METHOD_SIMPLE.equals(authMethod) ? "cn=bind,ou=users,dc=infosupport,dc=com" : "bind") .setProperty("ldap.infosupport.bindPassword", "bindpassword") .setProperty("ldap.infosupport.authentication", authMethod) .setProperty("ldap.infosupport.realm", "infosupport.com") .setProperty("ldap.infosupport.user.baseDn", "ou=users,dc=infosupport,dc=com") .setProperty("ldap.infosupport.group.baseDn", "ou=groups,dc=infosupport,dc=com"); } else { settings.setProperty("ldap.url", exampleServer.getUrl()) .setProperty("ldap.bindDn", LdapContextFactory.AUTH_METHOD_SIMPLE.equals(authMethod) ? "cn=bind,ou=users,dc=example,dc=org" : "bind") .setProperty("ldap.bindPassword", "bindpassword") .setProperty("ldap.authentication", authMethod) .setProperty("ldap.realm", "example.org") .setProperty("ldap.user.baseDn", "ou=users,dc=example,dc=org") .setProperty("ldap.group.baseDn", "ou=groups,dc=example,dc=org"); } return settings; } }
4,502
45.90625
157
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/it/java/org/sonar/auth/ldap/server/LdapServer.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap.server; import org.junit.rules.ExternalResource; import org.sonar.ldap.ApacheDS; public class LdapServer extends ExternalResource { private ApacheDS server; private String ldif; private final String realm; private final String baseDn; public LdapServer(String ldifResourceName) { this(ldifResourceName, "example.org", "dc=example,dc=org"); } public LdapServer(String ldifResourceName, String realm, String baseDn) { this.ldif = ldifResourceName; this.realm = realm; this.baseDn = baseDn; } @Override protected void before() throws Throwable { server = ApacheDS.start(realm, baseDn); server.importLdif(LdapServer.class.getResourceAsStream(ldif)); } @Override protected void after() { try { server.stop(); } catch (Exception e) { throw new IllegalStateException(e); } } public String getUrl() { return server.getUrl(); } public void disableAnonymousAccess() { server.disableAnonymousAccess(); } public void enableAnonymousAccess() { server.enableAnonymousAccess(); } }
1,949
26.857143
75
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/CallbackHandlerImpl.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import java.io.IOException; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; /** * @author Evgeny Mandrikov */ public class CallbackHandlerImpl implements CallbackHandler { private String name; private String password; public CallbackHandlerImpl(String name, String password) { this.name = name; this.password = password; } @Override public void handle(Callback[] callbacks) throws UnsupportedCallbackException, IOException { for (Callback callBack : callbacks) { if (callBack instanceof NameCallback nameCallback) { // Handles username callback nameCallback.setName(name); } else if (callBack instanceof PasswordCallback passwordCallback) { // Handles password callback passwordCallback.setPassword(password.toCharArray()); } else { throw new UnsupportedCallbackException(callBack, "Callback not supported"); } } } }
2,010
34.910714
93
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/ContextHelper.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import javax.annotation.Nullable; import javax.naming.Context; import javax.naming.NamingException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Evgeny Mandrikov */ public final class ContextHelper { private static final Logger LOG = LoggerFactory.getLogger(ContextHelper.class); private ContextHelper() { } /** * <pre> * public void useContextNicely() throws NamingException { * InitialDirContext context = null; * boolean threw = true; * try { * context = new InitialDirContext(); * // Some code which does something with the Context and may throw a NamingException * threw = false; // No throwable thrown * } finally { * // Close context * // If an exception occurs, only rethrow it if (threw==false) * close(context, threw); * } * } * </pre> * * @param context the {@code Context} object to be closed, or null, in which case this method does nothing * @param swallowIOException if true, don't propagate {@code NamingException} thrown by the {@code close} method * @throws NamingException if {@code swallowIOException} is false and {@code close} throws a {@code NamingException}. */ public static void close(@Nullable Context context, boolean swallowIOException) throws NamingException { if (context == null) { return; } try { context.close(); } catch (NamingException e) { if (swallowIOException) { LOG.warn("NamingException thrown while closing context.", e); } else { throw e; } } } public static void closeQuietly(@Nullable Context context) { try { close(context, true); } catch (NamingException e) { LOG.error("Unexpected NamingException", e); } } }
2,665
31.120482
119
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/DefaultLdapAuthenticator.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import java.util.Map; import javax.naming.NamingException; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchResult; import javax.security.auth.login.Configuration; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import org.apache.commons.lang.StringUtils; import org.sonar.api.server.ServerSide; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Evgeny Mandrikov */ @ServerSide public class DefaultLdapAuthenticator implements LdapAuthenticator { private static final Logger LOG = LoggerFactory.getLogger(DefaultLdapAuthenticator.class); private final Map<String, LdapContextFactory> contextFactories; private final Map<String, LdapUserMapping> userMappings; public DefaultLdapAuthenticator(Map<String, LdapContextFactory> contextFactories, Map<String, LdapUserMapping> userMappings) { this.contextFactories = contextFactories; this.userMappings = userMappings; } @Override public LdapAuthenticationResult doAuthenticate(Context context) { return authenticate(context.getUsername(), context.getPassword()); } /** * Authenticate the user against LDAP servers until first success. * * @param login The login to use. * @param password The password to use. * @return false if specified user cannot be authenticated with specified password on any LDAP server */ private LdapAuthenticationResult authenticate(String login, String password) { for (Map.Entry<String, LdapUserMapping> ldapEntry : userMappings.entrySet()) { String ldapKey = ldapEntry.getKey(); LdapUserMapping ldapUserMapping = ldapEntry.getValue(); LdapContextFactory ldapContextFactory = contextFactories.get(ldapKey); final String principal; if (ldapContextFactory.isSasl()) { principal = login; } else { SearchResult result = findUser(login, ldapKey, ldapUserMapping, ldapContextFactory); if (result == null) { continue; } principal = result.getNameInNamespace(); } boolean passwordValid = isPasswordValid(password, ldapKey, ldapContextFactory, principal); if (passwordValid) { return LdapAuthenticationResult.success(ldapKey); } } LOG.debug("User {} not found", login); return LdapAuthenticationResult.failed(); } private static SearchResult findUser(String login, String ldapKey, LdapUserMapping ldapUserMapping, LdapContextFactory ldapContextFactory) { SearchResult result; try { result = ldapUserMapping.createSearch(ldapContextFactory, login).findUnique(); } catch (NamingException e) { LOG.debug("User {} not found in server <{}>: {}", login, ldapKey, e.toString()); return null; } if (result == null) { LOG.debug("User {} not found in <{}>", login, ldapKey); return null; } return result; } private boolean isPasswordValid(String password, String ldapKey, LdapContextFactory ldapContextFactory, String principal) { if (ldapContextFactory.isGssapi()) { return checkPasswordUsingGssapi(principal, password, ldapKey); } return checkPasswordUsingBind(principal, password, ldapKey); } private boolean checkPasswordUsingBind(String principal, String password, String ldapKey) { if (StringUtils.isEmpty(password)) { LOG.debug("Password is blank."); return false; } InitialDirContext context = null; try { context = contextFactories.get(ldapKey).createUserContext(principal, password); return true; } catch (NamingException e) { LOG.debug("Password not valid for user {} in server {}: {}", principal, ldapKey, e.getMessage()); return false; } finally { ContextHelper.closeQuietly(context); } } private boolean checkPasswordUsingGssapi(String principal, String password, String ldapKey) { // Use our custom configuration to avoid reliance on external config Configuration.setConfiguration(new Krb5LoginConfiguration()); LoginContext lc; try { lc = new LoginContext(getClass().getName(), new CallbackHandlerImpl(principal, password)); lc.login(); } catch (LoginException e) { // Bad username: Client not found in Kerberos database // Bad password: Integrity check on decrypted field failed LOG.debug("Password not valid for {} in server {}: {}", principal, ldapKey, e.getMessage()); return false; } try { lc.logout(); } catch (LoginException e) { LOG.warn("Logout fails", e); } return true; } }
5,483
36.561644
142
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/DefaultLdapGroupsProvider.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attributes; import javax.naming.directory.SearchResult; import org.sonar.api.server.ServerSide; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.lang.String.format; /** * @author Evgeny Mandrikov */ @ServerSide public class DefaultLdapGroupsProvider implements LdapGroupsProvider { private static final Logger LOG = LoggerFactory.getLogger(DefaultLdapGroupsProvider.class); private final Map<String, LdapContextFactory> contextFactories; private final Map<String, LdapUserMapping> userMappings; private final Map<String, LdapGroupMapping> groupMappings; public DefaultLdapGroupsProvider(Map<String, LdapContextFactory> contextFactories, Map<String, LdapUserMapping> userMappings, Map<String, LdapGroupMapping> groupMapping) { this.contextFactories = contextFactories; this.userMappings = userMappings; this.groupMappings = groupMapping; } /** * @throws LdapException if unable to retrieve groups */ @Override public Collection<String> doGetGroups(Context context) { return getGroups(context.serverKey(), context.username()); } private Collection<String> getGroups(String serverKey, String username) { checkPrerequisites(username); Set<String> groups = new HashSet<>(); if (groupMappings.containsKey(serverKey)) { SearchResult searchResult = searchUserGroups(username, serverKey); if (searchResult != null) { try { NamingEnumeration<SearchResult> result = groupMappings .get(serverKey) .createSearch(contextFactories.get(serverKey), searchResult).find(); groups.addAll(mapGroups(serverKey, result)); } catch (NamingException e) { LOG.debug(e.getMessage(), e); throw new LdapException(format("Unable to retrieve groups for user %s in server with key <%s>", username, serverKey), e); } } } return groups; } private void checkPrerequisites(String username) { if (userMappings.isEmpty() || groupMappings.isEmpty()) { throw new LdapException(format("Unable to retrieve details for user %s: No user or group mapping found.", username)); } } private SearchResult searchUserGroups(String username, String serverKey) { try { LOG.debug("Requesting groups for user {}", username); return userMappings.get(serverKey).createSearch(contextFactories.get(serverKey), username) .returns(groupMappings.get(serverKey).getRequiredUserAttributes()) .findUnique(); } catch (NamingException e) { // just in case if Sonar silently swallowed exception LOG.debug(e.getMessage(), e); throw new LdapException(format("Unable to retrieve groups for user %s in server with key <%s>", username, serverKey), e); } } /** * Map all the groups. * * @param serverKey The index we use to choose the correct {@link LdapGroupMapping}. * @param searchResult The {@link SearchResult} from the search for the user. * @return A {@link Collection} of groups the user is member of. * @throws NamingException */ private Collection<String> mapGroups(String serverKey, NamingEnumeration<SearchResult> searchResult) throws NamingException { Set<String> groups = new HashSet<>(); while (searchResult.hasMoreElements()) { SearchResult obj = searchResult.nextElement(); Attributes attributes = obj.getAttributes(); String groupId = (String) attributes.get(groupMappings.get(serverKey).getIdAttribute()).get(); groups.add(groupId); } return groups; } }
4,638
37.338843
173
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/DefaultLdapUsersProvider.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import java.util.Map; import javax.annotation.Nullable; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.SearchResult; import org.sonar.api.server.ServerSide; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.lang.String.format; /** * @author Evgeny Mandrikov */ @ServerSide public class DefaultLdapUsersProvider implements LdapUsersProvider { private static final Logger LOG = LoggerFactory.getLogger(DefaultLdapUsersProvider.class); private final Map<String, LdapContextFactory> contextFactories; private final Map<String, LdapUserMapping> userMappings; public DefaultLdapUsersProvider(Map<String, LdapContextFactory> contextFactories, Map<String, LdapUserMapping> userMappings) { this.contextFactories = contextFactories; this.userMappings = userMappings; } private static String getAttributeValue(@Nullable Attribute attribute) throws NamingException { if (attribute == null) { return ""; } return (String) attribute.get(); } @Override public LdapUserDetails doGetUserDetails(Context context) { return getUserDetails(context.serverKey(), context.username()); } /** * @return details for specified user, or null if such user doesn't exist * @throws LdapException if unable to retrieve details */ private LdapUserDetails getUserDetails(String serverKey, String username) { LOG.debug("Requesting details for user {}", username); // If there are no userMappings available, we can not retrieve user details. LdapUserMapping ldapUserMapping = userMappings.get(serverKey); if (ldapUserMapping == null) { String errorMessage = format("Unable to retrieve details for user %s and server key %s: No user mapping found.", username, serverKey); LOG.debug(errorMessage); throw new LdapException(errorMessage); } SearchResult searchResult; try { searchResult = ldapUserMapping.createSearch(contextFactories.get(serverKey), username) .returns(ldapUserMapping.getEmailAttribute(), ldapUserMapping.getRealNameAttribute()) .findUnique(); if (searchResult != null) { return mapUserDetails(ldapUserMapping, searchResult); } else { LOG.debug("User {} not found in {}", username, serverKey); return null; } } catch (NamingException e) { // just in case if Sonar silently swallowed exception LOG.debug(e.getMessage(), e); throw new LdapException("Unable to retrieve details for user " + username + " in " + serverKey, e); } } private static LdapUserDetails mapUserDetails(LdapUserMapping ldapUserMapping, SearchResult searchResult) throws NamingException { Attributes attributes = searchResult.getAttributes(); LdapUserDetails details; details = new LdapUserDetails(); details.setName(getAttributeValue(attributes.get(ldapUserMapping.getRealNameAttribute()))); details.setEmail(getAttributeValue(attributes.get(ldapUserMapping.getEmailAttribute()))); return details; } }
3,992
37.76699
140
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/Krb5LoginConfiguration.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import java.util.HashMap; import javax.security.auth.login.AppConfigurationEntry; import javax.security.auth.login.Configuration; /** * @author Evgeny Mandrikov */ public class Krb5LoginConfiguration extends Configuration { private static final AppConfigurationEntry[] CONFIG_LIST = new AppConfigurationEntry[1]; static { String loginModule = "com.sun.security.auth.module.Krb5LoginModule"; AppConfigurationEntry.LoginModuleControlFlag flag = AppConfigurationEntry.LoginModuleControlFlag.REQUIRED; CONFIG_LIST[0] = new AppConfigurationEntry(loginModule, flag, new HashMap<>()); } /** * Creates a new instance of Krb5LoginConfiguration. */ public Krb5LoginConfiguration() { super(); } /** * Interface method requiring us to return all the LoginModules we know about. */ @Override public AppConfigurationEntry[] getAppConfigurationEntry(String applicationName) { // We will ignore the applicationName, since we want all apps to use Kerberos V5 return CONFIG_LIST.clone(); } /** * Interface method for reloading the configuration. We don't need this. */ @Override public void refresh() { // Right now this is a load once scheme and we will not implement the refresh method } }
2,128
33.33871
110
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapAuthenticationResult.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import javax.annotation.Nullable; import static org.sonar.api.utils.Preconditions.checkState; public final class LdapAuthenticationResult { private final boolean success; private final String serverKey; private LdapAuthenticationResult(boolean success, @Nullable String serverKey) { this.success = success; this.serverKey = serverKey; } public static LdapAuthenticationResult failed() { return new LdapAuthenticationResult(false, null); } public static LdapAuthenticationResult success(String serverKey) { return new LdapAuthenticationResult(true, serverKey); } public boolean isSuccess() { return success; } public String getServerKey() { checkState(isSuccess(), "serverKey is only set for successful authentication."); return serverKey; } }
1,677
30.074074
84
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapAuthenticator.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import javax.annotation.Nullable; import org.sonar.api.server.http.HttpRequest; import static java.util.Objects.requireNonNull; public interface LdapAuthenticator { /** * @return true if user was successfully authenticated with specified credentials, false otherwise * @throws RuntimeException in case of unexpected error such as connection failure */ LdapAuthenticationResult doAuthenticate(LdapAuthenticator.Context context); final class Context { private String username; private String password; private HttpRequest request; public Context(@Nullable String username, @Nullable String password, HttpRequest request) { requireNonNull(request); this.request = request; this.username = username; this.password = password; } /** * Username can be null, for example when using <a href="http://www.jasig.org/cas">CAS</a>. */ public String getUsername() { return username; } /** * Password can be null, for example when using <a href="http://www.jasig.org/cas">CAS</a>. */ public String getPassword() { return password; } public HttpRequest getRequest() { return request; } } }
2,086
30.621212
100
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapContextFactory.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import java.io.IOException; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.Properties; import javax.annotation.Nullable; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.directory.InitialDirContext; import javax.naming.ldap.InitialLdapContext; import javax.naming.ldap.StartTlsRequest; import javax.naming.ldap.StartTlsResponse; import javax.security.auth.Subject; import javax.security.auth.login.Configuration; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Evgeny Mandrikov */ public class LdapContextFactory { private static final Logger LOG = LoggerFactory.getLogger(LdapContextFactory.class); // visible for testing static final String AUTH_METHOD_SIMPLE = "simple"; static final String AUTH_METHOD_GSSAPI = "GSSAPI"; static final String AUTH_METHOD_DIGEST_MD5 = "DIGEST-MD5"; static final String AUTH_METHOD_CRAM_MD5 = "CRAM-MD5"; private static final String REFERRALS_FOLLOW_MODE = "follow"; private static final String REFERRALS_IGNORE_MODE = "ignore"; private static final String DEFAULT_AUTHENTICATION = AUTH_METHOD_SIMPLE; private static final String DEFAULT_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory"; /** * The Sun LDAP property used to enable connection pooling. This is used in the default implementation to enable * LDAP connection pooling. */ private static final String SUN_CONNECTION_POOLING_PROPERTY = "com.sun.jndi.ldap.connect.pool"; private static final String SASL_REALM_PROPERTY = "java.naming.security.sasl.realm"; private final String providerUrl; private final boolean startTLS; private final String authentication; private final String factory; private final String username; private final String password; private final String realm; private final String referral; public LdapContextFactory(org.sonar.api.config.Configuration config, String settingsPrefix, String ldapUrl) { this.authentication = StringUtils.defaultString(config.get(settingsPrefix + ".authentication").orElse(null), DEFAULT_AUTHENTICATION); this.factory = StringUtils.defaultString(config.get(settingsPrefix + ".contextFactoryClass").orElse(null), DEFAULT_FACTORY); this.realm = config.get(settingsPrefix + ".realm").orElse(null); this.providerUrl = ldapUrl; this.startTLS = config.getBoolean(settingsPrefix + ".StartTLS").orElse(false); this.username = config.get(settingsPrefix + ".bindDn").orElse(null); this.password = config.get(settingsPrefix + ".bindPassword").orElse(null); this.referral = getReferralsMode(config, settingsPrefix + ".followReferrals"); } /** * Returns {@code InitialDirContext} for Bind user. */ public InitialDirContext createBindContext() throws NamingException { if (isGssapi()) { return createInitialDirContextUsingGssapi(username, password); } else { return createInitialDirContext(username, password, true); } } /** * Returns {@code InitialDirContext} for specified user. * Note that pooling intentionally disabled by this method. */ public InitialDirContext createUserContext(String principal, String credentials) throws NamingException { return createInitialDirContext(principal, credentials, false); } private InitialDirContext createInitialDirContext(String principal, String credentials, boolean pooling) throws NamingException { final InitialLdapContext ctx; if (startTLS) { // Note that pooling is not enabled for such connections, because "Stop TLS" is not performed. Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, factory); env.put(Context.PROVIDER_URL, providerUrl); env.put(Context.REFERRAL, referral); // At this point env should not contain properties SECURITY_AUTHENTICATION, SECURITY_PRINCIPAL and SECURITY_CREDENTIALS to avoid // "bind" operation prior to StartTLS: ctx = new InitialLdapContext(env, null); // http://docs.oracle.com/javase/jndi/tutorial/ldap/ext/starttls.html StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest()); try { tls.negotiate(); } catch (IOException e) { NamingException ex = new NamingException("StartTLS failed"); ex.initCause(e); throw ex; } // Explicitly initiate "bind" operation: ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, authentication); if (principal != null) { ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, principal); } if (credentials != null) { ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials); } ctx.reconnect(null); } else { ctx = new InitialLdapContext(getEnvironment(principal, credentials, pooling), null); } return ctx; } private InitialDirContext createInitialDirContextUsingGssapi(String principal, String credentials) throws NamingException { Configuration.setConfiguration(new Krb5LoginConfiguration()); InitialDirContext initialDirContext; try { LoginContext lc = new LoginContext(getClass().getName(), new CallbackHandlerImpl(principal, credentials)); lc.login(); initialDirContext = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<InitialDirContext>() { @Override public InitialDirContext run() throws NamingException { Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, factory); env.put(Context.PROVIDER_URL, providerUrl); env.put(Context.REFERRAL, referral); return new InitialLdapContext(env, null); } }); } catch (LoginException | PrivilegedActionException e) { NamingException namingException = new NamingException(e.getMessage()); namingException.initCause(e); throw namingException; } return initialDirContext; } private Properties getEnvironment(@Nullable String principal, @Nullable String credentials, boolean pooling) { Properties env = new Properties(); env.put(Context.SECURITY_AUTHENTICATION, authentication); if (realm != null) { env.put(SASL_REALM_PROPERTY, realm); } if (pooling) { // Enable connection pooling env.put(SUN_CONNECTION_POOLING_PROPERTY, "true"); } env.put(Context.INITIAL_CONTEXT_FACTORY, factory); env.put(Context.PROVIDER_URL, providerUrl); env.put(Context.REFERRAL, referral); if (principal != null) { env.put(Context.SECURITY_PRINCIPAL, principal); } // Note: debug is intentionally was placed here - in order to not expose password in log LOG.debug("Initializing LDAP context {}", env); if (credentials != null) { env.put(Context.SECURITY_CREDENTIALS, credentials); } return env; } public boolean isSasl() { return AUTH_METHOD_DIGEST_MD5.equals(authentication) || AUTH_METHOD_CRAM_MD5.equals(authentication) || AUTH_METHOD_GSSAPI.equals(authentication); } public boolean isGssapi() { return AUTH_METHOD_GSSAPI.equals(authentication); } /** * Tests connection. * * @throws LdapException if unable to open connection */ public void testConnection() { if (StringUtils.isBlank(username) && isSasl()) { throw new IllegalArgumentException("When using SASL - property ldap.bindDn is required"); } try { createBindContext(); LOG.info("Test LDAP connection on {}: OK", providerUrl); } catch (NamingException e) { LOG.info("Test LDAP connection: FAIL"); throw new LdapException("Unable to open LDAP connection", e); } } public String getProviderUrl() { return providerUrl; } public String getReferral() { return referral; } private static String getReferralsMode(org.sonar.api.config.Configuration config, String followReferralsSettingKey) { // By default follow referrals return config.getBoolean(followReferralsSettingKey).orElse(true) ? REFERRALS_FOLLOW_MODE : REFERRALS_IGNORE_MODE; } @Override public String toString() { return getClass().getSimpleName() + "{" + "url=" + providerUrl + ", authentication=" + authentication + ", factory=" + factory + ", bindDn=" + username + ", realm=" + realm + ", referral=" + referral + "}"; } }
9,415
37.590164
137
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapException.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; public class LdapException extends RuntimeException { public LdapException(String message) { super(message); } public LdapException(String message, Throwable cause) { super(message, cause); } }
1,086
31.939394
75
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapGroupMapping.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import java.util.Arrays; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.SearchResult; import org.apache.commons.lang.StringUtils; import org.sonar.api.config.Configuration; /** * @author Evgeny Mandrikov */ public class LdapGroupMapping { private static final String DEFAULT_ID_ATTRIBUTE = "cn"; private static final String DEFAULT_REQUEST = "(&(objectClass=groupOfUniqueNames)(uniqueMember={dn}))"; private final String baseDn; private final String idAttribute; private final String request; private final String[] requiredUserAttributes; /** * Constructs mapping from Sonar settings. */ public LdapGroupMapping(Configuration config, String settingsPrefix) { this.baseDn = config.get(settingsPrefix + ".group.baseDn").orElse(null); this.idAttribute = StringUtils.defaultString(config.get(settingsPrefix + ".group.idAttribute").orElse(null), DEFAULT_ID_ATTRIBUTE); String req = StringUtils.defaultString(config.get(settingsPrefix + ".group.request").orElse(null), DEFAULT_REQUEST); this.requiredUserAttributes = StringUtils.substringsBetween(req, "{", "}"); for (int i = 0; i < requiredUserAttributes.length; i++) { req = StringUtils.replace(req, "{" + requiredUserAttributes[i] + "}", "{" + i + "}"); } this.request = req; } /** * Search for this mapping. */ public LdapSearch createSearch(LdapContextFactory contextFactory, SearchResult user) { String[] attrs = getRequiredUserAttributes(); String[] parameters = new String[attrs.length]; for (int i = 0; i < parameters.length; i++) { String attr = attrs[i]; if ("dn".equals(attr)) { parameters[i] = user.getNameInNamespace(); } else { parameters[i] = getAttributeValue(user, attr); } } return new LdapSearch(contextFactory) .setBaseDn(getBaseDn()) .setRequest(getRequest()) .setParameters(parameters) .returns(getIdAttribute()); } private static String getAttributeValue(SearchResult user, String attributeId) { Attribute attribute = user.getAttributes().get(attributeId); if (attribute == null) { return null; } try { return (String) attribute.get(); } catch (NamingException e) { throw new IllegalArgumentException(e); } } /** * Base DN. For example "ou=groups,o=mycompany". */ public String getBaseDn() { return baseDn; } /** * Group ID Attribute. For example "cn". */ public String getIdAttribute() { return idAttribute; } /** * Request. For example: * <pre> * (&(objectClass=groupOfUniqueNames)(uniqueMember={0})) * (&(objectClass=posixGroup)(memberUid={0})) * (&(|(objectClass=groupOfUniqueNames)(objectClass=posixGroup))(|(uniqueMember={0})(memberUid={1}))) * </pre> */ public String getRequest() { return request; } /** * Attributes of user required for search of groups. */ public String[] getRequiredUserAttributes() { return requiredUserAttributes; } @Override public String toString() { return getClass().getSimpleName() + "{" + "baseDn=" + getBaseDn() + ", idAttribute=" + getIdAttribute() + ", requiredUserAttributes=" + Arrays.toString(getRequiredUserAttributes()) + ", request=" + getRequest() + "}"; } }
4,242
30.664179
135
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapGroupsProvider.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import java.util.Collection; import org.sonar.api.server.http.HttpRequest; public interface LdapGroupsProvider { Collection<String> doGetGroups(Context context); record Context(String serverKey, String username, HttpRequest request) { } }
1,121
34.0625
75
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapModule.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import org.sonar.core.platform.Module; public class LdapModule extends Module { @Override protected void configureModule() { add( LdapRealm.class, LdapSettingsManager.class); } }
1,077
30.705882
75
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapRealm.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import java.util.Map; import javax.annotation.CheckForNull; import org.sonar.api.config.Configuration; import org.sonar.api.server.ServerSide; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.sonar.auth.ldap.LdapSettingsManager.DEFAULT_LDAP_SERVER_KEY; import static org.sonar.process.ProcessProperties.Property.SONAR_AUTHENTICATOR_IGNORE_STARTUP_FAILURE; import static org.sonar.process.ProcessProperties.Property.SONAR_SECURITY_REALM; /** * @author Evgeny Mandrikov */ @ServerSide public class LdapRealm { public static final String LDAP_SECURITY_REALM = "LDAP"; public static final String DEFAULT_LDAP_IDENTITY_PROVIDER_ID = LDAP_SECURITY_REALM + "_" + DEFAULT_LDAP_SERVER_KEY; private static final Logger LOG = LoggerFactory.getLogger(LdapRealm.class); private final boolean isLdapAuthActivated; private final LdapUsersProvider usersProvider; private final LdapGroupsProvider groupsProvider; private final LdapAuthenticator authenticator; public LdapRealm(LdapSettingsManager settingsManager, Configuration configuration) { String realmName = configuration.get(SONAR_SECURITY_REALM.getKey()).orElse(null); this.isLdapAuthActivated = LDAP_SECURITY_REALM.equals(realmName); boolean ignoreStartupFailure = configuration.getBoolean(SONAR_AUTHENTICATOR_IGNORE_STARTUP_FAILURE.getKey()).orElse(false); if (!isLdapAuthActivated) { this.usersProvider = null; this.groupsProvider = null; this.authenticator = null; } else { Map<String, LdapContextFactory> contextFactories = settingsManager.getContextFactories(); Map<String, LdapUserMapping> userMappings = settingsManager.getUserMappings(); this.usersProvider = new DefaultLdapUsersProvider(contextFactories, userMappings); this.authenticator = new DefaultLdapAuthenticator(contextFactories, userMappings); this.groupsProvider = createGroupsProvider(contextFactories, userMappings, settingsManager); testConnections(contextFactories, ignoreStartupFailure); } } private static LdapGroupsProvider createGroupsProvider(Map<String, LdapContextFactory> contextFactories, Map<String, LdapUserMapping> userMappings, LdapSettingsManager settingsManager) { Map<String, LdapGroupMapping> groupMappings = settingsManager.getGroupMappings(); if (!groupMappings.isEmpty()) { return new DefaultLdapGroupsProvider(contextFactories, userMappings, groupMappings); } else { return null; } } private static void testConnections(Map<String, LdapContextFactory> contextFactories, boolean ignoreStartupFailure) { try { for (LdapContextFactory contextFactory : contextFactories.values()) { contextFactory.testConnection(); } } catch (RuntimeException e) { if (ignoreStartupFailure) { LOG.error("IGNORED - LDAP realm failed to start: " + e.getMessage()); } else { throw new LdapException("LDAP realm failed to start: " + e.getMessage(), e); } } } @CheckForNull public LdapAuthenticator getAuthenticator() { return authenticator; } @CheckForNull public LdapUsersProvider getUsersProvider() { return usersProvider; } @CheckForNull public LdapGroupsProvider getGroupsProvider() { return groupsProvider; } public boolean isLdapAuthActivated() { return isLdapAuthActivated; } }
4,248
37.981651
149
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapSearch.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import java.util.Arrays; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.PartialResultException; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Fluent API for building LDAP queries. * * @author Evgeny Mandrikov */ public class LdapSearch { private static final Logger LOG = LoggerFactory.getLogger(LdapSearch.class); private final LdapContextFactory contextFactory; private String baseDn; private int scope = SearchControls.SUBTREE_SCOPE; private String request; private String[] parameters; private String[] returningAttributes; public LdapSearch(LdapContextFactory contextFactory) { this.contextFactory = contextFactory; } /** * Sets BaseDN. */ public LdapSearch setBaseDn(String baseDn) { this.baseDn = baseDn; return this; } public String getBaseDn() { return baseDn; } /** * Sets the search scope. * * @see SearchControls#ONELEVEL_SCOPE * @see SearchControls#SUBTREE_SCOPE * @see SearchControls#OBJECT_SCOPE */ public LdapSearch setScope(int scope) { this.scope = scope; return this; } public int getScope() { return scope; } /** * Sets request. */ public LdapSearch setRequest(String request) { this.request = request; return this; } public String getRequest() { return request; } /** * Sets search parameters. */ public LdapSearch setParameters(String... parameters) { this.parameters = parameters; return this; } public String[] getParameters() { return parameters; } /** * Sets attributes, which should be returned by search. */ public LdapSearch returns(String... attributes) { this.returningAttributes = attributes; return this; } public String[] getReturningAttributes() { return returningAttributes; } /** * @throws NamingException if unable to perform search */ public NamingEnumeration<SearchResult> find() throws NamingException { LOG.debug("Search: {}", this); NamingEnumeration<SearchResult> result; InitialDirContext context = null; boolean threw = false; try { context = contextFactory.createBindContext(); SearchControls controls = new SearchControls(); controls.setSearchScope(scope); controls.setReturningAttributes(returningAttributes); result = context.search(baseDn, request, parameters, controls); threw = true; } finally { ContextHelper.close(context, threw); } return result; } /** * @return result, or null if not found * @throws NamingException if unable to perform search, or non unique result */ public SearchResult findUnique() throws NamingException { NamingEnumeration<SearchResult> result = find(); if (hasMore(result)) { SearchResult obj = result.next(); if (!hasMore(result)) { return obj; } throw new NamingException("Non unique result for " + toString()); } return null; } private static boolean hasMore(NamingEnumeration<SearchResult> result) throws NamingException { try { return result.hasMore(); } catch (PartialResultException e) { LOG.debug("More result might be forthcoming if the referral is followed", e); // See LDAP-62 and http://docs.oracle.com/javase/jndi/tutorial/ldap/referral/jndi.html : // When the LDAP service provider receives a referral despite your having set Context.REFERRAL to "ignore", it will throw a // PartialResultException(in the API reference documentation) to indicate that more results might be forthcoming if the referral is // followed. In this case, the server does not support the Manage Referral control and is supporting referral updates in some other // way. return false; } } @Override public String toString() { return getClass().getSimpleName() + "{" + "baseDn=" + baseDn + ", scope=" + scopeToString() + ", request=" + request + ", parameters=" + Arrays.toString(parameters) + ", attributes=" + Arrays.toString(returningAttributes) + "}"; } private String scopeToString() { switch (scope) { case SearchControls.ONELEVEL_SCOPE: return "onelevel"; case SearchControls.OBJECT_SCOPE: return "object"; case SearchControls.SUBTREE_SCOPE: default: return "subtree"; } } }
5,445
27.364583
137
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapSettingsManager.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import java.util.LinkedHashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.sonar.api.config.Configuration; import org.sonar.api.server.ServerSide; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The LdapSettingsManager will parse the settings. * This class is also responsible to cope with multiple ldap servers. */ @ServerSide public class LdapSettingsManager { public static final String DEFAULT_LDAP_SERVER_KEY = "default"; private static final Logger LOG = LoggerFactory.getLogger(LdapSettingsManager.class); private static final String LDAP_SERVERS_PROPERTY = "ldap.servers"; private static final String LDAP_PROPERTY_PREFIX = "ldap"; protected static final String MANDATORY_LDAP_PROPERTY_ERROR = "The property '%s' property is empty while it is mandatory."; private final Configuration config; private Map<String, LdapUserMapping> userMappings = null; private Map<String, LdapGroupMapping> groupMappings = null; private Map<String, LdapContextFactory> contextFactories; /** * Create an instance of the settings manager. * * @param config The config to use. */ public LdapSettingsManager(Configuration config) { this.config = config; } /** * Get all the @link{LdapUserMapping}s available in the settings. * * @return A @link{Map} with all the @link{LdapUserMapping} objects. * The key is the server key used in the settings (ldap for old single server notation). */ public Map<String, LdapUserMapping> getUserMappings() { if (userMappings == null) { createUserMappings(); } return userMappings; } private void createUserMappings() { userMappings = new LinkedHashMap<>(); String[] serverKeys = config.getStringArray(LDAP_SERVERS_PROPERTY); if (serverKeys.length > 0) { createUserMappingsForMultipleLdapConfig(serverKeys); } else { createUserMappingsForSingleLdapConfig(); } } private void createUserMappingsForMultipleLdapConfig(String[] serverKeys) { for (String serverKey : serverKeys) { LdapUserMapping userMapping = new LdapUserMapping(config, LDAP_PROPERTY_PREFIX + "." + serverKey); if (StringUtils.isNotBlank(userMapping.getBaseDn())) { LOG.info("User mapping for server {}: {}", serverKey, userMapping); userMappings.put(serverKey, userMapping); } else { LOG.info("Users will not be synchronized for server {}, because property 'ldap.{}.user.baseDn' is empty.", serverKey, serverKey); } } } private void createUserMappingsForSingleLdapConfig() { LdapUserMapping userMapping = new LdapUserMapping(config, LDAP_PROPERTY_PREFIX); if (StringUtils.isNotBlank(userMapping.getBaseDn())) { LOG.info("User mapping: {}", userMapping); userMappings.put(DEFAULT_LDAP_SERVER_KEY, userMapping); } else { LOG.info("Users will not be synchronized, because property 'ldap.user.baseDn' is empty."); } } /** * Get all the @link{LdapGroupMapping}s available in the settings. * * @return A @link{Map} with all the @link{LdapGroupMapping} objects. * The key is the server key used in the settings (ldap for old single server notation). */ public Map<String, LdapGroupMapping> getGroupMappings() { if (groupMappings == null) { createGroupMappings(); } return groupMappings; } private void createGroupMappings() { groupMappings = new LinkedHashMap<>(); String[] serverKeys = config.getStringArray(LDAP_SERVERS_PROPERTY); if (serverKeys.length > 0) { createGroupMappingsForMultipleLdapConfig(serverKeys); } else { createGroupMappingsForSingleLdapConfig(); } } private void createGroupMappingsForMultipleLdapConfig(String[] serverKeys) { for (String serverKey : serverKeys) { LdapGroupMapping groupMapping = new LdapGroupMapping(config, LDAP_PROPERTY_PREFIX + "." + serverKey); if (StringUtils.isNotBlank(groupMapping.getBaseDn())) { LOG.info("Group mapping for server {}: {}", serverKey, groupMapping); groupMappings.put(serverKey, groupMapping); } else { LOG.info("Groups will not be synchronized for server {}, because property 'ldap.{}.group.baseDn' is empty.", serverKey, serverKey); } } } private void createGroupMappingsForSingleLdapConfig() { LdapGroupMapping groupMapping = new LdapGroupMapping(config, LDAP_PROPERTY_PREFIX); if (StringUtils.isNotBlank(groupMapping.getBaseDn())) { LOG.info("Group mapping: {}", groupMapping); groupMappings.put(DEFAULT_LDAP_SERVER_KEY, groupMapping); } else { LOG.info("Groups will not be synchronized, because property 'ldap.group.baseDn' is empty."); } } /** * Get all the @link{LdapContextFactory}s available in the settings. * * @return A @link{Map} with all the @link{LdapContextFactory} objects. * The key is the server key used in the settings (ldap for old single server notation). */ public Map<String, LdapContextFactory> getContextFactories() { if (contextFactories == null) { contextFactories = new LinkedHashMap<>(); String[] serverKeys = config.getStringArray(LDAP_SERVERS_PROPERTY); if (serverKeys.length > 0) { initMultiLdapConfiguration(serverKeys); } else { initSimpleLdapConfiguration(); } } return contextFactories; } private void initSimpleLdapConfiguration() { LdapContextFactory contextFactory = initLdapContextFactory(LDAP_PROPERTY_PREFIX); contextFactories.put(DEFAULT_LDAP_SERVER_KEY, contextFactory); } private void initMultiLdapConfiguration(String[] serverKeys) { if (config.hasKey("ldap.url") || config.hasKey("ldap.realm")) { throw new LdapException("When defining multiple LDAP servers with the property '" + LDAP_SERVERS_PROPERTY + "', " + "all LDAP properties must be linked to one of those servers. Please remove properties like 'ldap.url', 'ldap.realm', ..."); } for (String serverKey : serverKeys) { LdapContextFactory contextFactory = initLdapContextFactory(LDAP_PROPERTY_PREFIX + "." + serverKey); contextFactories.put(serverKey, contextFactory); } } private LdapContextFactory initLdapContextFactory(String prefix) { String ldapUrlKey = prefix + ".url"; String ldapUrl = config.get(ldapUrlKey).orElse(null); if (StringUtils.isBlank(ldapUrl)) { throw new LdapException(String.format(MANDATORY_LDAP_PROPERTY_ERROR, ldapUrlKey)); } return new LdapContextFactory(config, prefix, ldapUrl); } }
7,476
37.942708
139
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapUserDetails.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import org.sonar.api.security.ExternalUsersProvider; /** * This class is not intended to be subclassed by clients. * * @see ExternalUsersProvider * @since 2.14 */ public final class LdapUserDetails { private String name = ""; private String email = ""; private String userId = ""; public void setEmail(String email) { this.email = email; } public String getEmail() { return email; } public void setName(String name) { this.name = name; } public String getName() { return name; } /** * @since 5.2 */ public void setUserId(String userId) { this.userId = userId; } /** * @since 5.2 */ public String getUserId() { return userId; } @Override public String toString() { StringBuilder sb = new StringBuilder("UserDetails{"); sb.append("name='").append(name).append('\''); sb.append(", email='").append(email).append('\''); sb.append(", userId='").append(userId).append('\''); sb.append('}'); return sb.toString(); } }
1,898
23.986842
75
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapUserMapping.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import org.apache.commons.lang.StringUtils; import org.sonar.api.config.Configuration; import static org.sonar.auth.ldap.LdapSettingsManager.MANDATORY_LDAP_PROPERTY_ERROR; /** * @author Evgeny Mandrikov */ public class LdapUserMapping { private static final String DEFAULT_NAME_ATTRIBUTE = "cn"; private static final String DEFAULT_EMAIL_ATTRIBUTE = "mail"; private static final String DEFAULT_REQUEST = "(&(objectClass=inetOrgPerson)(uid={login}))"; private final String baseDn; private final String request; private final String realNameAttribute; private final String emailAttribute; /** * Constructs mapping from Sonar settings. */ public LdapUserMapping(Configuration config, String settingsPrefix) { String userBaseDnSettingKey = settingsPrefix + ".user.baseDn"; this.baseDn = config.get(userBaseDnSettingKey).orElseThrow(() -> new LdapException(String.format(MANDATORY_LDAP_PROPERTY_ERROR, userBaseDnSettingKey))); this.realNameAttribute = StringUtils.defaultString(config.get(settingsPrefix + ".user.realNameAttribute").orElse(null), DEFAULT_NAME_ATTRIBUTE); this.emailAttribute = StringUtils.defaultString(config.get(settingsPrefix + ".user.emailAttribute").orElse(null), DEFAULT_EMAIL_ATTRIBUTE); String req = StringUtils.defaultString(config.get(settingsPrefix + ".user.request").orElse(null), DEFAULT_REQUEST); req = StringUtils.replace(req, "{login}", "{0}"); this.request = req; } /** * Search for this mapping. */ public LdapSearch createSearch(LdapContextFactory contextFactory, String username) { return new LdapSearch(contextFactory) .setBaseDn(getBaseDn()) .setRequest(getRequest()) .setParameters(username); } /** * Base DN. For example "ou=users,o=mycompany" or "cn=users" (Active Directory Server). */ public String getBaseDn() { return baseDn; } /** * Request. For example: * <pre> * (&(objectClass=inetOrgPerson)(uid={0})) * (&(objectClass=user)(sAMAccountName={0})) * </pre> */ public String getRequest() { return request; } /** * Real Name Attribute. For example "cn". */ public String getRealNameAttribute() { return realNameAttribute; } /** * EMail Attribute. For example "mail". */ public String getEmailAttribute() { return emailAttribute; } @Override public String toString() { return getClass().getSimpleName() + "{" + "baseDn=" + getBaseDn() + ", request=" + getRequest() + ", realNameAttribute=" + getRealNameAttribute() + ", emailAttribute=" + getEmailAttribute() + "}"; } }
3,502
31.435185
156
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapUsersProvider.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import org.sonar.api.server.http.HttpRequest; public interface LdapUsersProvider { LdapUserDetails doGetUserDetails(Context context); record Context(String serverKey, String username, HttpRequest request) { } }
1,094
33.21875
75
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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. */ @ParametersAreNonnullByDefault package org.sonar.auth.ldap; import javax.annotation.ParametersAreNonnullByDefault;
959
39
75
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/CallbackHandlerImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import javax.security.auth.callback.Callback; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; public class CallbackHandlerImplTest { @Test public void test() throws Exception { NameCallback nameCallback = new NameCallback("username"); PasswordCallback passwordCallback = new PasswordCallback("password", false); new CallbackHandlerImpl("tester", "secret").handle(new Callback[] {nameCallback, passwordCallback}); assertThat(nameCallback.getName()).isEqualTo("tester"); assertThat(passwordCallback.getPassword()).isEqualTo("secret".toCharArray()); } @Test public void unsupportedCallback() { assertThatThrownBy(() -> { new CallbackHandlerImpl("tester", "secret").handle(new Callback[] {mock(Callback.class)}); }) .isInstanceOf(UnsupportedCallbackException.class); } }
2,007
36.886792
104
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/ContextHelperTest.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import javax.naming.Context; import javax.naming.NamingException; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; public class ContextHelperTest { @Test public void shouldSwallow() throws Exception { Context context = mock(Context.class); doThrow(new NamingException()).when(context).close(); ContextHelper.close(context, true); ContextHelper.closeQuietly(context); } @Test public void shouldNotSwallow() throws Exception { Context context = mock(Context.class); doThrow(new NamingException()).when(context).close(); assertThatThrownBy(() -> ContextHelper.close(context, false)) .isInstanceOf(NamingException.class); } @Test public void normal() throws NamingException { ContextHelper.close(null, true); ContextHelper.closeQuietly(null); ContextHelper.close(mock(Context.class), true); } }
1,857
32.178571
75
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapGroupMappingTest.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import org.junit.Test; import org.sonar.api.config.internal.MapSettings; import static org.assertj.core.api.Assertions.assertThat; public class LdapGroupMappingTest { @Test public void defaults() { LdapGroupMapping groupMapping = new LdapGroupMapping(new MapSettings().asConfig(), "ldap"); assertThat(groupMapping.getBaseDn()).isNull(); assertThat(groupMapping.getIdAttribute()).isEqualTo("cn"); assertThat(groupMapping.getRequest()).isEqualTo("(&(objectClass=groupOfUniqueNames)(uniqueMember={0}))"); assertThat(groupMapping.getRequiredUserAttributes()).isEqualTo(new String[] {"dn"}); assertThat(groupMapping).hasToString("LdapGroupMapping{" + "baseDn=null," + " idAttribute=cn," + " requiredUserAttributes=[dn]," + " request=(&(objectClass=groupOfUniqueNames)(uniqueMember={0}))}"); } @Test public void custom_request() { MapSettings settings = new MapSettings() .setProperty("ldap.group.request", "(&(|(objectClass=posixGroup)(objectClass=groupOfUniqueNames))(|(memberUid={uid})(uniqueMember={dn})))"); LdapGroupMapping groupMapping = new LdapGroupMapping(settings.asConfig(), "ldap"); assertThat(groupMapping.getRequest()).isEqualTo("(&(|(objectClass=posixGroup)(objectClass=groupOfUniqueNames))(|(memberUid={0})(uniqueMember={1})))"); assertThat(groupMapping.getRequiredUserAttributes()).isEqualTo(new String[] {"uid", "dn"}); } }
2,300
40.089286
154
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class LdapModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new LdapModule().configure(container); assertThat(container.getAddedObjects()).hasSize(2); } }
1,249
32.783784
75
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapSettingsManagerTest.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import java.util.Map; import org.junit.Test; import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.MapSettings; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class LdapSettingsManagerTest { @Test public void shouldFailWhenNoLdapUrl() { MapSettings settings = generateMultipleLdapSettingsWithUserAndGroupMapping(); settings.removeProperty("ldap.example.url"); LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); assertThatThrownBy(settingsManager::getContextFactories) .isInstanceOf(LdapException.class) .hasMessage("The property 'ldap.example.url' property is empty while it is mandatory."); } @Test public void shouldFailWhenMixingSingleAndMultipleConfiguration() { MapSettings settings = generateMultipleLdapSettingsWithUserAndGroupMapping(); settings.setProperty("ldap.url", "ldap://foo"); LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); assertThatThrownBy(settingsManager::getContextFactories) .isInstanceOf(LdapException.class) .hasMessage("When defining multiple LDAP servers with the property 'ldap.servers', all LDAP properties must be linked to one of those servers. Please remove properties like 'ldap.url', 'ldap.realm', ..."); } @Test public void testContextFactoriesWithSingleLdap() { LdapSettingsManager settingsManager = new LdapSettingsManager( generateSingleLdapSettingsWithUserAndGroupMapping().asConfig()); assertThat(settingsManager.getContextFactories()).hasSize(1); } /** * Test there are 2 @link{org.sonar.plugins.ldap.LdapContextFactory}s found. * */ @Test public void testContextFactoriesWithMultipleLdap() { LdapSettingsManager settingsManager = new LdapSettingsManager( generateMultipleLdapSettingsWithUserAndGroupMapping().asConfig()); assertThat(settingsManager.getContextFactories()).hasSize(2); // We do it twice to make sure the settings keep the same. assertThat(settingsManager.getContextFactories()).hasSize(2); } @Test public void getUserMappings_shouldCreateUserMappings_whenMultipleLdapConfig() { Configuration configuration = generateMultipleLdapSettingsWithUserAndGroupMapping().asConfig(); LdapSettingsManager settingsManager = new LdapSettingsManager(configuration); Map<String, LdapUserMapping> result = settingsManager.getUserMappings(); assertThat(result).hasSize(2).containsOnlyKeys("example", "infosupport"); assertThat(result.get("example")).usingRecursiveComparison().isEqualTo(new LdapUserMapping(configuration, "ldap.example")); assertThat(result.get("infosupport")).usingRecursiveComparison().isEqualTo(new LdapUserMapping(configuration, "ldap.infosupport")); } @Test public void getGroupMappings_shouldCreateGroupMappings_whenMultipleLdapConfig() { Configuration configuration = generateMultipleLdapSettingsWithUserAndGroupMapping().asConfig(); LdapSettingsManager settingsManager = new LdapSettingsManager(configuration); Map<String, LdapGroupMapping> result = settingsManager.getGroupMappings(); assertThat(result).hasSize(2).containsOnlyKeys("example", "infosupport"); assertThat(result.get("example")).usingRecursiveComparison().isEqualTo(new LdapGroupMapping(configuration, "ldap.example")); assertThat(result.get("infosupport")).usingRecursiveComparison().isEqualTo(new LdapGroupMapping(configuration, "ldap.infosupport")); } /** * Test what happens when no configuration is set. */ @Test public void testEmptySettings() { LdapSettingsManager settingsManager = new LdapSettingsManager( new MapSettings().asConfig()); assertThatThrownBy(settingsManager::getContextFactories) .isInstanceOf(LdapException.class) .hasMessage("The property 'ldap.url' property is empty while it is mandatory."); } @Test public void getUserMappings_shouldCreateUserMappings_whenSingleLdapConfig() { Configuration configuration = generateSingleLdapSettingsWithUserAndGroupMapping().asConfig(); LdapSettingsManager settingsManager = new LdapSettingsManager(configuration); Map<String, LdapUserMapping> result = settingsManager.getUserMappings(); assertThat(result).hasSize(1).containsOnlyKeys("default"); assertThat(result.get("default")).usingRecursiveComparison().isEqualTo(new LdapUserMapping(configuration, "ldap")); } @Test public void getGroupMappings_shouldCreateGroupMappings_whenSingleLdapConfig() { Configuration configuration = generateSingleLdapSettingsWithUserAndGroupMapping().asConfig(); LdapSettingsManager settingsManager = new LdapSettingsManager(configuration); Map<String, LdapGroupMapping> result = settingsManager.getGroupMappings(); assertThat(result).hasSize(1).containsOnlyKeys("default"); assertThat(result.get("default")).usingRecursiveComparison().isEqualTo(new LdapGroupMapping(configuration, "ldap")); } private MapSettings generateMultipleLdapSettingsWithUserAndGroupMapping() { MapSettings settings = new MapSettings(); settings.setProperty("ldap.servers", "example,infosupport"); settings.setProperty("ldap.example.url", "/users.example.org.ldif") .setProperty("ldap.example.user.baseDn", "ou=users,dc=example,dc=org") .setProperty("ldap.example.group.baseDn", "ou=groups,dc=example,dc=org") .setProperty("ldap.example.group.request", "(&(objectClass=posixGroup)(memberUid={uid}))"); settings.setProperty("ldap.infosupport.url", "/users.infosupport.com.ldif") .setProperty("ldap.infosupport.user.baseDn", "ou=users,dc=infosupport,dc=com") .setProperty("ldap.infosupport.group.baseDn", "ou=groups,dc=infosupport,dc=com") .setProperty("ldap.infosupport.group.request", "(&(objectClass=posixGroup)(memberUid={uid}))"); return settings; } private MapSettings generateSingleLdapSettingsWithUserAndGroupMapping() { MapSettings settings = new MapSettings(); settings.setProperty("ldap.url", "/users.example.org.ldif") .setProperty("ldap.user.baseDn", "ou=users,dc=example,dc=org") .setProperty("ldap.group.baseDn", "ou=groups,dc=example,dc=org") .setProperty("ldap.group.request", "(&(objectClass=posixGroup)(memberUid={uid}))"); return settings; } }
7,306
42.754491
211
java
sonarqube
sonarqube-master/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapUserMappingTest.java
/* * SonarQube * Copyright (C) 2009-2023 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.ldap; import org.junit.Test; import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.MapSettings; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class LdapUserMappingTest { @Test public void defaults() { MapSettings mapSettings = new MapSettings().setProperty("ldap.user.baseDn", "cn=users"); LdapUserMapping userMapping = new LdapUserMapping(mapSettings.asConfig(), "ldap"); assertThat(userMapping.getBaseDn()).isEqualTo("cn=users"); assertThat(userMapping.getRequest()).isEqualTo("(&(objectClass=inetOrgPerson)(uid={0}))"); assertThat(userMapping.getRealNameAttribute()).isEqualTo("cn"); assertThat(userMapping.getEmailAttribute()).isEqualTo("mail"); assertThat(userMapping).hasToString("LdapUserMapping{" + "baseDn=cn=users," + " request=(&(objectClass=inetOrgPerson)(uid={0}))," + " realNameAttribute=cn," + " emailAttribute=mail}"); } @Test public void activeDirectory() { MapSettings settings = new MapSettings() .setProperty("ldap.user.baseDn", "cn=users") .setProperty("ldap.user.request", "(&(objectClass=user)(sAMAccountName={0}))"); LdapUserMapping userMapping = new LdapUserMapping(settings.asConfig(), "ldap"); LdapSearch search = userMapping.createSearch(null, "tester"); assertThat(search.getBaseDn()).isEqualTo("cn=users"); assertThat(search.getRequest()).isEqualTo("(&(objectClass=user)(sAMAccountName={0}))"); assertThat(search.getParameters()).isEqualTo(new String[] {"tester"}); assertThat(search.getReturningAttributes()).isNull(); assertThat(userMapping).hasToString("LdapUserMapping{" + "baseDn=cn=users," + " request=(&(objectClass=user)(sAMAccountName={0}))," + " realNameAttribute=cn," + " emailAttribute=mail}"); } @Test public void ldapUserMapping_shouldThrowException_whenUserBaseDnIsNotSet() { Configuration config = new MapSettings() .setProperty("ldap.realm", "example.org") .setProperty("ldap.userObjectClass", "user") .setProperty("ldap.loginAttribute", "sAMAccountName") .asConfig(); assertThatThrownBy(() -> new LdapUserMapping(config, "ldap")) .isInstanceOf(LdapException.class) .hasMessage("The property 'ldap.user.baseDn' property is empty while it is mandatory."); } }
3,276
39.45679
94
java
sonarqube
sonarqube-master/server/sonar-auth-saml/src/it/java/org/sonar/auth/saml/SamlIdentityProviderIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.saml; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.PropertyDefinitions; 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 org.sonar.api.server.http.HttpResponse; import org.sonar.api.testfixtures.log.LogAndArguments; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.server.http.JavaxHttpRequest; import org.sonar.server.http.JavaxHttpResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.api.utils.log.LoggerLevel.ERROR; public class SamlIdentityProviderIT { private static final String SQ_CALLBACK_URL = "http://localhost:9000/oauth2/callback/saml"; /* IDP private key (keep here for future tests with signature) -----BEGIN PRIVATE KEY-----MIIJQQIBADANBgkqhkiG9w0BAQEFAASCCSswggknAgEAAoICAQC7ecVdi8hh52lHzhpmR2j/fIHlccz5gIUlwOxU7XTMRuUuSd9CyIw9rVd31Sy2enHDo/9LLMgmY72OIw514J5j3xrviM/t3gk9o7qHeX0htYBxh6KNCD3nqeWxUVjcUcMav7s9vxBw4DJXe/z2OIX0MUHzBdL7lR9ivY5+hFFviWLf17MPIN2Xk4uUzXWcSyzbPWYS/6xRSWhNzKuCPfs+yB7CS/LKbq0UZKCRX1lrhJVGEcXJOFjVUWthlIkVOdqlRhpFzuQzHPBf8AAdQMmuZhxpVzkHw4OnjDYDEMmF5DIJV9eM8VpSoEwbZT+th9Ve7Rlrs+f+9SjhRpJOHAIEoN6ELDP7rlMt0D43HIYPGe9j9KSw7IssYKa7y0qRd27SnOeciEFcQa+NQhVLt3pr/yB6D3U2hNZq7eLREX4PD/k30NLOmV3Xls+1vkJ7cGJ7X269++4f16D4PzH+F8Xp/eKXiw+Ugp0785V0zbwtF+YOqapA0+529urPvHLgBG7GToBFrh35pP3Oi+nC/E0ZOvuHWZ2A5S1QJ0hcvdIc2N3B0ADPS4JbO8TFsW741D5Xn5eeTHvWHI8W/34MtUYi7smF1izzTrAqyE7Xc2BrfyKDqC7fuWlWF+lleErLBSKKAbotcB7JZaQyT6+V/0xxl0wEPXp1k/iROy8/6s9WdQIDAQABAoICAC34UAL+MaaAHfqzeRm3TPHIz/k5DG/pqbx2L/0rNMaaY7wT9SDlGC5PgPErXoloQNkeL415b6KqNmLSCcuxxmTq4in2PDYxicaJjUWG7r4DSXmNLriyWquhp2bxcX6ktdirRvh/D0L+VpnJF2Awv/f+1BMJTJDQIiAOJxCy1V0qLQqCU6/T+UIftcxJDRvD+z3PMmZaNyC/hUn+c9e95wuf+preEKy+ssYbXpwG62BH5GqIFR2gKXg1PMVyrKJ9yzVXmT2g26gE4pRDv2Ns7YdMFo9mCd/zeybsZJof1ap1KCfOWFaBIAq+r6rQCus8MX/TV7ZnKO4Fo36J1Xo9t+iKGpvw2nwrN7I71MT3c8wglfg2zmgFqjNYdeUDFOrl0GXRboBcDSX4dd5iB9fkqZ9dOqTtTzPQNwEhbDqLyYQ6I+00nihW8xzEUaiqd4tey7WXoqae3u0Bo7ep5jbE7dzKWxiBKaqlfI+S4aWDkhUiwkUKvkSC3SXWWehJbaVQZb5+DvSjWU5nLQxcVZdMl9Lp7kE0+nEeS1hO8C1r482jlXKppl9k0GjkoIRzU9RARxHNt1UvHURa43CQ/4nIGNsK9WeYVxk2vR/qozCE6dKIRv+5gZrD32YM2UrPf8kAAQOSpW4iumtWuqkrysr3/04f40mCtLV1uNF6EQcV+WfJAoIBAQC+A4JoY7gMrEf0EmRVhNbAuRkt67ENz8PBr8NvDlgIVM9ZdjeVFYSKWeL+TbkwihBoSqhn5wgAs5RhiNGjwqgL+odHVY/9KirQDvcdsy8/NaheYd+JJLAyCOLJKAc/C7VaZ5fFpHWOKRkUPVOliK955+3cxLp37q1+10p4406i6JIWphzqNt8rCpEQgXydIfEgDY8IDoEs65+9JcutFkH2MtQR1ypH0uLPvNCVZu8SNitmcvERq2/mJ4U1+8rIhAJhbq9uvaSXBSKFSzK62hdxvOLvMIlKFcEia8xTBCO9MbLxIbSH2Ht69HSCmZSytaHBodOb7qBcLjOQD5ZXMPGjAoIBAQD8lKBHrYUT8Cd39B5IkdeU6tVbiJ80Lb2E2ePLbg3/Dx9NsmzXrvLeHI60+gpxP+GlI/h2IzUvLsOuEf5ICjmu9NrnK2lJJmS/pCZlKxEV0k1T0fyITMyjk0iy9Vb70+PF3CDextnEY3zzhkHj7iaXqXIf1zs2ypm3zTGsGLdLXT+5Fm2sxdhLUKGIwfflaUruyLTyE/OiArDrezqgX7CVlF4Q2zgQZqRHDODxt09fJbz0FU422y02Hv/sG5cYFB5C24upwe3dIXrFyM9xuZnTUpM8z8DLPeLShKUUqsiL/qyhxLbXgdGkXsDaPrX31eTX99gG3AX9WoxENLQzvgkHAoIBABkSzXqI7hh+A2CprKO8S7pSsofkuhBggixkzR0yf1taFaJwfxUlKcA37EQybWWCUnfwohhT3DJ7f/D+5Or/HL236XH4UG/PyKZ70xAQPQPSSM1rjNvEA5wWoBZ7ObmQCfZMBTMHaJvBwJVzIj6NstobSMABFboNvMcoEaOyGwZUOjLS6K3fX8OGOW48J/10JSVdpKojf9g1n3aOLjpA3aNnQaS5B9NCeLuA5uVQF+wHSeLS+Ayk2rc8L8/X0gJzqPzCZlPuonFrNAryyVbuwHk5u5hkhzlHdZzdLLEnsq+ch0hackAayPCIoXc6XOzYGug6OnoxGugPEK7J38TRqJECggEAdXZxK6RotSMEV+axhrI8fcbQPmdFErEK6BOkumCOJcXUmv+VWqDD1cOWIlf+Lzi0KWaXD+nDvBOVcQhxJvOKa/D3NHad2iT+yZj/OiFTKsDIsWiAdqqwqInAT2mFcEvUK5n5t2DmuUxDOcWAMw336KQmrOQdZ5fE8RN+PDiqVWQiVGM30heYRT5UQRNjw865yF6St9nLfdaejISceSTHLGj5bgFlC0uQrnIw0nibcvZL739RBnXbisXT4uvZ0prYj+MmCmZjxmjhfcWro4nbHcnTK366fEplh92kH/5kkaZ4hirDlWmMI1LlgRmU6pMQf9eFIXuFVZOck8Om4kFIVQKCAQARCxrge8m+hOTJ7EkNtxor+o+4XioZSQ+Ht9lNOL+Ry1J08fldWwM8P4cpVE7WHi+73UM7NlJDLRaCCgS13C7FoW1klK1Rt3VtJRUF4Ic6B8RcLZQrOAp4sfbCLeT/PomexJ6KURdXof3GaTdij3F149NsNoje1VPEBLq5GE9j8vbPI/pyhJxfXzWtKXUGkNG9fC0oH7NjWqTDVoBiyUbZurCY8KN5oIh40UwJnUqvgu6gaUItfStmJn78VgsFZLTJvPcfnir+q9mOVp8WBYE3jrPYEhWtEP2MaG+nAGBi7AuRZ0tCsOL+s8ADNyzOx9WtFQcXryn6b7+BjIEbSrjg-----END PRIVATE KEY----- */ private static final String IDP_CERTIFICATE = "-----BEGIN CERTIFICATE-----MIIF5zCCA8+gAwIBAgIUIXv9OVs/XUicgR1bsV9uccYhHfowDQYJKoZIhvcNAQELBQAwgYIxCzAJBgNVBAYTAkFVMQ8wDQYDVQQIDAZHRU5FVkExEDAOBgNVBAcMB1ZFUk5JRVIxDjAMBgNVBAoMBVNPTkFSMQ0wCwYDVQQLDARRVUJFMQ8wDQYDVQQDDAZaaXBlbmcxIDAeBgkqhkiG9w0BCQEWEW5vcmVwbHlAZ21haWwuY29tMB4XDTIyMDYxMzEzMTQyN1oXDTMyMDYxMDEzMTQyN1owgYIxCzAJBgNVBAYTAkFVMQ8wDQYDVQQIDAZHRU5FVkExEDAOBgNVBAcMB1ZFUk5JRVIxDjAMBgNVBAoMBVNPTkFSMQ0wCwYDVQQLDARRVUJFMQ8wDQYDVQQDDAZaaXBlbmcxIDAeBgkqhkiG9w0BCQEWEW5vcmVwbHlAZ21haWwuY29tMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAu3nFXYvIYedpR84aZkdo/3yB5XHM+YCFJcDsVO10zEblLknfQsiMPa1Xd9Ustnpxw6P/SyzIJmO9jiMOdeCeY98a74jP7d4JPaO6h3l9IbWAcYeijQg956nlsVFY3FHDGr+7Pb8QcOAyV3v89jiF9DFB8wXS+5UfYr2OfoRRb4li39ezDyDdl5OLlM11nEss2z1mEv+sUUloTcyrgj37Psgewkvyym6tFGSgkV9Za4SVRhHFyThY1VFrYZSJFTnapUYaRc7kMxzwX/AAHUDJrmYcaVc5B8ODp4w2AxDJheQyCVfXjPFaUqBMG2U/rYfVXu0Za7Pn/vUo4UaSThwCBKDehCwz+65TLdA+NxyGDxnvY/SksOyLLGCmu8tKkXdu0pznnIhBXEGvjUIVS7d6a/8geg91NoTWau3i0RF+Dw/5N9DSzpld15bPtb5Ce3Bie19uvfvuH9eg+D8x/hfF6f3il4sPlIKdO/OVdM28LRfmDqmqQNPudvbqz7xy4ARuxk6ARa4d+aT9zovpwvxNGTr7h1mdgOUtUCdIXL3SHNjdwdAAz0uCWzvExbFu+NQ+V5+Xnkx71hyPFv9+DLVGIu7JhdYs806wKshO13Nga38ig6gu37lpVhfpZXhKywUiigG6LXAeyWWkMk+vlf9McZdMBD16dZP4kTsvP+rPVnUCAwEAAaNTMFEwHQYDVR0OBBYEFI5UVLtTySvbGqH7UP8xTL4wxZq3MB8GA1UdIwQYMBaAFI5UVLtTySvbGqH7UP8xTL4wxZq3MA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggIBABAtXsKNWx0sDDFA53qZ1zRyWKWAMoh95pawFCrKgTEW4ZrA73pa790eE1Y+vT6qUXKI4li9skIDa+6psCdxhZIrHPRAnVZVeB2373Bxr5bw/XQ8elRCjWeMULbYJ9tgsLV0I9CiEP0a6Tm8t0yDVXNUfx36E5fkgLSrxoRo8XJzxHbJCnLVXHdaNBxOT7jVcom6Wo4PB2bsjVzhHm6amn5hZp4dMHm0Mv0ln1wH8jVnizHQBLsGMzvvl58+9s1pP17ceRDkpNDz+EQyA+ZArqkW1MqtwVhbzz8QgMprhflKkArrsC7v06Jv8fqUbn9LvtYK9IwHTX7J8dFcsO/gUC5PevYT3nriN3Azb20ggSQ1yOEMozvj5T96S6itfHPit7vyEQ84JPrEqfuQDZQ/LKZQqfvuXX1aAG3TU3TMWB9VMMFsTuMFS8bfrhMX77g0Ud4qJcBOYOH3hR59agSdd2QZNLP3zZsYQHLLQkq94jdTXKTqm/w7mlPFKV59HjTbHBhTtxBHMft/mvvLEuC9KKFfAOXYQ6V+s9Nk0BW4ggEfewaX58OBuy7ISqRtRFPGia18YRzzHqkhjubJYMPkIfYpFVd+C0II3F0kdy8TtpccjyKo9bcHMLxO4n8PDAl195CPthMi8gUvT008LGEotr+3kXsouTEZTT0glXKLdO2W-----END CERTIFICATE-----"; private static final String SP_CERTIFICATE = "MIICoTCCAYkCBgGBXPscaDANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDDAlzb25hcnF1YmUwHhcNMjIwNjEzMTIxMTA5WhcNMzIwNjEzMTIxMjQ5WjAUMRIwEAYDVQQDDAlzb25hcnF1YmUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDSFoT371C0/klZuPgvKbGItkmTaf5CweNXL8u389d98aOXRpDQ7maTXdV/W+VcL8vUWg8yG6nn8CRwweYnGTNdn9UAdhgknvxQe3pq3EwOJyls4Fpiq6YTh+DQfiZUQizjFjDOr/GG5O2lNvTRkI4XZj/XnWjRqVZwttiA5tm1sKkvGdyOQljwn4Jja/VbITdV8GASumx66Bil/wamSsqIzm2RjsOOGSsf5VjYUPwDobpuSf+j4DLtWjem/9vIzI2wcE30uC8LBAgO3JAlIS9NQrchjS9xhMJRohOoitaSPmqsOy7D2BH0h7XX6TNgv/WYTkBY4eZPao3PsL2A6AmhAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAMBmTHUK4w+DX21tmhqdwq0WqLH5ZAkwtiocDxFXiJ4GRrUWUh3BaXsgOHB8YYnNTDfScjaU0sZMEyfC0su1zsN8B7NFckg7RcZCHuBYdgIEAmvK4YM6s6zNsiKKwt66p2MNeL+o0acrT2rYjQ1L5QDj0gpfJQAT4N7xTZfuSc2iwjotaQfvcgsO8EZlcDVrL4UuyWLbuRUlSQjxHWGYaxCW+I3enK1+8fGpF3O+k9ZQ8xt5nJsalpsZvHcPLA4IBOmjsSHqSkhg4EIAWL/sJZ1KNct4hHh5kToUTu+Q6e949VeBkWgj4O+rcGDgiN2frGiEEc0EMv8KCSENRRRrO2k="; private static final String SP_PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDSFoT371C0/klZuPgvKbGItkmTaf5CweNXL8u389d98aOXRpDQ7maTXdV/W+VcL8vUWg8yG6nn8CRwweYnGTNdn9UAdhgknvxQe3pq3EwOJyls4Fpiq6YTh+DQfiZUQizjFjDOr/GG5O2lNvTRkI4XZj/XnWjRqVZwttiA5tm1sKkvGdyOQljwn4Jja/VbITdV8GASumx66Bil/wamSsqIzm2RjsOOGSsf5VjYUPwDobpuSf+j4DLtWjem/9vIzI2wcE30uC8LBAgO3JAlIS9NQrchjS9xhMJRohOoitaSPmqsOy7D2BH0h7XX6TNgv/WYTkBY4eZPao3PsL2A6AmhAgMBAAECggEBAJj11HJAR96/leBBkFGmZaBIOGGgNoOcb023evfADhGgsZ8evamhKgX5t8w2uFPaaOl/eLje82Hvslh2lH+7FW8BRDBFy2Y+ay6d+I99PdLAKKUg5C4bE5v8vm6OqpGGbPAZ5AdYit3QKEa2MKG0QgA/bhQqg3rDdDA0sIWJjtF9MLv7LI7Tm0qgiHOKsI0MEBFk+ZoibgKWYh/dnfGDRWyC3Puqe13rdSheNJYUDR/0QMkd/EJNpLWv06uk+w8w2lU4RgN6TiV76ZZUIGZAAHFgMELJysgtBTCkOQY5roPu17OmMZjKfxngeIfNyd42q3/T6DmUbbwNYfP2HRMoiMECgYEA6SVc1mZ4ykytC9M61rZwT+2zXtJKudQVa0qpTtkf0aznRmnDOuc1bL7ewKIIIp9r5HKVteO6SKgpHmrP+qmvbwZ0Pz51Zg0MetoSmT9m0599/tOU2k6OI09dvQ4Xa3ccN5Czl61Q/HkMeAIDny8MrhGVBwhallE4J4fm/OjuVK0CgYEA5q6IVgqZtfcV1azIF6uOFt6blfn142zrwq0fF39jog2f+4jXaBKw6L4aP0HvIL83UArGppYY31894bLb6YL4EjS2JNbABM2VnJpJd4oGopOE42GCZlZRpf751zOptYAN23NFSujLlfaUfMbyrqIbRFC2DCdzNTU50GT5SAXX80UCgYEAlyvQvHwJCjMZaTd3SU1WGZ1o1qzIIyHvGXh5u1Rxm0TfWPquyfys2WwRhxoI6FoyXRgnFp8oZIAU2VIstL1dsUGgEnnvKVKAqw/HS3Keu80IpziNpdeVtjN59mGysc2zkBvVNx38Cxh6Cz5TFt4s/JkN5ld2VU0oeglWrtph3qkCgYALszZ/BrKdJBcba1QKv0zJpCjIBpGOI2whx54YFwH6qi4/F8W1JZ2LcHjsVG/IfWpUyPciY+KHEdGVrPiyc04Zvkquu6WpmLPJ6ZloUrvbaxgGYF+4yRADF1ecrqYg6onJY6NUFVKeHI+TdJPCf75aTK2vGCEjxbtU8ooiOQmm8QKBgEGe9ZdrwTP9rMQ35jYtzU+dT06k1r9BE9Q8CmrXl0HwK717ZWboX4J0YoFjxZC8PDsMl3p46MJ83rKbLU728uKig1AkZo7/OedxTWvezjZ1+lDyjC2EguXbgY1ecSC2HbJh9g+v8RUuhWxuA7RYoW92xVtKj+6l4vMadVP4Myp8-----END PRIVATE KEY-----"; @Rule public DbTester db = DbTester.create(); @Rule public LogTester log = new LogTester(); private final MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, SamlSettings.definitions())); private final SamlIdentityProvider underTest = new SamlIdentityProvider(new SamlSettings(settings.asConfig()), new SamlMessageIdChecker(db.getDbClient())); private HttpServletResponse response = mock(HttpServletResponse.class); private HttpServletRequest request = mock(HttpServletRequest.class); @Before public void setup() { this.request = mock(HttpServletRequest.class); this.response = mock(HttpServletResponse.class); when(this.request.getRequestURL()).thenReturn(new StringBuffer(SQ_CALLBACK_URL)); } @Test public void check_fields() { setSettings(true); assertThat(underTest.getKey()).isEqualTo("saml"); assertThat(underTest.getName()).isEqualTo("SAML"); assertThat(underTest.getDisplay().getIconPath()).isEqualTo("/images/saml.png"); assertThat(underTest.getDisplay().getBackgroundColor()).isEqualTo("#444444"); assertThat(underTest.allowsUsersToSignUp()).isTrue(); } @Test public void provider_name_is_provided_by_setting() { // Default value assertThat(underTest.getName()).isEqualTo("SAML"); settings.setProperty("sonar.auth.saml.providerName", "My Provider"); assertThat(underTest.getName()).isEqualTo("My Provider"); } @Test public void is_enabled() { setSettings(true); assertThat(underTest.isEnabled()).isTrue(); setSettings(false); assertThat(underTest.isEnabled()).isFalse(); } @Test public void init() throws IOException { setSettings(true); DumbInitContext context = new DumbInitContext(); underTest.init(context); verify(context.response).sendRedirect(anyString()); assertThat(context.generateCsrfState.get()).isTrue(); } @Test public void fail_to_init_when_login_url_is_invalid() { setSettings(true); settings.setProperty("sonar.auth.saml.loginUrl", "invalid"); DumbInitContext context = new DumbInitContext(); assertThatThrownBy(() -> underTest.init(context)) .isInstanceOf(IllegalStateException.class) .hasMessage("Failed to create a SAML Auth"); } @Test public void callback() { setSettings(true); DumbCallbackContext callbackContext = new DumbCallbackContext(request, response, "encoded_full_response.txt", SQ_CALLBACK_URL); underTest.callback(callbackContext); assertThat(callbackContext.redirectedToRequestedPage.get()).isTrue(); assertThat(callbackContext.userIdentity.getProviderLogin()).isEqualTo("johndoe"); assertThat(callbackContext.verifyState.get()).isTrue(); } @Test public void failed_callback_when_behind_a_reverse_proxy_without_needed_header() { setSettings(true); // simulate reverse proxy stripping SSL and not adding X-Forwarded-Proto header when(this.request.getRequestURL()).thenReturn(new StringBuffer("http://localhost/oauth2/callback/saml")); DumbCallbackContext callbackContext = new DumbCallbackContext(request, response, "encoded_full_response_with_reverse_proxy.txt", "https://localhost/oauth2/callback/saml"); assertThatThrownBy(() -> underTest.callback(callbackContext)) .isInstanceOf(UnauthorizedException.class) .hasMessageContaining("The response was received at http://localhost/oauth2/callback/saml instead of https://localhost/oauth2/callback/saml"); } @Test public void successful_callback_when_behind_a_reverse_proxy_with_needed_header() { setSettings(true); // simulate reverse proxy stripping SSL and adding X-Forwarded-Proto header when(this.request.getRequestURL()).thenReturn(new StringBuffer("http://localhost/oauth2/callback/saml")); when(this.request.getHeader("X-Forwarded-Proto")).thenReturn("https"); DumbCallbackContext callbackContext = new DumbCallbackContext(request, response, "encoded_full_response_with_reverse_proxy.txt", "https://localhost/oauth2/callback/saml"); underTest.callback(callbackContext); assertThat(callbackContext.redirectedToRequestedPage.get()).isTrue(); assertThat(callbackContext.userIdentity.getProviderLogin()).isEqualTo("johndoe"); assertThat(callbackContext.verifyState.get()).isTrue(); } @Test public void callback_on_full_response() { setSettings(true); DumbCallbackContext callbackContext = new DumbCallbackContext(request, response, "encoded_full_response.txt", SQ_CALLBACK_URL); underTest.callback(callbackContext); assertThat(callbackContext.userIdentity.getName()).isEqualTo("John Doe"); assertThat(callbackContext.userIdentity.getEmail()).isEqualTo("johndoe@email.com"); assertThat(callbackContext.userIdentity.getProviderLogin()).isEqualTo("johndoe"); assertThat(callbackContext.userIdentity.getGroups()).containsExactlyInAnyOrder("developer", "product-manager"); } @Test public void callback_on_encrypted_response() { setSettings(true); DumbCallbackContext callbackContext = new DumbCallbackContext(request, response, "encoded_encrypted_response.txt", SQ_CALLBACK_URL); underTest.callback(callbackContext); assertThat(callbackContext.userIdentity.getName()).isEqualTo("John Doe"); assertThat(callbackContext.userIdentity.getEmail()).isEqualTo("johndoe@email.com"); assertThat(callbackContext.userIdentity.getProviderLogin()).isEqualTo("johndoe"); assertThat(callbackContext.userIdentity.getGroups()).containsExactlyInAnyOrder("developer", "product-manager"); } @Test public void callback_on_signed_request() throws IOException { setSettings(true); settings.setProperty("sonar.auth.saml.signature.enabled", true); DumbInitContext context = new DumbInitContext(); underTest.init(context); String[] samlRequestParams = {"http://localhost:8080/auth/realms/sonarqube/protocol/saml", "?SigAlg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%2Fxmldsig-more%23rsa-sha256", "&SAMLRequest=", "&Signature="}; verify(context.response).sendRedirect(argThat(x -> Arrays.stream(samlRequestParams).allMatch(x::contains))); } @Test public void callback_on_minimal_response() { setSettings(true); DumbCallbackContext callbackContext = new DumbCallbackContext(request, response, "encoded_minimal_response.txt", SQ_CALLBACK_URL); underTest.callback(callbackContext); assertThat(callbackContext.userIdentity.getName()).isEqualTo("John Doe"); assertThat(callbackContext.userIdentity.getEmail()).isNull(); assertThat(callbackContext.userIdentity.getProviderLogin()).isEqualTo("johndoe"); assertThat(callbackContext.userIdentity.getGroups()).isEmpty(); } @Test public void log_clear_error_when_private_key_is_not_pkcs8() { var WRONG_FORMAT_PRIVATE_KEY = "MIIEpAIBAAKCAQEA0haE9+9QtP5JWbj4LymxiLZJk2n+QsHjVy/Lt/PXffGjl0aQ0O5mk13Vf1vlXC/L1FoPMhup5/AkcMHmJxkzXZ/VAHYYJJ78UHt6atxMDicpbOBaYqumE4fg0H4mVEIs4xYwzq/xhuTtpTb00ZCOF2Y/151o0alWcLbYgObZtbCpLxncjkJY8J+CY2v1WyE3VfBgErpseugYpf8GpkrKiM5tkY7DjhkrH+VY2FD8A6G6bkn/o+Ay7Vo3pv/byMyNsHBN9LgvCwQIDtyQJSEvTUK3IY0vcYTCUaITqIrWkj5qrDsuw9gR9Ie11+kzYL/1mE5AWOHmT2qNz7C9gOgJoQIDAQABAoIBAQCY9dRyQEfev5XgQZBRpmWgSDhhoDaDnG9Nt3r3wA4RoLGfHr2poSoF+bfMNrhT2mjpf3i43vNh77JYdpR/uxVvAUQwRctmPmsunfiPfT3SwCilIOQuGxOb/L5ujqqRhmzwGeQHWIrd0ChGtjChtEIAP24UKoN6w3QwNLCFiY7RfTC7+yyO05tKoIhzirCNDBARZPmaIm4ClmIf3Z3xg0Vsgtz7qntd63UoXjSWFA0f9EDJHfxCTaS1r9OrpPsPMNpVOEYDek4le+mWVCBmQABxYDBCycrILQUwpDkGOa6D7tezpjGYyn8Z4HiHzcneNqt/0+g5lG28DWHz9h0TKIjBAoGBAOklXNZmeMpMrQvTOta2cE/ts17SSrnUFWtKqU7ZH9Gs50ZpwzrnNWy+3sCiCCKfa+RylbXjukioKR5qz/qpr28GdD8+dWYNDHraEpk/ZtOfff7TlNpOjiNPXb0OF2t3HDeQs5etUPx5DHgCA58vDK4RlQcIWpZROCeH5vzo7lStAoGBAOauiFYKmbX3FdWsyBerjhbem5X59eNs68KtHxd/Y6INn/uI12gSsOi+Gj9B7yC/N1AKxqaWGN9fPeGy2+mC+BI0tiTWwATNlZyaSXeKBqKThONhgmZWUaX++dczqbWADdtzRUroy5X2lHzG8q6iG0RQtgwnczU1OdBk+UgF1/NFAoGBAJcr0Lx8CQozGWk3d0lNVhmdaNasyCMh7xl4ebtUcZtE31j6rsn8rNlsEYcaCOhaMl0YJxafKGSAFNlSLLS9XbFBoBJ57ylSgKsPx0tynrvNCKc4jaXXlbYzefZhsrHNs5Ab1Tcd/AsYegs+UxbeLPyZDeZXdlVNKHoJVq7aYd6pAoGAC7M2fwaynSQXG2tUCr9MyaQoyAaRjiNsIceeGBcB+qouPxfFtSWdi3B47FRvyH1qVMj3ImPihxHRlaz4snNOGb5KrrulqZizyemZaFK722sYBmBfuMkQAxdXnK6mIOqJyWOjVBVSnhyPk3STwn++WkytrxghI8W7VPKKIjkJpvECgYBBnvWXa8Ez/azEN+Y2Lc1PnU9OpNa/QRPUPApq15dB8Cu9e2Vm6F+CdGKBY8WQvDw7DJd6eOjCfN6ymy1O9vLiooNQJGaO/znncU1r3s42dfpQ8owthILl24GNXnEgth2yYfYPr/EVLoVsbgO0WKFvdsVbSo/upeLzGnVT+DMqfA=="; setSettings(true); settings.setProperty("sonar.auth.saml.sp.privateKey.secured", WRONG_FORMAT_PRIVATE_KEY); DumbCallbackContext callbackContext = new DumbCallbackContext(request, response, "encoded_minimal_response.txt", SQ_CALLBACK_URL); underTest.callback(callbackContext); assertThat(log.getLogs(ERROR)) .extracting(LogAndArguments::getFormattedMsg) .contains("Error in parsing service provider private key, please make sure that it is in PKCS 8 format."); } @Test public void callback_does_not_sync_group_when_group_setting_is_not_set() { setSettings(true); settings.setProperty("sonar.auth.saml.group.name", (String) null); DumbCallbackContext callbackContext = new DumbCallbackContext(request, response, "encoded_full_response.txt", SQ_CALLBACK_URL); underTest.callback(callbackContext); assertThat(callbackContext.userIdentity.getProviderLogin()).isEqualTo("johndoe"); assertThat(callbackContext.userIdentity.getGroups()).isEmpty(); assertThat(callbackContext.userIdentity.shouldSyncGroups()).isFalse(); } @Test public void fail_to_callback_when_login_is_missing() { setSettings(true); DumbCallbackContext callbackContext = new DumbCallbackContext(request, response, "encoded_response_without_login.txt", SQ_CALLBACK_URL); assertThatThrownBy(() -> underTest.callback(callbackContext)) .isInstanceOf(NullPointerException.class) .hasMessage("login is missing"); } @Test public void fail_to_callback_when_name_is_missing() { setSettings(true); DumbCallbackContext callbackContext = new DumbCallbackContext(request, response, "encoded_response_without_name.txt", SQ_CALLBACK_URL); assertThatThrownBy(() -> underTest.callback(callbackContext)) .isInstanceOf(NullPointerException.class) .hasMessage("name is missing"); } @Test public void fail_to_callback_when_certificate_is_invalid() { setSettings(true); settings.setProperty("sonar.auth.saml.certificate.secured", "invalid"); DumbCallbackContext callbackContext = new DumbCallbackContext(request, response, "encoded_full_response.txt", SQ_CALLBACK_URL); assertThatThrownBy(() -> underTest.callback(callbackContext)) .isInstanceOf(IllegalStateException.class) .hasMessage("Failed to create a SAML Auth"); } @Test public void fail_to_callback_when_using_wrong_certificate() { setSettings(true); settings.setProperty("sonar.auth.saml.certificate.secured", "-----BEGIN CERTIFICATE-----\n" + "MIIEIzCCAwugAwIBAgIUHUzPjy5E2TmnsmTRT2sIUBRXFF8wDQYJKoZIhvcNAQEF\n" + "BQAwXDELMAkGA1UEBhMCVVMxFDASBgNVBAoMC1NvbmFyU291cmNlMRUwEwYDVQQL\n" + "DAxPbmVMb2dpbiBJZFAxIDAeBgNVBAMMF09uZUxvZ2luIEFjY291bnQgMTMxMTkx\n" + "MB4XDTE4MDcxOTA4NDUwNVoXDTIzMDcxOTA4NDUwNVowXDELMAkGA1UEBhMCVVMx\n" + "FDASBgNVBAoMC1NvbmFyU291cmNlMRUwEwYDVQQLDAxPbmVMb2dpbiBJZFAxIDAe\n" + "BgNVBAMMF09uZUxvZ2luIEFjY291bnQgMTMxMTkxMIIBIjANBgkqhkiG9w0BAQEF\n" + "AAOCAQ8AMIIBCgKCAQEArlpKHm4EkJiQyy+4GtZBixcy7fWnreB96T7cOoWLmWkK\n" + "05FM5M/boWHZsvaNAuHsoCAMzIY3/l+55WbORzAxsloH7rvDaDrdPYQN+sU9bzsD\n" + "ZkmDGDmA3QBSm/h/p5SiMkWU5Jg34toDdM0rmzUStIOMq6Gh/Ykx3fRRSjswy48x\n" + "wfZLy+0wU7lasHqdfk54dVbb7mCm9J3iHZizvOt2lbtzGbP6vrrjpzvZm43ZRgP8\n" + "FapYA8G3lczdIaG4IaLW6kYIRORd0UwI7IAwkao3uIo12rh1T6DLVyzjOs9PdIkb\n" + "HbICN2EehB/ut3wohuPwmwp2UmqopIMVVaBSsmSlYwIDAQABo4HcMIHZMAwGA1Ud\n" + "EwEB/wQCMAAwHQYDVR0OBBYEFAXGFMKYgtpzCpfpBUPQ1H/9AeDrMIGZBgNVHSME\n" + "gZEwgY6AFAXGFMKYgtpzCpfpBUPQ1H/9AeDroWCkXjBcMQswCQYDVQQGEwJVUzEU\n" + "MBIGA1UECgwLU29uYXJTb3VyY2UxFTATBgNVBAsMDE9uZUxvZ2luIElkUDEgMB4G\n" + "A1UEAwwXT25lTG9naW4gQWNjb3VudCAxMzExOTGCFB1Mz48uRNk5p7Jk0U9rCFAU\n" + "VxRfMA4GA1UdDwEB/wQEAwIHgDANBgkqhkiG9w0BAQUFAAOCAQEAPHgi9IdDaTxD\n" + "R5R8KHMdt385Uq8XC5pd0Li6y5RR2k6SKjThCt+eQU7D0Y2CyYU27vfCa2DQV4hJ\n" + "4v4UfQv3NR/fYfkVSsNpxjBXBI3YWouxt2yg7uwdZBdgGYd37Yv3g9PdIZenjOhr\n" + "Ck6WjdleMAWHRgJpocmB4IOESSyTfUul3jFupWnkbnn8c0ue6zwXd7LA1/yjVT2l\n" + "Yh45+lz25aIOlyyo7OUw2TD15LIl8OOIuWRS4+UWy5+VdhXMbmpSEQH+Byod90g6\n" + "A1bKpOFhRBzcxaZ6B2hB4SqjTBzS9zdmJyyFs/WNJxHri3aorcdqG9oUakjJJqqX\n" + "E13skIMV2g==\n" + "-----END CERTIFICATE-----\n"); DumbCallbackContext callbackContext = new DumbCallbackContext(request, response, "encoded_full_response.txt", SQ_CALLBACK_URL); assertThatThrownBy(() -> underTest.callback(callbackContext)) .isInstanceOf(UnauthorizedException.class) .hasMessage("Signature validation failed. SAML Response rejected"); } @Test public void fail_callback_when_message_was_already_sent() { setSettings(true); DumbCallbackContext callbackContext = new DumbCallbackContext(request, response, "encoded_minimal_response.txt", SQ_CALLBACK_URL); underTest.callback(callbackContext); assertThatThrownBy(() -> underTest.callback(callbackContext)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("This message has already been processed"); } private void setSettings(boolean enabled) { if (enabled) { settings.setProperty("sonar.auth.saml.applicationId", "MyApp"); settings.setProperty("sonar.auth.saml.providerId", "http://localhost:8080/auth/realms/sonarqube"); settings.setProperty("sonar.auth.saml.loginUrl", "http://localhost:8080/auth/realms/sonarqube/protocol/saml"); settings.setProperty("sonar.auth.saml.certificate.secured", IDP_CERTIFICATE); settings.setProperty("sonar.auth.saml.sp.privateKey.secured", SP_PRIVATE_KEY); settings.setProperty("sonar.auth.saml.sp.certificate.secured", SP_CERTIFICATE); settings.setProperty("sonar.auth.saml.user.login", "login"); settings.setProperty("sonar.auth.saml.user.name", "name"); settings.setProperty("sonar.auth.saml.user.email", "email"); settings.setProperty("sonar.auth.saml.group.name", "groups"); settings.setProperty("sonar.auth.saml.enabled", true); } else { settings.setProperty("sonar.auth.saml.enabled", false); } } private static class DumbInitContext implements OAuth2IdentityProvider.InitContext { private final HttpServletResponse response = mock(HttpServletResponse.class); private final AtomicBoolean generateCsrfState = new AtomicBoolean(false); @Override public String generateCsrfState() { generateCsrfState.set(true); return null; } @Override public void redirectTo(String url) { } @Override public String getCallbackUrl() { return SQ_CALLBACK_URL; } @Override public HttpRequest getHttpRequest() { return new JavaxHttpRequest(mock(HttpServletRequest.class)); } @Override public HttpResponse getHttpResponse() { return new JavaxHttpResponse(response); } @Override public HttpServletRequest getRequest() { throw new UnsupportedOperationException("deprecated"); } @Override public HttpServletResponse getResponse() { throw new UnsupportedOperationException("deprecated"); } } private static class DumbCallbackContext implements OAuth2IdentityProvider.CallbackContext { private final HttpServletResponse response; private final HttpServletRequest request; private final String expectedCallbackUrl; private final AtomicBoolean redirectedToRequestedPage = new AtomicBoolean(false); private final AtomicBoolean verifyState = new AtomicBoolean(false); private UserIdentity userIdentity = null; public DumbCallbackContext(HttpServletRequest request, HttpServletResponse response, String encodedResponseFile, String expectedCallbackUrl) { this.request = request; this.response = response; this.expectedCallbackUrl = expectedCallbackUrl; Map<String, String[]> parameterMap = new HashMap<>(); parameterMap.put("SAMLResponse", new String[]{loadResponse(encodedResponseFile)}); when(((JavaxHttpRequest) getHttpRequest()).getDelegate().getParameterMap()).thenReturn(parameterMap); } private String loadResponse(String file) { try (InputStream json = getClass().getResourceAsStream(SamlIdentityProviderIT.class.getSimpleName() + "/" + file)) { return IOUtils.toString(json, StandardCharsets.UTF_8); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void verifyCsrfState() { throw new IllegalStateException("This method should not be called !"); } @Override public void verifyCsrfState(String parameterName) { assertThat(parameterName).isEqualTo("RelayState"); verifyState.set(true); } @Override public void redirectToRequestedPage() { redirectedToRequestedPage.set(true); } @Override public void authenticate(UserIdentity userIdentity) { this.userIdentity = userIdentity; } @Override public String getCallbackUrl() { return this.expectedCallbackUrl; } @Override public HttpRequest getHttpRequest() { return new JavaxHttpRequest(request); } @Override public HttpResponse getHttpResponse() { return new JavaxHttpResponse(response); } @Override public HttpServletRequest getRequest() { return null; } @Override public HttpServletResponse getResponse() { return null; } } }
28,414
59.715812
3,216
java
sonarqube
sonarqube-master/server/sonar-auth-saml/src/it/java/org/sonar/auth/saml/SamlMessageIdCheckerIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.saml; import com.google.common.collect.ImmutableList; import com.onelogin.saml2.Auth; import java.util.Arrays; import org.joda.time.Instant; import org.junit.Rule; import org.junit.Test; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.user.SamlMessageIdDto; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class SamlMessageIdCheckerIT { @Rule public DbTester db = DbTester.create(); private DbSession dbSession = db.getSession(); private Auth auth = mock(Auth.class); private SamlMessageIdChecker underTest = new SamlMessageIdChecker(db.getDbClient()); @Test public void check_do_not_fail_when_message_id_is_new_and_insert_saml_message_in_db() { db.getDbClient().samlMessageIdDao().insert(dbSession, new SamlMessageIdDto().setMessageId("MESSAGE_1").setExpirationDate(1_000_000_000L)); db.commit(); when(auth.getLastMessageId()).thenReturn("MESSAGE_2"); when(auth.getLastAssertionNotOnOrAfter()).thenReturn(ImmutableList.of(Instant.ofEpochMilli(10_000_000_000L))); assertThatCode(() -> underTest.check(auth)).doesNotThrowAnyException(); SamlMessageIdDto result = db.getDbClient().samlMessageIdDao().selectByMessageId(dbSession, "MESSAGE_2").get(); assertThat(result.getMessageId()).isEqualTo("MESSAGE_2"); assertThat(result.getExpirationDate()).isEqualTo(10_000_000_000L); } @Test public void check_fails_when_message_id_already_exist() { db.getDbClient().samlMessageIdDao().insert(dbSession, new SamlMessageIdDto().setMessageId("MESSAGE_1").setExpirationDate(1_000_000_000L)); db.commit(); when(auth.getLastMessageId()).thenReturn("MESSAGE_1"); when(auth.getLastAssertionNotOnOrAfter()).thenReturn(ImmutableList.of(Instant.ofEpochMilli(10_000_000_000L))); assertThatThrownBy(() -> underTest.check(auth)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("This message has already been processed"); } @Test public void check_insert_message_id_using_oldest_NotOnOrAfter_value() { db.getDbClient().samlMessageIdDao().insert(dbSession, new SamlMessageIdDto().setMessageId("MESSAGE_1").setExpirationDate(1_000_000_000L)); db.commit(); when(auth.getLastMessageId()).thenReturn("MESSAGE_2"); when(auth.getLastAssertionNotOnOrAfter()) .thenReturn(Arrays.asList(Instant.ofEpochMilli(10_000_000_000L), Instant.ofEpochMilli(30_000_000_000L), Instant.ofEpochMilli(20_000_000_000L))); assertThatCode(() -> underTest.check(auth)).doesNotThrowAnyException(); SamlMessageIdDto result = db.getDbClient().samlMessageIdDao().selectByMessageId(dbSession, "MESSAGE_2").get(); assertThat(result.getMessageId()).isEqualTo("MESSAGE_2"); assertThat(result.getExpirationDate()).isEqualTo(10_000_000_000L); } }
3,871
42.022222
150
java
sonarqube
sonarqube-master/server/sonar-auth-saml/src/main/java/org/sonar/auth/saml/SamlAuthStatusPageGenerator.java
/* * SonarQube * Copyright (C) 2009-2023 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.saml; import com.google.common.io.Resources; import java.io.IOException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Map; import org.json.JSONObject; import org.sonar.api.server.http.HttpRequest; public final class SamlAuthStatusPageGenerator { private static final String WEB_CONTEXT = "%WEB_CONTEXT%"; private static final String SAML_AUTHENTICATION_STATUS = "%SAML_AUTHENTICATION_STATUS%"; private static final String HTML_TEMPLATE_NAME = "samlAuthResult.html"; private SamlAuthStatusPageGenerator() { throw new IllegalStateException("This Utility class cannot be instantiated"); } public static String getSamlAuthStatusHtml(HttpRequest request, SamlAuthenticationStatus samlAuthenticationStatus) { Map<String, String> substitutionsMap = getSubstitutionsMap(request, samlAuthenticationStatus); String htmlTemplate = getPlainTemplate(); return substitutionsMap .keySet() .stream() .reduce(htmlTemplate, (accumulator, pattern) -> accumulator.replace(pattern, substitutionsMap.get(pattern))); } private static Map<String, String> getSubstitutionsMap(HttpRequest request, SamlAuthenticationStatus samlAuthenticationStatus) { return Map.of( WEB_CONTEXT, request.getContextPath(), SAML_AUTHENTICATION_STATUS, getBase64EncodedStatus(samlAuthenticationStatus)); } private static String getBase64EncodedStatus(SamlAuthenticationStatus samlAuthenticationStatus) { byte[] bytes = new JSONObject(samlAuthenticationStatus).toString().getBytes(StandardCharsets.UTF_8); return String.format("%s", Base64.getEncoder().encodeToString(bytes)); } private static String getPlainTemplate() { URL url = Resources.getResource(HTML_TEMPLATE_NAME); try { return Resources.toString(url, StandardCharsets.UTF_8); } catch (IOException e) { throw new IllegalStateException("Cannot read the template " + HTML_TEMPLATE_NAME); } } }
2,853
38.638889
130
java
sonarqube
sonarqube-master/server/sonar-auth-saml/src/main/java/org/sonar/auth/saml/SamlAuthenticationStatus.java
/* * SonarQube * Copyright (C) 2009-2023 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.saml; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; public class SamlAuthenticationStatus { private String status = ""; private Map<String, List<String>> availableAttributes = new HashMap<>(); private Map<String, Collection<String>> mappedAttributes = new HashMap<>(); private List<String> errors = new ArrayList<>(); private List<String> warnings = new ArrayList<>(); public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Map<String, List<String>> getAvailableAttributes() { return availableAttributes; } public void setAvailableAttributes(Map<String, List<String>> availableAttributes) { this.availableAttributes = availableAttributes; } public Map<String, Collection<String>> getMappedAttributes() { return mappedAttributes; } public void setMappedAttributes(Map<String, Collection<String>> mappedAttributes) { this.mappedAttributes = mappedAttributes; } public List<String> getErrors() { return errors; } public void setErrors(List<String> errors) { this.errors = errors; } public List<String> getWarnings() { return warnings; } public void setWarnings(List<String> warnings) { this.warnings = warnings; } }
2,228
26.8625
85
java
sonarqube
sonarqube-master/server/sonar-auth-saml/src/main/java/org/sonar/auth/saml/SamlAuthenticator.java
/* * SonarQube * Copyright (C) 2009-2023 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.saml; import com.onelogin.saml2.Auth; import com.onelogin.saml2.exception.SettingsException; import com.onelogin.saml2.settings.Saml2Settings; import com.onelogin.saml2.settings.SettingsBuilder; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; 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 org.sonar.api.server.http.HttpResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.server.http.JavaxHttpRequest; import org.sonar.server.http.JavaxHttpResponse; import static java.util.Collections.emptySet; import static java.util.Objects.requireNonNull; import static org.sonar.auth.saml.SamlAuthStatusPageGenerator.getSamlAuthStatusHtml; import static org.sonar.auth.saml.SamlIdentityProvider.RSA_SHA_256_URL; import static org.sonar.auth.saml.SamlStatusChecker.getSamlAuthenticationStatus; public class SamlAuthenticator { private static final Logger LOGGER = LoggerFactory.getLogger(SamlAuthenticator.class); private static final String ANY_URL = "http://anyurl"; private static final String STATE_REQUEST_PARAMETER = "RelayState"; private final SamlSettings samlSettings; private final SamlMessageIdChecker samlMessageIdChecker; public SamlAuthenticator(SamlSettings samlSettings, SamlMessageIdChecker samlMessageIdChecker) { this.samlSettings = samlSettings; this.samlMessageIdChecker = samlMessageIdChecker; } public UserIdentity buildUserIdentity(OAuth2IdentityProvider.CallbackContext context, HttpRequest processedRequest) { Auth auth = this.initSamlAuth(processedRequest, context.getHttpResponse()); processResponse(auth); context.verifyCsrfState(STATE_REQUEST_PARAMETER); LOGGER.trace("Name ID : {}", getNameId(auth)); checkAuthentication(auth); this.checkMessageId(auth); LOGGER.trace("Attributes received : {}", getAttributes(auth)); String login = this.getLogin(auth); UserIdentity.Builder userIdentityBuilder = UserIdentity.builder() .setProviderLogin(login) .setName(this.getName(auth)); this.getEmail(auth).ifPresent(userIdentityBuilder::setEmail); this.getGroups(auth).ifPresent(userIdentityBuilder::setGroups); return userIdentityBuilder.build(); } public void initLogin(String callbackUrl, String relayState, HttpRequest request, HttpResponse response) { Auth auth = this.initSamlAuth(callbackUrl, request, response); login(auth, relayState); } private Auth initSamlAuth(HttpRequest request, HttpResponse response) { return initSamlAuth(null, request, response); } private Auth initSamlAuth(@Nullable String callbackUrl, HttpRequest request, HttpResponse response) { try { //no way around this as onelogin requires javax request/response HttpServletRequest httpServletRequest = ((JavaxHttpRequest) request).getDelegate(); HttpServletResponse httpServletResponse = ((JavaxHttpResponse) response).getDelegate(); return new Auth(initSettings(callbackUrl), httpServletRequest, httpServletResponse); } catch (SettingsException e) { throw new IllegalStateException("Failed to create a SAML Auth", e); } } private Saml2Settings initSettings(@Nullable String callbackUrl) { Map<String, Object> samlData = new HashMap<>(); samlData.put("onelogin.saml2.strict", true); samlData.put("onelogin.saml2.idp.entityid", samlSettings.getProviderId()); samlData.put("onelogin.saml2.idp.single_sign_on_service.url", samlSettings.getLoginUrl()); samlData.put("onelogin.saml2.idp.x509cert", samlSettings.getCertificate()); // Service Provider configuration samlData.put("onelogin.saml2.sp.entityid", samlSettings.getApplicationId()); if (samlSettings.isSignRequestsEnabled()) { samlData.put("onelogin.saml2.security.authnrequest_signed", true); samlData.put("onelogin.saml2.security.logoutrequest_signed", true); samlData.put("onelogin.saml2.security.logoutresponse_signed", true); samlData.put("onelogin.saml2.sp.x509cert", samlSettings.getServiceProviderCertificate()); samlData.put("onelogin.saml2.sp.privatekey", samlSettings.getServiceProviderPrivateKey().orElseThrow(() -> new IllegalArgumentException("Service provider private key is missing"))); } else { samlSettings.getServiceProviderPrivateKey().ifPresent(privateKey -> samlData.put("onelogin.saml2.sp.privatekey", privateKey)); } samlData.put("onelogin.saml2.security.signature_algorithm", RSA_SHA_256_URL); // During callback, the callback URL is by definition not needed, but the Saml2Settings does never allow this setting to be empty... samlData.put("onelogin.saml2.sp.assertion_consumer_service.url", callbackUrl != null ? callbackUrl : ANY_URL); var saml2Settings = new SettingsBuilder().fromValues(samlData).build(); if (samlSettings.getServiceProviderPrivateKey().isPresent() && saml2Settings.getSPkey() == null) { LOGGER.error("Error in parsing service provider private key, please make sure that it is in PKCS 8 format."); } return saml2Settings; } private static void login(Auth auth, String relayState) { try { auth.login(relayState); } catch (IOException | SettingsException e) { throw new IllegalStateException("Failed to initialize SAML authentication plugin", e); } } private static void processResponse(Auth auth) { try { auth.processResponse(); } catch (Exception e) { throw new IllegalStateException("Failed to process the authentication response", e); } } private static void checkAuthentication(Auth auth) { List<String> errors = auth.getErrors(); if (auth.isAuthenticated() && errors.isEmpty()) { return; } String errorReason = auth.getLastErrorReason(); throw new UnauthorizedException(errorReason != null && !errorReason.isEmpty() ? errorReason : "Unknown error reason"); } private String getLogin(Auth auth) { return getNonNullFirstAttribute(auth, samlSettings.getUserLogin()); } private String getName(Auth auth) { return getNonNullFirstAttribute(auth, samlSettings.getUserName()); } private Optional<String> getEmail(Auth auth) { return samlSettings.getUserEmail().map(userEmailField -> getFirstAttribute(auth, userEmailField)); } private Optional<Set<String>> getGroups(Auth auth) { return samlSettings.getGroupName().map(groupsField -> getGroups(auth, groupsField)); } private static String getNonNullFirstAttribute(Auth auth, String key) { String attribute = getFirstAttribute(auth, key); requireNonNull(attribute, String.format("%s is missing", key)); return attribute; } @CheckForNull private static String getFirstAttribute(Auth auth, String key) { Collection<String> attribute = auth.getAttribute(key); if (attribute == null || attribute.isEmpty()) { return null; } return attribute.iterator().next(); } private static Set<String> getGroups(Auth auth, String groupAttribute) { Collection<String> attribute = auth.getAttribute(groupAttribute); if (attribute == null || attribute.isEmpty()) { return emptySet(); } return new HashSet<>(attribute); } private static String getNameId(Auth auth) { return auth.getNameId(); } private static Map<String, List<String>> getAttributes(Auth auth) { return auth.getAttributes(); } private void checkMessageId(Auth auth) { samlMessageIdChecker.check(auth); } public String getAuthenticationStatusPage(HttpRequest request, HttpResponse response) { try { Auth auth = initSamlAuth(request, response); return getSamlAuthStatusHtml(request, getSamlAuthenticationStatus(auth, samlSettings)); } catch (IllegalStateException e) { return getSamlAuthStatusHtml(request, getSamlAuthenticationStatus(String.format("%s due to: %s", e.getMessage(), e.getCause().getMessage()))); } } }
9,260
39.618421
148
java
sonarqube
sonarqube-master/server/sonar-auth-saml/src/main/java/org/sonar/auth/saml/SamlIdentityProvider.java
/* * SonarQube * Copyright (C) 2009-2023 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.saml; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import org.sonar.api.server.ServerSide; import org.sonar.api.server.authentication.Display; import org.sonar.api.server.authentication.OAuth2IdentityProvider; import org.sonar.api.server.authentication.UserIdentity; import org.sonar.api.server.http.HttpRequest; import org.sonar.server.http.JavaxHttpRequest; @ServerSide public class SamlIdentityProvider implements OAuth2IdentityProvider { private static final Pattern HTTPS_PATTERN = Pattern.compile("https?://"); public static final String KEY = "saml"; public static final String RSA_SHA_256_URL = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; private final SamlSettings samlSettings; private final SamlMessageIdChecker samlMessageIdChecker; public SamlIdentityProvider(SamlSettings samlSettings, SamlMessageIdChecker samlMessageIdChecker) { this.samlSettings = samlSettings; this.samlMessageIdChecker = samlMessageIdChecker; } @Override public String getKey() { return KEY; } @Override public String getName() { return samlSettings.getProviderName(); } @Override public Display getDisplay() { return Display.builder() .setIconPath("/images/saml.png") .setBackgroundColor("#444444") .build(); } @Override public boolean isEnabled() { return samlSettings.isEnabled(); } @Override public boolean allowsUsersToSignUp() { return true; } @Override public void init(InitContext context) { SamlAuthenticator samlAuthenticator = new SamlAuthenticator(samlSettings, samlMessageIdChecker); samlAuthenticator.initLogin(context.getCallbackUrl(), context.generateCsrfState(), context.getHttpRequest(), context.getHttpResponse()); } @Override public void callback(CallbackContext context) { // // Workaround for onelogin/java-saml validation not taking into account running a reverse proxy configuration. This change // makes the validation take into account 'X-Forwarded-Proto' and 'Host' headers set by the reverse proxy // More details here: // - https://github.com/onelogin/java-saml/issues/198 // - https://github.com/onelogin/java-saml/issues/95 // HttpRequest processedRequest = useProxyHeadersInRequest(context.getHttpRequest()); SamlAuthenticator samlAuthenticator = new SamlAuthenticator(samlSettings, samlMessageIdChecker); UserIdentity userIdentity = samlAuthenticator.buildUserIdentity(context, processedRequest); context.authenticate(userIdentity); context.redirectToRequestedPage(); } private static HttpRequest useProxyHeadersInRequest(HttpRequest request) { String forwardedScheme = request.getHeader("X-Forwarded-Proto"); if (forwardedScheme != null) { HttpServletRequest httpServletRequest = new HttpServletRequestWrapper(((JavaxHttpRequest) request).getDelegate()) { @Override public String getScheme() { return forwardedScheme; } @Override public StringBuffer getRequestURL() { StringBuffer originalURL = ((HttpServletRequest) getRequest()).getRequestURL(); return new StringBuffer(HTTPS_PATTERN.matcher(originalURL.toString()).replaceFirst(forwardedScheme + "://")); } }; return new JavaxHttpRequest(httpServletRequest); } return request; } }
4,313
34.360656
126
java
sonarqube
sonarqube-master/server/sonar-auth-saml/src/main/java/org/sonar/auth/saml/SamlMessageIdChecker.java
/* * SonarQube * Copyright (C) 2009-2023 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.saml; import com.onelogin.saml2.Auth; import org.joda.time.Instant; import org.sonar.api.server.ServerSide; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.SamlMessageIdDto; import static java.util.Objects.requireNonNull; @ServerSide public class SamlMessageIdChecker { private final DbClient dbClient; public SamlMessageIdChecker(DbClient dbClient) { this.dbClient = dbClient; } public void check(Auth auth) { String messageId = requireNonNull(auth.getLastMessageId(), "Message ID is missing"); Instant lastAssertionNotOnOrAfter = auth.getLastAssertionNotOnOrAfter().stream() .sorted() .findFirst() .orElseThrow(() -> new IllegalArgumentException("Missing NotOnOrAfter element")); try (DbSession dbSession = dbClient.openSession(false)) { dbClient.samlMessageIdDao().selectByMessageId(dbSession, messageId) .ifPresent(m -> { throw new IllegalArgumentException("This message has already been processed"); }); dbClient.samlMessageIdDao().insert(dbSession, new SamlMessageIdDto() .setMessageId(messageId) .setExpirationDate(lastAssertionNotOnOrAfter.getMillis())); dbSession.commit(); } } }
2,108
34.745763
88
java
sonarqube
sonarqube-master/server/sonar-auth-saml/src/main/java/org/sonar/auth/saml/SamlModule.java
/* * SonarQube * Copyright (C) 2009-2023 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.saml; import java.util.List; import org.sonar.api.config.PropertyDefinition; import org.sonar.core.platform.Module; public class SamlModule extends Module { @Override protected void configureModule() { add( SamlIdentityProvider.class, SamlMessageIdChecker.class, SamlSettings.class, SamlAuthenticator.class); List<PropertyDefinition> definitions = SamlSettings.definitions(); add(definitions.toArray(new Object[definitions.size()])); } }
1,350
32.775
75
java
sonarqube
sonarqube-master/server/sonar-auth-saml/src/main/java/org/sonar/auth/saml/SamlSettings.java
/* * SonarQube * Copyright (C) 2009-2023 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.saml; import java.util.Arrays; import java.util.List; import java.util.Optional; import org.sonar.api.config.Configuration; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.server.ServerSide; import static java.lang.String.valueOf; import static org.sonar.api.PropertyType.BOOLEAN; import static org.sonar.api.PropertyType.PASSWORD; @ServerSide public class SamlSettings { public static final String ENABLED = "sonar.auth.saml.enabled"; public static final String PROVIDER_ID = "sonar.auth.saml.providerId"; public static final String PROVIDER_NAME = "sonar.auth.saml.providerName"; public static final String APPLICATION_ID = "sonar.auth.saml.applicationId"; public static final String LOGIN_URL = "sonar.auth.saml.loginUrl"; public static final String CERTIFICATE = "sonar.auth.saml.certificate.secured"; public static final String USER_LOGIN_ATTRIBUTE = "sonar.auth.saml.user.login"; public static final String USER_NAME_ATTRIBUTE = "sonar.auth.saml.user.name"; public static final String USER_EMAIL_ATTRIBUTE = "sonar.auth.saml.user.email"; public static final String GROUP_NAME_ATTRIBUTE = "sonar.auth.saml.group.name"; public static final String SIGN_REQUESTS_ENABLED = "sonar.auth.saml.signature.enabled"; public static final String SERVICE_PROVIDER_CERTIFICATE = "sonar.auth.saml.sp.certificate.secured"; public static final String SERVICE_PROVIDER_PRIVATE_KEY = "sonar.auth.saml.sp.privateKey.secured"; public static final String CATEGORY = "authentication"; public static final String SUBCATEGORY = "saml"; private final Configuration configuration; public SamlSettings(Configuration configuration) { this.configuration = configuration; } String getProviderId() { return configuration.get(PROVIDER_ID).orElseThrow(() -> new IllegalArgumentException("Provider ID is missing")); } String getProviderName() { return configuration.get(PROVIDER_NAME).orElseThrow(() -> new IllegalArgumentException("Provider Name is missing")); } String getApplicationId() { return configuration.get(APPLICATION_ID).orElseThrow(() -> new IllegalArgumentException("Application ID is missing")); } String getLoginUrl() { return configuration.get(LOGIN_URL).orElseThrow(() -> new IllegalArgumentException("Login URL is missing")); } String getCertificate() { return configuration.get(CERTIFICATE).orElseThrow(() -> new IllegalArgumentException("Identity provider certificate is missing")); } String getUserLogin() { return configuration.get(USER_LOGIN_ATTRIBUTE).orElseThrow(() -> new IllegalArgumentException("User login attribute is missing")); } String getUserName() { return configuration.get(USER_NAME_ATTRIBUTE).orElseThrow(() -> new IllegalArgumentException("User name attribute is missing")); } boolean isSignRequestsEnabled() { return configuration.getBoolean(SIGN_REQUESTS_ENABLED).orElse(false); } Optional<String> getServiceProviderPrivateKey() { return configuration.get(SERVICE_PROVIDER_PRIVATE_KEY); } String getServiceProviderCertificate() { return configuration.get(SERVICE_PROVIDER_CERTIFICATE).orElseThrow(() -> new IllegalArgumentException("Service provider certificate is missing")); } Optional<String> getUserEmail() { return configuration.get(USER_EMAIL_ATTRIBUTE); } Optional<String> getGroupName() { return configuration.get(GROUP_NAME_ATTRIBUTE); } public boolean isEnabled() { return configuration.getBoolean(ENABLED).orElse(false) && configuration.get(PROVIDER_ID).isPresent() && configuration.get(APPLICATION_ID).isPresent() && configuration.get(LOGIN_URL).isPresent() && configuration.get(CERTIFICATE).isPresent() && configuration.get(USER_LOGIN_ATTRIBUTE).isPresent() && configuration.get(USER_NAME_ATTRIBUTE).isPresent(); } public static List<PropertyDefinition> definitions() { return Arrays.asList( PropertyDefinition.builder(ENABLED) .name("Enabled") .description("Enable SAML users to login. Value is ignored if provider ID, login url, certificate, login, name attributes are not defined.") .category(CATEGORY) .subCategory(SUBCATEGORY) .type(BOOLEAN) .defaultValue(valueOf(false)) .index(1) .build(), PropertyDefinition.builder(APPLICATION_ID) .name("Application ID") .description("The identifier used on the Identity Provider for registering SonarQube.") .defaultValue("sonarqube") .category(CATEGORY) .subCategory(SUBCATEGORY) .index(2) .build(), PropertyDefinition.builder(PROVIDER_NAME) .name("Provider Name") .description("Name of the Identity Provider displayed in the login page when SAML authentication is active.") .defaultValue("SAML") .category(CATEGORY) .subCategory(SUBCATEGORY) .index(3) .build(), PropertyDefinition.builder(PROVIDER_ID) .name("Provider ID") .description("Identifier of the Identity Provider, the entity that provides SAML authentication.") .category(CATEGORY) .subCategory(SUBCATEGORY) .index(4) .build(), PropertyDefinition.builder(LOGIN_URL) .name("SAML login url") .description("The URL where the Identity Provider expects to receive SAML requests.") .category(CATEGORY) .subCategory(SUBCATEGORY) .index(5) .build(), PropertyDefinition.builder(CERTIFICATE) .name("Identity provider certificate") .description("The public X.509 certificate used by the Identity Provider to authenticate SAML messages.") .category(CATEGORY) .subCategory(SUBCATEGORY) .type(PASSWORD) .index(6) .build(), PropertyDefinition.builder(USER_LOGIN_ATTRIBUTE) .name("SAML user login attribute") .description("The name of the attribute where the SAML Identity Provider will put the login of the authenticated user.") .category(CATEGORY) .subCategory(SUBCATEGORY) .index(7) .build(), PropertyDefinition.builder(USER_NAME_ATTRIBUTE) .name("SAML user name attribute") .description("The name of the attribute where the SAML Identity Provider will put the name of the authenticated user.") .category(CATEGORY) .subCategory(SUBCATEGORY) .index(8) .build(), PropertyDefinition.builder(USER_EMAIL_ATTRIBUTE) .name("SAML user email attribute") .description("The name of the attribute where the SAML Identity Provider will put the email of the authenticated user.") .category(CATEGORY) .subCategory(SUBCATEGORY) .index(9) .build(), PropertyDefinition.builder(GROUP_NAME_ATTRIBUTE) .name("SAML group attribute") .description("Attribute defining the user groups in SAML, used to synchronize group memberships. If you leave this field empty, " + "group memberships are managed locally by SonarQube administrators.") .category(CATEGORY) .subCategory(SUBCATEGORY) .index(10) .build(), PropertyDefinition.builder(SIGN_REQUESTS_ENABLED) .name("Sign requests") .description("Enables signature of SAML requests. It requires both service provider private key and certificate to be set.") .category(CATEGORY) .subCategory(SUBCATEGORY) .type(BOOLEAN) .defaultValue(valueOf(false)) .index(11) .build(), PropertyDefinition.builder(SERVICE_PROVIDER_PRIVATE_KEY) .name("Service provider private key") .description("PKCS8 stored private key used for signing the requests and decrypting responses from the identity provider. ") .category(CATEGORY) .subCategory(SUBCATEGORY) .type(PASSWORD) .index(12) .build(), PropertyDefinition.builder(SERVICE_PROVIDER_CERTIFICATE) .name("Service provider certificate") .description("X.509 certificate for the service provider, used for signing the requests.") .category(CATEGORY) .subCategory(SUBCATEGORY) .type(PASSWORD) .index(13) .build()); } }
9,167
39.928571
150
java
sonarqube
sonarqube-master/server/sonar-auth-saml/src/main/java/org/sonar/auth/saml/SamlStatusChecker.java
/* * SonarQube * Copyright (C) 2009-2023 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.saml; import com.onelogin.saml2.Auth; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import static org.sonar.auth.saml.SamlSettings.GROUP_NAME_ATTRIBUTE; import static org.sonar.auth.saml.SamlSettings.USER_EMAIL_ATTRIBUTE; import static org.sonar.auth.saml.SamlSettings.USER_LOGIN_ATTRIBUTE; import static org.sonar.auth.saml.SamlSettings.USER_NAME_ATTRIBUTE; public final class SamlStatusChecker { private SamlStatusChecker() { throw new IllegalStateException("This Utility class cannot be instantiated"); } public static SamlAuthenticationStatus getSamlAuthenticationStatus(Auth auth, SamlSettings samlSettings) { SamlAuthenticationStatus samlAuthenticationStatus = new SamlAuthenticationStatus(); try { auth.processResponse(); } catch (Exception e) { samlAuthenticationStatus.getErrors().add(e.getMessage()); } samlAuthenticationStatus.getErrors().addAll(auth.getErrors().stream().filter(Objects::nonNull).toList()); if (auth.getLastErrorReason() != null) { samlAuthenticationStatus.getErrors().add(auth.getLastErrorReason()); } if (samlAuthenticationStatus.getErrors().isEmpty()) { samlAuthenticationStatus.getErrors().addAll(generateMappingErrors(auth, samlSettings)); } samlAuthenticationStatus.setAvailableAttributes(auth.getAttributes()); samlAuthenticationStatus.setMappedAttributes(getAttributesMapping(auth, samlSettings)); samlAuthenticationStatus.setWarnings(samlAuthenticationStatus.getErrors().isEmpty() ? generateWarnings(auth, samlSettings) : new ArrayList<>()); samlAuthenticationStatus.setStatus(samlAuthenticationStatus.getErrors().isEmpty() ? "success" : "error"); return samlAuthenticationStatus; } public static SamlAuthenticationStatus getSamlAuthenticationStatus(String errorMessage) { SamlAuthenticationStatus samlAuthenticationStatus = new SamlAuthenticationStatus(); samlAuthenticationStatus.getErrors().add(errorMessage); samlAuthenticationStatus.setStatus("error"); return samlAuthenticationStatus; } private static Map<String, Collection<String>> getAttributesMapping(Auth auth, SamlSettings samlSettings) { Map<String, Collection<String>> attributesMapping = new HashMap<>(); attributesMapping.put("User login value", auth.getAttribute(samlSettings.getUserLogin())); attributesMapping.put("User name value", auth.getAttribute(samlSettings.getUserName())); samlSettings.getUserEmail().ifPresent(emailFieldName -> attributesMapping.put("User email value", auth.getAttribute(emailFieldName))); samlSettings.getGroupName().ifPresent(groupFieldName -> attributesMapping.put("Groups value", auth.getAttribute(groupFieldName))); return attributesMapping; } private static List<String> generateWarnings(Auth auth, SamlSettings samlSettings) { List<String> warnings = new ArrayList<>(generateMappingWarnings(auth, samlSettings)); generatePrivateKeyWarning(auth, samlSettings).ifPresent(warnings::add); return warnings; } private static List<String> generateMappingWarnings(Auth auth, SamlSettings samlSettings) { Map<String, String> mappings = Map.of( USER_EMAIL_ATTRIBUTE, samlSettings.getUserEmail().orElse(""), GROUP_NAME_ATTRIBUTE, samlSettings.getGroupName().orElse("")); return generateMissingMappingMessages(mappings, auth); } private static Optional<String> generatePrivateKeyWarning(Auth auth, SamlSettings samlSettings) { if (samlSettings.getServiceProviderPrivateKey().isPresent() && auth.getSettings().getSPkey() == null) { return Optional.of("Error in parsing service provider private key, please make sure that it is in PKCS 8 format."); } return Optional.empty(); } private static List<String> generateMappingErrors(Auth auth, SamlSettings samlSettings) { Map<String, String> mappings = Map.of( USER_NAME_ATTRIBUTE, samlSettings.getUserName(), USER_LOGIN_ATTRIBUTE, samlSettings.getUserLogin()); List<String> mappingErrors = generateMissingMappingMessages(mappings, auth); if (mappingErrors.isEmpty()) { mappingErrors = generateEmptyMappingsMessages(mappings, auth); } return mappingErrors; } private static List<String> generateMissingMappingMessages(Map<String, String> mappings, Auth auth) { return mappings.entrySet() .stream() .filter(entry -> !entry.getValue().isEmpty() && (auth.getAttribute(entry.getValue()) == null || auth.getAttribute(entry.getValue()).isEmpty())) .map(entry -> String.format("Mapping not found for the property %s, the field %s is not available in the SAML response.", entry.getKey(), entry.getValue())) .toList(); } private static List<String> generateEmptyMappingsMessages(Map<String, String> mappings, Auth auth) { return mappings.entrySet() .stream() .filter(entry -> (auth.getAttribute(entry.getValue()).size() == 1 && auth.getAttribute(entry.getValue()).contains(""))) .map(entry -> String.format("Mapping found for the property %s, but the field %s is empty in the SAML response.", entry.getKey(), entry.getValue())) .toList(); } }
6,141
42.871429
162
java
sonarqube
sonarqube-master/server/sonar-auth-saml/src/main/java/org/sonar/auth/saml/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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. */ @ParametersAreNonnullByDefault package org.sonar.auth.saml; import javax.annotation.ParametersAreNonnullByDefault;
959
39
75
java
sonarqube
sonarqube-master/server/sonar-auth-saml/src/test/java/org/sonar/auth/saml/SamlAuthStatusPageGeneratorTest.java
/* * SonarQube * Copyright (C) 2009-2023 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.saml; import java.util.ArrayList; import java.util.HashMap; import org.junit.Test; import org.sonar.api.server.http.HttpRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.auth.saml.SamlAuthStatusPageGenerator.getSamlAuthStatusHtml; public class SamlAuthStatusPageGeneratorTest { private static final String EMPTY_DATA_RESPONSE = "eyJ3YXJuaW5ncyI6W10sImF2YWlsYWJsZUF0dHJpYnV0ZXMiOnt9LCJlcnJvcnMiOltdLCJtYXBwZWRBdHRyaWJ1dGVzIjp7fX0="; @Test public void getSamlAuthStatusHtml_whenCalled_shouldGeneratePageWithData() { SamlAuthenticationStatus samlAuthenticationStatus = mock(SamlAuthenticationStatus.class); HttpRequest request = mock(HttpRequest.class); when(samlAuthenticationStatus.getStatus()).thenReturn(null); when(samlAuthenticationStatus.getErrors()).thenReturn(new ArrayList<>()); when(samlAuthenticationStatus.getWarnings()).thenReturn(new ArrayList<>()); when(samlAuthenticationStatus.getAvailableAttributes()).thenReturn(new HashMap<>()); when(samlAuthenticationStatus.getMappedAttributes()).thenReturn(new HashMap<>()); when(request.getContextPath()).thenReturn("context"); String completeHtmlTemplate = getSamlAuthStatusHtml(request, samlAuthenticationStatus); assertThat(completeHtmlTemplate).contains(EMPTY_DATA_RESPONSE); } }
2,281
42.884615
155
java
sonarqube
sonarqube-master/server/sonar-auth-saml/src/test/java/org/sonar/auth/saml/SamlAuthenticatorTest.java
/* * SonarQube * Copyright (C) 2009-2023 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.saml; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Test; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.server.http.JavaxHttpRequest; import org.sonar.server.http.JavaxHttpResponse; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class SamlAuthenticatorTest { @Test public void authentication_status_with_errors_returned_when_init_fails() { SamlAuthenticator samlAuthenticator = new SamlAuthenticator(mock(SamlSettings.class), mock(SamlMessageIdChecker.class)); HttpRequest request = new JavaxHttpRequest(mock(HttpServletRequest.class)); HttpResponse response = new JavaxHttpResponse(mock(HttpServletResponse.class)); when(request.getContextPath()).thenReturn("context"); String authenticationStatus = samlAuthenticator.getAuthenticationStatusPage(request, response); assertFalse(authenticationStatus.isEmpty()); } }
1,930
39.229167
124
java
sonarqube
sonarqube-master/server/sonar-auth-saml/src/test/java/org/sonar/auth/saml/SamlModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 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.saml; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class SamlModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new SamlModule().configure(container); assertThat(container.getAddedObjects()).hasSize(17); } }
1,249
33.722222
75
java
sonarqube
sonarqube-master/server/sonar-auth-saml/src/test/java/org/sonar/auth/saml/SamlSettingsTest.java
/* * SonarQube * Copyright (C) 2009-2023 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.saml; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class SamlSettingsTest { private MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, SamlSettings.definitions())); private SamlSettings underTest = new SamlSettings(settings.asConfig()); @Test public void return_application_id() { settings.setProperty("sonar.auth.saml.applicationId", "MyApp"); assertThat(underTest.getApplicationId()).isEqualTo("MyApp"); } @Test public void return_default_value_of_application_id() { assertThat(underTest.getApplicationId()).isEqualTo("sonarqube"); } @Test public void return_provider_name() { settings.setProperty("sonar.auth.saml.providerName", "MyProviderName"); assertThat(underTest.getProviderName()).isEqualTo("MyProviderName"); } @Test public void return_default_value_of_application_name() { assertThat(underTest.getProviderName()).isEqualTo("SAML"); } @Test public void return_provider_id() { settings.setProperty("sonar.auth.saml.applicationId", "http://localhost:8080/auth/realms/sonarqube"); assertThat(underTest.getApplicationId()).isEqualTo("http://localhost:8080/auth/realms/sonarqube"); } @Test public void return_login_url() { settings.setProperty("sonar.auth.saml.loginUrl", "http://localhost:8080/"); assertThat(underTest.getLoginUrl()).isEqualTo("http://localhost:8080/"); settings.setProperty("sonar.auth.saml.loginUrl", "http://localhost:8080"); assertThat(underTest.getLoginUrl()).isEqualTo("http://localhost:8080"); } @Test public void return_certificate() { settings.setProperty("sonar.auth.saml.certificate.secured", "ABCDEFG"); assertThat(underTest.getCertificate()).isEqualTo("ABCDEFG"); } @Test public void is_sign_requests_enabled() { settings.setProperty("sonar.auth.saml.signature.enabled", true); assertThat(underTest.isSignRequestsEnabled()).isTrue(); settings.setProperty("sonar.auth.saml.signature.enabled", false); assertThat(underTest.isSignRequestsEnabled()).isFalse(); } @Test public void return_service_provider_certificate() { settings.setProperty("sonar.auth.saml.sp.certificate.secured", "my_certificate"); assertThat(underTest.getServiceProviderCertificate()).isEqualTo("my_certificate"); } @Test public void return_service_provider_private_key() { settings.setProperty("sonar.auth.saml.sp.privateKey.secured", "my_private_secret_private_key"); assertThat(underTest.getServiceProviderPrivateKey()).hasValue("my_private_secret_private_key"); } @Test public void return_user_login_attribute() { settings.setProperty("sonar.auth.saml.user.login", "userLogin"); assertThat(underTest.getUserLogin()).isEqualTo("userLogin"); } @Test public void return_user_name_attribute() { settings.setProperty("sonar.auth.saml.user.name", "userName"); assertThat(underTest.getUserName()).isEqualTo("userName"); } @Test public void return_user_email_attribute() { settings.setProperty("sonar.auth.saml.user.email", "userEmail"); assertThat(underTest.getUserEmail()).contains("userEmail"); } @Test public void return_empty_user_email_when_no_setting() { assertThat(underTest.getUserEmail()).isNotPresent(); } @Test public void return_group_name_attribute() { settings.setProperty("sonar.auth.saml.group.name", "groupName"); assertThat(underTest.getGroupName()).contains("groupName"); } @Test public void return_empty_group_name_when_no_setting() { assertThat(underTest.getGroupName()).isNotPresent(); } @Test public void is_enabled() { settings.setProperty("sonar.auth.saml.applicationId", "MyApp"); settings.setProperty("sonar.auth.saml.providerId", "http://localhost:8080/auth/realms/sonarqube"); settings.setProperty("sonar.auth.saml.loginUrl", "http://localhost:8080/auth/realms/sonarqube/protocol/saml"); settings.setProperty("sonar.auth.saml.certificate.secured", "ABCDEFG"); settings.setProperty("sonar.auth.saml.user.login", "login"); settings.setProperty("sonar.auth.saml.user.name", "name"); settings.setProperty("sonar.auth.saml.enabled", true); assertThat(underTest.isEnabled()).isTrue(); settings.setProperty("sonar.auth.saml.enabled", false); assertThat(underTest.isEnabled()).isFalse(); } @Test public void is_enabled_using_default_values() { settings.setProperty("sonar.auth.saml.providerId", "http://localhost:8080/auth/realms/sonarqube"); settings.setProperty("sonar.auth.saml.loginUrl", "http://localhost:8080/auth/realms/sonarqube/protocol/saml"); settings.setProperty("sonar.auth.saml.certificate.secured", "ABCDEFG"); settings.setProperty("sonar.auth.saml.user.login", "login"); settings.setProperty("sonar.auth.saml.user.name", "name"); settings.setProperty("sonar.auth.saml.enabled", true); assertThat(underTest.isEnabled()).isTrue(); } @DataProvider public static Object[][] settingsRequiredToEnablePlugin() { return new Object[][] { {"sonar.auth.saml.providerId"}, {"sonar.auth.saml.loginUrl"}, {"sonar.auth.saml.certificate.secured"}, {"sonar.auth.saml.user.login"}, {"sonar.auth.saml.user.name"}, {"sonar.auth.saml.enabled"}, }; } @Test @UseDataProvider("settingsRequiredToEnablePlugin") public void is_enabled_return_false_when_one_required_setting_is_missing(String setting) { initAllSettings(); settings.setProperty(setting, (String) null); assertThat(underTest.isEnabled()).isFalse(); } @Test public void fail_to_get_provider_id_when_null() { assertThatThrownBy(() -> underTest.getProviderId()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Provider ID is missing"); } @Test public void fail_to_get_login_url_when_null() { assertThatThrownBy(() -> underTest.getLoginUrl()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Login URL is missing"); } @Test public void fail_to_get_certificate_when_null() { assertThatThrownBy(() -> underTest.getCertificate()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Identity provider certificate is missing"); } @Test public void fail_to_get_user_login_attribute_when_null() { assertThatThrownBy(() -> underTest.getUserLogin()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("User login attribute is missing"); } @Test public void fail_to_get_user_name_attribute_when_null() { assertThatThrownBy(() -> underTest.getUserName()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("User name attribute is missing"); } private void initAllSettings() { settings.setProperty("sonar.auth.saml.applicationId", "MyApp"); settings.setProperty("sonar.auth.saml.providerId", "http://localhost:8080/auth/realms/sonarqube"); settings.setProperty("sonar.auth.saml.loginUrl", "http://localhost:8080/auth/realms/sonarqube/protocol/saml"); settings.setProperty("sonar.auth.saml.certificate.secured", "ABCDEFG"); settings.setProperty("sonar.auth.saml.user.login", "login"); settings.setProperty("sonar.auth.saml.user.name", "name"); settings.setProperty("sonar.auth.saml.enabled", true); } }
8,661
34.5
120
java
sonarqube
sonarqube-master/server/sonar-auth-saml/src/test/java/org/sonar/auth/saml/SamlStatusCheckerTest.java
/* * SonarQube * Copyright (C) 2009-2023 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.saml; import com.onelogin.saml2.Auth; import com.onelogin.saml2.settings.Saml2Settings; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.auth.saml.SamlSettings.GROUP_NAME_ATTRIBUTE; import static org.sonar.auth.saml.SamlSettings.USER_EMAIL_ATTRIBUTE; import static org.sonar.auth.saml.SamlSettings.USER_LOGIN_ATTRIBUTE; import static org.sonar.auth.saml.SamlSettings.USER_NAME_ATTRIBUTE; import static org.sonar.auth.saml.SamlStatusChecker.getSamlAuthenticationStatus; public class SamlStatusCheckerTest { private static final String IDP_CERTIFICATE = "-----BEGIN CERTIFICATE-----MIIF5zCCA8+gAwIBAgIUIXv9OVs/XUicgR1bsV9uccYhHfowDQYJKoZIhvcNAQELBQAwgYIxCzAJBgNVBAYTAkFVMQ8wDQYDVQQIDAZHRU5FVkExEDAOBgNVBAcMB1ZFUk5JRVIxDjAMBgNVBAoMBVNPTkFSMQ0wCwYDVQQLDARRVUJFMQ8wDQYDVQQDDAZaaXBlbmcxIDAeBgkqhkiG9w0BCQEWEW5vcmVwbHlAZ21haWwuY29tMB4XDTIyMDYxMzEzMTQyN1oXDTMyMDYxMDEzMTQyN1owgYIxCzAJBgNVBAYTAkFVMQ8wDQYDVQQIDAZHRU5FVkExEDAOBgNVBAcMB1ZFUk5JRVIxDjAMBgNVBAoMBVNPTkFSMQ0wCwYDVQQLDARRVUJFMQ8wDQYDVQQDDAZaaXBlbmcxIDAeBgkqhkiG9w0BCQEWEW5vcmVwbHlAZ21haWwuY29tMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAu3nFXYvIYedpR84aZkdo/3yB5XHM+YCFJcDsVO10zEblLknfQsiMPa1Xd9Ustnpxw6P/SyzIJmO9jiMOdeCeY98a74jP7d4JPaO6h3l9IbWAcYeijQg956nlsVFY3FHDGr+7Pb8QcOAyV3v89jiF9DFB8wXS+5UfYr2OfoRRb4li39ezDyDdl5OLlM11nEss2z1mEv+sUUloTcyrgj37Psgewkvyym6tFGSgkV9Za4SVRhHFyThY1VFrYZSJFTnapUYaRc7kMxzwX/AAHUDJrmYcaVc5B8ODp4w2AxDJheQyCVfXjPFaUqBMG2U/rYfVXu0Za7Pn/vUo4UaSThwCBKDehCwz+65TLdA+NxyGDxnvY/SksOyLLGCmu8tKkXdu0pznnIhBXEGvjUIVS7d6a/8geg91NoTWau3i0RF+Dw/5N9DSzpld15bPtb5Ce3Bie19uvfvuH9eg+D8x/hfF6f3il4sPlIKdO/OVdM28LRfmDqmqQNPudvbqz7xy4ARuxk6ARa4d+aT9zovpwvxNGTr7h1mdgOUtUCdIXL3SHNjdwdAAz0uCWzvExbFu+NQ+V5+Xnkx71hyPFv9+DLVGIu7JhdYs806wKshO13Nga38ig6gu37lpVhfpZXhKywUiigG6LXAeyWWkMk+vlf9McZdMBD16dZP4kTsvP+rPVnUCAwEAAaNTMFEwHQYDVR0OBBYEFI5UVLtTySvbGqH7UP8xTL4wxZq3MB8GA1UdIwQYMBaAFI5UVLtTySvbGqH7UP8xTL4wxZq3MA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggIBABAtXsKNWx0sDDFA53qZ1zRyWKWAMoh95pawFCrKgTEW4ZrA73pa790eE1Y+vT6qUXKI4li9skIDa+6psCdxhZIrHPRAnVZVeB2373Bxr5bw/XQ8elRCjWeMULbYJ9tgsLV0I9CiEP0a6Tm8t0yDVXNUfx36E5fkgLSrxoRo8XJzxHbJCnLVXHdaNBxOT7jVcom6Wo4PB2bsjVzhHm6amn5hZp4dMHm0Mv0ln1wH8jVnizHQBLsGMzvvl58+9s1pP17ceRDkpNDz+EQyA+ZArqkW1MqtwVhbzz8QgMprhflKkArrsC7v06Jv8fqUbn9LvtYK9IwHTX7J8dFcsO/gUC5PevYT3nriN3Azb20ggSQ1yOEMozvj5T96S6itfHPit7vyEQ84JPrEqfuQDZQ/LKZQqfvuXX1aAG3TU3TMWB9VMMFsTuMFS8bfrhMX77g0Ud4qJcBOYOH3hR59agSdd2QZNLP3zZsYQHLLQkq94jdTXKTqm/w7mlPFKV59HjTbHBhTtxBHMft/mvvLEuC9KKFfAOXYQ6V+s9Nk0BW4ggEfewaX58OBuy7ISqRtRFPGia18YRzzHqkhjubJYMPkIfYpFVd+C0II3F0kdy8TtpccjyKo9bcHMLxO4n8PDAl195CPthMi8gUvT008LGEotr+3kXsouTEZTT0glXKLdO2W-----END CERTIFICATE-----"; private static final String SP_CERTIFICATE = "MIICoTCCAYkCBgGBXPscaDANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDDAlzb25hcnF1YmUwHhcNMjIwNjEzMTIxMTA5WhcNMzIwNjEzMTIxMjQ5WjAUMRIwEAYDVQQDDAlzb25hcnF1YmUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDSFoT371C0/klZuPgvKbGItkmTaf5CweNXL8u389d98aOXRpDQ7maTXdV/W+VcL8vUWg8yG6nn8CRwweYnGTNdn9UAdhgknvxQe3pq3EwOJyls4Fpiq6YTh+DQfiZUQizjFjDOr/GG5O2lNvTRkI4XZj/XnWjRqVZwttiA5tm1sKkvGdyOQljwn4Jja/VbITdV8GASumx66Bil/wamSsqIzm2RjsOOGSsf5VjYUPwDobpuSf+j4DLtWjem/9vIzI2wcE30uC8LBAgO3JAlIS9NQrchjS9xhMJRohOoitaSPmqsOy7D2BH0h7XX6TNgv/WYTkBY4eZPao3PsL2A6AmhAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAMBmTHUK4w+DX21tmhqdwq0WqLH5ZAkwtiocDxFXiJ4GRrUWUh3BaXsgOHB8YYnNTDfScjaU0sZMEyfC0su1zsN8B7NFckg7RcZCHuBYdgIEAmvK4YM6s6zNsiKKwt66p2MNeL+o0acrT2rYjQ1L5QDj0gpfJQAT4N7xTZfuSc2iwjotaQfvcgsO8EZlcDVrL4UuyWLbuRUlSQjxHWGYaxCW+I3enK1+8fGpF3O+k9ZQ8xt5nJsalpsZvHcPLA4IBOmjsSHqSkhg4EIAWL/sJZ1KNct4hHh5kToUTu+Q6e949VeBkWgj4O+rcGDgiN2frGiEEc0EMv8KCSENRRRrO2k="; private static final String SP_PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDSFoT371C0/klZuPgvKbGItkmTaf5CweNXL8u389d98aOXRpDQ7maTXdV/W+VcL8vUWg8yG6nn8CRwweYnGTNdn9UAdhgknvxQe3pq3EwOJyls4Fpiq6YTh+DQfiZUQizjFjDOr/GG5O2lNvTRkI4XZj/XnWjRqVZwttiA5tm1sKkvGdyOQljwn4Jja/VbITdV8GASumx66Bil/wamSsqIzm2RjsOOGSsf5VjYUPwDobpuSf+j4DLtWjem/9vIzI2wcE30uC8LBAgO3JAlIS9NQrchjS9xhMJRohOoitaSPmqsOy7D2BH0h7XX6TNgv/WYTkBY4eZPao3PsL2A6AmhAgMBAAECggEBAJj11HJAR96/leBBkFGmZaBIOGGgNoOcb023evfADhGgsZ8evamhKgX5t8w2uFPaaOl/eLje82Hvslh2lH+7FW8BRDBFy2Y+ay6d+I99PdLAKKUg5C4bE5v8vm6OqpGGbPAZ5AdYit3QKEa2MKG0QgA/bhQqg3rDdDA0sIWJjtF9MLv7LI7Tm0qgiHOKsI0MEBFk+ZoibgKWYh/dnfGDRWyC3Puqe13rdSheNJYUDR/0QMkd/EJNpLWv06uk+w8w2lU4RgN6TiV76ZZUIGZAAHFgMELJysgtBTCkOQY5roPu17OmMZjKfxngeIfNyd42q3/T6DmUbbwNYfP2HRMoiMECgYEA6SVc1mZ4ykytC9M61rZwT+2zXtJKudQVa0qpTtkf0aznRmnDOuc1bL7ewKIIIp9r5HKVteO6SKgpHmrP+qmvbwZ0Pz51Zg0MetoSmT9m0599/tOU2k6OI09dvQ4Xa3ccN5Czl61Q/HkMeAIDny8MrhGVBwhallE4J4fm/OjuVK0CgYEA5q6IVgqZtfcV1azIF6uOFt6blfn142zrwq0fF39jog2f+4jXaBKw6L4aP0HvIL83UArGppYY31894bLb6YL4EjS2JNbABM2VnJpJd4oGopOE42GCZlZRpf751zOptYAN23NFSujLlfaUfMbyrqIbRFC2DCdzNTU50GT5SAXX80UCgYEAlyvQvHwJCjMZaTd3SU1WGZ1o1qzIIyHvGXh5u1Rxm0TfWPquyfys2WwRhxoI6FoyXRgnFp8oZIAU2VIstL1dsUGgEnnvKVKAqw/HS3Keu80IpziNpdeVtjN59mGysc2zkBvVNx38Cxh6Cz5TFt4s/JkN5ld2VU0oeglWrtph3qkCgYALszZ/BrKdJBcba1QKv0zJpCjIBpGOI2whx54YFwH6qi4/F8W1JZ2LcHjsVG/IfWpUyPciY+KHEdGVrPiyc04Zvkquu6WpmLPJ6ZloUrvbaxgGYF+4yRADF1ecrqYg6onJY6NUFVKeHI+TdJPCf75aTK2vGCEjxbtU8ooiOQmm8QKBgEGe9ZdrwTP9rMQ35jYtzU+dT06k1r9BE9Q8CmrXl0HwK717ZWboX4J0YoFjxZC8PDsMl3p46MJ83rKbLU728uKig1AkZo7/OedxTWvezjZ1+lDyjC2EguXbgY1ecSC2HbJh9g+v8RUuhWxuA7RYoW92xVtKj+6l4vMadVP4Myp8-----END PRIVATE KEY-----"; private final MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, SamlSettings.definitions())); private final Auth auth = mock(Auth.class); private SamlAuthenticationStatus samlAuthenticationStatus; @Before public void setUp() { when(auth.getErrors()).thenReturn(new ArrayList<>()); when(auth.getSettings()).thenReturn(new Saml2Settings()); when(auth.getAttributes()).thenReturn(getResponseAttributes()); } @Test public void authentication_status_has_errors_when_no_idp_certificate_is_provided() { samlAuthenticationStatus = getSamlAuthenticationStatus("error message"); assertEquals("error", samlAuthenticationStatus.getStatus()); assertFalse(samlAuthenticationStatus.getErrors().isEmpty()); assertEquals("error message", samlAuthenticationStatus.getErrors().get(0)); } @Test public void authentication_status_is_success_when_no_errors() { setSettings(); getResponseAttributes().forEach((key, value) -> when(auth.getAttribute(key)).thenReturn(value)); samlAuthenticationStatus = getSamlAuthenticationStatus(auth, new SamlSettings(settings.asConfig())); assertEquals("success", samlAuthenticationStatus.getStatus()); assertTrue(samlAuthenticationStatus.getErrors().isEmpty()); } @Test public void authentication_status_is_unsuccessful_when_errors_are_reported() { setSettings(); when(auth.getErrors()).thenReturn(Collections.singletonList("Error in Authentication")); when(auth.getLastErrorReason()).thenReturn("Authentication failed due to a missing parameter."); when(auth.getAttributes()).thenReturn(getEmptyAttributes()); samlAuthenticationStatus = getSamlAuthenticationStatus(auth, new SamlSettings(settings.asConfig())); assertEquals("error", samlAuthenticationStatus.getStatus()); assertFalse(samlAuthenticationStatus.getErrors().isEmpty()); assertEquals(2, samlAuthenticationStatus.getErrors().size()); assertTrue(samlAuthenticationStatus.getErrors().contains("Authentication failed due to a missing parameter.")); assertTrue(samlAuthenticationStatus.getErrors().contains("Error in Authentication")); } @Test public void authentication_status_is_unsuccessful_when_processResponse_throws_exception() { setSettings(); try { doThrow(new Exception("Exception when processing the response")).when(auth).processResponse(); } catch (Exception e) { e.printStackTrace(); } when(auth.getAttributes()).thenReturn(getEmptyAttributes()); samlAuthenticationStatus = getSamlAuthenticationStatus(auth, new SamlSettings(settings.asConfig())); assertEquals("error", samlAuthenticationStatus.getStatus()); assertFalse(samlAuthenticationStatus.getErrors().isEmpty()); assertEquals(1, samlAuthenticationStatus.getErrors().size()); assertTrue(samlAuthenticationStatus.getErrors().contains("Exception when processing the response")); } @Test public void authentication_has_warnings_when_optional_mappings_are_not_correct() { setSettings(); settings.setProperty(GROUP_NAME_ATTRIBUTE, "wrongGroupField"); settings.setProperty(USER_EMAIL_ATTRIBUTE, "wrongEmailField"); settings.setProperty("sonar.auth.saml.sp.privateKey.secured", (String) null); getResponseAttributes().forEach((key, value) -> when(auth.getAttribute(key)).thenReturn(value)); samlAuthenticationStatus = getSamlAuthenticationStatus(auth, new SamlSettings(settings.asConfig())); assertEquals("success", samlAuthenticationStatus.getStatus()); assertTrue(samlAuthenticationStatus.getErrors().isEmpty()); assertEquals(2, samlAuthenticationStatus.getWarnings().size()); assertTrue(samlAuthenticationStatus.getWarnings() .contains(String.format("Mapping not found for the property %s, the field %s is not available in the SAML response.", GROUP_NAME_ATTRIBUTE, "wrongGroupField"))); assertTrue(samlAuthenticationStatus.getWarnings() .contains(String.format("Mapping not found for the property %s, the field %s is not available in the SAML response.", USER_EMAIL_ATTRIBUTE, "wrongEmailField"))); } @Test public void authentication_has_errors_when_login_and_name_mappings_are_not_correct() { setSettings(); settings.setProperty(USER_LOGIN_ATTRIBUTE, "wrongLoginField"); settings.setProperty(USER_NAME_ATTRIBUTE, "wrongNameField"); getResponseAttributes().forEach((key, value) -> when(auth.getAttribute(key)).thenReturn(value)); samlAuthenticationStatus = getSamlAuthenticationStatus(auth, new SamlSettings(settings.asConfig())); assertEquals("error", samlAuthenticationStatus.getStatus()); assertTrue(samlAuthenticationStatus.getWarnings().isEmpty()); assertEquals(2, samlAuthenticationStatus.getErrors().size()); assertTrue(samlAuthenticationStatus.getErrors() .contains(String.format("Mapping not found for the property %s, the field %s is not available in the SAML response.", USER_LOGIN_ATTRIBUTE, "wrongLoginField"))); assertTrue(samlAuthenticationStatus.getErrors() .contains(String.format("Mapping not found for the property %s, the field %s is not available in the SAML response.", USER_NAME_ATTRIBUTE, "wrongNameField"))); } @Test public void authentication_has_errors_when_login_and_name_are_empty() { setSettings(); when(auth.getAttributes()).thenReturn(getEmptyAttributes()); getEmptyAttributes().forEach((key, value) -> when(auth.getAttribute(key)).thenReturn(value)); samlAuthenticationStatus = getSamlAuthenticationStatus(auth, new SamlSettings(settings.asConfig())); assertEquals("error", samlAuthenticationStatus.getStatus()); assertTrue(samlAuthenticationStatus.getWarnings().isEmpty()); assertEquals(2, samlAuthenticationStatus.getErrors().size()); assertTrue(samlAuthenticationStatus.getErrors() .contains(String.format("Mapping found for the property %s, but the field %s is empty in the SAML response.", USER_LOGIN_ATTRIBUTE, "login"))); assertTrue(samlAuthenticationStatus.getErrors() .contains(String.format("Mapping found for the property %s, but the field %s is empty in the SAML response.", USER_NAME_ATTRIBUTE, "name"))); } @Test public void authentication_has_no_warnings_when_optional_mappings_are_not_provided() { setSettings(); settings.setProperty("sonar.auth.saml.sp.privateKey.secured", (String) null); settings.setProperty(USER_EMAIL_ATTRIBUTE, (String) null); settings.setProperty(GROUP_NAME_ATTRIBUTE, (String) null); getResponseAttributes().forEach((key, value) -> when(auth.getAttribute(key)).thenReturn(value)); samlAuthenticationStatus = getSamlAuthenticationStatus(auth, new SamlSettings(settings.asConfig())); assertEquals("success", samlAuthenticationStatus.getStatus()); assertTrue(samlAuthenticationStatus.getErrors().isEmpty()); assertTrue(samlAuthenticationStatus.getWarnings().isEmpty()); } @Test public void authentication_has_warnings_when_the_private_key_is_invalid_but_auth_completes() { setSettings(); getResponseAttributes().forEach((key, value) -> when(auth.getAttribute(key)).thenReturn(value)); samlAuthenticationStatus = getSamlAuthenticationStatus(auth, new SamlSettings(settings.asConfig())); assertEquals("success", samlAuthenticationStatus.getStatus()); assertTrue(samlAuthenticationStatus.getErrors().isEmpty()); assertFalse(samlAuthenticationStatus.getWarnings().isEmpty()); assertTrue(samlAuthenticationStatus.getWarnings() .contains(String.format("Error in parsing service provider private key, please make sure that it is in PKCS 8 format."))); } @Test public void mapped_attributes_are_complete_when_mapping_fields_are_correct() { setSettings(); settings.setProperty("sonar.auth.saml.sp.privateKey.secured", (String) null); getResponseAttributes().forEach((key, value) -> when(auth.getAttribute(key)).thenReturn(value)); samlAuthenticationStatus = getSamlAuthenticationStatus(auth, new SamlSettings(settings.asConfig())); assertEquals("success", samlAuthenticationStatus.getStatus()); assertTrue(samlAuthenticationStatus.getErrors().isEmpty()); assertTrue(samlAuthenticationStatus.getWarnings().isEmpty()); assertEquals(4, samlAuthenticationStatus.getAvailableAttributes().size()); assertEquals(4, samlAuthenticationStatus.getMappedAttributes().size()); assertTrue(samlAuthenticationStatus.getAvailableAttributes().keySet().containsAll(Set.of("login", "name", "email", "groups"))); assertTrue(samlAuthenticationStatus.getMappedAttributes().keySet().containsAll(Set.of("User login value", "User name value", "User email value", "Groups value"))); } private void setSettings() { settings.setProperty("sonar.auth.saml.applicationId", "MyApp"); settings.setProperty("sonar.auth.saml.providerId", "http://localhost:8080/auth/realms/sonarqube"); settings.setProperty("sonar.auth.saml.loginUrl", "http://localhost:8080/auth/realms/sonarqube/protocol/saml"); settings.setProperty("sonar.auth.saml.certificate.secured", IDP_CERTIFICATE); settings.setProperty("sonar.auth.saml.sp.privateKey.secured", SP_PRIVATE_KEY); settings.setProperty("sonar.auth.saml.sp.certificate.secured", SP_CERTIFICATE); settings.setProperty("sonar.auth.saml.user.login", "login"); settings.setProperty("sonar.auth.saml.user.name", "name"); settings.setProperty("sonar.auth.saml.user.email", "email"); settings.setProperty("sonar.auth.saml.group.name", "groups"); } private Map<String, List<String>> getResponseAttributes() { return Map.of( "login", Collections.singletonList("loginId"), "name", Collections.singletonList("userName"), "email", Collections.singletonList("user@sonar.com"), "groups", List.of("group1", "group2")); } private Map<String, List<String>> getEmptyAttributes() { return Map.of( "login", Collections.singletonList(""), "name", Collections.singletonList(""), "email", Collections.singletonList(""), "groups", Collections.singletonList("")); } }
16,827
64.992157
2,123
java
sonarqube
sonarqube-master/server/sonar-ce-common/src/it/java/org/sonar/ce/queue/CeQueueImplIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.queue; import java.util.List; import java.util.Optional; import java.util.Random; import java.util.stream.IntStream; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.utils.System2; import org.sonar.ce.queue.CeTaskSubmit.Component; import org.sonar.ce.task.CeTask; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.core.util.UuidFactory; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.ce.CeActivityDto; import org.sonar.db.ce.CeQueueDto; import org.sonar.db.ce.CeTaskTypes; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ProjectData; import org.sonar.db.entity.EntityDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserTesting; import org.sonar.server.platform.NodeInformation; import static com.google.common.collect.ImmutableList.of; import static java.util.Arrays.asList; import static java.util.Collections.emptyMap; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.catchThrowable; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.ce.queue.CeQueue.SubmitOption.UNIQUE_QUEUE_PER_ENTITY; import static org.sonar.ce.queue.CeQueue.SubmitOption.UNIQUE_QUEUE_PER_TASK_TYPE; public class CeQueueImplIT { private static final String WORKER_UUID = "workerUuid"; private static final long NOW = 1_450_000_000_000L; private static final String NODE_NAME = "nodeName1"; private System2 system2 = new TestSystem2().setNow(NOW); @Rule public DbTester db = DbTester.create(system2); private DbSession session = db.getSession(); private UuidFactory uuidFactory = new SequenceUuidFactory(); private NodeInformation nodeInformation = mock(NodeInformation.class); private CeQueue underTest = new CeQueueImpl(system2, db.getDbClient(), uuidFactory, nodeInformation); @Test public void submit_returns_task_populated_from_CeTaskSubmit_and_creates_CeQueue_row() { String componentUuid = randomAlphabetic(3); String mainComponentUuid = randomAlphabetic(4); CeTaskSubmit taskSubmit = createTaskSubmit(CeTaskTypes.REPORT, new Component(componentUuid, mainComponentUuid), "submitter uuid"); UserDto userDto = db.getDbClient().userDao().selectByUuid(db.getSession(), taskSubmit.getSubmitterUuid()); CeTask task = underTest.submit(taskSubmit); verifyCeTask(taskSubmit, task, null, null, userDto); verifyCeQueueDtoForTaskSubmit(taskSubmit); } @Test public void submit_populates_component_name_and_key_of_CeTask_if_component_exists() { ProjectData projectData = db.components().insertPrivateProject("PROJECT_1"); CeTaskSubmit taskSubmit = createTaskSubmit(CeTaskTypes.REPORT, Component.fromDto(projectData.getMainBranchDto()), null); CeTask task = underTest.submit(taskSubmit); verifyCeTask(taskSubmit, task, projectData.getProjectDto(), projectData.getMainBranchDto(), null); } @Test public void submit_returns_task_without_component_info_when_submit_has_none() { CeTaskSubmit taskSubmit = createTaskSubmit("not cpt related"); CeTask task = underTest.submit(taskSubmit); verifyCeTask(taskSubmit, task, null, null, null); } @Test public void submit_populates_submitter_login_of_CeTask_if_submitter_exists() { UserDto userDto = insertUser(UserTesting.newUserDto()); CeTaskSubmit taskSubmit = createTaskSubmit(CeTaskTypes.REPORT, null, userDto.getUuid()); CeTask task = underTest.submit(taskSubmit); verifyCeTask(taskSubmit, task, null, null, userDto); } @Test public void submit_with_UNIQUE_QUEUE_PER_MAIN_COMPONENT_creates_task_without_component_when_there_is_a_pending_task_without_component() { CeTaskSubmit taskSubmit = createTaskSubmit("no_component"); CeQueueDto dto = insertPendingInQueue(null); Optional<CeTask> task = underTest.submit(taskSubmit, UNIQUE_QUEUE_PER_ENTITY); assertThat(task).isNotEmpty(); assertThat(db.getDbClient().ceQueueDao().selectAllInAscOrder(db.getSession())) .extracting(CeQueueDto::getUuid) .containsOnly(dto.getUuid(), task.get().getUuid()); } @Test public void submit_with_UNIQUE_QUEUE_PER_MAIN_COMPONENT_creates_task_when_there_is_a_pending_task_for_another_main_component() { String mainComponentUuid = randomAlphabetic(5); String otherMainComponentUuid = randomAlphabetic(6); CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null); CeQueueDto dto = insertPendingInQueue(newComponent(otherMainComponentUuid)); Optional<CeTask> task = underTest.submit(taskSubmit, UNIQUE_QUEUE_PER_ENTITY); assertThat(task).isNotEmpty(); assertThat(db.getDbClient().ceQueueDao().selectAllInAscOrder(db.getSession())) .extracting(CeQueueDto::getUuid) .containsOnly(dto.getUuid(), task.get().getUuid()); } @Test public void submit_with_UNIQUE_QUEUE_PER_MAIN_COMPONENT_does_not_create_task_when_there_is_one_pending_task_for_same_main_component() { String mainComponentUuid = randomAlphabetic(5); CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null); CeQueueDto dto = insertPendingInQueue(newComponent(mainComponentUuid)); Optional<CeTask> task = underTest.submit(taskSubmit, UNIQUE_QUEUE_PER_ENTITY); assertThat(task).isEmpty(); assertThat(db.getDbClient().ceQueueDao().selectAllInAscOrder(db.getSession())) .extracting(CeQueueDto::getUuid) .containsOnly(dto.getUuid()); } @Test public void submit_with_UNIQUE_QUEUE_PER_MAIN_COMPONENT_does_not_create_task_when_there_is_many_pending_task_for_same_main_component() { String mainComponentUuid = randomAlphabetic(5); CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null); String[] uuids = IntStream.range(0, 2 + new Random().nextInt(5)) .mapToObj(i -> insertPendingInQueue(newComponent(mainComponentUuid))) .map(CeQueueDto::getUuid) .toArray(String[]::new); Optional<CeTask> task = underTest.submit(taskSubmit, UNIQUE_QUEUE_PER_ENTITY); assertThat(task).isEmpty(); assertThat(db.getDbClient().ceQueueDao().selectAllInAscOrder(db.getSession())) .extracting(CeQueueDto::getUuid) .containsOnly(uuids); } @Test public void submit_without_UNIQUE_QUEUE_PER_MAIN_COMPONENT_creates_task_when_there_is_one_pending_task_for_same_main_component() { String mainComponentUuid = randomAlphabetic(5); CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null); CeQueueDto dto = insertPendingInQueue(newComponent(mainComponentUuid)); CeTask task = underTest.submit(taskSubmit); assertThat(db.getDbClient().ceQueueDao().selectAllInAscOrder(db.getSession())) .extracting(CeQueueDto::getUuid) .containsOnly(dto.getUuid(), task.getUuid()); } @Test public void submit_without_UNIQUE_QUEUE_PER_MAIN_COMPONENT_creates_task_when_there_is_many_pending_task_for_same_main_component() { String mainComponentUuid = randomAlphabetic(5); CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null); String[] uuids = IntStream.range(0, 2 + new Random().nextInt(5)) .mapToObj(i -> insertPendingInQueue(newComponent(mainComponentUuid))) .map(CeQueueDto::getUuid) .toArray(String[]::new); CeTask task = underTest.submit(taskSubmit); assertThat(db.getDbClient().ceQueueDao().selectAllInAscOrder(db.getSession())) .extracting(CeQueueDto::getUuid) .hasSize(uuids.length + 1) .contains(uuids) .contains(task.getUuid()); } @Test public void submit_with_UNIQUE_QUEUE_PER_TASK_TYPE_does_not_create_task_when_there_is_a_task_with_the_same_type() { String mainComponentUuid = randomAlphabetic(5); CeTaskSubmit taskSubmit = createTaskSubmit("some type", newComponent(mainComponentUuid), null); String[] uuids = IntStream.range(0, 2 + new Random().nextInt(5)) .mapToObj(i -> insertPendingInQueue(newComponent(mainComponentUuid))) .map(CeQueueDto::getUuid) .toArray(String[]::new); Optional<CeTask> task = underTest.submit(taskSubmit, UNIQUE_QUEUE_PER_TASK_TYPE); assertThat(task).isEmpty(); assertThat(db.getDbClient().ceQueueDao().selectAllInAscOrder(db.getSession())) .extracting(CeQueueDto::getUuid) .containsOnly(uuids); } @Test public void massSubmit_returns_tasks_for_each_CeTaskSubmit_populated_from_CeTaskSubmit_and_creates_CeQueue_row_for_each() { String mainComponentUuid = randomAlphabetic(10); CeTaskSubmit taskSubmit1 = createTaskSubmit(CeTaskTypes.REPORT, newComponent(mainComponentUuid), "submitter uuid"); CeTaskSubmit taskSubmit2 = createTaskSubmit("some type"); UserDto userDto1 = db.getDbClient().userDao().selectByUuid(db.getSession(), taskSubmit1.getSubmitterUuid()); List<CeTask> tasks = underTest.massSubmit(asList(taskSubmit1, taskSubmit2)); assertThat(tasks).hasSize(2); verifyCeTask(taskSubmit1, tasks.get(0), null, null, userDto1); verifyCeTask(taskSubmit2, tasks.get(1), null, null, null); verifyCeQueueDtoForTaskSubmit(taskSubmit1); verifyCeQueueDtoForTaskSubmit(taskSubmit2); } @Test public void massSubmit_populates_component_name_and_key_of_CeTask_if_project_exists() { ProjectData projectData = db.components().insertPrivateProject("PROJECT_1"); CeTaskSubmit taskSubmit1 = createTaskSubmit(CeTaskTypes.REPORT, Component.fromDto(projectData.getMainBranchDto()), null); CeTaskSubmit taskSubmit2 = createTaskSubmit("something", newComponent(randomAlphabetic(12)), null); List<CeTask> tasks = underTest.massSubmit(asList(taskSubmit1, taskSubmit2)); assertThat(tasks).hasSize(2); verifyCeTask(taskSubmit1, tasks.get(0), projectData.getProjectDto(), projectData.getMainBranchDto(), null); verifyCeTask(taskSubmit2, tasks.get(1), null, null, null); } @Test public void massSubmit_populates_component_name_and_key_of_CeTask_if_project_and_branch_exists() { ProjectDto project = db.components().insertPublicProject(p -> p.setUuid("PROJECT_1").setBranchUuid("PROJECT_1")).getProjectDto(); BranchDto branch1 = db.components().insertProjectBranch(project); BranchDto branch2 = db.components().insertProjectBranch(project); CeTaskSubmit taskSubmit1 = createTaskSubmit(CeTaskTypes.REPORT, Component.fromDto(branch1.getUuid(), project.getUuid()), null); CeTaskSubmit taskSubmit2 = createTaskSubmit("something", Component.fromDto(branch2.getUuid(), project.getUuid()), null); List<CeTask> tasks = underTest.massSubmit(asList(taskSubmit1, taskSubmit2)); assertThat(tasks).hasSize(2); verifyCeTask(taskSubmit1, tasks.get(0), project, branch1, null); verifyCeTask(taskSubmit2, tasks.get(1), project, branch2, null); } @Test public void massSubmit_with_UNIQUE_QUEUE_PER_MAIN_COMPONENT_creates_task_without_component_when_there_is_a_pending_task_without_component() { CeTaskSubmit taskSubmit = createTaskSubmit("no_component"); CeQueueDto dto = insertPendingInQueue(null); List<CeTask> tasks = underTest.massSubmit(of(taskSubmit), UNIQUE_QUEUE_PER_ENTITY); assertThat(tasks).hasSize(1); assertThat(db.getDbClient().ceQueueDao().selectAllInAscOrder(db.getSession())) .extracting(CeQueueDto::getUuid) .containsOnly(dto.getUuid(), tasks.iterator().next().getUuid()); } @Test public void massSubmit_with_UNIQUE_QUEUE_PER_MAIN_COMPONENT_creates_task_when_there_is_a_pending_task_for_another_main_component() { String mainComponentUuid = randomAlphabetic(5); String otherMainComponentUuid = randomAlphabetic(6); CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null); CeQueueDto dto = insertPendingInQueue(newComponent(otherMainComponentUuid)); List<CeTask> tasks = underTest.massSubmit(of(taskSubmit), UNIQUE_QUEUE_PER_ENTITY); assertThat(tasks).hasSize(1); assertThat(db.getDbClient().ceQueueDao().selectAllInAscOrder(db.getSession())) .extracting(CeQueueDto::getUuid) .containsOnly(dto.getUuid(), tasks.iterator().next().getUuid()); } @Test public void massSubmit_with_UNIQUE_QUEUE_PER_MAIN_COMPONENT_does_not_create_task_when_there_is_one_pending_task_for_same_main_component() { String mainComponentUuid = randomAlphabetic(5); CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null); CeQueueDto dto = insertPendingInQueue(newComponent(mainComponentUuid)); List<CeTask> tasks = underTest.massSubmit(of(taskSubmit), UNIQUE_QUEUE_PER_ENTITY); assertThat(tasks).isEmpty(); assertThat(db.getDbClient().ceQueueDao().selectAllInAscOrder(db.getSession())) .extracting(CeQueueDto::getUuid) .containsOnly(dto.getUuid()); } @Test public void massSubmit_with_UNIQUE_QUEUE_PER_MAIN_COMPONENT_does_not_create_task_when_there_is_many_pending_task_for_same_main_component() { String mainComponentUuid = randomAlphabetic(5); CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null); String[] uuids = IntStream.range(0, 7) .mapToObj(i -> insertPendingInQueue(newComponent(mainComponentUuid))) .map(CeQueueDto::getUuid) .toArray(String[]::new); List<CeTask> tasks = underTest.massSubmit(of(taskSubmit), UNIQUE_QUEUE_PER_ENTITY); assertThat(tasks).isEmpty(); assertThat(db.getDbClient().ceQueueDao().selectAllInAscOrder(db.getSession())) .extracting(CeQueueDto::getUuid) .containsOnly(uuids); } @Test public void massSubmit_without_UNIQUE_QUEUE_PER_MAIN_COMPONENT_creates_task_when_there_is_one_pending_task_for_other_main_component() { String mainComponentUuid = randomAlphabetic(5); CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null); CeQueueDto dto = insertPendingInQueue(newComponent(mainComponentUuid)); List<CeTask> tasks = underTest.massSubmit(of(taskSubmit)); assertThat(tasks).hasSize(1); assertThat(db.getDbClient().ceQueueDao().selectAllInAscOrder(db.getSession())) .extracting(CeQueueDto::getUuid) .containsOnly(dto.getUuid(), tasks.iterator().next().getUuid()); } @Test public void massSubmit_without_UNIQUE_QUEUE_PER_MAIN_COMPONENT_creates_task_when_there_is_many_pending_task_for_other_main_component() { String mainComponentUuid = randomAlphabetic(5); CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null); String[] uuids = IntStream.range(0, 2 + new Random().nextInt(5)) .mapToObj(i -> insertPendingInQueue(newComponent(mainComponentUuid))) .map(CeQueueDto::getUuid) .toArray(String[]::new); List<CeTask> tasks = underTest.massSubmit(of(taskSubmit)); assertThat(tasks).hasSize(1); assertThat(db.getDbClient().ceQueueDao().selectAllInAscOrder(db.getSession())) .extracting(CeQueueDto::getUuid) .hasSize(uuids.length + 1) .contains(uuids) .contains(tasks.iterator().next().getUuid()); } @Test public void massSubmit_with_UNIQUE_QUEUE_PER_MAIN_COMPONENT_creates_tasks_depending_on_whether_there_is_pending_task_for_same_main_component() { String mainComponentUuid1 = randomAlphabetic(5); String mainComponentUuid2 = randomAlphabetic(6); String mainComponentUuid3 = randomAlphabetic(7); String mainComponentUuid4 = randomAlphabetic(8); String mainComponentUuid5 = randomAlphabetic(9); CeTaskSubmit taskSubmit1 = createTaskSubmit("with_one_pending", newComponent(mainComponentUuid1), null); CeQueueDto dto1 = insertPendingInQueue(newComponent(mainComponentUuid1)); Component componentForMainComponentUuid2 = newComponent(mainComponentUuid2); CeTaskSubmit taskSubmit2 = createTaskSubmit("no_pending", componentForMainComponentUuid2, null); CeTaskSubmit taskSubmit3 = createTaskSubmit("with_many_pending", newComponent(mainComponentUuid3), null); String[] uuids3 = IntStream.range(0, 2 + new Random().nextInt(5)) .mapToObj(i -> insertPendingInQueue(newComponent(mainComponentUuid3))) .map(CeQueueDto::getUuid) .toArray(String[]::new); Component componentForMainComponentUuid4 = newComponent(mainComponentUuid4); CeTaskSubmit taskSubmit4 = createTaskSubmit("no_pending_2", componentForMainComponentUuid4, null); CeTaskSubmit taskSubmit5 = createTaskSubmit("with_pending_2", newComponent(mainComponentUuid5), null); CeQueueDto dto5 = insertPendingInQueue(newComponent(mainComponentUuid5)); List<CeTask> tasks = underTest.massSubmit(of(taskSubmit1, taskSubmit2, taskSubmit3, taskSubmit4, taskSubmit5), UNIQUE_QUEUE_PER_ENTITY); assertThat(tasks) .hasSize(2) .extracting(task -> task.getComponent().get().getUuid(), task -> task.getEntity().get().getUuid()) .containsOnly(tuple(componentForMainComponentUuid2.getUuid(), componentForMainComponentUuid2.getEntityUuid()), tuple(componentForMainComponentUuid4.getUuid(), componentForMainComponentUuid4.getEntityUuid())); assertThat(db.getDbClient().ceQueueDao().selectAllInAscOrder(db.getSession())) .extracting(CeQueueDto::getUuid) .hasSize(1 + uuids3.length + 1 + tasks.size()) .contains(dto1.getUuid()) .contains(uuids3) .contains(dto5.getUuid()) .containsAll(tasks.stream().map(CeTask::getUuid).toList()); } @Test public void cancel_pending() { CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12))); CeQueueDto queueDto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), task.getUuid()).get(); underTest.cancel(db.getSession(), queueDto); Optional<CeActivityDto> activity = findCeActivityDtoInDb(task); assertThat(activity).isPresent(); assertThat(activity.get().getStatus()).isEqualTo(CeActivityDto.Status.CANCELED); } @Test public void cancel_pending_whenNodeNameProvided_setItInCeActivity() { when(nodeInformation.getNodeName()).thenReturn(Optional.of(NODE_NAME)); CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12))); CeQueueDto queueDto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), task.getUuid()).get(); underTest.cancel(db.getSession(), queueDto); Optional<CeActivityDto> activity = findCeActivityDtoInDb(task); assertThat(activity).isPresent(); assertThat(activity.get().getNodeName()).isEqualTo(NODE_NAME); } @Test public void cancel_pending_whenNodeNameNOtProvided_setNulInCeActivity() { when(nodeInformation.getNodeName()).thenReturn(Optional.empty()); CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12))); CeQueueDto queueDto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), task.getUuid()).get(); underTest.cancel(db.getSession(), queueDto); Optional<CeActivityDto> activity = findCeActivityDtoInDb(task); assertThat(activity).isPresent(); assertThat(activity.get().getNodeName()).isNull(); } @Test public void fail_to_cancel_if_in_progress() { CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(11))); CeQueueDto ceQueueDto = db.getDbClient().ceQueueDao().tryToPeek(session, task.getUuid(), WORKER_UUID).get(); assertThatThrownBy(() -> underTest.cancel(db.getSession(), ceQueueDto)) .isInstanceOf(IllegalStateException.class) .hasMessageStartingWith("Task is in progress and can't be canceled"); } @Test public void cancelAll_pendings_but_not_in_progress() { CeTask inProgressTask = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12))); CeTask pendingTask1 = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12))); CeTask pendingTask2 = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12))); db.getDbClient().ceQueueDao().tryToPeek(session, inProgressTask.getUuid(), WORKER_UUID); int canceledCount = underTest.cancelAll(); assertThat(canceledCount).isEqualTo(2); Optional<CeActivityDto> ceActivityInProgress = findCeActivityDtoInDb(pendingTask1); assertThat(ceActivityInProgress.get().getStatus()).isEqualTo(CeActivityDto.Status.CANCELED); Optional<CeActivityDto> ceActivityPending1 = findCeActivityDtoInDb(pendingTask2); assertThat(ceActivityPending1.get().getStatus()).isEqualTo(CeActivityDto.Status.CANCELED); Optional<CeActivityDto> ceActivityPending2 = findCeActivityDtoInDb(inProgressTask); assertThat(ceActivityPending2).isNotPresent(); } @Test public void pauseWorkers_marks_workers_as_paused_if_zero_tasks_in_progress() { submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12))); // task is pending assertThat(underTest.getWorkersPauseStatus()).isEqualTo(CeQueue.WorkersPauseStatus.RESUMED); underTest.pauseWorkers(); assertThat(underTest.getWorkersPauseStatus()).isEqualTo(CeQueue.WorkersPauseStatus.PAUSED); } @Test public void pauseWorkers_marks_workers_as_pausing_if_some_tasks_in_progress() { CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12))); db.getDbClient().ceQueueDao().tryToPeek(session, task.getUuid(), WORKER_UUID); // task is in-progress assertThat(underTest.getWorkersPauseStatus()).isEqualTo(CeQueue.WorkersPauseStatus.RESUMED); underTest.pauseWorkers(); assertThat(underTest.getWorkersPauseStatus()).isEqualTo(CeQueue.WorkersPauseStatus.PAUSING); } @Test public void resumeWorkers_does_nothing_if_not_paused() { assertThat(underTest.getWorkersPauseStatus()).isEqualTo(CeQueue.WorkersPauseStatus.RESUMED); underTest.resumeWorkers(); assertThat(underTest.getWorkersPauseStatus()).isEqualTo(CeQueue.WorkersPauseStatus.RESUMED); } @Test public void resumeWorkers_resumes_pausing_workers() { CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12))); db.getDbClient().ceQueueDao().tryToPeek(session, task.getUuid(), WORKER_UUID); // task is in-progress underTest.pauseWorkers(); assertThat(underTest.getWorkersPauseStatus()).isEqualTo(CeQueue.WorkersPauseStatus.PAUSING); underTest.resumeWorkers(); assertThat(underTest.getWorkersPauseStatus()).isEqualTo(CeQueue.WorkersPauseStatus.RESUMED); } @Test public void resumeWorkers_resumes_paused_workers() { underTest.pauseWorkers(); assertThat(underTest.getWorkersPauseStatus()).isEqualTo(CeQueue.WorkersPauseStatus.PAUSED); underTest.resumeWorkers(); assertThat(underTest.getWorkersPauseStatus()).isEqualTo(CeQueue.WorkersPauseStatus.RESUMED); } @Test public void fail_in_progress_task() { CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12))); CeQueueDto queueDto = db.getDbClient().ceQueueDao().tryToPeek(db.getSession(), task.getUuid(), WORKER_UUID).get(); underTest.fail(db.getSession(), queueDto, "TIMEOUT", "Failed on timeout"); Optional<CeActivityDto> activity = findCeActivityDtoInDb(task); assertThat(activity).isPresent(); assertThat(activity.get().getStatus()).isEqualTo(CeActivityDto.Status.FAILED); assertThat(activity.get().getErrorType()).isEqualTo("TIMEOUT"); assertThat(activity.get().getErrorMessage()).isEqualTo("Failed on timeout"); assertThat(activity.get().getExecutedAt()).isEqualTo(NOW); assertThat(activity.get().getWorkerUuid()).isEqualTo(WORKER_UUID); assertThat(activity.get().getNodeName()).isNull(); } @Test public void fail_in_progress_task_whenNodeNameProvided_setsItInCeActivityDto() { when(nodeInformation.getNodeName()).thenReturn(Optional.of(NODE_NAME)); CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12))); CeQueueDto queueDto = db.getDbClient().ceQueueDao().tryToPeek(db.getSession(), task.getUuid(), WORKER_UUID).get(); underTest.fail(db.getSession(), queueDto, "TIMEOUT", "Failed on timeout"); Optional<CeActivityDto> activity = findCeActivityDtoInDb(task); assertThat(activity).isPresent(); assertThat(activity.get().getNodeName()).isEqualTo(NODE_NAME); } private Optional<CeActivityDto> findCeActivityDtoInDb(CeTask task) { return db.getDbClient().ceActivityDao().selectByUuid(db.getSession(), task.getUuid()); } @Test public void fail_throws_exception_if_task_is_pending() { CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12))); CeQueueDto queueDto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), task.getUuid()).get(); Throwable thrown = catchThrowable(() -> underTest.fail(db.getSession(), queueDto, "TIMEOUT", "Failed on timeout")); assertThat(thrown) .isInstanceOf(IllegalStateException.class) .hasMessage("Task is not in-progress and can't be marked as failed [uuid=" + task.getUuid() + "]"); } private void verifyCeTask(CeTaskSubmit taskSubmit, CeTask task, @Nullable EntityDto entityDto, @Nullable BranchDto branch, @Nullable UserDto userDto) { assertThat(task.getUuid()).isEqualTo(taskSubmit.getUuid()); if (branch != null) { CeTask.Component component = task.getComponent().get(); assertThat(component.getUuid()).isEqualTo(branch.getUuid()); assertThat(component.getKey()).contains(entityDto.getKey()); assertThat(component.getName()).contains(entityDto.getName()); } else if (taskSubmit.getComponent().isPresent()) { assertThat(task.getComponent()).contains(new CeTask.Component(taskSubmit.getComponent().get().getUuid(), null, null)); } else { assertThat(task.getComponent()).isEmpty(); } if (entityDto != null) { CeTask.Component component = task.getEntity().get(); assertThat(component.getUuid()).isEqualTo(entityDto.getUuid()); assertThat(component.getKey()).contains(entityDto.getKey()); assertThat(component.getName()).contains(entityDto.getName()); } else if (taskSubmit.getComponent().isPresent()) { assertThat(task.getEntity()).contains(new CeTask.Component(taskSubmit.getComponent().get().getEntityUuid(), null, null)); } else { assertThat(task.getEntity()).isEmpty(); } assertThat(task.getType()).isEqualTo(taskSubmit.getType()); if (taskSubmit.getSubmitterUuid() != null) { if (userDto == null) { assertThat(task.getSubmitter().uuid()).isEqualTo(taskSubmit.getSubmitterUuid()); assertThat(task.getSubmitter().login()).isNull(); } else { assertThat(task.getSubmitter().uuid()).isEqualTo(userDto.getUuid()).isEqualTo(taskSubmit.getSubmitterUuid()); assertThat(task.getSubmitter().login()).isEqualTo(userDto.getLogin()); } } } private void verifyCeQueueDtoForTaskSubmit(CeTaskSubmit taskSubmit) { Optional<CeQueueDto> queueDto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), taskSubmit.getUuid()); assertThat(queueDto).isPresent(); assertThat(queueDto.get().getTaskType()).isEqualTo(taskSubmit.getType()); Optional<Component> component = taskSubmit.getComponent(); if (component.isPresent()) { assertThat(queueDto.get().getComponentUuid()).isEqualTo(component.get().getUuid()); assertThat(queueDto.get().getEntityUuid()).isEqualTo(component.get().getEntityUuid()); } else { assertThat(queueDto.get().getComponentUuid()).isNull(); assertThat(queueDto.get().getComponentUuid()).isNull(); } assertThat(queueDto.get().getSubmitterUuid()).isEqualTo(taskSubmit.getSubmitterUuid()); assertThat(queueDto.get().getCreatedAt()).isEqualTo(1_450_000_000_000L); } private CeTask submit(String reportType, Component component) { return underTest.submit(createTaskSubmit(reportType, component, null)); } private CeTaskSubmit createTaskSubmit(String type) { return createTaskSubmit(type, null, null); } private CeTaskSubmit createTaskSubmit(String type, @Nullable Component component, @Nullable String submitterUuid) { return underTest.prepareSubmit() .setType(type) .setComponent(component) .setSubmitterUuid(submitterUuid) .setCharacteristics(emptyMap()) .build(); } private ComponentDto insertComponent(ComponentDto componentDto) { return db.components().insertComponent(componentDto); } private UserDto insertUser(UserDto userDto) { db.getDbClient().userDao().insert(session, userDto); session.commit(); return userDto; } private CeQueueDto insertPendingInQueue(@Nullable Component component) { CeQueueDto dto = new CeQueueDto() .setUuid(UuidFactoryFast.getInstance().create()) .setTaskType("some type") .setStatus(CeQueueDto.Status.PENDING); if (component != null) { dto.setComponentUuid(component.getUuid()) .setEntityUuid(component.getEntityUuid()); } db.getDbClient().ceQueueDao().insert(db.getSession(), dto); db.commit(); return dto; } private static int newComponentIdGenerator = new Random().nextInt(8_999_333); private static Component newComponent(String mainComponentUuid) { return new Component("uuid_" + newComponentIdGenerator++, mainComponentUuid); } }
30,469
44.682159
153
java
sonarqube
sonarqube-master/server/sonar-ce-common/src/main/java/org/sonar/ce/configuration/WorkerCountProvider.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.configuration; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.server.ServerSide; /** * When an implementation of this interface is available in the ioc container, the Compute Engine will use the value returned by * {@link #get()} as the number of worker the Compute Engine should run on. */ @ComputeEngineSide @ServerSide public interface WorkerCountProvider { /** * @return an integer strictly greater than 0 */ int get(); }
1,322
34.756757
128
java
sonarqube
sonarqube-master/server/sonar-ce-common/src/main/java/org/sonar/ce/configuration/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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. */ @ParametersAreNonnullByDefault package org.sonar.ce.configuration; import javax.annotation.ParametersAreNonnullByDefault;
966
39.291667
75
java
sonarqube
sonarqube-master/server/sonar-ce-common/src/main/java/org/sonar/ce/queue/CeQueue.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.queue; import java.util.Collection; import java.util.List; import java.util.Optional; import javax.annotation.Nullable; import org.sonar.ce.task.CeTask; import org.sonar.db.DbSession; import org.sonar.db.ce.CeActivityDto; import org.sonar.db.ce.CeQueueDto; /** * Queue of pending Compute Engine tasks. Both producer and consumer actions * are implemented. * <p> * This class is decoupled from the regular task type {@link org.sonar.db.ce.CeTaskTypes#REPORT}. * </p> */ public interface CeQueue { /** * Build an instance of {@link CeTaskSubmit} required for {@link #submit(CeTaskSubmit, SubmitOption...)}. It allows * to enforce that task ids are generated by the queue. It's used also for having access * to the id before submitting the task to the queue. */ CeTaskSubmit.Builder prepareSubmit(); /** * Submits a task to the queue. The task is processed asynchronously. * <p> * Convenience method for calling {@link #submit(CeTaskSubmit, SubmitOption...)} without any {@link SubmitOption} * and which does not returning an {@link Optional}. * <p> * This method is equivalent to calling {@link #massSubmit(Collection, SubmitOption...)} with a singleton list and no * option. */ CeTask submit(CeTaskSubmit submission); /** * Submits a task to the queue. The task is processed asynchronously. * <p> * This method is equivalent to calling {@code massSubmit(Collections.singletonList(submission))}. * * @return empty if {@code options} contains {@link SubmitOption#UNIQUE_QUEUE_PER_ENTITY UNIQUE_QUEUE_PER_MAIN_COMPONENT} * and there's already a queued task, otherwise the created task. */ Optional<CeTask> submit(CeTaskSubmit submission, SubmitOption... options); /** * Submits multiple tasks to the queue at once. All tasks are processed asynchronously. * <p> * This method will perform significantly better that calling {@link #submit(CeTaskSubmit, SubmitOption...)} in a loop. * </p> */ List<CeTask> massSubmit(Collection<CeTaskSubmit> submissions, SubmitOption... options); /** * Cancels a task in status {@link org.sonar.db.ce.CeQueueDto.Status#PENDING}. An unchecked * exception is thrown if the status is not {@link org.sonar.db.ce.CeQueueDto.Status#PENDING}. */ void cancel(DbSession dbSession, CeQueueDto ceQueueDto); /** * Removes all the tasks from the queue, except the tasks with status * {@link org.sonar.db.ce.CeQueueDto.Status#IN_PROGRESS} are ignored. They are marked * as {@link org.sonar.db.ce.CeActivityDto.Status#CANCELED} in past activity. * This method can be called at runtime, even if workers are being executed. * * @return the number of canceled tasks */ int cancelAll(); /** * Mark a task in status {@link org.sonar.db.ce.CeQueueDto.Status#IN_PROGRESS} as failed. An unchecked * exception is thrown if the status is not {@link org.sonar.db.ce.CeQueueDto.Status#IN_PROGRESS}. * * The {@code dbSession} is committed. * @throws RuntimeException if the task is concurrently removed from the queue */ void fail(DbSession dbSession, CeQueueDto ceQueueDto, @Nullable String errorType, @Nullable String errorMessage); /** * Requests workers to stop peeking tasks from queue. Does nothing if workers are already paused or being paused. * The workers that are already processing tasks are not interrupted. * This method is not restricted to the local workers. All the Compute Engine nodes are paused. */ void pauseWorkers(); /** * Resumes workers so that they can peek tasks from queue. * This method is not restricted to the local workers. All the Compute Engine nodes are paused. */ void resumeWorkers(); WorkersPauseStatus getWorkersPauseStatus(); /** * Removes all the tasks from the queue, whatever their status. They are marked * as {@link CeActivityDto.Status#CANCELED} in past activity. * This method can NOT be called when workers are being executed, as in progress * tasks can't be killed. * * @return the number of canceled tasks */ int clear(); enum SubmitOption { UNIQUE_QUEUE_PER_ENTITY, UNIQUE_QUEUE_PER_TASK_TYPE } enum WorkersPauseStatus { /** * Pause triggered but at least one task is still in-progress */ PAUSING, /** * Paused, no tasks are in-progress. Tasks are pending. */ PAUSED, /** * Not paused nor pausing */ RESUMED } }
5,335
34.812081
123
java
sonarqube
sonarqube-master/server/sonar-ce-common/src/main/java/org/sonar/ce/queue/CeQueueImpl.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.queue; import com.google.common.collect.Multimap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.slf4j.LoggerFactory; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.System2; import org.sonar.ce.task.CeTask; import org.sonar.core.util.UuidFactory; import org.sonar.core.util.stream.MoreCollectors; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.ce.CeActivityDto; import org.sonar.db.ce.CeQueueDto; import org.sonar.db.ce.CeTaskCharacteristicDto; import org.sonar.db.ce.CeTaskQuery; import org.sonar.db.ce.DeleteIf; import org.sonar.db.component.ComponentDto; import org.sonar.db.entity.EntityDto; import org.sonar.db.user.UserDto; import org.sonar.server.platform.NodeInformation; import org.sonar.server.property.InternalProperties; import static com.google.common.base.Preconditions.checkState; import static java.util.Collections.singleton; import static java.util.Optional.ofNullable; import static org.sonar.ce.queue.CeQueue.SubmitOption.UNIQUE_QUEUE_PER_ENTITY; import static org.sonar.db.ce.CeQueueDto.Status.IN_PROGRESS; import static org.sonar.db.ce.CeQueueDto.Status.PENDING; @ServerSide public class CeQueueImpl implements CeQueue { private final System2 system2; private final DbClient dbClient; private final UuidFactory uuidFactory; protected final NodeInformation nodeInformation; public CeQueueImpl(System2 system2, DbClient dbClient, UuidFactory uuidFactory, NodeInformation nodeInformation) { this.system2 = system2; this.dbClient = dbClient; this.uuidFactory = uuidFactory; this.nodeInformation = nodeInformation; } @Override public CeTaskSubmit.Builder prepareSubmit() { return new CeTaskSubmit.Builder(uuidFactory.create()); } @Override public CeTask submit(CeTaskSubmit submission) { return submit(submission, EnumSet.noneOf(SubmitOption.class)).get(); } @Override public Optional<CeTask> submit(CeTaskSubmit submission, SubmitOption... options) { return submit(submission, toSet(options)); } private Optional<CeTask> submit(CeTaskSubmit submission, Set<SubmitOption> submitOptions) { try (DbSession dbSession = dbClient.openSession(false)) { Optional<CeTask> ceTask = submit(dbSession, submission, submitOptions); dbSession.commit(); return ceTask; } } private Optional<CeTask> submit(DbSession dbSession, CeTaskSubmit submission, Set<SubmitOption> submitOptions) { CeTaskQuery query = new CeTaskQuery(); for (SubmitOption option : submitOptions) { switch (option) { case UNIQUE_QUEUE_PER_ENTITY -> submission.getComponent() .flatMap(component -> Optional.ofNullable(component.getEntityUuid())) .ifPresent(entityUuid -> query.setEntityUuid(entityUuid).setStatuses(List.of(PENDING.name()))); case UNIQUE_QUEUE_PER_TASK_TYPE -> query.setType(submission.getType()); } } boolean queryNonEmpty = query.getEntityUuids() != null || query.getStatuses() != null || query.getType() != null; if (queryNonEmpty && dbClient.ceQueueDao().countByQuery(dbSession, query) > 0) { return Optional.empty(); } CeQueueDto inserted = addToQueueInDb(dbSession, submission); return Optional.of(convertQueueDtoToTask(dbSession, inserted, submission)); } private CeTask convertQueueDtoToTask(DbSession dbSession, CeQueueDto queueDto, CeTaskSubmit submission) { return convertToTask(dbSession, queueDto, submission.getCharacteristics()); } protected CeTask convertToTask(DbSession dbSession, CeQueueDto queueDto, Map<String, String> characteristicDto) { ComponentDto component = null; EntityDto entity = null; if (queueDto.getComponentUuid() != null) { component = dbClient.componentDao().selectByUuid(dbSession, queueDto.getComponentUuid()).orElse(null); } if (queueDto.getEntityUuid() != null) { entity = dbClient.entityDao().selectByUuid(dbSession, queueDto.getEntityUuid()).orElse(null); } return convertToTask(dbSession, queueDto, characteristicDto, component, entity); } @Override public List<CeTask> massSubmit(Collection<CeTaskSubmit> submissions, SubmitOption... options) { if (submissions.isEmpty()) { return Collections.emptyList(); } try (DbSession dbSession = dbClient.openSession(false)) { List<CeQueueDto> taskDtos = submissions.stream() .filter(filterBySubmitOptions(options, submissions, dbSession)) .map(submission -> addToQueueInDb(dbSession, submission)) .toList(); List<CeTask> tasks = loadTasks(dbSession, taskDtos); dbSession.commit(); return tasks; } } private Predicate<CeTaskSubmit> filterBySubmitOptions(SubmitOption[] options, Collection<CeTaskSubmit> submissions, DbSession dbSession) { Set<SubmitOption> submitOptions = toSet(options); if (submitOptions.contains(UNIQUE_QUEUE_PER_ENTITY)) { Set<String> mainComponentUuids = submissions.stream() .map(CeTaskSubmit::getComponent) .filter(Optional::isPresent) .map(Optional::get) .map(CeTaskSubmit.Component::getEntityUuid) .collect(Collectors.toSet()); if (mainComponentUuids.isEmpty()) { return t -> true; } return new NoPendingTaskFilter(dbSession, mainComponentUuids); } return t -> true; } private class NoPendingTaskFilter implements Predicate<CeTaskSubmit> { private final Map<String, Integer> queuedItemsByMainComponentUuid; private NoPendingTaskFilter(DbSession dbSession, Set<String> projectUuids) { queuedItemsByMainComponentUuid = dbClient.ceQueueDao().countByStatusAndEntityUuids(dbSession, PENDING, projectUuids); } @Override public boolean test(CeTaskSubmit ceTaskSubmit) { return ceTaskSubmit.getComponent() .map(component -> queuedItemsByMainComponentUuid.getOrDefault(component.getEntityUuid(), 0) == 0) .orElse(true); } } private static Set<SubmitOption> toSet(SubmitOption[] options) { return Arrays.stream(options).collect(Collectors.toSet()); } private void insertCharacteristics(DbSession dbSession, CeTaskSubmit submission) { for (Map.Entry<String, String> characteristic : submission.getCharacteristics().entrySet()) { CeTaskCharacteristicDto characteristicDto = new CeTaskCharacteristicDto(); characteristicDto.setUuid(uuidFactory.create()); characteristicDto.setTaskUuid(submission.getUuid()); characteristicDto.setKey(characteristic.getKey()); characteristicDto.setValue(characteristic.getValue()); dbClient.ceTaskCharacteristicsDao().insert(dbSession, characteristicDto); } } private CeQueueDto addToQueueInDb(DbSession dbSession, CeTaskSubmit submission) { insertCharacteristics(dbSession, submission); CeQueueDto dto = new CeQueueDto(); dto.setUuid(submission.getUuid()); dto.setTaskType(submission.getType()); submission.getComponent().ifPresent(component -> dto .setComponentUuid(component.getUuid()) .setEntityUuid(component.getEntityUuid())); dto.setStatus(PENDING); dto.setSubmitterUuid(submission.getSubmitterUuid()); dbClient.ceQueueDao().insert(dbSession, dto); return dto; } private List<CeTask> loadTasks(DbSession dbSession, List<CeQueueDto> dtos) { // load components, if defined Set<String> componentUuids = dtos.stream() .map(CeQueueDto::getComponentUuid) .filter(Objects::nonNull) .collect(Collectors.toSet()); // these components correspond to a branch or a portfolio (analysis target) Map<String, ComponentDto> componentsByUuid = dbClient.componentDao() .selectByUuids(dbSession, componentUuids).stream() .collect(Collectors.toMap(ComponentDto::uuid, Function.identity())); Set<String> entityUuids = dtos.stream().map(CeQueueDto::getEntityUuid).filter(Objects::nonNull).collect(Collectors.toSet()); Map<String, EntityDto> entitiesByUuid = dbClient.entityDao().selectByUuids(dbSession, entityUuids).stream() .collect(Collectors.toMap(EntityDto::getUuid, e -> e)); // load characteristics // TODO could be avoided, characteristics are already present in submissions Set<String> taskUuids = dtos.stream().map(CeQueueDto::getUuid).collect(Collectors.toSet()); Multimap<String, CeTaskCharacteristicDto> characteristicsByTaskUuid = dbClient.ceTaskCharacteristicsDao() .selectByTaskUuids(dbSession, taskUuids).stream() .collect(MoreCollectors.index(CeTaskCharacteristicDto::getTaskUuid)); List<CeTask> result = new ArrayList<>(); for (CeQueueDto dto : dtos) { ComponentDto component = ofNullable(dto.getComponentUuid()) .map(componentsByUuid::get) .orElse(null); EntityDto entity = ofNullable(dto.getEntityUuid()) .map(entitiesByUuid::get) .orElse(null); Map<String, String> characteristics = characteristicsByTaskUuid.get(dto.getUuid()).stream() .collect(Collectors.toMap(CeTaskCharacteristicDto::getKey, CeTaskCharacteristicDto::getValue)); result.add(convertToTask(dbSession, dto, characteristics, component, entity)); } return result; } @Override public void cancel(DbSession dbSession, CeQueueDto ceQueueDto) { checkState(PENDING.equals(ceQueueDto.getStatus()), "Task is in progress and can't be canceled [uuid=%s]", ceQueueDto.getUuid()); cancelImpl(dbSession, ceQueueDto); } private void cancelImpl(DbSession dbSession, CeQueueDto q) { CeActivityDto activityDto = new CeActivityDto(q); activityDto.setNodeName(nodeInformation.getNodeName().orElse(null)); activityDto.setStatus(CeActivityDto.Status.CANCELED); remove(dbSession, q, activityDto); } @Override public void fail(DbSession dbSession, CeQueueDto task, @Nullable String errorType, @Nullable String errorMessage) { checkState(IN_PROGRESS.equals(task.getStatus()), "Task is not in-progress and can't be marked as failed [uuid=%s]", task.getUuid()); CeActivityDto activityDto = new CeActivityDto(task); activityDto.setNodeName(nodeInformation.getNodeName().orElse(null)); activityDto.setStatus(CeActivityDto.Status.FAILED); activityDto.setErrorType(errorType); activityDto.setErrorMessage(errorMessage); updateExecutionFields(activityDto); remove(dbSession, task, activityDto); } protected long updateExecutionFields(CeActivityDto activityDto) { Long startedAt = activityDto.getStartedAt(); if (startedAt == null) { return 0L; } long now = system2.now(); long executionTimeInMs = now - startedAt; activityDto.setExecutedAt(now); activityDto.setExecutionTimeMs(executionTimeInMs); return executionTimeInMs; } protected void remove(DbSession dbSession, CeQueueDto queueDto, CeActivityDto activityDto) { String taskUuid = queueDto.getUuid(); CeQueueDto.Status expectedQueueDtoStatus = queueDto.getStatus(); dbClient.ceActivityDao().insert(dbSession, activityDto); dbClient.ceTaskInputDao().deleteByUuids(dbSession, singleton(taskUuid)); int deletedTasks = dbClient.ceQueueDao().deleteByUuid(dbSession, taskUuid, new DeleteIf(expectedQueueDtoStatus)); if (deletedTasks == 1) { dbSession.commit(); } else { LoggerFactory.getLogger(CeQueueImpl.class).debug( "Remove rolled back because task in queue with uuid {} and status {} could not be deleted", taskUuid, expectedQueueDtoStatus); dbSession.rollback(); } } @Override public int cancelAll() { return cancelAll(false); } int cancelAll(boolean includeInProgress) { int count = 0; try (DbSession dbSession = dbClient.openSession(false)) { for (CeQueueDto queueDto : dbClient.ceQueueDao().selectAllInAscOrder(dbSession)) { if (includeInProgress || !queueDto.getStatus().equals(IN_PROGRESS)) { cancelImpl(dbSession, queueDto); count++; } } return count; } } @Override public void pauseWorkers() { try (DbSession dbSession = dbClient.openSession(false)) { dbClient.internalPropertiesDao().save(dbSession, InternalProperties.COMPUTE_ENGINE_PAUSE, "true"); dbSession.commit(); } } @Override public void resumeWorkers() { try (DbSession dbSession = dbClient.openSession(false)) { dbClient.internalPropertiesDao().delete(dbSession, InternalProperties.COMPUTE_ENGINE_PAUSE); dbSession.commit(); } } @Override public WorkersPauseStatus getWorkersPauseStatus() { try (DbSession dbSession = dbClient.openSession(false)) { Optional<String> propValue = dbClient.internalPropertiesDao().selectByKey(dbSession, InternalProperties.COMPUTE_ENGINE_PAUSE); if (!propValue.isPresent() || !propValue.get().equals("true")) { return WorkersPauseStatus.RESUMED; } int countInProgress = dbClient.ceQueueDao().countByStatus(dbSession, IN_PROGRESS); if (countInProgress > 0) { return WorkersPauseStatus.PAUSING; } return WorkersPauseStatus.PAUSED; } } @Override public int clear() { return cancelAll(true); } CeTask convertToTask(DbSession dbSession, CeQueueDto taskDto, Map<String, String> characteristics, @Nullable ComponentDto component, @Nullable EntityDto entity) { CeTask.Builder builder = new CeTask.Builder() .setUuid(taskDto.getUuid()) .setType(taskDto.getTaskType()) .setCharacteristics(characteristics) .setSubmitter(resolveSubmitter(dbSession, taskDto.getSubmitterUuid())); String componentUuid = taskDto.getComponentUuid(); if (component != null) { builder.setComponent(new CeTask.Component(component.uuid(), component.getKey(), component.name())); } else if (componentUuid != null) { builder.setComponent(new CeTask.Component(componentUuid, null, null)); } String entityUuid = taskDto.getEntityUuid(); if (entity != null) { builder.setEntity(new CeTask.Component(entity.getUuid(), entity.getKey(), entity.getName())); } else if (entityUuid != null) { builder.setEntity(new CeTask.Component(entityUuid, null, null)); } return builder.build(); } @CheckForNull private CeTask.User resolveSubmitter(DbSession dbSession, @Nullable String submitterUuid) { if (submitterUuid == null) { return null; } UserDto submitterDto = dbClient.userDao().selectByUuid(dbSession, submitterUuid); if (submitterDto != null) { return new CeTask.User(submitterUuid, submitterDto.getLogin()); } else { return new CeTask.User(submitterUuid, null); } } }
15,878
38.207407
164
java
sonarqube
sonarqube-master/server/sonar-ce-common/src/main/java/org/sonar/ce/queue/CeTaskSubmit.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.queue; import java.util.Map; import java.util.Objects; import java.util.Optional; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import org.sonar.db.component.BranchDto; import org.sonar.db.portfolio.PortfolioDto; import static com.google.common.base.Strings.emptyToNull; import static com.google.common.base.Strings.nullToEmpty; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; @Immutable public final class CeTaskSubmit { private final String uuid; private final String type; private final Component component; private final String submitterUuid; private final Map<String, String> characteristics; private CeTaskSubmit(Builder builder) { this.uuid = requireNonNull(builder.uuid); this.type = requireNonNull(builder.type); this.component = builder.component; this.submitterUuid = builder.submitterUuid; this.characteristics = unmodifiableMap(builder.characteristics); } public String getType() { return type; } public String getUuid() { return uuid; } public Optional<Component> getComponent() { return Optional.ofNullable(component); } @CheckForNull public String getSubmitterUuid() { return submitterUuid; } public Map<String, String> getCharacteristics() { return characteristics; } public static final class Builder { private final String uuid; private String type; private Component component; private String submitterUuid; private Map<String, String> characteristics = null; public Builder(String uuid) { this.uuid = emptyToNull(uuid); } public String getUuid() { return uuid; } public Builder setType(String s) { this.type = emptyToNull(s); return this; } public Builder setComponent(@Nullable Component component) { this.component = component; return this; } public Builder setSubmitterUuid(@Nullable String s) { this.submitterUuid = s; return this; } public Builder setCharacteristics(Map<String, String> m) { this.characteristics = m; return this; } public CeTaskSubmit build() { requireNonNull(uuid, "uuid can't be null"); requireNonNull(type, "type can't be null"); requireNonNull(characteristics, "characteristics can't be null"); return new CeTaskSubmit(this); } } public static class Component { private final String uuid; private final String entityUuid; public Component(String uuid, String entityUuid) { this.uuid = requireNonNull(nullToEmpty(uuid), "uuid can't be null"); this.entityUuid = requireNonNull(nullToEmpty(entityUuid), "mainComponentUuid can't be null"); } public static Component fromDto(String componentUuid, String entityUuid) { return new Component(componentUuid, entityUuid); } public static Component fromDto(PortfolioDto dto) { return new Component(dto.getUuid(), dto.getUuid()); } public static Component fromDto(BranchDto dto) { return new Component(dto.getUuid(), dto.getProjectUuid()); } public String getUuid() { return uuid; } public String getEntityUuid() { return entityUuid; } @Override public String toString() { return "Component{" + "uuid='" + uuid + '\'' + ", entityUuid='" + entityUuid + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Component component = (Component) o; return uuid.equals(component.uuid) && entityUuid.equals(component.entityUuid); } @Override public int hashCode() { return Objects.hash(uuid, entityUuid); } } }
4,771
26.744186
99
java
sonarqube
sonarqube-master/server/sonar-ce-common/src/main/java/org/sonar/ce/queue/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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. */ @ParametersAreNonnullByDefault package org.sonar.ce.queue; import javax.annotation.ParametersAreNonnullByDefault;
958
38.958333
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/component/BranchPersisterImplIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.component; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Collections; import java.util.Optional; import javax.annotation.Nullable; import org.assertj.core.api.ThrowableAssert; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.config.internal.ConfigurationBridge; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.analysis.Branch; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.BranchDto; import org.sonar.db.component.BranchType; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.component.ProjectData; import org.sonar.db.protobuf.DbProjectBranches; import org.sonar.server.project.Project; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; import static org.sonar.core.config.PurgeConstants.BRANCHES_TO_KEEP_WHEN_INACTIVE; import static org.sonar.db.component.BranchType.BRANCH; import static org.sonar.db.component.BranchType.PULL_REQUEST; @RunWith(DataProviderRunner.class) public class BranchPersisterImplIT { private final static Component MAIN = builder(Component.Type.PROJECT, 1, "PROJECT_KEY").setUuid("PROJECT_UUID").setName("p1").build(); private final static Component BRANCH1 = builder(Component.Type.PROJECT, 2, "BRANCH_KEY").setUuid("BRANCH_UUID").build(); private final static Component PR1 = builder(Component.Type.PROJECT, 3, "develop").setUuid("PR_UUID").build(); private static final Project PROJECT = new Project("PROJECT_UUID", MAIN.getKey(), MAIN.getName(), null, Collections.emptyList()); @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); private final MapSettings settings = new MapSettings(); private final ConfigurationRepository configurationRepository = new TestSettingsRepository(new ConfigurationBridge(settings)); private final BranchPersister underTest = new BranchPersisterImpl(dbTester.getDbClient(), treeRootHolder, analysisMetadataHolder, configurationRepository); @Test public void persist_fails_with_ISE_if_no_component_for_main_branches() { analysisMetadataHolder.setBranch(createBranch(BRANCH, true, "master")); analysisMetadataHolder.setProject(PROJECT); treeRootHolder.setRoot(MAIN); DbSession dbSession = dbTester.getSession(); expectMissingComponentISE(() -> underTest.persist(dbSession)); } @Test public void persist_fails_with_ISE_if_no_component_for_branches() { analysisMetadataHolder.setBranch(createBranch(BRANCH, false, "foo")); analysisMetadataHolder.setProject(PROJECT); treeRootHolder.setRoot(BRANCH1); DbSession dbSession = dbTester.getSession(); expectMissingComponentISE(() -> underTest.persist(dbSession)); } @Test public void persist_fails_with_ISE_if_no_component_for_pull_request() { analysisMetadataHolder.setBranch(createBranch(BranchType.PULL_REQUEST, false, "12")); analysisMetadataHolder.setProject(PROJECT); treeRootHolder.setRoot(BRANCH1); DbSession dbSession = dbTester.getSession(); expectMissingComponentISE(() -> underTest.persist(dbSession)); } @Test @UseDataProvider("nullOrNotNullString") public void persist_creates_row_in_PROJECTS_BRANCHES_for_branch(@Nullable String mergeBranchUuid) { String branchName = "branch"; // add project and branch in table PROJECTS ComponentDto mainComponent = ComponentTesting.newPrivateProjectDto(MAIN.getUuid()).setKey(MAIN.getKey()); ComponentDto component = ComponentTesting.newBranchComponent(mainComponent, new BranchDto().setUuid(BRANCH1.getUuid()).setKey(BRANCH1.getKey()).setBranchType(BRANCH)); dbTester.components().insertComponents(mainComponent, component); // set project in metadata treeRootHolder.setRoot(BRANCH1); analysisMetadataHolder.setBranch(createBranch(BRANCH, false, branchName, mergeBranchUuid)); analysisMetadataHolder.setProject(Project.from(mainComponent)); underTest.persist(dbTester.getSession()); dbTester.getSession().commit(); assertThat(dbTester.countRowsOfTable("components")).isEqualTo(2); Optional<BranchDto> branchDto = dbTester.getDbClient().branchDao().selectByUuid(dbTester.getSession(), BRANCH1.getUuid()); assertThat(branchDto).isPresent(); assertThat(branchDto.get().getBranchType()).isEqualTo(BRANCH); assertThat(branchDto.get().getKey()).isEqualTo(branchName); assertThat(branchDto.get().getMergeBranchUuid()).isEqualTo(mergeBranchUuid); assertThat(branchDto.get().getProjectUuid()).isEqualTo(MAIN.getUuid()); assertThat(branchDto.get().getPullRequestData()).isNull(); } @Test public void main_branch_is_excluded_from_branch_purge_by_default() { analysisMetadataHolder.setBranch(createBranch(BRANCH, true, "master")); analysisMetadataHolder.setProject(PROJECT); treeRootHolder.setRoot(MAIN); dbTester.components().insertPublicProject(p -> p.setKey(MAIN.getKey()).setUuid(MAIN.getUuid())).getMainBranchComponent(); dbTester.commit(); underTest.persist(dbTester.getSession()); Optional<BranchDto> branchDto = dbTester.getDbClient().branchDao().selectByUuid(dbTester.getSession(), MAIN.getUuid()); assertThat(branchDto).isPresent(); assertThat(branchDto.get().isExcludeFromPurge()).isTrue(); } @Test public void non_main_branch_is_excluded_from_branch_purge_if_matches_sonar_dbcleaner_keepFromPurge_property() { settings.setProperty(BRANCHES_TO_KEEP_WHEN_INACTIVE, "BRANCH.*"); analysisMetadataHolder.setProject(PROJECT); analysisMetadataHolder.setBranch(createBranch(BRANCH, false, "BRANCH_KEY")); treeRootHolder.setRoot(BRANCH1); ComponentDto mainComponent = dbTester.components().insertPublicProject(p -> p.setKey(MAIN.getKey()).setUuid(MAIN.getUuid())).getMainBranchComponent(); ComponentDto component = ComponentTesting.newBranchComponent(mainComponent, new BranchDto().setUuid(BRANCH1.getUuid()).setKey(BRANCH1.getKey()).setBranchType(BRANCH)); dbTester.getDbClient().componentDao().insert(dbTester.getSession(), component, false); dbTester.commit(); underTest.persist(dbTester.getSession()); Optional<BranchDto> branchDto = dbTester.getDbClient().branchDao().selectByUuid(dbTester.getSession(), BRANCH1.getUuid()); assertThat(branchDto).isPresent(); assertThat(branchDto.get().isExcludeFromPurge()).isTrue(); } @Test public void branch_is_excluded_from_purge_when_it_matches_setting() { analysisMetadataHolder.setProject(PROJECT); analysisMetadataHolder.setBranch(createBranch(BRANCH, false, "BRANCH_KEY")); treeRootHolder.setRoot(BRANCH1); ComponentDto mainComponent = dbTester.components().insertPublicProject(p -> p.setKey(MAIN.getKey()).setUuid(MAIN.getUuid())).getMainBranchComponent(); ComponentDto component = ComponentTesting.newBranchComponent(mainComponent, new BranchDto().setUuid(BRANCH1.getUuid()).setKey(BRANCH1.getKey()).setBranchType(BRANCH)); dbTester.getDbClient().componentDao().insert(dbTester.getSession(), component, false); settings.setProperty(BRANCHES_TO_KEEP_WHEN_INACTIVE, "BRANCH.*"); dbTester.commit(); underTest.persist(dbTester.getSession()); Optional<BranchDto> branchDto = dbTester.getDbClient().branchDao().selectByUuid(dbTester.getSession(), BRANCH1.getUuid()); assertThat(branchDto).isPresent(); assertThat(branchDto.get().isExcludeFromPurge()).isTrue(); } @Test public void branch_is_not_excluded_from_purge_when_it_does_not_match_setting() { analysisMetadataHolder.setProject(PROJECT); analysisMetadataHolder.setBranch(createBranch(BRANCH, false, "BRANCH_KEY")); treeRootHolder.setRoot(BRANCH1); ComponentDto mainComponent = dbTester.components().insertPublicProject(p -> p.setKey(MAIN.getKey()).setUuid(MAIN.getUuid())).getMainBranchComponent(); ComponentDto component = ComponentTesting.newBranchComponent(mainComponent, new BranchDto().setUuid(BRANCH1.getUuid()).setKey(BRANCH1.getKey()).setBranchType(BRANCH)); dbTester.getDbClient().componentDao().insert(dbTester.getSession(), component, false); settings.setProperty(BRANCHES_TO_KEEP_WHEN_INACTIVE, "abc.*"); dbTester.commit(); underTest.persist(dbTester.getSession()); Optional<BranchDto> branchDto = dbTester.getDbClient().branchDao().selectByUuid(dbTester.getSession(), BRANCH1.getUuid()); assertThat(branchDto).isPresent(); assertThat(branchDto.get().isExcludeFromPurge()).isFalse(); } @Test public void pull_request_is_never_excluded_from_branch_purge_even_if_its_source_branch_name_matches_sonar_dbcleaner_keepFromPurge_property() { settings.setProperty(BRANCHES_TO_KEEP_WHEN_INACTIVE, "develop"); analysisMetadataHolder.setBranch(createPullRequest(PR1.getKey(), MAIN.getUuid())); analysisMetadataHolder.setProject(PROJECT); analysisMetadataHolder.setPullRequestKey(PR1.getKey()); treeRootHolder.setRoot(PR1); ComponentDto mainComponent = dbTester.components().insertPublicProject(p -> p.setKey(MAIN.getKey()).setUuid(MAIN.getUuid())).getMainBranchComponent(); ComponentDto component = ComponentTesting.newBranchComponent(mainComponent, new BranchDto() .setUuid(PR1.getUuid()) .setKey(PR1.getKey()) .setProjectUuid(MAIN.getUuid()) .setBranchType(PULL_REQUEST) .setMergeBranchUuid(MAIN.getUuid())); dbTester.getDbClient().componentDao().insert(dbTester.getSession(), component, false); dbTester.commit(); underTest.persist(dbTester.getSession()); Optional<BranchDto> branchDto = dbTester.getDbClient().branchDao().selectByUuid(dbTester.getSession(), PR1.getUuid()); assertThat(branchDto).isPresent(); assertThat(branchDto.get().isExcludeFromPurge()).isFalse(); } @Test public void non_main_branch_is_included_in_branch_purge_if_branch_name_does_not_match_sonar_dbcleaner_keepFromPurge_property() { settings.setProperty(BRANCHES_TO_KEEP_WHEN_INACTIVE, "foobar-.*"); analysisMetadataHolder.setProject(PROJECT); analysisMetadataHolder.setBranch(createBranch(BRANCH, false, "BRANCH_KEY")); treeRootHolder.setRoot(BRANCH1); ComponentDto mainComponent = dbTester.components().insertPublicProject(p -> p.setKey(MAIN.getKey()).setUuid(MAIN.getUuid())).getMainBranchComponent(); ComponentDto component = ComponentTesting.newBranchComponent(mainComponent, new BranchDto().setUuid(BRANCH1.getUuid()).setKey(BRANCH1.getKey()).setBranchType(BRANCH)); dbTester.getDbClient().componentDao().insert(dbTester.getSession(), component, false); dbTester.commit(); underTest.persist(dbTester.getSession()); Optional<BranchDto> branchDto = dbTester.getDbClient().branchDao().selectByUuid(dbTester.getSession(), BRANCH1.getUuid()); assertThat(branchDto).isPresent(); assertThat(branchDto.get().isExcludeFromPurge()).isFalse(); } @DataProvider public static Object[][] nullOrNotNullString() { return new Object[][] { {null}, {randomAlphabetic(12)} }; } @Test public void persist_creates_row_in_PROJECTS_BRANCHES_for_pull_request() { String pullRequestId = "pr-123"; // add project and branch in table PROJECTS ProjectData projectData = dbTester.components().insertPrivateProject(p -> p.setKey(MAIN.getKey()).setUuid(MAIN.getUuid())); ComponentDto mainComponent = projectData.getMainBranchComponent(); ComponentDto component = ComponentTesting.newBranchComponent(mainComponent, new BranchDto().setUuid(BRANCH1.getUuid()).setKey(BRANCH1.getKey()).setBranchType(PULL_REQUEST)); dbTester.components().insertComponents(component); // set project in metadata treeRootHolder.setRoot(BRANCH1); analysisMetadataHolder.setBranch(createBranch(PULL_REQUEST, false, pullRequestId, "mergeBanchUuid")); analysisMetadataHolder.setProject(Project.from(projectData.getProjectDto())); analysisMetadataHolder.setPullRequestKey(pullRequestId); underTest.persist(dbTester.getSession()); dbTester.getSession().commit(); assertThat(dbTester.countRowsOfTable("components")).isEqualTo(2); Optional<BranchDto> branchDto = dbTester.getDbClient().branchDao().selectByUuid(dbTester.getSession(), BRANCH1.getUuid()); assertThat(branchDto).isPresent(); assertThat(branchDto.get().getBranchType()).isEqualTo(PULL_REQUEST); assertThat(branchDto.get().getKey()).isEqualTo(pullRequestId); assertThat(branchDto.get().getMergeBranchUuid()).isEqualTo("mergeBanchUuid"); assertThat(branchDto.get().getProjectUuid()).isEqualTo(projectData.projectUuid()); assertThat(branchDto.get().getPullRequestData()).isEqualTo(DbProjectBranches.PullRequestData.newBuilder() .setBranch(pullRequestId) .setTarget("mergeBanchUuid") .setTitle(pullRequestId) .build()); } private static Branch createBranch(BranchType type, boolean isMain, String name) { return createBranch(type, isMain, name, null); } private static Branch createPullRequest(String key, String mergeBranchUuid) { Branch branch = createBranch(PULL_REQUEST, false, key, mergeBranchUuid); when(branch.getPullRequestKey()).thenReturn(key); return branch; } private static Branch createBranch(BranchType type, boolean isMain, String name, @Nullable String mergeBranchUuid) { Branch branch = mock(Branch.class); when(branch.getType()).thenReturn(type); when(branch.getName()).thenReturn(name); when(branch.isMain()).thenReturn(isMain); when(branch.getReferenceBranchUuid()).thenReturn(mergeBranchUuid); when(branch.getTargetBranchName()).thenReturn(mergeBranchUuid); return branch; } private void expectMissingComponentISE(ThrowableAssert.ThrowingCallable callable) { assertThatThrownBy(callable) .isInstanceOf(IllegalStateException.class) .hasMessage("Component has been deleted by end-user during analysis"); } }
15,537
47.404984
157
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/component/ComponentUuidFactoryImplIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.component; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.analysis.Branch; import org.sonar.db.DbTester; import org.sonar.db.component.BranchType; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.portfolio.PortfolioDto; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME; public class ComponentUuidFactoryImplIT { private final Branch mainBranch = new DefaultBranchImpl(DEFAULT_MAIN_BRANCH_NAME); private final Branch mockedBranch = mock(Branch.class); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Test public void getOrCreateForKey_when_existingComponentsInDbForMainBranch_should_load() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentUuidFactory underTest = new ComponentUuidFactoryImpl(db.getDbClient(), db.getSession(), project.getKey(), mainBranch); assertThat(underTest.getOrCreateForKey(project.getKey())).isEqualTo(project.uuid()); } @Test public void getOrCreateForKey_when_existingComponentsInDbForNonMainBranch_should_load() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("b1")); when(mockedBranch.getType()).thenReturn(BranchType.BRANCH); when(mockedBranch.isMain()).thenReturn(false); when(mockedBranch.getName()).thenReturn("b1"); ComponentUuidFactory underTest = new ComponentUuidFactoryImpl(db.getDbClient(), db.getSession(), project.getKey(), mockedBranch); assertThat(underTest.getOrCreateForKey(project.getKey())).isEqualTo(branch.uuid()); } @Test public void getOrCreateForKey_when_existingComponentsInDbForPr_should_load() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto pr = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST).setKey("pr1")); when(mockedBranch.getType()).thenReturn(BranchType.PULL_REQUEST); when(mockedBranch.isMain()).thenReturn(false); when(mockedBranch.getPullRequestKey()).thenReturn("pr1"); ComponentUuidFactory underTest = new ComponentUuidFactoryImpl(db.getDbClient(), db.getSession(), project.getKey(), mockedBranch); assertThat(underTest.getOrCreateForKey(project.getKey())).isEqualTo(pr.uuid()); } @Test public void getOrCreateForKey_when_componentsNotInDb_should_generate() { ComponentUuidFactory underTest = new ComponentUuidFactoryImpl(db.getDbClient(), db.getSession(), "theProjectKey", mainBranch); String generatedKey = underTest.getOrCreateForKey("foo"); assertThat(generatedKey).isNotEmpty(); // uuid is kept in memory for further calls with same key assertThat(underTest.getOrCreateForKey("foo")).isEqualTo(generatedKey); } @Test public void getOrCreateForKey_whenExistingComponentsInDbForPortfolioAndSubPortfolio_shouldLoadUuidsFromComponentTable() { ComponentDto portfolioDto = db.components().insertPublicPortfolio("pft1", p -> p.setKey("root_portfolio")); ComponentDto subView = db.components().insertSubView(portfolioDto, s -> s.setKey("sub_portfolio").setUuid("subPtf1")); ComponentUuidFactory underTest = new ComponentUuidFactoryImpl(db.getDbClient(), db.getSession(), portfolioDto.getKey(), mockedBranch); assertThat(underTest.getOrCreateForKey("root_portfolio")).isEqualTo(portfolioDto.uuid()); assertThat(underTest.getOrCreateForKey("sub_portfolio")).isEqualTo(subView.uuid()); } @Test public void getOrCreateForKey_whenNoExistingComponentsInDbForPortfolioAndSubPortfolio_shouldLoadUuidFromPortfolioTable() { PortfolioDto portfolioDto = ComponentTesting.newPortfolioDto("uuid_ptf1", "ptf1", "Portfolio1", null); db.getDbClient().portfolioDao().insert(db.getSession(), portfolioDto); PortfolioDto subPortfolio = ComponentTesting.newPortfolioDto("subPtf1", "sub_ptf_1", "portfolio", portfolioDto); db.getDbClient().portfolioDao().insert(db.getSession(), subPortfolio); ComponentUuidFactory underTest = new ComponentUuidFactoryImpl(db.getDbClient(), db.getSession(), portfolioDto.getKey()); assertThat(underTest.getOrCreateForKey("ptf1")).isEqualTo(portfolioDto.getUuid()); assertThat(underTest.getOrCreateForKey("sub_ptf_1")).isEqualTo(subPortfolio.getUuid()); } }
5,504
47.289474
138
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/component/ProjectPersisterIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.component; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.db.DbTester; import org.sonar.db.project.ProjectDto; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; import static org.sonar.ce.task.projectanalysis.component.Component.Type.VIEW; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; public class ProjectPersisterIT { private final static Component ROOT = builder(PROJECT, 1) .setUuid("PROJECT_UUID") .setKey("PROJECT_KEY") .setDescription("PROJECT_DESC") .setName("PROJECT_NAME") .build(); @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); public TestSystem2 system2 = new TestSystem2(); private ProjectPersister underTest = new ProjectPersister(dbTester.getDbClient(), treeRootHolder, system2); @Before public void prepare() { treeRootHolder.setRoot(ROOT); system2.setNow(1000L); } @Test public void skip_portfolios() { Component root = ViewsComponent.builder(VIEW, 1).build(); TreeRootHolder treeRootHolder = mock(TreeRootHolder.class); when(treeRootHolder.getRoot()).thenReturn(root); new ProjectPersister(dbTester.getDbClient(), treeRootHolder, system2).persist(dbTester.getSession()); verify(treeRootHolder).getRoot(); verifyNoMoreInteractions(treeRootHolder); } @Test public void update_description() { ProjectDto p1 = dbTester.components().insertPublicProject("PROJECT_UUID", p -> p.setKey(ROOT.getKey()).setName(ROOT.getName()).setDescription("OLD_DESC")).getProjectDto(); assertProject("OLD_DESC", ROOT.getName(), p1.getUpdatedAt()); underTest.persist(dbTester.getSession()); assertProject(ROOT.getDescription(), ROOT.getName(), 1000L); } @Test public void update_name() { ProjectDto p1 = dbTester.components().insertPublicProject("PROJECT_UUID", p -> p.setKey(ROOT.getKey()).setName("OLD_NAME").setDescription(ROOT.getDescription())).getProjectDto(); assertProject(ROOT.getDescription(), "OLD_NAME", p1.getUpdatedAt()); underTest.persist(dbTester.getSession()); assertProject(ROOT.getDescription(), ROOT.getName(), 1000L); } @Test public void dont_update() { ProjectDto p1 = dbTester.components().insertPublicProject( c -> c.setUuid("PROJECT_UUID").setKey(ROOT.getKey()).setName(ROOT.getName()).setDescription(ROOT.getDescription())).getProjectDto(); assertProject(ROOT.getDescription(), ROOT.getName(), p1.getUpdatedAt()); underTest.persist(dbTester.getSession()); assertProject(ROOT.getDescription(), ROOT.getName(), p1.getUpdatedAt()); } private void assertProject(String description, String name, long updated) { assertThat(dbTester.getDbClient().projectDao().selectProjectByKey(dbTester.getSession(), ROOT.getKey()).get()) .extracting(ProjectDto::getName, ProjectDto::getDescription, ProjectDto::getUpdatedAt) .containsExactly(name, description, updated); } }
4,466
38.883929
138
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/component/ReferenceBranchComponentUuidsIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.component; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.analysis.Branch; import org.sonar.db.DbTester; import org.sonar.db.component.BranchType; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.server.project.Project; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.component.SnapshotTesting.newAnalysis; public class ReferenceBranchComponentUuidsIT { @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); @Rule public DbTester db = DbTester.create(); private ReferenceBranchComponentUuids underTest; private Branch branch = mock(Branch.class); private ComponentDto branch1; private ComponentDto branch1File; private ComponentDto pr1File; private ComponentDto pr2File; private Project project; private ComponentDto pr1; private ComponentDto pr2; private ComponentDto branch2; private ComponentDto branch2File; @Before public void setUp() { underTest = new ReferenceBranchComponentUuids(analysisMetadataHolder, db.getDbClient()); project = mock(Project.class); analysisMetadataHolder.setProject(project); analysisMetadataHolder.setBranch(branch); ComponentDto projectDto = db.components().insertPublicProject().getMainBranchComponent(); when(project.getUuid()).thenReturn(projectDto.uuid()); branch1 = db.components().insertProjectBranch(projectDto, b -> b.setKey("branch1")); branch2 = db.components().insertProjectBranch(projectDto, b -> b.setKey("branch2")); pr1 = db.components().insertProjectBranch(projectDto, b -> b.setKey("pr1").setBranchType(BranchType.PULL_REQUEST).setMergeBranchUuid(branch1.uuid())); pr2 = db.components().insertProjectBranch(projectDto, b -> b.setKey("pr2").setBranchType(BranchType.PULL_REQUEST).setMergeBranchUuid(branch1.uuid())); branch1File = ComponentTesting.newFileDto(branch1, null, "file").setUuid("branch1File"); branch2File = ComponentTesting.newFileDto(branch2, null, "file").setUuid("branch2File"); pr1File = ComponentTesting.newFileDto(pr1, null, "file").setUuid("file1"); pr2File = ComponentTesting.newFileDto(pr2, null, "file").setUuid("file2"); db.components().insertComponents(branch1File, pr1File, pr2File, branch2File); } @Test public void should_support_db_key_when_looking_for_reference_component() { when(branch.getReferenceBranchUuid()).thenReturn(branch1.uuid()); when(branch.getType()).thenReturn(BranchType.PULL_REQUEST); when(branch.getTargetBranchName()).thenReturn("notAnalyzedBranch"); db.components().insertSnapshot(newAnalysis(branch1)); assertThat(underTest.getComponentUuid(pr1File.getKey())).isEqualTo(branch1File.uuid()); assertThat(underTest.hasReferenceBranchAnalysis()).isTrue(); assertThat(underTest.getReferenceBranchName()).isEqualTo("branch1"); } @Test public void should_support_key_when_looking_for_reference_component() { when(branch.getReferenceBranchUuid()).thenReturn(branch1.uuid()); when(branch.getType()).thenReturn(BranchType.PULL_REQUEST); when(branch.getTargetBranchName()).thenReturn("notAnalyzedBranch"); db.components().insertSnapshot(newAnalysis(branch1)); assertThat(underTest.getComponentUuid(pr1File.getKey())).isEqualTo(branch1File.uuid()); } @Test public void return_null_if_file_doesnt_exist() { when(branch.getReferenceBranchUuid()).thenReturn(branch1.uuid()); when(branch.getType()).thenReturn(BranchType.PULL_REQUEST); when(branch.getTargetBranchName()).thenReturn("notAnalyzedBranch"); db.components().insertSnapshot(newAnalysis(branch1)); assertThat(underTest.getComponentUuid("doesnt exist")).isNull(); } @Test public void skip_init_if_no_reference_branch_analysis() { when(branch.getReferenceBranchUuid()).thenReturn(branch1.uuid()); when(branch.getType()).thenReturn(BranchType.PULL_REQUEST); when(branch.getTargetBranchName()).thenReturn("notAnalyzedBranch"); assertThat(underTest.getComponentUuid(pr1File.getKey())).isNull(); } }
5,203
44.252174
154
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/component/SiblingComponentsWithOpenIssuesIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.component; import java.util.Collections; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.analysis.Branch; import org.sonar.db.DbTester; import org.sonar.db.component.BranchType; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.rule.RuleDto; import org.sonar.server.project.Project; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class SiblingComponentsWithOpenIssuesIT { @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public AnalysisMetadataHolderRule metadataHolder = new AnalysisMetadataHolderRule(); @Rule public DbTester db = DbTester.create(); private SiblingComponentsWithOpenIssues underTest; private ComponentDto branch1; private ComponentDto fileWithNoIssuesOnBranch1; private ComponentDto fileWithOneOpenIssueOnBranch1Pr1; private ComponentDto fileWithOneResolvedIssueOnBranch1Pr1; private ComponentDto fileWithOneOpenTwoResolvedIssuesOnBranch1Pr1; private ComponentDto fileXWithOneResolvedIssueOnBranch1Pr1; private ComponentDto fileXWithOneResolvedIssueOnBranch1Pr2; private ComponentDto branch2; private ComponentDto fileWithOneOpenIssueOnBranch2Pr1; private ComponentDto fileWithOneResolvedIssueOnBranch2Pr1; private ComponentDto branch1pr1; @Before public void setUp() { ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); metadataHolder.setProject(new Project(project.uuid(), project.getKey(), project.name(), project.description(), Collections.emptyList())); branch1 = db.components().insertProjectBranch(project, b -> b.setKey("branch1"), b -> b.setBranchType(BranchType.BRANCH)); branch1pr1 = db.components().insertProjectBranch(project, b -> b.setKey("branch1pr1"), b -> b.setBranchType(BranchType.PULL_REQUEST), b -> b.setMergeBranchUuid(branch1.uuid())); ComponentDto branch1pr2 = db.components().insertProjectBranch(project, b -> b.setKey("branch1pr2"), b -> b.setBranchType(BranchType.PULL_REQUEST), b -> b.setMergeBranchUuid(branch1.uuid())); fileWithNoIssuesOnBranch1 = db.components().insertComponent(ComponentTesting.newFileDto(branch1)); RuleDto rule = db.rules().insert(); fileWithOneOpenIssueOnBranch1Pr1 = db.components().insertComponent(ComponentTesting.newFileDto(branch1pr1)); db.issues().insert(rule, branch1pr1, fileWithOneOpenIssueOnBranch1Pr1); fileWithOneResolvedIssueOnBranch1Pr1 = db.components().insertComponent(ComponentTesting.newFileDto(branch1pr1)); db.issues().insert(rule, branch1pr1, fileWithOneResolvedIssueOnBranch1Pr1, i -> i.setStatus("RESOLVED")); fileWithOneOpenTwoResolvedIssuesOnBranch1Pr1 = db.components().insertComponent(ComponentTesting.newFileDto(branch1pr1)); db.issues().insert(rule, branch1pr1, fileWithOneOpenTwoResolvedIssuesOnBranch1Pr1); db.issues().insert(rule, branch1pr1, fileWithOneOpenTwoResolvedIssuesOnBranch1Pr1, i -> i.setStatus("RESOLVED")); String fileKey = "file-x"; fileXWithOneResolvedIssueOnBranch1Pr1 = db.components().insertComponent(ComponentTesting.newFileDto(branch1pr1) .setKey(fileKey)); db.issues().insert(rule, branch1pr1, fileXWithOneResolvedIssueOnBranch1Pr1, i -> i.setStatus("RESOLVED")); fileXWithOneResolvedIssueOnBranch1Pr2 = db.components().insertComponent(ComponentTesting.newFileDto(branch1pr2) .setKey(fileKey)); db.issues().insert(rule, branch1pr2, fileXWithOneResolvedIssueOnBranch1Pr2, i -> i.setStatus("RESOLVED")); branch2 = db.components().insertProjectBranch(project, b -> b.setKey("branch2"), b -> b.setBranchType(BranchType.BRANCH)); ComponentDto branch2pr1 = db.components().insertProjectBranch(project, b -> b.setKey("branch2pr1"), b -> b.setBranchType(BranchType.PULL_REQUEST), b -> b.setMergeBranchUuid(branch2.uuid())); fileWithOneOpenIssueOnBranch2Pr1 = db.components().insertComponent(ComponentTesting.newFileDto(branch2pr1)); db.issues().insert(rule, branch2pr1, fileWithOneOpenIssueOnBranch2Pr1); fileWithOneResolvedIssueOnBranch2Pr1 = db.components().insertComponent(ComponentTesting.newFileDto(branch2pr1)); db.issues().insert(rule, branch2pr1, fileWithOneResolvedIssueOnBranch2Pr1, i -> i.setStatus("RESOLVED")); setRoot(branch1); underTest = new SiblingComponentsWithOpenIssues(treeRootHolder, metadataHolder, db.getDbClient()); } @Test public void should_find_sibling_components_with_open_issues_for_branch1() { setRoot(branch1); setBranch(BranchType.BRANCH); assertThat(underTest.getUuids(fileWithNoIssuesOnBranch1.getKey())).isEmpty(); assertThat(underTest.getUuids(fileWithOneOpenIssueOnBranch1Pr1.getKey())).containsOnly(fileWithOneOpenIssueOnBranch1Pr1.uuid()); assertThat(underTest.getUuids(fileWithOneResolvedIssueOnBranch1Pr1.getKey())).containsOnly(fileWithOneResolvedIssueOnBranch1Pr1.uuid()); assertThat(underTest.getUuids(fileWithOneOpenTwoResolvedIssuesOnBranch1Pr1.getKey())).containsOnly(fileWithOneOpenTwoResolvedIssuesOnBranch1Pr1.uuid()); assertThat(fileXWithOneResolvedIssueOnBranch1Pr1.getKey()).isEqualTo(fileXWithOneResolvedIssueOnBranch1Pr2.getKey()); assertThat(underTest.getUuids(fileXWithOneResolvedIssueOnBranch1Pr1.getKey())).containsOnly( fileXWithOneResolvedIssueOnBranch1Pr1.uuid(), fileXWithOneResolvedIssueOnBranch1Pr2.uuid()); } @Test public void should_find_sibling_components_with_open_issues_for_pr1() { setRoot(branch1pr1); setBranch(BranchType.PULL_REQUEST, branch1.uuid()); assertThat(underTest.getUuids(fileWithNoIssuesOnBranch1.getKey())).isEmpty(); assertThat(underTest.getUuids(fileWithOneOpenIssueOnBranch1Pr1.getKey())).isEmpty(); assertThat(underTest.getUuids(fileWithOneResolvedIssueOnBranch1Pr1.getKey())).isEmpty(); assertThat(underTest.getUuids(fileWithOneOpenTwoResolvedIssuesOnBranch1Pr1.getKey())).isEmpty(); assertThat(underTest.getUuids(fileXWithOneResolvedIssueOnBranch1Pr1.getKey())).containsOnly(fileXWithOneResolvedIssueOnBranch1Pr2.uuid()); } @Test public void should_find_sibling_components_with_open_issues_for_branch2() { setRoot(branch2); setBranch(BranchType.BRANCH); underTest = new SiblingComponentsWithOpenIssues(treeRootHolder, metadataHolder, db.getDbClient()); assertThat(underTest.getUuids(fileWithOneResolvedIssueOnBranch1Pr1.getKey())).isEmpty(); assertThat(underTest.getUuids(fileWithOneResolvedIssueOnBranch2Pr1.getKey())).containsOnly(fileWithOneResolvedIssueOnBranch2Pr1.uuid()); assertThat(underTest.getUuids(fileWithOneOpenIssueOnBranch2Pr1.getKey())).containsOnly(fileWithOneOpenIssueOnBranch2Pr1.uuid()); } @Test public void should_find_sibling_components_with_open_issues_from_pullrequest() { ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); setRoot(project); setBranch(BranchType.BRANCH); ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST), b -> b.setMergeBranchUuid(project.uuid())); RuleDto rule = db.rules().insert(); ComponentDto fileWithResolvedIssueOnPullrequest = db.components().insertComponent(ComponentTesting.newFileDto(pullRequest)); db.issues().insert(rule, pullRequest, fileWithResolvedIssueOnPullrequest, i -> i.setStatus("RESOLVED")); underTest = new SiblingComponentsWithOpenIssues(treeRootHolder, metadataHolder, db.getDbClient()); assertThat(underTest.getUuids(fileWithResolvedIssueOnPullrequest.getKey())).hasSize(1); } @Test public void should_not_find_sibling_components_on_derived_branch() { ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); setRoot(project); setBranch(BranchType.BRANCH); ComponentDto derivedBranch = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH), b -> b.setMergeBranchUuid(project.uuid())); RuleDto rule = db.rules().insert(); ComponentDto fileWithResolvedIssueOnDerivedBranch = db.components().insertComponent(ComponentTesting.newFileDto(derivedBranch)); db.issues().insert(rule, derivedBranch, fileWithResolvedIssueOnDerivedBranch, i -> i.setStatus("RESOLVED")); underTest = new SiblingComponentsWithOpenIssues(treeRootHolder, metadataHolder, db.getDbClient()); assertThat(underTest.getUuids(fileWithResolvedIssueOnDerivedBranch.getKey())).isEmpty(); } private void setRoot(ComponentDto componentDto) { Component root = mock(Component.class); when(root.getUuid()).thenReturn(componentDto.uuid()); treeRootHolder.setRoot(root); } private void setBranch(BranchType currentBranchType) { setBranch(currentBranchType, null); } private void setBranch(BranchType currentBranchType, @Nullable String mergeBranchUuid) { Branch branch = mock(Branch.class); when(branch.getType()).thenReturn(currentBranchType); when(branch.getReferenceBranchUuid()).thenReturn(mergeBranchUuid); metadataHolder.setBranch(branch); } }
10,260
46.725581
156
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/filemove/FileMoveDetectionStepIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.filemove; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.IntStream; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.analysis.Analysis; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.FileAttributes; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.source.SourceLinesHashRepository; import org.sonar.ce.task.step.TestComputationStepContext; import org.sonar.core.hash.SourceLineHashesComputer; import org.sonar.core.util.Uuids; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.BranchType; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.source.FileSourceDto; import static java.util.Arrays.stream; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; import static org.sonar.ce.task.projectanalysis.filemove.FileMoveDetectionStep.MIN_REQUIRED_SCORE; import static org.sonar.db.component.BranchType.BRANCH; import static org.sonar.db.component.BranchType.PULL_REQUEST; public class FileMoveDetectionStepIT { private static final String SNAPSHOT_UUID = "uuid_1"; private static final Analysis ANALYSIS = new Analysis.Builder() .setUuid(SNAPSHOT_UUID) .setCreatedAt(86521) .build(); private static final int ROOT_REF = 1; private static final int FILE_1_REF = 2; private static final int FILE_2_REF = 3; private static final int FILE_3_REF = 4; private static final String[] CONTENT1 = { "package org.sonar.ce.task.projectanalysis.filemove;", "", "public class Foo {", " public String bar() {", " return \"Doh!\";", " }", "}" }; private static final String[] LESS_CONTENT1 = { "package org.sonar.ce.task.projectanalysis.filemove;", "", "public class Foo {", " public String foo() {", " return \"Donut!\";", " }", "}" }; private static final String[] CONTENT_EMPTY = { "" }; private static final String[] CONTENT2 = { "package org.sonar.ce.queue;", "", "import com.google.common.base.MoreObjects;", "import javax.annotation.CheckForNull;", "import javax.annotation.Nullable;", "import javax.annotation.concurrent.Immutable;", "", "import static com.google.common.base.Strings.emptyToNull;", "import static java.util.Objects.requireNonNull;", "", "@Immutable", "public class CeTask {", "", ", private final String type;", ", private final String uuid;", ", private final String componentUuid;", ", private final String componentKey;", ", private final String componentName;", ", private final String submitterLogin;", "", ", private CeTask(Builder builder) {", ", this.uuid = requireNonNull(emptyToNull(builder.uuid));", ", this.type = requireNonNull(emptyToNull(builder.type));", ", this.componentUuid = emptyToNull(builder.componentUuid);", ", this.componentKey = emptyToNull(builder.componentKey);", ", this.componentName = emptyToNull(builder.componentName);", ", this.submitterLogin = emptyToNull(builder.submitterLogin);", ", }", "", ", public String getUuid() {", ", return uuid;", ", }", "", ", public String getType() {", ", return type;", ", }", "", ", @CheckForNull", ", public String getComponentUuid() {", ", return componentUuid;", ", }", "", ", @CheckForNull", ", public String getComponentKey() {", ", return componentKey;", ", }", "", ", @CheckForNull", ", public String getComponentName() {", ", return componentName;", ", }", "", ", @CheckForNull", ", public String getSubmitterLogin() {", ", return submitterLogin;", ", }", ",}", }; // removed immutable annotation private static final String[] LESS_CONTENT2 = { "package org.sonar.ce.queue;", "", "import com.google.common.base.MoreObjects;", "import javax.annotation.CheckForNull;", "import javax.annotation.Nullable;", "", "import static com.google.common.base.Strings.emptyToNull;", "import static java.util.Objects.requireNonNull;", "", "public class CeTask {", "", ", private final String type;", ", private final String uuid;", ", private final String componentUuid;", ", private final String componentKey;", ", private final String componentName;", ", private final String submitterLogin;", "", ", private CeTask(Builder builder) {", ", this.uuid = requireNonNull(emptyToNull(builder.uuid));", ", this.type = requireNonNull(emptyToNull(builder.type));", ", this.componentUuid = emptyToNull(builder.componentUuid);", ", this.componentKey = emptyToNull(builder.componentKey);", ", this.componentName = emptyToNull(builder.componentName);", ", this.submitterLogin = emptyToNull(builder.submitterLogin);", ", }", "", ", public String getUuid() {", ", return uuid;", ", }", "", ", public String getType() {", ", return type;", ", }", "", ", @CheckForNull", ", public String getComponentUuid() {", ", return componentUuid;", ", }", "", ", @CheckForNull", ", public String getComponentKey() {", ", return componentKey;", ", }", "", ", @CheckForNull", ", public String getComponentName() {", ", return componentName;", ", }", "", ", @CheckForNull", ", public String getSubmitterLogin() {", ", return submitterLogin;", ", }", ",}", }; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MutableMovedFilesRepositoryRule movedFilesRepository = new MutableMovedFilesRepositoryRule(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule public LogTester logTester = new LogTester(); private final DbClient dbClient = dbTester.getDbClient(); private ComponentDto project; private final AnalysisMetadataHolderRule analysisMetadataHolder = mock(AnalysisMetadataHolderRule.class); private final SourceLinesHashRepository sourceLinesHash = mock(SourceLinesHashRepository.class); private final FileSimilarity fileSimilarity = new FileSimilarityImpl(new SourceSimilarityImpl()); private final CapturingScoreMatrixDumper scoreMatrixDumper = new CapturingScoreMatrixDumper(); private final RecordingMutableAddedFileRepository addedFileRepository = new RecordingMutableAddedFileRepository(); private final FileMoveDetectionStep underTest = new FileMoveDetectionStep(analysisMetadataHolder, treeRootHolder, dbClient, fileSimilarity, movedFilesRepository, sourceLinesHash, scoreMatrixDumper, addedFileRepository); @Before public void setUp() throws Exception { logTester.setLevel(Level.DEBUG); project = dbTester.components().insertPrivateProject().getMainBranchComponent(); treeRootHolder.setRoot(builder(Component.Type.PROJECT, ROOT_REF).setUuid(project.uuid()).build()); } @Test public void getDescription_returns_description() { assertThat(underTest.getDescription()).isEqualTo("Detect file moves"); } @Test public void execute_detects_no_move_if_in_pull_request_scope() { prepareAnalysis(PULL_REQUEST, ANALYSIS); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(movedFilesRepository.getComponentsWithOriginal()).isEmpty(); verifyStatistics(context, null, null, null, null); } @Test public void execute_detects_no_move_on_first_analysis() { prepareAnalysis(BRANCH, null); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(movedFilesRepository.getComponentsWithOriginal()).isEmpty(); verifyStatistics(context, 0, null, null, null); } @Test public void execute_detects_no_move_if_baseSnapshot_has_no_file_and_report_has_no_file() { prepareBranchAnalysis(ANALYSIS); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(movedFilesRepository.getComponentsWithOriginal()).isEmpty(); assertThat(addedFileRepository.getComponents()).isEmpty(); verifyStatistics(context, 0, null, null, null); } @Test public void execute_detects_no_move_if_baseSnapshot_has_no_file() { prepareBranchAnalysis(ANALYSIS); Component file1 = fileComponent(FILE_1_REF, null); Component file2 = fileComponent(FILE_2_REF, null); setFilesInReport(file1, file2); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(movedFilesRepository.getComponentsWithOriginal()).isEmpty(); assertThat(addedFileRepository.getComponents()).containsOnly(file1, file2); verifyStatistics(context, 2, 0, 2, null); } @Test public void execute_detects_no_move_if_there_is_no_file_in_report() { prepareBranchAnalysis(ANALYSIS); insertFiles( /* no components */); setFilesInReport(); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(movedFilesRepository.getComponentsWithOriginal()).isEmpty(); assertThat(addedFileRepository.getComponents()).isEmpty(); verifyStatistics(context, 0, null, null, null); } @Test public void execute_detects_no_move_if_file_key_exists_in_both_DB_and_report() { prepareBranchAnalysis(ANALYSIS); Component file1 = fileComponent(FILE_1_REF, null); Component file2 = fileComponent(FILE_2_REF, null); insertFiles(file1.getUuid(), file2.getUuid()); insertContentOfFileInDb(file1.getUuid(), CONTENT1); insertContentOfFileInDb(file2.getUuid(), CONTENT2); setFilesInReport(file2, file1); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(movedFilesRepository.getComponentsWithOriginal()).isEmpty(); assertThat(addedFileRepository.getComponents()).isEmpty(); verifyStatistics(context, 2, 2, 0, null); } @Test public void execute_detects_move_if_content_of_file_is_same_in_DB_and_report() { prepareBranchAnalysis(ANALYSIS); Component file1 = fileComponent(FILE_1_REF, null); Component file2 = fileComponent(FILE_2_REF, CONTENT1); ComponentDto[] dtos = insertFiles(file1.getUuid()); insertContentOfFileInDb(file1.getUuid(), CONTENT1); setFilesInReport(file2); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(movedFilesRepository.getComponentsWithOriginal()).containsExactly(file2); MovedFilesRepository.OriginalFile originalFile = movedFilesRepository.getOriginalFile(file2).get(); assertThat(originalFile.key()).isEqualTo(dtos[0].getKey()); assertThat(originalFile.uuid()).isEqualTo(dtos[0].uuid()); assertThat(addedFileRepository.getComponents()).isEmpty(); verifyStatistics(context, 1, 1, 1, 1); } @Test public void execute_detects_no_move_if_content_of_file_is_not_similar_enough() { prepareBranchAnalysis(ANALYSIS); Component file1 = fileComponent(FILE_1_REF, null); Component file2 = fileComponent(FILE_2_REF, LESS_CONTENT1); insertFiles(file1.getKey()); insertContentOfFileInDb(file1.getKey(), CONTENT1); setFilesInReport(file2); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(movedFilesRepository.getComponentsWithOriginal()).isEmpty(); assertThat(scoreMatrixDumper.scoreMatrix.getMaxScore()) .isPositive() .isLessThan(MIN_REQUIRED_SCORE); assertThat(addedFileRepository.getComponents()).contains(file2); verifyStatistics(context, 1, 1, 1, 0); } @Test public void execute_detects_no_move_if_content_of_file_is_empty_in_DB() { prepareBranchAnalysis(ANALYSIS); Component file1 = fileComponent(FILE_1_REF, null); Component file2 = fileComponent(FILE_2_REF, CONTENT1); insertFiles(file1.getKey()); insertContentOfFileInDb(file1.getKey(), CONTENT_EMPTY); setFilesInReport(file2); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(movedFilesRepository.getComponentsWithOriginal()).isEmpty(); assertThat(scoreMatrixDumper.scoreMatrix.getMaxScore()).isZero(); assertThat(addedFileRepository.getComponents()).contains(file2); verifyStatistics(context, 1, 1, 1, 0); } @Test public void execute_detects_no_move_if_content_of_file_has_no_path_in_DB() { prepareBranchAnalysis(ANALYSIS); Component file1 = fileComponent(FILE_1_REF, null); Component file2 = fileComponent(FILE_2_REF, CONTENT1); insertFiles(key -> newComponentDto(key).setPath(null), file1.getKey()); insertContentOfFileInDb(file1.getKey(), CONTENT1); setFilesInReport(file2); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(movedFilesRepository.getComponentsWithOriginal()).isEmpty(); assertThat(scoreMatrixDumper.scoreMatrix).isNull(); assertThat(addedFileRepository.getComponents()).containsOnly(file2); verifyStatistics(context, 1, 0, 1, null); } @Test public void execute_detects_no_move_if_content_of_file_is_empty_in_report() { prepareBranchAnalysis(ANALYSIS); Component file1 = fileComponent(FILE_1_REF, null); Component file2 = fileComponent(FILE_2_REF, CONTENT_EMPTY); insertFiles(file1.getKey()); insertContentOfFileInDb(file1.getKey(), CONTENT1); setFilesInReport(file2); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(movedFilesRepository.getComponentsWithOriginal()).isEmpty(); assertThat(scoreMatrixDumper.scoreMatrix.getMaxScore()).isZero(); assertThat(addedFileRepository.getComponents()).contains(file2); verifyStatistics(context, 1, 1, 1, 0); assertThat(logTester.logs(Level.DEBUG)).contains("max score in matrix is less than min required score (85). Do nothing."); } @Test public void execute_detects_no_move_if_two_added_files_have_same_content_as_the_one_in_db() { prepareBranchAnalysis(ANALYSIS); Component file1 = fileComponent(FILE_1_REF, null); Component file2 = fileComponent(FILE_2_REF, CONTENT1); Component file3 = fileComponent(FILE_3_REF, CONTENT1); insertFiles(file1.getKey()); insertContentOfFileInDb(file1.getKey(), CONTENT1); setFilesInReport(file2, file3); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(movedFilesRepository.getComponentsWithOriginal()).isEmpty(); assertThat(scoreMatrixDumper.scoreMatrix.getMaxScore()).isEqualTo(100); assertThat(addedFileRepository.getComponents()).containsOnly(file2, file3); verifyStatistics(context, 2, 1, 2, 0); } @Test public void execute_detects_no_move_if_two_deleted_files_have_same_content_as_the_one_added() { prepareBranchAnalysis(ANALYSIS); Component file1 = fileComponent(FILE_1_REF, null); Component file2 = fileComponent(FILE_2_REF, null); Component file3 = fileComponent(FILE_3_REF, CONTENT1); insertFiles(file1.getUuid(), file2.getUuid()); insertContentOfFileInDb(file1.getUuid(), CONTENT1); insertContentOfFileInDb(file2.getUuid(), CONTENT1); setFilesInReport(file3); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(movedFilesRepository.getComponentsWithOriginal()).isEmpty(); assertThat(scoreMatrixDumper.scoreMatrix.getMaxScore()).isEqualTo(100); assertThat(addedFileRepository.getComponents()).containsOnly(file3); verifyStatistics(context, 1, 2, 1, 0); } @Test public void execute_detects_no_move_if_two_files_are_empty_in_DB() { prepareBranchAnalysis(ANALYSIS); Component file1 = fileComponent(FILE_1_REF, null); Component file2 = fileComponent(FILE_2_REF, null); insertFiles(file1.getUuid(), file2.getUuid()); insertContentOfFileInDb(file1.getUuid(), null); insertContentOfFileInDb(file2.getUuid(), null); setFilesInReport(file1, file2); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(movedFilesRepository.getComponentsWithOriginal()).isEmpty(); assertThat(scoreMatrixDumper.scoreMatrix).isNull(); assertThat(addedFileRepository.getComponents()).isEmpty(); verifyStatistics(context, 2, 2, 0, null); } @Test public void execute_detects_several_moves() { // testing: // - file1 renamed to file3 // - file2 deleted // - file4 untouched // - file5 renamed to file6 with a small change prepareBranchAnalysis(ANALYSIS); Component file1 = fileComponent(FILE_1_REF, null); Component file2 = fileComponent(FILE_2_REF, null); Component file3 = fileComponent(FILE_3_REF, CONTENT1); Component file4 = fileComponent(5, new String[] {"a", "b"}); Component file5 = fileComponent(6, null); Component file6 = fileComponent(7, LESS_CONTENT2); ComponentDto[] dtos = insertFiles(file1.getUuid(), file2.getUuid(), file4.getUuid(), file5.getUuid()); insertContentOfFileInDb(file1.getUuid(), CONTENT1); insertContentOfFileInDb(file2.getUuid(), LESS_CONTENT1); insertContentOfFileInDb(file4.getUuid(), new String[] {"e", "f", "g", "h", "i"}); insertContentOfFileInDb(file5.getUuid(), CONTENT2); setFilesInReport(file3, file4, file6); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(movedFilesRepository.getComponentsWithOriginal()).containsOnly(file3, file6); MovedFilesRepository.OriginalFile originalFile2 = movedFilesRepository.getOriginalFile(file3).get(); assertThat(originalFile2.key()).isEqualTo(dtos[0].getKey()); assertThat(originalFile2.uuid()).isEqualTo(dtos[0].uuid()); MovedFilesRepository.OriginalFile originalFile5 = movedFilesRepository.getOriginalFile(file6).get(); assertThat(originalFile5.key()).isEqualTo(dtos[3].getKey()); assertThat(originalFile5.uuid()).isEqualTo(dtos[3].uuid()); assertThat(scoreMatrixDumper.scoreMatrix.getMaxScore()).isGreaterThan(MIN_REQUIRED_SCORE); assertThat(addedFileRepository.getComponents()).isEmpty(); verifyStatistics(context, 3, 4, 2, 2); } @Test public void execute_does_not_compute_any_distance_if_all_files_sizes_are_all_too_different() { prepareBranchAnalysis(ANALYSIS); Component file1 = fileComponent(FILE_1_REF, null); Component file2 = fileComponent(FILE_2_REF, null); Component file3 = fileComponent(FILE_3_REF, arrayOf(118)); Component file4 = fileComponent(5, arrayOf(25)); insertFiles(file1.getKey(), file2.getKey()); insertContentOfFileInDb(file1.getKey(), arrayOf(100)); insertContentOfFileInDb(file2.getKey(), arrayOf(30)); setFilesInReport(file3, file4); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(movedFilesRepository.getComponentsWithOriginal()).isEmpty(); assertThat(scoreMatrixDumper.scoreMatrix.getMaxScore()).isZero(); verifyStatistics(context, 2, 2, 2, 0); } /** * Creates an array of {@code numberOfElements} int values as String, starting with zero. */ private static String[] arrayOf(int numberOfElements) { return IntStream.range(0, numberOfElements).mapToObj(String::valueOf).toArray(String[]::new); } /** * JH: A bug was encountered in the algorithm and I didn't manage to forge a simpler test case. */ @Test public void real_life_use_case() throws Exception { prepareBranchAnalysis(ANALYSIS); for (File f : FileUtils.listFiles(new File("src/it/resources/org/sonar/ce/task/projectanalysis/filemove/FileMoveDetectionStepIT/v1"), null, false)) { insertFiles("uuid_" + f.getName().hashCode()); insertContentOfFileInDb("uuid_" + f.getName().hashCode(), readLines(f)); } Map<String, Component> comps = new HashMap<>(); int i = 1; for (File f : FileUtils.listFiles(new File("src/it/resources/org/sonar/ce/task/projectanalysis/filemove/FileMoveDetectionStepIT/v2"), null, false)) { String[] lines = readLines(f); Component c = builder(Component.Type.FILE, i++) .setUuid("uuid_" + f.getName().hashCode()) .setKey(f.getName()) .setName(f.getName()) .setFileAttributes(new FileAttributes(false, null, lines.length)) .build(); comps.put(f.getName(), c); setFileLineHashesInReport(c, lines); } setFilesInReport(comps.values().toArray(new Component[0])); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); Component makeComponentUuidAndAnalysisUuidNotNullOnDuplicationsIndex = comps.get("MakeComponentUuidAndAnalysisUuidNotNullOnDuplicationsIndex.java"); Component migrationRb1238 = comps.get("1238_make_component_uuid_and_analysis_uuid_not_null_on_duplications_index.rb"); Component addComponentUuidAndAnalysisUuidColumnToDuplicationsIndex = comps.get("AddComponentUuidAndAnalysisUuidColumnToDuplicationsIndex.java"); assertThat(movedFilesRepository.getComponentsWithOriginal()).containsOnly( makeComponentUuidAndAnalysisUuidNotNullOnDuplicationsIndex, migrationRb1238, addComponentUuidAndAnalysisUuidColumnToDuplicationsIndex); assertThat(movedFilesRepository.getOriginalFile(makeComponentUuidAndAnalysisUuidNotNullOnDuplicationsIndex).get().uuid()) .isEqualTo("uuid_" + "MakeComponentUuidNotNullOnDuplicationsIndex.java".hashCode()); assertThat(movedFilesRepository.getOriginalFile(migrationRb1238).get().uuid()) .isEqualTo("uuid_" + "1242_make_analysis_uuid_not_null_on_duplications_index.rb".hashCode()); assertThat(movedFilesRepository.getOriginalFile(addComponentUuidAndAnalysisUuidColumnToDuplicationsIndex).get().uuid()) .isEqualTo("uuid_" + "AddComponentUuidColumnToDuplicationsIndex.java".hashCode()); verifyStatistics(context, comps.values().size(), 12, 6, 3); } private String[] readLines(File filename) throws IOException { return FileUtils .readLines(filename, StandardCharsets.UTF_8) .toArray(new String[0]); } @CheckForNull private FileSourceDto insertContentOfFileInDb(String uuid, @Nullable String[] content) { return dbTester.getDbClient().componentDao().selectByUuid(dbTester.getSession(), uuid) .map(file -> { SourceLineHashesComputer linesHashesComputer = new SourceLineHashesComputer(); if (content != null) { stream(content).forEach(linesHashesComputer::addLine); } FileSourceDto fileSourceDto = new FileSourceDto() .setUuid(Uuids.createFast()) .setFileUuid(file.uuid()) .setProjectUuid(file.branchUuid()) .setLineHashes(linesHashesComputer.getLineHashes()); dbTester.getDbClient().fileSourceDao().insert(dbTester.getSession(), fileSourceDto); dbTester.commit(); return fileSourceDto; }).orElse(null); } private void setFilesInReport(Component... files) { treeRootHolder.setRoot(builder(Component.Type.PROJECT, ROOT_REF) .setUuid(project.uuid()) .addChildren(files) .build()); } private ComponentDto[] insertFiles(String... uuids) { return insertFiles(this::newComponentDto, uuids); } private ComponentDto[] insertFiles(Function<String, ComponentDto> newComponentDto, String... uuids) { return stream(uuids) .map(newComponentDto) .map(dto -> dbTester.components().insertComponent(dto)) .toArray(ComponentDto[]::new); } private ComponentDto newComponentDto(String uuid) { return ComponentTesting.newFileDto(project) .setKey("key_" + uuid) .setUuid(uuid) .setPath("path_" + uuid); } private Component fileComponent(int ref, @Nullable String[] content) { ReportComponent component = builder(Component.Type.FILE, ref) .setName("report_path" + ref) .setFileAttributes(new FileAttributes(false, null, content == null ? 1 : content.length)) .build(); if (content != null) { setFileLineHashesInReport(component, content); } return component; } private void setFileLineHashesInReport(Component file, String[] content) { SourceLineHashesComputer computer = new SourceLineHashesComputer(); for (String line : content) { computer.addLine(line); } when(sourceLinesHash.getLineHashesMatchingDBVersion(file)).thenReturn(computer.getLineHashes()); } private static class CapturingScoreMatrixDumper implements ScoreMatrixDumper { private ScoreMatrix scoreMatrix; @Override public void dumpAsCsv(ScoreMatrix scoreMatrix) { this.scoreMatrix = scoreMatrix; } } private void prepareBranchAnalysis(Analysis analysis) { prepareAnalysis(BRANCH, analysis); } private void prepareAnalysis(BranchType branch, Analysis analysis) { mockBranchType(branch); analysisMetadataHolder.setBaseAnalysis(analysis); } private void mockBranchType(BranchType branchType) { when(analysisMetadataHolder.isPullRequest()).thenReturn(branchType == PULL_REQUEST); } public static void verifyStatistics(TestComputationStepContext context, @Nullable Integer expectedReportFiles, @Nullable Integer expectedDbFiles, @Nullable Integer expectedAddedFiles, @Nullable Integer expectedMovedFiles) { context.getStatistics().assertValue("reportFiles", expectedReportFiles); context.getStatistics().assertValue("dbFiles", expectedDbFiles); context.getStatistics().assertValue("addedFiles", expectedAddedFiles); context.getStatistics().assertValue("movedFiles", expectedMovedFiles); } public static class RecordingMutableAddedFileRepository implements MutableAddedFileRepository { private final List<Component> components = new ArrayList<>(); @Override public void register(Component file) { components.add(file); } @Override public boolean isAdded(Component component) { throw new UnsupportedOperationException("isAdded should not be called"); } public List<Component> getComponents() { return components; } } }
28,270
38.650771
153
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/filemove/PullRequestFileMoveDetectionStepIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.filemove; import java.util.Map; import java.util.Optional; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.System2; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.ce.task.projectanalysis.analysis.Analysis; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.analysis.Branch; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.FileAttributes; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.filemove.FileMoveDetectionStepIT.RecordingMutableAddedFileRepository; import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository.OriginalFile; import org.sonar.ce.task.step.TestComputationStepContext; import org.sonar.core.util.Uuids; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.BranchType; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.component.ProjectData; import org.sonar.db.project.ProjectDto; import org.sonar.db.source.FileSourceDto; import org.sonar.server.project.Project; import static java.util.function.Function.identity; import static java.util.stream.Collectors.toMap; import static java.util.stream.Collectors.toSet; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; import static org.sonar.ce.task.projectanalysis.filemove.FileMoveDetectionStepIT.verifyStatistics; import static org.sonar.db.component.BranchType.BRANCH; import static org.sonar.db.component.BranchType.PULL_REQUEST; public class PullRequestFileMoveDetectionStepIT { private static final String ROOT_REF = "0"; private static final String FILE_1_REF = "1"; private static final String FILE_2_REF = "2"; private static final String FILE_3_REF = "3"; private static final String FILE_4_REF = "4"; private static final String FILE_5_REF = "5"; private static final String FILE_6_REF = "6"; private static final String FILE_7_REF = "7"; private static final String TARGET_BRANCH = "target_branch"; private static final String BRANCH_UUID = "branch_uuid"; private static final String SNAPSHOT_UUID = "uuid_1"; private static final Analysis ANALYSIS = new Analysis.Builder() .setUuid(SNAPSHOT_UUID) .setCreatedAt(86521) .build(); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MutableMovedFilesRepositoryRule movedFilesRepository = new MutableMovedFilesRepositoryRule(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule public LogTester logTester = new LogTester(); private ComponentDto branch; private ComponentDto mainBranch; private ProjectDto project; private final DbClient dbClient = dbTester.getDbClient(); private final AnalysisMetadataHolderRule analysisMetadataHolder = mock(AnalysisMetadataHolderRule.class); private final RecordingMutableAddedFileRepository addedFileRepository = new RecordingMutableAddedFileRepository(); private final PullRequestFileMoveDetectionStep underTest = new PullRequestFileMoveDetectionStep(analysisMetadataHolder, treeRootHolder, dbClient, movedFilesRepository, addedFileRepository); @Before public void setUp() throws Exception { ProjectData projectData = dbTester.components().insertPrivateProject(); mainBranch = projectData.getMainBranchComponent(); project = projectData.getProjectDto(); branch = dbTester.components().insertProjectBranch(mainBranch, branchDto -> branchDto.setUuid(BRANCH_UUID).setKey(TARGET_BRANCH)); treeRootHolder.setRoot(builder(Component.Type.PROJECT, Integer.parseInt(ROOT_REF)).setUuid(mainBranch.uuid()).build()); } @Test public void getDescription_returns_description() { assertThat(underTest.getDescription()).isEqualTo("Detect file moves in Pull Request scope"); } @Test public void execute_does_not_detect_any_files_if_not_in_pull_request_scope() { prepareAnalysis(BRANCH, ANALYSIS); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(movedFilesRepository.getComponentsWithOriginal()).isEmpty(); verifyStatistics(context, null, null, null, null); } @Test public void execute_detects_no_move_if_report_has_no_file() { preparePullRequestAnalysis(ANALYSIS); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(movedFilesRepository.getComponentsWithOriginal()).isEmpty(); assertThat(addedFileRepository.getComponents()).isEmpty(); verifyStatistics(context, 0, null, null, null); } @Test public void execute_detects_no_move_if_target_branch_has_no_files() { preparePullRequestAnalysis(ANALYSIS); Set<FileReference> fileReferences = Set.of(FileReference.of(FILE_1_REF), FileReference.of(FILE_2_REF)); Map<String, Component> reportFilesByUuid = initializeAnalysisReportComponents(fileReferences); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(movedFilesRepository.getComponentsWithOriginal()).isEmpty(); assertThat(addedFileRepository.getComponents()).containsOnlyOnceElementsOf(reportFilesByUuid.values()); verifyStatistics(context, 2, 0, 2, null); } @Test public void execute_detects_no_move_if_there_are_no_files_in_report() { preparePullRequestAnalysis(ANALYSIS); initializeAnalysisReportComponents(Set.of()); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(movedFilesRepository.getComponentsWithOriginal()).isEmpty(); assertThat(addedFileRepository.getComponents()).isEmpty(); verifyStatistics(context, 0, null, null, null); } @Test public void execute_detects_no_move_if_file_key_exists_in_both_database_and_report() { preparePullRequestAnalysis(ANALYSIS); Set<FileReference> fileReferences = Set.of(FileReference.of(FILE_1_REF), FileReference.of(FILE_2_REF)); initializeAnalysisReportComponents(fileReferences); initializeTargetBranchDatabaseComponents(fileReferences); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(movedFilesRepository.getComponentsWithOriginal()).isEmpty(); assertThat(addedFileRepository.getComponents()).isEmpty(); verifyStatistics(context, 2, 2, 0, 0); } @Test public void execute_detects_renamed_file() { // - FILE_1_REF on target branch is renamed to FILE_2_REF on Pull Request preparePullRequestAnalysis(ANALYSIS); Set<FileReference> reportFileReferences = Set.of(FileReference.of(FILE_2_REF, FILE_1_REF)); Set<FileReference> databaseFileReferences = Set.of(FileReference.of(FILE_1_REF)); Map<String, Component> reportFilesByUuid = initializeAnalysisReportComponents(reportFileReferences); Map<String, Component> databaseFilesByUuid = initializeTargetBranchDatabaseComponents(databaseFileReferences); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(addedFileRepository.getComponents()).isEmpty(); assertThat(movedFilesRepository.getComponentsWithOriginal()).hasSize(1); assertThatFileRenameHasBeenDetected(reportFilesByUuid, databaseFilesByUuid, FILE_2_REF, FILE_1_REF); verifyStatistics(context, 1, 1, 0, 1); } @Test public void execute_detects_several_renamed_file() { // - FILE_1_REF has been renamed to FILE_3_REF on Pull Request // - FILE_2_REF has been deleted on Pull Request // - FILE_4_REF has been left untouched // - FILE_5_REF has been renamed to FILE_6_REF on Pull Request // - FILE_7_REF has been added on Pull Request preparePullRequestAnalysis(ANALYSIS); Set<FileReference> reportFileReferences = Set.of( FileReference.of(FILE_3_REF, FILE_1_REF), FileReference.of(FILE_4_REF), FileReference.of(FILE_6_REF, FILE_5_REF), FileReference.of(FILE_7_REF)); Set<FileReference> databaseFileReferences = Set.of( FileReference.of(FILE_1_REF), FileReference.of(FILE_2_REF), FileReference.of(FILE_4_REF), FileReference.of(FILE_5_REF)); Map<String, Component> reportFilesByUuid = initializeAnalysisReportComponents(reportFileReferences); Map<String, Component> databaseFilesByUuid = initializeTargetBranchDatabaseComponents(databaseFileReferences); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertThat(addedFileRepository.getComponents()).hasSize(1); assertThat(movedFilesRepository.getComponentsWithOriginal()).hasSize(2); assertThatFileAdditionHasBeenDetected(reportFilesByUuid, FILE_7_REF); assertThatFileRenameHasBeenDetected(reportFilesByUuid, databaseFilesByUuid, FILE_3_REF, FILE_1_REF); assertThatFileRenameHasBeenDetected(reportFilesByUuid, databaseFilesByUuid, FILE_6_REF, FILE_5_REF); verifyStatistics(context, 4, 4, 1, 2); } private void assertThatFileAdditionHasBeenDetected(Map<String, Component> reportFilesByUuid, String fileInReportReference) { Component fileInReport = reportFilesByUuid.get(fileInReportReference); assertThat(addedFileRepository.getComponents()).contains(fileInReport); assertThat(movedFilesRepository.getOriginalPullRequestFile(fileInReport)).isEmpty(); } private void assertThatFileRenameHasBeenDetected(Map<String, Component> reportFilesByUuid, Map<String, Component> databaseFilesByUuid, String fileInReportReference, String originalFileInDatabaseReference) { Component fileInReport = reportFilesByUuid.get(fileInReportReference); Component originalFileInDatabase = databaseFilesByUuid.get(originalFileInDatabaseReference); assertThat(movedFilesRepository.getComponentsWithOriginal()).contains(fileInReport); assertThat(movedFilesRepository.getOriginalPullRequestFile(fileInReport)).isPresent(); OriginalFile detectedOriginalFile = movedFilesRepository.getOriginalPullRequestFile(fileInReport).get(); assertThat(detectedOriginalFile.key()).isEqualTo(originalFileInDatabase.getKey()); assertThat(detectedOriginalFile.uuid()).isEqualTo(originalFileInDatabase.getUuid()); } private Map<String, Component> initializeTargetBranchDatabaseComponents(Set<FileReference> references) { Set<Component> fileComponents = createFileComponents(references); insertFileComponentsInDatabase(fileComponents); return toFileComponentsByUuidMap(fileComponents); } private Map<String, Component> initializeAnalysisReportComponents(Set<FileReference> refs) { Set<Component> fileComponents = createFileComponents(refs); insertFileComponentsInReport(fileComponents); return toFileComponentsByUuidMap(fileComponents); } private Map<String, Component> toFileComponentsByUuidMap(Set<Component> fileComponents) { return fileComponents .stream() .collect(toMap(Component::getUuid, identity())); } private static Set<Component> createFileComponents(Set<FileReference> references) { return references .stream() .map(PullRequestFileMoveDetectionStepIT::createReportFileComponent) .collect(toSet()); } private static Component createReportFileComponent(FileReference fileReference) { return builder(FILE, Integer.parseInt(fileReference.getReference())) .setUuid(fileReference.getReference()) .setName("report_path" + fileReference.getReference()) .setFileAttributes(new FileAttributes(false, null, 1, false, composeComponentPath(fileReference.getPastReference()))) .build(); } private void insertFileComponentsInReport(Set<Component> files) { treeRootHolder .setRoot(builder(PROJECT, Integer.parseInt(ROOT_REF)) .setUuid(mainBranch.uuid()) .addChildren(files.toArray(Component[]::new)) .build()); } private Set<ComponentDto> insertFileComponentsInDatabase(Set<Component> files) { return files .stream() .map(Component::getUuid) .map(this::composeComponentDto) .peek(this::insertComponentDto) .peek(this::insertContentOfFileInDatabase) .collect(toSet()); } private void insertComponentDto(ComponentDto component) { dbTester.components().insertComponent(component); } private ComponentDto composeComponentDto(String uuid) { return ComponentTesting .newFileDto(mainBranch) .setBranchUuid(branch.uuid()) .setKey("key_" + uuid) .setUuid(uuid) .setPath(composeComponentPath(uuid)); } @CheckForNull private static String composeComponentPath(@Nullable String reference) { return Optional.ofNullable(reference) .map(r -> String.join("_", "path", r)) .orElse(null); } private FileSourceDto insertContentOfFileInDatabase(ComponentDto file) { FileSourceDto fileSourceDto = composeFileSourceDto(file); persistFileSourceDto(fileSourceDto); return fileSourceDto; } private static FileSourceDto composeFileSourceDto(ComponentDto file) { return new FileSourceDto() .setUuid(Uuids.createFast()) .setFileUuid(file.uuid()) .setProjectUuid(file.branchUuid()); } private void persistFileSourceDto(FileSourceDto fileSourceDto) { dbTester.getDbClient().fileSourceDao().insert(dbTester.getSession(), fileSourceDto); dbTester.commit(); } private void preparePullRequestAnalysis(Analysis analysis) { prepareAnalysis(PULL_REQUEST, analysis); } private void prepareAnalysis(BranchType branch, Analysis analysis) { mockBranchType(branch); analysisMetadataHolder.setBaseAnalysis(analysis); } private void mockBranchType(BranchType branchType) { Branch branch = mock(Branch.class); when(analysisMetadataHolder.getBranch()).thenReturn(branch); when(analysisMetadataHolder.getBranch().getTargetBranchName()).thenReturn(TARGET_BRANCH); when(analysisMetadataHolder.isPullRequest()).thenReturn(branchType == PULL_REQUEST); when(analysisMetadataHolder.getProject()).thenReturn(Project.from(project)); } @Immutable private static class FileReference { private final String reference; private final String pastReference; private FileReference(String reference, @Nullable String pastReference) { this.reference = reference; this.pastReference = pastReference; } public String getReference() { return reference; } @CheckForNull public String getPastReference() { return pastReference; } public static FileReference of(String reference, String pastReference) { return new FileReference(reference, pastReference); } public static FileReference of(String reference) { return new FileReference(reference, null); } } }
16,291
40.667519
208
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/AdHocRuleCreatorIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.issue; import org.junit.Test; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.Severity; import org.sonar.api.rules.RuleType; import org.sonar.api.utils.System2; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.rule.RuleDto; import org.sonar.scanner.protocol.Constants; import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.server.es.EsTester; import org.sonar.server.rule.index.RuleIndexer; import static org.apache.commons.lang.StringUtils.repeat; import static org.assertj.core.api.Assertions.assertThat; public class AdHocRuleCreatorIT { @org.junit.Rule public DbTester db = DbTester.create(System2.INSTANCE); @org.junit.Rule public EsTester es = EsTester.create(); private RuleIndexer indexer = new RuleIndexer(es.client(), db.getDbClient()); private AdHocRuleCreator underTest = new AdHocRuleCreator(db.getDbClient(), System2.INSTANCE, indexer, new SequenceUuidFactory()); private DbSession dbSession = db.getSession(); @Test public void create_ad_hoc_rule_from_issue() { NewAdHocRule addHocRule = new NewAdHocRule(ScannerReport.ExternalIssue.newBuilder().setEngineId("eslint").setRuleId("no-cond-assign").build()); RuleDto rule = underTest.persistAndIndex(dbSession, addHocRule); assertThat(rule).isNotNull(); assertThat(rule.isExternal()).isTrue(); assertThat(rule.isAdHoc()).isTrue(); assertThat(rule.getUuid()).isNotBlank(); assertThat(rule.getKey()).isEqualTo(RuleKey.of("external_eslint", "no-cond-assign")); assertThat(rule.getName()).isEqualTo("eslint:no-cond-assign"); assertThat(rule.getRuleDescriptionSectionDtos()).isEmpty(); assertThat(rule.getSeverity()).isNull(); assertThat(rule.getType()).isZero(); assertThat(rule.getAdHocName()).isNull(); assertThat(rule.getAdHocDescription()).isNull(); assertThat(rule.getAdHocSeverity()).isNull(); assertThat(rule.getAdHocType()).isNull(); } @Test public void create_ad_hoc_rule_from_scanner_report() { NewAdHocRule addHocRule = new NewAdHocRule(ScannerReport.AdHocRule.newBuilder() .setEngineId("eslint") .setRuleId("no-cond-assign") .setName("No condition assigned") .setDescription("A description") .setSeverity(Constants.Severity.BLOCKER) .setType(ScannerReport.IssueType.BUG) .build()); RuleDto rule = underTest.persistAndIndex(dbSession, addHocRule); assertThat(rule).isNotNull(); assertThat(rule.isExternal()).isTrue(); assertThat(rule.isAdHoc()).isTrue(); assertThat(rule.getUuid()).isNotBlank(); assertThat(rule.getKey()).isEqualTo(RuleKey.of("external_eslint", "no-cond-assign")); assertThat(rule.getName()).isEqualTo("eslint:no-cond-assign"); assertThat(rule.getRuleDescriptionSectionDtos()).isEmpty(); assertThat(rule.getSeverity()).isNull(); assertThat(rule.getType()).isZero(); assertThat(rule.getAdHocName()).isEqualTo("No condition assigned"); assertThat(rule.getAdHocDescription()).isEqualTo("A description"); assertThat(rule.getAdHocSeverity()).isEqualTo(Severity.BLOCKER); assertThat(rule.getAdHocType()).isEqualTo(RuleType.BUG.getDbConstant()); } @Test public void truncate_metadata_name_and_desc_if_longer_than_max_value() { NewAdHocRule addHocRule = new NewAdHocRule(ScannerReport.AdHocRule.newBuilder() .setEngineId("eslint") .setRuleId("no-cond-assign") .setName(repeat("a", 201)) .setDescription(repeat("a", 16_777_216)) .setSeverity(Constants.Severity.BLOCKER) .setType(ScannerReport.IssueType.BUG) .build()); RuleDto rule = underTest.persistAndIndex(dbSession, addHocRule); assertThat(rule.getAdHocName()).isEqualTo(repeat("a", 200)); assertThat(rule.getAdHocDescription()).isEqualTo(repeat("a", 16_777_215)); } @Test public void update_metadata_only() { NewAdHocRule addHocRule = new NewAdHocRule(ScannerReport.AdHocRule.newBuilder() .setEngineId("eslint") .setRuleId("no-cond-assign") .setName("No condition assigned") .setDescription("A description") .setSeverity(Constants.Severity.BLOCKER) .setType(ScannerReport.IssueType.BUG) .build()); RuleDto rule = underTest.persistAndIndex(dbSession, addHocRule); long creationDate = rule.getCreatedAt(); NewAdHocRule addHocRuleUpdated = new NewAdHocRule(ScannerReport.AdHocRule.newBuilder() .setEngineId("eslint") .setRuleId("no-cond-assign") .setName("No condition assigned updated") .setDescription("A description updated") .setSeverity(Constants.Severity.CRITICAL) .setType(ScannerReport.IssueType.CODE_SMELL) .build()); RuleDto ruleUpdated = underTest.persistAndIndex(dbSession, addHocRuleUpdated); assertThat(ruleUpdated).isNotNull(); assertThat(ruleUpdated.isExternal()).isTrue(); assertThat(ruleUpdated.isAdHoc()).isTrue(); assertThat(ruleUpdated.getUuid()).isNotBlank(); assertThat(ruleUpdated.getKey()).isEqualTo(RuleKey.of("external_eslint", "no-cond-assign")); assertThat(ruleUpdated.getName()).isEqualTo("eslint:no-cond-assign"); assertThat(ruleUpdated.getRuleDescriptionSectionDtos()).isEmpty(); assertThat(ruleUpdated.getSeverity()).isNull(); assertThat(ruleUpdated.getType()).isZero(); assertThat(ruleUpdated.getAdHocName()).isEqualTo("No condition assigned updated"); assertThat(ruleUpdated.getAdHocDescription()).isEqualTo("A description updated"); assertThat(ruleUpdated.getAdHocSeverity()).isEqualTo(Severity.CRITICAL); assertThat(ruleUpdated.getAdHocType()).isEqualTo(RuleType.CODE_SMELL.getDbConstant()); assertThat(ruleUpdated.getCreatedAt()).isEqualTo(creationDate); assertThat(ruleUpdated.getUpdatedAt()).isGreaterThan(creationDate); } @Test public void does_not_update_rule_when_no_change() { RuleDto rule = db.rules().insert(r -> r.setRepositoryKey("external_eslint").setIsExternal(true).setIsAdHoc(true)); RuleDto ruleUpdated = underTest.persistAndIndex(dbSession, new NewAdHocRule(ScannerReport.AdHocRule.newBuilder() .setEngineId("eslint") .setRuleId(rule.getKey().rule()) .setName(rule.getAdHocName()) .setDescription(rule.getAdHocDescription()) .setSeverity(Constants.Severity.valueOf(rule.getAdHocSeverity())) .setType(ScannerReport.IssueType.forNumber(rule.getAdHocType())) .build())); assertThat(ruleUpdated).isNotNull(); assertThat(ruleUpdated.isExternal()).isTrue(); assertThat(ruleUpdated.isAdHoc()).isTrue(); assertThat(ruleUpdated.getKey()).isEqualTo(rule.getKey()); assertThat(ruleUpdated.getName()).isEqualTo(rule.getName()); assertThat(ruleUpdated.getRuleDescriptionSectionDtos()).usingRecursiveFieldByFieldElementComparator().isEqualTo(rule.getRuleDescriptionSectionDtos()); assertThat(ruleUpdated.getSeverity()).isEqualTo(rule.getSeverity()); assertThat(ruleUpdated.getType()).isEqualTo(rule.getType()); assertThat(ruleUpdated.getCreatedAt()).isEqualTo(rule.getCreatedAt()); assertThat(ruleUpdated.getUpdatedAt()).isEqualTo(rule.getUpdatedAt()); assertThat(ruleUpdated.getAdHocName()).isEqualTo(rule.getAdHocName()); assertThat(ruleUpdated.getAdHocDescription()).isEqualTo(rule.getAdHocDescription()); assertThat(ruleUpdated.getAdHocSeverity()).isEqualTo(rule.getAdHocSeverity()); assertThat(ruleUpdated.getAdHocType()).isEqualTo(rule.getAdHocType()); } }
8,386
43.850267
154
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/ClosedIssuesInputFactoryIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.issue; import com.google.common.collect.ImmutableList; import java.util.List; import java.util.Optional; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.tracking.Input; import org.sonar.db.DbClient; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; public class ClosedIssuesInputFactoryIT { private ComponentIssuesLoader issuesLoader = mock(ComponentIssuesLoader.class); private DbClient dbClient = mock(DbClient.class); private MovedFilesRepository movedFilesRepository = mock(MovedFilesRepository.class); private ClosedIssuesInputFactory underTest = new ClosedIssuesInputFactory(issuesLoader, dbClient, movedFilesRepository); @Test public void underTest_returns_inputFactory_loading_closed_issues_only_when_getIssues_is_called() { String componentUuid = randomAlphanumeric(12); ReportComponent component = ReportComponent.builder(Component.Type.FILE, 1).setUuid(componentUuid).build(); when(movedFilesRepository.getOriginalFile(component)).thenReturn(Optional.empty()); Input<DefaultIssue> input = underTest.create(component); verifyNoInteractions(dbClient, issuesLoader); List<DefaultIssue> issues = ImmutableList.of(new DefaultIssue(), new DefaultIssue()); when(issuesLoader.loadClosedIssues(componentUuid)).thenReturn(issues); assertThat(input.getIssues()).isSameAs(issues); } @Test public void underTest_returns_inputFactory_loading_closed_issues_from_moved_component_when_present() { String componentUuid = randomAlphanumeric(12); String originalComponentUuid = randomAlphanumeric(12); ReportComponent component = ReportComponent.builder(Component.Type.FILE, 1).setUuid(componentUuid).build(); when(movedFilesRepository.getOriginalFile(component)) .thenReturn(Optional.of(new MovedFilesRepository.OriginalFile(originalComponentUuid, randomAlphanumeric(2)))); Input<DefaultIssue> input = underTest.create(component); verifyNoInteractions(dbClient, issuesLoader); List<DefaultIssue> issues = ImmutableList.of(); when(issuesLoader.loadClosedIssues(originalComponentUuid)).thenReturn(issues); assertThat(input.getIssues()).isSameAs(issues); } @Test public void underTest_returns_inputFactory_which_caches_loaded_issues() { String componentUuid = randomAlphanumeric(12); ReportComponent component = ReportComponent.builder(Component.Type.FILE, 1).setUuid(componentUuid).build(); when(movedFilesRepository.getOriginalFile(component)).thenReturn(Optional.empty()); Input<DefaultIssue> input = underTest.create(component); verifyNoInteractions(dbClient, issuesLoader); List<DefaultIssue> issues = ImmutableList.of(new DefaultIssue()); when(issuesLoader.loadClosedIssues(componentUuid)).thenReturn(issues); assertThat(input.getIssues()).isSameAs(issues); reset(issuesLoader); assertThat(input.getIssues()).isSameAs(issues); verifyNoInteractions(issuesLoader); } }
4,319
41.772277
122
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/ComponentIssuesLoaderIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.issue; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Random; import java.util.function.Consumer; import java.util.stream.IntStream; import java.util.stream.LongStream; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.issue.Issue; import org.sonar.api.utils.System2; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.DefaultIssueComment; import org.sonar.core.issue.FieldDiffs; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.issue.IssueChangeDto; import org.sonar.db.issue.IssueDto; import org.sonar.db.rule.RuleDto; import static java.util.Collections.emptyList; import static java.util.Collections.singleton; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.sonar.api.issue.Issue.STATUS_CLOSED; import static org.sonar.api.rules.RuleType.CODE_SMELL; import static org.sonar.api.utils.DateUtils.addDays; import static org.sonar.api.utils.DateUtils.parseDateTime; import static org.sonar.ce.task.projectanalysis.issue.ComponentIssuesLoader.NUMBER_STATUS_AND_BRANCH_CHANGES_TO_KEEP; @RunWith(DataProviderRunner.class) public class ComponentIssuesLoaderIT { private static final Date NOW = parseDateTime("2018-08-17T13:44:53+0000"); private static final Date DATE_LIMIT_30_DAYS_BACK_MIDNIGHT = parseDateTime("2018-07-18T00:00:00+0000"); @Rule public DbTester db = DbTester.create(System2.INSTANCE); private final DbClient dbClient = db.getDbClient(); private final System2 system2 = mock(System2.class); private final IssueChangesToDeleteRepository issueChangesToDeleteRepository = new IssueChangesToDeleteRepository(); @Test public void loadClosedIssues_returns_single_DefaultIssue_by_issue_based_on_first_row() { ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project)); RuleDto rule = db.rules().insert(t -> t.setType(CODE_SMELL)); Date issueDate = addDays(NOW, -10); IssueDto issue = db.issues().insert(rule, project, file, t -> t.setStatus(STATUS_CLOSED).setIssueCloseDate(issueDate).setType(CODE_SMELL)); db.issues().insertFieldDiffs(issue, newToClosedDiffsWithLine(issueDate, 10)); db.issues().insertFieldDiffs(issue, newToClosedDiffsWithLine(addDays(issueDate, 3), 20)); db.issues().insertFieldDiffs(issue, newToClosedDiffsWithLine(addDays(issueDate, 1), 30)); when(system2.now()).thenReturn(NOW.getTime()); ComponentIssuesLoader underTest = newComponentIssuesLoader(newEmptySettings()); List<DefaultIssue> defaultIssues = underTest.loadClosedIssues(file.uuid()); assertThat(defaultIssues).hasSize(1); assertThat(defaultIssues.iterator().next().getLine()).isEqualTo(20); } @Test public void loadClosedIssues_returns_single_DefaultIssue_with_null_line_if_first_row_has_no_line_diff() { ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project)); RuleDto rule = db.rules().insert(t -> t.setType(CODE_SMELL)); Date issueDate = addDays(NOW, -10); IssueDto issue = db.issues().insert(rule, project, file, t -> t.setStatus(STATUS_CLOSED).setIssueCloseDate(issueDate).setType(CODE_SMELL)); db.issues().insertFieldDiffs(issue, newToClosedDiffsWithLine(issueDate, 10)); db.issues().insertFieldDiffs(issue, newToClosedDiffsWithLine(addDays(issueDate, 2), null)); db.issues().insertFieldDiffs(issue, newToClosedDiffsWithLine(addDays(issueDate, 1), 30)); when(system2.now()).thenReturn(NOW.getTime()); ComponentIssuesLoader underTest = newComponentIssuesLoader(newEmptySettings()); List<DefaultIssue> defaultIssues = underTest.loadClosedIssues(file.uuid()); assertThat(defaultIssues).hasSize(1); assertThat(defaultIssues.iterator().next().getLine()).isNull(); } @Test public void loadClosedIssues_returns_only_closed_issues_with_close_date() { ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project)); RuleDto rule = db.rules().insert(t -> t.setType(CODE_SMELL)); Date issueDate = addDays(NOW, -10); IssueDto closedIssue = db.issues().insert(rule, project, file, t -> t.setStatus(STATUS_CLOSED).setIssueCloseDate(issueDate).setType(CODE_SMELL)); db.issues().insertFieldDiffs(closedIssue, newToClosedDiffsWithLine(issueDate, 10)); IssueDto issueNoCloseDate = db.issues().insert(rule, project, file, t -> t.setStatus(STATUS_CLOSED)); db.issues().insertFieldDiffs(issueNoCloseDate, newToClosedDiffsWithLine(issueDate, 10)); when(system2.now()).thenReturn(NOW.getTime()); ComponentIssuesLoader underTest = newComponentIssuesLoader(newEmptySettings()); List<DefaultIssue> defaultIssues = underTest.loadClosedIssues(file.uuid()); assertThat(defaultIssues) .extracting(DefaultIssue::key) .containsOnly(closedIssue.getKey()); } @Test public void loadClosedIssues_returns_only_closed_issues_which_close_date_is_from_day_30_days_ago() { ComponentIssuesLoader underTest = newComponentIssuesLoader(newEmptySettings()); loadClosedIssues_returns_only_closed_issues_with_close_date_is_from_30_days_ago(underTest); } @Test public void loadClosedIssues_returns_only_closed_issues_with_close_date_is_from_30_days_ago_if_property_is_empty() { Configuration configuration = newConfiguration(null); ComponentIssuesLoader underTest = newComponentIssuesLoader(configuration); loadClosedIssues_returns_only_closed_issues_with_close_date_is_from_30_days_ago(underTest); } @Test public void loadClosedIssues_returns_only_closed_with_close_date_is_from_30_days_ago_if_property_is_less_than_0() { Configuration configuration = newConfiguration(String.valueOf(-(1 + new Random().nextInt(10)))); ComponentIssuesLoader underTest = newComponentIssuesLoader(configuration); loadClosedIssues_returns_only_closed_issues_with_close_date_is_from_30_days_ago(underTest); } @Test public void loadClosedIssues_returns_only_closed_with_close_date_is_from_30_days_ago_if_property_is_30() { Configuration configuration = newConfiguration("30"); ComponentIssuesLoader underTest = newComponentIssuesLoader(configuration); loadClosedIssues_returns_only_closed_issues_with_close_date_is_from_30_days_ago(underTest); } @Test @UseDataProvider("notAnIntegerPropertyValues") public void loadClosedIssues_returns_only_closed_with_close_date_is_from_30_days_ago_if_property_is_not_an_integer(String notAnInteger) { Configuration configuration = newConfiguration(notAnInteger); ComponentIssuesLoader underTest = newComponentIssuesLoader(configuration); loadClosedIssues_returns_only_closed_issues_with_close_date_is_from_30_days_ago(underTest); } @DataProvider public static Object[][] notAnIntegerPropertyValues() { return new Object[][] { {"foo"}, {"1,3"}, {"1.3"}, {"-3.14"} }; } private void loadClosedIssues_returns_only_closed_issues_with_close_date_is_from_30_days_ago(ComponentIssuesLoader underTest) { ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project)); RuleDto rule = db.rules().insert(t -> t.setType(CODE_SMELL)); Date[] issueDates = new Date[] { addDays(NOW, -10), addDays(NOW, -31), addDays(NOW, -30), DATE_LIMIT_30_DAYS_BACK_MIDNIGHT, addDays(NOW, -29), addDays(NOW, -60), }; IssueDto[] issues = Arrays.stream(issueDates) .map(issueDate -> { IssueDto closedIssue = db.issues().insert(rule, project, file, t -> t.setStatus(STATUS_CLOSED).setIssueCloseDate(issueDate).setType(CODE_SMELL)); db.issues().insertFieldDiffs(closedIssue, newToClosedDiffsWithLine(issueDate, 10)); return closedIssue; }) .toArray(IssueDto[]::new); when(system2.now()).thenReturn(NOW.getTime()); List<DefaultIssue> defaultIssues = underTest.loadClosedIssues(file.uuid()); assertThat(defaultIssues) .extracting(DefaultIssue::key) .containsOnly(issues[0].getKey(), issues[2].getKey(), issues[3].getKey(), issues[4].getKey()); } @Test public void loadClosedIssues_returns_empty_without_querying_DB_if_property_is_0() { System2 system2 = mock(System2.class); DbClient dbClient = mock(DbClient.class); Configuration configuration = newConfiguration("0"); String componentUuid = randomAlphabetic(15); ComponentIssuesLoader underTest = new ComponentIssuesLoader(dbClient, null, null, configuration, system2, issueChangesToDeleteRepository); assertThat(underTest.loadClosedIssues(componentUuid)).isEmpty(); verifyNoInteractions(dbClient, system2); } @Test public void loadLatestDiffChangesForReopeningOfClosedIssues_collects_issue_changes_to_delete() { IssueDto issue = db.issues().insert(); for (long i = 0; i < NUMBER_STATUS_AND_BRANCH_CHANGES_TO_KEEP + 5; i++) { db.issues().insertChange(issue, diffIssueChangeModifier(i, "status")); } // should not be deleted db.issues().insertChange(issue, diffIssueChangeModifier(-1, "other")); ComponentIssuesLoader underTest = new ComponentIssuesLoader(dbClient, null, null, newConfiguration("0"), null, issueChangesToDeleteRepository); underTest.loadLatestDiffChangesForReopeningOfClosedIssues(singleton(new DefaultIssue().setKey(issue.getKey()))); assertThat(issueChangesToDeleteRepository.getUuids()).containsOnly("0", "1", "2", "3", "4"); } @Test public void loadLatestDiffChangesForReopeningOfClosedIssues_does_not_query_DB_if_issue_list_is_empty() { DbClient dbClient = mock(DbClient.class); ComponentIssuesLoader underTest = new ComponentIssuesLoader(dbClient, null, null, newConfiguration("0"), null, issueChangesToDeleteRepository); underTest.loadLatestDiffChangesForReopeningOfClosedIssues(emptyList()); verifyNoInteractions(dbClient, system2); } @Test @UseDataProvider("statusOrResolutionFieldName") public void loadLatestDiffChangesForReopeningOfClosedIssues_add_diff_change_with_most_recent_status_or_resolution(String statusOrResolutionFieldName) { IssueDto issue = db.issues().insert(); db.issues().insertChange(issue, t -> t.setChangeData(randomDiffWith(statusOrResolutionFieldName, "val1")).setIssueChangeCreationDate(5)); db.issues().insertChange(issue, t -> t.setChangeData(randomDiffWith(statusOrResolutionFieldName, "val2")).setIssueChangeCreationDate(20)); db.issues().insertChange(issue, t -> t.setChangeData(randomDiffWith(statusOrResolutionFieldName, "val3")).setIssueChangeCreationDate(13)); ComponentIssuesLoader underTest = new ComponentIssuesLoader(dbClient, null, null, newConfiguration("0"), null, issueChangesToDeleteRepository); DefaultIssue defaultIssue = new DefaultIssue().setKey(issue.getKey()); underTest.loadLatestDiffChangesForReopeningOfClosedIssues(singleton(defaultIssue)); assertThat(defaultIssue.changes()) .hasSize(1); assertThat(defaultIssue.changes()) .extracting(t -> t.get(statusOrResolutionFieldName)) .filteredOn(t -> hasValue(t, "val2")) .hasSize(1); } @Test public void loadLatestDiffChangesForReopeningOfClosedIssues_add_single_diff_change_when_most_recent_status_and_resolution_is_the_same_diff() { IssueDto issue = db.issues().insert(); db.issues().insertChange(issue, t -> t.setChangeData(randomDiffWith("status", "valStatus1")).setIssueChangeCreationDate(5)); db.issues().insertChange(issue, t -> t.setChangeData(randomDiffWith("status", "valStatus2")).setIssueChangeCreationDate(19)); db.issues().insertChange(issue, t -> t.setChangeData(randomDiffWith("status", "valStatus3", "resolution", "valRes3")).setIssueChangeCreationDate(20)); db.issues().insertChange(issue, t -> t.setChangeData(randomDiffWith("resolution", "valRes4")).setIssueChangeCreationDate(13)); ComponentIssuesLoader underTest = new ComponentIssuesLoader(dbClient, null, null, newConfiguration("0"), null, issueChangesToDeleteRepository); DefaultIssue defaultIssue = new DefaultIssue().setKey(issue.getKey()); underTest.loadLatestDiffChangesForReopeningOfClosedIssues(singleton(defaultIssue)); assertThat(defaultIssue.changes()) .hasSize(1); assertThat(defaultIssue.changes()) .extracting(t -> t.get("status")) .filteredOn(t -> hasValue(t, "valStatus3")) .hasSize(1); assertThat(defaultIssue.changes()) .extracting(t -> t.get("resolution")) .filteredOn(t -> hasValue(t, "valRes3")) .hasSize(1); } @Test public void loadLatestDiffChangesForReopeningOfClosedIssues_adds_2_diff_changes_if_most_recent_status_and_resolution_are_not_the_same_diff() { IssueDto issue = db.issues().insert(); db.issues().insertChange(issue, t -> t.setChangeData(randomDiffWith("status", "valStatus1")).setIssueChangeCreationDate(5)); db.issues().insertChange(issue, t -> t.setChangeData(randomDiffWith("status", "valStatus2", "resolution", "valRes2")).setIssueChangeCreationDate(19)); db.issues().insertChange(issue, t -> t.setChangeData(randomDiffWith("status", "valStatus3")).setIssueChangeCreationDate(20)); db.issues().insertChange(issue, t -> t.setChangeData(randomDiffWith("resolution", "valRes4")).setIssueChangeCreationDate(13)); ComponentIssuesLoader underTest = new ComponentIssuesLoader(dbClient, null /* not used in method */, null /* not used in method */, newConfiguration("0"), null /* not used by method */, issueChangesToDeleteRepository); DefaultIssue defaultIssue = new DefaultIssue().setKey(issue.getKey()); underTest.loadLatestDiffChangesForReopeningOfClosedIssues(singleton(defaultIssue)); assertThat(defaultIssue.changes()) .hasSize(2); assertThat(defaultIssue.changes()) .extracting(t -> t.get("status")) .filteredOn(t -> hasValue(t, "valStatus3")) .hasSize(1); assertThat(defaultIssue.changes()) .extracting(t -> t.get("resolution")) .filteredOn(t -> hasValue(t, "valRes2")) .hasSize(1); } @Test public void loadChanges_should_filter_out_old_status_changes() { IssueDto issue = db.issues().insert(); for (int i = 0; i < NUMBER_STATUS_AND_BRANCH_CHANGES_TO_KEEP + 1; i++) { db.issues().insertChange(issue, diffIssueChangeModifier(i, "status")); } // these are kept db.issues().insertChange(issue, diffIssueChangeModifier(NUMBER_STATUS_AND_BRANCH_CHANGES_TO_KEEP + 1, "other")); db.issues().insertChange(issue, t -> t .setChangeType(IssueChangeDto.TYPE_COMMENT) .setKey("comment1")); ComponentIssuesLoader underTest = new ComponentIssuesLoader(dbClient, null, null, newConfiguration("0"), null, issueChangesToDeleteRepository); DefaultIssue defaultIssue = new DefaultIssue().setKey(issue.getKey()); underTest.loadChanges(db.getSession(), singleton(defaultIssue)); assertThat(defaultIssue.changes()) .extracting(d -> d.creationDate().getTime()) .containsOnly(LongStream.rangeClosed(1, NUMBER_STATUS_AND_BRANCH_CHANGES_TO_KEEP + 1).boxed().toArray(Long[]::new)); assertThat(defaultIssue.defaultIssueComments()).extracting(DefaultIssueComment::key).containsOnly("comment1"); assertThat(issueChangesToDeleteRepository.getUuids()).containsOnly("0"); } @Test public void loadChanges_should_filter_out_old_from_branch_changes() { IssueDto issue = db.issues().insert(); for (int i = 0; i < NUMBER_STATUS_AND_BRANCH_CHANGES_TO_KEEP + 1; i++) { db.issues().insertChange(issue, diffIssueChangeModifier(i, "from_branch")); } ComponentIssuesLoader underTest = new ComponentIssuesLoader(dbClient, null, null, newConfiguration("0"), null, issueChangesToDeleteRepository); DefaultIssue defaultIssue = new DefaultIssue().setKey(issue.getKey()); underTest.loadChanges(db.getSession(), singleton(defaultIssue)); assertThat(defaultIssue.changes()) .extracting(d -> d.creationDate().getTime()) .containsOnly(LongStream.rangeClosed(1, NUMBER_STATUS_AND_BRANCH_CHANGES_TO_KEEP).boxed().toArray(Long[]::new)); assertThat(issueChangesToDeleteRepository.getUuids()).containsOnly("0"); } private Consumer<IssueChangeDto> diffIssueChangeModifier(long created, String field) { return issueChangeDto -> issueChangeDto .setChangeData(new FieldDiffs().setDiff(field, "A", "B").toEncodedString()) .setIssueChangeCreationDate(created) .setUuid(String.valueOf(created)); } private static boolean hasValue(@Nullable FieldDiffs.Diff t, String value) { if (t == null) { return false; } return (t.oldValue() == null || value.equals(t.oldValue())) && (t.newValue() == null || value.equals(t.newValue())); } @DataProvider public static Object[][] statusOrResolutionFieldName() { return new Object[][] { {"status"}, {"resolution"}, }; } private static String randomDiffWith(String... fieldsAndValues) { Random random = new Random(); List<Diff> diffs = new ArrayList<>(); for (int i = 0; i < fieldsAndValues.length; i++) { int oldOrNew = random.nextInt(3); String value = fieldsAndValues[i + 1]; diffs.add(new Diff(fieldsAndValues[i], oldOrNew <= 2 ? value : null, oldOrNew >= 2 ? value : null)); i++; } IntStream.range(0, random.nextInt(5)) .forEach(i -> diffs.add(new Diff(randomAlphabetic(10), random.nextBoolean() ? null : randomAlphabetic(11), random.nextBoolean() ? null : randomAlphabetic(12)))); Collections.shuffle(diffs); FieldDiffs res = new FieldDiffs(); diffs.forEach(diff -> res.setDiff(diff.field, diff.oldValue, diff.newValue)); return res.toEncodedString(); } private static final class Diff { private final String field; private final String oldValue; private final String newValue; private Diff(String field, @Nullable String oldValue, @Nullable String newValue) { this.field = field; this.oldValue = oldValue; this.newValue = newValue; } } private static FieldDiffs newToClosedDiffsWithLine(Date creationDate, @Nullable Integer oldLineValue) { FieldDiffs fieldDiffs = new FieldDiffs().setCreationDate(addDays(creationDate, -5)) .setDiff("status", randomNonCloseStatus(), STATUS_CLOSED); if (oldLineValue != null) { fieldDiffs.setDiff("line", oldLineValue, ""); } return fieldDiffs; } private static String randomNonCloseStatus() { String[] nonCloseStatuses = Issue.STATUSES.stream() .filter(t -> !STATUS_CLOSED.equals(t)) .toArray(String[]::new); return nonCloseStatuses[new Random().nextInt(nonCloseStatuses.length)]; } private ComponentIssuesLoader newComponentIssuesLoader(Configuration configuration) { return new ComponentIssuesLoader(dbClient, null /* not used in loadClosedIssues */, null /* not used in loadClosedIssues */, configuration, system2, issueChangesToDeleteRepository); } private static Configuration newEmptySettings() { return new MapSettings().asConfig(); } private static Configuration newConfiguration(@Nullable String maxAge) { MapSettings settings = new MapSettings(); settings.setProperty("sonar.issuetracking.closedissues.maxage", maxAge); return settings.asConfig(); } }
21,165
46.886878
167
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/DefaultAssigneeIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.issue; import org.junit.Rule; import org.junit.Test; import org.sonar.api.CoreProperties; import org.sonar.api.config.internal.MapSettings; import org.sonar.ce.task.projectanalysis.component.ConfigurationRepository; import org.sonar.ce.task.projectanalysis.component.TestSettingsRepository; import org.sonar.db.DbTester; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserIdDto; import static org.assertj.core.api.Assertions.assertThat; public class DefaultAssigneeIT { public static final String PROJECT_KEY = "PROJECT_KEY"; @Rule public DbTester db = DbTester.create(); private final MapSettings settings = new MapSettings(); private final ConfigurationRepository settingsRepository = new TestSettingsRepository(settings.asConfig()); private final DefaultAssignee underTest = new DefaultAssignee(db.getDbClient(), settingsRepository); @Test public void no_default_assignee() { assertThat(underTest.loadDefaultAssigneeUserId()).isNull(); } @Test public void set_default_assignee() { settings.setProperty(CoreProperties.DEFAULT_ISSUE_ASSIGNEE, "erik"); UserDto userDto = db.users().insertUser("erik"); UserIdDto userId = underTest.loadDefaultAssigneeUserId(); assertThat(userId).isNotNull(); assertThat(userId.getUuid()).isEqualTo(userDto.getUuid()); assertThat(userId.getLogin()).isEqualTo(userDto.getLogin()); } @Test public void configured_login_does_not_exist() { settings.setProperty(CoreProperties.DEFAULT_ISSUE_ASSIGNEE, "erik"); assertThat(underTest.loadDefaultAssigneeUserId()).isNull(); } @Test public void configured_login_is_disabled() { settings.setProperty(CoreProperties.DEFAULT_ISSUE_ASSIGNEE, "erik"); db.users().insertUser(user -> user.setLogin("erik").setActive(false)); assertThat(underTest.loadDefaultAssigneeUserId()).isNull(); } @Test public void default_assignee_is_cached() { settings.setProperty(CoreProperties.DEFAULT_ISSUE_ASSIGNEE, "erik"); UserDto userDto = db.users().insertUser("erik"); UserIdDto userId = underTest.loadDefaultAssigneeUserId(); assertThat(userId).isNotNull(); assertThat(userId.getUuid()).isEqualTo(userDto.getUuid()); assertThat(userId.getLogin()).isEqualTo(userDto.getLogin()); // The setting is updated but the assignee hasn't changed settings.setProperty(CoreProperties.DEFAULT_ISSUE_ASSIGNEE, "other"); userId = underTest.loadDefaultAssigneeUserId(); assertThat(userId).isNotNull(); assertThat(userId.getUuid()).isEqualTo(userDto.getUuid()); assertThat(userId.getLogin()).isEqualTo(userDto.getLogin()); } }
3,511
36.763441
109
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/IntegrateIssuesVisitorIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.issue; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.Set; import org.jetbrains.annotations.NotNull; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mockito.ArgumentCaptor; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.Severity; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder; import org.sonar.ce.task.projectanalysis.analysis.Branch; import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.FileStatuses; import org.sonar.ce.task.projectanalysis.component.ReferenceBranchComponentUuids; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitor; import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository; import org.sonar.ce.task.projectanalysis.issue.filter.IssueFilter; import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRulesHolder; import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRulesHolderRule; import org.sonar.ce.task.projectanalysis.qualityprofile.AlwaysActiveRulesHolderImpl; import org.sonar.ce.task.projectanalysis.source.NewLinesRepository; import org.sonar.ce.task.projectanalysis.source.SourceLinesHashRepository; import org.sonar.ce.task.projectanalysis.source.SourceLinesRepository; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.FieldDiffs; import org.sonar.core.issue.IssueChangeContext; import org.sonar.core.issue.tracking.Tracker; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.BranchType; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.issue.IssueDto; import org.sonar.db.issue.IssueTesting; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleTesting; import org.sonar.scanner.protocol.Constants; import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.server.issue.IssueFieldsSetter; import org.sonar.server.issue.workflow.IssueWorkflow; import static com.google.common.collect.Lists.newArrayList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class IntegrateIssuesVisitorIT { private static final String FILE_UUID = "FILE_UUID"; private static final String FILE_UUID_ON_BRANCH = "FILE_UUID_BRANCH"; private static final String FILE_KEY = "FILE_KEY"; private static final int FILE_REF = 2; private static final Component FILE = ReportComponent.builder(Component.Type.FILE, FILE_REF) .setKey(FILE_KEY) .setUuid(FILE_UUID) .build(); private static final String PROJECT_KEY = "PROJECT_KEY"; private static final String PROJECT_UUID = "PROJECT_UUID"; private static final String PROJECT_UUID_ON_BRANCH = "PROJECT_UUID_BRANCH"; private static final int PROJECT_REF = 1; private static final Component PROJECT = ReportComponent.builder(Component.Type.PROJECT, PROJECT_REF) .setKey(PROJECT_KEY) .setUuid(PROJECT_UUID) .addChildren(FILE) .build(); @Rule public TemporaryFolder temp = new TemporaryFolder(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public BatchReportReaderRule reportReader = new BatchReportReaderRule(); @Rule public ActiveRulesHolderRule activeRulesHolderRule = new ActiveRulesHolderRule(); @Rule public RuleRepositoryRule ruleRepositoryRule = new RuleRepositoryRule(); private final AnalysisMetadataHolder analysisMetadataHolder = mock(AnalysisMetadataHolder.class); private final IssueFilter issueFilter = mock(IssueFilter.class); private final MovedFilesRepository movedFilesRepository = mock(MovedFilesRepository.class); private final IssueChangeContext issueChangeContext = mock(IssueChangeContext.class); private final IssueLifecycle issueLifecycle = new IssueLifecycle(analysisMetadataHolder, issueChangeContext, mock(IssueWorkflow.class), new IssueFieldsSetter(), mock(DebtCalculator.class), ruleRepositoryRule); private final IssueVisitor issueVisitor = mock(IssueVisitor.class); private final ReferenceBranchComponentUuids mergeBranchComponentsUuids = mock(ReferenceBranchComponentUuids.class); private final SiblingsIssueMerger issueStatusCopier = mock(SiblingsIssueMerger.class); private final ReferenceBranchComponentUuids referenceBranchComponentUuids = mock(ReferenceBranchComponentUuids.class); private final SourceLinesHashRepository sourceLinesHash = mock(SourceLinesHashRepository.class); private final NewLinesRepository newLinesRepository = mock(NewLinesRepository.class); private final TargetBranchComponentUuids targetBranchComponentUuids = mock(TargetBranchComponentUuids.class); private final SourceLinesRepository sourceLinesRepository = mock(SourceLinesRepository.class); private final FileStatuses fileStatuses = mock(FileStatuses.class); private ArgumentCaptor<DefaultIssue> defaultIssueCaptor; private final ComponentIssuesLoader issuesLoader = new ComponentIssuesLoader(dbTester.getDbClient(), ruleRepositoryRule, activeRulesHolderRule, new MapSettings().asConfig(), System2.INSTANCE, mock(IssueChangesToDeleteRepository.class)); private IssueTrackingDelegator trackingDelegator; private TrackerExecution tracker; private PullRequestTrackerExecution prBranchTracker; private ReferenceBranchTrackerExecution mergeBranchTracker; private final ActiveRulesHolder activeRulesHolder = new AlwaysActiveRulesHolderImpl(); private ProtoIssueCache protoIssueCache; private TypeAwareVisitor underTest; @Before public void setUp() throws Exception { IssueVisitors issueVisitors = new IssueVisitors(new IssueVisitor[] {issueVisitor}); defaultIssueCaptor = ArgumentCaptor.forClass(DefaultIssue.class); when(movedFilesRepository.getOriginalFile(any(Component.class))).thenReturn(Optional.empty()); DbClient dbClient = dbTester.getDbClient(); TrackerRawInputFactory rawInputFactory = new TrackerRawInputFactory(treeRootHolder, reportReader, sourceLinesHash, issueFilter, ruleRepositoryRule, activeRulesHolder); TrackerBaseInputFactory baseInputFactory = new TrackerBaseInputFactory(issuesLoader, dbClient, movedFilesRepository); TrackerTargetBranchInputFactory targetInputFactory = new TrackerTargetBranchInputFactory(issuesLoader, targetBranchComponentUuids, dbClient, movedFilesRepository); TrackerReferenceBranchInputFactory mergeInputFactory = new TrackerReferenceBranchInputFactory(issuesLoader, mergeBranchComponentsUuids, dbClient); ClosedIssuesInputFactory closedIssuesInputFactory = new ClosedIssuesInputFactory(issuesLoader, dbClient, movedFilesRepository); tracker = new TrackerExecution(baseInputFactory, closedIssuesInputFactory, new Tracker<>(), issuesLoader, analysisMetadataHolder); mergeBranchTracker = new ReferenceBranchTrackerExecution(mergeInputFactory, new Tracker<>()); prBranchTracker = new PullRequestTrackerExecution(baseInputFactory, targetInputFactory, new Tracker<>(), newLinesRepository); trackingDelegator = new IssueTrackingDelegator(prBranchTracker, mergeBranchTracker, tracker, analysisMetadataHolder); treeRootHolder.setRoot(PROJECT); protoIssueCache = new ProtoIssueCache(temp.newFile(), System2.INSTANCE); when(issueFilter.accept(any(DefaultIssue.class), eq(FILE))).thenReturn(true); when(issueChangeContext.date()).thenReturn(new Date()); underTest = new IntegrateIssuesVisitor(protoIssueCache, rawInputFactory, baseInputFactory, issueLifecycle, issueVisitors, trackingDelegator, issueStatusCopier, referenceBranchComponentUuids, mock(PullRequestSourceBranchMerger.class), fileStatuses); } @Test public void process_new_issue() { ruleRepositoryRule.add(RuleTesting.XOO_X1); when(analysisMetadataHolder.isBranch()).thenReturn(true); ScannerReport.Issue reportIssue = getReportIssue(RuleTesting.XOO_X1); reportReader.putIssues(FILE_REF, singletonList(reportIssue)); underTest.visitAny(FILE); List<DefaultIssue> issues = newArrayList(protoIssueCache.traverse()); assertThat(issues).hasSize(1); assertThat(issues.get(0).codeVariants()).containsExactlyInAnyOrder("foo", "bar"); } @Test public void process_existing_issue() { RuleKey ruleKey = RuleTesting.XOO_X1; // Issue from db has severity major addBaseIssue(ruleKey); // Issue from report has severity blocker ScannerReport.Issue reportIssue = getReportIssue(ruleKey); reportReader.putIssues(FILE_REF, singletonList(reportIssue)); underTest.visitAny(FILE); List<DefaultIssue> issues = newArrayList(protoIssueCache.traverse()); assertThat(issues).hasSize(1); assertThat(issues.get(0).severity()).isEqualTo(Severity.BLOCKER); } @Test public void dont_cache_existing_issue_if_unmodified() { RuleKey ruleKey = RuleTesting.XOO_X1; // Issue from db has severity major addBaseIssue(ruleKey); // Issue from report has severity blocker ScannerReport.Issue reportIssue = getReportIssue(ruleKey); reportReader.putIssues(FILE_REF, singletonList(reportIssue)); underTest.visitAny(FILE); List<DefaultIssue> issues = newArrayList(protoIssueCache.traverse()); assertThat(issues).hasSize(1); assertThat(issues.get(0).severity()).isEqualTo(Severity.BLOCKER); } @Test public void execute_issue_visitors() { ruleRepositoryRule.add(RuleTesting.XOO_X1); ScannerReport.Issue reportIssue = getReportIssue(RuleTesting.XOO_X1); reportReader.putIssues(FILE_REF, singletonList(reportIssue)); underTest.visitAny(FILE); verify(issueVisitor).beforeComponent(FILE); verify(issueVisitor).afterComponent(FILE); verify(issueVisitor).onIssue(eq(FILE), defaultIssueCaptor.capture()); assertThat(defaultIssueCaptor.getValue().ruleKey().rule()).isEqualTo("x1"); } @Test public void close_unmatched_base_issue() { RuleKey ruleKey = RuleTesting.XOO_X1; addBaseIssue(ruleKey); // No issue in the report underTest.visitAny(FILE); List<DefaultIssue> issues = newArrayList(protoIssueCache.traverse()); assertThat(issues).isEmpty(); } @Test public void remove_uuid_of_original_file_from_componentsWithUnprocessedIssues_if_component_has_one() { String originalFileUuid = "original file uuid"; when(movedFilesRepository.getOriginalFile(FILE)) .thenReturn(Optional.of(new MovedFilesRepository.OriginalFile(originalFileUuid, "original file key"))); underTest.visitAny(FILE); } @Test public void reuse_issues_when_data_unchanged() { RuleKey ruleKey = RuleTesting.XOO_X1; // Issue from db has severity major addBaseIssue(ruleKey); // Issue from report has severity blocker ScannerReport.Issue reportIssue = getReportIssue(ruleKey); reportReader.putIssues(FILE_REF, singletonList(reportIssue)); when(fileStatuses.isDataUnchanged(FILE)).thenReturn(true); underTest.visitAny(FILE); // visitors get called, so measures created from issues should be calculated taking these issues into account verify(issueVisitor).onIssue(eq(FILE), defaultIssueCaptor.capture()); assertThat(defaultIssueCaptor.getValue().ruleKey().rule()).isEqualTo(ruleKey.rule()); // most issues won't go to the cache since they aren't changed and don't need to be persisted // In this test they are being closed but the workflows aren't working (we mock them) so nothing is changed on the issue is not cached. assertThat(newArrayList(protoIssueCache.traverse())).isEmpty(); } @Test public void copy_issues_when_creating_new_non_main_branch() { when(mergeBranchComponentsUuids.getComponentUuid(FILE_KEY)).thenReturn(FILE_UUID_ON_BRANCH); when(referenceBranchComponentUuids.getReferenceBranchName()).thenReturn("master"); when(analysisMetadataHolder.isBranch()).thenReturn(true); when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(true); Branch branch = mock(Branch.class); when(branch.isMain()).thenReturn(false); when(branch.getType()).thenReturn(BranchType.BRANCH); when(analysisMetadataHolder.getBranch()).thenReturn(branch); RuleKey ruleKey = RuleTesting.XOO_X1; // Issue from main branch has severity major addBaseIssueOnBranch(ruleKey); // Issue from report has severity blocker ScannerReport.Issue reportIssue = getReportIssue(ruleKey); reportReader.putIssues(FILE_REF, singletonList(reportIssue)); underTest.visitAny(FILE); List<DefaultIssue> issues = newArrayList(protoIssueCache.traverse()); assertThat(issues).hasSize(1); assertThat(issues.get(0).severity()).isEqualTo(Severity.BLOCKER); assertThat(issues.get(0).isNew()).isFalse(); assertThat(issues.get(0).isCopied()).isTrue(); assertThat(issues.get(0).changes()).hasSize(1); assertThat(issues.get(0).changes().get(0).diffs()).contains(entry(IssueFieldsSetter.FROM_BRANCH, new FieldDiffs.Diff<>("master", null))); } private void addBaseIssue(RuleKey ruleKey) { ComponentDto project = ComponentTesting.newPrivateProjectDto(PROJECT_UUID).setKey(PROJECT_KEY); ComponentDto file = ComponentTesting.newFileDto(project, null, FILE_UUID).setKey(FILE_KEY); dbTester.components().insertComponents(project, file); RuleDto ruleDto = RuleTesting.newRule(ruleKey); dbTester.rules().insert(ruleDto); ruleRepositoryRule.add(ruleKey); IssueDto issue = IssueTesting.newIssue(ruleDto, project, file) .setKee("ISSUE") .setSeverity(Severity.MAJOR); dbTester.getDbClient().issueDao().insert(dbTester.getSession(), issue); dbTester.getSession().commit(); } private void addBaseIssueOnBranch(RuleKey ruleKey) { ComponentDto project = ComponentTesting.newPrivateProjectDto(PROJECT_UUID_ON_BRANCH).setKey(PROJECT_KEY); ComponentDto file = ComponentTesting.newFileDto(project, null, FILE_UUID_ON_BRANCH).setKey(FILE_KEY); dbTester.components().insertComponents(project, file); RuleDto ruleDto = RuleTesting.newRule(ruleKey); dbTester.rules().insert(ruleDto); ruleRepositoryRule.add(ruleKey); IssueDto issue = IssueTesting.newIssue(ruleDto, project, file) .setKee("ISSUE") .setSeverity(Severity.MAJOR) .setChecksum(null); dbTester.getDbClient().issueDao().insert(dbTester.getSession(), issue); dbTester.getSession().commit(); } @NotNull private static ScannerReport.Issue getReportIssue(RuleKey ruleKey) { return ScannerReport.Issue.newBuilder() .setMsg("the message") .setRuleRepository(ruleKey.repository()) .setRuleKey(ruleKey.rule()) .addAllCodeVariants(Set.of("foo", "bar")) .setSeverity(Constants.Severity.BLOCKER) .build(); } }
16,277
45.508571
175
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/ProjectTrackerBaseLazyInputIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.issue; import java.util.Date; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRulesHolderRule; import org.sonar.core.issue.DefaultIssue; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.issue.IssueDto; import org.sonar.db.rule.RuleDto; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.sonar.api.utils.DateUtils.parseDate; import static org.sonar.db.component.ComponentTesting.newFileDto; public class ProjectTrackerBaseLazyInputIT { private static final Date ANALYSIS_DATE = parseDate("2016-06-01"); @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule().setAnalysisDate(ANALYSIS_DATE); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule public ActiveRulesHolderRule activeRulesHolderRule = new ActiveRulesHolderRule(); @Rule public RuleRepositoryRule ruleRepositoryRule = new RuleRepositoryRule(); private DbClient dbClient = dbTester.getDbClient(); private ProjectTrackerBaseLazyInput underTest; private RuleDto rule; private ComponentDto rootProjectDto; private ComponentIssuesLoader issuesLoader = new ComponentIssuesLoader(dbTester.getDbClient(), ruleRepositoryRule, activeRulesHolderRule, new MapSettings().asConfig(), System2.INSTANCE, mock(IssueChangesToDeleteRepository.class)); @Before public void prepare() { rule = dbTester.rules().insert(); ruleRepositoryRule.add(rule.getKey()); rootProjectDto = dbTester.components().insertPublicProject().getMainBranchComponent(); ReportComponent rootProject = ReportComponent.builder(Component.Type.FILE, 1) .setKey(rootProjectDto.getKey()) .setUuid(rootProjectDto.uuid()).build(); underTest = new ProjectTrackerBaseLazyInput(dbClient, issuesLoader, rootProject); } @Test public void return_only_open_project_issues_if_no_folders() { ComponentDto file = dbTester.components().insertComponent(newFileDto(rootProjectDto)); IssueDto openIssueOnProject = dbTester.issues().insert(rule, rootProjectDto, rootProjectDto, i -> i.setStatus("OPEN").setResolution(null)); IssueDto closedIssueOnProject = dbTester.issues().insert(rule, rootProjectDto, rootProjectDto, i -> i.setStatus("CLOSED").setResolution("FIXED")); IssueDto openIssue1OnFile = dbTester.issues().insert(rule, rootProjectDto, file, i -> i.setStatus("OPEN").setResolution(null)); assertThat(underTest.loadIssues()).extracting(DefaultIssue::key).containsOnly(openIssueOnProject.getKey()); } }
3,875
44.6
169
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/ScmAccountToUserLoaderIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.issue; import org.junit.Rule; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.db.DbTester; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserIdDto; import org.sonar.server.es.EsTester; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; public class ScmAccountToUserLoaderIT { @Rule public DbTester db = DbTester.create(); @Rule public EsTester es = EsTester.create(); @Rule public LogTester logTester = new LogTester(); @Test public void load_login_for_scm_account() { UserDto user = db.users().insertUser(u -> u.setScmAccounts(asList("charlie", "jesuis@charlie.com"))); ScmAccountToUserLoader underTest = new ScmAccountToUserLoader(db.getDbClient()); assertThat(underTest.load("missing")).isNull(); UserIdDto result = underTest.load("jesuis@charlie.com"); assertThat(result).isNotNull(); assertThat(result.getUuid()).isEqualTo(user.getUuid()); assertThat(result.getLogin()).isEqualTo(user.getLogin()); } @Test public void warn_if_multiple_users_share_the_same_scm_account() { db.users().insertUser(u -> u.setLogin("charlie").setScmAccounts(asList("charlie", "jesuis@charlie.com"))); db.users().insertUser(u -> u.setLogin("another.charlie").setScmAccounts(asList("charlie"))); ScmAccountToUserLoader underTest = new ScmAccountToUserLoader(db.getDbClient()); assertThat(underTest.load("charlie")).isNull(); assertThat(logTester.logs(Level.WARN)).contains("Multiple users share the SCM account 'charlie': another.charlie, charlie"); } @Test public void load_by_multiple_scm_accounts_is_not_supported_yet() { ScmAccountToUserLoader underTest = new ScmAccountToUserLoader(db.getDbClient()); try { underTest.loadAll(emptyList()); fail(); } catch (UnsupportedOperationException ignored) { } } }
2,906
35.3375
128
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/SiblingsIssueMergerIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.issue; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Collections; import java.util.Date; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.issue.Issue; import org.sonar.api.rule.RuleKey; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.analysis.Branch; import org.sonar.ce.task.projectanalysis.component.SiblingComponentsWithOpenIssues; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.FieldDiffs; import org.sonar.core.issue.tracking.SimpleTracker; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.BranchType; import org.sonar.db.component.ComponentDto; import org.sonar.db.issue.IssueDto; import org.sonar.db.issue.IssueTesting; import org.sonar.db.rule.RuleDto; import org.sonar.db.user.UserDto; import org.sonar.server.project.Project; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; import static org.sonar.db.component.ComponentTesting.newFileDto; public class SiblingsIssueMergerIT { private final IssueLifecycle issueLifecycle = mock(IssueLifecycle.class); private final Branch branch = mock(Branch.class); @Rule public DbTester db = DbTester.create(); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule() .setRoot(builder(org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT, PROJECT_REF).setKey(PROJECT_KEY).setUuid(PROJECT_UUID) .addChildren(FILE_1) .build()); @Rule public AnalysisMetadataHolderRule metadataHolder = new AnalysisMetadataHolderRule(); private static final String PROJECT_KEY = "project"; private static final int PROJECT_REF = 1; private static final String PROJECT_UUID = "projectUuid"; private static final int FILE_1_REF = 12341; private static final String FILE_1_KEY = "fileKey"; private static final String FILE_1_UUID = "fileUuid"; private static final org.sonar.ce.task.projectanalysis.component.Component FILE_1 = builder( org.sonar.ce.task.projectanalysis.component.Component.Type.FILE, FILE_1_REF) .setKey(FILE_1_KEY) .setUuid(FILE_1_UUID) .build(); private final SimpleTracker<DefaultIssue, SiblingIssue> tracker = new SimpleTracker<>(); private SiblingsIssueMerger copier; private ComponentDto fileOnBranch1Dto; private ComponentDto fileOnBranch2Dto; private ComponentDto fileOnBranch3Dto; private ComponentDto projectDto; private ComponentDto branch1Dto; private ComponentDto branch2Dto; private ComponentDto branch3Dto; private RuleDto rule; @Before public void setUp() { DbClient dbClient = db.getDbClient(); ComponentIssuesLoader componentIssuesLoader = new ComponentIssuesLoader(dbClient, null, null, new MapSettings().asConfig(), System2.INSTANCE, mock(IssueChangesToDeleteRepository.class)); copier = new SiblingsIssueMerger(new SiblingsIssuesLoader(new SiblingComponentsWithOpenIssues(treeRootHolder, metadataHolder, dbClient), dbClient, componentIssuesLoader), tracker, issueLifecycle); projectDto = db.components().insertPublicProject(p -> p.setKey(PROJECT_KEY).setUuid(PROJECT_UUID).setBranchUuid(PROJECT_UUID)).getMainBranchComponent(); branch1Dto = db.components().insertProjectBranch(projectDto, b -> b.setKey("myBranch1") .setBranchType(BranchType.PULL_REQUEST) .setMergeBranchUuid(projectDto.uuid())); branch2Dto = db.components().insertProjectBranch(projectDto, b -> b.setKey("myBranch2") .setBranchType(BranchType.PULL_REQUEST) .setMergeBranchUuid(projectDto.uuid())); branch3Dto = db.components().insertProjectBranch(projectDto, b -> b.setKey("myBranch3") .setBranchType(BranchType.PULL_REQUEST) .setMergeBranchUuid(projectDto.uuid())); fileOnBranch1Dto = db.components().insertComponent(newFileDto(branch1Dto, projectDto.uuid()).setKey(FILE_1_KEY)); fileOnBranch2Dto = db.components().insertComponent(newFileDto(branch2Dto, projectDto.uuid()).setKey(FILE_1_KEY)); fileOnBranch3Dto = db.components().insertComponent(newFileDto(branch3Dto, projectDto.uuid()).setKey(FILE_1_KEY)); rule = db.rules().insert(); when(branch.getReferenceBranchUuid()).thenReturn(projectDto.uuid()); metadataHolder.setBranch(branch); metadataHolder.setProject(new Project(projectDto.uuid(), projectDto.getKey(), projectDto.name(), projectDto.description(), Collections.emptyList())); } @Test public void do_nothing_if_no_match() { DefaultIssue i = createIssue("issue1", rule.getKey(), Issue.STATUS_CONFIRMED, new Date()); copier.tryMerge(FILE_1, Collections.singleton(i)); verifyNoInteractions(issueLifecycle); } @Test public void do_nothing_if_no_new_issue() { db.issues().insert(IssueTesting.newIssue(rule, branch1Dto, fileOnBranch1Dto).setKee("issue1").setStatus(Issue.STATUS_CONFIRMED).setLine(1).setChecksum("checksum")); copier.tryMerge(FILE_1, Collections.emptyList()); verifyNoInteractions(issueLifecycle); } @Test public void merge_confirmed_issues() { db.issues().insert(IssueTesting.newIssue(rule, branch1Dto, fileOnBranch1Dto).setKee("issue1").setStatus(Issue.STATUS_CONFIRMED).setLine(1).setChecksum("checksum")); DefaultIssue newIssue = createIssue("issue2", rule.getKey(), Issue.STATUS_OPEN, new Date()); copier.tryMerge(FILE_1, Collections.singleton(newIssue)); ArgumentCaptor<DefaultIssue> issueToMerge = ArgumentCaptor.forClass(DefaultIssue.class); verify(issueLifecycle).mergeConfirmedOrResolvedFromPrOrBranch(eq(newIssue), issueToMerge.capture(), eq(BranchType.PULL_REQUEST), eq("myBranch1")); assertThat(issueToMerge.getValue().key()).isEqualTo("issue1"); } @Test public void prefer_more_recently_updated_issues() { Instant now = Instant.now(); db.issues().insert(IssueTesting.newIssue(rule, branch1Dto, fileOnBranch1Dto).setKee("issue1").setStatus(Issue.STATUS_REOPENED).setLine(1).setChecksum("checksum") .setIssueUpdateDate(Date.from(now.plus(2, ChronoUnit.SECONDS)))); db.issues().insert(IssueTesting.newIssue(rule, branch2Dto, fileOnBranch2Dto).setKee("issue2").setStatus(Issue.STATUS_OPEN).setLine(1).setChecksum("checksum") .setIssueUpdateDate(Date.from(now.plus(1, ChronoUnit.SECONDS)))); db.issues().insert(IssueTesting.newIssue(rule, branch3Dto, fileOnBranch3Dto).setKee("issue3").setStatus(Issue.STATUS_OPEN).setLine(1).setChecksum("checksum") .setIssueUpdateDate(Date.from(now))); DefaultIssue newIssue = createIssue("newIssue", rule.getKey(), Issue.STATUS_OPEN, new Date()); copier.tryMerge(FILE_1, Collections.singleton(newIssue)); ArgumentCaptor<DefaultIssue> issueToMerge = ArgumentCaptor.forClass(DefaultIssue.class); verify(issueLifecycle).mergeConfirmedOrResolvedFromPrOrBranch(eq(newIssue), issueToMerge.capture(), eq(BranchType.PULL_REQUEST), eq("myBranch1")); assertThat(issueToMerge.getValue().key()).isEqualTo("issue1"); } @Test public void lazy_load_changes() { UserDto user = db.users().insertUser(); IssueDto issue = db.issues() .insert(IssueTesting.newIssue(rule, branch2Dto, fileOnBranch2Dto).setKee("issue").setStatus(Issue.STATUS_CONFIRMED).setLine(1).setChecksum("checksum")); db.issues().insertComment(issue, user, "A comment 2"); db.issues().insertFieldDiffs(issue, FieldDiffs.parse("severity=BLOCKER|MINOR,assignee=foo|bar").setCreationDate(new Date())); DefaultIssue newIssue = createIssue("newIssue", rule.getKey(), Issue.STATUS_OPEN, new Date()); copier.tryMerge(FILE_1, Collections.singleton(newIssue)); ArgumentCaptor<DefaultIssue> issueToMerge = ArgumentCaptor.forClass(DefaultIssue.class); verify(issueLifecycle).mergeConfirmedOrResolvedFromPrOrBranch(eq(newIssue), issueToMerge.capture(), eq(BranchType.PULL_REQUEST), eq("myBranch2")); assertThat(issueToMerge.getValue().key()).isEqualTo("issue"); assertThat(issueToMerge.getValue().defaultIssueComments()).isNotEmpty(); assertThat(issueToMerge.getValue().changes()).isNotEmpty(); } private static DefaultIssue createIssue(String key, RuleKey ruleKey, String status, Date creationDate) { DefaultIssue issue = new DefaultIssue(); issue.setKey(key); issue.setRuleKey(ruleKey); issue.setMessage("msg"); issue.setLine(1); issue.setStatus(status); issue.setResolution(null); issue.setCreationDate(creationDate); issue.setChecksum("checksum"); return issue; } }
9,897
46.586538
174
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/SourceBranchComponentUuidsIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.issue; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.analysis.Branch; import org.sonar.db.DbTester; import org.sonar.db.component.BranchType; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.component.ProjectData; import org.sonar.db.protobuf.DbProjectBranches; import org.sonar.server.project.Project; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.component.SnapshotTesting.newAnalysis; public class SourceBranchComponentUuidsIT { private static final String BRANCH_KEY = "branch1"; private static final String PR_KEY = "pr1"; @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); @Rule public DbTester db = DbTester.create(); private SourceBranchComponentUuids underTest; private final Branch branch = mock(Branch.class); private ComponentDto branch1; private ComponentDto branch1File; private ComponentDto pr1File; @Before public void setup() { underTest = new SourceBranchComponentUuids(analysisMetadataHolder, db.getDbClient()); Project project = mock(Project.class); analysisMetadataHolder.setProject(project); analysisMetadataHolder.setBranch(branch); ProjectData projectData = db.components().insertPublicProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); when(project.getUuid()).thenReturn(projectData.projectUuid()); branch1 = db.components().insertProjectBranch(mainBranch, b -> b.setKey(BRANCH_KEY)); ComponentDto pr1branch = db.components().insertProjectBranch(mainBranch, b -> b.setKey(PR_KEY) .setBranchType(BranchType.PULL_REQUEST) .setPullRequestData(DbProjectBranches.PullRequestData.newBuilder().setBranch(BRANCH_KEY).build()) .setMergeBranchUuid(mainBranch.uuid())); branch1File = ComponentTesting.newFileDto(branch1, null, "file").setUuid("branch1File"); pr1File = ComponentTesting.newFileDto(pr1branch, null, "file").setUuid("file1"); db.components().insertComponents(branch1File, pr1File); } @Test public void should_support_db_key_when_looking_for_source_branch_component() { when(branch.getType()).thenReturn(BranchType.PULL_REQUEST); when(branch.getName()).thenReturn(BRANCH_KEY); when(branch.getPullRequestKey()).thenReturn(PR_KEY); db.components().insertSnapshot(newAnalysis(branch1)); assertThat(underTest.getSourceBranchComponentUuid(pr1File.getKey())).isEqualTo(branch1File.uuid()); assertThat(underTest.hasSourceBranchAnalysis()).isTrue(); } @Test public void should_support_key_when_looking_for_source_branch_component() { when(branch.getType()).thenReturn(BranchType.PULL_REQUEST); when(branch.getName()).thenReturn(BRANCH_KEY); when(branch.getPullRequestKey()).thenReturn(PR_KEY); db.components().insertSnapshot(newAnalysis(branch1)); assertThat(underTest.getSourceBranchComponentUuid(pr1File.getKey())).isEqualTo(branch1File.uuid()); } @Test public void return_null_if_file_doesnt_exist() { when(branch.getType()).thenReturn(BranchType.PULL_REQUEST); when(branch.getName()).thenReturn(BRANCH_KEY); when(branch.getPullRequestKey()).thenReturn(PR_KEY); db.components().insertSnapshot(newAnalysis(branch1)); assertThat(underTest.getSourceBranchComponentUuid("doesnt exist")).isNull(); } @Test public void skip_init_if_not_a_pull_request() { when(branch.getType()).thenReturn(BranchType.BRANCH); when(branch.getName()).thenReturn(BRANCH_KEY); assertThat(underTest.getSourceBranchComponentUuid(pr1File.getKey())).isNull(); } @Test public void skip_init_if_no_source_branch_analysis() { when(branch.getType()).thenReturn(BranchType.PULL_REQUEST); when(branch.getName()).thenReturn(BRANCH_KEY); assertThat(underTest.getSourceBranchComponentUuid(pr1File.getKey())).isNull(); } }
5,018
39.475806
103
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/TargetBranchComponentUuidsIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.issue; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.analysis.Branch; import org.sonar.db.DbTester; import org.sonar.db.component.BranchType; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.component.ProjectData; import org.sonar.db.protobuf.DbProjectBranches; import org.sonar.server.project.Project; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.component.SnapshotTesting.newAnalysis; public class TargetBranchComponentUuidsIT { private static final String BRANCH_KEY = "branch1"; private static final String PR_KEY = "pr1"; @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); @Rule public DbTester db = DbTester.create(); private TargetBranchComponentUuids underTest; private final Branch branch = mock(Branch.class); private ComponentDto branch1; private ComponentDto branch1File; private ComponentDto pr1File; @Before public void setup() { underTest = new TargetBranchComponentUuids(analysisMetadataHolder, db.getDbClient()); Project project = mock(Project.class); analysisMetadataHolder.setProject(project); analysisMetadataHolder.setBranch(branch); ProjectData projectData = db.components().insertPublicProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); when(project.getUuid()).thenReturn(projectData.projectUuid()); branch1 = db.components().insertProjectBranch(mainBranch, b -> b.setKey(BRANCH_KEY)); ComponentDto pr1branch = db.components().insertProjectBranch(mainBranch, b -> b.setKey(PR_KEY) .setBranchType(BranchType.PULL_REQUEST) .setPullRequestData(DbProjectBranches.PullRequestData.newBuilder().setTarget(BRANCH_KEY).build()) .setMergeBranchUuid(mainBranch.uuid())); branch1File = ComponentTesting.newFileDto(branch1, null, "file").setUuid("branch1File"); pr1File = ComponentTesting.newFileDto(pr1branch, null, "file").setUuid("file1"); db.components().insertComponents(branch1File, pr1File); } @Test public void should_support_db_key_when_looking_for_target_branch_component() { when(branch.getType()).thenReturn(BranchType.PULL_REQUEST); when(branch.getName()).thenReturn("prBranch"); when(branch.getTargetBranchName()).thenReturn(BRANCH_KEY); when(branch.getPullRequestKey()).thenReturn(PR_KEY); db.components().insertSnapshot(newAnalysis(branch1)); assertThat(underTest.getTargetBranchComponentUuid(pr1File.getKey())).isEqualTo(branch1File.uuid()); assertThat(underTest.hasTargetBranchAnalysis()).isTrue(); } @Test public void should_support_key_when_looking_for_target_branch_component() { when(branch.getType()).thenReturn(BranchType.PULL_REQUEST); when(branch.getName()).thenReturn("prBranch"); when(branch.getTargetBranchName()).thenReturn(BRANCH_KEY); when(branch.getPullRequestKey()).thenReturn(PR_KEY); db.components().insertSnapshot(newAnalysis(branch1)); assertThat(underTest.getTargetBranchComponentUuid(pr1File.getKey())).isEqualTo(branch1File.uuid()); } @Test public void return_null_if_file_doesnt_exist() { when(branch.getType()).thenReturn(BranchType.PULL_REQUEST); when(branch.getName()).thenReturn("prBranch"); when(branch.getTargetBranchName()).thenReturn(BRANCH_KEY); when(branch.getPullRequestKey()).thenReturn(PR_KEY); db.components().insertSnapshot(newAnalysis(branch1)); assertThat(underTest.getTargetBranchComponentUuid("doesnt exist")).isNull(); } @Test public void skip_init_if_not_a_pull_request() { when(branch.getType()).thenReturn(BranchType.BRANCH); when(branch.getName()).thenReturn("prBranch"); when(branch.getTargetBranchName()).thenReturn(BRANCH_KEY); assertThat(underTest.getTargetBranchComponentUuid(pr1File.getKey())).isNull(); } @Test public void skip_init_if_no_target_branch_analysis() { when(branch.getType()).thenReturn(BranchType.PULL_REQUEST); when(branch.getName()).thenReturn("prBranch"); when(branch.getTargetBranchName()).thenReturn(BRANCH_KEY); assertThat(underTest.getTargetBranchComponentUuid(pr1File.getKey())).isNull(); } }
5,333
40.348837
103
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/TrackerReferenceBranchInputFactoryIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.issue; import java.util.Collections; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReferenceBranchComponentUuids; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.tracking.Input; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class TrackerReferenceBranchInputFactoryIT { private final static String COMPONENT_KEY = "file1"; private final static String COMPONENT_UUID = "uuid1"; @Rule public DbTester db = DbTester.create(); private ComponentIssuesLoader componentIssuesLoader = mock(ComponentIssuesLoader.class); private ReferenceBranchComponentUuids referenceBranchComponentUuids = mock(ReferenceBranchComponentUuids.class); private TrackerReferenceBranchInputFactory underTest; @Before public void setUp() { underTest = new TrackerReferenceBranchInputFactory(componentIssuesLoader, referenceBranchComponentUuids, db.getDbClient()); } @Test public void gets_issues_and_hashes_in_matching_component() { DefaultIssue issue1 = new DefaultIssue(); when(referenceBranchComponentUuids.getComponentUuid(COMPONENT_KEY)).thenReturn(COMPONENT_UUID); when(componentIssuesLoader.loadOpenIssuesWithChanges(COMPONENT_UUID)).thenReturn(Collections.singletonList(issue1)); ComponentDto fileDto = ComponentTesting.newFileDto(ComponentTesting.newPublicProjectDto()).setUuid(COMPONENT_UUID); db.fileSources().insertFileSource(fileDto, 3); Component component = mock(Component.class); when(component.getKey()).thenReturn(COMPONENT_KEY); when(component.getType()).thenReturn(Component.Type.FILE); Input<DefaultIssue> input = underTest.create(component); assertThat(input.getIssues()).containsOnly(issue1); assertThat(input.getLineHashSequence().length()).isEqualTo(3); } @Test public void gets_nothing_when_there_is_no_matching_component() { Component component = mock(Component.class); when(component.getKey()).thenReturn(COMPONENT_KEY); when(component.getType()).thenReturn(Component.Type.FILE); Input<DefaultIssue> input = underTest.create(component); assertThat(input.getIssues()).isEmpty(); assertThat(input.getLineHashSequence().length()).isZero(); } }
3,418
40.695122
127
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/TrackerSourceBranchInputFactoryIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.issue; import java.util.Collections; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.tracking.Input; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class TrackerSourceBranchInputFactoryIT { private final static String COMPONENT_KEY = "file1"; private final static String COMPONENT_UUID = "uuid1"; @Rule public DbTester db = DbTester.create(); private final ComponentIssuesLoader componentIssuesLoader = mock(ComponentIssuesLoader.class); private final SourceBranchComponentUuids sourceBranchComponentUuids = mock(SourceBranchComponentUuids.class); private TrackerSourceBranchInputFactory underTest; @Before public void setUp() { underTest = new TrackerSourceBranchInputFactory(componentIssuesLoader, sourceBranchComponentUuids, db.getDbClient()); } @Test public void gets_issues_and_hashes_in_matching_component() { DefaultIssue issue1 = new DefaultIssue(); when(sourceBranchComponentUuids.getSourceBranchComponentUuid(COMPONENT_KEY)).thenReturn(COMPONENT_UUID); when(componentIssuesLoader.loadOpenIssuesWithChanges(COMPONENT_UUID)).thenReturn(Collections.singletonList(issue1)); ComponentDto fileDto = ComponentTesting.newFileDto(ComponentTesting.newPublicProjectDto()).setUuid(COMPONENT_UUID); db.fileSources().insertFileSource(fileDto, 3); Component component = mock(Component.class); when(component.getKey()).thenReturn(COMPONENT_KEY); when(component.getType()).thenReturn(Component.Type.FILE); Input<DefaultIssue> input = underTest.createForSourceBranch(component); assertThat(input.getIssues()).containsOnly(issue1); assertThat(input.getLineHashSequence().length()).isEqualTo(3); } @Test public void get_issues_without_line_hashes() { DefaultIssue issue1 = new DefaultIssue(); when(sourceBranchComponentUuids.getSourceBranchComponentUuid(COMPONENT_KEY)).thenReturn(COMPONENT_UUID); when(componentIssuesLoader.loadOpenIssuesWithChanges(COMPONENT_UUID)).thenReturn(Collections.singletonList(issue1)); ComponentDto fileDto = ComponentTesting.newFileDto(ComponentTesting.newPublicProjectDto()).setUuid(COMPONENT_UUID); db.fileSources().insertFileSource(fileDto, 0); Component component = mock(Component.class); when(component.getKey()).thenReturn(COMPONENT_KEY); when(component.getType()).thenReturn(Component.Type.FILE); Input<DefaultIssue> input = underTest.createForSourceBranch(component); assertThat(input.getIssues()).containsOnly(issue1); assertThat(input.getLineHashSequence().length()).isZero(); } @Test public void gets_nothing_when_there_is_no_matching_component() { Component component = mock(Component.class); when(component.getKey()).thenReturn(COMPONENT_KEY); when(component.getType()).thenReturn(Component.Type.FILE); Input<DefaultIssue> input = underTest.createForSourceBranch(component); assertThat(input.getIssues()).isEmpty(); assertThat(input.getLineHashSequence().length()).isZero(); } @Test public void hasSourceBranchAnalysis_returns_true_if_source_branch_of_pr_was_analysed() { when(sourceBranchComponentUuids.hasSourceBranchAnalysis()).thenReturn(true); assertThat(underTest.hasSourceBranchAnalysis()).isTrue(); } @Test public void hasSourceBranchAnalysis_returns_false_if_no_source_branch_analysis() { when(sourceBranchComponentUuids.hasSourceBranchAnalysis()).thenReturn(false); assertThat(underTest.hasSourceBranchAnalysis()).isFalse(); } }
4,732
41.258929
121
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/TrackerTargetBranchInputFactoryIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.issue; import java.util.Collections; import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.tracking.Input; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class TrackerTargetBranchInputFactoryIT { private final static String COMPONENT_KEY = "file1"; private final static String COMPONENT_UUID = "uuid1"; private final static String ORIGINAL_COMPONENT_KEY = "file2"; private final static String ORIGINAL_COMPONENT_UUID = "uuid2"; @Rule public DbTester db = DbTester.create(); private final ComponentIssuesLoader componentIssuesLoader = mock(ComponentIssuesLoader.class); private final TargetBranchComponentUuids targetBranchComponentUuids = mock(TargetBranchComponentUuids.class); private final MovedFilesRepository movedFilesRepository = mock(MovedFilesRepository.class); private TrackerTargetBranchInputFactory underTest; @Before public void setUp() { underTest = new TrackerTargetBranchInputFactory(componentIssuesLoader, targetBranchComponentUuids, db.getDbClient(), movedFilesRepository); } @Test public void gets_issues_and_hashes_in_matching_component() { DefaultIssue issue1 = new DefaultIssue(); when(targetBranchComponentUuids.getTargetBranchComponentUuid(COMPONENT_KEY)).thenReturn(COMPONENT_UUID); when(componentIssuesLoader.loadOpenIssuesWithChanges(COMPONENT_UUID)).thenReturn(Collections.singletonList(issue1)); ComponentDto fileDto = ComponentTesting.newFileDto(ComponentTesting.newPublicProjectDto()).setUuid(COMPONENT_UUID); db.fileSources().insertFileSource(fileDto, 3); Component component = getComponent(); Input<DefaultIssue> input = underTest.createForTargetBranch(component); assertThat(input.getIssues()).containsOnly(issue1); assertThat(input.getLineHashSequence().length()).isEqualTo(3); } @Test public void get_issues_without_line_hashes() { DefaultIssue issue1 = new DefaultIssue(); when(targetBranchComponentUuids.getTargetBranchComponentUuid(COMPONENT_KEY)).thenReturn(COMPONENT_UUID); when(componentIssuesLoader.loadOpenIssuesWithChanges(COMPONENT_UUID)).thenReturn(Collections.singletonList(issue1)); ComponentDto fileDto = ComponentTesting.newFileDto(ComponentTesting.newPublicProjectDto()).setUuid(COMPONENT_UUID); db.fileSources().insertFileSource(fileDto, 0); Component component = getComponent(); Input<DefaultIssue> input = underTest.createForTargetBranch(component); assertThat(input.getIssues()).containsOnly(issue1); assertThat(input.getLineHashSequence().length()).isZero(); } @Test public void gets_nothing_when_there_is_no_matching_component() { Component component = getComponent(); Input<DefaultIssue> input = underTest.createForTargetBranch(component); assertThat(input.getIssues()).isEmpty(); assertThat(input.getLineHashSequence().length()).isZero(); } @Test public void uses_original_component_uuid_when_component_is_moved_file() { Component component = getComponent(); MovedFilesRepository.OriginalFile originalFile = new MovedFilesRepository.OriginalFile(ORIGINAL_COMPONENT_UUID, ORIGINAL_COMPONENT_KEY); when(movedFilesRepository.getOriginalPullRequestFile(component)).thenReturn(Optional.of(originalFile)); when(targetBranchComponentUuids.getTargetBranchComponentUuid(ORIGINAL_COMPONENT_KEY)) .thenReturn(ORIGINAL_COMPONENT_UUID); DefaultIssue issue1 = new DefaultIssue(); when(componentIssuesLoader.loadOpenIssuesWithChanges(ORIGINAL_COMPONENT_UUID)).thenReturn(Collections.singletonList(issue1)); Input<DefaultIssue> targetBranchIssue = underTest.createForTargetBranch(component); verify(targetBranchComponentUuids).getTargetBranchComponentUuid(ORIGINAL_COMPONENT_KEY); assertThat(targetBranchIssue.getIssues()).containsOnly(issue1); } private Component getComponent() { Component component = mock(Component.class); when(component.getKey()).thenReturn(COMPONENT_KEY); when(component.getType()).thenReturn(Component.Type.FILE); return component; } @Test public void hasTargetBranchAnalysis_returns_true_if_source_branch_of_pr_was_analysed() { when(targetBranchComponentUuids.hasTargetBranchAnalysis()).thenReturn(true); assertThat(underTest.hasTargetBranchAnalysis()).isTrue(); } @Test public void hasTargetBranchAnalysis_returns_false_if_no_target_branch_analysis() { when(targetBranchComponentUuids.hasTargetBranchAnalysis()).thenReturn(false); assertThat(underTest.hasTargetBranchAnalysis()).isFalse(); } }
5,914
42.492647
143
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/measure/MeasureRepositoryImplIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.measure; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.List; import java.util.Map; import java.util.Optional; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.batch.BatchReportReader; import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricImpl; import org.sonar.ce.task.projectanalysis.metric.MetricRepository; import org.sonar.ce.task.projectanalysis.metric.ReportMetricValidator; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.SnapshotDto; import org.sonar.db.measure.MeasureDto; import org.sonar.db.metric.MetricDto; import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.scanner.protocol.output.ScannerReport.Measure.StringValue; import static com.google.common.collect.FluentIterable.from; 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.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.sonar.db.component.ComponentTesting.newFileDto; @RunWith(DataProviderRunner.class) public class MeasureRepositoryImplIT { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule public BatchReportReaderRule reportReader = new BatchReportReaderRule(); private static final String FILE_COMPONENT_KEY = "file cpt key"; private static final ReportComponent FILE_COMPONENT = ReportComponent.builder(Component.Type.FILE, 1).setKey(FILE_COMPONENT_KEY).build(); private static final ReportComponent OTHER_COMPONENT = ReportComponent.builder(Component.Type.FILE, 2).setKey("some other key").build(); private static final String METRIC_KEY_1 = "metric 1"; private static final int METRIC_ID_1 = 1; private static final String METRIC_KEY_2 = "metric 2"; private static final int METRIC_ID_2 = 2; private final Metric metric1 = mock(Metric.class); private final Metric metric2 = mock(Metric.class); private static final String LAST_ANALYSIS_UUID = "u123"; private static final String OTHER_ANALYSIS_UUID = "u369"; private static final Measure SOME_MEASURE = Measure.newMeasureBuilder().create("some value"); private static final String SOME_DATA = "some data"; private ReportMetricValidator reportMetricValidator = mock(ReportMetricValidator.class); private DbClient dbClient = dbTester.getDbClient(); private MetricRepository metricRepository = mock(MetricRepository.class); private MeasureRepositoryImpl underTest = new MeasureRepositoryImpl(dbClient, reportReader, metricRepository, reportMetricValidator); private DbClient mockedDbClient = mock(DbClient.class); private BatchReportReader mockBatchReportReader = mock(BatchReportReader.class); private MeasureRepositoryImpl underTestWithMock = new MeasureRepositoryImpl(mockedDbClient, mockBatchReportReader, metricRepository, reportMetricValidator); private DbSession dbSession = dbTester.getSession(); @Before public void setUp() { when(metric1.getKey()).thenReturn(METRIC_KEY_1); when(metric1.getType()).thenReturn(Metric.MetricType.STRING); when(metric2.getKey()).thenReturn(METRIC_KEY_2); when(metric2.getType()).thenReturn(Metric.MetricType.STRING); // references to metrics are consistent with DB by design when(metricRepository.getByKey(METRIC_KEY_1)).thenReturn(metric1); when(metricRepository.getByKey(METRIC_KEY_2)).thenReturn(metric2); } @Test public void getBaseMeasure_throws_NPE_and_does_not_open_session_if_component_is_null() { try { underTestWithMock.getBaseMeasure(null, metric1); fail("an NPE should have been raised"); } catch (NullPointerException e) { verifyNoInteractions(mockedDbClient); } } @Test public void getBaseMeasure_throws_NPE_and_does_not_open_session_if_metric_is_null() { try { underTestWithMock.getBaseMeasure(FILE_COMPONENT, null); fail("an NPE should have been raised"); } catch (NullPointerException e) { verifyNoInteractions(mockedDbClient); } } @Test public void getBaseMeasure_returns_absent_if_measure_does_not_exist_in_DB() { Optional<Measure> res = underTest.getBaseMeasure(FILE_COMPONENT, metric1); assertThat(res).isNotPresent(); } @Test public void getBaseMeasure_returns_Measure_if_measure_of_last_snapshot_only_in_DB() { ComponentDto project = dbTester.components().insertPrivateProject().getMainBranchComponent(); dbTester.components().insertComponent(newFileDto(project).setUuid(FILE_COMPONENT.getUuid())); SnapshotDto lastAnalysis = dbTester.components().insertSnapshot(project, t -> t.setLast(true)); SnapshotDto oldAnalysis = dbTester.components().insertSnapshot(project, t -> t.setLast(false)); MetricDto metric1 = dbTester.measures().insertMetric(t -> t.setValueType(org.sonar.api.measures.Metric.ValueType.STRING.name())); MetricDto metric2 = dbTester.measures().insertMetric(t -> t.setValueType(org.sonar.api.measures.Metric.ValueType.STRING.name())); dbClient.measureDao().insert(dbSession, createMeasureDto(metric1.getUuid(), FILE_COMPONENT.getUuid(), lastAnalysis.getUuid())); dbClient.measureDao().insert(dbSession, createMeasureDto(metric1.getUuid(), FILE_COMPONENT.getUuid(), oldAnalysis.getUuid())); dbSession.commit(); // metric 1 is associated to snapshot with "last=true" assertThat(underTest.getBaseMeasure(FILE_COMPONENT, metricOf(metric1)).get().getStringValue()) .isEqualTo(SOME_DATA); // metric 2 is associated to snapshot with "last=false" => not retrieved assertThat(underTest.getBaseMeasure(FILE_COMPONENT, metricOf(metric2))).isNotPresent(); } private Metric metricOf(MetricDto metricDto) { Metric res = mock(Metric.class); when(res.getKey()).thenReturn(metricDto.getKey()); when(res.getUuid()).thenReturn(metricDto.getUuid()); when(res.getType()).thenReturn(Metric.MetricType.valueOf(metricDto.getValueType())); return res; } @Test public void add_throws_NPE_if_Component_argument_is_null() { assertThatThrownBy(() -> underTest.add(null, metric1, SOME_MEASURE)) .isInstanceOf(NullPointerException.class); } @Test public void add_throws_NPE_if_Component_metric_is_null() { assertThatThrownBy(() -> underTest.add(FILE_COMPONENT, null, SOME_MEASURE)) .isInstanceOf(NullPointerException.class); } @Test public void add_throws_NPE_if_Component_measure_is_null() { assertThatThrownBy(() -> underTest.add(FILE_COMPONENT, metric1, null)) .isInstanceOf(NullPointerException.class); } @Test public void add_throws_UOE_if_measure_already_exists() { assertThatThrownBy(() -> { underTest.add(FILE_COMPONENT, metric1, SOME_MEASURE); underTest.add(FILE_COMPONENT, metric1, SOME_MEASURE); }) .isInstanceOf(UnsupportedOperationException.class); } @Test public void update_throws_NPE_if_Component_metric_is_null() { assertThatThrownBy(() -> underTest.update(FILE_COMPONENT, null, SOME_MEASURE)) .isInstanceOf(NullPointerException.class); } @Test public void update_throws_NPE_if_Component_measure_is_null() { assertThatThrownBy(() -> underTest.update(FILE_COMPONENT, metric1, null)) .isInstanceOf(NullPointerException.class); } @Test public void update_throws_UOE_if_measure_does_not_exists() { assertThatThrownBy(() -> underTest.update(FILE_COMPONENT, metric1, SOME_MEASURE)) .isInstanceOf(UnsupportedOperationException.class); } private static final List<Measure> MEASURES = ImmutableList.of( Measure.newMeasureBuilder().create(1), Measure.newMeasureBuilder().create(1L), Measure.newMeasureBuilder().create(1d, 1), Measure.newMeasureBuilder().create(true), Measure.newMeasureBuilder().create(false), Measure.newMeasureBuilder().create("sds"), Measure.newMeasureBuilder().create(Measure.Level.OK), Measure.newMeasureBuilder().createNoValue()); @DataProvider public static Object[][] measures() { return from(MEASURES).transform(new Function<Measure, Object[]>() { @Nullable @Override public Object[] apply(Measure input) { return new Measure[] {input}; } }).toArray(Object[].class); } @Test public void add_accepts_NO_VALUE_as_measure_arg() { for (Metric.MetricType metricType : Metric.MetricType.values()) { underTest.add(FILE_COMPONENT, new MetricImpl("1", "key" + metricType, "name" + metricType, metricType), Measure.newMeasureBuilder().createNoValue()); } } @Test @UseDataProvider("measures") public void update_throws_IAE_if_valueType_of_Measure_is_not_the_same_as_the_Metric_valueType_unless_NO_VALUE(Measure measure) { for (Metric.MetricType metricType : Metric.MetricType.values()) { if (metricType.getValueType() == measure.getValueType() || measure.getValueType() == Measure.ValueType.NO_VALUE) { continue; } try { final MetricImpl metric = new MetricImpl("1", "key" + metricType, "name" + metricType, metricType); underTest.add(FILE_COMPONENT, metric, getSomeMeasureByValueType(metricType)); underTest.update(FILE_COMPONENT, metric, measure); fail("An IllegalArgumentException should have been raised"); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(format( "Measure's ValueType (%s) is not consistent with the Metric's ValueType (%s)", measure.getValueType(), metricType.getValueType())); } } } @Test public void update_accepts_NO_VALUE_as_measure_arg() { for (Metric.MetricType metricType : Metric.MetricType.values()) { MetricImpl metric = new MetricImpl("1", "key" + metricType, "name" + metricType, metricType); underTest.add(FILE_COMPONENT, metric, getSomeMeasureByValueType(metricType)); underTest.update(FILE_COMPONENT, metric, Measure.newMeasureBuilder().createNoValue()); } } private Measure getSomeMeasureByValueType(final Metric.MetricType metricType) { return MEASURES.stream().filter(input -> input.getValueType() == metricType.getValueType()).findFirst().get(); } @Test public void update_supports_updating_to_the_same_value() { underTest.add(FILE_COMPONENT, metric1, SOME_MEASURE); underTest.update(FILE_COMPONENT, metric1, SOME_MEASURE); } @Test public void update_updates_the_stored_value() { Measure newMeasure = Measure.updatedMeasureBuilder(SOME_MEASURE).create(); underTest.add(FILE_COMPONENT, metric1, SOME_MEASURE); underTest.update(FILE_COMPONENT, metric1, newMeasure); assertThat(underTest.getRawMeasure(FILE_COMPONENT, metric1)).containsSame(newMeasure); } @Test public void getRawMeasure_throws_NPE_without_reading_batch_report_if_component_arg_is_null() { try { underTestWithMock.getRawMeasure(null, metric1); fail("an NPE should have been raised"); } catch (NullPointerException e) { verifyNoMoreInteractions(mockBatchReportReader); } } @Test public void getRawMeasure_throws_NPE_without_reading_batch_report_if_metric_arg_is_null() { try { underTestWithMock.getRawMeasure(FILE_COMPONENT, null); fail("an NPE should have been raised"); } catch (NullPointerException e) { verifyNoMoreInteractions(mockBatchReportReader); } } @Test public void getRawMeasure_returns_measure_added_through_add_method() { underTest.add(FILE_COMPONENT, metric1, SOME_MEASURE); Optional<Measure> res = underTest.getRawMeasure(FILE_COMPONENT, metric1); assertThat(res) .isPresent() .containsSame(SOME_MEASURE); // make sure we really match on the specified component and metric assertThat(underTest.getRawMeasure(OTHER_COMPONENT, metric1)).isNotPresent(); assertThat(underTest.getRawMeasure(FILE_COMPONENT, metric2)).isNotPresent(); } @Test public void getRawMeasure_returns_measure_from_batch_if_not_added_through_add_method() { String value = "trololo"; when(reportMetricValidator.validate(METRIC_KEY_1)).thenReturn(true); reportReader.putMeasures(FILE_COMPONENT.getReportAttributes().getRef(), ImmutableList.of( ScannerReport.Measure.newBuilder().setMetricKey(METRIC_KEY_1).setStringValue(StringValue.newBuilder().setValue(value)).build())); Optional<Measure> res = underTest.getRawMeasure(FILE_COMPONENT, metric1); assertThat(res).isPresent(); assertThat(res.get().getStringValue()).isEqualTo(value); // make sure we really match on the specified component and metric assertThat(underTest.getRawMeasure(FILE_COMPONENT, metric2)).isNotPresent(); assertThat(underTest.getRawMeasure(OTHER_COMPONENT, metric1)).isNotPresent(); } @Test public void getRawMeasure_returns_only_validate_measure_from_batch_if_not_added_through_add_method() { when(reportMetricValidator.validate(METRIC_KEY_1)).thenReturn(true); when(reportMetricValidator.validate(METRIC_KEY_2)).thenReturn(false); reportReader.putMeasures(FILE_COMPONENT.getReportAttributes().getRef(), ImmutableList.of( ScannerReport.Measure.newBuilder().setMetricKey(METRIC_KEY_1).setStringValue(StringValue.newBuilder().setValue("value1")).build(), ScannerReport.Measure.newBuilder().setMetricKey(METRIC_KEY_2).setStringValue(StringValue.newBuilder().setValue("value2")).build())); assertThat(underTest.getRawMeasure(FILE_COMPONENT, metric1)).isPresent(); assertThat(underTest.getRawMeasure(FILE_COMPONENT, metric2)).isNotPresent(); } @Test public void getRawMeasure_retrieves_added_measure_over_batch_measure() { when(reportMetricValidator.validate(METRIC_KEY_1)).thenReturn(true); reportReader.putMeasures(FILE_COMPONENT.getReportAttributes().getRef(), ImmutableList.of( ScannerReport.Measure.newBuilder().setMetricKey(METRIC_KEY_1).setStringValue(StringValue.newBuilder().setValue("some value")).build())); Measure addedMeasure = SOME_MEASURE; underTest.add(FILE_COMPONENT, metric1, addedMeasure); Optional<Measure> res = underTest.getRawMeasure(FILE_COMPONENT, metric1); assertThat(res) .isPresent() .containsSame(addedMeasure); } @Test public void getRawMeasure_retrieves_measure_from_batch_and_caches_it_locally_so_that_it_can_be_updated() { when(reportMetricValidator.validate(METRIC_KEY_1)).thenReturn(true); reportReader.putMeasures(FILE_COMPONENT.getReportAttributes().getRef(), ImmutableList.of( ScannerReport.Measure.newBuilder().setMetricKey(METRIC_KEY_1).setStringValue(StringValue.newBuilder().setValue("some value")).build())); Optional<Measure> measure = underTest.getRawMeasure(FILE_COMPONENT, metric1); underTest.update(FILE_COMPONENT, metric1, Measure.updatedMeasureBuilder(measure.get()).create()); } @Test public void getRawMeasures_returns_added_measures_over_batch_measures() { when(reportMetricValidator.validate(METRIC_KEY_1)).thenReturn(true); when(reportMetricValidator.validate(METRIC_KEY_2)).thenReturn(true); ScannerReport.Measure batchMeasure1 = ScannerReport.Measure.newBuilder().setMetricKey(METRIC_KEY_1).setStringValue(StringValue.newBuilder().setValue("some value")).build(); ScannerReport.Measure batchMeasure2 = ScannerReport.Measure.newBuilder().setMetricKey(METRIC_KEY_2).setStringValue(StringValue.newBuilder().setValue("some value")).build(); reportReader.putMeasures(FILE_COMPONENT.getReportAttributes().getRef(), ImmutableList.of(batchMeasure1, batchMeasure2)); Measure addedMeasure = SOME_MEASURE; underTest.add(FILE_COMPONENT, metric1, addedMeasure); Map<String, Measure> rawMeasures = underTest.getRawMeasures(FILE_COMPONENT); assertThat(rawMeasures.keySet()).hasSize(2); assertThat(rawMeasures).containsEntry(METRIC_KEY_1, addedMeasure); assertThat(rawMeasures.get(METRIC_KEY_2)).extracting(Measure::getStringValue).isEqualTo("some value"); } private static MeasureDto createMeasureDto(String metricUuid, String componentUuid, String analysisUuid) { return new MeasureDto() .setComponentUuid(componentUuid) .setAnalysisUuid(analysisUuid) .setData(SOME_DATA) .setMetricUuid(metricUuid); } }
17,935
42.853301
176
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/metric/MetricRepositoryImplIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.metric; import java.util.List; import java.util.Random; import java.util.stream.IntStream; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.metric.MetricDto; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class MetricRepositoryImplIT { private static final String SOME_KEY = "some_key"; private static final String SOME_UUID = "uuid"; @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); private DbClient dbClient = dbTester.getDbClient(); private MetricRepositoryImpl underTest = new MetricRepositoryImpl(dbClient); @Test public void getByKey_throws_NPE_if_arg_is_null() { assertThatThrownBy(() -> underTest.getByKey(null)) .isInstanceOf(NullPointerException.class); } @Test public void getByKey_throws_ISE_if_start_has_not_been_called() { assertThatThrownBy(() -> underTest.getByKey(SOME_KEY)) .isInstanceOf(IllegalStateException.class) .hasMessage("Metric cache has not been initialized"); } @Test public void getByKey_throws_ISE_of_Metric_does_not_exist() { assertThatThrownBy(() -> { underTest.start(); underTest.getByKey(SOME_KEY); }) .isInstanceOf(IllegalStateException.class) .hasMessage(String.format("Metric with key '%s' does not exist", SOME_KEY)); } @Test public void getByKey_throws_ISE_of_Metric_is_disabled() { dbTester.measures().insertMetric(t -> t.setKey("complexity").setEnabled(false)); underTest.start(); assertThatThrownBy(() -> underTest.getByKey("complexity")) .isInstanceOf(IllegalStateException.class) .hasMessage(String.format("Metric with key '%s' does not exist", "complexity")); } @Test public void getByKey_find_enabled_Metrics() { MetricDto ncloc = dbTester.measures().insertMetric(t -> t.setKey("ncloc").setEnabled(true)); MetricDto coverage = dbTester.measures().insertMetric(t -> t.setKey("coverage").setEnabled(true)); underTest.start(); assertThat(underTest.getByKey("ncloc").getUuid()).isEqualTo(ncloc.getUuid()); assertThat(underTest.getByKey("coverage").getUuid()).isEqualTo(coverage.getUuid()); } @Test public void getById_throws_ISE_if_start_has_not_been_called() { assertThatThrownBy(() -> underTest.getByUuid(SOME_UUID)) .isInstanceOf(IllegalStateException.class) .hasMessage("Metric cache has not been initialized"); } @Test public void getById_throws_ISE_of_Metric_does_not_exist() { underTest.start(); assertThatThrownBy(() -> underTest.getByUuid(SOME_UUID)) .isInstanceOf(IllegalStateException.class) .hasMessage(String.format("Metric with uuid '%s' does not exist", SOME_UUID)); } @Test public void getById_throws_ISE_of_Metric_is_disabled() { dbTester.measures().insertMetric(t -> t.setKey("complexity").setEnabled(false)); underTest.start(); assertThatThrownBy(() -> underTest.getByUuid(SOME_UUID)) .isInstanceOf(IllegalStateException.class) .hasMessage(String.format("Metric with uuid '%s' does not exist", SOME_UUID)); } @Test public void getById_find_enabled_Metrics() { MetricDto ncloc = dbTester.measures().insertMetric(t -> t.setKey("ncloc").setEnabled(true)); MetricDto coverage = dbTester.measures().insertMetric(t -> t.setKey("coverage").setEnabled(true)); underTest.start(); assertThat(underTest.getByUuid(ncloc.getUuid()).getKey()).isEqualTo("ncloc"); assertThat(underTest.getByUuid(coverage.getUuid()).getKey()).isEqualTo("coverage"); } @Test public void getOptionalById_throws_ISE_if_start_has_not_been_called() { assertThatThrownBy(() -> underTest.getOptionalByUuid(SOME_UUID)) .isInstanceOf(IllegalStateException.class) .hasMessage("Metric cache has not been initialized"); } @Test public void getOptionalById_returns_empty_of_Metric_does_not_exist() { underTest.start(); assertThat(underTest.getOptionalByUuid(SOME_UUID)).isEmpty(); } @Test public void getOptionalById_returns_empty_of_Metric_is_disabled() { dbTester.measures().insertMetric(t -> t.setKey("complexity").setEnabled(false)); underTest.start(); assertThat(underTest.getOptionalByUuid(SOME_UUID)).isEmpty(); } @Test public void getOptionalById_find_enabled_Metrics() { MetricDto ncloc = dbTester.measures().insertMetric(t -> t.setKey("ncloc").setEnabled(true)); MetricDto coverage = dbTester.measures().insertMetric(t -> t.setKey("coverage").setEnabled(true)); underTest.start(); assertThat(underTest.getOptionalByUuid(ncloc.getUuid()).get().getKey()).isEqualTo("ncloc"); assertThat(underTest.getOptionalByUuid(coverage.getUuid()).get().getKey()).isEqualTo("coverage"); } @Test public void get_all_metrics() { List<MetricDto> enabledMetrics = IntStream.range(0, 1 + new Random().nextInt(12)) .mapToObj(i -> dbTester.measures().insertMetric(t -> t.setKey("key_enabled_" + i).setEnabled(true))) .toList(); IntStream.range(0, 1 + new Random().nextInt(12)) .forEach(i -> dbTester.measures().insertMetric(t -> t.setKey("key_disabled_" + i).setEnabled(false))); underTest.start(); assertThat(underTest.getAll()) .extracting(Metric::getKey) .containsOnly(enabledMetrics.stream().map(MetricDto::getKey).toArray(String[]::new)); } @Test public void getMetricsByType_givenRatingType_returnRatingMetrics() { List<MetricDto> enabledMetrics = IntStream.range(0, 1 + new Random().nextInt(12)) .mapToObj(i -> dbTester.measures().insertMetric(t -> t.setKey("key_enabled_" + i).setEnabled(true).setValueType("RATING"))) .toList(); underTest.start(); assertThat(underTest.getMetricsByType(Metric.MetricType.RATING)) .extracting(Metric::getKey) .containsOnly(enabledMetrics.stream().map(MetricDto::getKey).toArray(String[]::new)); } @Test public void getMetricsByType_givenRatingTypeAndWantedMilisecType_returnEmptyList() { IntStream.range(0, 1 + new Random().nextInt(12)) .mapToObj(i -> dbTester.measures().insertMetric(t -> t.setKey("key_enabled_" + i).setEnabled(true).setValueType("RATING"))) .toList(); underTest.start(); assertThat(underTest.getMetricsByType(Metric.MetricType.MILLISEC)).isEmpty(); } @Test public void getMetricsByType_givenOnlyMilisecTypeAndWantedRatingMetrics_returnEmptyList() { IntStream.range(0, 1 + new Random().nextInt(12)) .mapToObj(i -> dbTester.measures().insertMetric(t -> t.setKey("key_enabled_" + i).setEnabled(true).setValueType("MILISEC"))); underTest.start(); assertThat(underTest.getMetricsByType(Metric.MetricType.RATING)).isEmpty(); } @Test public void getMetricsByType_givenMetricsAreNull_throwException() { assertThatThrownBy(() -> underTest.getMetricsByType(Metric.MetricType.RATING)) .isInstanceOf(IllegalStateException.class); } }
7,921
36.018692
131
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/period/NewCodeReferenceBranchComponentUuidsIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.period; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.db.DbTester; import org.sonar.db.component.BranchType; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.component.ProjectData; import org.sonar.db.newcodeperiod.NewCodePeriodType; import org.sonar.server.project.Project; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.component.SnapshotTesting.newAnalysis; public class NewCodeReferenceBranchComponentUuidsIT { @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); @Rule public PeriodHolderRule periodHolder = new PeriodHolderRule(); @Rule public DbTester db = DbTester.create(); private NewCodeReferenceBranchComponentUuids underTest = new NewCodeReferenceBranchComponentUuids(analysisMetadataHolder, periodHolder, db.getDbClient()); private ComponentDto branch1; private ComponentDto branch1File; private ComponentDto pr1File; private ComponentDto pr2File; private Project project = mock(Project.class); private ComponentDto pr1; private ComponentDto pr2; private ComponentDto branch2; private ComponentDto branch2File; @Before public void setUp() { analysisMetadataHolder.setProject(project); ProjectData projectData = db.components().insertPublicProject(); when(project.getUuid()).thenReturn(projectData.projectUuid()); branch1 = db.components().insertProjectBranch(projectData.getMainBranchComponent(), b -> b.setKey("branch1")); branch2 = db.components().insertProjectBranch(projectData.getMainBranchComponent(), b -> b.setKey("branch2")); pr1 = db.components().insertProjectBranch(projectData.getMainBranchComponent(), b -> b.setKey("pr1").setBranchType(BranchType.PULL_REQUEST).setMergeBranchUuid(branch1.uuid())); pr2 = db.components().insertProjectBranch(projectData.getMainBranchComponent(), b -> b.setKey("pr2").setBranchType(BranchType.PULL_REQUEST).setMergeBranchUuid(branch1.uuid())); branch1File = ComponentTesting.newFileDto(branch1, null, "file").setUuid("branch1File"); branch2File = ComponentTesting.newFileDto(branch2, null, "file").setUuid("branch2File"); pr1File = ComponentTesting.newFileDto(pr1, null, "file").setUuid("file1"); pr2File = ComponentTesting.newFileDto(pr2, null, "file").setUuid("file2"); db.components().insertComponents(branch1File, pr1File, pr2File, branch2File); } @Test public void should_support_db_key_when_looking_for_reference_component() { periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "branch1", null)); db.components().insertSnapshot(newAnalysis(branch1)); assertThat(underTest.getComponentUuid(pr1File.getKey())).isEqualTo(branch1File.uuid()); } @Test public void should_support_key_when_looking_for_reference_component() { periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "branch1", null)); db.components().insertSnapshot(newAnalysis(branch1)); assertThat(underTest.getComponentUuid(pr1File.getKey())).isEqualTo(branch1File.uuid()); } @Test public void return_null_if_file_doesnt_exist() { periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "branch1", null)); db.components().insertSnapshot(newAnalysis(branch1)); assertThat(underTest.getComponentUuid("doesnt exist")).isNull(); } @Test public void skip_init_if_no_reference_branch_analysis() { periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "branch1", null)); assertThat(underTest.getComponentUuid(pr1File.getKey())).isNull(); } @Test public void skip_init_if_branch_not_found() { periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "unknown", null)); assertThat(underTest.getComponentUuid(pr1File.getKey())).isNull(); } @Test public void throw_ise_if_mode_is_not_reference_branch() { periodHolder.setPeriod(new Period(NewCodePeriodType.NUMBER_OF_DAYS.name(), "10", 1000L)); assertThatThrownBy(() -> underTest.getComponentUuid(pr1File.getKey())) .isInstanceOf(IllegalStateException.class); } }
5,341
44.271186
180
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/scm/ScmInfoDbLoaderIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.task.projectanalysis.scm; import com.google.common.collect.ImmutableList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Optional; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.System2; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.ce.task.projectanalysis.analysis.Analysis; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.analysis.Branch; import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReferenceBranchComponentUuids; import org.sonar.ce.task.projectanalysis.filemove.MutableMovedFilesRepositoryRule; import org.sonar.ce.task.projectanalysis.period.NewCodeReferenceBranchComponentUuids; import org.sonar.ce.task.projectanalysis.period.Period; import org.sonar.ce.task.projectanalysis.period.PeriodHolderRule; import org.sonar.core.hash.SourceHashComputer; import org.sonar.core.util.Uuids; import org.sonar.db.DbTester; import org.sonar.db.component.BranchType; import org.sonar.db.newcodeperiod.NewCodePeriodType; import org.sonar.db.protobuf.DbFileSources; import org.sonar.db.source.FileSourceDto; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.slf4j.event.Level.TRACE; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; public class ScmInfoDbLoaderIT { static final int FILE_REF = 1; static final Component FILE = builder(Component.Type.FILE, FILE_REF).setKey("FILE_KEY").setUuid("FILE_UUID").build(); static final long DATE_1 = 123456789L; static Analysis baseProjectAnalysis = new Analysis.Builder() .setUuid("uuid_1") .setCreatedAt(123456789L) .build(); @Rule public LogTester logTester = new LogTester(); @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule public BatchReportReaderRule reportReader = new BatchReportReaderRule(); @Rule public MutableMovedFilesRepositoryRule movedFiles = new MutableMovedFilesRepositoryRule(); @Rule public PeriodHolderRule periodHolder = new PeriodHolderRule(); private final Branch branch = mock(Branch.class); private final ReferenceBranchComponentUuids referenceBranchComponentUuids = mock(ReferenceBranchComponentUuids.class); private final NewCodeReferenceBranchComponentUuids newCodeReferenceBranchComponentUuids = mock(NewCodeReferenceBranchComponentUuids.class); private final ScmInfoDbLoader underTest = new ScmInfoDbLoader(analysisMetadataHolder, movedFiles, dbTester.getDbClient(), referenceBranchComponentUuids, newCodeReferenceBranchComponentUuids, periodHolder); @Before public void before() { logTester.setLevel(TRACE); periodHolder.setPeriod(new Period(NewCodePeriodType.PREVIOUS_VERSION.name(), null, null)); } @Test public void returns_ScmInfo_from_DB() { analysisMetadataHolder.setBaseAnalysis(baseProjectAnalysis); analysisMetadataHolder.setBranch(null); String hash = computeSourceHash(1); addFileSourceInDb("henry", DATE_1, "rev-1", hash); DbScmInfo scmInfo = underTest.getScmInfo(FILE).get(); assertThat(scmInfo.getAllChangesets()).hasSize(1); assertThat(scmInfo.fileHash()).isEqualTo(hash); assertThat(logTester.logs(TRACE)).contains("Reading SCM info from DB for file 'FILE_UUID'"); } @Test public void read_from_reference_branch_if_no_base() { analysisMetadataHolder.setBaseAnalysis(null); analysisMetadataHolder.setBranch(branch); String referenceFileUuid = "referenceFileUuid"; String hash = computeSourceHash(1); when(referenceBranchComponentUuids.getComponentUuid(FILE.getKey())).thenReturn(referenceFileUuid); addFileSourceInDb("henry", DATE_1, "rev-1", hash, referenceFileUuid); DbScmInfo scmInfo = underTest.getScmInfo(FILE).get(); assertThat(scmInfo.getAllChangesets()).hasSize(1); assertThat(scmInfo.fileHash()).isEqualTo(hash); assertThat(logTester.logs(TRACE)).contains("Reading SCM info from DB for file 'referenceFileUuid'"); } @Test public void read_from_target_if_pullrequest() { Branch branch = mock(Branch.class); when(branch.getType()).thenReturn(BranchType.PULL_REQUEST); analysisMetadataHolder.setBaseAnalysis(null); analysisMetadataHolder.setBranch(branch); String targetBranchFileUuid = "targetBranchFileUuid"; String hash = computeSourceHash(1); when(referenceBranchComponentUuids.getComponentUuid(FILE.getKey())).thenReturn(targetBranchFileUuid); addFileSourceInDb("henry", DATE_1, "rev-1", hash, targetBranchFileUuid); DbScmInfo scmInfo = underTest.getScmInfo(FILE).get(); assertThat(scmInfo.getAllChangesets()).hasSize(1); assertThat(scmInfo.fileHash()).isEqualTo(hash); assertThat(logTester.logs(TRACE)).contains("Reading SCM info from DB for file 'targetBranchFileUuid'"); } @Test public void read_from_target_if_reference_branch() { periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), null, null)); Branch branch = mock(Branch.class); when(branch.getType()).thenReturn(BranchType.BRANCH); analysisMetadataHolder.setBaseAnalysis(null); analysisMetadataHolder.setBranch(branch); String targetBranchFileUuid = "targetBranchFileUuid"; String hash = computeSourceHash(1); when(newCodeReferenceBranchComponentUuids.getComponentUuid(FILE.getKey())).thenReturn(targetBranchFileUuid); addFileSourceInDb("henry", DATE_1, "rev-1", hash, targetBranchFileUuid); DbScmInfo scmInfo = underTest.getScmInfo(FILE).get(); assertThat(scmInfo.getAllChangesets()).hasSize(1); assertThat(scmInfo.fileHash()).isEqualTo(hash); assertThat(logTester.logs(TRACE)).contains("Reading SCM info from DB for file 'targetBranchFileUuid'"); } @Test public void read_from_db_if_not_exist_in_reference_branch() { periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), null, null)); Branch branch = mock(Branch.class); when(branch.getType()).thenReturn(BranchType.BRANCH); analysisMetadataHolder.setBaseAnalysis(null); analysisMetadataHolder.setBranch(branch); String hash = computeSourceHash(1); addFileSourceInDb("henry", DATE_1, "rev-1", hash, FILE.getUuid()); DbScmInfo scmInfo = underTest.getScmInfo(FILE).get(); assertThat(scmInfo.getAllChangesets()).hasSize(1); assertThat(scmInfo.fileHash()).isEqualTo(hash); assertThat(logTester.logs(TRACE)).contains("Reading SCM info from DB for file 'FILE_UUID'"); } @Test public void return_empty_if_no_dto_available() { analysisMetadataHolder.setBaseAnalysis(baseProjectAnalysis); analysisMetadataHolder.setBranch(null); Optional<DbScmInfo> scmInfo = underTest.getScmInfo(FILE); assertThat(logTester.logs(TRACE)).contains("Reading SCM info from DB for file 'FILE_UUID'"); assertThat(scmInfo).isEmpty(); } @Test public void do_not_read_from_db_on_first_analysis_if_there_is_no_reference_branch() { Branch branch = mock(Branch.class); when(branch.getType()).thenReturn(BranchType.PULL_REQUEST); analysisMetadataHolder.setBaseAnalysis(null); analysisMetadataHolder.setBranch(branch); assertThat(underTest.getScmInfo(FILE)).isEmpty(); assertThat(logTester.logs(TRACE)).isEmpty(); } private static List<String> generateLines(int lineCount) { ImmutableList.Builder<String> builder = ImmutableList.builder(); for (int i = 0; i < lineCount; i++) { builder.add("line " + i); } return builder.build(); } private static String computeSourceHash(int lineCount) { SourceHashComputer sourceHashComputer = new SourceHashComputer(); Iterator<String> lines = generateLines(lineCount).iterator(); while (lines.hasNext()) { sourceHashComputer.addLine(lines.next(), lines.hasNext()); } return sourceHashComputer.getHash(); } private void addFileSourceInDb(@Nullable String author, @Nullable Long date, @Nullable String revision, String srcHash) { addFileSourceInDb(author, date, revision, srcHash, FILE.getUuid()); } private void addFileSourceInDb(@Nullable String author, @Nullable Long date, @Nullable String revision, String srcHash, String fileUuid) { DbFileSources.Data.Builder fileDataBuilder = DbFileSources.Data.newBuilder(); DbFileSources.Line.Builder builder = fileDataBuilder.addLinesBuilder() .setLine(1); if (author != null) { builder.setScmAuthor(author); } if (date != null) { builder.setScmDate(date); } if (revision != null) { builder.setScmRevision(revision); } dbTester.getDbClient().fileSourceDao().insert(dbTester.getSession(), new FileSourceDto() .setUuid(Uuids.createFast()) .setLineHashes(Collections.singletonList("lineHash")) .setFileUuid(fileUuid) .setProjectUuid("PROJECT_UUID") .setSourceData(fileDataBuilder.build()) .setSrcHash(srcHash)); dbTester.commit(); } }
10,197
39.629482
154
java