From: Matteo Mara Date: Mon, 7 Oct 2024 16:13:33 +0000 (+0200) Subject: NO-JIRA Stop using deprecated methods from RandomStringUtils X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=1ad3667d30dd82213ae47bea2c267188f003b2c7;p=sonarqube.git NO-JIRA Stop using deprecated methods from RandomStringUtils --- diff --git a/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/GenericApplicationHttpClientTest.java b/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/GenericApplicationHttpClientTest.java index 5beea1acad1..8accc121408 100644 --- a/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/GenericApplicationHttpClientTest.java +++ b/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/GenericApplicationHttpClientTest.java @@ -47,7 +47,7 @@ import org.sonar.auth.github.security.AccessToken; import org.sonar.auth.github.security.UserAccessToken; import static java.lang.String.format; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; @@ -66,9 +66,9 @@ public class GenericApplicationHttpClientTest { private GenericApplicationHttpClient underTest; - private final AccessToken accessToken = new UserAccessToken(randomAlphabetic(10)); - private final String randomEndPoint = "/" + randomAlphabetic(10); - private final String randomBody = randomAlphabetic(40); + private final AccessToken accessToken = new UserAccessToken(secure().nextAlphabetic(10)); + private final String randomEndPoint = "/" + secure().nextAlphabetic(10); + private final String randomBody = secure().nextAlphabetic(40); private String appUrl; @Before diff --git a/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/GithubApplicationClientImplTest.java b/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/GithubApplicationClientImplTest.java index 071001b8c01..15c2747e6a9 100644 --- a/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/GithubApplicationClientImplTest.java +++ b/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/GithubApplicationClientImplTest.java @@ -64,7 +64,7 @@ import static java.net.HttpURLConnection.HTTP_CREATED; import static java.net.HttpURLConnection.HTTP_FORBIDDEN; import static java.net.HttpURLConnection.HTTP_NOT_FOUND; import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; @@ -339,7 +339,7 @@ public class GithubApplicationClientImplTest { @Test @UseDataProvider("githubServers") public void createUserAccessToken_from_authorization_code_returns_access_token(String apiUrl, String appUrl) throws IOException { - String token = randomAlphanumeric(10); + String token = secure().nextAlphanumeric(10); when(githubApplicationHttpClient.post(appUrl, null, "/login/oauth/access_token?client_id=clientId&client_secret=clientSecret&code=code")) .thenReturn(new OkGetResponse("access_token=" + token + "&status=")); @@ -389,7 +389,7 @@ public class GithubApplicationClientImplTest { @Test public void listOrganizations_fail_on_failure() throws IOException { String appUrl = "https://github.sonarsource.com"; - AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10)); + AccessToken accessToken = new UserAccessToken(secure().nextAlphanumeric(10)); when(githubApplicationHttpClient.get(appUrl, accessToken, format("/user/installations?page=%s&per_page=%s", 1, 100))) .thenThrow(new IOException("OOPS")); @@ -421,7 +421,7 @@ public class GithubApplicationClientImplTest { @Test public void listOrganizations_returns_no_installations() throws IOException { String appUrl = "https://github.sonarsource.com"; - AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10)); + AccessToken accessToken = new UserAccessToken(secure().nextAlphanumeric(10)); String responseJson = """ { "total_count": 0 @@ -440,7 +440,7 @@ public class GithubApplicationClientImplTest { @Test public void listOrganizations_returns_pages_results() throws IOException { String appUrl = "https://github.sonarsource.com"; - AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10)); + AccessToken accessToken = new UserAccessToken(secure().nextAlphanumeric(10)); String responseJson = """ { "total_count": 2, @@ -611,7 +611,7 @@ public class GithubApplicationClientImplTest { @Test public void listRepositories_fail_on_failure() throws IOException { String appUrl = "https://github.sonarsource.com"; - AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10)); + AccessToken accessToken = new UserAccessToken(secure().nextAlphanumeric(10)); when(githubApplicationHttpClient.get(appUrl, accessToken, format("/search/repositories?q=%s&page=%s&per_page=%s", "org:test", 1, 100))) .thenThrow(new IOException("OOPS")); @@ -643,7 +643,7 @@ public class GithubApplicationClientImplTest { @Test public void listRepositories_returns_empty_results() throws IOException { String appUrl = "https://github.sonarsource.com"; - AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10)); + AccessToken accessToken = new UserAccessToken(secure().nextAlphanumeric(10)); String responseJson = "{\n" + " \"total_count\": 0\n" + "}"; @@ -660,7 +660,7 @@ public class GithubApplicationClientImplTest { @Test public void listRepositories_returns_pages_results() throws IOException { String appUrl = "https://github.sonarsource.com"; - AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10)); + AccessToken accessToken = new UserAccessToken(secure().nextAlphanumeric(10)); String responseJson = """ { "total_count": 2, @@ -750,7 +750,7 @@ public class GithubApplicationClientImplTest { @Test public void listRepositories_returns_search_results() throws IOException { String appUrl = "https://github.sonarsource.com"; - AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10)); + AccessToken accessToken = new UserAccessToken(secure().nextAlphanumeric(10)); String responseJson = """ { "total_count": 2, @@ -850,7 +850,7 @@ public class GithubApplicationClientImplTest { @Test public void getRepository_returns_repository() throws IOException { String appUrl = "https://github.sonarsource.com"; - AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10)); + AccessToken accessToken = new UserAccessToken(secure().nextAlphanumeric(10)); String responseJson = "{\n" + " \"id\": 1296269,\n" + " \"node_id\": \"MDEwOlJlcG9zaXRvcnkxMjk2MjY5\",\n" @@ -1139,13 +1139,13 @@ public class GithubApplicationClientImplTest { } private AppToken mockAppToken() { - String jwt = randomAlphanumeric(5); + String jwt = secure().nextAlphanumeric(5); when(appSecurity.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey())).thenReturn(new AppToken(jwt)); return new AppToken(jwt); } private ExpiringAppInstallationToken mockCreateAccessTokenCallingGithub() throws IOException { - String token = randomAlphanumeric(5); + String token = secure().nextAlphanumeric(5); Response response = mock(Response.class); when(response.getContent()).thenReturn(Optional.of(format(""" { diff --git a/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/SonarQubeIssueKeyFormatterTest.java b/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/SonarQubeIssueKeyFormatterTest.java index b025b75aeaa..bb34dc1671f 100644 --- a/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/SonarQubeIssueKeyFormatterTest.java +++ b/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/SonarQubeIssueKeyFormatterTest.java @@ -32,7 +32,7 @@ public class SonarQubeIssueKeyFormatterTest { @Test public void should_serializeIssueKey() { - String issueKey = RandomStringUtils.randomAlphanumeric(20); + String issueKey = RandomStringUtils.secure().nextAlphanumeric(20); String serialized = SonarQubeIssueKeyFormatter.serialize(issueKey); @@ -42,7 +42,7 @@ public class SonarQubeIssueKeyFormatterTest { @Test public void should_deserializeIssueKey() { - String issueKey = RandomStringUtils.randomAlphanumeric(20); + String issueKey = RandomStringUtils.secure().nextAlphanumeric(20); String message = join("", SONAR_ISSUE_KEY_PREFIX, issueKey, SONAR_ISSUE_KEY_SUFFIX, "a message"); Optional deserialized = SonarQubeIssueKeyFormatter.deserialize(message); @@ -52,7 +52,7 @@ public class SonarQubeIssueKeyFormatterTest { @Test public void should_notDeserializeIssueKey_when_messageHasWrongFormat() { - String issueKey = RandomStringUtils.randomAlphanumeric(20); + String issueKey = RandomStringUtils.secure().nextAlphanumeric(20); String messageWithoutSuffix = join("", SONAR_ISSUE_KEY_PREFIX, issueKey, "a message"); String messageWithoutPrefix = join("", issueKey, SONAR_ISSUE_KEY_SUFFIX, "a message"); String messageWithPrefixSuffixReversed = join("", SONAR_ISSUE_KEY_SUFFIX, issueKey, SONAR_ISSUE_KEY_PREFIX, "a message"); diff --git a/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/security/GithubAppSecurityImplTest.java b/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/security/GithubAppSecurityImplTest.java index 3e5972d9490..65224ce6adb 100644 --- a/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/security/GithubAppSecurityImplTest.java +++ b/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/security/GithubAppSecurityImplTest.java @@ -30,8 +30,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.auth.github.GithubAppConfiguration; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -42,7 +41,7 @@ public class GithubAppSecurityImplTest { @Test public void createAppToken_fails_with_IAE_if_privateKey_content_is_garbage() { - String garbage = randomAlphanumeric(555); + String garbage = secure().nextAlphanumeric(555); GithubAppConfiguration githubAppConfiguration = createAppConfigurationForPrivateKey(garbage); assertThatThrownBy(() -> underTest.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey())) @@ -146,12 +145,12 @@ public class GithubAppSecurityImplTest { } private GithubAppConfiguration createAppConfiguration() { - return new GithubAppConfiguration(new Random().nextLong(), REAL_PRIVATE_KEY, randomAlphanumeric(5)); + return new GithubAppConfiguration(new Random().nextLong(), REAL_PRIVATE_KEY, secure().nextAlphanumeric(5)); } private GithubAppConfiguration createAppConfigurationForPrivateKey(String privateKey) { long applicationId = new Random().nextInt(654); - return new GithubAppConfiguration(applicationId, privateKey, randomAlphabetic(8)); + return new GithubAppConfiguration(applicationId, privateKey, secure().nextAlphabetic(8)); } private static final String REAL_PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\n" + diff --git a/server/sonar-auth-common/src/test/java/org/sonar/auth/OAuthRestClientTest.java b/server/sonar-auth-common/src/test/java/org/sonar/auth/OAuthRestClientTest.java index 76b95efbf19..8a03ce7762c 100644 --- a/server/sonar-auth-common/src/test/java/org/sonar/auth/OAuthRestClientTest.java +++ b/server/sonar-auth-common/src/test/java/org/sonar/auth/OAuthRestClientTest.java @@ -34,7 +34,7 @@ import org.junit.Rule; import org.junit.Test; import static java.lang.String.format; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; @@ -61,7 +61,7 @@ public class OAuthRestClientTest { @Test public void execute_request() throws IOException { - String body = randomAlphanumeric(10); + String body = secure().nextAlphanumeric(10); mockWebServer.enqueue(new MockResponse().setBody(body)); Response response = executeRequest(serverUrl + "/test", oAuth20Service, auth2AccessToken); diff --git a/server/sonar-auth-github/src/test/java/org/sonar/auth/github/GithubAppConfigurationTest.java b/server/sonar-auth-github/src/test/java/org/sonar/auth/github/GithubAppConfigurationTest.java index 7c17bcd0ed6..b143233a9e6 100644 --- a/server/sonar-auth-github/src/test/java/org/sonar/auth/github/GithubAppConfigurationTest.java +++ b/server/sonar-auth-github/src/test/java/org/sonar/auth/github/GithubAppConfigurationTest.java @@ -29,7 +29,7 @@ import org.apache.commons.lang3.ArrayUtils; import org.junit.Test; import org.junit.runner.RunWith; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -75,8 +75,8 @@ public class GithubAppConfigurationTest { @DataProvider public static Object[][] incompleteConfigurationParametersSonarQube() { long applicationId = new Random().nextLong(); - String privateKey = randomAlphabetic(9); - String apiEndpoint = randomAlphabetic(11); + String privateKey = secure().nextAlphabetic(9); + String apiEndpoint = secure().nextAlphabetic(11); return generateNullCombination(new Object[] { applicationId, @@ -88,8 +88,8 @@ public class GithubAppConfigurationTest { @Test public void toString_displays_complete_configuration() { long id = 34; - String privateKey = randomAlphabetic(3); - String apiEndpoint = randomAlphabetic(7); + String privateKey = secure().nextAlphabetic(3); + String apiEndpoint = secure().nextAlphabetic(7); GithubAppConfiguration underTest = new GithubAppConfiguration(id, privateKey, apiEndpoint); @@ -107,7 +107,7 @@ public class GithubAppConfigurationTest { @Test public void toString_displays_privateKey_as_stars() { - GithubAppConfiguration underTest = new GithubAppConfiguration(null, randomAlphabetic(555), null); + GithubAppConfiguration underTest = new GithubAppConfiguration(null, secure().nextAlphabetic(555), null); assertThat(underTest) .hasToString( @@ -117,8 +117,8 @@ public class GithubAppConfigurationTest { @Test public void equals_is_not_implemented() { long applicationId = new Random().nextLong(); - String privateKey = randomAlphabetic(8); - String apiEndpoint = randomAlphabetic(7); + String privateKey = secure().nextAlphabetic(8); + String apiEndpoint = secure().nextAlphabetic(7); GithubAppConfiguration underTest = new GithubAppConfiguration(applicationId, privateKey, apiEndpoint); @@ -130,8 +130,8 @@ public class GithubAppConfigurationTest { @Test public void hashcode_is_based_on_all_fields() { long applicationId = new Random().nextLong(); - String privateKey = randomAlphabetic(8); - String apiEndpoint = randomAlphabetic(7); + String privateKey = secure().nextAlphabetic(8); + String apiEndpoint = secure().nextAlphabetic(7); GithubAppConfiguration underTest = new GithubAppConfiguration(applicationId, privateKey, apiEndpoint); @@ -140,7 +140,7 @@ public class GithubAppConfigurationTest { } private GithubAppConfiguration newValidConfiguration(long applicationId) { - return new GithubAppConfiguration(applicationId, randomAlphabetic(6), randomAlphabetic(6)); + return new GithubAppConfiguration(applicationId, secure().nextAlphabetic(6), secure().nextAlphabetic(6)); } private static Object[][] generateNullCombination(Object[] objects) { diff --git a/server/sonar-ce-common/src/it/java/org/sonar/ce/queue/CeQueueImplIT.java b/server/sonar-ce-common/src/it/java/org/sonar/ce/queue/CeQueueImplIT.java index 5bcfa482469..da98131dbf4 100644 --- a/server/sonar-ce-common/src/it/java/org/sonar/ce/queue/CeQueueImplIT.java +++ b/server/sonar-ce-common/src/it/java/org/sonar/ce/queue/CeQueueImplIT.java @@ -50,7 +50,7 @@ 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.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.catchThrowable; @@ -81,8 +81,8 @@ public class CeQueueImplIT { @Test public void submit_returns_task_populated_from_CeTaskSubmit_and_creates_CeQueue_row() { - String componentUuid = randomAlphabetic(3); - String mainComponentUuid = randomAlphabetic(4); + String componentUuid = secure().nextAlphabetic(3); + String mainComponentUuid = secure().nextAlphabetic(4); CeTaskSubmit taskSubmit = createTaskSubmit(CeTaskTypes.REPORT, new Component(componentUuid, mainComponentUuid), "submitter uuid"); UserDto userDto = db.getDbClient().userDao().selectByUuid(db.getSession(), taskSubmit.getSubmitterUuid()); @@ -136,8 +136,8 @@ public class CeQueueImplIT { @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); + String mainComponentUuid = secure().nextAlphabetic(5); + String otherMainComponentUuid = secure().nextAlphabetic(6); CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null); CeQueueDto dto = insertPendingInQueue(newComponent(otherMainComponentUuid)); @@ -151,7 +151,7 @@ public class CeQueueImplIT { @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); + String mainComponentUuid = secure().nextAlphabetic(5); CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null); CeQueueDto dto = insertPendingInQueue(newComponent(mainComponentUuid)); @@ -165,7 +165,7 @@ public class CeQueueImplIT { @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); + String mainComponentUuid = secure().nextAlphabetic(5); CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null); String[] uuids = IntStream.range(0, 2 + new Random().nextInt(5)) .mapToObj(i -> insertPendingInQueue(newComponent(mainComponentUuid))) @@ -182,7 +182,7 @@ public class CeQueueImplIT { @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); + String mainComponentUuid = secure().nextAlphabetic(5); CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null); CeQueueDto dto = insertPendingInQueue(newComponent(mainComponentUuid)); @@ -195,7 +195,7 @@ public class CeQueueImplIT { @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); + String mainComponentUuid = secure().nextAlphabetic(5); CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null); String[] uuids = IntStream.range(0, 2 + new Random().nextInt(5)) .mapToObj(i -> insertPendingInQueue(newComponent(mainComponentUuid))) @@ -213,7 +213,7 @@ public class CeQueueImplIT { @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); + String mainComponentUuid = secure().nextAlphabetic(5); CeTaskSubmit taskSubmit = createTaskSubmit("some type", newComponent(mainComponentUuid), null); String[] uuids = IntStream.range(0, 2 + new Random().nextInt(5)) .mapToObj(i -> insertPendingInQueue(newComponent(mainComponentUuid))) @@ -229,7 +229,7 @@ public class CeQueueImplIT { @Test public void massSubmit_returns_tasks_for_each_CeTaskSubmit_populated_from_CeTaskSubmit_and_creates_CeQueue_row_for_each() { - String mainComponentUuid = randomAlphabetic(10); + String mainComponentUuid = secure().nextAlphabetic(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()); @@ -247,7 +247,7 @@ public class CeQueueImplIT { 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); + CeTaskSubmit taskSubmit2 = createTaskSubmit("something", newComponent(secure().nextAlphabetic(12)), null); List tasks = underTest.massSubmit(asList(taskSubmit1, taskSubmit2)); @@ -286,8 +286,8 @@ public class CeQueueImplIT { @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); + String mainComponentUuid = secure().nextAlphabetic(5); + String otherMainComponentUuid = secure().nextAlphabetic(6); CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null); CeQueueDto dto = insertPendingInQueue(newComponent(otherMainComponentUuid)); @@ -301,7 +301,7 @@ public class CeQueueImplIT { @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); + String mainComponentUuid = secure().nextAlphabetic(5); CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null); CeQueueDto dto = insertPendingInQueue(newComponent(mainComponentUuid)); @@ -315,7 +315,7 @@ public class CeQueueImplIT { @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); + String mainComponentUuid = secure().nextAlphabetic(5); CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null); String[] uuids = IntStream.range(0, 7) .mapToObj(i -> insertPendingInQueue(newComponent(mainComponentUuid))) @@ -332,7 +332,7 @@ public class CeQueueImplIT { @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); + String mainComponentUuid = secure().nextAlphabetic(5); CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null); CeQueueDto dto = insertPendingInQueue(newComponent(mainComponentUuid)); @@ -346,7 +346,7 @@ public class CeQueueImplIT { @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); + String mainComponentUuid = secure().nextAlphabetic(5); CeTaskSubmit taskSubmit = createTaskSubmit("with_component", newComponent(mainComponentUuid), null); String[] uuids = IntStream.range(0, 2 + new Random().nextInt(5)) .mapToObj(i -> insertPendingInQueue(newComponent(mainComponentUuid))) @@ -365,11 +365,11 @@ public class CeQueueImplIT { @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); + String mainComponentUuid1 = secure().nextAlphabetic(5); + String mainComponentUuid2 = secure().nextAlphabetic(6); + String mainComponentUuid3 = secure().nextAlphabetic(7); + String mainComponentUuid4 = secure().nextAlphabetic(8); + String mainComponentUuid5 = secure().nextAlphabetic(9); CeTaskSubmit taskSubmit1 = createTaskSubmit("with_one_pending", newComponent(mainComponentUuid1), null); CeQueueDto dto1 = insertPendingInQueue(newComponent(mainComponentUuid1)); Component componentForMainComponentUuid2 = newComponent(mainComponentUuid2); @@ -402,7 +402,7 @@ public class CeQueueImplIT { @Test public void cancel_pending() { - CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12))); + CeTask task = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12))); CeQueueDto queueDto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), task.getUuid()).get(); underTest.cancel(db.getSession(), queueDto); @@ -415,7 +415,7 @@ public class CeQueueImplIT { @Test public void cancel_pending_whenNodeNameProvided_setItInCeActivity() { when(nodeInformation.getNodeName()).thenReturn(Optional.of(NODE_NAME)); - CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12))); + CeTask task = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12))); CeQueueDto queueDto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), task.getUuid()).get(); underTest.cancel(db.getSession(), queueDto); @@ -428,7 +428,7 @@ public class CeQueueImplIT { @Test public void cancel_pending_whenNodeNameNOtProvided_setNulInCeActivity() { when(nodeInformation.getNodeName()).thenReturn(Optional.empty()); - CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12))); + CeTask task = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12))); CeQueueDto queueDto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), task.getUuid()).get(); underTest.cancel(db.getSession(), queueDto); @@ -440,7 +440,7 @@ public class CeQueueImplIT { @Test public void fail_to_cancel_if_in_progress() { - CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(11))); + CeTask task = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(11))); CeQueueDto ceQueueDto = db.getDbClient().ceQueueDao().tryToPeek(session, task.getUuid(), WORKER_UUID).get(); assertThatThrownBy(() -> underTest.cancel(db.getSession(), ceQueueDto)) @@ -450,9 +450,9 @@ public class CeQueueImplIT { @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))); + CeTask inProgressTask = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12))); + CeTask pendingTask1 = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12))); + CeTask pendingTask2 = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12))); db.getDbClient().ceQueueDao().tryToPeek(session, inProgressTask.getUuid(), WORKER_UUID); @@ -469,7 +469,7 @@ public class CeQueueImplIT { @Test public void pauseWorkers_marks_workers_as_paused_if_zero_tasks_in_progress() { - submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12))); + submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12))); // task is pending assertThat(underTest.getWorkersPauseStatus()).isEqualTo(CeQueue.WorkersPauseStatus.RESUMED); @@ -480,7 +480,7 @@ public class CeQueueImplIT { @Test public void pauseWorkers_marks_workers_as_pausing_if_some_tasks_in_progress() { - CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12))); + CeTask task = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12))); db.getDbClient().ceQueueDao().tryToPeek(session, task.getUuid(), WORKER_UUID); // task is in-progress @@ -501,7 +501,7 @@ public class CeQueueImplIT { @Test public void resumeWorkers_resumes_pausing_workers() { - CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12))); + CeTask task = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12))); db.getDbClient().ceQueueDao().tryToPeek(session, task.getUuid(), WORKER_UUID); // task is in-progress @@ -523,7 +523,7 @@ public class CeQueueImplIT { @Test public void fail_in_progress_task() { - CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12))); + CeTask task = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12))); CeQueueDto queueDto = db.getDbClient().ceQueueDao().tryToPeek(db.getSession(), task.getUuid(), WORKER_UUID).get(); underTest.fail(db.getSession(), queueDto, "TIMEOUT", "Failed on timeout"); @@ -541,7 +541,7 @@ public class CeQueueImplIT { @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))); + CeTask task = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12))); CeQueueDto queueDto = db.getDbClient().ceQueueDao().tryToPeek(db.getSession(), task.getUuid(), WORKER_UUID).get(); underTest.fail(db.getSession(), queueDto, "TIMEOUT", "Failed on timeout"); @@ -557,7 +557,7 @@ public class CeQueueImplIT { @Test public void fail_throws_exception_if_task_is_pending() { - CeTask task = submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(12))); + CeTask task = submit(CeTaskTypes.REPORT, newComponent(secure().nextAlphabetic(12))); CeQueueDto queueDto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), task.getUuid()).get(); Throwable thrown = catchThrowable(() -> underTest.fail(db.getSession(), queueDto, "TIMEOUT", "Failed on timeout")); diff --git a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/component/BranchPersisterImplIT.java b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/component/BranchPersisterImplIT.java index 7016999d8e5..24d1d81384c 100644 --- a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/component/BranchPersisterImplIT.java +++ b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/component/BranchPersisterImplIT.java @@ -44,7 +44,7 @@ import org.sonar.db.component.ProjectData; import org.sonar.db.protobuf.DbProjectBranches; import org.sonar.server.project.Project; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; @@ -254,7 +254,7 @@ public class BranchPersisterImplIT { public static Object[][] nullOrNotNullString() { return new Object[][] { {null}, - {randomAlphabetic(12)} + {secure().nextAlphabetic(12)} }; } diff --git a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/ClosedIssuesInputFactoryIT.java b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/ClosedIssuesInputFactoryIT.java index 3ff4cb4b18a..77fecea2136 100644 --- a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/ClosedIssuesInputFactoryIT.java +++ b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/ClosedIssuesInputFactoryIT.java @@ -30,7 +30,7 @@ import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.tracking.Input; import org.sonar.db.DbClient; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; @@ -45,7 +45,7 @@ public class ClosedIssuesInputFactoryIT { @Test public void underTest_returns_inputFactory_loading_closed_issues_only_when_getIssues_is_called() { - String componentUuid = randomAlphanumeric(12); + String componentUuid = secure().nextAlphanumeric(12); ReportComponent component = ReportComponent.builder(Component.Type.FILE, 1).setUuid(componentUuid).build(); when(movedFilesRepository.getOriginalFile(component)).thenReturn(Optional.empty()); @@ -61,11 +61,11 @@ public class ClosedIssuesInputFactoryIT { @Test public void underTest_returns_inputFactory_loading_closed_issues_from_moved_component_when_present() { - String componentUuid = randomAlphanumeric(12); - String originalComponentUuid = randomAlphanumeric(12); + String componentUuid = secure().nextAlphanumeric(12); + String originalComponentUuid = secure().nextAlphanumeric(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)))); + .thenReturn(Optional.of(new MovedFilesRepository.OriginalFile(originalComponentUuid, secure().nextAlphanumeric(2)))); Input input = underTest.create(component); @@ -79,7 +79,7 @@ public class ClosedIssuesInputFactoryIT { @Test public void underTest_returns_inputFactory_which_caches_loaded_issues() { - String componentUuid = randomAlphanumeric(12); + String componentUuid = secure().nextAlphanumeric(12); ReportComponent component = ReportComponent.builder(Component.Type.FILE, 1).setUuid(componentUuid).build(); when(movedFilesRepository.getOriginalFile(component)).thenReturn(Optional.empty()); diff --git a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/ComponentIssuesLoaderIT.java b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/ComponentIssuesLoaderIT.java index 50927dad62e..13b0d593e95 100644 --- a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/ComponentIssuesLoaderIT.java +++ b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/issue/ComponentIssuesLoaderIT.java @@ -52,7 +52,7 @@ import org.sonar.db.rule.RuleDto; import static java.util.Collections.emptyList; import static java.util.Collections.singleton; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; @@ -215,7 +215,7 @@ public class ComponentIssuesLoaderIT { System2 system2 = mock(System2.class); DbClient dbClient = mock(DbClient.class); Configuration configuration = newConfiguration("0"); - String componentUuid = randomAlphabetic(15); + String componentUuid = secure().nextAlphabetic(15); ComponentIssuesLoader underTest = new ComponentIssuesLoader(dbClient, null, null, configuration, system2, issueChangesToDeleteRepository); assertThat(underTest.loadClosedIssues(componentUuid)).isEmpty(); @@ -388,7 +388,7 @@ public class ComponentIssuesLoaderIT { 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)))); + .forEach(i -> diffs.add(new Diff(secure().nextAlphabetic(10), random.nextBoolean() ? null : secure().nextAlphabetic(11), random.nextBoolean() ? null : secure().nextAlphabetic(12)))); Collections.shuffle(diffs); FieldDiffs res = new FieldDiffs(); diff --git a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/BuildComponentTreeStepIT.java b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/BuildComponentTreeStepIT.java index 76d916163e3..d544a6a05cb 100644 --- a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/BuildComponentTreeStepIT.java +++ b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/BuildComponentTreeStepIT.java @@ -48,8 +48,7 @@ import org.sonar.scanner.protocol.output.ScannerReport.Component.FileStatus; import org.sonar.server.project.Project; import static java.util.Optional.ofNullable; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; @@ -274,7 +273,7 @@ public class BuildComponentTreeStepIT { @Test public void generate_keys_when_using_existing_branch() { ComponentDto projectDto = dbTester.components().insertPublicProject().getMainBranchComponent(); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto componentDto = dbTester.components().insertProjectBranch(projectDto, b -> b.setKey(branchName)); Branch branch = mock(Branch.class); when(branch.getName()).thenReturn(branchName); @@ -398,7 +397,7 @@ public class BuildComponentTreeStepIT { @Test public void set_projectVersion_when_it_is_set_on_first_analysis() { - String scannerProjectVersion = randomAlphabetic(12); + String scannerProjectVersion = secure().nextAlphabetic(12); setAnalysisMetadataHolder(); reportReader.setMetadata(createReportMetadata(scannerProjectVersion, NO_SCANNER_BUILD_STRING)); reportReader.putComponent(component(ROOT_REF, PROJECT, REPORT_PROJECT_KEY)); @@ -412,7 +411,7 @@ public class BuildComponentTreeStepIT { @Test @UseDataProvider("oneParameterNullNonNullCombinations") public void set_projectVersion_when_it_is_set_on_later_analysis(@Nullable String previousAnalysisProjectVersion) { - String scannerProjectVersion = randomAlphabetic(12); + String scannerProjectVersion = secure().nextAlphabetic(12); setAnalysisMetadataHolder(); reportReader.setMetadata(createReportMetadata(scannerProjectVersion, NO_SCANNER_BUILD_STRING)); ComponentDto project = insertComponent(newPrivateProjectDto("ABCD").setKey(REPORT_PROJECT_KEY)); @@ -428,7 +427,7 @@ public class BuildComponentTreeStepIT { @Test @UseDataProvider("oneParameterNullNonNullCombinations") public void set_buildString(@Nullable String buildString) { - String projectVersion = randomAlphabetic(7); + String projectVersion = secure().nextAlphabetic(7); setAnalysisMetadataHolder(); reportReader.setMetadata(createReportMetadata(projectVersion, buildString)); reportReader.putComponent(component(ROOT_REF, PROJECT, REPORT_PROJECT_KEY)); @@ -442,7 +441,7 @@ public class BuildComponentTreeStepIT { public static Object[][] oneParameterNullNonNullCombinations() { return new Object[][] { {null}, - {randomAlphabetic(7)} + {secure().nextAlphabetic(7)} }; } diff --git a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/LoadPeriodsStepIT.java b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/LoadPeriodsStepIT.java index 0d1184c2167..c43cf90fb35 100644 --- a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/LoadPeriodsStepIT.java +++ b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/LoadPeriodsStepIT.java @@ -58,7 +58,7 @@ import org.sonar.db.newcodeperiod.NewCodePeriodDao; import org.sonar.db.newcodeperiod.NewCodePeriodType; import org.sonar.server.project.Project; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; @@ -465,7 +465,7 @@ public class LoadPeriodsStepIT extends BaseStepTest { @DataProvider public static Object[][] stringConsideredAsVersions() { return new Object[][] { - {randomAlphabetic(5)}, + {secure().nextAlphabetic(5)}, {"1,3"}, {"1.3"}, {"0 1"}, @@ -478,7 +478,7 @@ public class LoadPeriodsStepIT extends BaseStepTest { public static Object[][] projectVersionNullOrNot() { return new Object[][] { {null}, - {randomAlphabetic(15)}, + {secure().nextAlphabetic(15)}, }; } diff --git a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/PersistAnalysisPropertiesStepIT.java b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/PersistAnalysisPropertiesStepIT.java index 3eee1239ad4..fef5626e171 100644 --- a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/PersistAnalysisPropertiesStepIT.java +++ b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/PersistAnalysisPropertiesStepIT.java @@ -35,18 +35,18 @@ import org.sonar.db.DbTester; import org.sonar.db.component.AnalysisPropertyDto; import org.sonar.scanner.protocol.output.ScannerReport; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class PersistAnalysisPropertiesStepIT { - private static final String SNAPSHOT_UUID = randomAlphanumeric(40); - private static final String SMALL_VALUE1 = randomAlphanumeric(50); - private static final String SMALL_VALUE2 = randomAlphanumeric(50); - private static final String SMALL_VALUE3 = randomAlphanumeric(50); - private static final String BIG_VALUE = randomAlphanumeric(5000); + private static final String SNAPSHOT_UUID = secure().nextAlphanumeric(40); + private static final String SMALL_VALUE1 = secure().nextAlphanumeric(50); + private static final String SMALL_VALUE2 = secure().nextAlphanumeric(50); + private static final String SMALL_VALUE3 = secure().nextAlphanumeric(50); + private static final String BIG_VALUE = secure().nextAlphanumeric(5000); private static final String VALUE_PREFIX_FOR_PR_PROPERTIES = "pr_"; private static final List PROPERTIES = Arrays.asList( newContextProperty("key1", "value1"), diff --git a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/ReportPersistAnalysisStepIT.java b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/ReportPersistAnalysisStepIT.java index 5281f0201ae..c04c0f46c60 100644 --- a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/ReportPersistAnalysisStepIT.java +++ b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/ReportPersistAnalysisStepIT.java @@ -42,7 +42,7 @@ import org.sonar.db.component.SnapshotDto; import org.sonar.db.component.SnapshotQuery; import org.sonar.db.component.SnapshotTesting; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -92,7 +92,7 @@ public class ReportPersistAnalysisStepIT extends BaseStepTest { @Test public void persist_analysis() { - String projectVersion = randomAlphabetic(10); + String projectVersion = secure().nextAlphabetic(10); ComponentDto projectDto = ComponentTesting.newPrivateProjectDto("ABCD").setKey(PROJECT_KEY).setName("Project"); dbTester.components().insertComponent(projectDto); ComponentDto directoryDto = ComponentTesting.newDirectory(projectDto, "CDEF", "src/main/java/dir").setKey("PROJECT_KEY:src/main/java/dir"); @@ -103,7 +103,7 @@ public class ReportPersistAnalysisStepIT extends BaseStepTest { Component file = ReportComponent.builder(Component.Type.FILE, 3).setUuid("DEFG").setKey("PROJECT_KEY:src/main/java/dir/Foo.java").build(); Component directory = ReportComponent.builder(Component.Type.DIRECTORY, 2).setUuid("CDEF").setKey("PROJECT_KEY:src/main/java/dir").addChildren(file).build(); - String buildString = Optional.ofNullable(projectVersion).map(v -> randomAlphabetic(7)).orElse(null); + String buildString = Optional.ofNullable(projectVersion).map(v -> secure().nextAlphabetic(7)).orElse(null); Component project = ReportComponent.builder(Component.Type.PROJECT, 1) .setUuid("ABCD") .setKey(PROJECT_KEY) diff --git a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/SendIssueNotificationsStepIT.java b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/SendIssueNotificationsStepIT.java index b8847b5c6de..ed904ccd70b 100644 --- a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/SendIssueNotificationsStepIT.java +++ b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/SendIssueNotificationsStepIT.java @@ -75,7 +75,7 @@ import static java.util.Collections.shuffle; import static java.util.Collections.singleton; import static java.util.stream.Collectors.toList; import static java.util.stream.Stream.concat; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.ArgumentCaptor.forClass; @@ -119,7 +119,7 @@ public class SendIssueNotificationsStepIT extends BaseStepTest { private static final Component FILE = builder(Type.FILE, 11).build(); private static final Component PROJECT = builder(Type.PROJECT, 1) - .setProjectVersion(randomAlphanumeric(10)) + .setProjectVersion(secure().nextAlphanumeric(10)) .addChildren(FILE).build(); @Rule diff --git a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/analysis/ExportAnalysesStepIT.java b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/analysis/ExportAnalysesStepIT.java index 33e9463a68f..808091735f0 100644 --- a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/analysis/ExportAnalysesStepIT.java +++ b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/analysis/ExportAnalysesStepIT.java @@ -44,7 +44,7 @@ import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.SnapshotDto; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.apache.commons.lang3.StringUtils.defaultString; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -141,8 +141,8 @@ public class ExportAnalysesStepIT { @DataProvider public static Object[][] versionAndBuildStringCombinations() { - String version = randomAlphabetic(7); - String buildString = randomAlphabetic(12); + String version = secure().nextAlphabetic(7); + String buildString = secure().nextAlphabetic(12); return new Object[][] { {null, null}, {version, null}, diff --git a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/rule/ExportAdHocRulesStepIT.java b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/rule/ExportAdHocRulesStepIT.java index 94e6af5c4cf..5ab529eb3af 100644 --- a/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/rule/ExportAdHocRulesStepIT.java +++ b/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/rule/ExportAdHocRulesStepIT.java @@ -261,10 +261,10 @@ public class ExportAdHocRulesStepIT { .setCleanCodeAttribute(CleanCodeAttribute.CONVENTIONAL) .addDefaultImpact(new ImpactDto().setSoftwareQuality(SoftwareQuality.MAINTAINABILITY).setSeverity(org.sonar.api.issue.impact.Severity.MEDIUM)) .addDefaultImpact(new ImpactDto().setSoftwareQuality(SoftwareQuality.RELIABILITY).setSeverity(org.sonar.api.issue.impact.Severity.HIGH)) - .setAdHocName("ad_hoc_rule" + RandomStringUtils.randomAlphabetic(10)) + .setAdHocName("ad_hoc_rule" + RandomStringUtils.secure().nextAlphabetic(10)) .setAdHocType(RuleType.VULNERABILITY) .setAdHocSeverity(Severity.CRITICAL) - .setAdHocDescription("ad hoc description: " + RandomStringUtils.randomAlphanumeric(100)); + .setAdHocDescription("ad hoc description: " + RandomStringUtils.secure().nextAlphanumeric(100)); return insertRule(ruleName, ruleDto); } @@ -278,9 +278,9 @@ public class ExportAdHocRulesStepIT { private RuleDto insertRule(String ruleName, RuleDto partiallyInitRuleDto) { RuleKey ruleKey = RuleKey.of("plugin1", ruleName); partiallyInitRuleDto - .setName("ruleName" + RandomStringUtils.randomAlphanumeric(10)) + .setName("ruleName" + RandomStringUtils.secure().nextAlphanumeric(10)) .setRuleKey(ruleKey) - .setPluginKey("pluginKey" + RandomStringUtils.randomAlphanumeric(10)) + .setPluginKey("pluginKey" + RandomStringUtils.secure().nextAlphanumeric(10)) .setStatus(RuleStatus.READY) .setScope(RuleDto.Scope.ALL); diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/PostProjectAnalysisTasksExecutorTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/PostProjectAnalysisTasksExecutorTest.java index 72d8fc66994..1b4ad0f5449 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/PostProjectAnalysisTasksExecutorTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/PostProjectAnalysisTasksExecutorTest.java @@ -198,7 +198,7 @@ public class PostProjectAnalysisTasksExecutorTest { @Test public void date_comes_from_AnalysisMetadataHolder() { analysisMetadataHolder.setAnalysisDate(8_465_132_498L); - analysisMetadataHolder.setUuid(RandomStringUtils.randomAlphanumeric(40)); + analysisMetadataHolder.setUuid(RandomStringUtils.secure().nextAlphanumeric(40)); underTest.finished(true); @@ -211,7 +211,7 @@ public class PostProjectAnalysisTasksExecutorTest { @Test public void analysisDate_and_analysisUuid_comes_from_AnalysisMetadataHolder_when_set() { analysisMetadataHolder.setAnalysisDate(8465132498L); - analysisMetadataHolder.setUuid(RandomStringUtils.randomAlphanumeric(40)); + analysisMetadataHolder.setUuid(RandomStringUtils.secure().nextAlphanumeric(40)); underTest.finished(true); @@ -361,7 +361,7 @@ public class PostProjectAnalysisTasksExecutorTest { verify(postProjectAnalysisTask).finished(taskContextCaptor.capture()); PostProjectAnalysisTask.LogStatistics logStatistics = taskContextCaptor.getValue().getLogStatistics(); - String key = RandomStringUtils.randomAlphabetic(10); + String key = RandomStringUtils.secure().nextAlphabetic(10); logStatistics.add(key, new Object()); assertThat(catchThrowable(() -> logStatistics.add(key, "bar"))) .isInstanceOf(IllegalArgumentException.class) diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentImplTest.java index 02efc7fc4da..81c86f3d360 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentImplTest.java @@ -25,7 +25,7 @@ import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component.Status; import static com.google.common.base.Strings.repeat; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; @@ -239,7 +239,7 @@ public class ComponentImplTest { .setUuid("uuid_" + dbKey) .setReportAttributes(ReportAttributes.newBuilder(dbKey.hashCode()).build()); if (type == PROJECT) { - String buildString = randomAlphabetic(15); + String buildString = secure().nextAlphabetic(15); builder.setProjectAttributes(new ProjectAttributes("version_1", buildString, "453def")); } return builder; diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentTreeBuilderTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentTreeBuilderTest.java index 8f6e737572c..f43fef95051 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentTreeBuilderTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentTreeBuilderTest.java @@ -39,7 +39,7 @@ import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.server.project.Project; import static com.google.common.base.Preconditions.checkArgument; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; @@ -60,7 +60,7 @@ class ComponentTreeBuilderTest { private static final String NO_SCM_BASE_PATH = ""; // both no project as "" or null should be supported private static final ProjectAttributes SOME_PROJECT_ATTRIBUTES = new ProjectAttributes( - randomAlphabetic(20), new Random().nextBoolean() ? null : randomAlphabetic(12), "1def5123"); + secure().nextAlphabetic(20), new Random().nextBoolean() ? null : secure().nextAlphabetic(12), "1def5123"); @RegisterExtension private final ScannerComponentProvider scannerComponentProvider = new ScannerComponentProvider(); @@ -117,7 +117,7 @@ class ComponentTreeBuilderTest { void by_default_project_fields_are_loaded_from_report() { String nameInReport = "the name"; String descriptionInReport = "the desc"; - String buildString = randomAlphabetic(21); + String buildString = secure().nextAlphabetic(21); Component root = call(newBuilder() .setType(PROJECT) .setKey(projectInDb.getKey()) @@ -149,7 +149,7 @@ class ComponentTreeBuilderTest { @Test void project_name_is_loaded_from_report_if_present_and_on_main_branch() { - String reportName = randomAlphabetic(5); + String reportName = secure().nextAlphabetic(5); ScannerReport.Component reportProject = newBuilder() .setType(PROJECT) .setName(reportName) @@ -162,7 +162,7 @@ class ComponentTreeBuilderTest { @Test void project_name_is_loaded_from_db_if_not_on_main_branch() { - String reportName = randomAlphabetic(5); + String reportName = secure().nextAlphabetic(5); ScannerReport.Component reportProject = newBuilder() .setType(PROJECT) .setName(reportName) @@ -185,7 +185,7 @@ class ComponentTreeBuilderTest { @Test void project_description_is_loaded_from_report_if_present_and_on_main_branch() { - String reportDescription = randomAlphabetic(5); + String reportDescription = secure().nextAlphabetic(5); ScannerReport.Component reportProject = newBuilder() .setType(PROJECT) .setDescription(reportDescription) @@ -198,7 +198,7 @@ class ComponentTreeBuilderTest { @Test void project_description_is_loaded_from_db_if_not_on_main_branch() { - String reportDescription = randomAlphabetic(5); + String reportDescription = secure().nextAlphabetic(5); ScannerReport.Component reportProject = newBuilder() .setType(PROJECT) .setDescription(reportDescription) @@ -257,7 +257,7 @@ class ComponentTreeBuilderTest { @Test void any_component_with_projectRelativePath_has_this_value_appended_to_scmBasePath_and_a_slash_as_scmPath_if_scmBasePath_is_not_empty() { ScannerReport.Component project = createProject(); - String scmBasePath = randomAlphabetic(10); + String scmBasePath = secure().nextAlphabetic(10); Component root = call(project, scmBasePath, SOME_PROJECT_ATTRIBUTES); assertThat(root.getReportAttributes().getScmPath()) diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/IntegrateCrossProjectDuplicationsTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/IntegrateCrossProjectDuplicationsTest.java index 03955c55068..dd2204bcbf5 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/IntegrateCrossProjectDuplicationsTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/IntegrateCrossProjectDuplicationsTest.java @@ -38,7 +38,7 @@ import org.sonar.duplications.block.ByteArray; import static com.google.common.base.Strings.padStart; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -293,7 +293,7 @@ public class IntegrateCrossProjectDuplicationsTest { for (int i = 0; i < 110; i++) { duplicatedBlocks.add( blockBuilder - .setResourceId(randomAlphanumeric(16)) + .setResourceId(secure().nextAlphanumeric(16)) .build()); } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/ScoreMatrixDumperImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/ScoreMatrixDumperImplTest.java index 9d17a2cddec..bdbe84d16bd 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/ScoreMatrixDumperImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/ScoreMatrixDumperImplTest.java @@ -38,7 +38,7 @@ import org.sonar.ce.task.CeTask; import org.sonar.ce.task.projectanalysis.filemove.ScoreMatrix.ScoreFile; import org.sonar.server.platform.ServerFileSystem; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -96,7 +96,7 @@ public class ScoreMatrixDumperImplTest { @Test public void dumpAsCsv_has_no_effect_if_configuration_is_empty() throws IOException { - String taskUuid = randomAlphabetic(6); + String taskUuid = secure().nextAlphabetic(6); when(ceTask.getUuid()).thenReturn(taskUuid); underTest.dumpAsCsv(A_SCORE_MATRIX); @@ -107,7 +107,7 @@ public class ScoreMatrixDumperImplTest { @Test @UseDataProvider("notTruePropertyValues") public void dumpAsCsv_has_no_effect_if_property_is_not_true(String value) throws IOException { - String taskUuid = randomAlphabetic(6); + String taskUuid = secure().nextAlphabetic(6); when(ceTask.getUuid()).thenReturn(taskUuid); settings.setProperty("sonar.filemove.dumpCsv", value); @@ -119,7 +119,7 @@ public class ScoreMatrixDumperImplTest { @DataProvider public static Object[][] notTruePropertyValues() { return new Object[][] { - {randomAlphabetic(6)}, + {secure().nextAlphabetic(6)}, {"false"}, }; } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/locations/flow/FlowGeneratorTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/locations/flow/FlowGeneratorTest.java index 90f547b0fe0..6b7c51d904b 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/locations/flow/FlowGeneratorTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/locations/flow/FlowGeneratorTest.java @@ -35,7 +35,7 @@ import org.sonar.db.protobuf.DbIssues; import static java.util.function.Function.identity; import static java.util.stream.Collectors.toMap; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -139,9 +139,9 @@ public class FlowGeneratorTest { when(treeRootHolder.getComponentByUuid(componentId)).thenReturn(component); return DbIssues.Location.newBuilder() .setComponentId(componentId) - .setChecksum("hash" + randomAlphanumeric(10)) + .setChecksum("hash" + secure().nextAlphanumeric(10)) .setTextRange(textRange) - .setMsg("msg" + randomAlphanumeric(15)) + .setMsg("msg" + secure().nextAlphanumeric(15)) .build(); } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/notification/NotificationFactoryTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/notification/NotificationFactoryTest.java index 3c859cff728..fdd39a8096d 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/notification/NotificationFactoryTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/notification/NotificationFactoryTest.java @@ -60,7 +60,7 @@ import org.sonar.server.issue.notification.NewIssuesNotification.DetailsSupplier import org.sonar.server.issue.notification.NewIssuesNotification.RuleDefinition; import static java.util.Collections.emptyMap; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; @@ -553,7 +553,7 @@ public class NotificationFactoryTest { .setStatus(STATUS_OPEN); Map assigneesByUuid = nonEmptyAssigneesByUuid(); ReportComponent project = ReportComponent.builder(PROJECT, 1).build(); - String branchName = randomAlphabetic(12); + String branchName = secure().nextAlphabetic(12); ruleRepository.add(ruleKey); treeRootHolder.setRoot(project); analysisMetadata.setAnalysisDate(new Random().nextLong()); @@ -583,7 +583,7 @@ public class NotificationFactoryTest { .setStatus(STATUS_OPEN); Map assigneesByUuid = nonEmptyAssigneesByUuid(); ReportComponent project = ReportComponent.builder(PROJECT, 1).build(); - String branchName = randomAlphabetic(12); + String branchName = secure().nextAlphabetic(12); ruleRepository.add(ruleKey); treeRootHolder.setRoot(project); analysisMetadata.setAnalysisDate(new Random().nextLong()); @@ -604,7 +604,7 @@ public class NotificationFactoryTest { @Test public void newIssuesChangesNotification_fails_with_ISE_if_issue_has_assignee_not_in_assigneesByUuid() { RuleKey ruleKey = RuleKey.of("foo", "bar"); - String assigneeUuid = randomAlphabetic(40); + String assigneeUuid = secure().nextAlphabetic(40); DefaultIssue issue = new DefaultIssue() .setRuleKey(ruleKey) .setKey("issueKey") @@ -615,7 +615,7 @@ public class NotificationFactoryTest { ruleRepository.add(ruleKey); treeRootHolder.setRoot(project); analysisMetadata.setAnalysisDate(new Random().nextLong()); - analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, randomAlphabetic(12))); + analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, secure().nextAlphabetic(12))); assertThatThrownBy(() -> underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid)) .isInstanceOf(IllegalStateException.class) @@ -625,7 +625,7 @@ public class NotificationFactoryTest { @Test public void newIssuesChangesNotification_creates_assignee_from_UserDto() { RuleKey ruleKey = RuleKey.of("foo", "bar"); - String assigneeUuid = randomAlphabetic(40); + String assigneeUuid = secure().nextAlphabetic(40); DefaultIssue issue = new DefaultIssue() .setRuleKey(ruleKey) .setKey("issueKey") @@ -637,7 +637,7 @@ public class NotificationFactoryTest { ruleRepository.add(ruleKey); treeRootHolder.setRoot(project); analysisMetadata.setAnalysisDate(new Random().nextLong()); - analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, randomAlphabetic(12))); + analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, secure().nextAlphabetic(12))); IssuesChangesNotification expected = mock(IssuesChangesNotification.class); when(issuesChangesSerializer.serialize(any(IssuesChangesNotificationBuilder.class))).thenReturn(expected); @@ -667,7 +667,7 @@ public class NotificationFactoryTest { ruleRepository.add(ruleKey); treeRootHolder.setRoot(project); analysisMetadata.setAnalysisDate(analysisDate); - analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, randomAlphabetic(12))); + analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, secure().nextAlphabetic(12))); IssuesChangesNotification expected = mock(IssuesChangesNotification.class); when(issuesChangesSerializer.serialize(any(IssuesChangesNotificationBuilder.class))).thenReturn(expected); @@ -697,7 +697,7 @@ public class NotificationFactoryTest { .forEach(ruleKey -> ruleRepository.add(ruleKey)); treeRootHolder.setRoot(project); analysisMetadata.setAnalysisDate(analysisDate); - analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, randomAlphabetic(12))); + analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, secure().nextAlphabetic(12))); IssuesChangesNotification expected = mock(IssuesChangesNotification.class); when(issuesChangesSerializer.serialize(any(IssuesChangesNotificationBuilder.class))).thenReturn(expected); diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/notification/ReportAnalysisFailureNotificationHandlerTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/notification/ReportAnalysisFailureNotificationHandlerTest.java index 1b2c639eeff..37688ab622b 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/notification/ReportAnalysisFailureNotificationHandlerTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/notification/ReportAnalysisFailureNotificationHandlerTest.java @@ -38,7 +38,7 @@ import org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliver import static java.util.Collections.emptySet; import static java.util.stream.Collectors.toSet; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -132,7 +132,7 @@ public class ReportAnalysisFailureNotificationHandlerTest { @Test public void deliver_has_no_effect_if_no_notification_has_subscribed_recipients_to_ReportFailure_notifications() { - String projectKey = randomAlphabetic(12); + String projectKey = secure().nextAlphabetic(12); ReportAnalysisFailureNotification notification = newNotification(projectKey); when(emailNotificationChannel.isActivated()).thenReturn(true); when(notificationManager.findSubscribedEmailRecipients(REPORT_FAILURE_DISPATCHER_KEY, projectKey, REQUIRED_SUBSCRIBER_PERMISSIONS)) @@ -149,7 +149,7 @@ public class ReportAnalysisFailureNotificationHandlerTest { @Test public void deliver_ignores_notification_without_projectKey() { - String projectKey = randomAlphabetic(10); + String projectKey = secure().nextAlphabetic(10); Set withProjectKey = IntStream.range(0, 1 + new Random().nextInt(5)) .mapToObj(i -> newNotification(projectKey)) .collect(toSet()); @@ -182,8 +182,8 @@ public class ReportAnalysisFailureNotificationHandlerTest { @Test public void deliver_checks_by_projectKey_if_notifications_have_subscribed_assignee_to_ReportFailure_notifications() { - String projectKey1 = randomAlphabetic(10); - String projectKey2 = randomAlphabetic(11); + String projectKey1 = secure().nextAlphabetic(10); + String projectKey2 = secure().nextAlphabetic(11); Set notifications1 = randomSetOfNotifications(projectKey1); Set notifications2 = randomSetOfNotifications(projectKey2); when(emailNotificationChannel.isActivated()).thenReturn(true); @@ -220,8 +220,8 @@ public class ReportAnalysisFailureNotificationHandlerTest { @Test public void deliver_send_notifications_to_all_subscribers_of_all_projects() { - String projectKey1 = randomAlphabetic(10); - String projectKey2 = randomAlphabetic(11); + String projectKey1 = secure().nextAlphabetic(10); + String projectKey2 = secure().nextAlphabetic(11); Set notifications1 = randomSetOfNotifications(projectKey1); Set notifications2 = randomSetOfNotifications(projectKey2); when(emailNotificationChannel.isActivated()).thenReturn(true); diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/pushevent/PushEventFactoryTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/pushevent/PushEventFactoryTest.java index 56dbc23139c..9b626898741 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/pushevent/PushEventFactoryTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/pushevent/PushEventFactoryTest.java @@ -49,7 +49,7 @@ import org.sonar.db.protobuf.DbIssues; import org.sonar.db.rule.RuleDto; import org.sonar.server.issue.TaintChecker; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.tuple; @@ -83,7 +83,7 @@ public class PushEventFactoryTest { public void raiseEventOnIssue_whenNewTaintVulnerability_shouldCreateRaisedEvent() { DefaultIssue defaultIssue = createDefaultIssue() .setNew(true) - .setRuleDescriptionContextKey(randomAlphabetic(6)); + .setRuleDescriptionContextKey(secure().nextAlphabetic(6)); when(taintChecker.isTaintVulnerability(any())).thenReturn(true); @@ -126,7 +126,7 @@ public class PushEventFactoryTest { DefaultIssue defaultIssue = createDefaultIssue() .setNew(true) .addImpact(SoftwareQuality.MAINTAINABILITY, Severity.HIGH) - .setRuleDescriptionContextKey(randomAlphabetic(6)); + .setRuleDescriptionContextKey(secure().nextAlphabetic(6)); when(taintChecker.isTaintVulnerability(any())).thenReturn(true); @@ -261,7 +261,7 @@ public class PushEventFactoryTest { .setType(RuleType.SECURITY_HOTSPOT) .setStatus(Issue.STATUS_TO_REVIEW) .setNew(true) - .setRuleDescriptionContextKey(randomAlphabetic(6)); + .setRuleDescriptionContextKey(secure().nextAlphabetic(6)); assertThat(underTest.raiseEventOnIssue("some-project-uuid", defaultIssue)) .isNotEmpty() diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/FileSourceDataWarningsTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/FileSourceDataWarningsTest.java index df5120f8d68..63aea0b5cc8 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/FileSourceDataWarningsTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/FileSourceDataWarningsTest.java @@ -34,7 +34,7 @@ import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.source.linereader.LineReader; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -52,7 +52,7 @@ public class FileSourceDataWarningsTest { private Random random = new Random(); private int line = 1 + new Random().nextInt(200); private long timeStamp = 9_887L + new Random().nextInt(300); - private String path = randomAlphabetic(50); + private String path = secure().nextAlphabetic(50); private FileSourceDataWarnings underTest = new FileSourceDataWarnings(taskMessages, system2); diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistComponentsStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistComponentsStepTest.java index 88788df63f3..bcdefd09294 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistComponentsStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistComponentsStepTest.java @@ -32,7 +32,7 @@ import org.sonar.db.DbSession; import org.sonar.db.component.ComponentDao; import static java.util.Collections.emptyList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -47,7 +47,7 @@ public class PersistComponentsStepTest { Component component = mock(Component.class); DbClient dbClient = mock(DbClient.class); ComponentDao componentDao = mock(ComponentDao.class); - String projectKey = randomAlphabetic(20); + String projectKey = secure().nextAlphabetic(20); doReturn(component).when(treeRootHolder).getRoot(); doReturn(projectKey).when(component).getKey(); diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/QualityGateEventsStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/QualityGateEventsStepTest.java index f869075e537..dd61f4258fd 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/QualityGateEventsStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/QualityGateEventsStepTest.java @@ -47,7 +47,7 @@ import org.sonar.server.project.Project; import org.sonar.server.qualitygate.notification.QGChangeNotification; import static java.util.Collections.emptyList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; @@ -61,7 +61,7 @@ import static org.sonar.ce.task.projectanalysis.measure.Measure.Level.OK; import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME; public class QualityGateEventsStepTest { - private static final String PROJECT_VERSION = randomAlphabetic(19); + private static final String PROJECT_VERSION = secure().nextAlphabetic(19); private static final ReportComponent PROJECT_COMPONENT = ReportComponent.builder(Component.Type.PROJECT, 1) .setUuid("uuid 1") .setKey("key 1") diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/webhook/WebhookPostTaskTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/webhook/WebhookPostTaskTest.java index 98a9032e054..bd2f4babee8 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/webhook/WebhookPostTaskTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/webhook/WebhookPostTaskTest.java @@ -47,7 +47,7 @@ import org.sonar.server.webhook.WebHooks; import org.sonar.server.webhook.WebhookPayload; import org.sonar.server.webhook.WebhookPayloadFactory; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -90,36 +90,36 @@ public class WebhookPostTaskTest { @Test public void call_webhooks_with_analysis_and_qualitygate() { QualityGate.Condition condition = newConditionBuilder() - .setMetricKey(randomAlphanumeric(96)) + .setMetricKey(secure().nextAlphanumeric(96)) .setOperator(QualityGate.Operator.LESS_THAN) - .setErrorThreshold(randomAlphanumeric(22)) - .build(QualityGate.EvaluationStatus.OK, randomAlphanumeric(33)); + .setErrorThreshold(secure().nextAlphanumeric(22)) + .build(QualityGate.EvaluationStatus.OK, secure().nextAlphanumeric(33)); QualityGate qualityGate = newQualityGateBuilder() - .setId(randomAlphanumeric(23)) - .setName(randomAlphanumeric(66)) + .setId(secure().nextAlphanumeric(23)) + .setName(secure().nextAlphanumeric(66)) .setStatus(QualityGate.Status.values()[random.nextInt(QualityGate.Status.values().length)]) .add(condition) .build(); - callWebHooks(randomAlphanumeric(40), qualityGate); + callWebHooks(secure().nextAlphanumeric(40), qualityGate); } private void callWebHooks(@Nullable String analysisUUid, @Nullable QualityGate qualityGate) { Project project = newProjectBuilder() - .setUuid(randomAlphanumeric(3)) - .setKey(randomAlphanumeric(4)) - .setName(randomAlphanumeric(5)) + .setUuid(secure().nextAlphanumeric(3)) + .setKey(secure().nextAlphanumeric(4)) + .setName(secure().nextAlphanumeric(5)) .build(); CeTask ceTask = newCeTaskBuilder() .setStatus(CeTask.Status.values()[random.nextInt(CeTask.Status.values().length)]) - .setId(randomAlphanumeric(6)) + .setId(secure().nextAlphanumeric(6)) .build(); Date date = new Date(); - Map properties = ImmutableMap.of(randomAlphanumeric(17), randomAlphanumeric(18)); + Map properties = ImmutableMap.of(secure().nextAlphanumeric(17), secure().nextAlphanumeric(18)); Branch branch = newBranchBuilder() .setIsMain(random.nextBoolean()) .setType(Branch.Type.values()[random.nextInt(Branch.Type.values().length)]) - .setName(randomAlphanumeric(29)) + .setName(secure().nextAlphanumeric(29)) .build(); PostProjectAnalysisTaskTester.of(underTest) diff --git a/server/sonar-ce-task/src/it/java/org/sonar/ce/task/log/CeTaskMessagesImplIT.java b/server/sonar-ce-task/src/it/java/org/sonar/ce/task/log/CeTaskMessagesImplIT.java index 966c7f84ce8..0a42950d338 100644 --- a/server/sonar-ce-task/src/it/java/org/sonar/ce/task/log/CeTaskMessagesImplIT.java +++ b/server/sonar-ce-task/src/it/java/org/sonar/ce/task/log/CeTaskMessagesImplIT.java @@ -36,8 +36,7 @@ import org.sonar.db.DbClient; import org.sonar.db.DbTester; import static java.util.stream.Collectors.toList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; @@ -51,11 +50,11 @@ public class CeTaskMessagesImplIT { private DbClient dbClient = dbTester.getDbClient(); private UuidFactory uuidFactory = mock(UuidFactory.class); - private String taskUuid = randomAlphabetic(12); + private String taskUuid = secure().nextAlphabetic(12); private CeTask ceTask = new CeTask.Builder() .setUuid(taskUuid) - .setType(randomAlphabetic(5)) + .setType(secure().nextAlphabetic(5)) .build(); private CeTaskMessagesImpl underTest = new CeTaskMessagesImpl(dbClient, uuidFactory, ceTask); @@ -69,8 +68,8 @@ public class CeTaskMessagesImplIT { @Test public void add_persist_message_to_DB() { - CeTaskMessages.Message message = new CeTaskMessages.Message(randomAlphabetic(20), 2_999L); - String uuid = randomAlphanumeric(40); + CeTaskMessages.Message message = new CeTaskMessages.Message(secure().nextAlphabetic(20), 2_999L); + String uuid = secure().nextAlphanumeric(40); when(uuidFactory.create()).thenReturn(uuid); underTest.add(message); @@ -91,10 +90,10 @@ public class CeTaskMessagesImplIT { Random random = new Random(); List messages = Stream.of( // some (or none) non null Message before null one - IntStream.range(0, random.nextInt(5)).mapToObj(i -> new CeTaskMessages.Message(randomAlphabetic(3) + "_i", 1_999L + i)), + IntStream.range(0, random.nextInt(5)).mapToObj(i -> new CeTaskMessages.Message(secure().nextAlphabetic(3) + "_i", 1_999L + i)), Stream.of((CeTaskMessages.Message) null), // some (or none) non null Message after null one - IntStream.range(0, random.nextInt(5)).mapToObj(i -> new CeTaskMessages.Message(randomAlphabetic(3) + "_i", 1_999L + i))) + IntStream.range(0, random.nextInt(5)).mapToObj(i -> new CeTaskMessages.Message(secure().nextAlphabetic(3) + "_i", 1_999L + i))) .flatMap(t -> t) .collect(toList()); diff --git a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskCanceledExceptionTest.java b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskCanceledExceptionTest.java index 6f3825f1dd1..36b50d3f9e5 100644 --- a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskCanceledExceptionTest.java +++ b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskCanceledExceptionTest.java @@ -22,14 +22,14 @@ package org.sonar.ce.task; import org.junit.Test; import org.sonar.db.ce.CeActivityDto; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; public class CeTaskCanceledExceptionTest { @Test public void message_is_based_on_specified_thread_name() { Thread t = new Thread(); - t.setName(randomAlphabetic(29)); + t.setName(secure().nextAlphabetic(29)); CeTaskCanceledException underTest = new CeTaskCanceledException(t); diff --git a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskComponentTest.java b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskComponentTest.java index 091c4fd6fb3..c9448120b98 100644 --- a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskComponentTest.java +++ b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskComponentTest.java @@ -25,7 +25,7 @@ import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.Test; import org.junit.runner.RunWith; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -58,10 +58,10 @@ public class CeTaskComponentTest { @Test public void equals_is_based_on_all_fields() { - String uuid = randomAlphabetic(2); - String key = randomAlphabetic(3); - String name = randomAlphabetic(4); - String somethingElse = randomAlphabetic(5); + String uuid = secure().nextAlphabetic(2); + String key = secure().nextAlphabetic(3); + String name = secure().nextAlphabetic(4); + String somethingElse = secure().nextAlphabetic(5); CeTask.Component underTest = new CeTask.Component(uuid, key, name); assertThat(underTest) @@ -77,10 +77,10 @@ public class CeTaskComponentTest { @Test public void hashcode_is_based_on_all_fields() { - String uuid = randomAlphabetic(2); - String key = randomAlphabetic(3); - String name = randomAlphabetic(4); - String somethingElse = randomAlphabetic(5); + String uuid = secure().nextAlphabetic(2); + String key = secure().nextAlphabetic(3); + String name = secure().nextAlphabetic(4); + String somethingElse = secure().nextAlphabetic(5); CeTask.Component underTest = new CeTask.Component(uuid, key, name); assertThat(underTest) diff --git a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskInterruptedExceptionTest.java b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskInterruptedExceptionTest.java index c0c69cc7aca..aaa4b37d01d 100644 --- a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskInterruptedExceptionTest.java +++ b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskInterruptedExceptionTest.java @@ -23,7 +23,7 @@ import java.util.Random; import org.junit.Test; import org.sonar.db.ce.CeActivityDto; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.ce.task.CeTaskInterruptedException.isTaskInterruptedException; @@ -31,7 +31,7 @@ public class CeTaskInterruptedExceptionTest { @Test public void isCauseInterruptedException_returns_CeTaskInterruptedException_or_subclass() { - String message = randomAlphabetic(50); + String message = secure().nextAlphabetic(50); CeActivityDto.Status status = randomStatus(); CeTaskInterruptedException e1 = new CeTaskInterruptedException(message, status) { @@ -46,7 +46,7 @@ public class CeTaskInterruptedExceptionTest { @Test public void isCauseInterruptedException_returns_CeTaskInterruptedException_or_subclass_in_cause_chain() { - String message = randomAlphabetic(50); + String message = secure().nextAlphabetic(50); CeActivityDto.Status status = randomStatus(); CeTaskInterruptedException e1 = new CeTaskInterruptedException(message, status) { diff --git a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskTimeoutExceptionTest.java b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskTimeoutExceptionTest.java index d624ed25023..7f5d3aba3ee 100644 --- a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskTimeoutExceptionTest.java +++ b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskTimeoutExceptionTest.java @@ -28,7 +28,7 @@ import org.sonar.db.ce.CeActivityDto; import static org.assertj.core.api.Assertions.assertThat; public class CeTaskTimeoutExceptionTest { - private String message = RandomStringUtils.randomAlphabetic(50); + private String message = RandomStringUtils.secure().nextAlphabetic(50); private CeTaskTimeoutException underTest = new CeTaskTimeoutException(message); @Test diff --git a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/log/CeTaskMessagesMessageTest.java b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/log/CeTaskMessagesMessageTest.java index 74663de4144..458f4111672 100644 --- a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/log/CeTaskMessagesMessageTest.java +++ b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/log/CeTaskMessagesMessageTest.java @@ -22,7 +22,7 @@ package org.sonar.ce.task.log; import org.junit.Test; import org.sonar.ce.task.log.CeTaskMessages.Message; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -52,7 +52,7 @@ public class CeTaskMessagesMessageTest { @Test public void equals_is_based_on_text_and_timestamp() { long timestamp = 10_000_000_000L; - String text = randomAlphabetic(23); + String text = secure().nextAlphabetic(23); Message underTest = new Message(text, timestamp); assertThat(underTest) @@ -67,7 +67,7 @@ public class CeTaskMessagesMessageTest { @Test public void hashsode_is_based_on_text_and_timestamp() { long timestamp = 10_000_000_000L; - String text = randomAlphabetic(23); + String text = secure().nextAlphabetic(23); Message underTest = new Message(text, timestamp); assertThat(underTest.hashCode()) diff --git a/server/sonar-ce/src/it/java/org/sonar/ce/notification/ReportAnalysisFailureNotificationExecutionListenerIT.java b/server/sonar-ce/src/it/java/org/sonar/ce/notification/ReportAnalysisFailureNotificationExecutionListenerIT.java index 74bb003acf6..a462fe431f0 100644 --- a/server/sonar-ce/src/it/java/org/sonar/ce/notification/ReportAnalysisFailureNotificationExecutionListenerIT.java +++ b/server/sonar-ce/src/it/java/org/sonar/ce/notification/ReportAnalysisFailureNotificationExecutionListenerIT.java @@ -51,7 +51,7 @@ import org.sonar.db.project.ProjectDto; import org.sonar.server.notification.NotificationService; import static java.util.Collections.singleton; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; @@ -99,7 +99,7 @@ public class ReportAnalysisFailureNotificationExecutionListenerIT { @Test public void onEnd_has_no_effect_if_CeTask_type_is_not_report() { - when(ceTaskMock.getType()).thenReturn(randomAlphanumeric(12)); + when(ceTaskMock.getType()).thenReturn(secure().nextAlphanumeric(12)); fullMockedUnderTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration(), ceTaskResultMock, throwableMock); @@ -145,8 +145,8 @@ public class ReportAnalysisFailureNotificationExecutionListenerIT { @Test public void onEnd_fails_with_ISE_if_branch_does_not_exist_in_DB() { - String componentUuid = randomAlphanumeric(6); - ProjectDto project = new ProjectDto().setUuid(componentUuid).setKey(randomAlphanumeric(5)).setQualifier(Qualifiers.PROJECT).setCreationMethod(CreationMethod.LOCAL_API); + String componentUuid = secure().nextAlphanumeric(6); + ProjectDto project = new ProjectDto().setUuid(componentUuid).setKey(secure().nextAlphanumeric(5)).setQualifier(Qualifiers.PROJECT).setCreationMethod(CreationMethod.LOCAL_API); dbTester.getDbClient().projectDao().insert(dbTester.getSession(), project); dbTester.getSession().commit(); when(ceTaskMock.getType()).thenReturn(CeTaskTypes.REPORT); @@ -164,7 +164,7 @@ public class ReportAnalysisFailureNotificationExecutionListenerIT { public void onEnd_fails_with_IAE_if_component_is_not_a_branch() { when(ceTaskMock.getType()).thenReturn(CeTaskTypes.REPORT); ComponentDto mainBranch = dbTester.components().insertPrivateProject().getMainBranchComponent(); - ComponentDto directory = dbTester.components().insertComponent(newDirectory(mainBranch, randomAlphanumeric(12))); + ComponentDto directory = dbTester.components().insertComponent(newDirectory(mainBranch, secure().nextAlphanumeric(12))); ComponentDto file = dbTester.components().insertComponent(ComponentTesting.newFileDto(mainBranch)); ComponentDto view = dbTester.components().insertComponent(ComponentTesting.newPortfolio()); ComponentDto subView = dbTester.components().insertComponent(ComponentTesting.newSubPortfolio(view)); @@ -193,7 +193,7 @@ public class ReportAnalysisFailureNotificationExecutionListenerIT { public void onEnd_fails_with_RowNotFoundException_if_activity_for_task_does_not_exist_in_DB() { ProjectData projectData = dbTester.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); - String taskUuid = randomAlphanumeric(6); + String taskUuid = secure().nextAlphanumeric(6); when(ceTaskMock.getType()).thenReturn(CeTaskTypes.REPORT); when(ceTaskMock.getUuid()).thenReturn(taskUuid); when(ceTaskMock.getComponent()).thenReturn(Optional.of(new CeTask.Component(mainBranch.uuid(), null, null))); @@ -208,7 +208,7 @@ public class ReportAnalysisFailureNotificationExecutionListenerIT { @Test public void onEnd_creates_notification_with_data_from_activity_and_project_and_deliver_it() { - String taskUuid = randomAlphanumeric(12); + String taskUuid = secure().nextAlphanumeric(12); int createdAt = random.nextInt(999_999); long executedAt = random.nextInt(999_999); ProjectData project = initMocksToPassConditions(taskUuid, createdAt, executedAt); @@ -234,7 +234,7 @@ public class ReportAnalysisFailureNotificationExecutionListenerIT { @Test public void onEnd_shouldCreateNotificationWithDataFromActivity_whenNonMainBranchIsFailing() { - String taskUuid = randomAlphanumeric(12); + String taskUuid = secure().nextAlphanumeric(12); int createdAt = random.nextInt(999_999); long executedAt = random.nextInt(999_999); @@ -264,8 +264,8 @@ public class ReportAnalysisFailureNotificationExecutionListenerIT { @Test public void onEnd_creates_notification_with_error_message_from_Throwable_argument_message() { - initMocksToPassConditions(randomAlphanumeric(12), random.nextInt(999_999), (long) random.nextInt(999_999)); - String message = randomAlphanumeric(66); + initMocksToPassConditions(secure().nextAlphanumeric(12), random.nextInt(999_999), (long) random.nextInt(999_999)); + String message = secure().nextAlphanumeric(66); when(throwableMock.getMessage()).thenReturn(message); underTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration(), ceTaskResultMock, throwableMock); @@ -278,7 +278,7 @@ public class ReportAnalysisFailureNotificationExecutionListenerIT { @Test public void onEnd_creates_notification_with_null_error_message_if_Throwable_is_null() { - String taskUuid = randomAlphanumeric(12); + String taskUuid = secure().nextAlphanumeric(12); initMocksToPassConditions(taskUuid, random.nextInt(999_999), (long) random.nextInt(999_999)); Notification notificationMock = mockSerializer(); @@ -293,7 +293,7 @@ public class ReportAnalysisFailureNotificationExecutionListenerIT { @Test public void onEnd_ignores_null_CeTaskResult_argument() { - String taskUuid = randomAlphanumeric(12); + String taskUuid = secure().nextAlphanumeric(12); initMocksToPassConditions(taskUuid, random.nextInt(999_999), (long) random.nextInt(999_999)); Notification notificationMock = mockSerializer(); @@ -304,7 +304,7 @@ public class ReportAnalysisFailureNotificationExecutionListenerIT { @Test public void onEnd_ignores_CeTaskResult_argument() { - String taskUuid = randomAlphanumeric(12); + String taskUuid = secure().nextAlphanumeric(12); initMocksToPassConditions(taskUuid, random.nextInt(999_999), (long) random.nextInt(999_999)); Notification notificationMock = mockSerializer(); @@ -316,7 +316,7 @@ public class ReportAnalysisFailureNotificationExecutionListenerIT { @Test public void onEnd_uses_system_data_as_failedAt_if_task_has_no_executedAt() { - String taskUuid = randomAlphanumeric(12); + String taskUuid = secure().nextAlphanumeric(12); initMocksToPassConditions(taskUuid, random.nextInt(999_999), null); long now = random.nextInt(999_999); when(system2.now()).thenReturn(now); diff --git a/server/sonar-ce/src/it/java/org/sonar/ce/taskprocessor/CeWorkerImplIT.java b/server/sonar-ce/src/it/java/org/sonar/ce/taskprocessor/CeWorkerImplIT.java index 0387d7ec429..2569c97e571 100644 --- a/server/sonar-ce/src/it/java/org/sonar/ce/taskprocessor/CeWorkerImplIT.java +++ b/server/sonar-ce/src/it/java/org/sonar/ce/taskprocessor/CeWorkerImplIT.java @@ -53,7 +53,7 @@ import org.sonar.db.ce.CeTaskTypes; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserTesting; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; @@ -397,7 +397,7 @@ class CeWorkerImplIT { @Test void call_sets_and_restores_thread_name_with_information_of_worker_when_there_is_no_task_to_process() throws Exception { - String threadName = randomAlphabetic(3); + String threadName = secure().nextAlphabetic(3); when(queue.peek(anyString(), anyBoolean())).thenAnswer(invocation -> { assertThat(Thread.currentThread().getName()) .isEqualTo("Worker " + ordinal + " (UUID=" + workerUuid + ") on " + threadName); @@ -411,7 +411,7 @@ class CeWorkerImplIT { @Test void call_sets_and_restores_thread_name_with_information_of_worker_when_a_task_is_processed() throws Exception { - String threadName = randomAlphabetic(3); + String threadName = secure().nextAlphabetic(3); when(queue.peek(anyString(), anyBoolean())).thenAnswer(invocation -> { assertThat(Thread.currentThread().getName()) .isEqualTo("Worker " + ordinal + " (UUID=" + workerUuid + ") on " + threadName); @@ -426,7 +426,7 @@ class CeWorkerImplIT { @Test void call_sets_and_restores_thread_name_with_information_of_worker_when_an_error_occurs() throws Exception { - String threadName = randomAlphabetic(3); + String threadName = secure().nextAlphabetic(3); CeTask ceTask = createCeTask(submitter); when(queue.peek(anyString(), anyBoolean())).thenAnswer(invocation -> { assertThat(Thread.currentThread().getName()) @@ -446,7 +446,7 @@ class CeWorkerImplIT { reset(ceWorkerController); when(ceWorkerController.isEnabled(underTest)).thenReturn(false); - String threadName = randomAlphabetic(3); + String threadName = secure().nextAlphabetic(3); Thread newThread = createThreadNameVerifyingThread(threadName); newThread.start(); @@ -587,7 +587,7 @@ class CeWorkerImplIT { void isExecutedBy_returns_false_unless_a_thread_is_currently_executing_a_task() throws InterruptedException { CountDownLatch inCallLatch = new CountDownLatch(1); CountDownLatch assertionsDoneLatch = new CountDownLatch(1); - String taskType = randomAlphabetic(12); + String taskType = secure().nextAlphabetic(12); CeTask ceTask = mock(CeTask.class); when(ceTask.getType()).thenReturn(taskType); when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(ceTask)); @@ -673,7 +673,7 @@ class CeWorkerImplIT { void getCurrentTask_returns_empty_unless_a_thread_is_currently_executing_a_task() throws InterruptedException { CountDownLatch inCallLatch = new CountDownLatch(1); CountDownLatch assertionsDoneLatch = new CountDownLatch(1); - String taskType = randomAlphabetic(12); + String taskType = secure().nextAlphabetic(12); CeTask ceTask = mock(CeTask.class); when(ceTask.getType()).thenReturn(taskType); when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(ceTask)); diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/configuration/CeWorkerCountSettingWarningTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/configuration/CeWorkerCountSettingWarningTest.java index 8e45999d8b9..886998ba1e0 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/configuration/CeWorkerCountSettingWarningTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/configuration/CeWorkerCountSettingWarningTest.java @@ -25,7 +25,7 @@ import org.slf4j.event.Level; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.testfixtures.log.LogTester; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; public class CeWorkerCountSettingWarningTest { @@ -55,7 +55,7 @@ public class CeWorkerCountSettingWarningTest { @Test public void start_logs_a_warning_if_property_ceWorkerCount_exists_with_a_value() { - settings.setProperty(PROPERTY_SONAR_CE_WORKER_COUNT, randomAlphabetic(12)); + settings.setProperty(PROPERTY_SONAR_CE_WORKER_COUNT, secure().nextAlphabetic(12)); underTest.start(); diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/monitoring/CeTasksMBeanImplTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/monitoring/CeTasksMBeanImplTest.java index c4808e860ef..baf3fd77d1d 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/monitoring/CeTasksMBeanImplTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/monitoring/CeTasksMBeanImplTest.java @@ -57,7 +57,7 @@ public class CeTasksMBeanImplTest { private static final int WORKER_MAX_COUNT = 666; private static final int WORKER_COUNT = 56; private static final Set WORKERS = IntStream.range(0, 2 + new Random().nextInt(10)) - .mapToObj(i -> RandomStringUtils.randomAlphabetic(15)) + .mapToObj(i -> RandomStringUtils.secure().nextAlphabetic(15)) .map(uuid -> { CeWorker res = mock(CeWorker.class); when(res.getUUID()).thenReturn(uuid); diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/SimpleCeTaskInterrupterTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/SimpleCeTaskInterrupterTest.java index 56558d16cff..7e87c120e6f 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/SimpleCeTaskInterrupterTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/SimpleCeTaskInterrupterTest.java @@ -23,7 +23,7 @@ import org.junit.Test; import org.sonar.ce.task.CeTask; import org.sonar.ce.task.CeTaskCanceledException; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; @@ -34,7 +34,7 @@ public class SimpleCeTaskInterrupterTest { @Test public void check_throws_CeTaskCanceledException_if_provided_thread_is_interrupted() throws InterruptedException { - String threadName = randomAlphabetic(30); + String threadName = secure().nextAlphabetic(30); ComputingThread t = new ComputingThread(threadName); try { diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/TimeoutCeTaskInterrupterTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/TimeoutCeTaskInterrupterTest.java index d22d6e12bbb..f881505255a 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/TimeoutCeTaskInterrupterTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/TimeoutCeTaskInterrupterTest.java @@ -30,7 +30,7 @@ import org.sonar.ce.task.CeTask; import org.sonar.ce.task.CeTaskCanceledException; import org.sonar.ce.task.CeTaskTimeoutException; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; @@ -96,7 +96,7 @@ public class TimeoutCeTaskInterrupterTest { @Test public void check_fails_with_ISE_if_thread_is_executing_a_CeTask_but_on_start_has_not_been_called_on_it() { - String taskUuid = randomAlphabetic(15); + String taskUuid = secure().nextAlphabetic(15); Thread t = new Thread(); mockWorkerOnThread(t, ceWorker); mockWorkerWithTask(ceTask); @@ -109,7 +109,7 @@ public class TimeoutCeTaskInterrupterTest { @Test public void check_fails_with_ISE_if_thread_is_executing_a_CeTask_but_on_start_and_on_end_have_not_been_called_on_it() { - String taskUuid = randomAlphabetic(15); + String taskUuid = secure().nextAlphabetic(15); Thread t = new Thread(); mockWorkerOnThread(t, ceWorker); mockWorkerWithTask(ceTask); @@ -124,7 +124,7 @@ public class TimeoutCeTaskInterrupterTest { @Test public void check_throws_CeTaskCanceledException_if_provided_thread_is_interrupted() throws InterruptedException { - String threadName = randomAlphabetic(30); + String threadName = secure().nextAlphabetic(30); ComputingThread t = new ComputingThread(threadName); mockWorkerOnThread(t, ceWorker); mockWorkerWithTask(ceTask); @@ -171,7 +171,7 @@ public class TimeoutCeTaskInterrupterTest { @Test public void check_throws_CeTaskCanceledException_if_provided_thread_is_interrupted_even_if_timed_out() throws InterruptedException { - String threadName = randomAlphabetic(30); + String threadName = secure().nextAlphabetic(30); ComputingThread t = new ComputingThread(threadName); mockWorkerOnThread(t, ceWorker); mockWorkerWithTask(ceTask); @@ -197,7 +197,7 @@ public class TimeoutCeTaskInterrupterTest { } private static Thread newThreadWithRandomName() { - String threadName = randomAlphabetic(30); + String threadName = secure().nextAlphabetic(30); Thread t = new Thread(); t.setName(threadName); return t; diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/alm/pat/AlmPatDaoIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/alm/pat/AlmPatDaoIT.java index 7fba2db8cce..cf4ed16dc6e 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/alm/pat/AlmPatDaoIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/alm/pat/AlmPatDaoIT.java @@ -30,7 +30,7 @@ import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.audit.NoOpAuditPersister; import org.sonar.db.user.UserDto; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -78,7 +78,7 @@ class AlmPatDaoIT { AlmPatDto almPatDto = newAlmPatDto(); almPatDto.setAlmSettingUuid(almSetting.getUuid()); - String userUuid = randomAlphanumeric(40); + String userUuid = secure().nextAlphanumeric(40); almPatDto.setUserUuid(userUuid); underTest.insert(dbSession, almPatDto, null, null); @@ -89,7 +89,7 @@ class AlmPatDaoIT { .containsExactly(A_UUID, almPatDto.getPersonalAccessToken(), userUuid, almSetting.getUuid(), NOW, NOW); - assertThat(underTest.selectByUserAndAlmSetting(dbSession, randomAlphanumeric(40), newGithubAlmSettingDto())).isNotPresent(); + assertThat(underTest.selectByUserAndAlmSetting(dbSession, secure().nextAlphanumeric(40), newGithubAlmSettingDto())).isNotPresent(); } @Test diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/audit/AuditDaoIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/audit/AuditDaoIT.java index 089898fa803..079f453b421 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/audit/AuditDaoIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/audit/AuditDaoIT.java @@ -30,7 +30,7 @@ import org.sonar.core.util.UuidFactoryImpl; import org.sonar.db.DbSession; import org.sonar.db.DbTester; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.db.audit.AuditDao.EXCEEDED_LENGTH; @@ -131,7 +131,7 @@ class AuditDaoIT { @Test void insert_truncateVeryLongNewValue() { AuditDto auditDto = AuditTesting.newAuditDto(); - String veryLongString = randomAlphanumeric(5000); + String veryLongString = secure().nextAlphanumeric(5000); auditDto.setNewValue(veryLongString); testAuditDao.insert(dbSession, auditDto); diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/ce/CeActivityDaoIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/ce/CeActivityDaoIT.java index 5159888bea3..d5129752906 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/ce/CeActivityDaoIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/ce/CeActivityDaoIT.java @@ -51,7 +51,7 @@ import org.sonar.db.project.ProjectDto; import static java.util.Collections.emptyList; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.db.Pagination.forPage; @@ -64,9 +64,9 @@ import static org.sonar.db.ce.CeTaskTypes.REPORT; class CeActivityDaoIT { - private static final String ENTITY_1 = randomAlphabetic(12); - private static final String MAINCOMPONENT_2 = randomAlphabetic(13); - private static final String COMPONENT_1 = randomAlphabetic(14); + private static final String ENTITY_1 = secure().nextAlphabetic(12); + private static final String MAINCOMPONENT_2 = secure().nextAlphabetic(13); + private static final String COMPONENT_1 = secure().nextAlphabetic(14); private static final long INITIAL_TIME = 1_450_000_000_000L; private static final String NODE_NAME = "node1"; @@ -158,11 +158,11 @@ class CeActivityDaoIT { @ParameterizedTest @MethodSource("notCanceledStatus") void insert_resets_is_last_and_main_is_last_fields_based_on_component_and_main_component(CeActivityDto.Status status) { - String project1 = randomAlphabetic(5); - String branch11 = randomAlphabetic(6); - String project2 = randomAlphabetic(8); - String branch21 = randomAlphabetic(9); - String type = randomAlphabetic(10); + String project1 = secure().nextAlphabetic(5); + String branch11 = secure().nextAlphabetic(6); + String project2 = secure().nextAlphabetic(8); + String branch21 = secure().nextAlphabetic(9); + String type = secure().nextAlphabetic(10); String task1Project1 = insertAndCommit(newUuid(), type, project1, project1, status).getUuid(); assertIsLastAndMainIsLastFieldsOf(task1Project1).containsOnly(tuple(true, true)); @@ -220,10 +220,10 @@ class CeActivityDaoIT { @ParameterizedTest @MethodSource("notCanceledStatus") void insert_resets_is_last_and_main_is_last_fields_based_on_type(CeActivityDto.Status status) { - String type1 = randomAlphabetic(10); - String type2 = randomAlphabetic(11); - String project = randomAlphabetic(5); - String branch = randomAlphabetic(6); + String type1 = secure().nextAlphabetic(10); + String type2 = secure().nextAlphabetic(11); + String project = secure().nextAlphabetic(5); + String branch = secure().nextAlphabetic(6); String type1Project1 = insertAndCommit(newUuid(), type1, project, project, status).getUuid(); assertIsLastAndMainIsLastFieldsOf(type1Project1).containsOnly(tuple(true, true)); @@ -262,9 +262,9 @@ class CeActivityDaoIT { @ParameterizedTest @MethodSource("notCanceledStatus") void insert_resets_is_last_and_main_is_last_fields_based_on_component_or_not(CeActivityDto.Status status) { - String project = randomAlphabetic(5); - String type1 = randomAlphabetic(11); - String type2 = randomAlphabetic(11); + String project = secure().nextAlphabetic(5); + String type1 = secure().nextAlphabetic(11); + String type2 = secure().nextAlphabetic(11); String type1Project1 = insertAndCommit(newUuid(), type1, project, project, status).getUuid(); assertIsLastAndMainIsLastFieldsOf(type1Project1).containsOnly(tuple(true, true)); @@ -303,9 +303,9 @@ class CeActivityDaoIT { @ParameterizedTest @MethodSource("notCanceledStatus") void insert_does_not_resets_is_last_and_main_is_last_fields_if_status_is_CANCELED(CeActivityDto.Status status) { - String project = randomAlphabetic(5); - String branch = randomAlphabetic(6); - String type = randomAlphabetic(10); + String project = secure().nextAlphabetic(5); + String branch = secure().nextAlphabetic(6); + String type = secure().nextAlphabetic(10); String task1Project1 = insertAndCommit(newUuid(), type, project, project, status).getUuid(); assertIsLastAndMainIsLastFieldsOf(task1Project1).containsOnly(tuple(true, true)); diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/component/AnalysisPropertiesDaoIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/component/AnalysisPropertiesDaoIT.java index 60c5b58dc46..a3cd73549ff 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/component/AnalysisPropertiesDaoIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/component/AnalysisPropertiesDaoIT.java @@ -31,7 +31,7 @@ import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.project.ProjectDto; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.tuple; @@ -50,9 +50,9 @@ class AnalysisPropertiesDaoIT { @Test void insert_with_null_uuid_throws_NPE() { AnalysisPropertyDto analysisPropertyDto = new AnalysisPropertyDto() - .setAnalysisUuid(randomAlphanumeric(10)) - .setKey(randomAlphanumeric(10)) - .setValue(randomAlphanumeric(10)); + .setAnalysisUuid(secure().nextAlphanumeric(10)) + .setKey(secure().nextAlphanumeric(10)) + .setValue(secure().nextAlphanumeric(10)); assertThatThrownBy(() -> underTest.insert(dbSession, analysisPropertyDto)) .isInstanceOf(NullPointerException.class) @@ -62,9 +62,9 @@ class AnalysisPropertiesDaoIT { @Test void insert_with_null_key_throws_NPE() { AnalysisPropertyDto analysisPropertyDto = new AnalysisPropertyDto() - .setAnalysisUuid(randomAlphanumeric(10)) - .setUuid(randomAlphanumeric(10)) - .setValue(randomAlphanumeric(10)); + .setAnalysisUuid(secure().nextAlphanumeric(10)) + .setUuid(secure().nextAlphanumeric(10)) + .setValue(secure().nextAlphanumeric(10)); assertThatThrownBy(() -> underTest.insert(dbSession, analysisPropertyDto)) .isInstanceOf(NullPointerException.class) @@ -74,9 +74,9 @@ class AnalysisPropertiesDaoIT { @Test void insert_with_null_analysis_uuid_throws_NPE() { AnalysisPropertyDto analysisPropertyDto = new AnalysisPropertyDto() - .setUuid(randomAlphanumeric(10)) - .setKey(randomAlphanumeric(10)) - .setValue(randomAlphanumeric(10)); + .setUuid(secure().nextAlphanumeric(10)) + .setKey(secure().nextAlphanumeric(10)) + .setValue(secure().nextAlphanumeric(10)); assertThatThrownBy(() -> underTest.insert(dbSession, analysisPropertyDto)) .isInstanceOf(NullPointerException.class) @@ -86,9 +86,9 @@ class AnalysisPropertiesDaoIT { @Test void insert_with_null_value_throws_NPE() { AnalysisPropertyDto analysisPropertyDto = new AnalysisPropertyDto() - .setAnalysisUuid(randomAlphanumeric(10)) - .setUuid(randomAlphanumeric(10)) - .setKey(randomAlphanumeric(10)); + .setAnalysisUuid(secure().nextAlphanumeric(10)) + .setUuid(secure().nextAlphanumeric(10)) + .setKey(secure().nextAlphanumeric(10)); assertThatThrownBy(() -> underTest.insert(dbSession, analysisPropertyDto)) .isInstanceOf(NullPointerException.class) @@ -122,14 +122,14 @@ class AnalysisPropertiesDaoIT { @Test void insert_a_list() { List propertyDtos = Arrays.asList( - newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)), - newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)), - newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)), - newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)), - newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)), - newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)), - newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40)), - newAnalysisPropertyDto(random.nextInt(8000), randomAlphanumeric(40))); + newAnalysisPropertyDto(random.nextInt(8000), secure().nextAlphanumeric(40)), + newAnalysisPropertyDto(random.nextInt(8000), secure().nextAlphanumeric(40)), + newAnalysisPropertyDto(random.nextInt(8000), secure().nextAlphanumeric(40)), + newAnalysisPropertyDto(random.nextInt(8000), secure().nextAlphanumeric(40)), + newAnalysisPropertyDto(random.nextInt(8000), secure().nextAlphanumeric(40)), + newAnalysisPropertyDto(random.nextInt(8000), secure().nextAlphanumeric(40)), + newAnalysisPropertyDto(random.nextInt(8000), secure().nextAlphanumeric(40)), + newAnalysisPropertyDto(random.nextInt(8000), secure().nextAlphanumeric(40))); underTest.insert(dbSession, propertyDtos); assertThat(dbTester.countRowsOfTable(dbSession, "ANALYSIS_PROPERTIES")).isEqualTo(propertyDtos.size()); @@ -137,7 +137,7 @@ class AnalysisPropertiesDaoIT { @Test void selectByAnalysisUuid_should_return_correct_values() { - String analysisUuid = randomAlphanumeric(40); + String analysisUuid = secure().nextAlphanumeric(40); List propertyDtos = Arrays.asList( newAnalysisPropertyDto(random.nextInt(8000), analysisUuid), @@ -158,7 +158,7 @@ class AnalysisPropertiesDaoIT { @Test void selectByKeyAndAnalysisUuids_should_return_correct_values() { - String analysisUuid = randomAlphanumeric(40); + String analysisUuid = secure().nextAlphanumeric(40); List propertyDtos = Arrays.asList( newAnalysisPropertyDto(random.nextInt(10), "key1", analysisUuid), @@ -218,7 +218,7 @@ class AnalysisPropertiesDaoIT { } private AnalysisPropertyDto insertAnalysisPropertyDto(int valueLength) { - AnalysisPropertyDto analysisPropertyDto = newAnalysisPropertyDto(valueLength, randomAlphanumeric(40)); + AnalysisPropertyDto analysisPropertyDto = newAnalysisPropertyDto(valueLength, secure().nextAlphanumeric(40)); underTest.insert(dbSession, analysisPropertyDto); return analysisPropertyDto; } @@ -227,13 +227,13 @@ class AnalysisPropertiesDaoIT { return new AnalysisPropertyDto() .setAnalysisUuid(analysisUuid) .setKey(key) - .setUuid(randomAlphanumeric(40)) - .setValue(randomAlphanumeric(valueLength)) + .setUuid(secure().nextAlphanumeric(40)) + .setValue(secure().nextAlphanumeric(valueLength)) .setCreatedAt(1_000L); } private AnalysisPropertyDto newAnalysisPropertyDto(int valueLength, String analysisUuid) { - return newAnalysisPropertyDto(valueLength, randomAlphanumeric(512), analysisUuid); + return newAnalysisPropertyDto(valueLength, secure().nextAlphanumeric(512), analysisUuid); } private void compareFirstValueWith(AnalysisPropertyDto analysisPropertyDto) { diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/component/ComponentDaoIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/component/ComponentDaoIT.java index 198ae57e5c1..a5288b236bf 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/component/ComponentDaoIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/component/ComponentDaoIT.java @@ -60,7 +60,7 @@ import static java.util.Collections.emptySet; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toSet; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; @@ -605,7 +605,7 @@ class ComponentDaoIT { @MethodSource("oneOrMoreProjects") void selectViewKeysWithEnabledCopyOfProject_returns_empty_when_there_is_no_view(int projectCount) { Set projectUuids = IntStream.range(0, projectCount) - .mapToObj(i -> randomAlphabetic(5)) + .mapToObj(i -> secure().nextAlphabetic(5)) .collect(toSet()); assertThat(underTest.selectViewKeysWithEnabledCopyOfProject(dbSession, projectUuids)).isEmpty(); @@ -1789,7 +1789,7 @@ class ComponentDaoIT { @Test void selectByKeyCaseInsensitive_shouldFindProject_whenCaseIsDifferent() { - String projectKey = randomAlphabetic(5).toLowerCase(); + String projectKey = secure().nextAlphabetic(5).toLowerCase(); db.components().insertPrivateProject(c -> c.setKey(projectKey)).getMainBranchComponent(); List result = underTest.selectByKeyCaseInsensitive(db.getSession(), projectKey.toUpperCase()); @@ -1800,7 +1800,7 @@ class ComponentDaoIT { @Test void selectByKeyCaseInsensitive_should_not_match_non_main_branch() { - String projectKey = randomAlphabetic(5).toLowerCase(); + String projectKey = secure().nextAlphabetic(5).toLowerCase(); ProjectDto project = db.components().insertPrivateProject(c -> c.setKey(projectKey)).getProjectDto(); BranchDto projectBranch = db.components().insertProjectBranch(project); ComponentDto file = db.components().insertFile(projectBranch); @@ -1812,10 +1812,10 @@ class ComponentDaoIT { @Test void selectByKeyCaseInsensitive_shouldNotFindProject_whenKeyIsDifferent() { - String projectKey = randomAlphabetic(5).toLowerCase(); + String projectKey = secure().nextAlphabetic(5).toLowerCase(); db.components().insertPrivateProject(c -> c.setKey(projectKey)).getMainBranchComponent(); - List result = underTest.selectByKeyCaseInsensitive(db.getSession(), projectKey + randomAlphabetic(1)); + List result = underTest.selectByKeyCaseInsensitive(db.getSession(), projectKey + secure().nextAlphabetic(1)); assertThat(result).isEmpty(); } @@ -1826,7 +1826,7 @@ class ComponentDaoIT { private static Set shuffleWithNonExistentUuids(String... uuids) { return Stream.concat( - IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(i -> randomAlphabetic(9)), + IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(i -> secure().nextAlphabetic(9)), Arrays.stream(uuids)) .collect(toSet()); } diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/component/ComponentKeyUpdaterDaoIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/component/ComponentKeyUpdaterDaoIT.java index c6964a51ba7..d508194217c 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/component/ComponentKeyUpdaterDaoIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/component/ComponentKeyUpdaterDaoIT.java @@ -32,7 +32,7 @@ import org.sonar.db.audit.AuditPersister; import org.sonar.db.audit.model.ComponentKeyNewValue; import org.sonar.db.project.ProjectDto; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; @@ -98,7 +98,7 @@ class ComponentKeyUpdaterDaoIT { void updateKey_updates_branches_too() { ProjectData projectData = db.components().insertPublicProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(mainBranch, b -> b.setKey(branchName)); db.components().insertComponent(newFileDto(branch, mainBranch.uuid())); db.components().insertComponent(newFileDto(branch, mainBranch.uuid())); @@ -125,7 +125,7 @@ class ComponentKeyUpdaterDaoIT { void updateKey_updates_pull_requests_too() { ProjectData projectData = db.components().insertPublicProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); - String pullRequestKey1 = randomAlphanumeric(100); + String pullRequestKey1 = secure().nextAlphanumeric(100); ComponentDto pullRequest = db.components().insertProjectBranch(mainBranch, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey1)); db.components().insertComponent(newFileDto(pullRequest)); db.components().insertComponent(newFileDto(pullRequest)); diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/component/ScrollForFileMoveComponentDaoIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/component/ScrollForFileMoveComponentDaoIT.java index 0f6edb1c5d9..9a509e8da57 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/component/ScrollForFileMoveComponentDaoIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/component/ScrollForFileMoveComponentDaoIT.java @@ -38,7 +38,7 @@ import org.sonar.db.DbTester; import org.sonar.db.audit.NoOpAuditPersister; import org.sonar.db.source.FileSourceDto; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.resources.Qualifiers.FILE; import static org.sonar.api.resources.Qualifiers.UNIT_TEST_FILE; @@ -52,7 +52,7 @@ class ScrollForFileMoveComponentDaoIT { @Test void scrollAllFilesForFileMove_has_no_effect_if_project_does_not_exist() { - String nonExistingProjectUuid = randomAlphabetic(10); + String nonExistingProjectUuid = secure().nextAlphabetic(10); underTest.scrollAllFilesForFileMove(dbSession, nonExistingProjectUuid, resultContext -> Assertions.fail("handler should not be " + "called")); diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/component/SnapshotDaoIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/component/SnapshotDaoIT.java index 606ac14a93c..7a980f8ef40 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/component/SnapshotDaoIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/component/SnapshotDaoIT.java @@ -46,7 +46,7 @@ import static com.google.common.collect.Lists.newArrayList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.db.ce.CeActivityDto.Status.CANCELED; @@ -456,7 +456,7 @@ class SnapshotDaoIT { return new Object[][]{ {null}, {""}, - {randomAlphanumeric(7)}, + {secure().nextAlphanumeric(7)}, }; } @@ -571,7 +571,7 @@ class SnapshotDaoIT { CeQueueDto queueDto = new CeQueueDto(); queueDto.setTaskType(CeTaskTypes.REPORT); queueDto.setComponentUuid(projectUuid); - queueDto.setUuid(randomAlphanumeric(40)); + queueDto.setUuid(secure().nextAlphanumeric(40)); queueDto.setCreatedAt(random.nextLong(Long.MAX_VALUE)); CeActivityDto activityDto = new CeActivityDto(queueDto); activityDto.setStatus(status); diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/event/EventComponentChangeDaoIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/event/EventComponentChangeDaoIT.java index bb7b889b155..bec72eaf5fb 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/event/EventComponentChangeDaoIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/event/EventComponentChangeDaoIT.java @@ -30,7 +30,7 @@ import org.sonar.db.DbSession; import org.sonar.db.DbTester; import static java.util.Collections.singletonList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; @@ -53,14 +53,14 @@ class EventComponentChangeDaoIT { @Test void selectByEventUuid_on_empty_table() { - assertThat(underTest.selectByEventUuid(dbSession, randomAlphabetic(10))) + assertThat(underTest.selectByEventUuid(dbSession, secure().nextAlphabetic(10))) .isEmpty(); } @Test void selectByEventUuid_maps_columns_correctly() { - String eventBase = randomAlphabetic(5); - String rowBase = randomAlphabetic(6); + String eventBase = secure().nextAlphabetic(5); + String rowBase = secure().nextAlphabetic(6); String eventUuid = eventBase + "_event_uuid"; String uuid = rowBase + "_uuid"; EventComponentChangeDto dto = new EventComponentChangeDto() @@ -101,8 +101,8 @@ class EventComponentChangeDaoIT { @Test void selectByAnalysisUuids_maps_columns_correctly() { - String eventBase = randomAlphabetic(5); - String rowBase = randomAlphabetic(6); + String eventBase = secure().nextAlphabetic(5); + String rowBase = secure().nextAlphabetic(6); String eventUuid = eventBase + "_event_uuid"; String uuid = rowBase + "_uuid"; EventComponentChangeDto dto = new EventComponentChangeDto() @@ -143,8 +143,8 @@ class EventComponentChangeDaoIT { @Test void selectByEventUuid_branchKey_can_be_null() { - String eventBase = randomAlphabetic(5); - String rowBase = randomAlphabetic(6); + String eventBase = secure().nextAlphabetic(5); + String rowBase = secure().nextAlphabetic(6); String eventUuid = eventBase + "_event_uuid"; EventComponentChangeDto dto = new EventComponentChangeDto() .setCategory(REMOVED) @@ -168,8 +168,8 @@ class EventComponentChangeDaoIT { @Test void selectByEventUuid_returns_all_rows_for_specified_event() { - String eventBase = randomAlphabetic(5); - String rowBase = randomAlphabetic(6); + String eventBase = secure().nextAlphabetic(5); + String rowBase = secure().nextAlphabetic(6); String eventUuid1 = eventBase + "_event_uuid1"; String eventUuid2 = eventBase + "_event_uuid2"; EventComponentChangeDto[] event1Dtos = IntStream.range(0, 3) @@ -192,7 +192,7 @@ class EventComponentChangeDaoIT { .setComponentName(rowBase + "_component_name") .setComponentBranchKey(null)) .toArray(EventComponentChangeDto[]::new); - EventPurgeData doesNotMatter = new EventPurgeData(randomAlphabetic(7), randomAlphabetic(8)); + EventPurgeData doesNotMatter = new EventPurgeData(secure().nextAlphabetic(7), secure().nextAlphabetic(8)); when(system2.now()).thenReturn(now) .thenReturn(now + 1) .thenReturn(now + 2) @@ -239,8 +239,8 @@ class EventComponentChangeDaoIT { @Test void selectByAnalysisUuids_returns_all_rows_for_specified_event() { - String eventBase = randomAlphabetic(5); - String rowBase = randomAlphabetic(6); + String eventBase = secure().nextAlphabetic(5); + String rowBase = secure().nextAlphabetic(6); String eventUuid1 = eventBase + "_event_uuid1"; String eventUuid2 = eventBase + "_event_uuid2"; EventComponentChangeDto[] event1Dtos = IntStream.range(0, 3) @@ -263,7 +263,7 @@ class EventComponentChangeDaoIT { .setComponentName(rowBase + "_component_name") .setComponentBranchKey(null)) .toArray(EventComponentChangeDto[]::new); - EventPurgeData doesNotMatter = new EventPurgeData(randomAlphabetic(7), randomAlphabetic(8)); + EventPurgeData doesNotMatter = new EventPurgeData(secure().nextAlphabetic(7), secure().nextAlphabetic(8)); when(system2.now()).thenReturn(now) .thenReturn(now + 1) .thenReturn(now + 2) diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/issue/IssueMapperIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/issue/IssueMapperIT.java index 9646983c237..374f82cf99f 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/issue/IssueMapperIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/issue/IssueMapperIT.java @@ -51,7 +51,7 @@ import org.sonar.db.component.ComponentTesting; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleTesting; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; @@ -246,7 +246,7 @@ class IssueMapperIT { @Test void scrollClosedByComponentUuid_returns_empty_when_no_issue_for_component() { - String componentUuid = randomAlphabetic(10); + String componentUuid = secure().nextAlphabetic(10); RecorderResultHandler resultHandler = new RecorderResultHandler(); underTest.scrollClosedByComponentUuid(componentUuid, new Date().getTime(), resultHandler); diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/project/ProjectExportDaoIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/project/ProjectExportDaoIT.java index 6d7dbfe0619..0df5a0e5271 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/project/ProjectExportDaoIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/project/ProjectExportDaoIT.java @@ -202,13 +202,13 @@ class ProjectExportDaoIT { .setIsExternal(isExternal) .setIsAdHoc(isAdHoc) .setRuleKey(ruleKey) - .setPluginKey("pluginKey" + RandomStringUtils.randomAlphanumeric(10)) + .setPluginKey("pluginKey" + RandomStringUtils.secure().nextAlphanumeric(10)) .setStatus(ruleStatus); if (isAdHoc) { - rule.setAdHocName("ad_hoc_rule" + RandomStringUtils.randomAlphabetic(10)) + rule.setAdHocName("ad_hoc_rule" + RandomStringUtils.secure().nextAlphabetic(10)) .setAdHocType(RuleType.VULNERABILITY) .setAdHocSeverity(Severity.CRITICAL) - .setAdHocDescription("ad hoc description: " + RandomStringUtils.randomAlphanumeric(100)); + .setAdHocDescription("ad hoc description: " + RandomStringUtils.secure().nextAlphanumeric(100)); } }; } diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/property/InternalPropertiesDaoIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/property/InternalPropertiesDaoIT.java index 3bb89a1adeb..2beac85fd0d 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/property/InternalPropertiesDaoIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/property/InternalPropertiesDaoIT.java @@ -48,7 +48,7 @@ import org.sonar.db.audit.model.PropertyNewValue; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; @@ -494,7 +494,7 @@ class InternalPropertiesDaoIT { @Test void tryLock_fails_if_it_would_insert_concurrently() { - String name = randomAlphabetic(5); + String name = secure().nextAlphabetic(5); String propertyKey = propertyKeyOf(name); long now = new Random().nextInt(); @@ -516,7 +516,7 @@ class InternalPropertiesDaoIT { @Test void tryLock_fails_if_concurrent_caller_succeeded_first() { int lockDurationSeconds = 60; - String name = randomAlphabetic(5); + String name = secure().nextAlphabetic(5); String propertyKey = propertyKeyOf(name); long now = new Random().nextInt(4_889_989); @@ -548,7 +548,7 @@ class InternalPropertiesDaoIT { @Test void tryLock_throws_IAE_if_lock_name_length_is_too_long() { - String tooLongName = randomAlphabetic(LOCK_NAME_MAX_LENGTH + 1); + String tooLongName = secure().nextAlphabetic(LOCK_NAME_MAX_LENGTH + 1); assertThatThrownBy(() -> underTest.tryLock(dbSession, tooLongName, 60)) .isInstanceOf(IllegalArgumentException.class) diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/property/PropertiesDaoIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/property/PropertiesDaoIT.java index 754eb0ece6e..b136fd44817 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/property/PropertiesDaoIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/property/PropertiesDaoIT.java @@ -50,7 +50,7 @@ import org.sonar.db.user.UserDto; import static com.google.common.collect.ImmutableSet.of; import static com.google.common.collect.Sets.newHashSet; import static java.util.Collections.singletonList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; @@ -91,8 +91,8 @@ class PropertiesDaoIT { UserDto user1 = db.users().insertUser(u -> u.setLogin("user1")); UserDto user2 = db.users().insertUser(u -> u.setLogin("user2")); String projectUuid = db.components().insertPrivateProject().getProjectDto().getUuid(); - String projectKey = randomAlphabetic(4); - String projectName = randomAlphabetic(4); + String projectKey = secure().nextAlphabetic(4); + String projectName = secure().nextAlphabetic(4); // global subscription @@ -135,9 +135,9 @@ class PropertiesDaoIT { @Test void findEmailRecipientsForNotification_returns_empty_on_empty_properties_table() { db.users().insertUser(); - String dispatcherKey = randomAlphabetic(5); - String channelKey = randomAlphabetic(6); - String projectKey = randomAlphabetic(7); + String dispatcherKey = secure().nextAlphabetic(5); + String channelKey = secure().nextAlphabetic(6); + String projectKey = secure().nextAlphabetic(7); Set subscribers = underTest.findEmailSubscribersForNotification(db.getSession(), dispatcherKey, channelKey, projectKey); @@ -148,9 +148,9 @@ class PropertiesDaoIT { @Test void findEmailRecipientsForNotification_with_logins_returns_empty_on_empty_properties_table() { db.users().insertUser(); - String dispatcherKey = randomAlphabetic(5); - String channelKey = randomAlphabetic(6); - String projectKey = randomAlphabetic(7); + String dispatcherKey = secure().nextAlphabetic(5); + String channelKey = secure().nextAlphabetic(6); + String projectKey = secure().nextAlphabetic(7); Set logins = of("user1", "user2"); Set subscribers = underTest.findEmailSubscribersForNotification(db.getSession(), dispatcherKey, channelKey, @@ -166,10 +166,10 @@ class PropertiesDaoIT { UserDto user3 = db.users().insertUser(withEmail("user3")); UserDto user4 = db.users().insertUser(withEmail("user4")); ProjectDto project = insertPrivateProject("PROJECT_A"); - String dispatcherKey = randomAlphabetic(5); - String otherDispatcherKey = randomAlphabetic(6); - String channelKey = randomAlphabetic(7); - String otherChannelKey = randomAlphabetic(8); + String dispatcherKey = secure().nextAlphabetic(5); + String otherDispatcherKey = secure().nextAlphabetic(6); + String channelKey = secure().nextAlphabetic(7); + String otherChannelKey = secure().nextAlphabetic(8); // user1 subscribed only globally insertProperty(propertyKeyOf(dispatcherKey, channelKey), "true", null, user1.getUuid(), user1.getLogin(), null, null); @@ -203,10 +203,10 @@ class PropertiesDaoIT { UserDto user3 = db.users().insertUser(withEmail("user3")); UserDto user4 = db.users().insertUser(withEmail("user4")); ProjectDto project = insertPrivateProject("PROJECT_A"); - String dispatcherKey = randomAlphabetic(5); - String otherDispatcherKey = randomAlphabetic(6); - String channelKey = randomAlphabetic(7); - String otherChannelKey = randomAlphabetic(8); + String dispatcherKey = secure().nextAlphabetic(5); + String otherDispatcherKey = secure().nextAlphabetic(6); + String channelKey = secure().nextAlphabetic(7); + String otherChannelKey = secure().nextAlphabetic(8); // user1 subscribed only globally insertProperty(propertyKeyOf(dispatcherKey, channelKey), "true", null, user1.getUuid(), user1.getLogin(), null, null); @@ -276,13 +276,13 @@ class PropertiesDaoIT { UserDto user2 = db.users().insertUser(withEmail("user2")); UserDto user3 = db.users().insertUser(withEmail("user3")); UserDto user4 = db.users().insertUser(withEmail("user4")); - String projectKey = randomAlphabetic(3); - String otherProjectKey = randomAlphabetic(4); + String projectKey = secure().nextAlphabetic(3); + String otherProjectKey = secure().nextAlphabetic(4); ProjectDto project = insertPrivateProject(projectKey); - String dispatcherKey = randomAlphabetic(5); - String otherDispatcherKey = randomAlphabetic(6); - String channelKey = randomAlphabetic(7); - String otherChannelKey = randomAlphabetic(8); + String dispatcherKey = secure().nextAlphabetic(5); + String otherDispatcherKey = secure().nextAlphabetic(6); + String channelKey = secure().nextAlphabetic(7); + String otherChannelKey = secure().nextAlphabetic(8); // user1 subscribed only globally insertProperty(propertyKeyOf(dispatcherKey, channelKey), "true", null, user1.getUuid(), user1.getLogin(), null, null); @@ -320,13 +320,13 @@ class PropertiesDaoIT { UserDto user2 = db.users().insertUser(withEmail("user2")); UserDto user3 = db.users().insertUser(withEmail("user3")); UserDto user4 = db.users().insertUser(withEmail("user4")); - String projectKey = randomAlphabetic(3); - String otherProjectKey = randomAlphabetic(4); + String projectKey = secure().nextAlphabetic(3); + String otherProjectKey = secure().nextAlphabetic(4); ProjectDto project = insertPrivateProject(projectKey); - String dispatcherKey = randomAlphabetic(5); - String otherDispatcherKey = randomAlphabetic(6); - String channelKey = randomAlphabetic(7); - String otherChannelKey = randomAlphabetic(8); + String dispatcherKey = secure().nextAlphabetic(5); + String otherDispatcherKey = secure().nextAlphabetic(6); + String channelKey = secure().nextAlphabetic(7); + String otherChannelKey = secure().nextAlphabetic(8); // user1 subscribed only globally insertProperty(propertyKeyOf(dispatcherKey, channelKey), "true", null, user1.getUuid(), user1.getLogin(), null, null); @@ -375,10 +375,10 @@ class PropertiesDaoIT { UserDto user2 = db.users().insertUser(noEmail("user2")); UserDto user3 = db.users().insertUser(withEmail("user3")); UserDto user4 = db.users().insertUser(noEmail("user4")); - String projectKey = randomAlphabetic(3); + String projectKey = secure().nextAlphabetic(3); ProjectDto project = insertPrivateProject(projectKey); - String dispatcherKey = randomAlphabetic(4); - String channelKey = randomAlphabetic(5); + String dispatcherKey = secure().nextAlphabetic(4); + String channelKey = secure().nextAlphabetic(5); // user1 and user2 subscribed on project and globally insertProperty(propertyKeyOf(dispatcherKey, channelKey), "true", null, user1.getUuid(), user1.getLogin(), null, null); @@ -411,10 +411,10 @@ class PropertiesDaoIT { UserDto user3 = db.users().insertUser(withEmail("user3")); UserDto user4 = db.users().insertUser(noEmail("user4")); Set allLogins = of("user1", "user2", "user3"); - String projectKey = randomAlphabetic(3); + String projectKey = secure().nextAlphabetic(3); ProjectDto project = insertPrivateProject(projectKey); - String dispatcherKey = randomAlphabetic(4); - String channelKey = randomAlphabetic(5); + String dispatcherKey = secure().nextAlphabetic(4); + String channelKey = secure().nextAlphabetic(5); // user1 and user2 subscribed on project and globally insertProperty(propertyKeyOf(dispatcherKey, channelKey), "true", null, user1.getUuid(), user1.getLogin(), null, null); diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/purge/PurgeCommandsIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/purge/PurgeCommandsIT.java index 0653bb15b9d..b250f707397 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/purge/PurgeCommandsIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/purge/PurgeCommandsIT.java @@ -69,7 +69,7 @@ import static com.google.common.collect.Lists.newArrayList; import static java.util.Arrays.asList; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.api.Assertions.tuple; @@ -869,7 +869,7 @@ class PurgeCommandsIT { dbTester.getDbClient().duplicationDao().insert(dbTester.getSession(), new DuplicationUnitDto() .setAnalysisUuid(analysis.getUuid()) .setComponentUuid(project.uuid()) - .setHash(randomAlphabetic(12)) + .setHash(secure().nextAlphabetic(12)) .setIndexInFile(random.nextInt(10)) .setStartLine(random.nextInt(10)) .setEndLine(random.nextInt(10))); @@ -899,10 +899,10 @@ class PurgeCommandsIT { "EVENT_UUID", newUuid(), "EVENT_COMPONENT_UUID", componentUuid, "EVENT_ANALYSIS_UUID", analysisUuid, - "CHANGE_CATEGORY", randomAlphabetic(12), + "CHANGE_CATEGORY", secure().nextAlphabetic(12), "COMPONENT_UUID", newUuid(), - "COMPONENT_KEY", randomAlphabetic(9), - "COMPONENT_NAME", randomAlphabetic(10), + "COMPONENT_KEY", secure().nextAlphabetic(9), + "COMPONENT_NAME", secure().nextAlphabetic(10), "CREATED_AT", 1L); } @@ -936,8 +936,8 @@ class PurgeCommandsIT { "ANALYSIS_PROPERTIES", "UUID", newUuid(), "ANALYSIS_UUID", analysis1.getUuid(), - "KEE", randomAlphabetic(10), - "TEXT_VALUE", isEmpty ? null : randomAlphabetic(50), + "KEE", secure().nextAlphabetic(10), + "TEXT_VALUE", isEmpty ? null : secure().nextAlphabetic(50), "IS_EMPTY", isEmpty, "CREATED_AT", 1L); } @@ -947,9 +947,9 @@ class PurgeCommandsIT { dbTester.executeInsert( "PROPERTIES", "UUID", newUuid(), - "PROP_KEY", randomAlphabetic(10), + "PROP_KEY", secure().nextAlphabetic(10), "ENTITY_UUID", component.uuid(), - "TEXT_VALUE", randomAlphabetic(10), + "TEXT_VALUE", secure().nextAlphabetic(10), "IS_EMPTY", isEmpty, "CREATED_AT", 1L); } diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/purge/PurgeDaoIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/purge/PurgeDaoIT.java index 594a941b51d..506c3dfe4ee 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/purge/PurgeDaoIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/purge/PurgeDaoIT.java @@ -99,7 +99,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static java.time.ZoneOffset.UTC; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; @@ -2008,16 +2008,16 @@ oldCreationDate)); private void insertPropertyFor(ComponentDto... components) { Stream.of(components).forEach(componentDto -> db.properties().insertProperty(new PropertyDto() - .setKey(randomAlphabetic(3)) - .setValue(randomAlphabetic(3)) + .setKey(secure().nextAlphabetic(3)) + .setValue(secure().nextAlphabetic(3)) .setEntityUuid(componentDto.uuid()), componentDto.getKey(), componentDto.name(), componentDto.qualifier(), null)); } private void insertPropertyFor(ProjectDto project) { db.properties().insertProperty(new PropertyDto() - .setKey(randomAlphabetic(3)) - .setValue(randomAlphabetic(3)) + .setKey(secure().nextAlphabetic(3)) + .setValue(secure().nextAlphabetic(3)) .setEntityUuid(project.getUuid()), null, project.getKey(), null, null); } @@ -2029,9 +2029,9 @@ oldCreationDate)); private void insertProjectMeasureFor(ComponentDto... components) { Arrays.stream(components).forEach(componentDto -> db.getDbClient().projectMeasureDao().insert(dbSession, new ProjectMeasureDto() - .setMetricUuid(randomAlphabetic(3)) + .setMetricUuid(secure().nextAlphabetic(3)) .setComponentUuid(componentDto.uuid()) - .setAnalysisUuid(randomAlphabetic(3)))); + .setAnalysisUuid(secure().nextAlphabetic(3)))); dbSession.commit(); } diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/qualitygate/QualityGateConditionDaoIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/qualitygate/QualityGateConditionDaoIT.java index f085811598f..51e53b2c6d9 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/qualitygate/QualityGateConditionDaoIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/qualitygate/QualityGateConditionDaoIT.java @@ -31,7 +31,7 @@ import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.metric.MetricDto; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.tuple; @@ -166,11 +166,11 @@ class QualityGateConditionDaoIT { } private QualityGateConditionDto insertQGCondition(String qualityGateUuid) { - return insertQGCondition(qualityGateUuid, randomAlphabetic(2)); + return insertQGCondition(qualityGateUuid, secure().nextAlphabetic(2)); } private QualityGateConditionDto insertQGCondition(String qualityGateUuid, String metricUuid) { - return insertQGCondition(qualityGateUuid, metricUuid, randomAlphabetic(2), randomAlphabetic(3)); + return insertQGCondition(qualityGateUuid, metricUuid, secure().nextAlphabetic(2), secure().nextAlphabetic(3)); } private QualityGateConditionDto insertQGCondition(String qualityGateUuid, String metricUuid, String operator, String threshold) { diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/qualitygate/QualityGateGroupPermissionsDaoIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/qualitygate/QualityGateGroupPermissionsDaoIT.java index ad21b9f43eb..e0a7e898fda 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/qualitygate/QualityGateGroupPermissionsDaoIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/qualitygate/QualityGateGroupPermissionsDaoIT.java @@ -35,7 +35,7 @@ import org.sonar.db.user.GroupDto; import org.sonar.db.user.GroupTesting; import org.sonar.db.user.SearchGroupMembershipDto; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.eq; @@ -94,7 +94,7 @@ class QualityGateGroupPermissionsDaoIT { @Test void existsReturnsFalseWhenQGEditGroupsDoesNotExist() { - assertThat(underTest.exists(dbSession, randomAlphabetic(5), randomAlphabetic(5))).isFalse(); + assertThat(underTest.exists(dbSession, secure().nextAlphabetic(5), secure().nextAlphabetic(5))).isFalse(); } @Test @@ -301,8 +301,8 @@ class QualityGateGroupPermissionsDaoIT { private QualityGateDto insertQualityGate() { QualityGateDto qg = new QualityGateDto() - .setUuid(randomAlphabetic(5)) - .setName(randomAlphabetic(5)); + .setUuid(secure().nextAlphabetic(5)) + .setName(secure().nextAlphabetic(5)); dbTester.getDbClient().qualityGateDao().insert(dbTester.getSession(), qg); dbTester.commit(); return qg; diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/qualityprofile/QualityProfileDaoIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/qualityprofile/QualityProfileDaoIT.java index a99c13ffdad..0125835906b 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/qualityprofile/QualityProfileDaoIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/qualityprofile/QualityProfileDaoIT.java @@ -45,7 +45,7 @@ import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; @@ -220,8 +220,8 @@ class QualityProfileDaoIT { private RulesProfileDto insertRulesProfile() { RulesProfileDto dto = new RulesProfileDto() - .setName(randomAlphanumeric(10)) - .setLanguage(randomAlphanumeric(3)) + .setName(secure().nextAlphanumeric(10)) + .setLanguage(secure().nextAlphanumeric(3)) .setUuid(Uuids.createFast()) .setIsBuiltIn(false); db.getDbClient().qualityProfileDao().insert(dbSession, dto); diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/rule/RuleDaoIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/rule/RuleDaoIT.java index fcf19a2ed78..cf38d2f4b94 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/rule/RuleDaoIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/rule/RuleDaoIT.java @@ -58,7 +58,7 @@ import static com.google.common.collect.Sets.newHashSet; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; @@ -684,9 +684,9 @@ class RuleDaoIT { RuleDto rule = db.rules().insert(); RuleDescriptionSectionDto existingSection = rule.getRuleDescriptionSectionDtos().iterator().next(); RuleDescriptionSectionDto newSection = RuleDescriptionSectionDto.builder() - .uuid(randomAlphanumeric(20)) + .uuid(secure().nextAlphanumeric(20)) .key("new_key") - .content(randomAlphanumeric(1000)) + .content(secure().nextAlphanumeric(1000)) .build(); rule.addRuleDescriptionSectionDto(newSection); @@ -707,9 +707,9 @@ class RuleDaoIT { Set ruleDescriptionSectionDtos = rule.getRuleDescriptionSectionDtos(); RuleDescriptionSectionDto existingSection = ruleDescriptionSectionDtos.iterator().next(); RuleDescriptionSectionDto replacingSection = RuleDescriptionSectionDto.builder() - .uuid(randomAlphanumeric(20)) + .uuid(secure().nextAlphanumeric(20)) .key(existingSection.getKey()) - .content(randomAlphanumeric(1000)) + .content(secure().nextAlphanumeric(1000)) .build(); rule.replaceRuleDescriptionSectionDtos(List.of(replacingSection)); @@ -727,11 +727,11 @@ class RuleDaoIT { RuleDto rule = db.rules().insert(); Set ruleDescriptionSectionDtos = rule.getRuleDescriptionSectionDtos(); RuleDescriptionSectionDto existingSection = ruleDescriptionSectionDtos.iterator().next(); - RuleDescriptionSectionContextDto contextDto = RuleDescriptionSectionContextDto.of(randomAlphanumeric(10), randomAlphanumeric(10)); + RuleDescriptionSectionContextDto contextDto = RuleDescriptionSectionContextDto.of(secure().nextAlphanumeric(10), secure().nextAlphanumeric(10)); RuleDescriptionSectionDto replacingSection = RuleDescriptionSectionDto.builder() - .uuid(randomAlphanumeric(20)) + .uuid(secure().nextAlphanumeric(20)) .key(existingSection.getKey()) - .content(randomAlphanumeric(1000)) + .content(secure().nextAlphanumeric(1000)) .context(contextDto) .build(); @@ -1290,8 +1290,8 @@ class RuleDaoIT { @Test void insertDeprecatedRuleKey_with_same_RuleKey_should_fail() { - String repositoryKey = randomAlphanumeric(50); - String ruleKey = randomAlphanumeric(50); + String repositoryKey = secure().nextAlphanumeric(50); + String ruleKey = secure().nextAlphanumeric(50); RuleDbTester ruleTester = db.rules(); ruleTester.insertDeprecatedKey(d -> d.setOldRepositoryKey(repositoryKey) .setOldRuleKey(ruleKey)); @@ -1374,7 +1374,7 @@ class RuleDaoIT { private static RuleDescriptionSectionDto createDefaultRuleDescriptionSection() { return RuleDescriptionSectionDto.createDefaultRuleDescriptionSection(UuidFactoryFast.getInstance().create(), - RandomStringUtils.randomAlphanumeric(1000)); + RandomStringUtils.secure().nextAlphanumeric(1000)); } private static class Accumulator implements Consumer { diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/scim/ScimUserDaoIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/scim/ScimUserDaoIT.java index 71e0d3a0b6a..804fcce8d14 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/scim/ScimUserDaoIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/scim/ScimUserDaoIT.java @@ -39,7 +39,7 @@ import org.sonar.db.Pagination; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.AssertionsForClassTypes.tuple; @@ -360,7 +360,7 @@ class ScimUserDaoIT { @Test void deleteFromUserUuid_shouldNotFail_whenNoUser() { - assertThatCode(() -> scimUserDao.deleteByUserUuid(dbSession, randomAlphanumeric(6))).doesNotThrowAnyException(); + assertThatCode(() -> scimUserDao.deleteByUserUuid(dbSession, secure().nextAlphanumeric(6))).doesNotThrowAnyException(); } private List insertScimUsersWithUsers(List userLogins) { @@ -377,7 +377,7 @@ class ScimUserDaoIT { } private ScimUserTestData insertScimUser(String scimUserUuid) { - return insertScimUser(scimUserUuid, randomAlphanumeric(40)); + return insertScimUser(scimUserUuid, secure().nextAlphanumeric(40)); } private ScimUserTestData insertScimUser(String scimUserUuid, String userUuid) { diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/user/UserDaoIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/user/UserDaoIT.java index 97c15d618ac..cf2eaa9cd1e 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/user/UserDaoIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/user/UserDaoIT.java @@ -49,7 +49,7 @@ import static java.util.Collections.emptySet; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toMap; import static java.util.stream.Collectors.toSet; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.groups.Tuple.tuple; @@ -843,7 +843,7 @@ class UserDaoIT { } private UserGroupDto insertUserGroup(UserDto user) { - GroupDto group = newGroupDto().setName(randomAlphanumeric(30)); + GroupDto group = newGroupDto().setName(secure().nextAlphanumeric(30)); dbClient.groupDao().insert(session, group); UserGroupDto dto = new UserGroupDto().setUserUuid(user.getUuid()).setGroupUuid(group.getUuid()); diff --git a/server/sonar-db-dao/src/it/java/org/sonar/db/user/UserDaoWithPersisterIT.java b/server/sonar-db-dao/src/it/java/org/sonar/db/user/UserDaoWithPersisterIT.java index 3977de53ad3..03afbd71804 100644 --- a/server/sonar-db-dao/src/it/java/org/sonar/db/user/UserDaoWithPersisterIT.java +++ b/server/sonar-db-dao/src/it/java/org/sonar/db/user/UserDaoWithPersisterIT.java @@ -30,7 +30,7 @@ import org.sonar.db.DbTester; import org.sonar.db.audit.AuditPersister; import org.sonar.db.audit.model.UserNewValue; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -160,7 +160,7 @@ class UserDaoWithPersisterIT { } private UserGroupDto insertUserGroup(UserDto user) { - GroupDto group = newGroupDto().setName(randomAlphanumeric(30)); + GroupDto group = newGroupDto().setName(secure().nextAlphanumeric(30)); dbClient.groupDao().insert(db.getSession(), group); UserGroupDto dto = new UserGroupDto().setUserUuid(user.getUuid()).setGroupUuid(group.getUuid()); diff --git a/server/sonar-db-dao/src/main/java/org/sonar/db/issue/IssueTesting.java b/server/sonar-db-dao/src/main/java/org/sonar/db/issue/IssueTesting.java index c527cebd03e..76e6a7b551c 100644 --- a/server/sonar-db-dao/src/main/java/org/sonar/db/issue/IssueTesting.java +++ b/server/sonar-db-dao/src/main/java/org/sonar/db/issue/IssueTesting.java @@ -37,8 +37,7 @@ import org.sonar.db.rule.RuleDto; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.Sets.newHashSet; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; public class IssueTesting { @@ -73,14 +72,14 @@ public class IssueTesting { //TODO map to correct impact. Will be fixed with persistence of impacts on issues .addImpact(new ImpactDto().setSoftwareQuality(SoftwareQuality.MAINTAINABILITY).setSeverity(org.sonar.api.issue.impact.Severity.HIGH)) .setEffort((long) RANDOM.nextInt(10)) - .setAssigneeUuid("assignee-uuid_" + randomAlphabetic(26)) - .setAuthorLogin("author_" + randomAlphabetic(5)) + .setAssigneeUuid("assignee-uuid_" + secure().nextAlphabetic(26)) + .setAuthorLogin("author_" + secure().nextAlphabetic(5)) // Starting from 1 in order to never get 0 (as it's a forbidden value) .setLine(RANDOM.nextInt(1, 1_001)) - .setMessage("message_" + randomAlphabetic(5)) - .setChecksum("checksum_" + randomAlphabetic(5)) - .setTags(newHashSet("tag_" + randomAlphanumeric(5), "tag_" + randomAlphanumeric(5))) - .setRuleDescriptionContextKey("context_" + randomAlphabetic(5)) + .setMessage("message_" + secure().nextAlphabetic(5)) + .setChecksum("checksum_" + secure().nextAlphabetic(5)) + .setTags(newHashSet("tag_" + secure().nextAlphanumeric(5), "tag_" + secure().nextAlphanumeric(5))) + .setRuleDescriptionContextKey("context_" + secure().nextAlphabetic(5)) .setIssueCreationDate(new Date(System.currentTimeMillis() - 2_000)) .setIssueUpdateDate(new Date(System.currentTimeMillis() - 1_500)) .setCreatedAt(System.currentTimeMillis() - 1_000) @@ -92,9 +91,9 @@ public class IssueTesting { .setUuid(UuidFactoryFast.getInstance().create()) .setKey(UuidFactoryFast.getInstance().create()) .setIssueKey(issue.getKey()) - .setChangeData("data_" + randomAlphanumeric(40)) + .setChangeData("data_" + secure().nextAlphanumeric(40)) .setChangeType(IssueChangeDto.TYPE_FIELD_CHANGE) - .setUserUuid("userUuid_" + randomAlphanumeric(40)) + .setUserUuid("userUuid_" + secure().nextAlphanumeric(40)) .setProjectUuid(issue.getProjectUuid()) .setIssueChangeCreationDate(RANDOM.nextLong(Long.MAX_VALUE)) .setCreatedAt(RANDOM.nextLong(Long.MAX_VALUE)) diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/DBSessionsImplTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/DBSessionsImplTest.java index 28a7df9aa5b..6a42b7b2b93 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/DBSessionsImplTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/DBSessionsImplTest.java @@ -41,7 +41,7 @@ import org.slf4j.event.Level; import org.sonar.api.testfixtures.log.LogTesterJUnit5; import static java.lang.Math.abs; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.mock; @@ -203,30 +203,30 @@ class DBSessionsImplTest { }); verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> { - String str = randomAlphabetic(10); + String str = secure().nextAlphabetic(10); dbSession.selectOne(str); verify(myBatisDbSession).selectOne(str); }); verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> { - String str = randomAlphabetic(10); + String str = secure().nextAlphabetic(10); Object object = new Object(); dbSession.selectOne(str, object); verify(myBatisDbSession).selectOne(str, object); }); verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> { - String str = randomAlphabetic(10); + String str = secure().nextAlphabetic(10); dbSession.selectList(str); verify(myBatisDbSession).selectList(str); }); verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> { - String str = randomAlphabetic(10); + String str = secure().nextAlphabetic(10); Object object = new Object(); dbSession.selectList(str, object); verify(myBatisDbSession).selectList(str, object); }); verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> { - String str = randomAlphabetic(10); + String str = secure().nextAlphabetic(10); Object parameter = new Object(); RowBounds rowBounds = new RowBounds(); dbSession.selectList(str, parameter, rowBounds); @@ -234,42 +234,42 @@ class DBSessionsImplTest { }); verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> { - String str = randomAlphabetic(10); - String mapKey = randomAlphabetic(10); + String str = secure().nextAlphabetic(10); + String mapKey = secure().nextAlphabetic(10); dbSession.selectMap(str, mapKey); verify(myBatisDbSession).selectMap(str, mapKey); }); verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> { - String str = randomAlphabetic(10); + String str = secure().nextAlphabetic(10); Object parameter = new Object(); - String mapKey = randomAlphabetic(10); + String mapKey = secure().nextAlphabetic(10); dbSession.selectMap(str, parameter, mapKey); verify(myBatisDbSession).selectMap(str, parameter, mapKey); }); verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> { - String str = randomAlphabetic(10); + String str = secure().nextAlphabetic(10); Object parameter = new Object(); - String mapKey = randomAlphabetic(10); + String mapKey = secure().nextAlphabetic(10); RowBounds rowBounds = new RowBounds(); dbSession.selectMap(str, parameter, mapKey, rowBounds); verify(myBatisDbSession).selectMap(str, parameter, mapKey, rowBounds); }); verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> { - String str = randomAlphabetic(10); + String str = secure().nextAlphabetic(10); ResultHandler handler = mock(ResultHandler.class); dbSession.select(str, handler); verify(myBatisDbSession).select(str, handler); }); verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> { - String str = randomAlphabetic(10); + String str = secure().nextAlphabetic(10); Object parameter = new Object(); ResultHandler handler = mock(ResultHandler.class); dbSession.select(str, parameter, handler); verify(myBatisDbSession).select(str, parameter, handler); }); verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> { - String str = randomAlphabetic(10); + String str = secure().nextAlphabetic(10); Object parameter = new Object(); ResultHandler handler = mock(ResultHandler.class); RowBounds rowBounds = new RowBounds(); @@ -278,36 +278,36 @@ class DBSessionsImplTest { }); verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> { - String str = randomAlphabetic(10); + String str = secure().nextAlphabetic(10); dbSession.insert(str); verify(myBatisDbSession).insert(str); }); verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> { - String str = randomAlphabetic(10); + String str = secure().nextAlphabetic(10); Object object = new Object(); dbSession.insert(str, object); verify(myBatisDbSession).insert(str, object); }); verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> { - String str = randomAlphabetic(10); + String str = secure().nextAlphabetic(10); dbSession.update(str); verify(myBatisDbSession).update(str); }); verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> { - String str = randomAlphabetic(10); + String str = secure().nextAlphabetic(10); Object object = new Object(); dbSession.update(str, object); verify(myBatisDbSession).update(str, object); }); verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> { - String str = randomAlphabetic(10); + String str = secure().nextAlphabetic(10); dbSession.delete(str); verify(myBatisDbSession).delete(str); }); verifyDelegation(batchOrRegular, (myBatisDbSession, dbSession) -> { - String str = randomAlphabetic(10); + String str = secure().nextAlphabetic(10); Object object = new Object(); dbSession.delete(str, object); verify(myBatisDbSession).delete(str, object); @@ -409,12 +409,12 @@ class DBSessionsImplTest { } private static DbSessionCaller[] DIRTYING_CALLS = { - session -> session.insert(randomAlphabetic(3)), - session -> session.insert(randomAlphabetic(2), new Object()), - session -> session.update(randomAlphabetic(3)), - session -> session.update(randomAlphabetic(3), new Object()), - session -> session.delete(randomAlphabetic(3)), - session -> session.delete(randomAlphabetic(3), new Object()), + session -> session.insert(secure().nextAlphabetic(3)), + session -> session.insert(secure().nextAlphabetic(2), new Object()), + session -> session.update(secure().nextAlphabetic(3)), + session -> session.update(secure().nextAlphabetic(3), new Object()), + session -> session.delete(secure().nextAlphabetic(3)), + session -> session.delete(secure().nextAlphabetic(3), new Object()), }; private static DbSessionCaller[] COMMIT_CALLS = { @@ -428,17 +428,17 @@ class DBSessionsImplTest { }; private static DbSessionCaller[] NEUTRAL_CALLS = { - session -> session.selectOne(randomAlphabetic(3)), - session -> session.selectOne(randomAlphabetic(3), new Object()), - session -> session.select(randomAlphabetic(3), mock(ResultHandler.class)), - session -> session.select(randomAlphabetic(3), new Object(), mock(ResultHandler.class)), - session -> session.select(randomAlphabetic(3), new Object(), new RowBounds(), mock(ResultHandler.class)), - session -> session.selectList(randomAlphabetic(3)), - session -> session.selectList(randomAlphabetic(3), new Object()), - session -> session.selectList(randomAlphabetic(3), new Object(), new RowBounds()), - session -> session.selectMap(randomAlphabetic(3), randomAlphabetic(3)), - session -> session.selectMap(randomAlphabetic(3), new Object(), randomAlphabetic(3)), - session -> session.selectMap(randomAlphabetic(3), new Object(), randomAlphabetic(3), new RowBounds()), + session -> session.selectOne(secure().nextAlphabetic(3)), + session -> session.selectOne(secure().nextAlphabetic(3), new Object()), + session -> session.select(secure().nextAlphabetic(3), mock(ResultHandler.class)), + session -> session.select(secure().nextAlphabetic(3), new Object(), mock(ResultHandler.class)), + session -> session.select(secure().nextAlphabetic(3), new Object(), new RowBounds(), mock(ResultHandler.class)), + session -> session.selectList(secure().nextAlphabetic(3)), + session -> session.selectList(secure().nextAlphabetic(3), new Object()), + session -> session.selectList(secure().nextAlphabetic(3), new Object(), new RowBounds()), + session -> session.selectMap(secure().nextAlphabetic(3), secure().nextAlphabetic(3)), + session -> session.selectMap(secure().nextAlphabetic(3), new Object(), secure().nextAlphabetic(3)), + session -> session.selectMap(secure().nextAlphabetic(3), new Object(), secure().nextAlphabetic(3), new RowBounds()), session -> session.getMapper(Object.class), session -> session.getConfiguration(), session -> session.getConnection(), diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/DbSessionImplTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/DbSessionImplTest.java index 63080cc63c6..ce8a0871b09 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/DbSessionImplTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/DbSessionImplTest.java @@ -34,7 +34,7 @@ import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.SqlSession; import org.junit.jupiter.api.Test; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; @@ -52,14 +52,14 @@ class DbSessionImplTest { Random random = new Random(); boolean randomBoolean = random.nextBoolean(); int randomInt = random.nextInt(200); - String randomStatement = randomAlphabetic(10); + String randomStatement = secure().nextAlphabetic(10); Object randomParameter = new Object(); Cursor mockCursor = mock(Cursor.class); RowBounds rowBounds = new RowBounds(); Object randomObject = new Object(); List randomList = new ArrayList<>(); Map randomMap = new HashMap<>(); - String randomMapKey = randomAlphabetic(10); + String randomMapKey = secure().nextAlphabetic(10); ResultHandler randomResultHandler = resultContext -> { // don't care }; diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeActivityDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeActivityDtoTest.java index bb6ee8a1bc7..6724092155d 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeActivityDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeActivityDtoTest.java @@ -24,27 +24,26 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.api.Assertions.assertThatThrownBy; class CeActivityDtoTest { private static final String STR_40_CHARS = "0123456789012345678901234567890123456789"; - private static final String STR_100_CHARS = randomAlphabetic(100); + private static final String STR_100_CHARS = secure().nextAlphabetic(100); private final CeActivityDto underTest = new CeActivityDto(); @Test void constructor_from_CeQueueDto_populates_fields() { long now = new Random().nextLong(); CeQueueDto ceQueueDto = new CeQueueDto() - .setUuid(randomAlphanumeric(10)) - .setTaskType(randomAlphanumeric(11)) - .setComponentUuid(randomAlphanumeric(12)) - .setEntityUuid(randomAlphanumeric(13)) - .setSubmitterUuid(randomAlphanumeric(14)) - .setWorkerUuid(randomAlphanumeric(15)) + .setUuid(secure().nextAlphanumeric(10)) + .setTaskType(secure().nextAlphanumeric(11)) + .setComponentUuid(secure().nextAlphanumeric(12)) + .setEntityUuid(secure().nextAlphanumeric(13)) + .setSubmitterUuid(secure().nextAlphanumeric(14)) + .setWorkerUuid(secure().nextAlphanumeric(15)) .setCreatedAt(now + 9_999) .setStartedAt(now + 865); @@ -132,9 +131,9 @@ class CeActivityDtoTest { @Test void setErrorMessage_truncates_to_1000_after_removing_char_zero() { - String before = randomAlphanumeric(50); - String after = randomAlphanumeric(950); - String truncated = randomAlphanumeric(1 + new Random().nextInt(50)); + String before = secure().nextAlphanumeric(50); + String after = secure().nextAlphanumeric(950); + String truncated = secure().nextAlphanumeric(1 + new Random().nextInt(50)); underTest.setErrorMessage(before + "\u0000" + after + truncated); assertThat(underTest.getErrorMessage()).isEqualTo(before + after); diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/UpdateIfTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/UpdateIfTest.java index 26eeec51bca..ce3ab177108 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/UpdateIfTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/UpdateIfTest.java @@ -48,7 +48,7 @@ class UpdateIfTest { @Test void newProperties_constructor_fails_with_IAE_if_workerUuid_is_41_or_more() { - String workerUuid = RandomStringUtils.randomAlphanumeric(41 + new Random().nextInt(5)); + String workerUuid = RandomStringUtils.secure().nextAlphanumeric(41 + new Random().nextInt(5)); assertThatThrownBy(() -> new UpdateIf.NewProperties(CeQueueDto.Status.PENDING, workerUuid, 123, 456)) .isInstanceOf(IllegalArgumentException.class) diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/component/AnalysisPropertyDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/component/AnalysisPropertyDtoTest.java index 2b6c722ddd9..762bc5ad468 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/component/AnalysisPropertyDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/component/AnalysisPropertyDtoTest.java @@ -21,7 +21,7 @@ package org.sonar.db.component; import org.junit.jupiter.api.Test; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -68,10 +68,10 @@ class AnalysisPropertyDtoTest { @Test void test_equality() { underTest = new AnalysisPropertyDto() - .setUuid(randomAlphanumeric(40)) - .setAnalysisUuid(randomAlphanumeric(40)) - .setKey(randomAlphanumeric(512)) - .setValue(randomAlphanumeric(10000)); + .setUuid(secure().nextAlphanumeric(40)) + .setAnalysisUuid(secure().nextAlphanumeric(40)) + .setKey(secure().nextAlphanumeric(512)) + .setValue(secure().nextAlphanumeric(10000)); assertThat(underTest) .isEqualTo( @@ -109,10 +109,10 @@ class AnalysisPropertyDtoTest { @Test void test_hashcode() { underTest = new AnalysisPropertyDto() - .setUuid(randomAlphanumeric(40)) - .setAnalysisUuid(randomAlphanumeric(40)) - .setKey(randomAlphanumeric(512)) - .setValue(randomAlphanumeric(10000)); + .setUuid(secure().nextAlphanumeric(40)) + .setAnalysisUuid(secure().nextAlphanumeric(40)) + .setKey(secure().nextAlphanumeric(512)) + .setValue(secure().nextAlphanumeric(10000)); assertThat(underTest.hashCode()).isEqualTo( new AnalysisPropertyDto() diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ScrapAnalysisPropertyDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/component/ScrapAnalysisPropertyDtoTest.java index c868dca9097..0bb11026f18 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ScrapAnalysisPropertyDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/component/ScrapAnalysisPropertyDtoTest.java @@ -23,7 +23,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; class ScrapAnalysisPropertyDtoTest { @@ -40,7 +40,7 @@ class ScrapAnalysisPropertyDtoTest { @ValueSource(ints = {1, 2000, 4000}) void test_text_set(int value) { ScrapAnalysisPropertyDto underTest = new ScrapAnalysisPropertyDto(); - String text = randomAlphanumeric(value); + String text = secure().nextAlphanumeric(value); underTest.setTextValue(text); assertThat(underTest.getValue()).isEqualTo(text); @@ -50,7 +50,7 @@ class ScrapAnalysisPropertyDtoTest { @ValueSource(ints = {1, 2000, 4000}) void test_clob_set(int value) { ScrapAnalysisPropertyDto underTest = new ScrapAnalysisPropertyDto(); - String text = randomAlphanumeric(4000 + value); + String text = secure().nextAlphanumeric(4000 + value); underTest.setClobValue(text); assertThat(underTest.getValue()).isEqualTo(text); diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDtoTest.java index 5d5fdf89a43..c141ab39f9e 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDtoTest.java @@ -31,7 +31,7 @@ import org.sonar.api.rules.RuleType; import org.sonar.core.util.Uuids; import org.sonar.db.issue.ImpactDto; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.apache.commons.lang3.StringUtils.repeat; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -156,8 +156,8 @@ class RuleDtoTest { @Test void addRuleDescriptionSectionDto_whenSameSectionAndContext_shouldThrowError() { RuleDto dto = new RuleDto(); - String contextKey = randomAlphanumeric(50); - String displayName = randomAlphanumeric(50); + String contextKey = secure().nextAlphanumeric(50); + String displayName = secure().nextAlphanumeric(50); RuleDescriptionSectionDto section1 = createSection(SECTION_KEY, contextKey, displayName); dto.addRuleDescriptionSectionDto(section1); RuleDescriptionSectionDto section2 = createSection(SECTION_KEY, contextKey, displayName); diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/scim/ScimGroupDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/scim/ScimGroupDaoTest.java index 3fd4797c6a4..58f0907d9bb 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/scim/ScimGroupDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/scim/ScimGroupDaoTest.java @@ -33,7 +33,7 @@ import org.sonar.db.OffsetBasedPagination; import org.sonar.db.Pagination; import org.sonar.db.user.GroupDto; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Fail.fail; @@ -249,7 +249,7 @@ class ScimGroupDaoTest { @Test void deleteFromGroupUuid_shouldNotFail_whenNoGroup() { - assertThatCode(() -> scimGroupDao.deleteByGroupUuid(db.getSession(), randomAlphanumeric(6))).doesNotThrowAnyException(); + assertThatCode(() -> scimGroupDao.deleteByGroupUuid(db.getSession(), secure().nextAlphanumeric(6))).doesNotThrowAnyException(); } diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTokenDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTokenDtoTest.java index 5a7482f59a0..2a607c580fc 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTokenDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTokenDtoTest.java @@ -23,7 +23,7 @@ import java.time.ZoneId; import java.time.ZonedDateTime; import org.junit.jupiter.api.Test; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -31,7 +31,7 @@ class UserTokenDtoTest { @Test void fail_if_token_hash_is_longer_than_255_characters() { - assertThatThrownBy(() -> new UserTokenDto().setTokenHash(randomAlphabetic(256))) + assertThatThrownBy(() -> new UserTokenDto().setTokenHash(secure().nextAlphabetic(256))) .isInstanceOf(IllegalStateException.class) .hasMessage("Token hash length (256) is longer than the maximum authorized (255)"); } diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/alm/integration/pat/AlmPatsTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/alm/integration/pat/AlmPatsTesting.java index ed2433ccb86..bfc29516fe0 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/alm/integration/pat/AlmPatsTesting.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/alm/integration/pat/AlmPatsTesting.java @@ -21,15 +21,15 @@ package org.sonar.db.alm.integration.pat; import org.sonar.db.alm.pat.AlmPatDto; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; public class AlmPatsTesting { public static AlmPatDto newAlmPatDto() { AlmPatDto almPatDto = new AlmPatDto(); - almPatDto.setAlmSettingUuid(randomAlphanumeric(40)); - almPatDto.setPersonalAccessToken(randomAlphanumeric(2000)); - almPatDto.setUserUuid(randomAlphanumeric(40)); + almPatDto.setAlmSettingUuid(secure().nextAlphanumeric(40)); + almPatDto.setPersonalAccessToken(secure().nextAlphanumeric(2000)); + almPatDto.setUserUuid(secure().nextAlphanumeric(40)); return almPatDto; } diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/almsettings/AlmSettingsTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/almsettings/AlmSettingsTesting.java index d5cbfe94322..b15a23bca7d 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/almsettings/AlmSettingsTesting.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/almsettings/AlmSettingsTesting.java @@ -24,8 +24,8 @@ import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.db.alm.setting.ProjectAlmSettingDto; import org.sonar.db.project.ProjectDto; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; -import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; + public class AlmSettingsTesting { @@ -35,45 +35,45 @@ public class AlmSettingsTesting { public static AlmSettingDto newGithubAlmSettingDto() { return new AlmSettingDto() - .setKey(randomAlphanumeric(200)) - .setUrl(randomAlphanumeric(2000)) - .setAppId(randomNumeric(8)) - .setClientId(randomNumeric(8)) - .setClientSecret(randomAlphanumeric(80)) - .setPrivateKey(randomAlphanumeric(2000)) + .setKey(secure().nextAlphanumeric(200)) + .setUrl(secure().nextAlphanumeric(2000)) + .setAppId(secure().nextNumeric(8)) + .setClientId(secure().nextNumeric(8)) + .setClientSecret(secure().nextAlphanumeric(80)) + .setPrivateKey(secure().nextAlphanumeric(2000)) .setAlm(ALM.GITHUB); } public static AlmSettingDto newAzureAlmSettingDto() { return new AlmSettingDto() - .setKey(randomAlphanumeric(200)) - .setPersonalAccessToken(randomAlphanumeric(2000)) - .setUrl(randomAlphanumeric(2000)) + .setKey(secure().nextAlphanumeric(200)) + .setPersonalAccessToken(secure().nextAlphanumeric(2000)) + .setUrl(secure().nextAlphanumeric(2000)) .setAlm(ALM.AZURE_DEVOPS); } public static AlmSettingDto newGitlabAlmSettingDto() { return new AlmSettingDto() - .setKey(randomAlphanumeric(200)) - .setPersonalAccessToken(randomAlphanumeric(2000)) - .setUrl(randomAlphanumeric(2000)) + .setKey(secure().nextAlphanumeric(200)) + .setPersonalAccessToken(secure().nextAlphanumeric(2000)) + .setUrl(secure().nextAlphanumeric(2000)) .setAlm(ALM.GITLAB); } public static AlmSettingDto newBitbucketAlmSettingDto() { return new AlmSettingDto() - .setKey(randomAlphanumeric(200)) - .setUrl(randomAlphanumeric(2000)) - .setPersonalAccessToken(randomAlphanumeric(2000)) + .setKey(secure().nextAlphanumeric(200)) + .setUrl(secure().nextAlphanumeric(2000)) + .setPersonalAccessToken(secure().nextAlphanumeric(2000)) .setAlm(ALM.BITBUCKET); } public static AlmSettingDto newBitbucketCloudAlmSettingDto() { return new AlmSettingDto() - .setKey(randomAlphanumeric(200)) - .setClientId(randomAlphanumeric(50)) - .setAppId(randomAlphanumeric(80)) - .setClientSecret(randomAlphanumeric(50)) + .setKey(secure().nextAlphanumeric(200)) + .setClientId(secure().nextAlphanumeric(50)) + .setAppId(secure().nextAlphanumeric(80)) + .setClientSecret(secure().nextAlphanumeric(50)) .setAlm(ALM.BITBUCKET_CLOUD); } @@ -85,7 +85,7 @@ public class AlmSettingsTesting { return new ProjectAlmSettingDto() .setAlmSettingUuid(githubAlmSetting.getUuid()) .setProjectUuid(project.getUuid()) - .setAlmRepo(randomAlphanumeric(256)) + .setAlmRepo(secure().nextAlphanumeric(256)) .setSummaryCommentEnabled(true) .setMonorepo(monorepo); } @@ -105,8 +105,8 @@ public class AlmSettingsTesting { return new ProjectAlmSettingDto() .setAlmSettingUuid(azureAlmSetting.getUuid()) .setProjectUuid(project.getUuid()) - .setAlmSlug(randomAlphanumeric(256)) - .setAlmRepo(randomAlphanumeric(256)) + .setAlmSlug(secure().nextAlphanumeric(256)) + .setAlmRepo(secure().nextAlphanumeric(256)) .setMonorepo(false); } @@ -114,8 +114,8 @@ public class AlmSettingsTesting { return new ProjectAlmSettingDto() .setAlmSettingUuid(bitbucketAlmSetting.getUuid()) .setProjectUuid(project.getUuid()) - .setAlmRepo(randomAlphanumeric(256)) - .setAlmSlug(randomAlphanumeric(256)) + .setAlmRepo(secure().nextAlphanumeric(256)) + .setAlmSlug(secure().nextAlphanumeric(256)) .setMonorepo(false); } @@ -123,7 +123,7 @@ public class AlmSettingsTesting { return new ProjectAlmSettingDto() .setAlmSettingUuid(bitbucketCloudAlmSetting.getUuid()) .setProjectUuid(project.getUuid()) - .setAlmRepo(randomAlphanumeric(256)) + .setAlmRepo(secure().nextAlphanumeric(256)) .setMonorepo(false); } } diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/anticipatedtransition/AnticipatedTransitionDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/anticipatedtransition/AnticipatedTransitionDbTester.java index 09a41b7d914..06623b270e8 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/anticipatedtransition/AnticipatedTransitionDbTester.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/anticipatedtransition/AnticipatedTransitionDbTester.java @@ -27,7 +27,7 @@ import org.sonar.db.DbTester; import org.sonar.db.issue.AnticipatedTransitionDto; import org.sonar.db.issue.AnticipatedTransitionMapper; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; public class AnticipatedTransitionDbTester { @@ -39,7 +39,7 @@ public class AnticipatedTransitionDbTester { public AnticipatedTransitionDto createForIssue(DefaultIssue issue, String userUuid, String filePath) { var dto = new AnticipatedTransitionDto( - "uuid_" + randomAlphabetic(5), + "uuid_" + secure().nextAlphabetic(5), issue.projectUuid(), userUuid, "wontfix", diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/audit/AuditTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/audit/AuditTesting.java index a1890290811..90df2c359cd 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/audit/AuditTesting.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/audit/AuditTesting.java @@ -22,7 +22,7 @@ package org.sonar.db.audit; import java.security.SecureRandom; import java.util.Random; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; public class AuditTesting { @@ -46,9 +46,9 @@ public class AuditTesting { public static AuditDto newAuditDto(long createdAt, String operation) { AuditDto auditDto = new AuditDto(); - auditDto.setUuid(randomAlphanumeric(40)); - auditDto.setUserUuid(randomAlphanumeric(255)); - auditDto.setUserLogin(randomAlphanumeric(255)); + auditDto.setUuid(secure().nextAlphanumeric(40)); + auditDto.setUserUuid(secure().nextAlphanumeric(255)); + auditDto.setUserLogin(secure().nextAlphanumeric(255)); auditDto.setNewValue("{ \"someKey\": \"someValue\", \"anotherKey\": \"\\\"anotherValue\\\" with quotes \\ \n\t\b\f\r\"}"); auditDto.setOperation(operation); auditDto.setCategory("category"); diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/ce/CeQueueTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/ce/CeQueueTesting.java index 9db889fbe1f..cf59633189f 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/ce/CeQueueTesting.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/ce/CeQueueTesting.java @@ -25,7 +25,7 @@ import java.util.stream.Stream; import org.sonar.db.DbSession; import static com.google.common.base.Preconditions.checkArgument; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.db.ce.CeQueueDto.Status.IN_PROGRESS; import static org.sonar.db.ce.CeQueueDto.Status.PENDING; @@ -41,11 +41,11 @@ public class CeQueueTesting { public static CeQueueDto newCeQueueDto(String uuid) { return new CeQueueDto() .setUuid(uuid) - .setComponentUuid(randomAlphanumeric(40)) - .setEntityUuid(randomAlphanumeric(39)) + .setComponentUuid(secure().nextAlphanumeric(40)) + .setEntityUuid(secure().nextAlphanumeric(39)) .setStatus(CeQueueDto.Status.PENDING) .setTaskType(CeTaskTypes.REPORT) - .setSubmitterUuid(randomAlphanumeric(255)) + .setSubmitterUuid(secure().nextAlphanumeric(255)) .setCreatedAt(RANDOM.nextLong(Long.MAX_VALUE)) .setUpdatedAt(RANDOM.nextLong(Long.MAX_VALUE)); } diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ComponentTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ComponentTesting.java index a0178d92e98..ab716d43767 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ComponentTesting.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ComponentTesting.java @@ -29,7 +29,7 @@ import org.sonar.db.project.CreationMethod; import org.sonar.db.project.ProjectDto; import static com.google.common.base.Preconditions.checkArgument; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME; import static org.sonar.db.component.ComponentDto.UUID_PATH_OF_ROOT; import static org.sonar.db.component.ComponentDto.formatUuidPathFromParent; @@ -226,7 +226,7 @@ public class ComponentTesting { public static BranchDto newBranchDto(@Nullable String projectUuid, BranchType branchType) { - String key = "branch_" + randomAlphanumeric(248); + String key = "branch_" + secure().nextAlphanumeric(248); return new BranchDto() .setKey(key) .setUuid(Uuids.createFast()) @@ -240,7 +240,7 @@ public class ComponentTesting { } public static BranchDto newBranchDto(ComponentDto branchComponent, BranchType branchType, String projectUuid) { - String key = "branch_" + randomAlphanumeric(248); + String key = "branch_" + secure().nextAlphanumeric(248); return new BranchDto() .setKey(key) diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ProjectLinkTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ProjectLinkTesting.java index 3bae295722d..49a10779bff 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ProjectLinkTesting.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/ProjectLinkTesting.java @@ -23,8 +23,7 @@ import java.security.SecureRandom; import java.util.Random; import org.sonar.core.util.Uuids; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; public class ProjectLinkTesting { @@ -37,7 +36,7 @@ public class ProjectLinkTesting { } public static ProjectLinkDto newCustomLinkDto() { - String nameAndType = randomAlphabetic(20); + String nameAndType = secure().nextAlphabetic(20); return newCommonLinkDto() .setName(nameAndType) .setType(nameAndType); @@ -47,7 +46,7 @@ public class ProjectLinkTesting { return new ProjectLinkDto() .setUuid(Uuids.createFast()) .setProjectUuid(Uuids.createFast()) - .setHref(randomAlphanumeric(128)) + .setHref(secure().nextAlphanumeric(128)) .setCreatedAt(System.currentTimeMillis()) .setUpdatedAt(System.currentTimeMillis()); } diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/SnapshotTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/SnapshotTesting.java index 39ad4a518cc..7b8dc9bf2ba 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/SnapshotTesting.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/component/SnapshotTesting.java @@ -21,8 +21,8 @@ package org.sonar.db.component; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; import static org.apache.commons.lang3.RandomStringUtils.randomAscii; +import static org.apache.commons.lang3.RandomStringUtils.secure; public class SnapshotTesting { @@ -43,19 +43,19 @@ public class SnapshotTesting { public static SnapshotDto newAnalysis(String uuid) { return new SnapshotDto() - .setUuid(randomAlphanumeric(40)) + .setUuid(secure().nextAlphanumeric(40)) .setRootComponentUuid(uuid) .setStatus(SnapshotDto.STATUS_PROCESSED) .setCreatedAt(System.currentTimeMillis()) .setAnalysisDate(System.currentTimeMillis()) - .setRevision(randomAlphanumeric(50)) + .setRevision(secure().nextAlphanumeric(50)) .setLast(true); } public static SnapshotDto newSnapshot() { return new SnapshotDto() - .setUuid(randomAlphanumeric(40)) - .setRootComponentUuid(randomAlphanumeric(40)) + .setUuid(secure().nextAlphanumeric(40)) + .setRootComponentUuid(secure().nextAlphanumeric(40)) .setStatus(randomAscii(1)) .setCreatedAt(System.currentTimeMillis()) .setAnalysisDate(System.currentTimeMillis()) diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/event/EventTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/event/EventTesting.java index d95dc7b6b65..7ed99ce8602 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/event/EventTesting.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/event/EventTesting.java @@ -22,7 +22,7 @@ package org.sonar.db.event; import org.sonar.db.component.SnapshotDto; import static java.util.Objects.requireNonNull; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; public class EventTesting { @@ -33,8 +33,8 @@ public class EventTesting { return new EventDto() .setAnalysisUuid(analysis.getUuid()) .setComponentUuid(analysis.getRootComponentUuid()) - .setUuid(randomAlphanumeric(40)) - .setName(randomAlphanumeric(400)) + .setUuid(secure().nextAlphanumeric(40)) + .setName(secure().nextAlphanumeric(400)) .setDescription(null) .setCategory("Other") .setCreatedAt(System.currentTimeMillis()) diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/metric/MetricTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/metric/MetricTesting.java index 84cdc5a7571..541d4f5ab56 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/metric/MetricTesting.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/metric/MetricTesting.java @@ -35,12 +35,12 @@ public class MetricTesting { public static MetricDto newMetricDto() { Metric.ValueType[] metricTypes = Metric.ValueType.values(); return new MetricDto() - .setUuid(RandomStringUtils.randomAlphanumeric(40)) - .setKey(RandomStringUtils.randomAlphanumeric(64)) - .setShortName(RandomStringUtils.randomAlphanumeric(64)) + .setUuid(RandomStringUtils.secure().nextAlphanumeric(40)) + .setKey(RandomStringUtils.secure().nextAlphanumeric(64)) + .setShortName(RandomStringUtils.secure().nextAlphanumeric(64)) .setValueType(metricTypes[RANDOM.nextInt(metricTypes.length - 1)].name()) - .setDomain(RandomStringUtils.randomAlphanumeric(64)) - .setDescription(RandomStringUtils.randomAlphanumeric(250)) + .setDomain(RandomStringUtils.secure().nextAlphanumeric(64)) + .setDescription(RandomStringUtils.secure().nextAlphanumeric(250)) .setBestValue(RANDOM.nextDouble()) .setDeleteHistoricalData(RANDOM.nextBoolean()) .setDirection(RANDOM.nextInt(Integer.MAX_VALUE)) diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/permission/template/PermissionTemplateTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/permission/template/PermissionTemplateTesting.java index 8cb96a4afe8..7a0ab93cac4 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/permission/template/PermissionTemplateTesting.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/permission/template/PermissionTemplateTesting.java @@ -27,8 +27,8 @@ import org.sonar.core.util.Uuids; import org.sonar.db.permission.PermissionsTestHelper; import static java.util.Arrays.stream; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; import static org.apache.commons.lang3.RandomStringUtils.randomAscii; +import static org.apache.commons.lang3.RandomStringUtils.secure; public class PermissionTemplateTesting { @@ -37,7 +37,7 @@ public class PermissionTemplateTesting { @SafeVarargs public static PermissionTemplateDto newPermissionTemplateDto(Consumer... populators) { PermissionTemplateDto dto = new PermissionTemplateDto() - .setName(randomAlphanumeric(60)) + .setName(secure().nextAlphanumeric(60)) .setDescription(randomAscii(500)) .setUuid(Uuids.create()) .setCreatedAt(new Date()) diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/plugin/PluginTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/plugin/PluginTesting.java index 517a31ba5f8..6f109ba42f2 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/plugin/PluginTesting.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/plugin/PluginTesting.java @@ -23,7 +23,7 @@ import java.security.SecureRandom; import java.util.Random; import org.sonar.core.util.Uuids; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; public class PluginTesting { @@ -41,7 +41,7 @@ public class PluginTesting { return new PluginDto() .setUuid(uuid) .setKee(uuid) - .setFileHash(randomAlphanumeric(32)) + .setFileHash(secure().nextAlphanumeric(32)) .setCreatedAt(RANDOM.nextLong(Long.MAX_VALUE)) .setUpdatedAt(RANDOM.nextLong(Long.MAX_VALUE)); } diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/qualitygate/QualityGateDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/qualitygate/QualityGateDbTester.java index f721e7104ed..f9c7c58b19c 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/qualitygate/QualityGateDbTester.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/qualitygate/QualityGateDbTester.java @@ -25,7 +25,6 @@ import java.util.Optional; import java.util.function.Consumer; import org.sonar.core.util.Uuids; import org.sonar.db.DbClient; -import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.metric.MetricDto; import org.sonar.db.project.ProjectDto; @@ -33,8 +32,8 @@ import org.sonar.db.property.PropertyDto; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; -import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; + public class QualityGateDbTester { private static final String DEFAULT_QUALITY_GATE_PROPERTY_NAME = "qualitygate.default"; @@ -60,7 +59,7 @@ public class QualityGateDbTester { @SafeVarargs public final QualityGateDto insertQualityGate(Consumer... dtoPopulators) { QualityGateDto qualityGate = new QualityGateDto() - .setName(randomAlphanumeric(30)) + .setName(secure().nextAlphanumeric(30)) .setUuid(Uuids.createFast()) .setBuiltIn(false); Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(qualityGate)); @@ -92,7 +91,7 @@ public class QualityGateDbTester { .setUuid(Uuids.createFast()) .setMetricUuid(metric.getUuid()) .setOperator("GT") - .setErrorThreshold(randomNumeric(10)); + .setErrorThreshold(secure().nextNumeric(10)); Arrays.stream(dtoPopulators).forEach(dtoPopulator -> dtoPopulator.accept(condition)); dbClient.gateConditionDao().insert(condition, db.getSession()); db.commit(); diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/qualityprofile/QualityProfileTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/qualityprofile/QualityProfileTesting.java index 32034fd6162..4d43da6061b 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/qualityprofile/QualityProfileTesting.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/qualityprofile/QualityProfileTesting.java @@ -25,8 +25,7 @@ import java.util.function.Consumer; import org.sonar.core.util.Uuids; import static java.util.Arrays.stream; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; public class QualityProfileTesting { @@ -45,7 +44,7 @@ public class QualityProfileTesting { .setKee(uuid) .setRulesProfileUuid(Uuids.createFast()) .setName(uuid) - .setLanguage(randomAlphanumeric(20)) + .setLanguage(secure().nextAlphanumeric(20)) .setLastUsed(RANDOM.nextLong(Long.MAX_VALUE)); } @@ -55,11 +54,11 @@ public class QualityProfileTesting { */ public static QProfileChangeDto newQProfileChangeDto() { return new QProfileChangeDto() - .setUuid(randomAlphanumeric(40)) - .setRulesProfileUuid(randomAlphanumeric(40)) + .setUuid(secure().nextAlphanumeric(40)) + .setRulesProfileUuid(secure().nextAlphanumeric(40)) .setCreatedAt(RANDOM.nextLong(Long.MAX_VALUE)) .setChangeType("ACTIVATED") - .setUserUuid("userUuid_" + randomAlphanumeric(10)); + .setUserUuid("userUuid_" + secure().nextAlphanumeric(10)); } /** @@ -67,9 +66,9 @@ public class QualityProfileTesting { */ public static RulesProfileDto newRuleProfileDto(Consumer... populators) { RulesProfileDto dto = new RulesProfileDto() - .setUuid("uuid" + randomAlphabetic(10)) - .setName("name" + randomAlphabetic(10)) - .setLanguage("lang" + randomAlphabetic(5)) + .setUuid("uuid" + secure().nextAlphabetic(10)) + .setName("name" + secure().nextAlphabetic(10)) + .setLanguage("lang" + secure().nextAlphabetic(5)) .setIsBuiltIn(false); stream(populators).forEach(p -> p.accept(dto)); return dto; diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/rule/RuleTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/rule/RuleTesting.java index b81a436edc2..bfb63cabd21 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/rule/RuleTesting.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/rule/RuleTesting.java @@ -42,8 +42,7 @@ import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableSet.copyOf; import static com.google.common.collect.Sets.newHashSet; import static java.util.Arrays.stream; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.sonar.api.rule.RuleKey.EXTERNAL_RULE_REPO_PREFIX; import static org.sonar.api.rules.RuleType.CODE_SMELL; import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection; @@ -69,7 +68,7 @@ public class RuleTesting { } public static RuleDto newRule() { - return newRule(RuleKey.of(randomAlphanumeric(30), randomAlphanumeric(30))); + return newRule(RuleKey.of(secure().nextAlphanumeric(30), secure().nextAlphanumeric(30))); } public static RuleDto newRule(RuleDescriptionSectionDto... ruleDescriptionSectionDtos) { @@ -79,7 +78,7 @@ public class RuleTesting { public static RuleDto newRule(RuleKey key, RuleDescriptionSectionDto... ruleDescriptionSectionDtos) { RuleDto ruleDto = newRuleWithoutDescriptionSection(key); if (ruleDescriptionSectionDtos.length == 0) { - ruleDto.addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "description_" + randomAlphabetic(5))); + ruleDto.addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "description_" + secure().nextAlphabetic(5))); } else { stream(ruleDescriptionSectionDtos).forEach(ruleDto::addRuleDescriptionSectionDto); } @@ -95,8 +94,8 @@ public class RuleTesting { return new RuleDto() .setRepositoryKey(ruleKey.repository()) .setRuleKey(ruleKey.rule()) - .setUuid("rule_uuid_" + randomAlphanumeric(5)) - .setName("name_" + randomAlphanumeric(5)) + .setUuid("rule_uuid_" + secure().nextAlphanumeric(5)) + .setName("name_" + secure().nextAlphanumeric(5)) .setDescriptionFormat(RuleDto.Format.HTML) .setType(CODE_SMELL) .setCleanCodeAttribute(CleanCodeAttribute.CLEAR) @@ -109,9 +108,9 @@ public class RuleTesting { .setIsTemplate(false) .setIsExternal(false) .setIsAdHoc(false) - .setSystemTags(newHashSet("tag_" + randomAlphanumeric(5), "tag_" + randomAlphanumeric(5))) - .setLanguage("lang_" + randomAlphanumeric(3)) - .setGapDescription("gapDescription_" + randomAlphanumeric(5)) + .setSystemTags(newHashSet("tag_" + secure().nextAlphanumeric(5), "tag_" + secure().nextAlphanumeric(5))) + .setLanguage("lang_" + secure().nextAlphanumeric(3)) + .setGapDescription("gapDescription_" + secure().nextAlphanumeric(5)) .setDefRemediationBaseEffort(RANDOM.nextInt(10) + "h") // voluntarily offset the remediation to be able to detect issues .setDefRemediationGapMultiplier((RANDOM.nextInt(10) + 10) + "h") @@ -119,36 +118,36 @@ public class RuleTesting { .setRemediationBaseEffort(RANDOM.nextInt(10) + "h") .setRemediationGapMultiplier(RANDOM.nextInt(10) + "h") .setRemediationFunction("LINEAR_OFFSET") - .setTags(newHashSet("tag_" + randomAlphanumeric(5), "tag_" + randomAlphanumeric(5))) - .setNoteData("noteData_" + randomAlphanumeric(5)) - .setNoteUserUuid("noteUserUuid_" + randomAlphanumeric(5)) + .setTags(newHashSet("tag_" + secure().nextAlphanumeric(5), "tag_" + secure().nextAlphanumeric(5))) + .setNoteData("noteData_" + secure().nextAlphanumeric(5)) + .setNoteUserUuid("noteUserUuid_" + secure().nextAlphanumeric(5)) .setNoteCreatedAt(System.currentTimeMillis() - 200) .setNoteUpdatedAt(System.currentTimeMillis() - 150) - .setAdHocName("adHocName_" + randomAlphanumeric(5)) - .setAdHocDescription("adHocDescription_" + randomAlphanumeric(5)) + .setAdHocName("adHocName_" + secure().nextAlphanumeric(5)) + .setAdHocDescription("adHocDescription_" + secure().nextAlphanumeric(5)) .setAdHocSeverity(Severity.ALL.get(RANDOM.nextInt(Severity.ALL.size()))) .setAdHocType(RuleType.values()[RANDOM.nextInt(RuleType.values().length - 1)]) .setCreatedAt(currentTimeMillis) .setUpdatedAt(currentTimeMillis + 5) .setScope(Scope.MAIN) - .setEducationPrinciples(Set.of(randomAlphanumeric(5), randomAlphanumeric(5))); + .setEducationPrinciples(Set.of(secure().nextAlphanumeric(5), secure().nextAlphanumeric(5))); } public static RuleParamDto newRuleParam(RuleDto rule) { return new RuleParamDto() .setRuleUuid(rule.getUuid()) - .setName("name_" + randomAlphabetic(5)) - .setDefaultValue("default_" + randomAlphabetic(5)) - .setDescription("description_" + randomAlphabetic(5)) + .setName("name_" + secure().nextAlphabetic(5)) + .setDefaultValue("default_" + secure().nextAlphabetic(5)) + .setDescription("description_" + secure().nextAlphabetic(5)) .setType(RuleParamType.STRING.type()); } public static DeprecatedRuleKeyDto newDeprecatedRuleKey() { return new DeprecatedRuleKeyDto() .setUuid(uuidFactory.create()) - .setOldRepositoryKey(randomAlphanumeric(50)) - .setOldRuleKey(randomAlphanumeric(50)) - .setRuleUuid(randomAlphanumeric(40)) + .setOldRepositoryKey(secure().nextAlphanumeric(50)) + .setOldRuleKey(secure().nextAlphanumeric(50)) + .setRuleUuid(secure().nextAlphanumeric(40)) .setCreatedAt(System.currentTimeMillis()); } @@ -166,7 +165,7 @@ public class RuleTesting { } public static RuleDto newCustomRule(RuleDto templateRule) { - return newCustomRule(templateRule, "description_" + randomAlphabetic(5)); + return newCustomRule(templateRule, "description_" + secure().nextAlphabetic(5)); } public static RuleDto newCustomRule(RuleDto templateRule, String description) { diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/source/FileSourceTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/source/FileSourceTester.java index 06210cfb73f..6f10c5abfd4 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/source/FileSourceTester.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/source/FileSourceTester.java @@ -30,7 +30,7 @@ import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.protobuf.DbFileSources; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; public class FileSourceTester { @@ -48,10 +48,10 @@ public class FileSourceTester { .setUuid(Uuids.createFast()) .setProjectUuid(file.branchUuid()) .setFileUuid(file.uuid()) - .setSrcHash(randomAlphanumeric(50)) - .setDataHash(randomAlphanumeric(50)) + .setSrcHash(secure().nextAlphanumeric(50)) + .setDataHash(secure().nextAlphanumeric(50)) .setLineHashes(IntStream.range(0, RANDOM.nextInt(21)).mapToObj(String::valueOf).toList()) - .setRevision(randomAlphanumeric(100)) + .setRevision(secure().nextAlphanumeric(100)) .setSourceData(newRandomData(3).build()) .setCreatedAt(new Date().getTime()) .setUpdatedAt(new Date().getTime()); @@ -68,10 +68,10 @@ public class FileSourceTester { .setUuid(Uuids.createFast()) .setProjectUuid(file.branchUuid()) .setFileUuid(file.uuid()) - .setSrcHash(randomAlphanumeric(50)) - .setDataHash(randomAlphanumeric(50)) + .setSrcHash(secure().nextAlphanumeric(50)) + .setDataHash(secure().nextAlphanumeric(50)) .setLineHashes(IntStream.range(0, numLines).mapToObj(String::valueOf).toList()) - .setRevision(randomAlphanumeric(100)) + .setRevision(secure().nextAlphanumeric(100)) .setSourceData(newRandomData(numLines).build()) .setCreatedAt(new Date().getTime()) .setUpdatedAt(new Date().getTime()); @@ -86,10 +86,10 @@ public class FileSourceTester { for (int i = 1; i <= numberOfLines; i++) { dataBuilder.addLinesBuilder() .setLine(i) - .setScmRevision(randomAlphanumeric(15)) - .setScmAuthor(randomAlphanumeric(10)) + .setScmRevision(secure().nextAlphanumeric(15)) + .setScmAuthor(secure().nextAlphanumeric(10)) .setScmDate(RANDOM.nextLong(Long.MAX_VALUE)) - .setSource(randomAlphanumeric(20)) + .setSource(secure().nextAlphanumeric(20)) .setLineHits(RANDOM.nextInt(4)) .setConditions(RANDOM.nextInt(4)) .setCoveredConditions(RANDOM.nextInt(4)) diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/telemetry/TelemetryMetricsSentTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/telemetry/TelemetryMetricsSentTesting.java index 2475d46f778..7ccc51abf4d 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/telemetry/TelemetryMetricsSentTesting.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/telemetry/TelemetryMetricsSentTesting.java @@ -33,8 +33,8 @@ public class TelemetryMetricsSentTesting { public static TelemetryMetricsSentDto newTelemetryMetricsSentDto() { return new TelemetryMetricsSentDto( - RandomStringUtils.randomAlphanumeric(40), // key - RandomStringUtils.randomAlphanumeric(30) // dimension + RandomStringUtils.secure().nextAlphanumeric(40), // key + RandomStringUtils.secure().nextAlphanumeric(30) // dimension ).setLastSent(RANDOM.nextLong()); } } diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/GroupTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/GroupTesting.java index 08d7f04db06..570af3abfa1 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/GroupTesting.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/GroupTesting.java @@ -23,7 +23,7 @@ import java.security.SecureRandom; import java.util.Date; import java.util.Random; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; public class GroupTesting { @@ -35,9 +35,9 @@ public class GroupTesting { public static GroupDto newGroupDto() { return new GroupDto() - .setUuid(randomAlphanumeric(40)) - .setName(randomAlphanumeric(255)) - .setDescription(randomAlphanumeric(200)) + .setUuid(secure().nextAlphanumeric(40)) + .setName(secure().nextAlphanumeric(255)) + .setDescription(secure().nextAlphanumeric(200)) .setCreatedAt(new Date(RANDOM.nextLong(Long.MAX_VALUE))) .setUpdatedAt(new Date(RANDOM.nextLong(Long.MAX_VALUE))); } diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserDbTester.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserDbTester.java index 1edb93d4e99..87cb69cd2c4 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserDbTester.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserDbTester.java @@ -49,7 +49,7 @@ import org.sonar.db.scim.ScimUserDto; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Arrays.stream; import static java.util.stream.Collectors.toSet; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; import static org.sonar.db.user.GroupTesting.newGroupDto; @@ -169,7 +169,7 @@ public class UserDbTester { } public void markGroupAsGithubManaged(String groupUuid) { - db.getDbClient().externalGroupDao().insert(db.getSession(), new ExternalGroupDto(groupUuid, randomAlphanumeric(20), "github")); + db.getDbClient().externalGroupDao().insert(db.getSession(), new ExternalGroupDto(groupUuid, secure().nextAlphanumeric(20), "github")); db.commit(); } diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserTesting.java index 72ec8b15351..94cb1019dc0 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserTesting.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserTesting.java @@ -20,7 +20,6 @@ package org.sonar.db.user; import java.security.SecureRandom; -import java.util.Collections; import java.util.Locale; import java.util.Random; import javax.annotation.Nullable; @@ -29,7 +28,7 @@ import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.apache.commons.lang.math.RandomUtils.nextBoolean; import static org.apache.commons.lang.math.RandomUtils.nextInt; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; public class UserTesting { @@ -39,29 +38,29 @@ public class UserTesting { public static UserDto newUserDto() { return new UserDto() - .setUuid(randomAlphanumeric(40)) + .setUuid(secure().nextAlphanumeric(40)) .setActive(true) .setLocal(RANDOM.nextBoolean()) - .setLogin(randomAlphanumeric(30)) - .setName(randomAlphanumeric(30)) - .setEmail(randomAlphanumeric(30)) - .setScmAccounts(singletonList(randomAlphanumeric(40).toLowerCase(Locale.ENGLISH))) - .setExternalId(randomAlphanumeric(40)) - .setExternalLogin(randomAlphanumeric(40)) - .setExternalIdentityProvider(randomAlphanumeric(40)) - .setSalt(randomAlphanumeric(40)) - .setCryptedPassword(randomAlphanumeric(40)) + .setLogin(secure().nextAlphanumeric(30)) + .setName(secure().nextAlphanumeric(30)) + .setEmail(secure().nextAlphanumeric(30)) + .setScmAccounts(singletonList(secure().nextAlphanumeric(40).toLowerCase(Locale.ENGLISH))) + .setExternalId(secure().nextAlphanumeric(40)) + .setExternalLogin(secure().nextAlphanumeric(40)) + .setExternalIdentityProvider(secure().nextAlphanumeric(40)) + .setSalt(secure().nextAlphanumeric(40)) + .setCryptedPassword(secure().nextAlphanumeric(40)) .setCreatedAt(RANDOM.nextLong(Long.MAX_VALUE)) .setUpdatedAt(RANDOM.nextLong(Long.MAX_VALUE)); } public static UserDto newUserDtoRealistic() { long timeNow = System.currentTimeMillis(); - String loginAndAndId = randomAlphanumeric(30); + String loginAndAndId = secure().nextAlphanumeric(30); String realisticIdentityProvider = realisticIdentityProviders[nextInt(realisticIdentityProviders.length)]; boolean isExternal = nextBoolean(); String externalIdAndLogin = isExternal ? loginAndAndId + "_" + realisticIdentityProvider : loginAndAndId; - return new UserDto().setUuid(randomAlphanumeric(40)) + return new UserDto().setUuid(secure().nextAlphanumeric(40)) .setActive(nextBoolean()) .setLocal(!isExternal) .setLogin(loginAndAndId) @@ -107,9 +106,9 @@ public class UserTesting { .setName(name) .setEmail(email) .setLogin(login) - .setExternalId(randomAlphanumeric(40)) - .setExternalLogin(randomAlphanumeric(40)) - .setExternalIdentityProvider(randomAlphanumeric(40)); + .setExternalId(secure().nextAlphanumeric(40)) + .setExternalLogin(secure().nextAlphanumeric(40)) + .setExternalIdentityProvider(secure().nextAlphanumeric(40)); } public static UserDto newDisabledUser() { diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserTokenTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserTokenTesting.java index d7c3d90fbe1..b942bac0d4f 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserTokenTesting.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/user/UserTokenTesting.java @@ -21,7 +21,7 @@ package org.sonar.db.user; import org.sonar.api.utils.System2; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; public class UserTokenTesting { @@ -33,21 +33,21 @@ public class UserTokenTesting { public static UserTokenDto newUserToken() { return new UserTokenDto() - .setUserUuid("userUuid_" + randomAlphanumeric(40)) - .setName("name_" + randomAlphanumeric(20)) - .setTokenHash("hash_" + randomAlphanumeric(30)) + .setUserUuid("userUuid_" + secure().nextAlphanumeric(40)) + .setName("name_" + secure().nextAlphanumeric(20)) + .setTokenHash("hash_" + secure().nextAlphanumeric(30)) .setCreatedAt(NOW) .setType("USER_TOKEN"); } public static UserTokenDto newProjectAnalysisToken() { return new UserTokenDto() - .setUserUuid("userUuid_" + randomAlphanumeric(40)) - .setName("name_" + randomAlphanumeric(20)) - .setTokenHash("hash_" + randomAlphanumeric(30)) - .setProjectUuid("projectUuid_" + randomAlphanumeric(20)) - .setProjectKey("projectKey_" + randomAlphanumeric(40)) - .setProjectName("Project " + randomAlphanumeric(40)) + .setUserUuid("userUuid_" + secure().nextAlphanumeric(40)) + .setName("name_" + secure().nextAlphanumeric(20)) + .setTokenHash("hash_" + secure().nextAlphanumeric(30)) + .setProjectUuid("projectUuid_" + secure().nextAlphanumeric(20)) + .setProjectKey("projectKey_" + secure().nextAlphanumeric(40)) + .setProjectName("Project " + secure().nextAlphanumeric(40)) .setCreatedAt(NOW) .setType("PROJECT_ANALYSIS_TOKEN"); } diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookDeliveryTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookDeliveryTesting.java index c458c909d42..3ff31853f8e 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookDeliveryTesting.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookDeliveryTesting.java @@ -26,7 +26,7 @@ import org.sonar.core.util.Uuids; import org.sonar.db.DbSession; import org.sonar.db.DbTester; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; public class WebhookDeliveryTesting { @@ -51,16 +51,16 @@ public class WebhookDeliveryTesting { public static WebhookDeliveryDto newDto() { return new WebhookDeliveryDto() .setUuid(Uuids.createFast()) - .setWebhookUuid(randomAlphanumeric(40)) - .setProjectUuid(randomAlphanumeric(40)) - .setCeTaskUuid(randomAlphanumeric(40)) - .setAnalysisUuid(randomAlphanumeric(40)) - .setName(randomAlphanumeric(10)) - .setUrl(randomAlphanumeric(10)) + .setWebhookUuid(secure().nextAlphanumeric(40)) + .setProjectUuid(secure().nextAlphanumeric(40)) + .setCeTaskUuid(secure().nextAlphanumeric(40)) + .setAnalysisUuid(secure().nextAlphanumeric(40)) + .setName(secure().nextAlphanumeric(10)) + .setUrl(secure().nextAlphanumeric(10)) .setDurationMs(RANDOM.nextInt(Integer.MAX_VALUE)) .setHttpStatus(RANDOM.nextInt(Integer.MAX_VALUE)) .setSuccess(RANDOM.nextBoolean()) - .setPayload(randomAlphanumeric(10)) + .setPayload(secure().nextAlphanumeric(10)) .setCreatedAt(RANDOM.nextLong(Long.MAX_VALUE)); } diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookTesting.java index 686fa1fd934..e3a4f31d6f6 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookTesting.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/webhook/WebhookTesting.java @@ -24,7 +24,7 @@ import java.util.Calendar; import java.util.function.Consumer; import org.sonar.db.project.ProjectDto; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; public class WebhookTesting { @@ -55,10 +55,10 @@ public class WebhookTesting { @SafeVarargs private static WebhookDto getWebhookDto(Consumer... consumers) { WebhookDto res = new WebhookDto() - .setUuid(randomAlphanumeric(40)) - .setName(randomAlphanumeric(64)) - .setUrl("https://www.random-site/" + randomAlphanumeric(256)) - .setSecret(randomAlphanumeric(10)) + .setUuid(secure().nextAlphanumeric(40)) + .setName(secure().nextAlphanumeric(64)) + .setUrl("https://www.random-site/" + secure().nextAlphanumeric(256)) + .setSecret(secure().nextAlphanumeric(10)) .setCreatedAt(Calendar.getInstance().getTimeInMillis()); Arrays.stream(consumers).forEach(consumer -> consumer.accept(res)); return res; diff --git a/server/sonar-db-migration/src/it/java/org/sonar/server/platform/db/migration/step/ForceReloadingOfAllPluginsIT.java b/server/sonar-db-migration/src/it/java/org/sonar/server/platform/db/migration/step/ForceReloadingOfAllPluginsIT.java index 8b05c83ecf4..77f5867c8b7 100644 --- a/server/sonar-db-migration/src/it/java/org/sonar/server/platform/db/migration/step/ForceReloadingOfAllPluginsIT.java +++ b/server/sonar-db-migration/src/it/java/org/sonar/server/platform/db/migration/step/ForceReloadingOfAllPluginsIT.java @@ -28,7 +28,7 @@ import org.sonar.core.util.UuidFactory; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.CoreDbTester; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.server.platform.db.migration.step.ForceReloadingOfAllPlugins.OVERWRITE_HASH; @@ -74,8 +74,8 @@ class ForceReloadingOfAllPluginsIT { Map map = new HashMap<>(); String uuid = uuidFactory.create(); map.put("UUID", uuid); - map.put("KEE", randomAlphabetic(20)); - map.put("FILE_HASH", randomAlphabetic(32)); + map.put("KEE", secure().nextAlphabetic(20)); + map.put("FILE_HASH", secure().nextAlphabetic(32)); map.put("CREATED_AT", System.currentTimeMillis()); map.put("UPDATED_AT", System.currentTimeMillis()); map.put("TYPE", "EXTERNAL"); diff --git a/server/sonar-db-migration/src/it/java/org/sonar/server/platform/db/migration/version/v100/PopulateNclocForForProjectsIT.java b/server/sonar-db-migration/src/it/java/org/sonar/server/platform/db/migration/version/v100/PopulateNclocForForProjectsIT.java index 0fa8d7e5ede..99fbca30912 100644 --- a/server/sonar-db-migration/src/it/java/org/sonar/server/platform/db/migration/version/v100/PopulateNclocForForProjectsIT.java +++ b/server/sonar-db-migration/src/it/java/org/sonar/server/platform/db/migration/version/v100/PopulateNclocForForProjectsIT.java @@ -29,7 +29,7 @@ import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.MigrationDbTester; import org.sonar.server.platform.db.migration.step.DataChange; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; class PopulateNclocForForProjectsIT { @@ -106,7 +106,7 @@ class PopulateNclocForForProjectsIT { Map map = new HashMap<>(); String uuid = uuidFactory.create(); map.put("UUID", uuid); - map.put("KEE", randomAlphabetic(20)); + map.put("KEE", secure().nextAlphabetic(20)); map.put("QUALIFIER", "TRK"); map.put("PRIVATE", true); map.put("UPDATED_AT", System.currentTimeMillis()); @@ -119,7 +119,7 @@ class PopulateNclocForForProjectsIT { String uuid = uuidFactory.create(); map.put("UUID", uuid); map.put("PROJECT_UUID", projectUuid); - map.put("KEE", randomAlphabetic(20)); + map.put("KEE", secure().nextAlphabetic(20)); map.put("BRANCH_TYPE", "PULL_REQUEST"); map.put("UPDATED_AT", System.currentTimeMillis()); map.put("CREATED_AT", System.currentTimeMillis()); diff --git a/server/sonar-db-migration/src/it/java/org/sonar/server/platform/db/migration/version/v100/UpdateUserLocalValueInUsersIT.java b/server/sonar-db-migration/src/it/java/org/sonar/server/platform/db/migration/version/v100/UpdateUserLocalValueInUsersIT.java index 6e10a1de332..1e3d3b1109b 100644 --- a/server/sonar-db-migration/src/it/java/org/sonar/server/platform/db/migration/version/v100/UpdateUserLocalValueInUsersIT.java +++ b/server/sonar-db-migration/src/it/java/org/sonar/server/platform/db/migration/version/v100/UpdateUserLocalValueInUsersIT.java @@ -29,8 +29,7 @@ import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.MigrationDbTester; import org.sonar.server.platform.db.migration.step.DataChange; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; class UpdateUserLocalValueInUsersIT { @@ -82,10 +81,10 @@ class UpdateUserLocalValueInUsersIT { Map map = new HashMap<>(); String uuid = uuidFactory.create(); map.put("UUID", uuid); - map.put("LOGIN", randomAlphabetic(20)); - map.put("EXTERNAL_LOGIN", randomAlphabetic(20)); + map.put("LOGIN", secure().nextAlphabetic(20)); + map.put("EXTERNAL_LOGIN", secure().nextAlphabetic(20)); map.put("EXTERNAL_IDENTITY_PROVIDER", "sonarqube"); - map.put("EXTERNAL_ID", randomNumeric(5)); + map.put("EXTERNAL_ID", secure().nextNumeric(5)); map.put("CREATED_AT", System.currentTimeMillis()); map.put("USER_LOCAL", userLocal); map.put("RESET_PASSWORD", false); diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/RenameColumnsBuilderTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/RenameColumnsBuilderTest.java index b041f4f9d4d..6542132ace9 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/RenameColumnsBuilderTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/RenameColumnsBuilderTest.java @@ -39,12 +39,12 @@ import org.sonar.server.platform.db.migration.def.IntegerColumnDef; import org.sonar.server.platform.db.migration.def.TinyIntColumnDef; import org.sonar.server.platform.db.migration.def.VarcharColumnDef; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class RenameColumnsBuilderTest { - private static final String NEW_COLUMN_NAME = "new_" + randomAlphabetic(6).toLowerCase(); + private static final String NEW_COLUMN_NAME = "new_" + secure().nextAlphabetic(6).toLowerCase(); private static final DatabaseAndResult[] DATABASES = { new DatabaseAndResult(new H2(), "ALTER TABLE ${table_name} ALTER COLUMN ${old_column_name} RENAME TO ${new_column_name}"), @@ -94,8 +94,8 @@ public class RenameColumnsBuilderTest { DatabaseAndResult database, ColumnDef columnDef) { - String oldColumnName = "old_" + randomAlphabetic(6).toLowerCase(); - String tableName = "table_" + randomAlphabetic(6).toLowerCase(); + String oldColumnName = "old_" + secure().nextAlphabetic(6).toLowerCase(); + String tableName = "table_" + secure().nextAlphabetic(6).toLowerCase(); List result = new RenameColumnsBuilder(database.dialect(), tableName) .renameColumn(oldColumnName, columnDef) @@ -123,7 +123,7 @@ public class RenameColumnsBuilderTest { DatabaseAndResult database, ColumnDef columnDef) { - String tableName = "table_" + randomAlphabetic(6).toLowerCase(); + String tableName = "table_" + secure().nextAlphabetic(6).toLowerCase(); RenameColumnsBuilder renameColumnsBuilder = new RenameColumnsBuilder(database.dialect(), tableName) .renameColumn(NEW_COLUMN_NAME, columnDef); @@ -148,7 +148,7 @@ public class RenameColumnsBuilderTest { ColumnDef columnDef, String illegalColumnName) { - String tableName = "table_" + randomAlphabetic(6).toLowerCase(); + String tableName = "table_" + secure().nextAlphabetic(6).toLowerCase(); RenameColumnsBuilder renameColumnsBuilder = new RenameColumnsBuilder(database.dialect(), tableName) .renameColumn(illegalColumnName, columnDef); diff --git a/server/sonar-main/src/test/java/org/sonar/application/AbstractStopRequestWatcherTest.java b/server/sonar-main/src/test/java/org/sonar/application/AbstractStopRequestWatcherTest.java index a81e4cc1d97..7934e228046 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/AbstractStopRequestWatcherTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/AbstractStopRequestWatcherTest.java @@ -37,7 +37,7 @@ public class AbstractStopRequestWatcherTest { @Rule public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60)); - private String threadName = RandomStringUtils.randomAlphabetic(12); + private String threadName = RandomStringUtils.secure().nextAlphabetic(12); private TestBooleanSupplier booleanSupplier = new TestBooleanSupplier(); private TestAction stopAction = new TestAction(); diff --git a/server/sonar-main/src/test/java/org/sonar/application/SchedulerImplTest.java b/server/sonar-main/src/test/java/org/sonar/application/SchedulerImplTest.java index 14f7975d271..e083d5d2b8e 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/SchedulerImplTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/SchedulerImplTest.java @@ -53,7 +53,7 @@ import org.sonar.process.cluster.hz.HazelcastMember; import static com.google.common.collect.ImmutableMap.of; import static java.util.Collections.synchronizedList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -410,8 +410,8 @@ public class SchedulerImplTest { } private ImmutableMap.Builder addRequiredNodeProperties(ImmutableMap.Builder builder) { - builder.put(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(4)); - builder.put(CLUSTER_NODE_HOST.getKey(), randomAlphanumeric(4)); + builder.put(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(4)); + builder.put(CLUSTER_NODE_HOST.getKey(), secure().nextAlphanumeric(4)); builder.put(CLUSTER_NODE_HZ_PORT.getKey(), String.valueOf(1 + new Random().nextInt(999))); return builder; } diff --git a/server/sonar-main/src/test/java/org/sonar/application/cluster/health/SearchNodeHealthProviderTest.java b/server/sonar-main/src/test/java/org/sonar/application/cluster/health/SearchNodeHealthProviderTest.java index 9e1f27a1f48..2f93d9cd9f3 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/cluster/health/SearchNodeHealthProviderTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/cluster/health/SearchNodeHealthProviderTest.java @@ -30,8 +30,7 @@ import org.sonar.process.Props; import org.sonar.process.cluster.health.NodeHealth; import static java.lang.String.valueOf; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import static org.mockito.Mockito.mock; @@ -59,7 +58,7 @@ public class SearchNodeHealthProviderTest { @Test public void constructor_throws_NPE_if_NetworkUtils_getHostname_returns_null_and_property_is_not_set() { Properties properties = new Properties(); - properties.put(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); + properties.put(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(3)); Props props = new Props(properties); assertThatThrownBy(() -> new SearchNodeHealthProvider(props, clusterAppState, networkUtils, clock)) @@ -69,8 +68,8 @@ public class SearchNodeHealthProviderTest { @Test public void constructor_throws_IAE_if_property_node_port_is_not_set() { Properties properties = new Properties(); - properties.put(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); - when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(34)); + properties.put(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(3)); + when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(34)); Props props = new Props(properties); assertThatThrownBy(() -> new SearchNodeHealthProvider(props, clusterAppState, networkUtils, clock)) @@ -80,11 +79,11 @@ public class SearchNodeHealthProviderTest { @Test public void constructor_throws_FormatException_if_property_node_port_is_not_an_integer() { - String port = randomAlphabetic(3); + String port = secure().nextAlphabetic(3); Properties properties = new Properties(); - properties.put(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); + properties.put(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(3)); properties.put(CLUSTER_NODE_HZ_PORT.getKey(), port); - when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(34)); + when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(34)); Props props = new Props(properties); assertThatThrownBy(() -> new SearchNodeHealthProvider(props, clusterAppState, networkUtils, clock)) @@ -94,12 +93,12 @@ public class SearchNodeHealthProviderTest { @Test public void get_returns_name_and_port_from_properties_at_constructor_time() { - String name = randomAlphanumeric(3); + String name = secure().nextAlphanumeric(3); int port = 1 + random.nextInt(4); Properties properties = new Properties(); properties.setProperty(CLUSTER_NODE_NAME.getKey(), name); properties.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), valueOf(port)); - when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(34)); + when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(34)); when(clock.now()).thenReturn(1L + random.nextInt(87)); SearchNodeHealthProvider underTest = new SearchNodeHealthProvider(new Props(properties), clusterAppState, networkUtils, clock); @@ -109,7 +108,7 @@ public class SearchNodeHealthProviderTest { assertThat(nodeHealth.getDetails().getPort()).isEqualTo(port); // change values in properties - properties.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(6)); + properties.setProperty(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(6)); properties.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), valueOf(1 + random.nextInt(99))); NodeHealth newNodeHealth = underTest.get(); @@ -120,9 +119,9 @@ public class SearchNodeHealthProviderTest { @Test public void get_returns_host_from_property_if_set_at_constructor_time() { - String host = randomAlphanumeric(55); + String host = secure().nextAlphanumeric(55); Properties properties = new Properties(); - properties.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); + properties.setProperty(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(3)); properties.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), valueOf(1 + random.nextInt(4))); properties.setProperty(CLUSTER_NODE_HOST.getKey(), host); when(clock.now()).thenReturn(1L + random.nextInt(87)); @@ -133,7 +132,7 @@ public class SearchNodeHealthProviderTest { assertThat(nodeHealth.getDetails().getHost()).isEqualTo(host); // change now - properties.setProperty(CLUSTER_NODE_HOST.getKey(), randomAlphanumeric(96)); + properties.setProperty(CLUSTER_NODE_HOST.getKey(), secure().nextAlphanumeric(96)); NodeHealth newNodeHealth = underTest.get(); @@ -151,9 +150,9 @@ public class SearchNodeHealthProviderTest { } private void getReturnsHostFromNetworkUtils(@Nullable String hostPropertyValue) { - String host = randomAlphanumeric(34); + String host = secure().nextAlphanumeric(34); Properties properties = new Properties(); - properties.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); + properties.setProperty(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(3)); properties.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), valueOf(1 + random.nextInt(4))); if (hostPropertyValue != null) { properties.setProperty(CLUSTER_NODE_HOST.getKey(), hostPropertyValue); @@ -167,7 +166,7 @@ public class SearchNodeHealthProviderTest { assertThat(nodeHealth.getDetails().getHost()).isEqualTo(host); // change now - when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(96)); + when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(96)); NodeHealth newNodeHealth = underTest.get(); @@ -218,11 +217,11 @@ public class SearchNodeHealthProviderTest { } private long setRequiredPropertiesAndMocks(Properties properties) { - properties.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); + properties.setProperty(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(3)); properties.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), valueOf(1 + random.nextInt(4))); long now = 1L + random.nextInt(87); when(clock.now()).thenReturn(now); - when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(34)); + when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(34)); return now; } } diff --git a/server/sonar-main/src/test/java/org/sonar/application/command/AbstractCommandTest.java b/server/sonar-main/src/test/java/org/sonar/application/command/AbstractCommandTest.java index 4ba830d0fa2..0b0fbae30e4 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/command/AbstractCommandTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/command/AbstractCommandTest.java @@ -33,7 +33,7 @@ import org.mockito.Mockito; import org.sonar.process.ProcessId; import org.sonar.process.System2; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.when; @@ -72,7 +72,7 @@ public class AbstractCommandTest { }; - assertThatThrownBy(() -> underTest.setEnvVariable(null, randomAlphanumeric(30))) + assertThatThrownBy(() -> underTest.setEnvVariable(null, secure().nextAlphanumeric(30))) .isInstanceOf(NullPointerException.class) .hasMessage("key can't be null"); } @@ -84,7 +84,7 @@ public class AbstractCommandTest { }; - assertThatThrownBy(() -> underTest.setEnvVariable(randomAlphanumeric(30), null)) + assertThatThrownBy(() -> underTest.setEnvVariable(secure().nextAlphanumeric(30), null)) .isInstanceOf(NullPointerException.class) .hasMessage("value can't be null"); } @@ -107,8 +107,8 @@ public class AbstractCommandTest { File workDir = temp.newFolder(); System2 system2 = Mockito.mock(System2.class); Map env = new HashMap<>(); - String key1 = randomAlphanumeric(3); - env.put(key1, randomAlphanumeric(9)); + String key1 = secure().nextAlphanumeric(3); + env.put(key1, secure().nextAlphanumeric(9)); when(system2.getenv()).thenReturn(env); AbstractCommand underTest = new AbstractCommand(ProcessId.ELASTICSEARCH, workDir, system2) { diff --git a/server/sonar-main/src/test/java/org/sonar/application/command/EsJvmOptionsTest.java b/server/sonar-main/src/test/java/org/sonar/application/command/EsJvmOptionsTest.java index b26ff72651d..7180b5dd653 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/command/EsJvmOptionsTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/command/EsJvmOptionsTest.java @@ -31,7 +31,7 @@ import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.sonar.process.Props; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -100,7 +100,7 @@ public class EsJvmOptionsTest { @Test public void constructor_forces_boostrap_checks_if_jdbc_url_property_is_not_h2() throws IOException { - properties.put("sonar.jdbc.url", randomAlphanumeric(53)); + properties.put("sonar.jdbc.url", secure().nextAlphanumeric(53)); File tmpDir = temporaryFolder.newFolder(); EsJvmOptions underTest = new EsJvmOptions(new Props(properties), tmpDir); @@ -147,7 +147,7 @@ public class EsJvmOptionsTest { @Test public void boostrap_checks_can_be_set_true_if_jdbc_other_than_h2() throws IOException { - properties.put("sonar.jdbc.url", randomAlphanumeric(53)); + properties.put("sonar.jdbc.url", secure().nextAlphanumeric(53)); properties.put("sonar.es.bootstrap.checks.disable", "true"); File tmpDir = temporaryFolder.newFolder(); @@ -160,7 +160,7 @@ public class EsJvmOptionsTest { @Test public void boostrap_checks_can_be_set_false_if_jdbc_other_than_h2() throws IOException { - properties.put("sonar.jdbc.url", randomAlphanumeric(53)); + properties.put("sonar.jdbc.url", secure().nextAlphanumeric(53)); properties.put("sonar.es.bootstrap.checks.disable", "false"); File tmpDir = temporaryFolder.newFolder(); diff --git a/server/sonar-main/src/test/java/org/sonar/application/command/JvmOptionsTest.java b/server/sonar-main/src/test/java/org/sonar/application/command/JvmOptionsTest.java index ae4a4ad6d7e..550cb2303a7 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/command/JvmOptionsTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/command/JvmOptionsTest.java @@ -41,8 +41,7 @@ import org.sonar.process.MessageException; import org.sonar.process.Props; import static java.lang.String.valueOf; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; @@ -51,9 +50,9 @@ import static org.assertj.core.api.Assertions.fail; public class JvmOptionsTest { private final Random random = new Random(); - private final String randomPropertyName = randomAlphanumeric(3); - private final String randomPrefix = "-" + randomAlphabetic(5).toLowerCase(Locale.ENGLISH); - private final String randomValue = randomAlphanumeric(4).toLowerCase(Locale.ENGLISH); + private final String randomPropertyName = secure().nextAlphanumeric(3); + private final String randomPrefix = "-" + secure().nextAlphabetic(5).toLowerCase(Locale.ENGLISH); + private final String randomValue = secure().nextAlphanumeric(4).toLowerCase(Locale.ENGLISH); private final Properties properties = new Properties(); private final JvmOptions underTest = new JvmOptions(); @@ -98,7 +97,7 @@ public class JvmOptionsTest { @Test public void constructor_throws_IAE_if_any_option_prefix_does_not_start_with_dash() { - String invalidPrefix = randomAlphanumeric(3); + String invalidPrefix = secure().nextAlphanumeric(3); Map mandatoryJvmOptions = shuffleThenToMap( Stream.of( IntStream.range(0, random.nextInt(10)).mapToObj(i -> new Option("-B", valueOf(i))), @@ -146,7 +145,7 @@ public class JvmOptionsTest { @Test public void add_throws_IAE_if_argument_does_not_start_with_dash() { - expectJvmOptionNotEmptyAndStartByDashIAE(() -> underTest.add(randomAlphanumeric(3))); + expectJvmOptionNotEmptyAndStartByDashIAE(() -> underTest.add(secure().nextAlphanumeric(3))); } @@ -162,10 +161,10 @@ public class JvmOptionsTest { public void add_throws_MessageException_if_option_starts_with_prefix_of_mandatory_option_but_has_different_value() { String[] optionOverrides = { randomPrefix, - randomPrefix + randomAlphanumeric(1), - randomPrefix + randomAlphanumeric(2), - randomPrefix + randomAlphanumeric(3), - randomPrefix + randomAlphanumeric(4), + randomPrefix + secure().nextAlphanumeric(1), + randomPrefix + secure().nextAlphanumeric(2), + randomPrefix + secure().nextAlphanumeric(3), + randomPrefix + secure().nextAlphanumeric(4), randomPrefix + randomValue.substring(1), randomPrefix + randomValue.substring(2), randomPrefix + randomValue.substring(3) @@ -187,10 +186,10 @@ public class JvmOptionsTest { public void add_checks_against_mandatory_options_is_case_sensitive() { String[] optionOverrides = { randomPrefix, - randomPrefix + randomAlphanumeric(1), - randomPrefix + randomAlphanumeric(2), - randomPrefix + randomAlphanumeric(3), - randomPrefix + randomAlphanumeric(4), + randomPrefix + secure().nextAlphanumeric(1), + randomPrefix + secure().nextAlphanumeric(2), + randomPrefix + secure().nextAlphanumeric(3), + randomPrefix + secure().nextAlphanumeric(4), randomPrefix + randomValue.substring(1), randomPrefix + randomValue.substring(2), randomPrefix + randomValue.substring(3) @@ -267,10 +266,10 @@ public class JvmOptionsTest { randomPrefix + randomValue.substring(1), randomPrefix + randomValue.substring(2), randomPrefix + randomValue.substring(3), - randomPrefix + randomValue.substring(3) + randomAlphanumeric(1), - randomPrefix + randomValue.substring(3) + randomAlphanumeric(2), - randomPrefix + randomValue.substring(3) + randomAlphanumeric(3), - randomPrefix + randomValue + randomAlphanumeric(1) + randomPrefix + randomValue.substring(3) + secure().nextAlphanumeric(1), + randomPrefix + randomValue.substring(3) + secure().nextAlphanumeric(2), + randomPrefix + randomValue.substring(3) + secure().nextAlphanumeric(3), + randomPrefix + randomValue + secure().nextAlphanumeric(1) }; JvmOptions underTest = new JvmOptions(ImmutableMap.of(randomPrefix, randomValue)); @@ -296,10 +295,10 @@ public class JvmOptionsTest { randomPrefix + randomValue.substring(1), randomPrefix + randomValue.substring(2), randomPrefix + randomValue.substring(3), - randomPrefix + randomValue.substring(3) + randomAlphanumeric(1), - randomPrefix + randomValue.substring(3) + randomAlphanumeric(2), - randomPrefix + randomValue.substring(3) + randomAlphanumeric(3), - randomPrefix + randomValue + randomAlphanumeric(1) + randomPrefix + randomValue.substring(3) + secure().nextAlphanumeric(1), + randomPrefix + randomValue.substring(3) + secure().nextAlphanumeric(2), + randomPrefix + randomValue.substring(3) + secure().nextAlphanumeric(3), + randomPrefix + randomValue + secure().nextAlphanumeric(1) }; JvmOptions underTest = new JvmOptions(ImmutableMap.of(randomPrefix, randomValue)); @@ -313,7 +312,7 @@ public class JvmOptionsTest { @Test public void addFromMandatoryProperty_reports_all_overriding_options_in_single_exception() { String overriding1 = randomPrefix; - String overriding2 = randomPrefix + randomValue + randomAlphanumeric(1); + String overriding2 = randomPrefix + randomValue + secure().nextAlphanumeric(1); properties.setProperty(randomPropertyName, "-foo " + overriding1 + " -bar " + overriding2); JvmOptions underTest = new JvmOptions(ImmutableMap.of(randomPrefix, randomValue)); diff --git a/server/sonar-main/src/test/java/org/sonar/application/es/EsSettingsTest.java b/server/sonar-main/src/test/java/org/sonar/application/es/EsSettingsTest.java index b5e264b8ddb..fbbe56b27cb 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/es/EsSettingsTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/es/EsSettingsTest.java @@ -43,7 +43,7 @@ import org.sonar.process.Props; import org.sonar.process.System2; import static java.util.Optional.ofNullable; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; @@ -111,7 +111,7 @@ public class EsSettingsTest { public void constructor_logs_warning_if_env_variable_ES_JVM_OPTIONS_is_set_and_non_empty() { this.listAppender = ListAppender.attachMemoryAppenderToLoggerOf(EsSettings.class); Props props = minimalProps(); - when(system.getenv("ES_JVM_OPTIONS")).thenReturn(randomAlphanumeric(2)); + when(system.getenv("ES_JVM_OPTIONS")).thenReturn(secure().nextAlphanumeric(2)); new EsSettings(props, new EsInstallation(props), system); assertThat(listAppender.getLogs()) @@ -122,11 +122,11 @@ public class EsSettingsTest { private Props minimalProps() { Props props = new Props(new Properties()); - props.set(PATH_HOME.getKey(), randomAlphanumeric(12)); - props.set(PATH_DATA.getKey(), randomAlphanumeric(12)); - props.set(PATH_TEMP.getKey(), randomAlphanumeric(12)); - props.set(PATH_LOGS.getKey(), randomAlphanumeric(12)); - props.set(CLUSTER_NAME.getKey(), randomAlphanumeric(12)); + props.set(PATH_HOME.getKey(), secure().nextAlphanumeric(12)); + props.set(PATH_DATA.getKey(), secure().nextAlphanumeric(12)); + props.set(PATH_TEMP.getKey(), secure().nextAlphanumeric(12)); + props.set(PATH_LOGS.getKey(), secure().nextAlphanumeric(12)); + props.set(CLUSTER_NAME.getKey(), secure().nextAlphanumeric(12)); return props; } diff --git a/server/sonar-process/src/test/java/org/sonar/process/NetworkUtilsImplTest.java b/server/sonar-process/src/test/java/org/sonar/process/NetworkUtilsImplTest.java index d9d22a09d03..fee3eb21507 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/NetworkUtilsImplTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/NetworkUtilsImplTest.java @@ -29,7 +29,7 @@ import java.util.Set; import org.hamcrest.CoreMatchers; import org.junit.Test; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeThat; @@ -110,7 +110,7 @@ public class NetworkUtilsImplTest { @Test public void toInetAddress_returns_empty_on_unvalid_IP_and_hostname() { - assertThat(underTest.toInetAddress(randomAlphabetic(32))).isEmpty(); + assertThat(underTest.toInetAddress(secure().nextAlphabetic(32))).isEmpty(); } @Test diff --git a/server/sonar-process/src/test/java/org/sonar/process/PropsTest.java b/server/sonar-process/src/test/java/org/sonar/process/PropsTest.java index bed9daa475f..e271ae24d25 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/PropsTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/PropsTest.java @@ -45,8 +45,8 @@ public class PropsTest { @UseDataProvider("beforeAndAfterBlanks") public void constructor_trims_key_and_values_from_Properties_argument(String blankBefore, String blankAfter) { Properties properties = new Properties(); - String key = RandomStringUtils.randomAlphanumeric(3); - String value = RandomStringUtils.randomAlphanumeric(3); + String key = RandomStringUtils.secure().nextAlphanumeric(3); + String value = RandomStringUtils.secure().nextAlphanumeric(3); properties.put(blankBefore + key + blankAfter, blankBefore + value + blankAfter); Props underTest = new Props(properties); diff --git a/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeDetailsTest.java b/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeDetailsTest.java index 83be9bcb570..afcae5f8ffe 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeDetailsTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeDetailsTest.java @@ -25,7 +25,7 @@ import java.io.ObjectInputStream; import java.util.Random; import org.junit.Test; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.process.cluster.health.NodeDetails.newNodeDetailsBuilder; @@ -121,7 +121,7 @@ public class NodeDetailsTest { public void build_throws_NPE_if_host_is_null() { builderUnderTest .setType(randomType) - .setName(randomAlphanumeric(2)); + .setName(secure().nextAlphanumeric(2)); assertThatThrownBy(() -> builderUnderTest.build()) .isInstanceOf(NullPointerException.class) @@ -132,8 +132,8 @@ public class NodeDetailsTest { public void build_throws_IAE_if_setPort_not_called() { builderUnderTest .setType(randomType) - .setName(randomAlphanumeric(2)) - .setHost(randomAlphanumeric(3)); + .setName(secure().nextAlphanumeric(2)) + .setHost(secure().nextAlphanumeric(3)); assertThatThrownBy(() -> builderUnderTest.build()) .isInstanceOf(IllegalArgumentException.class) @@ -144,8 +144,8 @@ public class NodeDetailsTest { public void build_throws_IAE_if_setStarted_not_called() { builderUnderTest .setType(randomType) - .setName(randomAlphanumeric(2)) - .setHost(randomAlphanumeric(3)) + .setName(secure().nextAlphanumeric(2)) + .setHost(secure().nextAlphanumeric(3)) .setPort(1 + random.nextInt(33)); assertThatThrownBy(() -> builderUnderTest.build()) @@ -190,8 +190,8 @@ public class NodeDetailsTest { @Test public void verify_toString() { - String name = randomAlphanumeric(3); - String host = randomAlphanumeric(10); + String name = secure().nextAlphanumeric(3); + String host = secure().nextAlphanumeric(10); int port = 1 + random.nextInt(10); long startedAt = 1 + random.nextInt(666); @@ -209,8 +209,8 @@ public class NodeDetailsTest { @Test public void verify_getters() { - String name = randomAlphanumeric(3); - String host = randomAlphanumeric(10); + String name = secure().nextAlphanumeric(3); + String host = secure().nextAlphanumeric(10); int port = 1 + random.nextInt(10); long startedAt = 1 + random.nextInt(666); diff --git a/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeDetailsTestSupport.java b/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeDetailsTestSupport.java index 191b10bf346..b1da9f7cea3 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeDetailsTestSupport.java +++ b/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeDetailsTestSupport.java @@ -25,7 +25,7 @@ import java.io.ObjectOutputStream; import java.util.Random; import java.util.stream.IntStream; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.sonar.process.cluster.health.NodeDetails.newNodeDetailsBuilder; import static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder; @@ -56,7 +56,7 @@ public class NodeDetailsTestSupport { NodeHealth.Builder builder = newNodeHealthBuilder() .setStatus(randomStatus()) .setDetails(randomNodeDetails()); - IntStream.range(0, minCauseCount + random.nextInt(2)).mapToObj(i -> randomAlphanumeric(4)).forEach(builder::addCause); + IntStream.range(0, minCauseCount + random.nextInt(2)).mapToObj(i -> secure().nextAlphanumeric(4)).forEach(builder::addCause); return builder; } @@ -68,8 +68,8 @@ public class NodeDetailsTestSupport { NodeDetails.Builder randomNodeDetailsBuilder() { return newNodeDetailsBuilder() .setType(randomType()) - .setName(randomAlphanumeric(3)) - .setHost(randomAlphanumeric(10)) + .setName(secure().nextAlphanumeric(3)) + .setHost(secure().nextAlphanumeric(10)) .setPort(1 + random.nextInt(10)) .setStartedAt(1 + random.nextInt(666)); } diff --git a/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeHealthTest.java b/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeHealthTest.java index 129b9b72812..f098069944d 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeHealthTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeHealthTest.java @@ -27,7 +27,7 @@ import java.util.Random; import java.util.stream.IntStream; import org.junit.Test; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder; @@ -73,7 +73,7 @@ public class NodeHealthTest { public void clearClauses_clears_clauses_of_builder() { NodeHealth.Builder underTest = testSupport.randomBuilder(); NodeHealth original = underTest - .addCause(randomAlphanumeric(3)) + .addCause(secure().nextAlphanumeric(3)) .build(); underTest.clearCauses(); @@ -96,7 +96,7 @@ public class NodeHealthTest { .clearCauses() .setStatus(newRandomStatus) .setDetails(newNodeDetails); - String[] newCauses = IntStream.range(0, 1 + random.nextInt(2)).mapToObj(i -> randomAlphanumeric(4)).toArray(String[]::new); + String[] newCauses = IntStream.range(0, 1 + random.nextInt(2)).mapToObj(i -> secure().nextAlphanumeric(4)).toArray(String[]::new); Arrays.stream(newCauses).forEach(builder::addCause); NodeHealth newNodeHealth = builder.build(); @@ -158,7 +158,7 @@ public class NodeHealthTest { @Test public void verify_toString() { NodeDetails nodeDetails = testSupport.randomNodeDetails(); - String cause = randomAlphanumeric(4); + String cause = secure().nextAlphanumeric(4); NodeHealth.Builder builder = builderUnderTest .setStatus(randomStatus) .setDetails(nodeDetails) @@ -176,7 +176,7 @@ public class NodeHealthTest { NodeHealth.Builder builder = builderUnderTest .setStatus(randomStatus) .setDetails(nodeDetails); - String[] causes = IntStream.range(0, random.nextInt(10)).mapToObj(i -> randomAlphanumeric(4)).toArray(String[]::new); + String[] causes = IntStream.range(0, random.nextInt(10)).mapToObj(i -> secure().nextAlphanumeric(4)).toArray(String[]::new); Arrays.stream(causes).forEach(builder::addCause); NodeHealth underTest = builder.build(); diff --git a/server/sonar-process/src/test/java/org/sonar/process/cluster/health/SharedHealthStateImplTest.java b/server/sonar-process/src/test/java/org/sonar/process/cluster/health/SharedHealthStateImplTest.java index 00e60860b77..85f151bce87 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/cluster/health/SharedHealthStateImplTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/cluster/health/SharedHealthStateImplTest.java @@ -32,7 +32,7 @@ import org.sonar.process.LoggingRule; import org.sonar.process.cluster.hz.HazelcastMember; import static java.util.Collections.singleton; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.doReturn; @@ -83,7 +83,7 @@ public class SharedHealthStateImplTest { logging.setLevel(Level.TRACE); NodeHealth newNodeHealth = randomNodeHealth(); Map map = new HashMap<>(); - map.put(randomAlphanumeric(4), new TimestampedNodeHealth(randomNodeHealth(), random.nextLong())); + map.put(secure().nextAlphanumeric(4), new TimestampedNodeHealth(randomNodeHealth(), random.nextLong())); doReturn(new HashMap<>(map)).when(hazelcastMember).getReplicatedMap(MAP_SQ_HEALTH_STATE); UUID uuid = UUID.randomUUID(); when(hazelcastMember.getUuid()).thenReturn(uuid); @@ -165,8 +165,8 @@ public class SharedHealthStateImplTest { public void readAll_logs_message_for_each_non_existing_member_ignored_if_TRACE() { logging.setLevel(Level.TRACE); Map map = new HashMap<>(); - String memberUuid1 = randomAlphanumeric(44); - String memberUuid2 = randomAlphanumeric(44); + String memberUuid1 = secure().nextAlphanumeric(44); + String memberUuid2 = secure().nextAlphanumeric(44); map.put(memberUuid1, new TimestampedNodeHealth(randomNodeHealth(), clusterTime - 1)); map.put(memberUuid2, new TimestampedNodeHealth(randomNodeHealth(), clusterTime - 1)); when(hazelcastMember.getClusterTime()).thenReturn(clusterTime); @@ -238,8 +238,8 @@ public class SharedHealthStateImplTest { .setStatus(NodeHealth.Status.values()[random.nextInt(NodeHealth.Status.values().length)]) .setDetails(newNodeDetailsBuilder() .setType(random.nextBoolean() ? NodeDetails.Type.SEARCH : NodeDetails.Type.APPLICATION) - .setName(randomAlphanumeric(30)) - .setHost(randomAlphanumeric(10)) + .setName(secure().nextAlphanumeric(30)) + .setHost(secure().nextAlphanumeric(10)) .setPort(1 + random.nextInt(666)) .setStartedAt(1 + random.nextInt(852)) .build()) diff --git a/server/sonar-process/src/test/java/org/sonar/process/logging/Log4JPropertiesBuilderTest.java b/server/sonar-process/src/test/java/org/sonar/process/logging/Log4JPropertiesBuilderTest.java index eda1a1708fa..084169a70ee 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/logging/Log4JPropertiesBuilderTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/logging/Log4JPropertiesBuilderTest.java @@ -39,7 +39,7 @@ import org.sonar.process.ProcessId; import org.sonar.process.Props; import static java.lang.String.valueOf; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertThrows; @@ -65,7 +65,7 @@ public class Log4JPropertiesBuilderTest { @Test public void constructor_sets_status_to_ERROR() throws IOException { File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); Properties properties = newLog4JPropertiesBuilder().rootLoggerConfig(esRootLoggerConfig).logDir(logDir).logPattern(logPattern).build(); assertThat(properties.getProperty("status")).isEqualTo("ERROR"); @@ -79,7 +79,7 @@ public class Log4JPropertiesBuilderTest { @Test public void get_always_returns_a_new_object() throws IOException { File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); Properties previous = newLog4JPropertiesBuilder().rootLoggerConfig(esRootLoggerConfig).logDir(logDir).logPattern(logPattern).build(); for (int i = 0; i < 2 + new Random().nextInt(5); i++) { @@ -100,7 +100,7 @@ public class Log4JPropertiesBuilderTest { @Test public void buildLogPattern_puts_threadIdFieldPattern_from_RootLoggerConfig_non_null() { - String threadIdFieldPattern = RandomStringUtils.randomAlphabetic(5); + String threadIdFieldPattern = RandomStringUtils.secure().nextAlphabetic(5); String pattern = newLog4JPropertiesBuilder().buildLogPattern( newRootLoggerConfigBuilder() @@ -135,7 +135,7 @@ public class Log4JPropertiesBuilderTest { @Test public void configureGlobalFileLog_sets_properties_for_daily_time_rolling_policy_with_max_7_files_for_empty_props() throws Exception { File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); var underTest = newLog4JPropertiesBuilder() .rootLoggerConfig(esRootLoggerConfig) .logDir(logDir) @@ -209,8 +209,8 @@ public class Log4JPropertiesBuilderTest { @Test public void configureGlobalFileLog_throws_MessageException_when_property_is_not_supported() throws Exception { File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); - String invalidPropertyValue = randomAlphanumeric(3); + String logPattern = secure().nextAlphanumeric(15); + String invalidPropertyValue = secure().nextAlphanumeric(3); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder( ROLLING_POLICY_PROPERTY, invalidPropertyValue) .rootLoggerConfig(esRootLoggerConfig) @@ -225,8 +225,8 @@ public class Log4JPropertiesBuilderTest { @Test public void configureGlobalFileLog_sets_properties_for_time_rolling_policy_with_max_7_files_when_property_starts_with_time_colon() throws Exception { File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); - String timePattern = randomAlphanumeric(6); + String logPattern = secure().nextAlphanumeric(15); + String timePattern = secure().nextAlphanumeric(6); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder( ROLLING_POLICY_PROPERTY, "time:" + timePattern) @@ -240,8 +240,8 @@ public class Log4JPropertiesBuilderTest { @Test public void configureGlobalFileLog_sets_properties_for_time_rolling_policy_when_property_starts_with_time_colon_and_specified_max_number_of_files() throws Exception { File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); - String timePattern = randomAlphanumeric(6); + String logPattern = secure().nextAlphanumeric(15); + String timePattern = secure().nextAlphanumeric(6); int maxFile = 1 + new Random().nextInt(10); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder( @@ -257,8 +257,8 @@ public class Log4JPropertiesBuilderTest { @Test public void configureGlobalFileLog_sets_properties_for_size_rolling_policy_with_max_7_files_when_property_starts_with_size_colon() throws Exception { File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); - String sizePattern = randomAlphanumeric(6); + String logPattern = secure().nextAlphanumeric(15); + String sizePattern = secure().nextAlphanumeric(6); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder( ROLLING_POLICY_PROPERTY, "size:" + sizePattern) .rootLoggerConfig(esRootLoggerConfig) @@ -271,8 +271,8 @@ public class Log4JPropertiesBuilderTest { @Test public void configureGlobalFileLog_sets_properties_for_size_rolling_policy_when_property_starts_with_size_colon_and_specified_max_number_of_files() throws Exception { File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); - String sizePattern = randomAlphanumeric(6); + String logPattern = secure().nextAlphanumeric(15); + String sizePattern = secure().nextAlphanumeric(6); int maxFile = 1 + new Random().nextInt(10); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder( ROLLING_POLICY_PROPERTY, "size:" + sizePattern, @@ -287,7 +287,7 @@ public class Log4JPropertiesBuilderTest { @Test public void configureGlobalFileLog_sets_properties_for_no_rolling_policy_when_property_is_none() throws Exception { File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder( ROLLING_POLICY_PROPERTY, "none") .rootLoggerConfig(esRootLoggerConfig) @@ -306,7 +306,7 @@ public class Log4JPropertiesBuilderTest { @Test public void enable_all_logs_to_stdout_write_additionally_Console_appender() throws IOException { File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder(ROLLING_POLICY_PROPERTY, "none") .enableAllLogsToConsole(true) @@ -384,9 +384,9 @@ public class Log4JPropertiesBuilderTest { @Test public void apply_fails_with_IAE_if_LogLevelConfig_does_not_have_rootLoggerName_of_Log4J() throws IOException { - LogLevelConfig logLevelConfig = LogLevelConfig.newBuilder(randomAlphanumeric(2)).build(); + LogLevelConfig logLevelConfig = LogLevelConfig.newBuilder(secure().nextAlphanumeric(2)).build(); File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder() .rootLoggerConfig(esRootLoggerConfig) @@ -403,7 +403,7 @@ public class Log4JPropertiesBuilderTest { public void apply_fails_with_IAE_if_global_property_has_unsupported_level() throws IOException { LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build(); File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level", "ERROR") .rootLoggerConfig(esRootLoggerConfig) @@ -420,7 +420,7 @@ public class Log4JPropertiesBuilderTest { public void apply_fails_with_IAE_if_process_property_has_unsupported_level() throws IOException { LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build(); File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level.web", "ERROR") .rootLoggerConfig(esRootLoggerConfig) @@ -437,7 +437,7 @@ public class Log4JPropertiesBuilderTest { public void apply_sets_root_logger_to_INFO_if_no_property_is_set() throws IOException { LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build(); File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder() .rootLoggerConfig(esRootLoggerConfig) @@ -454,7 +454,7 @@ public class Log4JPropertiesBuilderTest { public void apply_sets_root_logger_to_global_property_if_set() throws IOException { LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build(); File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level", "TRACE") .rootLoggerConfig(esRootLoggerConfig) @@ -469,7 +469,7 @@ public class Log4JPropertiesBuilderTest { public void apply_sets_root_logger_to_process_property_if_set() throws IOException { LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build(); File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level.web", "DEBUG") .rootLoggerConfig(esRootLoggerConfig) @@ -484,7 +484,7 @@ public class Log4JPropertiesBuilderTest { public void apply_sets_root_logger_to_process_property_over_global_property_if_both_set() throws IOException { LogLevelConfig config = newLogLevelConfig().rootLevelFor(ProcessId.WEB_SERVER).build(); File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level", "DEBUG", "sonar.log.level.web", "TRACE") @@ -500,7 +500,7 @@ public class Log4JPropertiesBuilderTest { public void apply_sets_domain_property_over_process_and_global_property_if_all_set() throws IOException { LogLevelConfig config = newLogLevelConfig().levelByDomain("foo", ProcessId.WEB_SERVER, LogDomain.ES).build(); File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder( "sonar.log.level", "DEBUG", @@ -518,7 +518,7 @@ public class Log4JPropertiesBuilderTest { public void apply_sets_domain_property_over_process_property_if_both_set() throws IOException { LogLevelConfig config = newLogLevelConfig().levelByDomain("foo", ProcessId.WEB_SERVER, LogDomain.ES).build(); File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder( "sonar.log.level.web", "DEBUG", @@ -535,7 +535,7 @@ public class Log4JPropertiesBuilderTest { public void apply_sets_domain_property_over_global_property_if_both_set() throws IOException { LogLevelConfig config = newLogLevelConfig().levelByDomain("foo", ProcessId.WEB_SERVER, LogDomain.ES).build(); File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder( "sonar.log.level", "DEBUG", @@ -551,7 +551,7 @@ public class Log4JPropertiesBuilderTest { @Test public void apply_fails_with_IAE_if_domain_property_has_unsupported_level() throws IOException { File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); LogLevelConfig config = newLogLevelConfig().levelByDomain("foo", ProcessId.WEB_SERVER, LogDomain.JMX).build(); @@ -571,7 +571,7 @@ public class Log4JPropertiesBuilderTest { public void apply_accepts_any_level_as_hardcoded_level(Level level) throws IOException { LogLevelConfig config = newLogLevelConfig().immutableLevel("bar", level).build(); File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder() .rootLoggerConfig(esRootLoggerConfig) @@ -585,7 +585,7 @@ public class Log4JPropertiesBuilderTest { @Test public void apply_set_level_to_OFF_if_sonar_global_level_is_not_set() throws IOException { File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder() .rootLoggerConfig(esRootLoggerConfig) @@ -637,7 +637,7 @@ public class Log4JPropertiesBuilderTest { public void apply_does_not_create_loggers_property_if_only_root_level_is_defined() throws IOException { LogLevelConfig logLevelConfig = newLogLevelConfig().rootLevelFor(ProcessId.APP).build(); File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder() .rootLoggerConfig(esRootLoggerConfig) @@ -660,7 +660,7 @@ public class Log4JPropertiesBuilderTest { .build(); File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder() .rootLoggerConfig(esRootLoggerConfig) @@ -674,7 +674,7 @@ public class Log4JPropertiesBuilderTest { @Test public void apply_does_not_set_level_if_sonar_global_level_is_TRACE() throws IOException { File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level", Level.TRACE.toString()) .rootLoggerConfig(esRootLoggerConfig) @@ -687,7 +687,7 @@ public class Log4JPropertiesBuilderTest { private void setLevelToOff(Level globalLogLevel) throws IOException { File logDir = temporaryFolder.newFolder(); - String logPattern = randomAlphanumeric(15); + String logPattern = secure().nextAlphanumeric(15); Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder("sonar.log.level", globalLogLevel.toString()) .rootLoggerConfig(esRootLoggerConfig) diff --git a/server/sonar-process/src/test/java/org/sonar/process/logging/LogLevelConfigTest.java b/server/sonar-process/src/test/java/org/sonar/process/logging/LogLevelConfigTest.java index df79c5b4d8e..4f1a23c04e7 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/logging/LogLevelConfigTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/logging/LogLevelConfigTest.java @@ -32,7 +32,7 @@ import static org.sonar.process.logging.LogLevelConfig.newBuilder; public class LogLevelConfigTest { - private final String rootLoggerName = RandomStringUtils.randomAlphabetic(20); + private final String rootLoggerName = RandomStringUtils.secure().nextAlphabetic(20); private LogLevelConfig.Builder underTest = newBuilder(rootLoggerName); @Test @@ -44,7 +44,7 @@ public class LogLevelConfigTest { @Test public void getLoggerName_returns_name_passed_to_builder() { - String rootLoggerName = RandomStringUtils.randomAlphabetic(32); + String rootLoggerName = RandomStringUtils.secure().nextAlphabetic(32); LogLevelConfig logLevelConfig = newBuilder(rootLoggerName).build(); diff --git a/server/sonar-process/src/test/java/org/sonar/process/logging/LogbackHelperTest.java b/server/sonar-process/src/test/java/org/sonar/process/logging/LogbackHelperTest.java index 7cd6f7eb572..d807d723b7c 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/logging/LogbackHelperTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/logging/LogbackHelperTest.java @@ -56,7 +56,7 @@ import org.sonar.process.ProcessId; import org.sonar.process.Props; import static java.util.stream.Collectors.toList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; @@ -111,7 +111,7 @@ public class LogbackHelperTest { @Test public void buildLogPattern_puts_threadIdFieldPattern_from_RootLoggerConfig_non_null() { - String threadIdFieldPattern = RandomStringUtils.randomAlphabetic(5); + String threadIdFieldPattern = RandomStringUtils.secure().nextAlphabetic(5); String pattern = underTest.buildLogPattern( newRootLoggerConfigBuilder() .setProcessId(ProcessId.APP) @@ -305,7 +305,7 @@ public class LogbackHelperTest { @Test public void apply_fails_with_IAE_if_LogLevelConfig_does_not_have_ROOT_LOGGER_NAME_of_LogBack() { - LogLevelConfig logLevelConfig = LogLevelConfig.newBuilder(randomAlphanumeric(2)).build(); + LogLevelConfig logLevelConfig = LogLevelConfig.newBuilder(secure().nextAlphanumeric(2)).build(); assertThatThrownBy(() -> underTest.apply(logLevelConfig, props)) .isInstanceOf(IllegalArgumentException.class) diff --git a/server/sonar-server-common/src/it/java/org/sonar/server/es/metadata/MetadataIndexIT.java b/server/sonar-server-common/src/it/java/org/sonar/server/es/metadata/MetadataIndexIT.java index 65965230587..9e20502abf6 100644 --- a/server/sonar-server-common/src/it/java/org/sonar/server/es/metadata/MetadataIndexIT.java +++ b/server/sonar-server-common/src/it/java/org/sonar/server/es/metadata/MetadataIndexIT.java @@ -33,8 +33,7 @@ import org.sonar.server.es.IndexType; import org.sonar.server.es.IndexType.IndexMainType; import org.sonar.server.es.newindex.FakeIndexDefinition; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; @RunWith(DataProviderRunner.class) @@ -43,7 +42,7 @@ public class MetadataIndexIT { @Rule public EsTester es = EsTester.createCustom(new MetadataIndexDefinitionBridge(), new FakeIndexDefinition()); private final MetadataIndex underTest = new MetadataIndexImpl(es.client()); - private final String indexName = randomAlphabetic(20).toLowerCase(Locale.ENGLISH); + private final String indexName = secure().nextAlphabetic(20).toLowerCase(Locale.ENGLISH); private final Index index = new Random().nextBoolean() ? Index.simple(indexName) : Index.withRelations(indexName); @Test @@ -76,7 +75,7 @@ public class MetadataIndexIT { @Test public void hash_should_be_able_to_be_automatically_set() { - String hash = randomAlphanumeric(20); + String hash = secure().nextAlphanumeric(20); underTest.setHash(index, hash); assertThat(underTest.getHash(index)).hasValue(hash); } diff --git a/server/sonar-server-common/src/it/java/org/sonar/server/issue/notification/NewIssuesNotificationIT.java b/server/sonar-server-common/src/it/java/org/sonar/server/issue/notification/NewIssuesNotificationIT.java index 5677a893c6c..9d140f1f525 100644 --- a/server/sonar-server-common/src/it/java/org/sonar/server/issue/notification/NewIssuesNotificationIT.java +++ b/server/sonar-server-common/src/it/java/org/sonar/server/issue/notification/NewIssuesNotificationIT.java @@ -35,8 +35,7 @@ import org.sonar.server.issue.notification.NewIssuesNotification.RuleDefinition; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -87,7 +86,7 @@ public class NewIssuesNotificationIT { @Test public void set_project_version() { - String version = randomAlphanumeric(5); + String version = secure().nextAlphanumeric(5); underTest.setProjectVersion(version); @@ -108,10 +107,10 @@ public class NewIssuesNotificationIT { @Test public void getProjectKey_returns_projectKey_if_setProject_has_been_called() { - String projectKey = randomAlphabetic(5); - String projectName = randomAlphabetic(6); - String branchName = randomAlphabetic(7); - String pullRequest = randomAlphabetic(8); + String projectKey = secure().nextAlphabetic(5); + String projectName = secure().nextAlphabetic(6); + String branchName = secure().nextAlphabetic(7); + String pullRequest = secure().nextAlphabetic(8); underTest.setProject(projectKey, projectName, branchName, pullRequest); assertThat(underTest.getProjectKey()).isEqualTo(projectKey); @@ -119,7 +118,7 @@ public class NewIssuesNotificationIT { @Test public void getProjectKey_returns_value_of_field_projectKey() { - String projectKey = randomAlphabetic(5); + String projectKey = secure().nextAlphabetic(5); underTest.setFieldValue("projectKey", projectKey); assertThat(underTest.getProjectKey()).isEqualTo(projectKey); @@ -421,16 +420,16 @@ public class NewIssuesNotificationIT { @Test public void RuleDefinition_implements_equals_base_on_name_and_language() { - String name = randomAlphabetic(5); - String language = randomAlphabetic(6); + String name = secure().nextAlphabetic(5); + String language = secure().nextAlphabetic(6); RuleDefinition underTest = new RuleDefinition(name, language); assertThat(underTest) .isEqualTo(underTest) .isEqualTo(new RuleDefinition(name, language)) .isNotEqualTo(new RuleDefinition(language, name)) - .isNotEqualTo(new RuleDefinition(randomAlphabetic(7), name)) - .isNotEqualTo(new RuleDefinition(language, randomAlphabetic(7))) + .isNotEqualTo(new RuleDefinition(secure().nextAlphabetic(7), name)) + .isNotEqualTo(new RuleDefinition(language, secure().nextAlphabetic(7))) .isNotEqualTo(new RuleDefinition(language, null)) .isNotNull() .isNotEqualTo(new Object()); @@ -438,8 +437,8 @@ public class NewIssuesNotificationIT { @Test public void RuleDefinition_implements_hashcode_base_on_name_and_language() { - String name = randomAlphabetic(5); - String language = randomAlphabetic(6); + String name = secure().nextAlphabetic(5); + String language = secure().nextAlphabetic(6); RuleDefinition underTest = new RuleDefinition(name, language); assertThat(underTest) @@ -448,8 +447,8 @@ public class NewIssuesNotificationIT { assertThat(underTest.hashCode()) .isNotEqualTo(new RuleDefinition(language, name).hashCode()) - .isNotEqualTo(new RuleDefinition(randomAlphabetic(7), name).hashCode()) - .isNotEqualTo(new RuleDefinition(language, randomAlphabetic(7)).hashCode()) + .isNotEqualTo(new RuleDefinition(secure().nextAlphabetic(7), name).hashCode()) + .isNotEqualTo(new RuleDefinition(language, secure().nextAlphabetic(7)).hashCode()) .isNotEqualTo(new RuleDefinition(language, null).hashCode()) .isNotEqualTo(new Object().hashCode()); } diff --git a/server/sonar-server-common/src/it/java/org/sonar/server/rule/DefaultRuleFinderIT.java b/server/sonar-server-common/src/it/java/org/sonar/server/rule/DefaultRuleFinderIT.java index 4ff697978d2..7f231384e45 100644 --- a/server/sonar-server-common/src/it/java/org/sonar/server/rule/DefaultRuleFinderIT.java +++ b/server/sonar-server-common/src/it/java/org/sonar/server/rule/DefaultRuleFinderIT.java @@ -36,7 +36,7 @@ import org.sonar.db.rule.RuleDto.Scope; import org.sonar.db.rule.RuleParamDto; import static java.util.Collections.emptySet; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; @@ -154,7 +154,7 @@ public class DefaultRuleFinderIT { @Test public void findByKey_populates_system_tags_but_not_tags() { RuleDto ruleDto = dbTester.rules() - .insert(t -> t.setSystemTags(Set.of(randomAlphanumeric(5), randomAlphanumeric(6))).setTags(emptySet())); + .insert(t -> t.setSystemTags(Set.of(secure().nextAlphanumeric(5), secure().nextAlphanumeric(6))).setTags(emptySet())); dbTester.rules().insertRule(); Rule rule = underTest.findByKey(ruleDto.getKey()); diff --git a/server/sonar-server-common/src/it/java/org/sonar/server/rule/index/RuleIndexerIT.java b/server/sonar-server-common/src/it/java/org/sonar/server/rule/index/RuleIndexerIT.java index 8d499b45360..9704c193a77 100644 --- a/server/sonar-server-common/src/it/java/org/sonar/server/rule/index/RuleIndexerIT.java +++ b/server/sonar-server-common/src/it/java/org/sonar/server/rule/index/RuleIndexerIT.java @@ -52,7 +52,7 @@ import static java.lang.String.format; import static java.util.Collections.emptyList; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toSet; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection; import static org.sonar.db.rule.RuleTesting.newRule; @@ -136,7 +136,7 @@ public class RuleIndexerIT { @Test public void index_long_rule_description() { - RuleDescriptionSectionDto ruleDescriptionSectionDto = createDefaultRuleDescriptionSection(uuidFactory.create(), randomAlphanumeric(100000)); + RuleDescriptionSectionDto ruleDescriptionSectionDto = createDefaultRuleDescriptionSection(uuidFactory.create(), secure().nextAlphanumeric(100000)); RuleDto rule = dbTester.rules().insert(newRule(ruleDescriptionSectionDto)); underTest.commitAndIndex(dbTester.getSession(), rule.getUuid()); diff --git a/server/sonar-server-common/src/it/java/org/sonar/server/webhook/WebhookDeliveryStorageIT.java b/server/sonar-server-common/src/it/java/org/sonar/server/webhook/WebhookDeliveryStorageIT.java index cc0210de254..c031ddd935e 100644 --- a/server/sonar-server-common/src/it/java/org/sonar/server/webhook/WebhookDeliveryStorageIT.java +++ b/server/sonar-server-common/src/it/java/org/sonar/server/webhook/WebhookDeliveryStorageIT.java @@ -31,7 +31,7 @@ import org.sonar.db.DbTester; import org.sonar.db.webhook.WebhookDeliveryDto; import org.sonar.db.webhook.WebhookDeliveryTesting; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -105,7 +105,7 @@ public class WebhookDeliveryStorageIT { @Test public void persist_effective_url_if_present() { when(uuidFactory.create()).thenReturn(DELIVERY_UUID); - String effectiveUrl = randomAlphabetic(15); + String effectiveUrl = secure().nextAlphabetic(15); WebhookDelivery delivery = newBuilderTemplate() .setEffectiveUrl(effectiveUrl) .build(); @@ -118,7 +118,7 @@ public class WebhookDeliveryStorageIT { private static WebhookDelivery.Builder newBuilderTemplate() { return new WebhookDelivery.Builder() - .setWebhook(new Webhook("WEBHOOK_UUID_1", "COMPONENT1", "TASK1", RandomStringUtils.randomAlphanumeric(40),"Jenkins", "http://jenkins", null)) + .setWebhook(new Webhook("WEBHOOK_UUID_1", "COMPONENT1", "TASK1", RandomStringUtils.secure().nextAlphanumeric(40),"Jenkins", "http://jenkins", null)) .setPayload(new WebhookPayload("my-project", "{json}")) .setAt(1_000_000L) .setHttpStatus(200) diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/config/ConfigurationProviderTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/config/ConfigurationProviderTest.java index d7e52cec8b8..f1a5e31c730 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/config/ConfigurationProviderTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/config/ConfigurationProviderTest.java @@ -36,9 +36,9 @@ import static org.sonar.api.config.PropertyDefinition.builder; @RunWith(DataProviderRunner.class) public class ConfigurationProviderTest { private static final String[] EMPTY_STRING_ARRAY = {}; - private final String nonDeclaredKey = RandomStringUtils.randomAlphabetic(3); - private final String nonMultivalueKey = RandomStringUtils.randomAlphabetic(3); - private final String multivalueKey = RandomStringUtils.randomAlphabetic(3); + private final String nonDeclaredKey = RandomStringUtils.secure().nextAlphabetic(3); + private final String nonMultivalueKey = RandomStringUtils.secure().nextAlphabetic(3); + private final String multivalueKey = RandomStringUtils.secure().nextAlphabetic(3); private final MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, builder(nonMultivalueKey).multiValues(false).build(), builder(multivalueKey).multiValues(true).build())); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/DocIdTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/DocIdTest.java index 1f7b898deee..a7f9d9064b5 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/DocIdTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/DocIdTest.java @@ -21,43 +21,43 @@ package org.sonar.server.es; import org.junit.Test; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; public class DocIdTest { @Test public void equals_is_based_on_index_type_and_id() { - String index = randomAlphabetic(5); - String type = randomAlphabetic(6); - String id = randomAlphabetic(7); + String index = secure().nextAlphabetic(5); + String type = secure().nextAlphabetic(6); + String id = secure().nextAlphabetic(7); DocId underTest = new DocId(index, type, id); assertThat(underTest) .isEqualTo(new DocId(index, type, id)) - .isNotEqualTo(new DocId(randomAlphabetic(7), type, id)) - .isNotEqualTo(new DocId(index, type, randomAlphabetic(7))) - .isNotEqualTo(new DocId(index, randomAlphabetic(7), id)) - .isNotEqualTo(new DocId(randomAlphabetic(7), randomAlphabetic(8), id)) - .isNotEqualTo(new DocId(randomAlphabetic(7), type, randomAlphabetic(8))) - .isNotEqualTo(new DocId(index, randomAlphabetic(7), randomAlphabetic(8))) - .isNotEqualTo(new DocId(randomAlphabetic(7), randomAlphabetic(8), randomAlphabetic(9))); + .isNotEqualTo(new DocId(secure().nextAlphabetic(7), type, id)) + .isNotEqualTo(new DocId(index, type, secure().nextAlphabetic(7))) + .isNotEqualTo(new DocId(index, secure().nextAlphabetic(7), id)) + .isNotEqualTo(new DocId(secure().nextAlphabetic(7), secure().nextAlphabetic(8), id)) + .isNotEqualTo(new DocId(secure().nextAlphabetic(7), type, secure().nextAlphabetic(8))) + .isNotEqualTo(new DocId(index, secure().nextAlphabetic(7), secure().nextAlphabetic(8))) + .isNotEqualTo(new DocId(secure().nextAlphabetic(7), secure().nextAlphabetic(8), secure().nextAlphabetic(9))); } @Test public void hashcode_is_based_on_index_type_and_id() { - String index = randomAlphabetic(5); - String type = randomAlphabetic(6); - String id = randomAlphabetic(7); + String index = secure().nextAlphabetic(5); + String type = secure().nextAlphabetic(6); + String id = secure().nextAlphabetic(7); DocId underTest = new DocId(index, type, id); assertThat(underTest.hashCode()) .isEqualTo(new DocId(index, type, id).hashCode()) - .isNotEqualTo(new DocId(randomAlphabetic(7), type, id).hashCode()) - .isNotEqualTo(new DocId(index, type, randomAlphabetic(7)).hashCode()) - .isNotEqualTo(new DocId(index, randomAlphabetic(7), id).hashCode()) - .isNotEqualTo(new DocId(randomAlphabetic(7), randomAlphabetic(8), id).hashCode()) - .isNotEqualTo(new DocId(randomAlphabetic(7), type, randomAlphabetic(8)).hashCode()) - .isNotEqualTo(new DocId(index, randomAlphabetic(7), randomAlphabetic(8)).hashCode()) - .isNotEqualTo(new DocId(randomAlphabetic(7), randomAlphabetic(8), randomAlphabetic(9)).hashCode()); + .isNotEqualTo(new DocId(secure().nextAlphabetic(7), type, id).hashCode()) + .isNotEqualTo(new DocId(index, type, secure().nextAlphabetic(7)).hashCode()) + .isNotEqualTo(new DocId(index, secure().nextAlphabetic(7), id).hashCode()) + .isNotEqualTo(new DocId(secure().nextAlphabetic(7), secure().nextAlphabetic(8), id).hashCode()) + .isNotEqualTo(new DocId(secure().nextAlphabetic(7), type, secure().nextAlphabetic(8)).hashCode()) + .isNotEqualTo(new DocId(index, secure().nextAlphabetic(7), secure().nextAlphabetic(8)).hashCode()) + .isNotEqualTo(new DocId(secure().nextAlphabetic(7), secure().nextAlphabetic(8), secure().nextAlphabetic(9)).hashCode()); } } diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexDefinitionContextTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexDefinitionContextTest.java index aae40c01e27..7b9caf854d3 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexDefinitionContextTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexDefinitionContextTest.java @@ -28,7 +28,7 @@ import org.junit.runner.RunWith; import org.sonar.api.config.internal.MapSettings; import org.sonar.server.es.newindex.SettingsConfiguration; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder; @@ -62,7 +62,7 @@ public class IndexDefinitionContextTest { @DataProvider public static Object[][] paarOfIndicesWithSameName() { - String indexName = randomAlphabetic(10).toLowerCase(Locale.ENGLISH); + String indexName = secure().nextAlphabetic(10).toLowerCase(Locale.ENGLISH); return new Object[][] { {Index.simple(indexName), Index.simple(indexName)}, {Index.withRelations(indexName), Index.withRelations(indexName)}, diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexTest.java index cb437950e3e..89278ee2b23 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexTest.java @@ -26,7 +26,7 @@ import java.util.Locale; import org.junit.Test; import org.junit.runner.RunWith; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -106,7 +106,7 @@ public class IndexTest { @Test public void getName_returns_constructor_parameter() { - String indexName = randomAlphabetic(10).toLowerCase(Locale.ENGLISH); + String indexName = secure().nextAlphabetic(10).toLowerCase(Locale.ENGLISH); assertThat(Index.simple(indexName).getName()).isEqualTo(indexName); assertThat(Index.withRelations(indexName).getName()).isEqualTo(indexName); @@ -123,7 +123,7 @@ public class IndexTest { @Test public void getJoinField_returns_name_based_on_index_name() { - String indexName = randomAlphabetic(10).toLowerCase(Locale.ENGLISH); + String indexName = secure().nextAlphabetic(10).toLowerCase(Locale.ENGLISH); Index underTest = Index.withRelations(indexName); assertThat(underTest.getJoinField()).isEqualTo("join_" + indexName); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/FieldAwareTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/FieldAwareTest.java index 20bfa8f725c..59eef06c822 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/FieldAwareTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/FieldAwareTest.java @@ -24,7 +24,7 @@ import java.util.function.BiConsumer; import java.util.stream.Stream; import org.junit.Test; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Fail.fail; @@ -47,7 +47,7 @@ public class FieldAwareTest { fieldSetters.forEach(c -> { TestFieldAware underTest = new TestFieldAware(); // should not fail for other field name - c.accept(underTest, randomAlphabetic(1 + new Random().nextInt(10))); + c.accept(underTest, secure().nextAlphabetic(1 + new Random().nextInt(10))); // fails whatever the case Stream.of("indexType", "indextype", "InDexType", "INDEXTYPE") .forEach(illegalFieldName -> { diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewAuthorizedIndexTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewAuthorizedIndexTest.java index a30587ba7dd..1c020a1441a 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewAuthorizedIndexTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewAuthorizedIndexTest.java @@ -27,7 +27,7 @@ import org.sonar.api.config.internal.MapSettings; import org.sonar.server.es.Index; import org.sonar.server.es.IndexType; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; @@ -35,7 +35,7 @@ import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder; public class NewAuthorizedIndexTest { - private String someIndexName = randomAlphabetic(10).toLowerCase(Locale.ENGLISH); + private String someIndexName = secure().nextAlphabetic(10).toLowerCase(Locale.ENGLISH); private Index someIndex = Index.withRelations(someIndexName); private MapSettings settings = new MapSettings(); private SettingsConfiguration defaultSettingsConfiguration = newBuilder(settings.asConfig()).build(); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewIndexTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewIndexTest.java index 6824d572e02..8e33bbc620e 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewIndexTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewIndexTest.java @@ -33,7 +33,7 @@ import org.sonar.server.es.Index; import org.sonar.server.es.IndexType; import org.sonar.server.es.IndexType.IndexMainType; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.data.MapEntry.entry; @@ -45,7 +45,7 @@ import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder; public class NewIndexTest { - private static final String someIndexName = randomAlphabetic(5).toLowerCase(); + private static final String someIndexName = secure().nextAlphabetic(5).toLowerCase(); private MapSettings settings = new MapSettings(); private SettingsConfiguration defaultSettingsConfiguration = newBuilder(settings.asConfig()).build(); @@ -209,7 +209,7 @@ public class NewIndexTest { @DataProvider public static Object[][] indexAndTypeMappings() { - String indexName = randomAlphabetic(5).toLowerCase(); + String indexName = secure().nextAlphabetic(5).toLowerCase(); MapSettings settings = new MapSettings(); SettingsConfiguration defaultSettingsConfiguration = newBuilder(settings.asConfig()).build(); Index index = Index.withRelations(indexName); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewRegularIndexTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewRegularIndexTest.java index 643d0d8fdf2..dd3210cfb8a 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewRegularIndexTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewRegularIndexTest.java @@ -31,7 +31,7 @@ import org.sonar.api.config.internal.MapSettings; import org.sonar.server.es.Index; import org.sonar.server.es.IndexType; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; @@ -42,7 +42,7 @@ import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder; @RunWith(DataProviderRunner.class) public class NewRegularIndexTest { - private static final String SOME_INDEX_NAME = randomAlphabetic(10).toLowerCase(Locale.ENGLISH); + private static final String SOME_INDEX_NAME = secure().nextAlphabetic(10).toLowerCase(Locale.ENGLISH); private MapSettings settings = new MapSettings(); @@ -178,7 +178,7 @@ public class NewRegularIndexTest { @DataProvider public static Object[][] indexes() { - String someIndexName = randomAlphabetic(10).toLowerCase(Locale.ENGLISH); + String someIndexName = secure().nextAlphabetic(10).toLowerCase(Locale.ENGLISH); return new Object[][] { {Index.simple(someIndexName)}, {Index.withRelations(someIndexName)} diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/AllFiltersTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/AllFiltersTest.java index fceb696a323..b6ec64e6e4f 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/AllFiltersTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/AllFiltersTest.java @@ -29,7 +29,7 @@ import org.elasticsearch.index.query.QueryBuilder; import org.junit.Test; import org.sonar.server.es.searchrequest.TopAggregationDefinition.FilterScope; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; @@ -59,7 +59,7 @@ public class AllFiltersTest { @Test public void addFilter_fails_if_fieldname_is_null() { - String name = randomAlphabetic(12); + String name = secure().nextAlphabetic(12); RequestFiltersComputer.AllFilters allFilters = RequestFiltersComputer.newAllFilters(); BoolQueryBuilder boolQuery = boolQuery(); @@ -70,8 +70,8 @@ public class AllFiltersTest { @Test public void addFilter_fails_if_field_with_name_already_exists() { - String name1 = randomAlphabetic(12); - String name2 = randomAlphabetic(15); + String name1 = secure().nextAlphabetic(12); + String name2 = secure().nextAlphabetic(15); FilterScope filterScope1 = mock(FilterScope.class); FilterScope filterScope2 = mock(FilterScope.class); RequestFiltersComputer.AllFilters allFilters = RequestFiltersComputer.newAllFilters(); @@ -89,8 +89,8 @@ public class AllFiltersTest { @Test public void addFilter_does_not_add_filter_if_QueryBuilder_is_null() { - String name = randomAlphabetic(12); - String name2 = randomAlphabetic(14); + String name = secure().nextAlphabetic(12); + String name2 = secure().nextAlphabetic(14); RequestFiltersComputer.AllFilters allFilters = RequestFiltersComputer.newAllFilters(); BoolQueryBuilder query = boolQuery(); allFilters.addFilter(name, mock(FilterScope.class), query) diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/NestedFieldFilterScopeTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/NestedFieldFilterScopeTest.java index 33485e62199..3afa4f7d3a1 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/NestedFieldFilterScopeTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/NestedFieldFilterScopeTest.java @@ -23,15 +23,15 @@ import org.junit.Test; import org.sonar.server.es.searchrequest.TopAggregationDefinition.NestedFieldFilterScope; import org.sonar.server.es.searchrequest.TopAggregationDefinition.SimpleFieldFilterScope; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class NestedFieldFilterScopeTest { @Test public void constructor_fails_with_NPE_if_fieldName_is_null() { - String nestedFieldName = randomAlphabetic(11); - String value = randomAlphabetic(12); + String nestedFieldName = secure().nextAlphabetic(11); + String value = secure().nextAlphabetic(12); assertThatThrownBy(() -> new NestedFieldFilterScope<>(null, nestedFieldName, value)) .isInstanceOf(NullPointerException.class) @@ -40,8 +40,8 @@ public class NestedFieldFilterScopeTest { @Test public void constructor_fails_with_NPE_if_nestedFieldName_is_null() { - String fieldName = randomAlphabetic(10); - String value = randomAlphabetic(12); + String fieldName = secure().nextAlphabetic(10); + String value = secure().nextAlphabetic(12); assertThatThrownBy(() -> new NestedFieldFilterScope<>(fieldName, null, value)) .isInstanceOf(NullPointerException.class) @@ -50,8 +50,8 @@ public class NestedFieldFilterScopeTest { @Test public void constructor_fails_with_NPE_if_value_is_null() { - String fieldName = randomAlphabetic(10); - String nestedFieldName = randomAlphabetic(11); + String fieldName = secure().nextAlphabetic(10); + String nestedFieldName = secure().nextAlphabetic(11); assertThatThrownBy(() -> new NestedFieldFilterScope<>(fieldName, nestedFieldName, null)) .isInstanceOf(NullPointerException.class) @@ -60,8 +60,8 @@ public class NestedFieldFilterScopeTest { @Test public void verify_getters() { - String fieldName = randomAlphabetic(10); - String nestedFieldName = randomAlphabetic(11); + String fieldName = secure().nextAlphabetic(10); + String nestedFieldName = secure().nextAlphabetic(11); Object value = new Object(); NestedFieldFilterScope underTest = new NestedFieldFilterScope<>(fieldName, nestedFieldName, value); @@ -73,11 +73,11 @@ public class NestedFieldFilterScopeTest { @Test public void verify_equals() { - String fieldName = randomAlphabetic(10); - String nestedFieldName = randomAlphabetic(11); + String fieldName = secure().nextAlphabetic(10); + String nestedFieldName = secure().nextAlphabetic(11); Object value = new Object(); - String fieldName2 = randomAlphabetic(12); - String nestedFieldName2 = randomAlphabetic(13); + String fieldName2 = secure().nextAlphabetic(12); + String nestedFieldName2 = secure().nextAlphabetic(13); Object value2 = new Object(); NestedFieldFilterScope underTest = new NestedFieldFilterScope<>(fieldName, nestedFieldName, value); @@ -99,11 +99,11 @@ public class NestedFieldFilterScopeTest { @Test public void verify_hashcode() { - String fieldName = randomAlphabetic(10); - String nestedFieldName = randomAlphabetic(11); + String fieldName = secure().nextAlphabetic(10); + String nestedFieldName = secure().nextAlphabetic(11); Object value = new Object(); - String fieldName2 = randomAlphabetic(12); - String nestedFieldName2 = randomAlphabetic(13); + String fieldName2 = secure().nextAlphabetic(12); + String nestedFieldName2 = secure().nextAlphabetic(13); Object value2 = new Object(); NestedFieldFilterScope underTest = new NestedFieldFilterScope<>(fieldName, nestedFieldName, value); @@ -125,11 +125,11 @@ public class NestedFieldFilterScopeTest { @Test public void verify_intersect() { - String fieldName = randomAlphabetic(10); - String nestedFieldName = randomAlphabetic(11); + String fieldName = secure().nextAlphabetic(10); + String nestedFieldName = secure().nextAlphabetic(11); Object value = new Object(); - String fieldName2 = randomAlphabetic(12); - String nestedFieldName2 = randomAlphabetic(13); + String fieldName2 = secure().nextAlphabetic(12); + String nestedFieldName2 = secure().nextAlphabetic(13); Object value2 = new Object(); NestedFieldFilterScope underTest = new NestedFieldFilterScope<>(fieldName, nestedFieldName, value); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/NestedFieldTopAggregationDefinitionTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/NestedFieldTopAggregationDefinitionTest.java index cb782d720b4..854d432ee85 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/NestedFieldTopAggregationDefinitionTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/NestedFieldTopAggregationDefinitionTest.java @@ -32,7 +32,7 @@ import org.junit.runner.RunWith; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -44,7 +44,7 @@ public class NestedFieldTopAggregationDefinitionTest { @Test @UseDataProvider("notOneLevelDeepPaths") public void constructor_supports_nestedFieldPath_only_one_level_deep(String unsupportedPath) { - String value = randomAlphabetic(7); + String value = secure().nextAlphabetic(7); boolean sticky = RANDOM.nextBoolean(); assertThatThrownBy(() -> new NestedFieldTopAggregationDefinition<>(unsupportedPath, value, sticky)) @@ -68,7 +68,7 @@ public class NestedFieldTopAggregationDefinitionTest { @Test @UseDataProvider("emptyFieldNames") public void constructor_fails_with_IAE_if_empty_field_name(String unsupportedPath, List expectedParsedFieldNames) { - String value = randomAlphabetic(7); + String value = secure().nextAlphabetic(7); assertThatThrownBy(() -> new NestedFieldTopAggregationDefinition<>(unsupportedPath, value, true)) .isInstanceOf(IllegalArgumentException.class) @@ -77,7 +77,7 @@ public class NestedFieldTopAggregationDefinitionTest { @DataProvider public static Object[][] emptyFieldNames() { - String str1 = randomAlphabetic(6); + String str1 = secure().nextAlphabetic(6); return new Object[][] { {".", emptyList()}, {" . ", emptyList()}, @@ -90,9 +90,9 @@ public class NestedFieldTopAggregationDefinitionTest { @Test public void constructor_parses_nested_field_path() { - String fieldName = randomAlphabetic(5); - String nestedFieldName = randomAlphabetic(6); - String value = randomAlphabetic(7); + String fieldName = secure().nextAlphabetic(5); + String nestedFieldName = secure().nextAlphabetic(6); + String value = secure().nextAlphabetic(7); boolean sticky = RANDOM.nextBoolean(); NestedFieldTopAggregationDefinition underTest = new NestedFieldTopAggregationDefinition<>(fieldName + "." + nestedFieldName, value, sticky); @@ -104,7 +104,7 @@ public class NestedFieldTopAggregationDefinitionTest { @Test public void constructor_fails_with_NPE_if_nestedFieldPath_is_null() { - String value = randomAlphabetic(7); + String value = secure().nextAlphabetic(7); boolean sticky = RANDOM.nextBoolean(); assertThatThrownBy(() -> new NestedFieldTopAggregationDefinition<>(null, value, sticky)) @@ -114,7 +114,7 @@ public class NestedFieldTopAggregationDefinitionTest { @Test public void constructor_fails_with_NPE_if_value_is_null() { - String value = randomAlphabetic(7); + String value = secure().nextAlphabetic(7); boolean sticky = RANDOM.nextBoolean(); assertThatThrownBy(() -> new NestedFieldTopAggregationDefinition<>(value, null, sticky)) @@ -124,9 +124,9 @@ public class NestedFieldTopAggregationDefinitionTest { @Test public void getFilterScope_always_returns_the_same_instance() { - String fieldName = randomAlphabetic(5); - String nestedFieldName = randomAlphabetic(6); - String value = randomAlphabetic(7); + String fieldName = secure().nextAlphabetic(5); + String nestedFieldName = secure().nextAlphabetic(6); + String value = secure().nextAlphabetic(7); boolean sticky = RANDOM.nextBoolean(); NestedFieldTopAggregationDefinition underTest = new NestedFieldTopAggregationDefinition<>(fieldName + "." + nestedFieldName, value, sticky); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/SimpleFieldFilterScopeTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/SimpleFieldFilterScopeTest.java index 159097cf72f..5052465b913 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/SimpleFieldFilterScopeTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/SimpleFieldFilterScopeTest.java @@ -23,7 +23,7 @@ import org.junit.Test; import org.sonar.server.es.searchrequest.TopAggregationDefinition.NestedFieldFilterScope; import org.sonar.server.es.searchrequest.TopAggregationDefinition.SimpleFieldFilterScope; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -37,7 +37,7 @@ public class SimpleFieldFilterScopeTest { @Test public void getFieldName() { - String fieldName = randomAlphabetic(12); + String fieldName = secure().nextAlphabetic(12); SimpleFieldFilterScope underTest = new SimpleFieldFilterScope(fieldName); assertThat(underTest.getFieldName()).isEqualTo(fieldName); @@ -45,8 +45,8 @@ public class SimpleFieldFilterScopeTest { @Test public void verify_equals() { - String fieldName1 = randomAlphabetic(11); - String fieldName2 = randomAlphabetic(12); + String fieldName1 = secure().nextAlphabetic(11); + String fieldName2 = secure().nextAlphabetic(12); SimpleFieldFilterScope underTest = new SimpleFieldFilterScope(fieldName1); assertThat(underTest) @@ -61,8 +61,8 @@ public class SimpleFieldFilterScopeTest { @Test public void verify_hashcode() { - String fieldName1 = randomAlphabetic(11); - String fieldName2 = randomAlphabetic(12); + String fieldName1 = secure().nextAlphabetic(11); + String fieldName2 = secure().nextAlphabetic(12); SimpleFieldFilterScope underTest = new SimpleFieldFilterScope(fieldName1); assertThat(underTest.hashCode()) @@ -77,8 +77,8 @@ public class SimpleFieldFilterScopeTest { @Test public void verify_intersect() { - String fieldName1 = randomAlphabetic(11); - String fieldName2 = randomAlphabetic(12); + String fieldName1 = secure().nextAlphabetic(11); + String fieldName2 = secure().nextAlphabetic(12); SimpleFieldFilterScope underTest = new SimpleFieldFilterScope(fieldName1); assertThat(underTest.intersect(underTest)).isTrue(); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/SimpleFieldTopAggregationDefinitionTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/SimpleFieldTopAggregationDefinitionTest.java index 20933384d78..42d37a4dda8 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/SimpleFieldTopAggregationDefinitionTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/SimpleFieldTopAggregationDefinitionTest.java @@ -26,7 +26,7 @@ import java.util.stream.IntStream; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Test; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -45,7 +45,7 @@ public class SimpleFieldTopAggregationDefinitionTest { @Test public void getters() { - String fieldName = RandomStringUtils.randomAlphabetic(12); + String fieldName = RandomStringUtils.secure().nextAlphabetic(12); boolean sticky = new Random().nextBoolean(); SimpleFieldTopAggregationDefinition underTest = new SimpleFieldTopAggregationDefinition(fieldName, sticky); @@ -55,7 +55,7 @@ public class SimpleFieldTopAggregationDefinitionTest { @Test public void getFilterScope_always_returns_the_same_instance() { - String fieldName = randomAlphabetic(12); + String fieldName = secure().nextAlphabetic(12); boolean sticky = RANDOM.nextBoolean(); SimpleFieldTopAggregationDefinition underTest = new SimpleFieldTopAggregationDefinition(fieldName, sticky); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/SubAggregationHelperTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/SubAggregationHelperTest.java index 2bf3faecea0..639d4aff996 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/SubAggregationHelperTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/SubAggregationHelperTest.java @@ -28,7 +28,7 @@ import org.elasticsearch.search.aggregations.BucketOrder; import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import org.junit.Test; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.server.es.searchrequest.TopAggregationHelperTest.DEFAULT_BUCKET_SIZE; @@ -44,7 +44,7 @@ public class SubAggregationHelperTest { @Test public void buildTermsAggregation_adds_term_subaggregation_with_minDoc_1_and_default_sort() { - String aggName = randomAlphabetic(10); + String aggName = secure().nextAlphabetic(10); SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false); Stream.of( @@ -63,7 +63,7 @@ public class SubAggregationHelperTest { @Test public void buildTermsAggregation_adds_custom_order_from_constructor() { - String aggName = randomAlphabetic(10); + String aggName = secure().nextAlphabetic(10); SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false); TermsAggregationBuilder agg = underTestWithCustomsSubAggAndOrder.buildTermsAggregation(aggName, topAggregation, null); @@ -75,7 +75,7 @@ public class SubAggregationHelperTest { @Test public void buildTermsAggregation_adds_custom_sub_agg_from_constructor() { - String aggName = randomAlphabetic(10); + String aggName = secure().nextAlphabetic(10); SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false); Stream.of( @@ -93,7 +93,7 @@ public class SubAggregationHelperTest { @Test public void buildTermsAggregation_adds_custom_size_if_TermTopAggregation_specifies_one() { - String aggName = randomAlphabetic(10); + String aggName = secure().nextAlphabetic(10); int customSize = 1 + new Random().nextInt(400); SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false); @@ -112,7 +112,7 @@ public class SubAggregationHelperTest { @Test public void buildSelectedItemsAggregation_returns_empty_if_no_selected_item() { - String aggName = randomAlphabetic(10); + String aggName = secure().nextAlphabetic(10); SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false); Stream.of( @@ -124,7 +124,7 @@ public class SubAggregationHelperTest { @Test public void buildSelectedItemsAggregation_does_not_add_custom_order_from_constructor() { - String aggName = randomAlphabetic(10); + String aggName = secure().nextAlphabetic(10); SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false); String[] selected = randomNonEmptySelected(); @@ -138,7 +138,7 @@ public class SubAggregationHelperTest { @Test public void buildSelectedItemsAggregation_adds_custom_sub_agg_from_constructor() { - String aggName = randomAlphabetic(10); + String aggName = secure().nextAlphabetic(10); SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false); String[] selected = randomNonEmptySelected(); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/TopAggregationHelperTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/TopAggregationHelperTest.java index 152956666af..18ad6f58f6e 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/TopAggregationHelperTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/TopAggregationHelperTest.java @@ -32,7 +32,7 @@ import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilde import org.elasticsearch.search.aggregations.metrics.MinAggregationBuilder; import org.junit.Test; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; @@ -65,7 +65,7 @@ public class TopAggregationHelperTest { AggregationBuilder[] subAggs = IntStream.range(0, 1 + new Random().nextInt(12)) .mapToObj(i -> AggregationBuilders.min("subAgg_" + i)) .toArray(AggregationBuilder[]::new); - String topAggregationName = randomAlphabetic(10); + String topAggregationName = secure().nextAlphabetic(10); AggregationBuilder aggregationBuilder = underTest.buildTopAggregation(topAggregationName, topAggregation, NO_EXTRA_FILTER, t -> Arrays.stream(subAggs).forEach(t::subAggregation)); @@ -84,7 +84,7 @@ public class TopAggregationHelperTest { when(filtersComputer.getTopAggregationFilter(topAggregation)).thenReturn(Optional.of(computerFilter)); when(filtersComputer.getTopAggregationFilter(otherTopAggregation)).thenReturn(Optional.of(otherFilter)); MinAggregationBuilder subAggregation = AggregationBuilders.min("donut"); - String topAggregationName = randomAlphabetic(10); + String topAggregationName = secure().nextAlphabetic(10); FilterAggregationBuilder aggregationBuilder = underTest.buildTopAggregation(topAggregationName, topAggregation, NO_EXTRA_FILTER, t -> t.subAggregation(subAggregation)); @@ -101,7 +101,7 @@ public class TopAggregationHelperTest { when(filtersComputer.getTopAggregationFilter(topAggregation)).thenReturn(Optional.empty()); when(filtersComputer.getTopAggregationFilter(otherTopAggregation)).thenReturn(Optional.of(otherFilter)); MinAggregationBuilder subAggregation = AggregationBuilders.min("donut"); - String topAggregationName = randomAlphabetic(10); + String topAggregationName = secure().nextAlphabetic(10); FilterAggregationBuilder aggregationBuilder = underTest.buildTopAggregation(topAggregationName, topAggregation, NO_EXTRA_FILTER, t -> t.subAggregation(subAggregation)); @@ -112,7 +112,7 @@ public class TopAggregationHelperTest { @Test public void buildTopAggregation_adds_filter_from_FiltersComputer_for_TopAggregation_and_extra_one() { - String topAggregationName = randomAlphabetic(10); + String topAggregationName = secure().nextAlphabetic(10); SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false); SimpleFieldTopAggregationDefinition otherTopAggregation = new SimpleFieldTopAggregationDefinition("acme", false); BoolQueryBuilder computerFilter = boolQuery(); @@ -135,7 +135,7 @@ public class TopAggregationHelperTest { SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false); when(filtersComputer.getTopAggregationFilter(topAggregation)).thenReturn(Optional.empty()); MinAggregationBuilder subAggregation = AggregationBuilders.min("donut"); - String topAggregationName = randomAlphabetic(10); + String topAggregationName = secure().nextAlphabetic(10); underTest.buildTopAggregation(topAggregationName, topAggregation, NO_EXTRA_FILTER, t -> t.subAggregation(subAggregation)); @@ -144,7 +144,7 @@ public class TopAggregationHelperTest { @Test public void buildTermTopAggregation_adds_term_subaggregation_from_subAggregationHelper() { - String topAggregationName = randomAlphabetic(10); + String topAggregationName = secure().nextAlphabetic(10); SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false); TermsAggregationBuilder termSubAgg = AggregationBuilders.terms("foo"); when(subAggregationHelper.buildTermsAggregation(topAggregationName, topAggregation, null)).thenReturn(termSubAgg); @@ -164,7 +164,7 @@ public class TopAggregationHelperTest { AggregationBuilder[] subAggs = IntStream.range(0, 1 + new Random().nextInt(12)) .mapToObj(i -> AggregationBuilders.min("subAgg_" + i)) .toArray(AggregationBuilder[]::new); - String topAggregationName = randomAlphabetic(10); + String topAggregationName = secure().nextAlphabetic(10); TermsAggregationBuilder termSubAgg = AggregationBuilders.terms("foo"); when(subAggregationHelper.buildTermsAggregation(topAggregationName, topAggregation, null)).thenReturn(termSubAgg); AggregationBuilder[] allSubAggs = Stream.concat(Arrays.stream(subAggs), Stream.of(termSubAgg)).toArray(AggregationBuilder[]::new); @@ -186,7 +186,7 @@ public class TopAggregationHelperTest { BoolQueryBuilder otherFilter = boolQuery(); when(filtersComputer.getTopAggregationFilter(topAggregation)).thenReturn(Optional.of(computerFilter)); when(filtersComputer.getTopAggregationFilter(otherTopAggregation)).thenReturn(Optional.of(otherFilter)); - String topAggregationName = randomAlphabetic(10); + String topAggregationName = secure().nextAlphabetic(10); TermsAggregationBuilder termSubAgg = AggregationBuilders.terms("foo"); when(subAggregationHelper.buildTermsAggregation(topAggregationName, topAggregation, null)).thenReturn(termSubAgg); @@ -205,7 +205,7 @@ public class TopAggregationHelperTest { BoolQueryBuilder otherFilter = boolQuery(); when(filtersComputer.getTopAggregationFilter(topAggregation)).thenReturn(Optional.empty()); when(filtersComputer.getTopAggregationFilter(otherTopAggregation)).thenReturn(Optional.of(otherFilter)); - String topAggregationName = randomAlphabetic(10); + String topAggregationName = secure().nextAlphabetic(10); TermsAggregationBuilder termSubAgg = AggregationBuilders.terms("foo"); when(subAggregationHelper.buildTermsAggregation(topAggregationName, topAggregation, null)).thenReturn(termSubAgg); @@ -219,7 +219,7 @@ public class TopAggregationHelperTest { @Test public void buildTermTopAggregation_adds_filter_from_FiltersComputer_for_TopAggregation_and_extra_one() { - String topAggregationName = randomAlphabetic(10); + String topAggregationName = secure().nextAlphabetic(10); SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false); SimpleFieldTopAggregationDefinition otherTopAggregation = new SimpleFieldTopAggregationDefinition("acme", false); BoolQueryBuilder computerFilter = boolQuery(); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/ChangesOnMyIssueNotificationHandlerTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/ChangesOnMyIssueNotificationHandlerTest.java index 286c39d5a56..ac051a5ee5c 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/ChangesOnMyIssueNotificationHandlerTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/ChangesOnMyIssueNotificationHandlerTest.java @@ -50,7 +50,7 @@ import org.sonar.server.notification.email.EmailNotificationChannel; import org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliveryRequest; import static java.util.stream.Collectors.toSet; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anySet; import static org.mockito.Mockito.mock; @@ -404,7 +404,7 @@ public class ChangesOnMyIssueNotificationHandlerTest { @DataProvider public static Object[][] userOrAnalysisChange() { - User changeAuthor = new User(randomAlphabetic(12), randomAlphabetic(10), randomAlphabetic(11)); + User changeAuthor = new User(secure().nextAlphabetic(12), secure().nextAlphabetic(10), secure().nextAlphabetic(11)); return new Object[][] { {new AnalysisChange(new Random().nextLong())}, {new UserChange(new Random().nextLong(), changeAuthor)}, @@ -412,7 +412,7 @@ public class ChangesOnMyIssueNotificationHandlerTest { } private static Project newProject() { - String base = randomAlphabetic(6); + String base = secure().nextAlphabetic(6); return newProject(base); } @@ -437,7 +437,7 @@ public class ChangesOnMyIssueNotificationHandlerTest { } private static Rule newRule() { - return newRandomNotAHotspotRule(randomAlphabetic(5)); + return newRandomNotAHotspotRule(secure().nextAlphabetic(5)); } private static Set randomSetOfNotifications(@Nullable String projectKey, @Nullable String assignee, @Nullable String changeAuthor) { diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/ChangesOnMyIssuesEmailTemplateTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/ChangesOnMyIssuesEmailTemplateTest.java index ad3ab1c9429..009ed3c2d2d 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/ChangesOnMyIssuesEmailTemplateTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/ChangesOnMyIssuesEmailTemplateTest.java @@ -52,7 +52,7 @@ import org.sonar.test.html.HtmlParagraphAssert; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -307,8 +307,8 @@ public class ChangesOnMyIssuesEmailTemplateTest { } private void format_set_html_message_with_footer(Change change, String issueStatus, Function skipContent, RuleType ruleType) { - String wordingNotification = randomAlphabetic(20); - String host = randomAlphabetic(15); + String wordingNotification = secure().nextAlphabetic(20); + String host = secure().nextAlphabetic(15); when(i18n.message(Locale.ENGLISH, "notification.dispatcher.ChangesOnMyIssue", "notification.dispatcher.ChangesOnMyIssue")) .thenReturn(wordingNotification); when(emailSettings.getServerBaseURL()).thenReturn(host); @@ -393,8 +393,8 @@ public class ChangesOnMyIssuesEmailTemplateTest { @Test public void formats_returns_html_message_for_single_issue_on_master_when_analysis_change() { Project project = newProject("1"); - String ruleName = randomAlphabetic(8); - String host = randomAlphabetic(15); + String ruleName = secure().nextAlphabetic(8); + String host = secure().nextAlphabetic(15); ChangedIssue changedIssue = newChangedIssue("key", randomValidStatus(), project, ruleName, randomRuleTypeHotspotExcluded()); AnalysisChange analysisChange = newAnalysisChange(); when(emailSettings.getServerBaseURL()).thenReturn(host); @@ -414,7 +414,7 @@ public class ChangesOnMyIssuesEmailTemplateTest { public void user_input_content_should_be_html_escape() { Project project = new Project.Builder("uuid").setProjectName("").setKey("project_key").build(); String ruleName = ""; - String host = randomAlphabetic(15); + String host = secure().nextAlphabetic(15); Rule rule = newRule(ruleName, randomRuleTypeHotspotExcluded()); List changedIssues = IntStream.range(0, 2 + new Random().nextInt(5)) .mapToObj(i -> newChangedIssue("issue_" + i, randomValidStatus(), project, rule)) @@ -445,8 +445,8 @@ public class ChangesOnMyIssuesEmailTemplateTest { @Test public void formats_returns_html_message_for_single_issue_on_master_when_user_change() { Project project = newProject("1"); - String ruleName = randomAlphabetic(8); - String host = randomAlphabetic(15); + String ruleName = secure().nextAlphabetic(8); + String host = secure().nextAlphabetic(15); ChangedIssue changedIssue = newChangedIssue("key", randomValidStatus(), project, ruleName, randomRuleTypeHotspotExcluded()); UserChange userChange = newUserChange(); when(emailSettings.getServerBaseURL()).thenReturn(host); @@ -464,10 +464,10 @@ public class ChangesOnMyIssuesEmailTemplateTest { @Test public void formats_returns_html_message_for_single_issue_on_branch_when_analysis_change() { - String branchName = randomAlphabetic(6); + String branchName = secure().nextAlphabetic(6); Project project = newBranch("1", branchName); - String ruleName = randomAlphabetic(8); - String host = randomAlphabetic(15); + String ruleName = secure().nextAlphabetic(8); + String host = secure().nextAlphabetic(15); String key = "key"; ChangedIssue changedIssue = newChangedIssue(key, randomValidStatus(), project, ruleName, randomRuleTypeHotspotExcluded()); AnalysisChange analysisChange = newAnalysisChange(); @@ -487,10 +487,10 @@ public class ChangesOnMyIssuesEmailTemplateTest { @Test public void formats_returns_html_message_for_single_issue_on_branch_when_user_change() { - String branchName = randomAlphabetic(6); + String branchName = secure().nextAlphabetic(6); Project project = newBranch("1", branchName); - String ruleName = randomAlphabetic(8); - String host = randomAlphabetic(15); + String ruleName = secure().nextAlphabetic(8); + String host = secure().nextAlphabetic(15); String key = "key"; ChangedIssue changedIssue = newChangedIssue(key, randomValidStatus(), project, ruleName, randomRuleTypeHotspotExcluded()); UserChange userChange = newUserChange(); @@ -511,8 +511,8 @@ public class ChangesOnMyIssuesEmailTemplateTest { @Test public void formats_returns_html_message_for_multiple_issues_of_same_rule_on_same_project_on_master_when_analysis_change() { Project project = newProject("1"); - String ruleName = randomAlphabetic(8); - String host = randomAlphabetic(15); + String ruleName = secure().nextAlphabetic(8); + String host = secure().nextAlphabetic(15); Rule rule = newRule(ruleName, randomRuleTypeHotspotExcluded()); String issueStatus = randomValidStatus(); List changedIssues = IntStream.range(0, 2 + new Random().nextInt(5)) @@ -538,8 +538,8 @@ public class ChangesOnMyIssuesEmailTemplateTest { @Test public void formats_returns_html_message_for_multiple_issues_of_same_rule_on_same_project_on_master_when_user_change() { Project project = newProject("1"); - String ruleName = randomAlphabetic(8); - String host = randomAlphabetic(15); + String ruleName = secure().nextAlphabetic(8); + String host = secure().nextAlphabetic(15); Rule rule = newRule(ruleName, randomRuleTypeHotspotExcluded()); List changedIssues = IntStream.range(0, 2 + new Random().nextInt(5)) .mapToObj(i -> newChangedIssue("issue_" + i, randomValidStatus(), project, rule)) @@ -563,10 +563,10 @@ public class ChangesOnMyIssuesEmailTemplateTest { @Test public void formats_returns_html_message_for_multiple_issues_of_same_rule_on_same_project_on_branch_when_analysis_change() { - String branchName = randomAlphabetic(19); + String branchName = secure().nextAlphabetic(19); Project project = newBranch("1", branchName); - String ruleName = randomAlphabetic(8); - String host = randomAlphabetic(15); + String ruleName = secure().nextAlphabetic(8); + String host = secure().nextAlphabetic(15); Rule rule = newRule(ruleName, randomRuleTypeHotspotExcluded()); String status = randomValidStatus(); List changedIssues = IntStream.range(0, 2 + new Random().nextInt(5)) @@ -591,10 +591,10 @@ public class ChangesOnMyIssuesEmailTemplateTest { @Test public void formats_returns_html_message_for_multiple_issues_of_same_rule_on_same_project_on_branch_when_user_change() { - String branchName = randomAlphabetic(19); + String branchName = secure().nextAlphabetic(19); Project project = newBranch("1", branchName); - String ruleName = randomAlphabetic(8); - String host = randomAlphabetic(15); + String ruleName = secure().nextAlphabetic(8); + String host = secure().nextAlphabetic(15); Rule rule = newRandomNotAHotspotRule(ruleName); List changedIssues = IntStream.range(0, 2 + new Random().nextInt(5)) .mapToObj(i -> newChangedIssue("issue_" + i, randomValidStatus(), project, rule)) @@ -624,9 +624,9 @@ public class ChangesOnMyIssuesEmailTemplateTest { Project project2 = newProject("B"); Project project2Branch1 = newBranch("B", "a"); Project project3 = newProject("C"); - String host = randomAlphabetic(15); + String host = secure().nextAlphabetic(15); List changedIssues = Stream.of(project1, project1Branch1, project1Branch2, project2, project2Branch1, project3) - .map(project -> newChangedIssue("issue_" + project.getUuid(), randomValidStatus(), project, newRule(randomAlphabetic(2), randomRuleTypeHotspotExcluded()))) + .map(project -> newChangedIssue("issue_" + project.getUuid(), randomValidStatus(), project, newRule(secure().nextAlphabetic(2), randomRuleTypeHotspotExcluded()))) .collect(toList()); Collections.shuffle(changedIssues); UserChange userChange = newUserChange(); @@ -660,7 +660,7 @@ public class ChangesOnMyIssuesEmailTemplateTest { Rule rule3 = newRandomNotAHotspotRule("b"); Rule rule4 = newRandomNotAHotspotRule("X"); - String host = randomAlphabetic(15); + String host = secure().nextAlphabetic(15); String issueStatus = randomValidStatus(); List changedIssues = Stream.of(rule1, rule2, rule3, rule4) .map(rule -> newChangedIssue("issue_" + rule.getName(), issueStatus, project, rule)) @@ -696,7 +696,7 @@ public class ChangesOnMyIssuesEmailTemplateTest { Rule hotspot3 = newSecurityHotspotRule("N"); Rule hotspot4 = newSecurityHotspotRule("M"); - String host = randomAlphabetic(15); + String host = secure().nextAlphabetic(15); List changedIssues = Stream.of(rule1, rule2, rule3, rule4, hotspot1, hotspot2, hotspot3, hotspot4) .map(rule -> newChangedIssue("issue_" + rule.getName(), randomValidStatus(), project, rule)) .collect(toList()); @@ -731,7 +731,7 @@ public class ChangesOnMyIssuesEmailTemplateTest { Rule rule1 = newRandomNotAHotspotRule("1"); Rule rule2 = newRandomNotAHotspotRule("a"); - String host = randomAlphabetic(15); + String host = secure().nextAlphabetic(15); String issueStatusClosed = STATUS_CLOSED; String otherIssueStatus = STATUS_RESOLVED; @@ -793,7 +793,7 @@ public class ChangesOnMyIssuesEmailTemplateTest { Rule hotspot2 = newSecurityHotspotRule("h2"); String status = randomValidStatus(); - String host = randomAlphabetic(15); + String host = secure().nextAlphabetic(15); List changedIssues = Stream.of( IntStream.range(0, 39).mapToObj(i -> newChangedIssue("39_" + i, status, project1, rule1)), IntStream.range(0, 40).mapToObj(i -> newChangedIssue("40_" + i, status, project1, rule2)), diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/ChangesOnMyIssuesNotificationTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/ChangesOnMyIssuesNotificationTest.java index 89c9fef0663..ff9847b368a 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/ChangesOnMyIssuesNotificationTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/ChangesOnMyIssuesNotificationTest.java @@ -28,7 +28,7 @@ import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Chan import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.User; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.UserChange; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.newRandomNotAHotspotRule; @@ -37,7 +37,7 @@ public class ChangesOnMyIssuesNotificationTest { @Test public void key_is_ChangesOnMyIssues() { ChangesOnMyIssuesNotification underTest = new ChangesOnMyIssuesNotification( - new UserChange(new Random().nextLong(), new User(randomAlphabetic(2), randomAlphabetic(3), randomAlphabetic(4))), + new UserChange(new Random().nextLong(), new User(secure().nextAlphabetic(2), secure().nextAlphabetic(3), secure().nextAlphabetic(4))), ImmutableSet.of()); assertThat(underTest.getType()).isEqualTo("ChangesOnMyIssues"); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/EmailMessageTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/EmailMessageTest.java index b9f193b08ff..eab9f0726c2 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/EmailMessageTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/EmailMessageTest.java @@ -21,7 +21,7 @@ package org.sonar.server.issue.notification; import org.junit.Test; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; public class EmailMessageTest { @@ -29,7 +29,7 @@ public class EmailMessageTest { @Test public void setHtmlMessage_sets_message_and_html_to_true() { - String message = randomAlphabetic(12); + String message = secure().nextAlphabetic(12); underTest.setHtmlMessage(message); @@ -39,7 +39,7 @@ public class EmailMessageTest { @Test public void setPlainTextMessage_sets_message_and_html_to_false() { - String message = randomAlphabetic(12); + String message = secure().nextAlphabetic(12); underTest.setPlainTextMessage(message); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/FPOrAcceptedNotificationHandlerTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/FPOrAcceptedNotificationHandlerTest.java index fe25236bc07..88d29e00181 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/FPOrAcceptedNotificationHandlerTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/FPOrAcceptedNotificationHandlerTest.java @@ -47,7 +47,7 @@ import org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliver import static java.util.Collections.singleton; import static java.util.stream.Collectors.toSet; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; @@ -219,10 +219,10 @@ public class FPOrAcceptedNotificationHandlerTest { @UseDataProvider("FPorWontFixResolutionWithCorrespondingIssueStatus") public void deliver_checks_by_projectKey_if_notifications_have_subscribed_assignee_to_FPorWontFix_notifications(String newResolution, IssueStatus newIssueStatus) { - Project projectKey1 = newProject(randomAlphabetic(4)); - Project projectKey2 = newProject(randomAlphabetic(5)); - Project projectKey3 = newProject(randomAlphabetic(6)); - Project projectKey4 = newProject(randomAlphabetic(7)); + Project projectKey1 = newProject(secure().nextAlphabetic(4)); + Project projectKey2 = newProject(secure().nextAlphabetic(5)); + Project projectKey3 = newProject(secure().nextAlphabetic(6)); + Project projectKey4 = newProject(secure().nextAlphabetic(7)); Change changeMock = mock(Change.class); // some notifications with some issues on project1 Stream project1Notifications = IntStream.range(0, 5) @@ -264,7 +264,7 @@ public class FPOrAcceptedNotificationHandlerTest { @Test @UseDataProvider("FPorWontFixResolutionWithCorrespondingIssueStatus") public void deliver_does_not_send_email_request_for_notifications_a_subscriber_is_the_changeAuthor_of(String newResolution, IssueStatus newIssueStatus) { - Project project = newProject(randomAlphabetic(5)); + Project project = newProject(secure().nextAlphabetic(5)); User subscriber1 = newUser("subscriber1"); User subscriber2 = newUser("subscriber2"); User subscriber3 = newUser("subscriber3"); @@ -477,12 +477,12 @@ public class FPOrAcceptedNotificationHandlerTest { return IntStream.range(0, 5) .mapToObj(i -> { ChangedIssue.Builder builder = new ChangedIssue.Builder("key_" + i) - .setAssignee(new User(randomAlphabetic(3), randomAlphabetic(4), randomAlphabetic(5))) - .setNewStatus(randomAlphabetic(12)) - .setRule(newRandomNotAHotspotRule(randomAlphabetic(8))) - .setProject(new Project.Builder(randomAlphabetic(9)) - .setKey(randomAlphabetic(10)) - .setProjectName(randomAlphabetic(11)) + .setAssignee(new User(secure().nextAlphabetic(3), secure().nextAlphabetic(4), secure().nextAlphabetic(5))) + .setNewStatus(secure().nextAlphabetic(12)) + .setRule(newRandomNotAHotspotRule(secure().nextAlphabetic(8))) + .setProject(new Project.Builder(secure().nextAlphabetic(9)) + .setKey(secure().nextAlphabetic(10)) + .setProjectName(secure().nextAlphabetic(11)) .build()); consumer.accept(builder); return builder.build(); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/FpPrAcceptedEmailTemplateTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/FpPrAcceptedEmailTemplateTest.java index b3a7700a671..7a0d96b10ca 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/FpPrAcceptedEmailTemplateTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/FpPrAcceptedEmailTemplateTest.java @@ -48,7 +48,7 @@ import org.sonar.test.html.HtmlFragmentAssert; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -102,7 +102,7 @@ public class FpPrAcceptedEmailTemplateTest { @Test public void format_sets_from_to_name_of_author_change_when_available() { - UserChange change = new UserChange(new Random().nextLong(), new User(randomAlphabetic(5), randomAlphabetic(6), randomAlphabetic(7))); + UserChange change = new UserChange(new Random().nextLong(), new User(secure().nextAlphabetic(5), secure().nextAlphabetic(6), secure().nextAlphabetic(7))); EmailMessage emailMessage = underTest.format(new FPOrAcceptedNotification(change, Collections.emptySet(), ACCEPTED)); assertThat(emailMessage.getFrom()).isEqualTo(change.getUser().getName().get()); @@ -110,7 +110,7 @@ public class FpPrAcceptedEmailTemplateTest { @Test public void format_sets_from_to_login_of_author_change_when_name_is_not_available() { - UserChange change = new UserChange(new Random().nextLong(), new User(randomAlphabetic(5), randomAlphabetic(6), null)); + UserChange change = new UserChange(new Random().nextLong(), new User(secure().nextAlphabetic(5), secure().nextAlphabetic(6), null)); EmailMessage emailMessage = underTest.format(new FPOrAcceptedNotification(change, Collections.emptySet(), ACCEPTED)); assertThat(emailMessage.getFrom()).isEqualTo(change.getUser().getLogin()); @@ -137,8 +137,8 @@ public class FpPrAcceptedEmailTemplateTest { } public void formats_returns_html_message_with_only_footer_and_header_when_no_issue(Change change, FpPrAccepted fpPrAccepted, String fpOrWontFixLabel) { - String wordingNotification = randomAlphabetic(20); - String host = randomAlphabetic(15); + String wordingNotification = secure().nextAlphabetic(20); + String host = secure().nextAlphabetic(15); when(i18n.message(Locale.ENGLISH, "notification.dispatcher.NewFalsePositiveIssue", "notification.dispatcher.NewFalsePositiveIssue")) .thenReturn(wordingNotification); when(emailSettings.getServerBaseURL()).thenReturn(host); @@ -163,8 +163,8 @@ public class FpPrAcceptedEmailTemplateTest { @UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange") public void formats_returns_html_message_for_single_issue_on_master(Change change, FpPrAccepted fpPrAccepted) { Project project = newProject("1"); - String ruleName = randomAlphabetic(8); - String host = randomAlphabetic(15); + String ruleName = secure().nextAlphabetic(8); + String host = secure().nextAlphabetic(15); ChangedIssue changedIssue = newChangedIssue("key", project, ruleName, randomRuleTypeHotspotExcluded()); when(emailSettings.getServerBaseURL()).thenReturn(host); @@ -183,8 +183,8 @@ public class FpPrAcceptedEmailTemplateTest { @UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange") public void formats_returns_html_message_for_single_hotspot_on_master(Change change, FpPrAccepted fpPrAccepted) { Project project = newProject("1"); - String ruleName = randomAlphabetic(8); - String host = randomAlphabetic(15); + String ruleName = secure().nextAlphabetic(8); + String host = secure().nextAlphabetic(15); ChangedIssue changedIssue = newChangedIssue("key", project, ruleName, SECURITY_HOTSPOT); when(emailSettings.getServerBaseURL()).thenReturn(host); @@ -202,10 +202,10 @@ public class FpPrAcceptedEmailTemplateTest { @Test @UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange") public void formats_returns_html_message_for_single_issue_on_branch(Change change, FpPrAccepted fpPrAccepted) { - String branchName = randomAlphabetic(6); + String branchName = secure().nextAlphabetic(6); Project project = newBranch("1", branchName); - String ruleName = randomAlphabetic(8); - String host = randomAlphabetic(15); + String ruleName = secure().nextAlphabetic(8); + String host = secure().nextAlphabetic(15); String key = "key"; ChangedIssue changedIssue = newChangedIssue(key, project, ruleName, randomRuleTypeHotspotExcluded()); when(emailSettings.getServerBaseURL()).thenReturn(host); @@ -225,10 +225,10 @@ public class FpPrAcceptedEmailTemplateTest { @Test @UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange") public void formats_returns_html_message_for_single_hotspot_on_branch(Change change, FpPrAccepted fpPrAccepted) { - String branchName = randomAlphabetic(6); + String branchName = secure().nextAlphabetic(6); Project project = newBranch("1", branchName); - String ruleName = randomAlphabetic(8); - String host = randomAlphabetic(15); + String ruleName = secure().nextAlphabetic(8); + String host = secure().nextAlphabetic(15); String key = "key"; ChangedIssue changedIssue = newChangedIssue(key, project, ruleName, SECURITY_HOTSPOT); when(emailSettings.getServerBaseURL()).thenReturn(host); @@ -249,8 +249,8 @@ public class FpPrAcceptedEmailTemplateTest { @UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange") public void formats_returns_html_message_for_multiple_issues_of_same_rule_on_same_project_on_master(Change change, FpPrAccepted fpPrAccepted) { Project project = newProject("1"); - String ruleName = randomAlphabetic(8); - String host = randomAlphabetic(15); + String ruleName = secure().nextAlphabetic(8); + String host = secure().nextAlphabetic(15); Rule rule = newRandomNotAHotspotRule(ruleName); List changedIssues = IntStream.range(0, 2 + new Random().nextInt(5)) .mapToObj(i -> newChangedIssue("issue_" + i, project, rule)) @@ -275,8 +275,8 @@ public class FpPrAcceptedEmailTemplateTest { @UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange") public void formats_returns_html_message_for_multiple_hotspots_of_same_rule_on_same_project_on_master(Change change, FpPrAccepted fpPrAccepted) { Project project = newProject("1"); - String ruleName = randomAlphabetic(8); - String host = randomAlphabetic(15); + String ruleName = secure().nextAlphabetic(8); + String host = secure().nextAlphabetic(15); Rule rule = newSecurityHotspotRule(ruleName); List changedIssues = IntStream.range(0, 2 + new Random().nextInt(5)) .mapToObj(i -> newChangedIssue("issue_" + i, project, rule)) @@ -300,10 +300,10 @@ public class FpPrAcceptedEmailTemplateTest { @Test @UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange") public void formats_returns_html_message_for_multiple_issues_of_same_rule_on_same_project_on_branch(Change change, FpPrAccepted fpPrAccepted) { - String branchName = randomAlphabetic(19); + String branchName = secure().nextAlphabetic(19); Project project = newBranch("1", branchName); - String ruleName = randomAlphabetic(8); - String host = randomAlphabetic(15); + String ruleName = secure().nextAlphabetic(8); + String host = secure().nextAlphabetic(15); Rule rule = newRandomNotAHotspotRule(ruleName); List changedIssues = IntStream.range(0, 2 + new Random().nextInt(5)) .mapToObj(i -> newChangedIssue("issue_" + i, project, rule)) @@ -327,10 +327,10 @@ public class FpPrAcceptedEmailTemplateTest { @Test @UseDataProvider("fpOrWontFixValuesByUserOrAnalysisChange") public void formats_returns_html_message_for_multiple_hotspots_of_same_rule_on_same_project_on_branch(Change change, FpPrAccepted fpPrAccepted) { - String branchName = randomAlphabetic(19); + String branchName = secure().nextAlphabetic(19); Project project = newBranch("1", branchName); - String ruleName = randomAlphabetic(8); - String host = randomAlphabetic(15); + String ruleName = secure().nextAlphabetic(8); + String host = secure().nextAlphabetic(15); Rule rule = newSecurityHotspotRule(ruleName); List changedIssues = IntStream.range(0, 2 + new Random().nextInt(5)) .mapToObj(i -> newChangedIssue("issue_" + i, project, rule)) @@ -360,9 +360,9 @@ public class FpPrAcceptedEmailTemplateTest { Project project2 = newProject("B"); Project project2Branch1 = newBranch("B", "a"); Project project3 = newProject("C"); - String host = randomAlphabetic(15); + String host = secure().nextAlphabetic(15); List changedIssues = Stream.of(project1, project1Branch1, project1Branch2, project2, project2Branch1, project3) - .map(project -> newChangedIssue("issue_" + project.getUuid(), project, newRandomNotAHotspotRule(randomAlphabetic(2)))) + .map(project -> newChangedIssue("issue_" + project.getUuid(), project, newRandomNotAHotspotRule(secure().nextAlphabetic(2)))) .collect(toList()); Collections.shuffle(changedIssues); when(emailSettings.getServerBaseURL()).thenReturn(host); @@ -395,7 +395,7 @@ public class FpPrAcceptedEmailTemplateTest { Rule rule2 = newRandomNotAHotspotRule("a"); Rule rule3 = newRandomNotAHotspotRule("b"); Rule rule4 = newRandomNotAHotspotRule("X"); - String host = randomAlphabetic(15); + String host = secure().nextAlphabetic(15); List changedIssues = Stream.of(rule1, rule2, rule3, rule4) .map(rule -> newChangedIssue("issue_" + rule.getName(), project, rule)) .collect(toList()); @@ -424,7 +424,7 @@ public class FpPrAcceptedEmailTemplateTest { Project project2Branch = newBranch("V", "AB"); Rule rule1 = newRandomNotAHotspotRule("1"); Rule rule2 = newRandomNotAHotspotRule("a"); - String host = randomAlphabetic(15); + String host = secure().nextAlphabetic(15); List changedIssues = Stream.of( IntStream.range(0, 39).mapToObj(i -> newChangedIssue("39_" + i, project1, rule1)), IntStream.range(0, 40).mapToObj(i -> newChangedIssue("40_" + i, project1, rule2)), @@ -473,8 +473,8 @@ public class FpPrAcceptedEmailTemplateTest { @DataProvider public static Object[][] userOrAnalysisChange() { AnalysisChange analysisChange = new AnalysisChange(new Random().nextLong()); - UserChange userChange = new UserChange(new Random().nextLong(), new User(randomAlphabetic(5), randomAlphabetic(6), - new Random().nextBoolean() ? null : randomAlphabetic(7))); + UserChange userChange = new UserChange(new Random().nextLong(), new User(secure().nextAlphabetic(5), secure().nextAlphabetic(6), + new Random().nextBoolean() ? null : secure().nextAlphabetic(7))); return new Object[][] { {analysisChange}, {userChange} @@ -484,8 +484,8 @@ public class FpPrAcceptedEmailTemplateTest { @DataProvider public static Object[][] fpOrWontFixValuesByUserOrAnalysisChange() { AnalysisChange analysisChange = new AnalysisChange(new Random().nextLong()); - UserChange userChange = new UserChange(new Random().nextLong(), new User(randomAlphabetic(5), randomAlphabetic(6), - new Random().nextBoolean() ? null : randomAlphabetic(7))); + UserChange userChange = new UserChange(new Random().nextLong(), new User(secure().nextAlphabetic(5), secure().nextAlphabetic(6), + new Random().nextBoolean() ? null : secure().nextAlphabetic(7))); return new Object[][] { {analysisChange, FP}, {analysisChange, ACCEPTED}, @@ -500,14 +500,14 @@ public class FpPrAcceptedEmailTemplateTest { private static ChangedIssue newChangedIssue(String key, Project project, Rule rule) { return new ChangedIssue.Builder(key) - .setNewStatus(randomAlphabetic(19)) + .setNewStatus(secure().nextAlphabetic(19)) .setProject(project) .setRule(rule) .build(); } private static Rule newRule(String ruleName, RuleType ruleType) { - return new Rule(RuleKey.of(randomAlphabetic(6), randomAlphabetic(7)), ruleType, ruleName); + return new Rule(RuleKey.of(secure().nextAlphabetic(6), secure().nextAlphabetic(7)), ruleType, ruleName); } private static Project newProject(String uuid) { diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/MyNewIssuesNotificationHandlerTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/MyNewIssuesNotificationHandlerTest.java index c9a698b37b4..cb4ee4ccb5f 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/MyNewIssuesNotificationHandlerTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/MyNewIssuesNotificationHandlerTest.java @@ -37,7 +37,7 @@ import org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliver import static com.google.common.collect.ImmutableSet.of; import static java.util.Collections.emptySet; import static java.util.stream.Collectors.toSet; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -134,7 +134,7 @@ public class MyNewIssuesNotificationHandlerTest { public void deliver_has_no_effect_if_no_notification_has_assignee() { when(emailNotificationChannel.isActivated()).thenReturn(true); Set notifications = IntStream.range(0, 1 + new Random().nextInt(10)) - .mapToObj(i -> newNotification(randomAlphabetic(5 + i), null)) + .mapToObj(i -> newNotification(secure().nextAlphabetic(5 + i), null)) .collect(toSet()); int deliver = underTest.deliver(notifications); @@ -152,8 +152,8 @@ public class MyNewIssuesNotificationHandlerTest { @Test public void deliver_has_no_effect_if_no_notification_has_subscribed_assignee_to_MyNewIssue_notifications() { - String projectKey = randomAlphabetic(12); - String assignee = randomAlphabetic(10); + String projectKey = secure().nextAlphabetic(12); + String assignee = secure().nextAlphabetic(10); MyNewIssuesNotification notification = newNotification(projectKey, assignee); when(emailNotificationChannel.isActivated()).thenReturn(true); when(notificationManager.findSubscribedEmailRecipients(MY_NEW_ISSUES_DISPATCHER_KEY, projectKey, of(assignee), ALL_MUST_HAVE_ROLE_USER)) @@ -170,12 +170,12 @@ public class MyNewIssuesNotificationHandlerTest { @Test public void deliver_ignores_notification_without_projectKey() { - String projectKey = randomAlphabetic(10); + String projectKey = secure().nextAlphabetic(10); Set withProjectKey = IntStream.range(0, 1 + new Random().nextInt(5)) - .mapToObj(i -> newNotification(projectKey, randomAlphabetic(11 + i))) + .mapToObj(i -> newNotification(projectKey, secure().nextAlphabetic(11 + i))) .collect(toSet()); Set noProjectKey = IntStream.range(0, 1 + new Random().nextInt(5)) - .mapToObj(i -> newNotification(null, randomAlphabetic(11 + i))) + .mapToObj(i -> newNotification(null, secure().nextAlphabetic(11 + i))) .collect(toSet()); Set noProjectKeyNoAssignee = randomSetOfNotifications(null, null); Set authorizedRecipients = withProjectKey.stream() @@ -204,9 +204,9 @@ public class MyNewIssuesNotificationHandlerTest { @Test public void deliver_ignores_notification_without_assignee() { - String projectKey = randomAlphabetic(10); + String projectKey = secure().nextAlphabetic(10); Set withAssignee = IntStream.range(0, 1 + new Random().nextInt(5)) - .mapToObj(i -> newNotification(projectKey, randomAlphabetic(11 + i))) + .mapToObj(i -> newNotification(projectKey, secure().nextAlphabetic(11 + i))) .collect(toSet()); Set noAssignee = randomSetOfNotifications(projectKey, null); Set noProjectKeyNoAssignee = randomSetOfNotifications(null, null); @@ -236,10 +236,10 @@ public class MyNewIssuesNotificationHandlerTest { @Test public void deliver_checks_by_projectKey_if_notifications_have_subscribed_assignee_to_MyNewIssue_notifications() { - String projectKey1 = randomAlphabetic(10); - String assignee1 = randomAlphabetic(11); - String projectKey2 = randomAlphabetic(12); - String assignee2 = randomAlphabetic(13); + String projectKey1 = secure().nextAlphabetic(10); + String assignee1 = secure().nextAlphabetic(11); + String projectKey2 = secure().nextAlphabetic(12); + String assignee2 = secure().nextAlphabetic(13); Set notifications1 = randomSetOfNotifications(projectKey1, assignee1); Set notifications2 = randomSetOfNotifications(projectKey2, assignee2); when(emailNotificationChannel.isActivated()).thenReturn(true); @@ -260,9 +260,9 @@ public class MyNewIssuesNotificationHandlerTest { @Test public void deliver_ignores_notifications_which_assignee_has_no_subscribed_to_MyNewIssue_notifications() { - String projectKey = randomAlphabetic(5); - String assignee1 = randomAlphabetic(6); - String assignee2 = randomAlphabetic(7); + String projectKey = secure().nextAlphabetic(5); + String assignee1 = secure().nextAlphabetic(6); + String assignee2 = secure().nextAlphabetic(7); Set assignees = of(assignee1, assignee2); // assignee1 is not authorized Set assignee1Notifications = randomSetOfNotifications(projectKey, assignee1); @@ -289,12 +289,12 @@ public class MyNewIssuesNotificationHandlerTest { @Test public void deliver_returns_sum_of_delivery_counts_when_multiple_projects() { - String projectKey1 = randomAlphabetic(5); - String projectKey2 = randomAlphabetic(6); - String projectKey3 = randomAlphabetic(7); - String assignee1 = randomAlphabetic(8); - String assignee2 = randomAlphabetic(9); - String assignee3 = randomAlphabetic(10); + String projectKey1 = secure().nextAlphabetic(5); + String projectKey2 = secure().nextAlphabetic(6); + String projectKey3 = secure().nextAlphabetic(7); + String assignee1 = secure().nextAlphabetic(8); + String assignee2 = secure().nextAlphabetic(9); + String assignee3 = secure().nextAlphabetic(10); // assignee1 has subscribed to project1 only, no notification on project3 Set assignee1Project1 = randomSetOfNotifications(projectKey1, assignee1); Set assignee1Project2 = randomSetOfNotifications(projectKey2, assignee1); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/NewIssuesNotificationHandlerTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/NewIssuesNotificationHandlerTest.java index 6b85ad907e4..4014dbc979a 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/NewIssuesNotificationHandlerTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/NewIssuesNotificationHandlerTest.java @@ -36,7 +36,7 @@ import org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliver import static java.util.Collections.emptySet; import static java.util.stream.Collectors.toSet; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -130,7 +130,7 @@ public class NewIssuesNotificationHandlerTest { @Test public void deliver_has_no_effect_if_no_notification_has_subscribed_recipients_to_NewIssue_notifications() { - String projectKey = randomAlphabetic(12); + String projectKey = secure().nextAlphabetic(12); NewIssuesNotification notification = newNotification(projectKey); when(emailNotificationChannel.isActivated()).thenReturn(true); when(notificationManager.findSubscribedEmailRecipients(NEW_ISSUES_DISPATCHER_KEY, projectKey, ALL_MUST_HAVE_ROLE_USER)) @@ -147,7 +147,7 @@ public class NewIssuesNotificationHandlerTest { @Test public void deliver_ignores_notification_without_projectKey() { - String projectKey = randomAlphabetic(10); + String projectKey = secure().nextAlphabetic(10); Set withProjectKey = IntStream.range(0, 1 + new Random().nextInt(5)) .mapToObj(i -> newNotification(projectKey)) .collect(toSet()); @@ -180,8 +180,8 @@ public class NewIssuesNotificationHandlerTest { @Test public void deliver_checks_by_projectKey_if_notifications_have_subscribed_assignee_to_NewIssue_notifications() { - String projectKey1 = randomAlphabetic(10); - String projectKey2 = randomAlphabetic(11); + String projectKey1 = secure().nextAlphabetic(10); + String projectKey2 = secure().nextAlphabetic(11); Set notifications1 = randomSetOfNotifications(projectKey1); Set notifications2 = randomSetOfNotifications(projectKey2); when(emailNotificationChannel.isActivated()).thenReturn(true); @@ -218,8 +218,8 @@ public class NewIssuesNotificationHandlerTest { @Test public void deliver_send_notifications_to_all_subscribers_of_all_projects() { - String projectKey1 = randomAlphabetic(10); - String projectKey2 = randomAlphabetic(11); + String projectKey1 = secure().nextAlphabetic(10); + String projectKey2 = secure().nextAlphabetic(11); Set notifications1 = randomSetOfNotifications(projectKey1); Set notifications2 = randomSetOfNotifications(projectKey2); when(emailNotificationChannel.isActivated()).thenReturn(true); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/NewIssuesStatisticsTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/NewIssuesStatisticsTest.java index 48c45249eed..3df3104ebce 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/NewIssuesStatisticsTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/NewIssuesStatisticsTest.java @@ -36,8 +36,7 @@ import org.sonar.api.utils.Duration; import org.sonar.core.issue.DefaultIssue; import org.sonar.server.issue.notification.NewIssuesStatistics.Metric; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; class NewIssuesStatisticsTest { @@ -78,7 +77,7 @@ class NewIssuesStatisticsTest { @Test void add_counts_issues_on_current_analysis_globally_and_per_assignee() { - String assignee = randomAlphanumeric(10); + String assignee = secure().nextAlphanumeric(10); IntStream.range(0, 10) .mapToObj(i -> new DefaultIssue().setAssigneeUuid(assignee).setNew(true)) .forEach(underTest::add); @@ -93,7 +92,7 @@ class NewIssuesStatisticsTest { @Test void add_counts_issues_off_current_analysis_globally_and_per_assignee() { - String assignee = randomAlphanumeric(10); + String assignee = secure().nextAlphanumeric(10); IntStream.range(0, 10) .mapToObj(i -> new DefaultIssue().setAssigneeUuid(assignee).setNew(false)) .forEach(underTest::add); @@ -108,8 +107,8 @@ class NewIssuesStatisticsTest { @Test void add_counts_issue_per_component_on_current_analysis_globally_and_per_assignee() { - List componentUuids = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList(); - String assignee = randomAlphanumeric(10); + List componentUuids = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> secure().nextAlphabetic(3)).toList(); + String assignee = secure().nextAlphanumeric(10); componentUuids.stream() .map(componentUuid -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setComponentUuid(componentUuid).setAssigneeUuid(assignee).setNew(true)) .forEach(underTest::add); @@ -123,8 +122,8 @@ class NewIssuesStatisticsTest { @Test void add_counts_issue_per_component_off_current_analysis_globally_and_per_assignee() { - List componentUuids = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList(); - String assignee = randomAlphanumeric(10); + List componentUuids = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> secure().nextAlphabetic(3)).toList(); + String assignee = secure().nextAlphanumeric(10); componentUuids.stream() .map(componentUuid -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setComponentUuid(componentUuid).setAssigneeUuid(assignee).setNew(false)) .forEach(underTest::add); @@ -138,7 +137,7 @@ class NewIssuesStatisticsTest { @Test void add_does_not_count_component_if_null_neither_globally_nor_per_assignee() { - String assignee = randomAlphanumeric(10); + String assignee = secure().nextAlphanumeric(10); underTest.add(new DefaultIssue().setType(randomRuleTypeExceptHotspot).setComponentUuid(null).setAssigneeUuid(assignee).setNew(new Random().nextBoolean())); DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.COMPONENT); @@ -153,9 +152,9 @@ class NewIssuesStatisticsTest { @Test void add_counts_issue_per_ruleKey_on_current_analysis_globally_and_per_assignee() { - String repository = randomAlphanumeric(3); - List ruleKeys = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList(); - String assignee = randomAlphanumeric(10); + String repository = secure().nextAlphanumeric(3); + List ruleKeys = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> secure().nextAlphabetic(3)).toList(); + String assignee = secure().nextAlphanumeric(10); ruleKeys.stream() .map(ruleKey -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setRuleKey(RuleKey.of(repository, ruleKey)).setAssigneeUuid(assignee).setNew(true)) .forEach(underTest::add); @@ -169,9 +168,9 @@ class NewIssuesStatisticsTest { @Test void add_counts_issue_per_ruleKey_off_current_analysis_globally_and_per_assignee() { - String repository = randomAlphanumeric(3); - List ruleKeys = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList(); - String assignee = randomAlphanumeric(10); + String repository = secure().nextAlphanumeric(3); + List ruleKeys = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> secure().nextAlphabetic(3)).toList(); + String assignee = secure().nextAlphanumeric(10); ruleKeys.stream() .map(ruleKey -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setRuleKey(RuleKey.of(repository, ruleKey)).setAssigneeUuid(assignee).setNew(false)) .forEach(underTest::add); @@ -185,7 +184,7 @@ class NewIssuesStatisticsTest { @Test void add_does_not_count_ruleKey_if_null_neither_globally_nor_per_assignee() { - String assignee = randomAlphanumeric(10); + String assignee = secure().nextAlphanumeric(10); underTest.add(new DefaultIssue().setType(randomRuleTypeExceptHotspot).setRuleKey(null).setAssigneeUuid(assignee).setNew(new Random().nextBoolean())); DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.RULE); @@ -200,7 +199,7 @@ class NewIssuesStatisticsTest { @Test void add_counts_issue_per_assignee_on_current_analysis_globally_and_per_assignee() { - List assignees = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList(); + List assignees = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> secure().nextAlphabetic(3)).toList(); assignees.stream() .map(assignee -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setAssigneeUuid(assignee).setNew(true)) .forEach(underTest::add); @@ -228,7 +227,7 @@ class NewIssuesStatisticsTest { @Test void add_counts_issue_per_assignee_off_current_analysis_globally_and_per_assignee() { - List assignees = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList(); + List assignees = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> secure().nextAlphabetic(3)).toList(); assignees.stream() .map(assignee -> new DefaultIssue().setType(randomRuleTypeExceptHotspot).setAssigneeUuid(assignee).setNew(false)) .forEach(underTest::add); @@ -266,8 +265,8 @@ class NewIssuesStatisticsTest { @Test void add_counts_issue_per_tags_on_current_analysis_globally_and_per_assignee() { - List tags = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList(); - String assignee = randomAlphanumeric(10); + List tags = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> secure().nextAlphabetic(3)).toList(); + String assignee = secure().nextAlphanumeric(10); underTest.add(new DefaultIssue().setType(randomRuleTypeExceptHotspot).setTags(tags).setAssigneeUuid(assignee).setNew(true)); DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.TAG); @@ -278,8 +277,8 @@ class NewIssuesStatisticsTest { @Test void add_counts_issue_per_tags_off_current_analysis_globally_and_per_assignee() { - List tags = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> randomAlphabetic(3)).toList(); - String assignee = randomAlphanumeric(10); + List tags = IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> secure().nextAlphabetic(3)).toList(); + String assignee = secure().nextAlphanumeric(10); underTest.add(new DefaultIssue().setType(randomRuleTypeExceptHotspot).setTags(tags).setAssigneeUuid(assignee).setNew(false)); DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.TAG); @@ -290,7 +289,7 @@ class NewIssuesStatisticsTest { @Test void add_does_not_count_tags_if_empty_neither_globally_nor_per_assignee() { - String assignee = randomAlphanumeric(10); + String assignee = secure().nextAlphanumeric(10); underTest.add(new DefaultIssue().setType(randomRuleTypeExceptHotspot).setTags(Collections.emptyList()).setAssigneeUuid(assignee).setNew(new Random().nextBoolean())); DistributedMetricStatsInt globalDistribution = underTest.globalStatistics().getDistributedMetricStats(Metric.TAG); @@ -309,11 +308,11 @@ class NewIssuesStatisticsTest { @Test void verify_toString() { - String componentUuid = randomAlphanumeric(2); - String tag = randomAlphanumeric(3); - String assignee = randomAlphanumeric(4); + String componentUuid = secure().nextAlphanumeric(2); + String tag = secure().nextAlphanumeric(3); + String assignee = secure().nextAlphanumeric(4); int effort = 10 + new Random().nextInt(5); - RuleKey ruleKey = RuleKey.of(randomAlphanumeric(5), randomAlphanumeric(6)); + RuleKey ruleKey = RuleKey.of(secure().nextAlphanumeric(5), secure().nextAlphanumeric(6)); underTest.add(new DefaultIssue() .setType(randomRuleTypeExceptHotspot) .setComponentUuid(componentUuid) diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/IssueWorkflowForSecurityHotspotsTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/IssueWorkflowForSecurityHotspotsTest.java index aac60df573f..52b3abd9e10 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/IssueWorkflowForSecurityHotspotsTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/IssueWorkflowForSecurityHotspotsTest.java @@ -38,7 +38,7 @@ import org.sonar.core.issue.FieldDiffs; import org.sonar.core.issue.IssueChangeContext; import org.sonar.server.issue.IssueFieldsSetter; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.issue.DefaultTransitions.RESET_AS_TO_REVIEW; import static org.sonar.api.issue.DefaultTransitions.RESOLVE_AS_ACKNOWLEDGED; @@ -81,7 +81,7 @@ public class IssueWorkflowForSecurityHotspotsTest { return Stream.of( Issue.RESOLUTIONS.stream(), Issue.SECURITY_HOTSPOT_RESOLUTIONS.stream(), - Stream.of(randomAlphabetic(12), null)) + Stream.of(secure().nextAlphabetic(12), null)) .flatMap(t -> t) .map(t -> new Object[] {t}) .toArray(Object[][]::new); @@ -123,7 +123,7 @@ public class IssueWorkflowForSecurityHotspotsTest { return Stream.of( Issue.RESOLUTIONS.stream(), Issue.SECURITY_HOTSPOT_RESOLUTIONS.stream(), - Stream.of(randomAlphabetic(12))) + Stream.of(secure().nextAlphabetic(12))) .flatMap(t -> t) .filter(t -> !RESOLUTION_TYPES.contains(t)) .map(t -> new Object[] {t}) diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/log/ServerLoggingTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/log/ServerLoggingTest.java index b756b7a8342..b3c00d2fdfd 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/log/ServerLoggingTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/log/ServerLoggingTest.java @@ -57,7 +57,7 @@ public class ServerLoggingTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); - private final String rootLoggerName = RandomStringUtils.randomAlphabetic(20); + private final String rootLoggerName = RandomStringUtils.secure().nextAlphabetic(20); private LogbackHelper logbackHelper = spy(new LogbackHelper()); private MapSettings settings = new MapSettings(); private final ServerProcessLogging serverProcessLogging = mock(ServerProcessLogging.class); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/notification/DefaultNotificationManagerTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/notification/DefaultNotificationManagerTest.java index 9a2b0d77947..f9b0ebe070b 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/notification/DefaultNotificationManagerTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/notification/DefaultNotificationManagerTest.java @@ -44,8 +44,7 @@ import org.sonar.server.notification.NotificationManager.EmailRecipient; import org.sonar.server.notification.NotificationManager.SubscriberPermissionsOnProject; import static com.google.common.collect.Sets.newHashSet; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; @@ -137,7 +136,7 @@ public class DefaultNotificationManagerTest { @Test public void findSubscribedEmailRecipients_fails_with_NPE_if_projectKey_is_null() { - String dispatcherKey = randomAlphabetic(12); + String dispatcherKey = secure().nextAlphabetic(12); assertThatThrownBy(() -> underTest.findSubscribedEmailRecipients(dispatcherKey, null, ALL_MUST_HAVE_ROLE_USER)) .isInstanceOf(NullPointerException.class) @@ -146,7 +145,7 @@ public class DefaultNotificationManagerTest { @Test public void findSubscribedEmailRecipients_with_logins_fails_with_NPE_if_projectKey_is_null() { - String dispatcherKey = randomAlphabetic(12); + String dispatcherKey = secure().nextAlphabetic(12); assertThatThrownBy(() -> underTest.findSubscribedEmailRecipients(dispatcherKey, null, ImmutableSet.of(), ALL_MUST_HAVE_ROLE_USER)) .isInstanceOf(NullPointerException.class) @@ -155,8 +154,8 @@ public class DefaultNotificationManagerTest { @Test public void findSubscribedEmailRecipients_with_logins_fails_with_NPE_if_logins_is_null() { - String dispatcherKey = randomAlphabetic(12); - String projectKey = randomAlphabetic(6); + String dispatcherKey = secure().nextAlphabetic(12); + String projectKey = secure().nextAlphabetic(6); assertThatThrownBy(() -> underTest.findSubscribedEmailRecipients(dispatcherKey, projectKey, null, ALL_MUST_HAVE_ROLE_USER)) .isInstanceOf(NullPointerException.class) @@ -165,8 +164,8 @@ public class DefaultNotificationManagerTest { @Test public void findSubscribedEmailRecipients_with_logins_returns_empty_if_login_set_is_empty() { - String dispatcherKey = randomAlphabetic(12); - String projectKey = randomAlphabetic(6); + String dispatcherKey = secure().nextAlphabetic(12); + String projectKey = secure().nextAlphabetic(6); Set recipients = underTest.findSubscribedEmailRecipients(dispatcherKey, projectKey, ImmutableSet.of(), ALL_MUST_HAVE_ROLE_USER); @@ -175,10 +174,10 @@ public class DefaultNotificationManagerTest { @Test public void findSubscribedEmailRecipients_returns_empty_if_no_email_recipients_in_project_for_dispatcher_key() { - String dispatcherKey = randomAlphabetic(12); - String globalPermission = randomAlphanumeric(4); - String projectPermission = randomAlphanumeric(5); - String projectKey = randomAlphabetic(6); + String dispatcherKey = secure().nextAlphabetic(12); + String globalPermission = secure().nextAlphanumeric(4); + String projectPermission = secure().nextAlphanumeric(5); + String projectKey = secure().nextAlphabetic(6); when(propertiesDao.findEmailSubscribersForNotification(dbSession, dispatcherKey, "EmailNotificationChannel", projectKey)) .thenReturn(Collections.emptySet()); @@ -191,10 +190,10 @@ public class DefaultNotificationManagerTest { @Test public void findSubscribedEmailRecipients_with_logins_returns_empty_if_no_email_recipients_in_project_for_dispatcher_key() { - String dispatcherKey = randomAlphabetic(12); - String globalPermission = randomAlphanumeric(4); - String projectPermission = randomAlphanumeric(5); - String projectKey = randomAlphabetic(6); + String dispatcherKey = secure().nextAlphabetic(12); + String globalPermission = secure().nextAlphanumeric(4); + String projectPermission = secure().nextAlphanumeric(5); + String projectKey = secure().nextAlphabetic(6); Set logins = IntStream.range(0, 1 + new Random().nextInt(10)) .mapToObj(i -> "login_" + i) .collect(Collectors.toSet()); @@ -210,10 +209,10 @@ public class DefaultNotificationManagerTest { @Test public void findSubscribedEmailRecipients_applies_distinct_permission_filtering_global_or_project_subscribers() { - String dispatcherKey = randomAlphabetic(12); - String globalPermission = randomAlphanumeric(4); - String projectPermission = randomAlphanumeric(5); - String projectKey = randomAlphabetic(6); + String dispatcherKey = secure().nextAlphabetic(12); + String globalPermission = secure().nextAlphanumeric(4); + String projectPermission = secure().nextAlphanumeric(5); + String projectKey = secure().nextAlphabetic(6); when(propertiesDao.findEmailSubscribersForNotification(dbSession, dispatcherKey, "EmailNotificationChannel", projectKey)) .thenReturn( newHashSet(EmailSubscriberDto.create("user1", false, "user1@foo"), EmailSubscriberDto.create("user3", false, "user3@foo"), @@ -235,10 +234,10 @@ public class DefaultNotificationManagerTest { @Test public void findSubscribedEmailRecipients_with_logins_applies_distinct_permission_filtering_global_or_project_subscribers() { - String dispatcherKey = randomAlphabetic(12); - String globalPermission = randomAlphanumeric(4); - String projectPermission = randomAlphanumeric(5); - String projectKey = randomAlphabetic(6); + String dispatcherKey = secure().nextAlphabetic(12); + String globalPermission = secure().nextAlphanumeric(4); + String projectPermission = secure().nextAlphanumeric(5); + String projectKey = secure().nextAlphabetic(6); Set logins = ImmutableSet.of("user1", "user2", "user3"); when(propertiesDao.findEmailSubscribersForNotification(dbSession, dispatcherKey, "EmailNotificationChannel", projectKey, logins)) .thenReturn( @@ -261,10 +260,10 @@ public class DefaultNotificationManagerTest { @Test public void findSubscribedEmailRecipients_does_not_call_db_for_project_permission_filtering_if_there_is_no_project_subscriber() { - String dispatcherKey = randomAlphabetic(12); - String globalPermission = randomAlphanumeric(4); - String projectPermission = randomAlphanumeric(5); - String projectKey = randomAlphabetic(6); + String dispatcherKey = secure().nextAlphabetic(12); + String globalPermission = secure().nextAlphanumeric(4); + String projectPermission = secure().nextAlphanumeric(5); + String projectKey = secure().nextAlphabetic(6); Set subscribers = IntStream.range(0, 1 + new Random().nextInt(10)) .mapToObj(i -> EmailSubscriberDto.create("user" + i, true, "user" + i + "@sonarsource.com")) .collect(Collectors.toSet()); @@ -286,10 +285,10 @@ public class DefaultNotificationManagerTest { @Test public void findSubscribedEmailRecipients_with_logins_does_not_call_db_for_project_permission_filtering_if_there_is_no_project_subscriber() { - String dispatcherKey = randomAlphabetic(12); - String globalPermission = randomAlphanumeric(4); - String projectPermission = randomAlphanumeric(5); - String projectKey = randomAlphabetic(6); + String dispatcherKey = secure().nextAlphabetic(12); + String globalPermission = secure().nextAlphanumeric(4); + String projectPermission = secure().nextAlphanumeric(5); + String projectKey = secure().nextAlphabetic(6); Set subscribers = IntStream.range(0, 1 + new Random().nextInt(10)) .mapToObj(i -> EmailSubscriberDto.create("user" + i, true, "user" + i + "@sonarsource.com")) .collect(Collectors.toSet()); @@ -311,10 +310,10 @@ public class DefaultNotificationManagerTest { @Test public void findSubscribedEmailRecipients_does_not_call_DB_for_project_permission_filtering_if_there_is_no_global_subscriber() { - String dispatcherKey = randomAlphabetic(12); - String globalPermission = randomAlphanumeric(4); - String projectPermission = randomAlphanumeric(5); - String projectKey = randomAlphabetic(6); + String dispatcherKey = secure().nextAlphabetic(12); + String globalPermission = secure().nextAlphanumeric(4); + String projectPermission = secure().nextAlphanumeric(5); + String projectKey = secure().nextAlphabetic(6); Set subscribers = IntStream.range(0, 1 + new Random().nextInt(10)) .mapToObj(i -> EmailSubscriberDto.create("user" + i, false, "user" + i + "@sonarsource.com")) .collect(Collectors.toSet()); @@ -336,10 +335,10 @@ public class DefaultNotificationManagerTest { @Test public void findSubscribedEmailRecipients_with_logins_does_not_call_DB_for_project_permission_filtering_if_there_is_no_global_subscriber() { - String dispatcherKey = randomAlphabetic(12); - String globalPermission = randomAlphanumeric(4); - String projectPermission = randomAlphanumeric(5); - String projectKey = randomAlphabetic(6); + String dispatcherKey = secure().nextAlphabetic(12); + String globalPermission = secure().nextAlphanumeric(4); + String projectPermission = secure().nextAlphanumeric(5); + String projectKey = secure().nextAlphabetic(6); Set subscribers = IntStream.range(0, 1 + new Random().nextInt(10)) .mapToObj(i -> EmailSubscriberDto.create("user" + i, false, "user" + i + "@sonarsource.com")) .collect(Collectors.toSet()); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/notification/EmailRecipientTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/notification/EmailRecipientTest.java index ee3c11ea8a7..c11060c6736 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/notification/EmailRecipientTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/notification/EmailRecipientTest.java @@ -22,7 +22,7 @@ package org.sonar.server.notification; import org.junit.Test; import org.sonar.server.notification.NotificationManager.EmailRecipient; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -30,7 +30,7 @@ public class EmailRecipientTest { @Test public void constructor_fails_with_NPE_if_login_is_null() { - String email = randomAlphabetic(12); + String email = secure().nextAlphabetic(12); assertThatThrownBy(() -> new EmailRecipient(null, email)) .isInstanceOf(NullPointerException.class) @@ -39,7 +39,7 @@ public class EmailRecipientTest { @Test public void constructor_fails_with_NPE_if_email_is_null() { - String login = randomAlphabetic(12); + String login = secure().nextAlphabetic(12); assertThatThrownBy(() -> new EmailRecipient(login, null)) .isInstanceOf(NullPointerException.class) @@ -48,8 +48,8 @@ public class EmailRecipientTest { @Test public void equals_is_based_on_login_and_email() { - String login = randomAlphabetic(11); - String email = randomAlphabetic(12); + String login = secure().nextAlphabetic(11); + String email = secure().nextAlphabetic(12); EmailRecipient underTest = new EmailRecipient(login, email); assertThat(underTest) @@ -57,30 +57,30 @@ public class EmailRecipientTest { .isNotNull() .isNotEqualTo(new Object()) .isNotEqualTo(new EmailRecipient(email, login)) - .isNotEqualTo(new EmailRecipient(randomAlphabetic(5), email)) - .isNotEqualTo(new EmailRecipient(login, randomAlphabetic(5))) - .isNotEqualTo(new EmailRecipient(randomAlphabetic(5), randomAlphabetic(6))); + .isNotEqualTo(new EmailRecipient(secure().nextAlphabetic(5), email)) + .isNotEqualTo(new EmailRecipient(login, secure().nextAlphabetic(5))) + .isNotEqualTo(new EmailRecipient(secure().nextAlphabetic(5), secure().nextAlphabetic(6))); } @Test public void hashcode_is_based_on_login_and_email() { - String login = randomAlphabetic(11); - String email = randomAlphabetic(12); + String login = secure().nextAlphabetic(11); + String email = secure().nextAlphabetic(12); EmailRecipient underTest = new EmailRecipient(login, email); assertThat(underTest.hashCode()) .isEqualTo(new EmailRecipient(login, email).hashCode()) .isNotEqualTo(new Object().hashCode()) .isNotEqualTo(new EmailRecipient(email, login).hashCode()) - .isNotEqualTo(new EmailRecipient(randomAlphabetic(5), email).hashCode()) - .isNotEqualTo(new EmailRecipient(login, randomAlphabetic(5)).hashCode()) - .isNotEqualTo(new EmailRecipient(randomAlphabetic(5), randomAlphabetic(6)).hashCode()); + .isNotEqualTo(new EmailRecipient(secure().nextAlphabetic(5), email).hashCode()) + .isNotEqualTo(new EmailRecipient(login, secure().nextAlphabetic(5)).hashCode()) + .isNotEqualTo(new EmailRecipient(secure().nextAlphabetic(5), secure().nextAlphabetic(6)).hashCode()); } @Test public void verify_to_String() { - String login = randomAlphabetic(11); - String email = randomAlphabetic(12); + String login = secure().nextAlphabetic(11); + String email = secure().nextAlphabetic(12); assertThat(new EmailRecipient(login, email)).hasToString("EmailRecipient{'" + login + "':'" + email + "'}"); } diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/notification/NotificationServiceTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/notification/NotificationServiceTest.java index c95bb9cb3ce..7f39711e90d 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/notification/NotificationServiceTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/notification/NotificationServiceTest.java @@ -30,7 +30,7 @@ import org.sonar.api.notifications.Notification; import org.sonar.db.DbClient; import org.sonar.db.property.PropertiesDao; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyCollection; @@ -210,7 +210,7 @@ public class NotificationServiceTest { @Test public void hasProjectSubscribersForType_returns_false_if_there_are_no_handler() { - String projectUuid = randomAlphabetic(7); + String projectUuid = secure().nextAlphabetic(7); NotificationService underTest = new NotificationService(dbClient); assertThat(underTest.hasProjectSubscribersForTypes(projectUuid, ImmutableSet.of(Notification1.class))).isFalse(); @@ -219,9 +219,9 @@ public class NotificationServiceTest { @Test public void hasProjectSubscribersForType_checks_property_for_each_dispatcher_key_supporting_Notification_type() { - String dispatcherKey1A = randomAlphabetic(5); - String dispatcherKey1B = randomAlphabetic(6); - String projectUuid = randomAlphabetic(7); + String dispatcherKey1A = secure().nextAlphabetic(5); + String dispatcherKey1B = secure().nextAlphabetic(6); + String projectUuid = secure().nextAlphabetic(7); NotificationHandler handler1A = getMockOfNotificationHandlerForType(Notification1.class); when(handler1A.getMetadata()).thenReturn(Optional.of(NotificationDispatcherMetadata.create(dispatcherKey1A))); @@ -252,10 +252,10 @@ public class NotificationServiceTest { @Test public void hasProjectSubscribersForType_checks_property_for_each_dispatcher_key_supporting_Notification_types() { - String dispatcherKey1A = randomAlphabetic(5); - String dispatcherKey1B = randomAlphabetic(6); - String dispatcherKey2 = randomAlphabetic(7); - String projectUuid = randomAlphabetic(8); + String dispatcherKey1A = secure().nextAlphabetic(5); + String dispatcherKey1B = secure().nextAlphabetic(6); + String dispatcherKey2 = secure().nextAlphabetic(7); + String projectUuid = secure().nextAlphabetic(8); NotificationHandler handler1A = getMockOfNotificationHandlerForType(Notification1.class); when(handler1A.getMetadata()).thenReturn(Optional.of(NotificationDispatcherMetadata.create(dispatcherKey1A))); @@ -289,9 +289,9 @@ public class NotificationServiceTest { @Test public void hasProjectSubscribersForType_returns_false_if_set_is_empty() { - String dispatcherKey1A = randomAlphabetic(5); - String dispatcherKey1B = randomAlphabetic(6); - String projectUuid = randomAlphabetic(7); + String dispatcherKey1A = secure().nextAlphabetic(5); + String dispatcherKey1B = secure().nextAlphabetic(6); + String projectUuid = secure().nextAlphabetic(7); NotificationHandler handler1A = getMockOfNotificationHandlerForType(Notification1.class); when(handler1A.getMetadata()).thenReturn(Optional.of(NotificationDispatcherMetadata.create(dispatcherKey1A))); @@ -313,9 +313,9 @@ public class NotificationServiceTest { @Test public void hasProjectSubscribersForType_returns_false_for_type_which_have_no_handler() { - String dispatcherKey1A = randomAlphabetic(5); - String dispatcherKey1B = randomAlphabetic(6); - String projectUuid = randomAlphabetic(7); + String dispatcherKey1A = secure().nextAlphabetic(5); + String dispatcherKey1B = secure().nextAlphabetic(6); + String projectUuid = secure().nextAlphabetic(7); NotificationHandler handler1A = getMockOfNotificationHandlerForType(Notification1.class); when(handler1A.getMetadata()).thenReturn(Optional.of(NotificationDispatcherMetadata.create(dispatcherKey1A))); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/permission/index/AuthorizationDocTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/permission/index/AuthorizationDocTest.java index 75246618e7c..23e47a79507 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/permission/index/AuthorizationDocTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/permission/index/AuthorizationDocTest.java @@ -30,7 +30,7 @@ import org.junit.runner.RunWith; import org.sonar.server.es.Index; import org.sonar.server.es.IndexType; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Fail.fail; @@ -40,7 +40,7 @@ public class AuthorizationDocTest { @Test public void idOf_returns_argument_with_a_prefix() { - String s = randomAlphabetic(12); + String s = secure().nextAlphabetic(12); assertThat(AuthorizationDoc.idOf(s)).isEqualTo("auth_" + s); } @@ -62,13 +62,13 @@ public class AuthorizationDocTest { public void projectUuidOf_returns_substring_if_starts_with_id_prefix() { assertThat(AuthorizationDoc.entityUuidOf("auth_")).isEmpty(); - String id = randomAlphabetic(1 + new Random().nextInt(10)); + String id = secure().nextAlphabetic(1 + new Random().nextInt(10)); assertThat(AuthorizationDoc.entityUuidOf("auth_" + id)).isEqualTo(id); } @Test public void projectUuidOf_returns_argument_if_does_not_starts_with_id_prefix() { - String id = randomAlphabetic(1 + new Random().nextInt(10)); + String id = secure().nextAlphabetic(1 + new Random().nextInt(10)); assertThat(AuthorizationDoc.entityUuidOf(id)).isEqualTo(id); assertThat(AuthorizationDoc.entityUuidOf("")).isEmpty(); } @@ -102,7 +102,7 @@ public class AuthorizationDocTest { @Test public void fromDto_of_allowAnyone_is_false_and_no_user_nor_group() { - IndexPermissions underTest = new IndexPermissions(randomAlphabetic(3), randomAlphabetic(4)); + IndexPermissions underTest = new IndexPermissions(secure().nextAlphabetic(3), secure().nextAlphabetic(4)); AuthorizationDoc doc = AuthorizationDoc.fromDto(IndexType.main(Index.simple("foo"), "bar"), underTest); @@ -116,7 +116,7 @@ public class AuthorizationDocTest { @Test public void fromDto_defines_userIds_and_groupIds_if_allowAnyone_is_false() { - IndexPermissions underTest = new IndexPermissions(randomAlphabetic(3), randomAlphabetic(4)); + IndexPermissions underTest = new IndexPermissions(secure().nextAlphabetic(3), secure().nextAlphabetic(4)); IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(String::valueOf).forEach(underTest::addUserUuid); IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(Integer::toString).forEach(underTest::addGroupUuid); @@ -132,7 +132,7 @@ public class AuthorizationDocTest { @Test public void fromDto_ignores_userIds_and_groupUuids_if_allowAnyone_is_true() { - IndexPermissions underTest = new IndexPermissions(randomAlphabetic(3), randomAlphabetic(4)); + IndexPermissions underTest = new IndexPermissions(secure().nextAlphabetic(3), secure().nextAlphabetic(4)); IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(String::valueOf).forEach(underTest::addUserUuid); IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(Integer::toString).forEach(underTest::addGroupUuid); underTest.allowAnyone(); @@ -157,13 +157,13 @@ public class AuthorizationDocTest { @DataProvider public static Object[][] dtos() { - IndexPermissions allowAnyone = new IndexPermissions(randomAlphabetic(3), randomAlphabetic(4)); + IndexPermissions allowAnyone = new IndexPermissions(secure().nextAlphabetic(3), secure().nextAlphabetic(4)); allowAnyone.allowAnyone(); - IndexPermissions someUserIds = new IndexPermissions(randomAlphabetic(3), randomAlphabetic(4)); + IndexPermissions someUserIds = new IndexPermissions(secure().nextAlphabetic(3), secure().nextAlphabetic(4)); IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(String::valueOf).forEach(someUserIds::addUserUuid); - IndexPermissions someGroupUuids = new IndexPermissions(randomAlphabetic(3), randomAlphabetic(4)); + IndexPermissions someGroupUuids = new IndexPermissions(secure().nextAlphabetic(3), secure().nextAlphabetic(4)); IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(Integer::toString).forEach(someGroupUuids::addGroupUuid); - IndexPermissions someGroupUuidAndUserIs = new IndexPermissions(randomAlphabetic(3), randomAlphabetic(4)); + IndexPermissions someGroupUuidAndUserIs = new IndexPermissions(secure().nextAlphabetic(3), secure().nextAlphabetic(4)); IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(String::valueOf).forEach(someGroupUuidAndUserIs::addUserUuid); IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(Integer::toString).forEach(someGroupUuidAndUserIs::addGroupUuid); return new Object[][] { diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/EvaluatedQualityGateTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/EvaluatedQualityGateTest.java index e401bd741c8..2b0ce22d34d 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/EvaluatedQualityGateTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/EvaluatedQualityGateTest.java @@ -50,7 +50,7 @@ public class EvaluatedQualityGateTest { private final Level randomStatus = Level.values()[random.nextInt(Level.values().length)]; private final EvaluatedCondition.EvaluationStatus randomEvaluationStatus = EvaluatedCondition.EvaluationStatus.values()[random .nextInt(EvaluatedCondition.EvaluationStatus.values().length)]; - private final String randomValue = random.nextBoolean() ? null : RandomStringUtils.randomAlphanumeric(3); + private final String randomValue = random.nextBoolean() ? null : RandomStringUtils.secure().nextAlphanumeric(3); private EvaluatedQualityGate.Builder builder = newBuilder(); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/notification/QGChangeNotificationHandlerTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/notification/QGChangeNotificationHandlerTest.java index a3b3843bd83..2aaf636548e 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/notification/QGChangeNotificationHandlerTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/notification/QGChangeNotificationHandlerTest.java @@ -34,7 +34,7 @@ import org.sonar.server.notification.email.EmailNotificationChannel; import static java.util.Collections.emptySet; import static java.util.stream.Collectors.toSet; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -128,7 +128,7 @@ public class QGChangeNotificationHandlerTest { @Test public void deliver_has_no_effect_if_no_notification_has_subscribed_recipients_to_QGChange_notifications() { - String projectKey = randomAlphabetic(12); + String projectKey = secure().nextAlphabetic(12); QGChangeNotification notification = newNotification(projectKey); when(emailNotificationChannel.isActivated()).thenReturn(true); when(notificationManager.findSubscribedEmailRecipients(QG_CHANGE_DISPATCHER_KEY, projectKey, ALL_MUST_HAVE_ROLE_USER)) @@ -145,7 +145,7 @@ public class QGChangeNotificationHandlerTest { @Test public void deliver_ignores_notification_without_projectKey() { - String projectKey = randomAlphabetic(10); + String projectKey = secure().nextAlphabetic(10); Set withProjectKey = IntStream.range(0, 1 + new Random().nextInt(5)) .mapToObj(i -> newNotification(projectKey)) .collect(toSet()); @@ -178,8 +178,8 @@ public class QGChangeNotificationHandlerTest { @Test public void deliver_checks_by_projectKey_if_notifications_have_subscribed_assignee_to_QGChange_notifications() { - String projectKey1 = randomAlphabetic(10); - String projectKey2 = randomAlphabetic(11); + String projectKey1 = secure().nextAlphabetic(10); + String projectKey2 = secure().nextAlphabetic(11); Set notifications1 = randomSetOfNotifications(projectKey1); Set notifications2 = randomSetOfNotifications(projectKey2); when(emailNotificationChannel.isActivated()).thenReturn(true); @@ -216,8 +216,8 @@ public class QGChangeNotificationHandlerTest { @Test public void deliver_send_notifications_to_all_subscribers_of_all_projects() { - String projectKey1 = randomAlphabetic(10); - String projectKey2 = randomAlphabetic(11); + String projectKey1 = secure().nextAlphabetic(10); + String projectKey2 = secure().nextAlphabetic(11); Set notifications1 = randomSetOfNotifications(projectKey1); Set notifications2 = randomSetOfNotifications(projectKey2); when(emailNotificationChannel.isActivated()).thenReturn(true); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/setting/ChildSettingsTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/setting/ChildSettingsTest.java index 0bf3c297dfb..0d8f2d53de3 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/setting/ChildSettingsTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/setting/ChildSettingsTest.java @@ -29,7 +29,7 @@ import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -42,21 +42,21 @@ public class ChildSettingsTest { @Test public void childSettings_should_retrieve_parent_settings() { - String multipleValuesKey = randomAlphanumeric(19); + String multipleValuesKey = secure().nextAlphanumeric(19); PropertyDefinition multipleValues = PropertyDefinition.builder(multipleValuesKey).multiValues(true).build(); MapSettings parent = new MapSettings(new PropertyDefinitions(System2.INSTANCE, Collections.singletonList(multipleValues))); ChildSettings underTest = new ChildSettings(parent); - parent.setProperty(randomAlphanumeric(10), randomAlphanumeric(20)); - parent.setProperty(randomAlphanumeric(11), RANDOM.nextLong()); - parent.setProperty(randomAlphanumeric(12), RANDOM.nextDouble()); - parent.setProperty(randomAlphanumeric(13), RANDOM.nextFloat()); - parent.setProperty(randomAlphanumeric(14), RANDOM.nextBoolean()); - parent.setProperty(randomAlphanumeric(15), RANDOM.nextInt(Integer.MAX_VALUE)); - parent.setProperty(randomAlphanumeric(16), new Date(RANDOM.nextInt())); - parent.setProperty(randomAlphanumeric(17), new Date(RANDOM.nextInt()), true); - parent.setProperty(randomAlphanumeric(18), new Date(RANDOM.nextInt()), false); - parent.setProperty(multipleValuesKey, new String[] {randomAlphanumeric(10), randomAlphanumeric(20)}); + parent.setProperty(secure().nextAlphanumeric(10), secure().nextAlphanumeric(20)); + parent.setProperty(secure().nextAlphanumeric(11), RANDOM.nextLong()); + parent.setProperty(secure().nextAlphanumeric(12), RANDOM.nextDouble()); + parent.setProperty(secure().nextAlphanumeric(13), RANDOM.nextFloat()); + parent.setProperty(secure().nextAlphanumeric(14), RANDOM.nextBoolean()); + parent.setProperty(secure().nextAlphanumeric(15), RANDOM.nextInt(Integer.MAX_VALUE)); + parent.setProperty(secure().nextAlphanumeric(16), new Date(RANDOM.nextInt())); + parent.setProperty(secure().nextAlphanumeric(17), new Date(RANDOM.nextInt()), true); + parent.setProperty(secure().nextAlphanumeric(18), new Date(RANDOM.nextInt()), false); + parent.setProperty(multipleValuesKey, new String[] {secure().nextAlphanumeric(10), secure().nextAlphanumeric(20)}); assertThat(underTest.getProperties()).isEqualTo(parent.getProperties()); } @@ -70,16 +70,16 @@ public class ChildSettingsTest { @Test public void set_will_throw_NPE_if_value_is_null() { - assertThatThrownBy(() -> underTest.set(randomAlphanumeric(10), null)) + assertThatThrownBy(() -> underTest.set(secure().nextAlphanumeric(10), null)) .isInstanceOf(NullPointerException.class) .hasMessage("value can't be null"); } @Test public void childSettings_override_parent() { - String key = randomAlphanumeric(10); - parent.setProperty(key, randomAlphanumeric(20)); - underTest.setProperty(key, randomAlphanumeric(10)); + String key = secure().nextAlphanumeric(10); + parent.setProperty(key, secure().nextAlphanumeric(20)); + underTest.setProperty(key, secure().nextAlphanumeric(10)); Optional result = underTest.get(key); assertThat(result).isPresent(); @@ -88,13 +88,13 @@ public class ChildSettingsTest { @Test public void remove_should_not_throw_exception_if_key_is_not_present() { - underTest.remove(randomAlphanumeric(90)); + underTest.remove(secure().nextAlphanumeric(90)); } @Test public void remove_should_remove_value() { - String key = randomAlphanumeric(10); - String childValue = randomAlphanumeric(10); + String key = secure().nextAlphanumeric(10); + String childValue = secure().nextAlphanumeric(10); underTest.set(key, childValue); assertThat(underTest.get(key)).isEqualTo(Optional.of(childValue)); @@ -105,9 +105,9 @@ public class ChildSettingsTest { @Test public void remove_should_retrieve_parent_value() { - String key = randomAlphanumeric(10); - String childValue = randomAlphanumeric(10); - String parentValue = randomAlphanumeric(10); + String key = secure().nextAlphanumeric(10); + String childValue = secure().nextAlphanumeric(10); + String parentValue = secure().nextAlphanumeric(10); parent.setProperty(key, parentValue); underTest.set(key, childValue); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/setting/ThreadLocalSettingsTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/setting/ThreadLocalSettingsTest.java index 3c0d9e5c8b9..2b2deae3a99 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/setting/ThreadLocalSettingsTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/setting/ThreadLocalSettingsTest.java @@ -40,7 +40,7 @@ import org.sonar.core.config.CorePropertyDefinitions; import static java.util.Collections.emptyMap; import static java.util.Collections.unmodifiableMap; import static java.util.concurrent.TimeUnit.SECONDS; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.data.MapEntry.entry; import static org.mockito.Mockito.doAnswer; @@ -310,9 +310,9 @@ public class ThreadLocalSettingsTest { @Test public void getProperties_return_properties_from_previous_thread_cache_if_DB_error_on_not_first_call() { - String key = randomAlphanumeric(3); - String value1 = randomAlphanumeric(4); - String value2 = randomAlphanumeric(5); + String key = secure().nextAlphanumeric(3); + String value1 = secure().nextAlphanumeric(4); + String value2 = secure().nextAlphanumeric(5); SettingLoader settingLoaderMock = mock(SettingLoader.class); PersistenceException toBeThrown = new PersistenceException("Faking an error connecting to DB"); doAnswer(invocationOnMock -> ImmutableMap.of(key, value1)) @@ -342,7 +342,7 @@ public class ThreadLocalSettingsTest { public void get_returns_empty_if_DB_error_on_first_call_ever_out_of_thread_cache() { SettingLoader settingLoaderMock = mock(SettingLoader.class); PersistenceException toBeThrown = new PersistenceException("Faking an error connecting to DB"); - String key = randomAlphanumeric(3); + String key = secure().nextAlphanumeric(3); doThrow(toBeThrown).when(settingLoaderMock).load(key); underTest = new ThreadLocalSettings(new PropertyDefinitions(system), new Properties(), settingLoaderMock); @@ -353,7 +353,7 @@ public class ThreadLocalSettingsTest { public void get_returns_empty_if_DB_error_on_first_call_ever_in_thread_cache() { SettingLoader settingLoaderMock = mock(SettingLoader.class); PersistenceException toBeThrown = new PersistenceException("Faking an error connecting to DB"); - String key = randomAlphanumeric(3); + String key = secure().nextAlphanumeric(3); doThrow(toBeThrown).when(settingLoaderMock).load(key); underTest = new ThreadLocalSettings(new PropertyDefinitions(system), new Properties(), settingLoaderMock); underTest.load(); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/webhook/WebhookCallerImplTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/webhook/WebhookCallerImplTest.java index 385cdf137cf..ab939e2d093 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/webhook/WebhookCallerImplTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/webhook/WebhookCallerImplTest.java @@ -41,7 +41,7 @@ import org.sonar.api.utils.Version; import org.sonar.core.platform.SonarQubeVersion; import org.sonar.server.util.OkHttpClientProvider; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; import static org.sonar.api.CoreProperties.SONAR_VALIDATE_WEBHOOKS_PROPERTY; @@ -68,7 +68,7 @@ public class WebhookCallerImplTest { @Test public void post_payload_to_http_server() throws Exception { - Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, randomAlphanumeric(40), + Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, secure().nextAlphanumeric(40), "my-webhook", server.url("/ping").toString(), null); server.enqueue(new MockResponse().setBody("pong").setResponseCode(201)); @@ -94,7 +94,7 @@ public class WebhookCallerImplTest { @Test public void sign_payload_if_secret_is_set() throws Exception { - Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, randomAlphanumeric(40), + Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, secure().nextAlphanumeric(40), "my-webhook", server.url("/ping").toString(), "my_secret"); server.enqueue(new MockResponse().setBody("pong").setResponseCode(201)); @@ -107,7 +107,7 @@ public class WebhookCallerImplTest { @Test public void silently_catch_error_when_external_server_does_not_answer() throws Exception { Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, - randomAlphanumeric(40), "my-webhook", server.url("/ping").toString(), null); + secure().nextAlphanumeric(40), "my-webhook", server.url("/ping").toString(), null); server.shutdown(); WebhookDelivery delivery = newSender(false).call(webhook, PAYLOAD); @@ -124,7 +124,7 @@ public class WebhookCallerImplTest { @Test public void silently_catch_error_when_url_is_incorrect() { Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, - randomAlphanumeric(40), "my-webhook", "this_is_not_an_url", null); + secure().nextAlphanumeric(40), "my-webhook", "this_is_not_an_url", null); WebhookDelivery delivery = newSender(false).call(webhook, PAYLOAD); @@ -143,7 +143,7 @@ public class WebhookCallerImplTest { @Test public void redirects_should_be_followed_with_POST_method() throws Exception { Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, - randomAlphanumeric(40), "my-webhook", server.url("/redirect").toString(), null); + secure().nextAlphanumeric(40), "my-webhook", server.url("/redirect").toString(), null); // /redirect redirects to /target server.enqueue(new MockResponse().setResponseCode(307).setHeader("Location", server.url("target"))); @@ -166,7 +166,7 @@ public class WebhookCallerImplTest { public void credentials_are_propagated_to_POST_redirects() throws Exception { HttpUrl url = server.url("/redirect").newBuilder().username("theLogin").password("thePassword").build(); Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, - randomAlphanumeric(40), "my-webhook", url.toString(), null); + secure().nextAlphanumeric(40), "my-webhook", url.toString(), null); // /redirect redirects to /target server.enqueue(new MockResponse().setResponseCode(307).setHeader("Location", server.url("target"))); @@ -187,7 +187,7 @@ public class WebhookCallerImplTest { public void redirects_throws_ISE_if_header_Location_is_missing() { HttpUrl url = server.url("/redirect"); Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, - randomAlphanumeric(40), "my-webhook", url.toString(), null); + secure().nextAlphanumeric(40), "my-webhook", url.toString(), null); server.enqueue(new MockResponse().setResponseCode(307)); @@ -203,7 +203,7 @@ public class WebhookCallerImplTest { public void redirects_throws_ISE_if_header_Location_does_not_relate_to_a_supported_protocol() { HttpUrl url = server.url("/redirect"); Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, - randomAlphanumeric(40), "my-webhook", url.toString(), null); + secure().nextAlphanumeric(40), "my-webhook", url.toString(), null); server.enqueue(new MockResponse().setResponseCode(307).setHeader("Location", "ftp://foo")); @@ -219,7 +219,7 @@ public class WebhookCallerImplTest { public void send_basic_authentication_header_if_url_contains_credentials() throws Exception { HttpUrl url = server.url("/ping").newBuilder().username("theLogin").password("thePassword").build(); Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, - randomAlphanumeric(40), "my-webhook", url.toString(), null); + secure().nextAlphanumeric(40), "my-webhook", url.toString(), null); server.enqueue(new MockResponse().setBody("pong")); WebhookDelivery delivery = newSender(false).call(webhook, PAYLOAD); @@ -235,7 +235,7 @@ public class WebhookCallerImplTest { public void silently_catch_error_when_url_is_localhost(){ String url = server.url("/").toString(); Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, - randomAlphanumeric(40), "my-webhook", url, null); + secure().nextAlphanumeric(40), "my-webhook", url, null); WebhookDelivery delivery = newSender(true).call(webhook, PAYLOAD); @@ -258,7 +258,7 @@ public class WebhookCallerImplTest { .thenReturn(ImmutableList.of(inetAddress)); Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, - randomAlphanumeric(40), "my-webhook", url, null); + secure().nextAlphanumeric(40), "my-webhook", url, null); WebhookDelivery delivery = newSender(true).call(webhook, PAYLOAD); diff --git a/server/sonar-server-common/src/testFixtures/java/org/sonar/server/issue/IssueDocTesting.java b/server/sonar-server-common/src/testFixtures/java/org/sonar/server/issue/IssueDocTesting.java index 255ee0ce5f0..cecedee55b1 100644 --- a/server/sonar-server-common/src/testFixtures/java/org/sonar/server/issue/IssueDocTesting.java +++ b/server/sonar-server-common/src/testFixtures/java/org/sonar/server/issue/IssueDocTesting.java @@ -33,7 +33,7 @@ import org.sonar.db.component.ComponentDto; import org.sonar.server.issue.index.IssueDoc; import org.sonar.server.issue.index.IssueScope; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.sonar.api.issue.Issue.STATUS_OPEN; public class IssueDocTesting { @@ -86,13 +86,13 @@ public class IssueDocTesting { doc.setKey(Uuids.createFast()); doc.setRuleUuid(Uuids.createFast()); doc.setType(RuleType.CODE_SMELL); - doc.setAssigneeUuid("assignee_uuid_" + randomAlphabetic(26)); - doc.setAuthorLogin("author_" + randomAlphabetic(5)); + doc.setAssigneeUuid("assignee_uuid_" + secure().nextAlphabetic(26)); + doc.setAuthorLogin("author_" + secure().nextAlphabetic(5)); doc.setScope(IssueScope.MAIN); - doc.setLanguage("language_" + randomAlphabetic(5)); + doc.setLanguage("language_" + secure().nextAlphabetic(5)); doc.setComponentUuid(Uuids.createFast()); - doc.setFilePath("filePath_" + randomAlphabetic(5)); - doc.setDirectoryPath("directory_" + randomAlphabetic(5)); + doc.setFilePath("filePath_" + secure().nextAlphabetic(5)); + doc.setDirectoryPath("directory_" + secure().nextAlphabetic(5)); doc.setProjectUuid(Uuids.createFast()); doc.setLine(RANDOM.nextInt(1_000) + 1); doc.setStatus(STATUS_OPEN); diff --git a/server/sonar-server-common/src/testFixtures/java/org/sonar/server/issue/notification/IssuesChangesNotificationBuilderTesting.java b/server/sonar-server-common/src/testFixtures/java/org/sonar/server/issue/notification/IssuesChangesNotificationBuilderTesting.java index b9f0d04af2d..43db339b666 100644 --- a/server/sonar-server-common/src/testFixtures/java/org/sonar/server/issue/notification/IssuesChangesNotificationBuilderTesting.java +++ b/server/sonar-server-common/src/testFixtures/java/org/sonar/server/issue/notification/IssuesChangesNotificationBuilderTesting.java @@ -35,7 +35,7 @@ import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.User import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.UserChange; import static com.google.common.base.Preconditions.checkArgument; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.sonar.api.rules.RuleType.BUG; import static org.sonar.api.rules.RuleType.CODE_SMELL; import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT; @@ -75,7 +75,7 @@ public class IssuesChangesNotificationBuilderTesting { static ChangedIssue newChangedIssue(String key, Project project, Rule rule) { return new ChangedIssue.Builder(key) - .setNewStatus(randomAlphabetic(19)) + .setNewStatus(secure().nextAlphabetic(19)) .setProject(project) .setRule(rule) .build(); @@ -94,7 +94,7 @@ public class IssuesChangesNotificationBuilderTesting { } static Rule newRule(String ruleName, RuleType ruleType) { - return new Rule(RuleKey.of(randomAlphabetic(6), randomAlphabetic(7)), ruleType, ruleName); + return new Rule(RuleKey.of(secure().nextAlphabetic(6), secure().nextAlphabetic(7)), ruleType, ruleName); } static Rule newRandomNotAHotspotRule(String ruleName) { @@ -114,7 +114,7 @@ public class IssuesChangesNotificationBuilderTesting { } static UserChange newUserChange() { - return new UserChange(new Random().nextLong(), new User(randomAlphabetic(4), randomAlphabetic(5), randomAlphabetic(6))); + return new UserChange(new Random().nextLong(), new User(secure().nextAlphabetic(4), secure().nextAlphabetic(5), secure().nextAlphabetic(6))); } static AnalysisChange newAnalysisChange() { diff --git a/server/sonar-telemetry/src/it/java/org/sonar/telemetry/legacy/TelemetryDataLoaderImplIT.java b/server/sonar-telemetry/src/it/java/org/sonar/telemetry/legacy/TelemetryDataLoaderImplIT.java index a523f348f1e..e4f21c21a6d 100644 --- a/server/sonar-telemetry/src/it/java/org/sonar/telemetry/legacy/TelemetryDataLoaderImplIT.java +++ b/server/sonar-telemetry/src/it/java/org/sonar/telemetry/legacy/TelemetryDataLoaderImplIT.java @@ -77,7 +77,7 @@ import org.sonar.telemetry.legacy.TelemetryData.ProjectStatistics; import org.sonar.updatecenter.common.Version; import static java.util.Arrays.asList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import static org.assertj.core.groups.Tuple.tuple; @@ -565,8 +565,8 @@ class TelemetryDataLoaderImplIT { @Test void send_server_id_and_version() { - String id = randomAlphanumeric(40); - String version = randomAlphanumeric(10); + String id = secure().nextAlphanumeric(40); + String version = secure().nextAlphanumeric(10); server.setId(id); server.setVersion(version); diff --git a/server/sonar-telemetry/src/test/java/org/sonar/telemetry/FakeServer.java b/server/sonar-telemetry/src/test/java/org/sonar/telemetry/FakeServer.java index 5fa8a71ed47..9377c13ddf9 100644 --- a/server/sonar-telemetry/src/test/java/org/sonar/telemetry/FakeServer.java +++ b/server/sonar-telemetry/src/test/java/org/sonar/telemetry/FakeServer.java @@ -22,15 +22,15 @@ package org.sonar.telemetry; import java.util.Date; import org.sonar.api.platform.Server; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; public class FakeServer extends Server { private String id; private String version; public FakeServer() { - this.id = randomAlphanumeric(20); - this.version = randomAlphanumeric(10); + this.id = secure().nextAlphanumeric(20); + this.version = secure().nextAlphanumeric(10); } @Override diff --git a/server/sonar-telemetry/src/test/java/org/sonar/telemetry/legacy/TelemetryDataJsonWriterTest.java b/server/sonar-telemetry/src/test/java/org/sonar/telemetry/legacy/TelemetryDataJsonWriterTest.java index a4cdbb2559d..1984cf4b041 100644 --- a/server/sonar-telemetry/src/test/java/org/sonar/telemetry/legacy/TelemetryDataJsonWriterTest.java +++ b/server/sonar-telemetry/src/test/java/org/sonar/telemetry/legacy/TelemetryDataJsonWriterTest.java @@ -46,7 +46,7 @@ import org.sonar.server.qualitygate.Condition; import org.sonar.server.util.DigestUtil; import static java.util.stream.Collectors.joining; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -138,8 +138,8 @@ class TelemetryDataJsonWriterTest { @Test void writes_database() { - String name = randomAlphabetic(12); - String version = randomAlphabetic(10); + String name = secure().nextAlphabetic(12); + String version = secure().nextAlphabetic(10); TelemetryData data = telemetryBuilder() .setDatabase(new TelemetryData.Database(name, version)) .build(); @@ -226,7 +226,7 @@ class TelemetryDataJsonWriterTest { @Test void write_installation_version() { - String installationVersion = randomAlphabetic(5); + String installationVersion = secure().nextAlphabetic(5); TelemetryData data = telemetryBuilder() .setInstallationVersion(installationVersion) .build(); diff --git a/server/sonar-webserver-api/src/it/java/org/sonar/server/rule/CachingRuleFinderIT.java b/server/sonar-webserver-api/src/it/java/org/sonar/server/rule/CachingRuleFinderIT.java index dee8b18493e..2a39d2ad552 100644 --- a/server/sonar-webserver-api/src/it/java/org/sonar/server/rule/CachingRuleFinderIT.java +++ b/server/sonar-webserver-api/src/it/java/org/sonar/server/rule/CachingRuleFinderIT.java @@ -39,7 +39,7 @@ import org.sonar.db.rule.RuleParamDto; import org.sonar.db.rule.RuleTesting; import static java.util.stream.Collectors.toList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.mock; @@ -133,12 +133,12 @@ public class CachingRuleFinderIT { @Test public void findByKey_returns_null_when_repository_key_is_null() { - assertThat(underTest.findByKey(null, randomAlphabetic(2))).isNull(); + assertThat(underTest.findByKey(null, secure().nextAlphabetic(2))).isNull(); } @Test public void findByKey_returns_null_when_key_is_null() { - assertThat(underTest.findByKey(randomAlphabetic(2), null)).isNull(); + assertThat(underTest.findByKey(secure().nextAlphabetic(2), null)).isNull(); } @Test @@ -175,7 +175,7 @@ public class CachingRuleFinderIT { .isEqualTo(otherRule.getKey()); assertThat(underTest.find(RuleQuery.create().withRepositoryKey(repoKey.toLowerCase()))) .isNull(); - assertThat(underTest.find(RuleQuery.create().withRepositoryKey(randomAlphabetic(3)))) + assertThat(underTest.find(RuleQuery.create().withRepositoryKey(secure().nextAlphabetic(3)))) .isNull(); } @@ -196,7 +196,7 @@ public class CachingRuleFinderIT { .isEqualTo(otherRule.getKey()); assertThat(underTest.find(RuleQuery.create().withKey(ruleKey.toLowerCase()))) .isNull(); - assertThat(underTest.find(RuleQuery.create().withKey(randomAlphabetic(3)))) + assertThat(underTest.find(RuleQuery.create().withKey(secure().nextAlphabetic(3)))) .isNull(); } @@ -217,7 +217,7 @@ public class CachingRuleFinderIT { .isEqualTo(otherRule.getKey()); assertThat(underTest.find(RuleQuery.create().withConfigKey(configKey.toLowerCase()))) .isNull(); - assertThat(underTest.find(RuleQuery.create().withConfigKey(randomAlphabetic(3)))) + assertThat(underTest.find(RuleQuery.create().withConfigKey(secure().nextAlphabetic(3)))) .isNull(); } @@ -283,7 +283,7 @@ public class CachingRuleFinderIT { .containsExactly(otherRule.getKey()); assertThat(underTest.findAll(RuleQuery.create().withRepositoryKey(repoKey.toLowerCase()))) .isEmpty(); - assertThat(underTest.findAll(RuleQuery.create().withRepositoryKey(randomAlphabetic(3)))) + assertThat(underTest.findAll(RuleQuery.create().withRepositoryKey(secure().nextAlphabetic(3)))) .isEmpty(); } @@ -306,7 +306,7 @@ public class CachingRuleFinderIT { .containsExactly(otherRule.getKey()); assertThat(underTest.findAll(RuleQuery.create().withKey(ruleKey.toLowerCase()))) .isEmpty(); - assertThat(underTest.findAll(RuleQuery.create().withKey(randomAlphabetic(3)))) + assertThat(underTest.findAll(RuleQuery.create().withKey(secure().nextAlphabetic(3)))) .isEmpty(); } @@ -329,7 +329,7 @@ public class CachingRuleFinderIT { .containsExactly(otherRule.getKey()); assertThat(underTest.findAll(RuleQuery.create().withConfigKey(configKey.toLowerCase()))) .isEmpty(); - assertThat(underTest.findAll(RuleQuery.create().withConfigKey(randomAlphabetic(3)))) + assertThat(underTest.findAll(RuleQuery.create().withConfigKey(secure().nextAlphabetic(3)))) .isEmpty(); } diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/exceptions/NotFoundExceptionTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/exceptions/NotFoundExceptionTest.java index f34b8117ba9..295d757243a 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/exceptions/NotFoundExceptionTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/exceptions/NotFoundExceptionTest.java @@ -22,7 +22,7 @@ package org.sonar.server.exceptions; import java.util.Optional; import org.junit.Test; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.sonar.server.exceptions.NotFoundException.checkFound; @@ -31,13 +31,13 @@ import static org.sonar.server.exceptions.NotFoundException.checkFoundWithOption public class NotFoundExceptionTest { @Test public void http_code_is_404() { - NotFoundException underTest = new NotFoundException(randomAlphabetic(12)); + NotFoundException underTest = new NotFoundException(secure().nextAlphabetic(12)); assertThat(underTest.httpCode()).isEqualTo(404); } @Test public void message_is_constructor_argument() { - String message = randomAlphabetic(12); + String message = secure().nextAlphabetic(12); NotFoundException underTest = new NotFoundException(message); assertThat(underTest.getMessage()).isEqualTo(message); @@ -45,7 +45,7 @@ public class NotFoundExceptionTest { @Test public void checkFound_type_throws_NotFoundException_if_parameter_is_null() { - String message = randomAlphabetic(12); + String message = secure().nextAlphabetic(12); assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> checkFound(null, message)) .withMessage(message); @@ -61,7 +61,7 @@ public class NotFoundExceptionTest { @Test public void checkFound_return_parameter_if_parameter_is_not_null() { - String message = randomAlphabetic(12); + String message = secure().nextAlphabetic(12); Object o = new Object(); assertThat(checkFound(o, message)).isSameAs(o); @@ -69,7 +69,7 @@ public class NotFoundExceptionTest { @Test public void checkFoundWithOptional_throws_NotFoundException_if_empty() { - String message = randomAlphabetic(12); + String message = secure().nextAlphabetic(12); assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> checkFoundWithOptional(Optional.empty(), message)) .withMessage(message); @@ -85,7 +85,7 @@ public class NotFoundExceptionTest { @Test public void checkFoundWithOptional_return_content_of_if_not_empty() { - String message = randomAlphabetic(12); + String message = secure().nextAlphabetic(12); Object o = new Object(); assertThat(checkFoundWithOptional(Optional.of(o), message)).isSameAs(o); diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/edition/EditionBundledPluginsTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/edition/EditionBundledPluginsTest.java index 47d9d3a3cab..6dad3bdf7ad 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/edition/EditionBundledPluginsTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/edition/EditionBundledPluginsTest.java @@ -24,7 +24,7 @@ import org.junit.Test; import org.sonar.core.platform.PluginInfo; import org.sonar.updatecenter.common.Plugin; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -40,21 +40,21 @@ public class EditionBundledPluginsTest { @Test public void isEditionBundled_on_Plugin_returns_false_for_SonarSource_and_non_commercial_license() { - Plugin plugin = newPlugin(randomizeCase("SonarSource"), randomAlphanumeric(3)); + Plugin plugin = newPlugin(randomizeCase("SonarSource"), secure().nextAlphanumeric(3)); assertThat(EditionBundledPlugins.isEditionBundled(plugin)).isFalse(); } @Test public void isEditionBundled_on_Plugin_returns_false_for_license_SonarSource_and_non_SonarSource_organization() { - Plugin plugin = newPlugin(randomAlphanumeric(3), randomizeCase("SonarSource")); + Plugin plugin = newPlugin(secure().nextAlphanumeric(3), randomizeCase("SonarSource")); assertThat(EditionBundledPlugins.isEditionBundled(plugin)).isFalse(); } @Test public void isEditionBundled_on_Plugin_returns_false_for_license_Commercial_and_non_SonarSource_organization() { - Plugin plugin = newPlugin(randomAlphanumeric(3), randomizeCase("Commercial")); + Plugin plugin = newPlugin(secure().nextAlphanumeric(3), randomizeCase("Commercial")); assertThat(EditionBundledPlugins.isEditionBundled(plugin)).isFalse(); } @@ -81,21 +81,21 @@ public class EditionBundledPluginsTest { @Test public void isEditionBundled_on_PluginInfo_returns_false_for_SonarSource_and_non_commercial_license() { - PluginInfo pluginInfo = newPluginInfo(randomizeCase("SonarSource"), randomAlphanumeric(3)); + PluginInfo pluginInfo = newPluginInfo(randomizeCase("SonarSource"), secure().nextAlphanumeric(3)); assertThat(EditionBundledPlugins.isEditionBundled(pluginInfo)).isFalse(); } @Test public void isEditionBundled_on_PluginInfo_returns_false_for_license_SonarSource_and_non_SonarSource_organization() { - PluginInfo pluginInfo = newPluginInfo(randomAlphanumeric(3), randomizeCase("SonarSource")); + PluginInfo pluginInfo = newPluginInfo(secure().nextAlphanumeric(3), randomizeCase("SonarSource")); assertThat(EditionBundledPlugins.isEditionBundled(pluginInfo)).isFalse(); } @Test public void isEditionBundled_on_PluginInfo_returns_false_for_license_Commercial_and_non_SonarSource_organization() { - PluginInfo pluginInfo = newPluginInfo(randomAlphanumeric(3), randomizeCase("Commercial")); + PluginInfo pluginInfo = newPluginInfo(secure().nextAlphanumeric(3), randomizeCase("Commercial")); assertThat(EditionBundledPlugins.isEditionBundled(pluginInfo)).isFalse(); } @@ -122,24 +122,24 @@ public class EditionBundledPluginsTest { } private PluginInfo newPluginInfo(String organization, String license) { - PluginInfo pluginInfo = new PluginInfo(randomAlphanumeric(2)); + PluginInfo pluginInfo = new PluginInfo(secure().nextAlphanumeric(2)); if (random.nextBoolean()) { - pluginInfo.setName(randomAlphanumeric(3)); + pluginInfo.setName(secure().nextAlphanumeric(3)); } if (random.nextBoolean()) { - pluginInfo.setOrganizationUrl(randomAlphanumeric(4)); + pluginInfo.setOrganizationUrl(secure().nextAlphanumeric(4)); } if (random.nextBoolean()) { - pluginInfo.setIssueTrackerUrl(randomAlphanumeric(5)); + pluginInfo.setIssueTrackerUrl(secure().nextAlphanumeric(5)); } if (random.nextBoolean()) { - pluginInfo.setIssueTrackerUrl(randomAlphanumeric(6)); + pluginInfo.setIssueTrackerUrl(secure().nextAlphanumeric(6)); } if (random.nextBoolean()) { - pluginInfo.setBasePlugin(randomAlphanumeric(7)); + pluginInfo.setBasePlugin(secure().nextAlphanumeric(7)); } if (random.nextBoolean()) { - pluginInfo.setHomepageUrl(randomAlphanumeric(8)); + pluginInfo.setHomepageUrl(secure().nextAlphanumeric(8)); } return pluginInfo .setOrganizationName(organization) @@ -147,24 +147,24 @@ public class EditionBundledPluginsTest { } private Plugin newPlugin(String organization, String license) { - Plugin plugin = Plugin.factory(randomAlphanumeric(2)); + Plugin plugin = Plugin.factory(secure().nextAlphanumeric(2)); if (random.nextBoolean()) { - plugin.setName(randomAlphanumeric(3)); + plugin.setName(secure().nextAlphanumeric(3)); } if (random.nextBoolean()) { - plugin.setOrganizationUrl(randomAlphanumeric(4)); + plugin.setOrganizationUrl(secure().nextAlphanumeric(4)); } if (random.nextBoolean()) { - plugin.setTermsConditionsUrl(randomAlphanumeric(5)); + plugin.setTermsConditionsUrl(secure().nextAlphanumeric(5)); } if (random.nextBoolean()) { - plugin.setIssueTrackerUrl(randomAlphanumeric(6)); + plugin.setIssueTrackerUrl(secure().nextAlphanumeric(6)); } if (random.nextBoolean()) { - plugin.setCategory(randomAlphanumeric(7)); + plugin.setCategory(secure().nextAlphanumeric(7)); } if (random.nextBoolean()) { - plugin.setHomepageUrl(randomAlphanumeric(8)); + plugin.setHomepageUrl(secure().nextAlphanumeric(8)); } return plugin .setLicense(license) diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/project/RekeyedProjectTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/project/RekeyedProjectTest.java index 6b1908b5c86..e2183929c41 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/project/RekeyedProjectTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/project/RekeyedProjectTest.java @@ -22,7 +22,7 @@ package org.sonar.server.project; import org.junit.Test; import static java.util.Collections.emptyList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; @@ -31,7 +31,7 @@ public class RekeyedProjectTest { @Test public void constructor_throws_NPE_if_project_is_null() { - assertThatThrownBy(() -> new RekeyedProject(null, randomAlphanumeric(3))) + assertThatThrownBy(() -> new RekeyedProject(null, secure().nextAlphanumeric(3))) .isInstanceOf(NullPointerException.class) .hasMessage("project can't be null"); } @@ -46,7 +46,7 @@ public class RekeyedProjectTest { @Test public void verify_getters() { Project project = newRandomProject(); - String previousKey = randomAlphanumeric(6); + String previousKey = secure().nextAlphanumeric(6); RekeyedProject underTest = new RekeyedProject(project, previousKey); assertThat(underTest.project()).isSameAs(project); @@ -56,13 +56,13 @@ public class RekeyedProjectTest { @Test public void equals_is_based_on_project_and_previousKey() { Project project = newRandomProject(); - String previousKey = randomAlphanumeric(6); + String previousKey = secure().nextAlphanumeric(6); RekeyedProject underTest = new RekeyedProject(project, previousKey); assertThat(underTest) .isEqualTo(underTest) .isEqualTo(new RekeyedProject(project, previousKey)) - .isNotEqualTo(new RekeyedProject(project, randomAlphanumeric(11))) + .isNotEqualTo(new RekeyedProject(project, secure().nextAlphanumeric(11))) .isNotEqualTo(new RekeyedProject(newRandomProject(), previousKey)) .isNotEqualTo(new Object()) .isNotNull(); @@ -71,14 +71,14 @@ public class RekeyedProjectTest { @Test public void hashCode_is_based_on_project_and_previousKey() { Project project = newRandomProject(); - String previousKey = randomAlphanumeric(6); + String previousKey = secure().nextAlphanumeric(6); RekeyedProject underTest = new RekeyedProject(project, previousKey); assertThat(underTest) .hasSameHashCodeAs(underTest) .hasSameHashCodeAs(new RekeyedProject(project, previousKey)); assertThat(underTest.hashCode()) - .isNotEqualTo(new RekeyedProject(project, randomAlphanumeric(11)).hashCode()) + .isNotEqualTo(new RekeyedProject(project, secure().nextAlphanumeric(11)).hashCode()) .isNotEqualTo(new RekeyedProject(newRandomProject(), previousKey).hashCode()) .isNotEqualTo(new Object().hashCode()); } diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/qualitygate/changeevent/QGChangeEventListenersImplTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/qualitygate/changeevent/QGChangeEventListenersImplTest.java index 68308dcccb7..d447dc22165 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/qualitygate/changeevent/QGChangeEventListenersImplTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/qualitygate/changeevent/QGChangeEventListenersImplTest.java @@ -70,7 +70,7 @@ public class QGChangeEventListenersImplTest { private final QGChangeEventListener listener3 = mock(QGChangeEventListener.class); private final List listeners = Arrays.asList(listener1, listener2, listener3); - private final String project1Uuid = RandomStringUtils.randomAlphabetic(6); + private final String project1Uuid = RandomStringUtils.secure().nextAlphabetic(6); private final BranchDto project1 = newBranchDto(project1Uuid); private final DefaultIssue component1Issue = newDefaultIssue(project1Uuid); private final List oneIssueOnComponent1 = singletonList(component1Issue); diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/util/GlobalLockManagerImplTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/util/GlobalLockManagerImplTest.java index 3cdfd3b435d..92f556e19cf 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/util/GlobalLockManagerImplTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/util/GlobalLockManagerImplTest.java @@ -32,7 +32,7 @@ import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.property.InternalPropertiesDao; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -151,7 +151,7 @@ public class GlobalLockManagerImplTest { @DataProvider public static Object[][] randomValidLockName() { return new Object[][] { - {randomAlphabetic(1 + new Random().nextInt(LOCK_NAME_MAX_LENGTH))} + {secure().nextAlphabetic(1 + new Random().nextInt(LOCK_NAME_MAX_LENGTH))} }; } diff --git a/server/sonar-webserver-auth/src/it/java/org/sonar/server/authentication/CredentialsLocalAuthenticationIT.java b/server/sonar-webserver-auth/src/it/java/org/sonar/server/authentication/CredentialsLocalAuthenticationIT.java index 3e469619d0c..8a64f08d8f4 100644 --- a/server/sonar-webserver-auth/src/it/java/org/sonar/server/authentication/CredentialsLocalAuthenticationIT.java +++ b/server/sonar-webserver-auth/src/it/java/org/sonar/server/authentication/CredentialsLocalAuthenticationIT.java @@ -36,7 +36,7 @@ import org.sonar.server.authentication.event.AuthenticationEvent; import org.sonar.server.authentication.event.AuthenticationException; import static java.lang.String.format; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -85,7 +85,7 @@ public class CredentialsLocalAuthenticationIT { @Test public void authentication_with_bcrypt_with_correct_password_should_work() { - String password = randomAlphanumeric(60); + String password = secure().nextAlphanumeric(60); UserDto user = newUserDto() .setHashMethod(BCRYPT.name()) @@ -96,7 +96,7 @@ public class CredentialsLocalAuthenticationIT { @Test public void authentication_with_sha1_should_throw_AuthenticationException() { - String password = randomAlphanumeric(60); + String password = secure().nextAlphanumeric(60); byte[] saltRandom = new byte[20]; RANDOM.nextBytes(saltRandom); @@ -116,7 +116,7 @@ public class CredentialsLocalAuthenticationIT { @Test public void authentication_with_bcrypt_with_incorrect_password_should_throw_AuthenticationException() { DbSession dbSession = db.getSession(); - String password = randomAlphanumeric(60); + String password = secure().nextAlphanumeric(60); UserDto user = newUserDto() .setHashMethod(BCRYPT.name()) @@ -141,7 +141,7 @@ public class CredentialsLocalAuthenticationIT { @Test public void authentication_upgrade_hash_function_when_BCRYPT_was_used() { - String password = randomAlphanumeric(60); + String password = secure().nextAlphanumeric(60); UserDto user = newUserDto() .setLogin("myself") @@ -163,7 +163,7 @@ public class CredentialsLocalAuthenticationIT { @Test public void authentication_updates_db_if_PBKDF2_iterations_changes() { - String password = randomAlphanumeric(60); + String password = secure().nextAlphanumeric(60); UserDto user = newUserDto().setLogin("myself"); db.users().insertUser(user); @@ -182,7 +182,7 @@ public class CredentialsLocalAuthenticationIT { @Test public void authentication_with_pbkdf2_with_correct_password_should_work() { - String password = randomAlphanumeric(60); + String password = secure().nextAlphanumeric(60); UserDto user = newUserDto() .setHashMethod(PBKDF2.name()); @@ -199,7 +199,7 @@ public class CredentialsLocalAuthenticationIT { settings.clear(); CredentialsLocalAuthentication underTest = new CredentialsLocalAuthentication(db.getDbClient(), settings.asConfig()); - String password = randomAlphanumeric(60); + String password = secure().nextAlphanumeric(60); UserDto user = newUserDto() .setHashMethod(PBKDF2.name()); @@ -227,7 +227,7 @@ public class CredentialsLocalAuthenticationIT { @Test public void authentication_with_pbkdf2_with_invalid_hash_should_throw_AuthenticationException() { DbSession dbSession = db.getSession(); - String password = randomAlphanumeric(60); + String password = secure().nextAlphanumeric(60); UserDto userInvalidHash = newUserDto() .setHashMethod(PBKDF2.name()) @@ -264,7 +264,7 @@ public class CredentialsLocalAuthenticationIT { @Test public void authentication_with_pbkdf2_with_empty_salt_should_throw_AuthenticationException() { - String password = randomAlphanumeric(60); + String password = secure().nextAlphanumeric(60); DbSession dbSession = db.getSession(); UserDto user = newUserDto() diff --git a/server/sonar-webserver-auth/src/it/java/org/sonar/server/user/UserUpdaterCreateIT.java b/server/sonar-webserver-auth/src/it/java/org/sonar/server/user/UserUpdaterCreateIT.java index fd7f815f317..8995f3df438 100644 --- a/server/sonar-webserver-auth/src/it/java/org/sonar/server/user/UserUpdaterCreateIT.java +++ b/server/sonar-webserver-auth/src/it/java/org/sonar/server/user/UserUpdaterCreateIT.java @@ -46,7 +46,7 @@ import org.sonar.server.usergroups.DefaultGroupFinder; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertNotNull; @@ -349,7 +349,7 @@ public class UserUpdaterCreateIT { @Test public void fail_to_create_user_with_too_long_login() { - NewUser newUser = newUserBuilder().setLogin(randomAlphabetic(256)).build(); + NewUser newUser = newUserBuilder().setLogin(secure().nextAlphabetic(256)).build(); assertThatThrownBy(() -> underTest.createAndCommit(session, newUser, u -> { })) .isInstanceOf(BadRequestException.class) @@ -371,7 +371,7 @@ public class UserUpdaterCreateIT { @Test public void fail_to_create_user_with_too_long_name() { - NewUser newUser = newUserBuilder().setName(randomAlphabetic(201)).build(); + NewUser newUser = newUserBuilder().setName(secure().nextAlphabetic(201)).build(); assertThatThrownBy(() -> underTest.createAndCommit(session, newUser, u -> { })) .isInstanceOf(BadRequestException.class) @@ -380,7 +380,7 @@ public class UserUpdaterCreateIT { @Test public void fail_to_create_user_with_too_long_email() { - NewUser newUser = newUserBuilder().setEmail(randomAlphabetic(101)).build(); + NewUser newUser = newUserBuilder().setEmail(secure().nextAlphabetic(101)).build(); assertThatThrownBy(() -> underTest.createAndCommit(session, newUser, u -> { })) .isInstanceOf(BadRequestException.class) diff --git a/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/CredentialsLocalAuthentication.java b/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/CredentialsLocalAuthentication.java index ebb73be857d..fd788c38c9c 100644 --- a/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/CredentialsLocalAuthentication.java +++ b/server/sonar-webserver-auth/src/main/java/org/sonar/server/authentication/CredentialsLocalAuthentication.java @@ -69,8 +69,8 @@ public class CredentialsLocalAuthentication { } void generateHashToAvoidEnumerationAttack(){ - String randomSalt = RandomStringUtils.randomAlphabetic(DUMMY_PASSWORD_AND_SALT_SIZE); - String randomPassword = RandomStringUtils.randomAlphabetic(DUMMY_PASSWORD_AND_SALT_SIZE); + String randomSalt = RandomStringUtils.secure().nextAlphabetic(DUMMY_PASSWORD_AND_SALT_SIZE); + String randomPassword = RandomStringUtils.secure().nextAlphabetic(DUMMY_PASSWORD_AND_SALT_SIZE); hashFunctions.get(HashMethod.PBKDF2).encryptPassword(randomSalt, randomPassword); } diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/permission/GroupUuidOrAnyoneTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/permission/GroupUuidOrAnyoneTest.java index 67cf9b7f874..49149ca1aab 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/permission/GroupUuidOrAnyoneTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/permission/GroupUuidOrAnyoneTest.java @@ -22,7 +22,7 @@ package org.sonar.server.permission; import org.junit.Test; import org.sonar.db.user.GroupDto; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; public class GroupUuidOrAnyoneTest { @@ -39,7 +39,7 @@ public class GroupUuidOrAnyoneTest { @Test public void for_returns_isAnyone_false_if_id_is_not_null() { - String uuid = randomAlphabetic(10); + String uuid = secure().nextAlphabetic(10); GroupDto dto = new GroupDto(); dto.setUuid(uuid); diff --git a/server/sonar-webserver-common/src/it/java/org/sonar/server/common/component/ComponentUpdaterIT.java b/server/sonar-webserver-common/src/it/java/org/sonar/server/common/component/ComponentUpdaterIT.java index 30a70a126ef..3ac8d1490dc 100644 --- a/server/sonar-webserver-common/src/it/java/org/sonar/server/common/component/ComponentUpdaterIT.java +++ b/server/sonar-webserver-common/src/it/java/org/sonar/server/common/component/ComponentUpdaterIT.java @@ -61,7 +61,7 @@ import org.sonar.server.permission.index.PermissionIndexer; import org.sonar.server.project.DefaultBranchNameResolver; import static java.util.stream.IntStream.rangeClosed; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; @@ -375,7 +375,7 @@ public class ComponentUpdaterIT { } private void createComponent_shouldFail_whenCreatingComponentWithExistingKeyButDifferentCase(String qualifier) { - String existingKey = randomAlphabetic(5).toUpperCase(); + String existingKey = secure().nextAlphabetic(5).toUpperCase(); db.components().insertPrivateProject(component -> component.setKey(existingKey)); String newKey = existingKey.toLowerCase(); @@ -397,7 +397,7 @@ public class ComponentUpdaterIT { @Test public void createComponent_shouldFail_whenCreatingComponentWithMultipleExistingKeyButDifferentCase() { - String existingKey = randomAlphabetic(5).toUpperCase(); + String existingKey = secure().nextAlphabetic(5).toUpperCase(); String existingKeyLowerCase = existingKey.toLowerCase(); db.components().insertPrivateProject(component -> component.setKey(existingKey)); db.components().insertPrivateProject(component -> component.setKey(existingKeyLowerCase)); @@ -420,7 +420,7 @@ public class ComponentUpdaterIT { @Test public void createComponent_shouldFail_whenCreatingComponentWithMultipleExistingPortfolioKeysButDifferentCase() { - String existingKey = randomAlphabetic(5).toUpperCase(); + String existingKey = secure().nextAlphabetic(5).toUpperCase(); String existingKeyLowerCase = existingKey.toLowerCase(); db.components().insertPrivatePortfolio(portfolio -> portfolio.setKey(existingKey)); db.components().insertPrivatePortfolio(portfolio -> portfolio.setKey(existingKeyLowerCase)); diff --git a/server/sonar-webserver-common/src/main/java/org/sonar/server/common/user/UserAnonymizer.java b/server/sonar-webserver-common/src/main/java/org/sonar/server/common/user/UserAnonymizer.java index 5d7608bd768..c1b0b9b39c2 100644 --- a/server/sonar-webserver-common/src/main/java/org/sonar/server/common/user/UserAnonymizer.java +++ b/server/sonar-webserver-common/src/main/java/org/sonar/server/common/user/UserAnonymizer.java @@ -35,7 +35,7 @@ public class UserAnonymizer { @Inject public UserAnonymizer(DbClient dbClient) { - this(dbClient, () -> "sq-removed-" + RandomStringUtils.randomAlphanumeric(LOGIN_RANDOM_LENGTH)); + this(dbClient, () -> "sq-removed-" + RandomStringUtils.secure().nextAlphanumeric(LOGIN_RANDOM_LENGTH)); } public UserAnonymizer(DbClient dbClient, Supplier randomNameGenerator) { diff --git a/server/sonar-webserver-common/src/test/java/org/sonar/server/common/almintegration/ProjectKeyGeneratorTest.java b/server/sonar-webserver-common/src/test/java/org/sonar/server/common/almintegration/ProjectKeyGeneratorTest.java index 3751d757bda..c1a92023573 100644 --- a/server/sonar-webserver-common/src/test/java/org/sonar/server/common/almintegration/ProjectKeyGeneratorTest.java +++ b/server/sonar-webserver-common/src/test/java/org/sonar/server/common/almintegration/ProjectKeyGeneratorTest.java @@ -37,7 +37,7 @@ import static org.sonar.server.common.almintegration.ProjectKeyGenerator.PROJECT public class ProjectKeyGeneratorTest { private static final int MAX_UUID_SIZE = 40; - private static final String UUID_STRING = RandomStringUtils.randomAlphanumeric(MAX_UUID_SIZE); + private static final String UUID_STRING = RandomStringUtils.secure().nextAlphanumeric(MAX_UUID_SIZE); @Mock private UuidFactory uuidFactory; @@ -52,7 +52,7 @@ public class ProjectKeyGeneratorTest { @Test public void generateUniqueProjectKey_shortProjectName_shouldAppendUuid() { - String fullProjectName = RandomStringUtils.randomAlphanumeric(10); + String fullProjectName = RandomStringUtils.secure().nextAlphanumeric(10); assertThat(projectKeyGenerator.generateUniqueProjectKey(fullProjectName)) .isEqualTo(generateExpectedKeyName(fullProjectName)); @@ -60,7 +60,7 @@ public class ProjectKeyGeneratorTest { @Test public void generateUniqueProjectKey_projectNameEqualsToMaximumSize_shouldTruncateProjectNameAndPreserveUUID() { - String fullProjectName = RandomStringUtils.randomAlphanumeric(MAX_PROJECT_KEY_SIZE); + String fullProjectName = RandomStringUtils.secure().nextAlphanumeric(MAX_PROJECT_KEY_SIZE); String projectKey = projectKeyGenerator.generateUniqueProjectKey(fullProjectName); assertThat(projectKey) @@ -70,7 +70,7 @@ public class ProjectKeyGeneratorTest { @Test public void generateUniqueProjectKey_projectNameBiggerThanMaximumSize_shouldTruncateProjectNameAndPreserveUUID() { - String fullProjectName = RandomStringUtils.randomAlphanumeric(MAX_PROJECT_KEY_SIZE + 50); + String fullProjectName = RandomStringUtils.secure().nextAlphanumeric(MAX_PROJECT_KEY_SIZE + 50); String projectKey = projectKeyGenerator.generateUniqueProjectKey(fullProjectName); assertThat(projectKey) diff --git a/server/sonar-webserver-common/src/test/java/org/sonar/server/common/group/service/GroupServiceTest.java b/server/sonar-webserver-common/src/test/java/org/sonar/server/common/group/service/GroupServiceTest.java index b61267214b2..76282263d74 100644 --- a/server/sonar-webserver-common/src/test/java/org/sonar/server/common/group/service/GroupServiceTest.java +++ b/server/sonar-webserver-common/src/test/java/org/sonar/server/common/group/service/GroupServiceTest.java @@ -60,7 +60,7 @@ import org.sonar.server.usergroups.DefaultGroupFinder; import static java.lang.String.format; import static java.util.function.Function.identity; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -356,7 +356,7 @@ public class GroupServiceTest { public static Object[][] invalidGroupNames() { return new Object[][] { {"", "Group name cannot be empty"}, - {randomAlphanumeric(256), "Group name cannot be longer than 255 characters"}, + {secure().nextAlphanumeric(256), "Group name cannot be longer than 255 characters"}, {"Anyone", "Anyone group cannot be used"}, }; } diff --git a/server/sonar-webserver-common/src/test/java/org/sonar/server/common/health/AppNodeClusterCheckTest.java b/server/sonar-webserver-common/src/test/java/org/sonar/server/common/health/AppNodeClusterCheckTest.java index a68c4121dea..d0c11baac72 100644 --- a/server/sonar-webserver-common/src/test/java/org/sonar/server/common/health/AppNodeClusterCheckTest.java +++ b/server/sonar-webserver-common/src/test/java/org/sonar/server/common/health/AppNodeClusterCheckTest.java @@ -31,7 +31,7 @@ import org.sonar.server.health.Health; import static java.util.stream.Collectors.toSet; import static java.util.stream.Stream.of; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.sonar.process.cluster.health.NodeHealth.Status.GREEN; import static org.sonar.process.cluster.health.NodeHealth.Status.RED; import static org.sonar.process.cluster.health.NodeHealth.Status.YELLOW; @@ -275,8 +275,8 @@ public class AppNodeClusterCheckTest { .setStatus(status) .setDetails(NodeDetails.newNodeDetailsBuilder() .setType(type) - .setHost(randomAlphanumeric(32)) - .setName(randomAlphanumeric(32)) + .setHost(secure().nextAlphanumeric(32)) + .setName(secure().nextAlphanumeric(32)) .setPort(1 + random.nextInt(88)) .setStartedAt(1 + random.nextInt(54)) .build()) diff --git a/server/sonar-webserver-common/src/test/java/org/sonar/server/common/health/EsStatusClusterCheckTest.java b/server/sonar-webserver-common/src/test/java/org/sonar/server/common/health/EsStatusClusterCheckTest.java index 5a18f084a5d..e635268e964 100644 --- a/server/sonar-webserver-common/src/test/java/org/sonar/server/common/health/EsStatusClusterCheckTest.java +++ b/server/sonar-webserver-common/src/test/java/org/sonar/server/common/health/EsStatusClusterCheckTest.java @@ -27,11 +27,10 @@ import org.junit.Test; import org.mockito.Mockito; import org.sonar.process.cluster.health.NodeDetails; import org.sonar.process.cluster.health.NodeHealth; -import org.sonar.server.common.health.EsStatusClusterCheck; import org.sonar.server.es.EsClient; import org.sonar.server.health.Health; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; @@ -96,8 +95,8 @@ public class EsStatusClusterCheckTest { .setStatus(status) .setDetails(NodeDetails.newNodeDetailsBuilder() .setType(random.nextBoolean() ? NodeDetails.Type.APPLICATION : NodeDetails.Type.SEARCH) - .setName(randomAlphanumeric(23)) - .setHost(randomAlphanumeric(23)) + .setName(secure().nextAlphanumeric(23)) + .setHost(secure().nextAlphanumeric(23)) .setPort(1 + random.nextInt(96)) .setStartedAt(1 + random.nextInt(966)) .build()) diff --git a/server/sonar-webserver-core/src/it/java/org/sonar/server/platform/serverid/ServerIdManagerIT.java b/server/sonar-webserver-core/src/it/java/org/sonar/server/platform/serverid/ServerIdManagerIT.java index e7cb5a6f6f6..187a31afea3 100644 --- a/server/sonar-webserver-core/src/it/java/org/sonar/server/platform/serverid/ServerIdManagerIT.java +++ b/server/sonar-webserver-core/src/it/java/org/sonar/server/platform/serverid/ServerIdManagerIT.java @@ -39,7 +39,7 @@ import org.sonar.db.property.PropertyDto; import org.sonar.server.platform.NodeInformation; import org.sonar.server.property.InternalProperties; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; @@ -56,8 +56,8 @@ import static org.sonar.core.platform.ServerId.UUID_DATASET_ID_LENGTH; @RunWith(DataProviderRunner.class) public class ServerIdManagerIT { - private static final ServerId WITH_DATABASE_ID_SERVER_ID = ServerId.of(randomAlphanumeric(DATABASE_ID_LENGTH), randomAlphanumeric(NOT_UUID_DATASET_ID_LENGTH)); - private static final String CHECKSUM_1 = randomAlphanumeric(12); + private static final ServerId WITH_DATABASE_ID_SERVER_ID = ServerId.of(secure().nextAlphanumeric(DATABASE_ID_LENGTH), secure().nextAlphanumeric(NOT_UUID_DATASET_ID_LENGTH)); + private static final String CHECKSUM_1 = secure().nextAlphanumeric(12); @Rule public final DbTester dbTester = DbTester.create(System2.INSTANCE); @@ -115,7 +115,7 @@ public class ServerIdManagerIT { @Test public void web_leader_creates_server_id_from_current_serverId_with_databaseId_if_checksum_fails() { - ServerId currentServerId = ServerId.of(randomAlphanumeric(DATABASE_ID_LENGTH), randomAlphanumeric(UUID_DATASET_ID_LENGTH)); + ServerId currentServerId = ServerId.of(secure().nextAlphanumeric(DATABASE_ID_LENGTH), secure().nextAlphanumeric(UUID_DATASET_ID_LENGTH)); insertServerId(currentServerId); insertChecksum("does_not_match_WITH_DATABASE_ID_SERVER_ID"); mockChecksumOf(currentServerId, "matches_WITH_DATABASE_ID_SERVER_ID"); diff --git a/server/sonar-webserver-core/src/it/java/org/sonar/server/rule/registration/RulesRegistrantIT.java b/server/sonar-webserver-core/src/it/java/org/sonar/server/rule/registration/RulesRegistrantIT.java index 3e3860db136..b11ba508409 100644 --- a/server/sonar-webserver-core/src/it/java/org/sonar/server/rule/registration/RulesRegistrantIT.java +++ b/server/sonar-webserver-core/src/it/java/org/sonar/server/rule/registration/RulesRegistrantIT.java @@ -39,8 +39,6 @@ import org.junit.runner.RunWith; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.issue.impact.Severity; import org.sonar.api.issue.impact.SoftwareQuality; -import org.sonar.api.resources.Language; -import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleScope; import org.sonar.api.rule.RuleStatus; @@ -94,7 +92,7 @@ import static java.lang.String.format; import static java.lang.String.valueOf; import static java.util.Collections.emptySet; import static java.util.Collections.singletonList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -273,14 +271,14 @@ public class RulesRegistrantIT { @Test public void insert_then_remove_rule() { - String ruleKey = randomAlphanumeric(5); + String ruleKey = secure().nextAlphanumeric(5); // register one rule executeWithPluginRules(context -> { NewRepository repo = context.createRepository("fake", "java"); repo.createRule(ruleKey) - .setName(randomAlphanumeric(5)) - .setHtmlDescription(randomAlphanumeric(20)); + .setName(secure().nextAlphanumeric(5)) + .setHtmlDescription(secure().nextAlphanumeric(20)); repo.done(); }); @@ -325,8 +323,8 @@ public class RulesRegistrantIT { IntStream.range(0, numberOfRules) .mapToObj(i -> "rule-" + i) .forEach(ruleKey -> repo.createRule(ruleKey) - .setName(randomAlphanumeric(20)) - .setHtmlDescription(randomAlphanumeric(20))); + .setName(secure().nextAlphanumeric(20)) + .setHtmlDescription(secure().nextAlphanumeric(20))); repo.done(); }); @@ -820,7 +818,7 @@ public class RulesRegistrantIT { } private static RuleDescriptionSection createRuleDescriptionSection(String sectionKey, String description, @Nullable String contextKey) { - Context context = Optional.ofNullable(contextKey).map(key -> new Context(contextKey, contextKey + randomAlphanumeric(10))).orElse(null); + Context context = Optional.ofNullable(contextKey).map(key -> new Context(contextKey, contextKey + secure().nextAlphanumeric(10))).orElse(null); return RuleDescriptionSection.builder().sectionKey(sectionKey) .htmlContent(description) .context(context) diff --git a/server/sonar-webserver-core/src/it/java/org/sonar/server/webhook/WebhookQGChangeEventListenerIT.java b/server/sonar-webserver-core/src/it/java/org/sonar/server/webhook/WebhookQGChangeEventListenerIT.java index cc530b0e946..9eae477d2f9 100644 --- a/server/sonar-webserver-core/src/it/java/org/sonar/server/webhook/WebhookQGChangeEventListenerIT.java +++ b/server/sonar-webserver-core/src/it/java/org/sonar/server/webhook/WebhookQGChangeEventListenerIT.java @@ -55,7 +55,7 @@ import static java.util.Arrays.stream; import static java.util.Collections.emptySet; import static java.util.stream.Stream.concat; import static java.util.stream.Stream.of; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -145,8 +145,8 @@ public class WebhookQGChangeEventListenerIT { Configuration configuration = mock(Configuration.class); mockPayloadSupplierConsumedByWebhooks(); Map properties = new HashMap<>(); - properties.put("sonar.analysis.test1", randomAlphanumeric(50)); - properties.put("sonar.analysis.test2", randomAlphanumeric(5000)); + properties.put("sonar.analysis.test1", secure().nextAlphanumeric(50)); + properties.put("sonar.analysis.test2", secure().nextAlphanumeric(5000)); insertPropertiesFor(analysis.getUuid(), properties); QGChangeEvent qualityGateEvent = newQGChangeEvent(projectBranch, analysis, configuration, newQualityGate); mockWebhookEnabled(qualityGateEvent.getProject()); diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/serverid/ServerIdFactoryImplTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/serverid/ServerIdFactoryImplTest.java index cc1dd1047ff..a51156faaf7 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/serverid/ServerIdFactoryImplTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/serverid/ServerIdFactoryImplTest.java @@ -31,7 +31,7 @@ import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.MapSettings; import org.sonar.core.platform.ServerId; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; @@ -45,7 +45,7 @@ import static org.sonar.server.platform.serverid.ServerIdFactoryImpl.crc32Hex; @RunWith(DataProviderRunner.class) public class ServerIdFactoryImplTest { - private static final ServerId A_SERVERID = ServerId.of(randomAlphabetic(DATABASE_ID_LENGTH), randomAlphabetic(UUID_DATASET_ID_LENGTH)); + private static final ServerId A_SERVERID = ServerId.of(secure().nextAlphabetic(DATABASE_ID_LENGTH), secure().nextAlphabetic(UUID_DATASET_ID_LENGTH)); private MapSettings settings = new MapSettings(); private Configuration config = settings.asConfig(); @@ -99,10 +99,10 @@ public class ServerIdFactoryImplTest { public static Object[][] anyFormatServerId() { return new Object[][] { {ServerId.parse(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()))}, - {ServerId.parse(randomAlphabetic(NOT_UUID_DATASET_ID_LENGTH))}, - {ServerId.parse(randomAlphabetic(UUID_DATASET_ID_LENGTH))}, - {ServerId.of(randomAlphabetic(DATABASE_ID_LENGTH), randomAlphabetic(NOT_UUID_DATASET_ID_LENGTH))}, - {ServerId.of(randomAlphabetic(DATABASE_ID_LENGTH), randomAlphabetic(UUID_DATASET_ID_LENGTH))} + {ServerId.parse(secure().nextAlphabetic(NOT_UUID_DATASET_ID_LENGTH))}, + {ServerId.parse(secure().nextAlphabetic(UUID_DATASET_ID_LENGTH))}, + {ServerId.of(secure().nextAlphabetic(DATABASE_ID_LENGTH), secure().nextAlphabetic(NOT_UUID_DATASET_ID_LENGTH))}, + {ServerId.of(secure().nextAlphabetic(DATABASE_ID_LENGTH), secure().nextAlphabetic(UUID_DATASET_ID_LENGTH))} }; } diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/rule/registration/SingleDeprecatedRuleKeyTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/rule/registration/SingleDeprecatedRuleKeyTest.java index 311ccad5dd3..47f9cd15bfa 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/rule/registration/SingleDeprecatedRuleKeyTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/rule/registration/SingleDeprecatedRuleKeyTest.java @@ -26,9 +26,8 @@ import org.junit.Test; import org.sonar.api.rule.RuleKey; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.db.rule.DeprecatedRuleKeyDto; -import org.sonar.server.rule.registration.SingleDeprecatedRuleKey; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; @@ -40,10 +39,10 @@ public class SingleDeprecatedRuleKeyTest { public void test_creation_from_DeprecatedRuleKeyDto() { // Creation from DeprecatedRuleKeyDto DeprecatedRuleKeyDto deprecatedRuleKeyDto = new DeprecatedRuleKeyDto() - .setOldRuleKey(randomAlphanumeric(50)) - .setOldRepositoryKey(randomAlphanumeric(50)) - .setRuleUuid(randomAlphanumeric(50)) - .setUuid(randomAlphanumeric(40)); + .setOldRuleKey(secure().nextAlphanumeric(50)) + .setOldRepositoryKey(secure().nextAlphanumeric(50)) + .setRuleUuid(secure().nextAlphanumeric(50)) + .setUuid(secure().nextAlphanumeric(40)); SingleDeprecatedRuleKey singleDeprecatedRuleKey = SingleDeprecatedRuleKey.from(deprecatedRuleKeyDto); @@ -61,15 +60,15 @@ public class SingleDeprecatedRuleKeyTest { public void test_creation_from_RulesDefinitionRule() { // Creation from RulesDefinition.Rule ImmutableSet deprecatedRuleKeys = ImmutableSet.of( - RuleKey.of(randomAlphanumeric(50), randomAlphanumeric(50)), - RuleKey.of(randomAlphanumeric(50), randomAlphanumeric(50)), - RuleKey.of(randomAlphanumeric(50), randomAlphanumeric(50))); + RuleKey.of(secure().nextAlphanumeric(50), secure().nextAlphanumeric(50)), + RuleKey.of(secure().nextAlphanumeric(50), secure().nextAlphanumeric(50)), + RuleKey.of(secure().nextAlphanumeric(50), secure().nextAlphanumeric(50))); RulesDefinition.Repository repository = mock(RulesDefinition.Repository.class); - when(repository.key()).thenReturn(randomAlphanumeric(50)); + when(repository.key()).thenReturn(secure().nextAlphanumeric(50)); RulesDefinition.Rule rule = mock(RulesDefinition.Rule.class); - when(rule.key()).thenReturn(randomAlphanumeric(50)); + when(rule.key()).thenReturn(secure().nextAlphanumeric(50)); when(rule.deprecatedRuleKeys()).thenReturn(deprecatedRuleKeys); when(rule.repository()).thenReturn(repository); @@ -87,9 +86,9 @@ public class SingleDeprecatedRuleKeyTest { @Test public void test_equality() { DeprecatedRuleKeyDto deprecatedRuleKeyDto1 = new DeprecatedRuleKeyDto() - .setOldRuleKey(randomAlphanumeric(50)) - .setOldRepositoryKey(randomAlphanumeric(50)) - .setUuid(randomAlphanumeric(40)) + .setOldRuleKey(secure().nextAlphanumeric(50)) + .setOldRepositoryKey(secure().nextAlphanumeric(50)) + .setUuid(secure().nextAlphanumeric(40)) .setRuleUuid("some-uuid"); DeprecatedRuleKeyDto deprecatedRuleKeyDto1WithoutUuid = new DeprecatedRuleKeyDto() @@ -97,9 +96,9 @@ public class SingleDeprecatedRuleKeyTest { .setOldRepositoryKey(deprecatedRuleKeyDto1.getOldRepositoryKey()); DeprecatedRuleKeyDto deprecatedRuleKeyDto2 = new DeprecatedRuleKeyDto() - .setOldRuleKey(randomAlphanumeric(50)) - .setOldRepositoryKey(randomAlphanumeric(50)) - .setUuid(randomAlphanumeric(40)); + .setOldRuleKey(secure().nextAlphanumeric(50)) + .setOldRepositoryKey(secure().nextAlphanumeric(50)) + .setUuid(secure().nextAlphanumeric(40)); SingleDeprecatedRuleKey singleDeprecatedRuleKey1 = SingleDeprecatedRuleKey.from(deprecatedRuleKeyDto1); SingleDeprecatedRuleKey singleDeprecatedRuleKey2 = SingleDeprecatedRuleKey.from(deprecatedRuleKeyDto2); diff --git a/server/sonar-webserver-es/src/test/java/org/sonar/server/es/metadata/EsDbCompatibilityImplTest.java b/server/sonar-webserver-es/src/test/java/org/sonar/server/es/metadata/EsDbCompatibilityImplTest.java index 73444a3a10d..8c527967068 100644 --- a/server/sonar-webserver-es/src/test/java/org/sonar/server/es/metadata/EsDbCompatibilityImplTest.java +++ b/server/sonar-webserver-es/src/test/java/org/sonar/server/es/metadata/EsDbCompatibilityImplTest.java @@ -29,7 +29,7 @@ import org.sonar.db.DbClient; import org.sonar.server.es.Index; import org.sonar.server.es.IndexType; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; @@ -98,7 +98,7 @@ public class EsDbCompatibilityImplTest { @Test public void markAsCompatible_has_no_effect_if_vendor_is_the_same() { - String vendor = randomAlphabetic(12); + String vendor = secure().nextAlphabetic(12); prepareEs(vendor); prepareDb(vendor); diff --git a/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexProjectStatisticsTest.java b/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexProjectStatisticsTest.java index a41947f8cb9..8b12f2712e3 100644 --- a/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexProjectStatisticsTest.java +++ b/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexProjectStatisticsTest.java @@ -28,7 +28,7 @@ import org.sonar.db.component.ComponentDto; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.db.component.ComponentTesting.newBranchComponent; @@ -54,8 +54,8 @@ class IssueIndexProjectStatisticsTest extends IssueIndexTestCommon { @Test void searchProjectStatistics_does_not_return_results_if_assignee_does_not_match() { ComponentDto project = newPrivateProjectDto(); - String user1Uuid = randomAlphanumeric(40); - String user2Uuid = randomAlphanumeric(40); + String user1Uuid = secure().nextAlphanumeric(40); + String user2Uuid = secure().nextAlphanumeric(40); long from = 1_111_234_567_890L; indexIssues(newDocForProject("issue1", project).setAssigneeUuid(user1Uuid).setFuncCreationDate(new Date(from + 1L))); @@ -67,7 +67,7 @@ class IssueIndexProjectStatisticsTest extends IssueIndexTestCommon { @Test void searchProjectStatistics_returns_results_if_assignee_matches() { ComponentDto project = newPrivateProjectDto(); - String user1Uuid = randomAlphanumeric(40); + String user1Uuid = secure().nextAlphanumeric(40); long from = 1_111_234_567_890L; indexIssues(newDocForProject("issue1", project).setAssigneeUuid(user1Uuid).setFuncCreationDate(new Date(from + 1L))); @@ -79,7 +79,7 @@ class IssueIndexProjectStatisticsTest extends IssueIndexTestCommon { @Test void searchProjectStatistics_returns_results_if_functional_date_is_strictly_after_from_date() { ComponentDto project = newPrivateProjectDto(); - String userUuid = randomAlphanumeric(40); + String userUuid = secure().nextAlphanumeric(40); long from = 1_111_234_567_890L; indexIssues(newDocForProject("issue1", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L))); @@ -91,7 +91,7 @@ class IssueIndexProjectStatisticsTest extends IssueIndexTestCommon { @Test void searchProjectStatistics_does_not_return_results_if_functional_date_is_same_as_from_date() { ComponentDto project = newPrivateProjectDto(); - String userUuid = randomAlphanumeric(40); + String userUuid = secure().nextAlphanumeric(40); long from = 1_111_234_567_890L; indexIssues(newDocForProject("issue1", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from))); @@ -103,7 +103,7 @@ class IssueIndexProjectStatisticsTest extends IssueIndexTestCommon { @Test void searchProjectStatistics_does_not_return_resolved_issues() { ComponentDto project = newPrivateProjectDto(); - String userUuid = randomAlphanumeric(40); + String userUuid = secure().nextAlphanumeric(40); long from = 1_111_234_567_890L; indexIssues( newDocForProject("issue1", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)).setResolution(Issue.RESOLUTION_FALSE_POSITIVE), @@ -119,7 +119,7 @@ class IssueIndexProjectStatisticsTest extends IssueIndexTestCommon { @Test void searchProjectStatistics_does_not_return_results_if_functional_date_is_before_from_date() { ComponentDto project = newPrivateProjectDto(); - String userUuid = randomAlphanumeric(40); + String userUuid = secure().nextAlphanumeric(40); long from = 1_111_234_567_890L; indexIssues(newDocForProject("issue1", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from - 1000L))); @@ -131,7 +131,7 @@ class IssueIndexProjectStatisticsTest extends IssueIndexTestCommon { @Test void searchProjectStatistics_returns_issue_count() { ComponentDto project = newPrivateProjectDto(); - String userUuid = randomAlphanumeric(40); + String userUuid = secure().nextAlphanumeric(40); long from = 1_111_234_567_890L; indexIssues( newDocForProject("issue1", project).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)), @@ -148,7 +148,7 @@ class IssueIndexProjectStatisticsTest extends IssueIndexTestCommon { ComponentDto project1 = newPrivateProjectDto(); ComponentDto project2 = newPrivateProjectDto(); ComponentDto project3 = newPrivateProjectDto(); - String userUuid = randomAlphanumeric(40); + String userUuid = secure().nextAlphanumeric(40); long from = 1_111_234_567_890L; indexIssues( newDocForProject("issue1", project1).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)), @@ -175,7 +175,7 @@ class IssueIndexProjectStatisticsTest extends IssueIndexTestCommon { ComponentDto project1 = newPrivateProjectDto(); ComponentDto project2 = newPrivateProjectDto(); ComponentDto project3 = newPrivateProjectDto(); - String userUuid = randomAlphanumeric(40); + String userUuid = secure().nextAlphanumeric(40); long from = 1_111_234_567_000L; indexIssues( newDocForProject("issue1", project1).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1_000L)), @@ -201,7 +201,7 @@ class IssueIndexProjectStatisticsTest extends IssueIndexTestCommon { void searchProjectStatistics_return_branch_issues() { ComponentDto project = newPrivateProjectDto(); ComponentDto branch = newBranchComponent(project, newBranchDto(project).setKey("branch")); - String userUuid = randomAlphanumeric(40); + String userUuid = secure().nextAlphanumeric(40); long from = 1_111_234_567_890L; indexIssues( newDoc("issue1", project.uuid(), branch).setAssigneeUuid(userUuid).setFuncCreationDate(new Date(from + 1L)), diff --git a/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueQueryFactoryTest.java b/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueQueryFactoryTest.java index acc2610ff8d..6197d35b9d9 100644 --- a/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueQueryFactoryTest.java +++ b/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueQueryFactoryTest.java @@ -44,7 +44,7 @@ import org.sonar.server.tester.UserSessionRule; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; @@ -523,7 +523,7 @@ public class IssueQueryFactoryTest { public void search_issue_from_branch() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(mainBranch, b -> b.setKey(branchName)); assertThat(underTest.create(new SearchRequest() @@ -542,7 +542,7 @@ public class IssueQueryFactoryTest { @Test public void search_file_issue_from_branch() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName)); ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid())); @@ -570,7 +570,7 @@ public class IssueQueryFactoryTest { @Test public void search_issue_on_component_only_from_branch() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName)); ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid())); diff --git a/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/qualityprofile/QualityProfileChangeEventServiceImplTest.java b/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/qualityprofile/QualityProfileChangeEventServiceImplTest.java index 8d629900c8f..0ba4583234b 100644 --- a/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/qualityprofile/QualityProfileChangeEventServiceImplTest.java +++ b/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/qualityprofile/QualityProfileChangeEventServiceImplTest.java @@ -44,7 +44,7 @@ import org.sonar.server.qualityprofile.ActiveRuleChange; import org.sonarqube.ws.Common; import static java.util.List.of; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.measures.CoreMetrics.NCLOC_LANGUAGE_DISTRIBUTION_KEY; import static org.sonar.db.rule.RuleTesting.newCustomRule; @@ -183,7 +183,7 @@ public class QualityProfileChangeEventServiceImplTest { RuleParamDto rule1Param = db.rules().insertRuleParam(rule1); ActiveRuleDto activeRule1 = db.qualityProfiles().activateRule(activatedQualityProfile, rule1); - ActiveRuleParamDto activeRuleParam1 = ActiveRuleParamDto.createFor(rule1Param).setValue(randomAlphanumeric(20)); + ActiveRuleParamDto activeRuleParam1 = ActiveRuleParamDto.createFor(rule1Param).setValue(secure().nextAlphanumeric(20)); db.getDbClient().activeRuleDao().insertParam(db.getSession(), activeRule1, activeRuleParam1); db.getSession().commit(); @@ -193,7 +193,7 @@ public class QualityProfileChangeEventServiceImplTest { RuleParamDto rule2Param = db.rules().insertRuleParam(rule2); ActiveRuleDto activeRule2 = db.qualityProfiles().activateRule(deactivatedQualityProfile, rule2); - ActiveRuleParamDto activeRuleParam2 = ActiveRuleParamDto.createFor(rule2Param).setValue(randomAlphanumeric(20)); + ActiveRuleParamDto activeRuleParam2 = ActiveRuleParamDto.createFor(rule2Param).setValue(secure().nextAlphanumeric(20)); db.getDbClient().activeRuleDao().insertParam(db.getSession(), activeRule2, activeRuleParam2); db.getSession().commit(); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/bitbucketserver/ImportBitbucketServerProjectActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/bitbucketserver/ImportBitbucketServerProjectActionIT.java index b0315679e7e..a5eca9dda99 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/bitbucketserver/ImportBitbucketServerProjectActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almintegration/ws/bitbucketserver/ImportBitbucketServerProjectActionIT.java @@ -74,7 +74,7 @@ import org.sonarqube.ws.Projects; import static java.lang.String.format; import static java.util.Objects.requireNonNull; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -532,8 +532,8 @@ public class ImportBitbucketServerProjectActionIT { private Repository mockBitbucketServerRepo(Project project, BranchesList branchesList) { Repository bbsResult = new Repository(); bbsResult.setProject(project); - bbsResult.setSlug(randomAlphanumeric(5)); - bbsResult.setName(randomAlphanumeric(5)); + bbsResult.setSlug(secure().nextAlphanumeric(5)); + bbsResult.setName(secure().nextAlphanumeric(5)); bbsResult.setId(random.nextLong(100)); when(bitbucketServerRestClient.getRepo(any(), any(), any(), any())).thenReturn(bbsResult); when(bitbucketServerRestClient.getBranches(any(), any(), any(), any())).thenReturn(branchesList); @@ -542,9 +542,9 @@ public class ImportBitbucketServerProjectActionIT { private Project getGsonBBSProject() { return new Project() - .setKey(randomAlphanumeric(5)) + .setKey(secure().nextAlphanumeric(5)) .setId(random.nextLong(100)) - .setName(randomAlphanumeric(5)); + .setName(secure().nextAlphanumeric(5)); } private ProjectDto getProjectDto(Projects.CreateWsResponse.Project result) { diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almsettings/ws/UpdateGithubActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almsettings/ws/UpdateGithubActionIT.java index 8c6b7325636..6222324e23f 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almsettings/ws/UpdateGithubActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/almsettings/ws/UpdateGithubActionIT.java @@ -48,7 +48,7 @@ import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; @@ -267,7 +267,7 @@ public class UpdateGithubActionIT { @Test @UseDataProvider("secretParams") public void update_withSecretChange_shouldAuditDevOpsPlatformSecret(String secretParam) { - buildTestRequestWithoutSecrets().setParam(secretParam, randomAlphanumeric(10)).execute(); + buildTestRequestWithoutSecrets().setParam(secretParam, secure().nextAlphanumeric(10)).execute(); SecretNewValue expected = new SecretNewValue("DevOpsPlatform", GITHUB.getId()); ArgumentCaptor captor = ArgumentCaptor.forClass(SecretNewValue.class); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/badge/ws/MeasureActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/badge/ws/MeasureActionIT.java index a416f1caec9..4755ea77522 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/badge/ws/MeasureActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/badge/ws/MeasureActionIT.java @@ -53,7 +53,7 @@ import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; @@ -244,7 +244,7 @@ public class MeasureActionIT { userSession.registerProjects(projectData.getProjectDto()); MetricDto metric = createIntMetricAndMeasure(project, BUGS_KEY, 5_000); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(BRANCH).setKey(branchName)); db.measures().insertMeasure(branch, m -> m.addValue(metric.getKey(), 10_000d)); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/badge/ws/QualityGateActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/badge/ws/QualityGateActionIT.java index 4654493f845..e838155659d 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/badge/ws/QualityGateActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/badge/ws/QualityGateActionIT.java @@ -51,7 +51,7 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; @@ -228,7 +228,7 @@ public class QualityGateActionIT { userSession.registerProjects(projectData.getProjectDto()); MetricDto metric = createQualityGateMetric(); db.measures().insertMeasure(project, m -> m.addValue(metric.getKey(), OK.name())); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(BRANCH).setKey(branchName)); db.measures().insertMeasure(branch, m -> m.addValue(metric.getKey(), ERROR.name())); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ce/queue/BranchReportSubmitterIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ce/queue/BranchReportSubmitterIT.java index 0b4539d9b0b..b71470c86ae 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ce/queue/BranchReportSubmitterIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ce/queue/BranchReportSubmitterIT.java @@ -49,20 +49,20 @@ import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.common.almsettings.DevOpsProjectCreatorFactory; import org.sonar.server.common.almsettings.github.GithubProjectCreatorFactory; -import org.sonar.server.component.ComponentCreationData; import org.sonar.server.common.component.ComponentCreationParameters; import org.sonar.server.common.component.ComponentUpdater; +import org.sonar.server.common.permission.PermissionTemplateService; +import org.sonar.server.common.project.ProjectCreator; +import org.sonar.server.component.ComponentCreationData; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.favorite.FavoriteUpdater; import org.sonar.server.management.ManagedInstanceService; -import org.sonar.server.common.permission.PermissionTemplateService; import org.sonar.server.project.ProjectDefaultVisibility; import org.sonar.server.project.Visibility; -import org.sonar.server.common.project.ProjectCreator; import org.sonar.server.tester.UserSessionRule; import static java.util.Collections.emptyMap; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; @@ -273,7 +273,7 @@ public class BranchReportSubmitterIT { } private String mockSuccessfulPrepareSubmitCall() { - String taskUuid = randomAlphabetic(12); + String taskUuid = secure().nextAlphabetic(12); when(queue.prepareSubmit()).thenReturn(new CeTaskSubmit.Builder(taskUuid)); return taskUuid; } @@ -293,7 +293,7 @@ public class BranchReportSubmitterIT { } private static BranchSupport.ComponentKey createComponentKeyOfBranch(String projectKey) { - return createComponentKeyOfBranch(projectKey, randomAlphabetic(5)); + return createComponentKeyOfBranch(projectKey, secure().nextAlphabetic(5)); } private static BranchSupport.ComponentKey createComponentKeyOfBranch(String projectKey, String branchKey) { diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ce/ws/ActivityActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ce/ws/ActivityActionIT.java index 08cd3c65d61..8f411ebb702 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ce/ws/ActivityActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ce/ws/ActivityActionIT.java @@ -456,7 +456,7 @@ public class ActivityActionIT { logInAsSystemAdministrator(); ProjectData project = db.components().insertPrivateProject(); userSession.addProjectPermission(UserRole.USER, project.getProjectDto()); - String pullRequestKey = RandomStringUtils.randomAlphanumeric(100); + String pullRequestKey = RandomStringUtils.secure().nextAlphanumeric(100); ComponentDto pullRequest = db.components().insertProjectBranch(project.getMainBranchComponent(), b -> b.setBranchType(BranchType.PULL_REQUEST).setKey(pullRequestKey)); SnapshotDto analysis = db.components().insertSnapshot(pullRequest); CeActivityDto activity = insertActivity("T1", project.projectUuid(), project.getMainBranchComponent().uuid(), SUCCESS, analysis); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ce/ws/ComponentActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ce/ws/ComponentActionIT.java index 32d2033afe3..5184f8147c9 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ce/ws/ComponentActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ce/ws/ComponentActionIT.java @@ -52,7 +52,7 @@ import org.sonarqube.ws.Common; import org.sonarqube.ws.MediaTypes; import static java.util.Collections.emptyList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; @@ -176,7 +176,7 @@ public class ComponentActionIT { public void branch_in_activity() { ProjectData project = db.components().insertPrivateProject(); userSession.addProjectPermission(UserRole.USER, project.getProjectDto()); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(project.getMainBranchComponent(), b -> b.setBranchType(BRANCH).setKey(branchName)); SnapshotDto analysis = db.components().insertSnapshot(branch); CeActivityDto activity = insertActivity("T1", project.getMainBranchComponent(), project.getProjectDto(), SUCCESS, analysis); @@ -197,7 +197,7 @@ public class ComponentActionIT { public void branch_in_queue_analysis() { ProjectData project = db.components().insertPrivateProject(); userSession.addProjectPermission(UserRole.USER, project.getProjectDto()); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(project.getMainBranchComponent(), b -> b.setBranchType(BRANCH).setKey(branchName)); CeQueueDto queue1 = insertQueue("T1", project.getMainBranchComponent(), project.getProjectDto(), IN_PROGRESS); insertCharacteristic(queue1, CeTaskCharacteristics.BRANCH, branchName); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ce/ws/TaskActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ce/ws/TaskActionIT.java index e8bddb90dc7..66deb20879b 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ce/ws/TaskActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ce/ws/TaskActionIT.java @@ -53,7 +53,7 @@ import org.sonarqube.ws.Ce; import org.sonarqube.ws.Common; import static java.util.Collections.singleton; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.web.UserRole.ADMIN; @@ -170,7 +170,7 @@ public class TaskActionIT { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); userSession.addProjectPermission(UserRole.USER, projectData.getProjectDto()); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(mainBranch, b -> b.setBranchType(BRANCH).setKey(branchName)); db.components().insertSnapshot(branch); CeActivityDto activity = createAndPersistArchivedTask(mainBranch); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/AppActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/AppActionIT.java index aa92b558ed0..3fbfbdb96b5 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/AppActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/AppActionIT.java @@ -36,7 +36,7 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.measures.CoreMetrics.COVERAGE_KEY; @@ -257,7 +257,7 @@ public class AppActionIT { @Test public void branch() { userSession.logIn("john").addProjectPermission(USER, projectData.getProjectDto()); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(mainBranchComponent, b -> b.setKey(branchName)); userSession.addProjectBranchMapping(projectData.getProjectDto().getUuid(), branch); ComponentDto directory = db.components().insertComponent(newDirectory(branch, "src")); @@ -299,7 +299,7 @@ public class AppActionIT { @Test public void component_and_branch_parameters_provided() { userSession.logIn("john").addProjectPermission(USER, projectData.getProjectDto()); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(mainBranchComponent, b -> b.setKey(branchName)); userSession.addProjectBranchMapping(projectData.projectUuid(), branch); ComponentDto file = db.components().insertComponent(newFileDto(branch, mainBranchComponent.uuid())); @@ -330,7 +330,7 @@ public class AppActionIT { public void component_and_pull_request_parameters_provided() { userSession.logIn("john").addProjectPermission(USER, projectData.getProjectDto()) .registerBranches(projectData.getMainBranchDto()); - String pullRequestKey = RandomStringUtils.randomAlphanumeric(100); + String pullRequestKey = RandomStringUtils.secure().nextAlphanumeric(100); ComponentDto branch = db.components().insertProjectBranch(mainBranchComponent, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey)); userSession.addProjectBranchMapping(projectData.projectUuid(), branch); ComponentDto file = db.components().insertComponent(newFileDto(branch, mainBranchComponent.uuid())); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/ShowActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/ShowActionIT.java index 35beb3c850a..2c7db008865 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/ShowActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/ShowActionIT.java @@ -42,7 +42,7 @@ import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Components.Component; import org.sonarqube.ws.Components.ShowWsResponse; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; @@ -341,7 +341,7 @@ public class ShowActionIT { ComponentDto portfolio2 = db.components().insertPublicPortfolio(); ComponentDto subview = db.components().insertSubView(portfolio1); - String pullRequestKey1 = randomAlphanumeric(100); + String pullRequestKey1 = secure().nextAlphanumeric(100); ProjectData projectData1 = db.components().insertPrivateProject(); ComponentDto project1 = projectData1.getMainBranchComponent(); ComponentDto branch1 = db.components().insertProjectBranch(project1, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey1) @@ -353,9 +353,9 @@ public class ShowActionIT { ProjectData projectData2 = db.components().insertPrivateProject(); ComponentDto project2 = projectData2.getMainBranchComponent(); - String branchName2 = randomAlphanumeric(248); + String branchName2 = secure().nextAlphanumeric(248); ComponentDto branch2 = db.components().insertProjectBranch(project2, b -> b.setBranchType(BRANCH).setNeedIssueSync(true).setKey(branchName2)); - String branchName3 = randomAlphanumeric(248); + String branchName3 = secure().nextAlphanumeric(248); ComponentDto branch3 = db.components().insertProjectBranch(project2, b -> b.setBranchType(BRANCH).setNeedIssueSync(false).setKey(branchName3)); userSession.addProjectBranchMapping(projectData2.projectUuid(), projectData2.getMainBranchComponent()); userSession.addProjectBranchMapping(projectData2.projectUuid(), branch2); @@ -363,11 +363,11 @@ public class ShowActionIT { ProjectData projectData3 = db.components().insertPrivateProject(); ComponentDto project3 = projectData3.getMainBranchComponent(); - String pullRequestKey4 = randomAlphanumeric(100); + String pullRequestKey4 = secure().nextAlphanumeric(100); ComponentDto branch4 = db.components().insertProjectBranch(project3, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey4).setNeedIssueSync(false)); ComponentDto directoryOfBranch4 = db.components().insertComponent(newDirectoryOnBranch(branch4, "dir", project3.uuid())); ComponentDto fileOfBranch4 = db.components().insertComponent(newFileDto(project3.uuid(), branch4, directoryOfBranch4)); - String branchName5 = randomAlphanumeric(248); + String branchName5 = secure().nextAlphanumeric(248); ComponentDto branch5 = db.components().insertProjectBranch(project3, b -> b.setBranchType(BRANCH).setNeedIssueSync(false).setKey(branchName5)); userSession.addProjectBranchMapping(projectData3.projectUuid(), projectData3.getMainBranchComponent()); userSession.addProjectBranchMapping(projectData3.projectUuid(), branch4); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/SuggestionsActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/SuggestionsActionIT.java index a8708689fc0..557b0a2271a 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/SuggestionsActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/component/ws/SuggestionsActionIT.java @@ -30,7 +30,6 @@ import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; -import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.component.ProjectData; @@ -56,7 +55,7 @@ import static java.util.Collections.singletonList; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.joining; import static java.util.stream.IntStream.range; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.doReturn; @@ -529,7 +528,7 @@ public class SuggestionsActionIT { @Test public void should_only_provide_project_for_certain_qualifiers() { - String query = randomAlphabetic(10); + String query = secure().nextAlphabetic(10); ProjectData appData = db.components().insertPublicApplication(v -> v.setName(query)); ComponentDto app = appData.getMainBranchComponent(); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/developers/ws/SearchEventsActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/developers/ws/SearchEventsActionIT.java index 66c26815102..61512fd0dac 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/developers/ws/SearchEventsActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/developers/ws/SearchEventsActionIT.java @@ -53,7 +53,7 @@ import org.sonarqube.ws.Developers.SearchEventsWsResponse; import org.sonarqube.ws.Developers.SearchEventsWsResponse.Event; import static java.lang.String.format; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; @@ -132,7 +132,7 @@ public class SearchEventsActionIT { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); userSession.addProjectPermission(USER, projectData.getProjectDto()); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(mainBranch, b -> b.setKey(branchName)); SnapshotDto projectAnalysis = insertAnalysis(mainBranch, 1_500_000_000_000L); db.events().insertEvent(newQualityGateEvent(projectAnalysis).setDate(projectAnalysis.getCreatedAt()).setName("Passed")); @@ -270,7 +270,7 @@ public class SearchEventsActionIT { CeQueueDto queueDto = new CeQueueDto(); queueDto.setTaskType(CeTaskTypes.REPORT); queueDto.setComponentUuid(mainBranchUuid); - queueDto.setUuid(randomAlphanumeric(40)); + queueDto.setUuid(secure().nextAlphanumeric(40)); queueDto.setCreatedAt(random.nextLong(Long.MAX_VALUE)); CeActivityDto activityDto = new CeActivityDto(queueDto); activityDto.setStatus(status); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/developers/ws/SearchEventsActionNewIssuesIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/developers/ws/SearchEventsActionNewIssuesIT.java index e9212dfe7bb..57d63155358 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/developers/ws/SearchEventsActionNewIssuesIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/developers/ws/SearchEventsActionNewIssuesIT.java @@ -50,7 +50,7 @@ import org.sonarqube.ws.Developers.SearchEventsWsResponse.Event; import static java.lang.String.format; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; @@ -306,7 +306,7 @@ public class SearchEventsActionNewIssuesIT { CeQueueDto queueDto = new CeQueueDto(); queueDto.setTaskType(CeTaskTypes.REPORT); queueDto.setComponentUuid(mainBranchUuid); - queueDto.setUuid(randomAlphanumeric(40)); + queueDto.setUuid(secure().nextAlphanumeric(40)); queueDto.setCreatedAt(random.nextLong(Long.MAX_VALUE)); CeActivityDto activityDto = new CeActivityDto(queueDto); activityDto.setStatus(status); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/developers/ws/SearchEventsActionQualityGateIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/developers/ws/SearchEventsActionQualityGateIT.java index 31fa46f1827..9a256d6c399 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/developers/ws/SearchEventsActionQualityGateIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/developers/ws/SearchEventsActionQualityGateIT.java @@ -40,7 +40,7 @@ import org.sonarqube.ws.Developers.SearchEventsWsResponse.Event; import static java.lang.String.format; import static java.lang.String.join; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; @@ -99,7 +99,7 @@ public class SearchEventsActionQualityGateIT { when(server.getPublicRootUrl()).thenReturn("https://sonarcloud.io"); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.addProjectPermission(USER, db.components().getProjectDtoByMainBranch(project)); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(BRANCH).setKey(branchName)); insertSuccessfulActivity(project, 1_500_000_000_000L); SnapshotDto branchAnalysis = insertSuccessfulActivity(branch, 1_500_000_000_000L); @@ -279,7 +279,7 @@ public class SearchEventsActionQualityGateIT { CeQueueDto queueDto = new CeQueueDto(); queueDto.setTaskType(CeTaskTypes.REPORT); queueDto.setComponentUuid(mainBranchUuid); - queueDto.setUuid(randomAlphanumeric(40)); + queueDto.setUuid(secure().nextAlphanumeric(40)); queueDto.setCreatedAt(ANY_TIMESTAMP); CeActivityDto activityDto = new CeActivityDto(queueDto); activityDto.setStatus(status); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/duplication/ws/DuplicationsParserIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/duplication/ws/DuplicationsParserIT.java index 7b788ae0be4..a53261fc569 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/duplication/ws/DuplicationsParserIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/duplication/ws/DuplicationsParserIT.java @@ -31,7 +31,7 @@ import org.sonar.db.component.ComponentDto; import org.sonar.server.component.ComponentFinder; import static java.lang.String.format; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.db.component.ComponentTesting.newFileDto; @@ -250,7 +250,7 @@ public class DuplicationsParserIT { @Test public void duplication_on_branch() { ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName)); ComponentDto file1 = db.components().insertComponent(newFileDto(branch, project.uuid())); ComponentDto file2 = db.components().insertComponent(newFileDto(branch, project.uuid())); @@ -285,7 +285,7 @@ public class DuplicationsParserIT { @Test public void duplication_on_pull_request() { ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); - String pullRequestKey = RandomStringUtils.randomAlphanumeric(100); + String pullRequestKey = RandomStringUtils.secure().nextAlphanumeric(100); ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST).setKey(pullRequestKey)); ComponentDto file1 = db.components().insertComponent(newFileDto(pullRequest)); ComponentDto file2 = db.components().insertComponent(newFileDto(pullRequest)); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/duplication/ws/ShowActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/duplication/ws/ShowActionIT.java index 1b098921962..caa5b6688cd 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/duplication/ws/ShowActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/duplication/ws/ShowActionIT.java @@ -40,7 +40,7 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.component.BranchType.PULL_REQUEST; @@ -109,7 +109,7 @@ public class ShowActionIT { public void duplications_by_file_key_and_branch() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName)); userSessionRule.addProjectBranchMapping(project.uuid(), branch); ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid())); @@ -165,7 +165,7 @@ public class ShowActionIT { public void duplications_by_file_key_and_pull_request() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project); - String pullRequestKey = randomAlphanumeric(100); + String pullRequestKey = secure().nextAlphanumeric(100); ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey)); userSessionRule.addProjectBranchMapping(project.uuid(), pullRequest); ComponentDto file = db.components().insertComponent(newFileDto(pullRequest, project.uuid())); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/duplication/ws/ShowResponseBuilderIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/duplication/ws/ShowResponseBuilderIT.java index 4ee0dd0aef9..8033a17fa44 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/duplication/ws/ShowResponseBuilderIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/duplication/ws/ShowResponseBuilderIT.java @@ -32,7 +32,7 @@ import org.sonar.db.component.ComponentDto; import org.sonar.test.JsonAssert; import static com.google.common.collect.Lists.newArrayList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.sonar.db.component.BranchType.PULL_REQUEST; import static org.sonar.db.component.ComponentTesting.newDirectory; import static org.sonar.db.component.ComponentTesting.newFileDto; @@ -204,7 +204,7 @@ public class ShowResponseBuilderIT { @Test public void write_duplications_on_branch() { ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName)); ComponentDto file1 = db.components().insertComponent(newFileDto(branch, project.uuid())); ComponentDto file2 = db.components().insertComponent(newFileDto(branch, project.uuid())); @@ -249,7 +249,7 @@ public class ShowResponseBuilderIT { @Test public void write_duplications_on_pull_request() { ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); - String pullRequestKey = randomAlphanumeric(100); + String pullRequestKey = secure().nextAlphanumeric(100); ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey)); ComponentDto file1 = db.components().insertComponent(newFileDto(pullRequest)); ComponentDto file2 = db.components().insertComponent(newFileDto(pullRequest)); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/AddCommentActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/AddCommentActionIT.java index 67822c7a3d3..ebc9d14414b 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/AddCommentActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/AddCommentActionIT.java @@ -52,7 +52,7 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; @@ -115,7 +115,7 @@ public class AddCommentActionIT { @Test public void fails_with_IAE_if_parameter_comment_is_missing() { - String key = randomAlphabetic(12); + String key = secure().nextAlphabetic(12); userSessionRule.logIn(); TestRequest request = actionTester.newRequest() .setParam("hotspot", key); @@ -127,11 +127,11 @@ public class AddCommentActionIT { @Test public void fails_with_NotFoundException_if_hotspot_does_not_exist() { - String key = randomAlphabetic(12); + String key = secure().nextAlphabetic(12); userSessionRule.logIn(); TestRequest request = actionTester.newRequest() .setParam("hotspot", key) - .setParam("comment", randomAlphabetic(10)); + .setParam("comment", secure().nextAlphabetic(10)); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) @@ -146,7 +146,7 @@ public class AddCommentActionIT { RuleDto rule = dbTester.rules().insert(t -> t.setType(ruleType)); IssueDto notAHotspot = dbTester.issues().insertIssue(rule, project, file, i -> i.setType(ruleType)); userSessionRule.logIn(); - TestRequest request = newRequest(notAHotspot, randomAlphabetic(12)); + TestRequest request = newRequest(notAHotspot, secure().nextAlphabetic(12)); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) @@ -168,7 +168,7 @@ public class AddCommentActionIT { RuleDto rule = dbTester.rules().insertHotspotRule(); IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setStatus(STATUS_CLOSED)); userSessionRule.logIn(); - TestRequest request = newRequest(hotspot, randomAlphabetic(12)); + TestRequest request = newRequest(hotspot, secure().nextAlphabetic(12)); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) @@ -184,7 +184,7 @@ public class AddCommentActionIT { ComponentDto file = dbTester.components().insertComponent(newFileDto(project)); RuleDto rule = dbTester.rules().insertHotspotRule(); IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file); - String comment = randomAlphabetic(12); + String comment = secure().nextAlphabetic(12); TestRequest request = newRequest(hotspot, comment); assertThatThrownBy(request::execute) @@ -201,7 +201,7 @@ public class AddCommentActionIT { ComponentDto file = dbTester.components().insertComponent(newFileDto(project)); RuleDto rule = dbTester.rules().insertHotspotRule(); IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file); - String comment = randomAlphabetic(12); + String comment = secure().nextAlphabetic(12); newRequest(hotspot, comment).execute().assertNoContent(); } @@ -216,7 +216,7 @@ public class AddCommentActionIT { ComponentDto file = dbTester.components().insertComponent(newFileDto(project)); RuleDto rule = dbTester.rules().insertHotspotRule(); IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file); - String comment = randomAlphabetic(12); + String comment = secure().nextAlphabetic(12); newRequest(hotspot, comment).execute().assertNoContent(); } @@ -233,7 +233,7 @@ public class AddCommentActionIT { ComponentDto file = dbTester.components().insertComponent(newFileDto(project)); RuleDto rule = dbTester.rules().insertHotspotRule(); IssueDto hotspot = dbTester.issues().insertHotspot(rule, project, file, t -> t.setStatus(currentStatus).setResolution(currentResolution)); - String comment = randomAlphabetic(12); + String comment = secure().nextAlphabetic(12); newRequest(hotspot, comment).execute().assertNoContent(); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/AssignActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/AssignActionIT.java index c1a21869669..60332f71ca3 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/AssignActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/AssignActionIT.java @@ -65,7 +65,7 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -142,10 +142,10 @@ public class AssignActionIT { ComponentDto file = dbTester.components().insertComponent(newFileDto(project)); IssueDto hotspot = dbTester.issues().insertHotspot(project, file); - UserDto userDto = insertUser(randomAlphanumeric(10)); + UserDto userDto = insertUser(secure().nextAlphanumeric(10)); userSessionRule.logIn(userDto).registerProjects(projectData.getProjectDto()); - UserDto assignee = insertUser(randomAlphanumeric(15)); + UserDto assignee = insertUser(secure().nextAlphanumeric(15)); when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(true); executeRequest(hotspot, assignee.getLogin(), null); @@ -158,11 +158,11 @@ public class AssignActionIT { ProjectData projectData = dbTester.components().insertPublicProject(); ComponentDto project = projectData.getMainBranchComponent(); ComponentDto file = dbTester.components().insertComponent(newFileDto(project)); - UserDto assignee = insertUser(randomAlphanumeric(15)); + UserDto assignee = insertUser(secure().nextAlphanumeric(15)); IssueDto hotspot = dbTester.issues().insertHotspot(project, file, h -> h.setAssigneeUuid(assignee.getUuid())); - UserDto userDto = insertUser(randomAlphanumeric(10)); + UserDto userDto = insertUser(secure().nextAlphanumeric(10)); userSessionRule.logIn(userDto).registerProjects(projectData.getProjectDto()); when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), isNull(), any(IssueChangeContext.class))).thenReturn(true); @@ -178,7 +178,7 @@ public class AssignActionIT { ComponentDto file = dbTester.components().insertComponent(newFileDto(project)); IssueDto hotspot = dbTester.issues().insertHotspot(project, file); - UserDto me = insertUser(randomAlphanumeric(10)); + UserDto me = insertUser(secure().nextAlphanumeric(10)); userSessionRule.logIn(me).registerProjects(projectData.getProjectDto()); when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(me), any(IssueChangeContext.class))).thenReturn(true); @@ -193,7 +193,7 @@ public class AssignActionIT { ProjectData projectData = dbTester.components().insertPublicProject(); ComponentDto project = projectData.getMainBranchComponent(); ComponentDto file = dbTester.components().insertComponent(newFileDto(project)); - UserDto me = insertUser(randomAlphanumeric(10)); + UserDto me = insertUser(secure().nextAlphanumeric(10)); userSessionRule.logIn(me).registerProjects(projectData.getProjectDto()); IssueDto hotspot = dbTester.issues().insertHotspot(project, file, h -> h.setAssigneeUuid(me.getUuid())); @@ -210,8 +210,8 @@ public class AssignActionIT { ComponentDto file = dbTester.components().insertComponent(newFileDto(project.getMainBranchComponent())); IssueDto hotspot = dbTester.issues().insertHotspot(project.getMainBranchComponent(), file); - insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project.getProjectDto(), UserRole.USER); - UserDto assignee = insertUserWithProjectUserPermission(randomAlphanumeric(15), project.getProjectDto()); + insertAndLoginAsUserWithProjectUserPermission(secure().nextAlphanumeric(10), project.getProjectDto(), UserRole.USER); + UserDto assignee = insertUserWithProjectUserPermission(secure().nextAlphanumeric(15), project.getProjectDto()); when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(true); @@ -224,10 +224,10 @@ public class AssignActionIT { public void wsExecution_whenUnassignedForPrivateProject() { ProjectData project = dbTester.components().insertPrivateProject(); ComponentDto file = dbTester.components().insertComponent(newFileDto(project.getMainBranchComponent())); - UserDto assignee = insertUser(randomAlphanumeric(15)); + UserDto assignee = insertUser(secure().nextAlphanumeric(15)); IssueDto hotspot = dbTester.issues().insertHotspot(project.getMainBranchComponent(), file, h -> h.setAssigneeUuid(assignee.getUuid())); - insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project.getProjectDto(), UserRole.USER); + insertAndLoginAsUserWithProjectUserPermission(secure().nextAlphanumeric(10), project.getProjectDto(), UserRole.USER); when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), isNull(), any(IssueChangeContext.class))).thenReturn(true); @@ -243,9 +243,9 @@ public class AssignActionIT { ComponentDto file = dbTester.components().insertComponent(newFileDto(branch, project.getMainBranchComponent().uuid())); IssueDto hotspot = dbTester.issues().insertHotspot(branch, file); - insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project.getProjectDto(), UserRole.USER); + insertAndLoginAsUserWithProjectUserPermission(secure().nextAlphanumeric(10), project.getProjectDto(), UserRole.USER); userSessionRule.addProjectBranchMapping(project.projectUuid(), branch); - UserDto assignee = insertUserWithProjectUserPermission(randomAlphanumeric(15), project.getProjectDto()); + UserDto assignee = insertUserWithProjectUserPermission(secure().nextAlphanumeric(15), project.getProjectDto()); when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(true); @@ -260,8 +260,8 @@ public class AssignActionIT { ComponentDto file = dbTester.components().insertComponent(newFileDto(project.getMainBranchComponent())); IssueDto hotspot = dbTester.issues().insertHotspot(project.getMainBranchComponent(), file); - insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project.getProjectDto(), UserRole.USER); - UserDto assignee = insertUser(randomAlphanumeric(15)); + insertAndLoginAsUserWithProjectUserPermission(secure().nextAlphanumeric(10), project.getProjectDto(), UserRole.USER); + UserDto assignee = insertUser(secure().nextAlphanumeric(15)); when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(true); @@ -278,9 +278,9 @@ public class AssignActionIT { ComponentDto file = dbTester.components().insertComponent(newFileDto(branch, project.getMainBranchComponent())); IssueDto hotspot = dbTester.issues().insertHotspot(branch, file); - insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project.getProjectDto(), UserRole.USER); + insertAndLoginAsUserWithProjectUserPermission(secure().nextAlphanumeric(10), project.getProjectDto(), UserRole.USER); userSessionRule.addProjectBranchMapping(project.projectUuid(), branch); - UserDto assignee = insertUser(randomAlphanumeric(15)); + UserDto assignee = insertUser(secure().nextAlphanumeric(15)); when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(true); @@ -296,7 +296,7 @@ public class AssignActionIT { ComponentDto file = dbTester.components().insertComponent(newFileDto(project.getMainBranchComponent())); IssueDto hotspot = dbTester.issues().insertHotspot(project.getMainBranchComponent(), file); - UserDto me = insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project.getProjectDto(), UserRole.USER); + UserDto me = insertAndLoginAsUserWithProjectUserPermission(secure().nextAlphanumeric(10), project.getProjectDto(), UserRole.USER); when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(me), any(IssueChangeContext.class))).thenReturn(true); @@ -312,10 +312,10 @@ public class AssignActionIT { ComponentDto file = dbTester.components().insertComponent(newFileDto(project)); IssueDto hotspot = dbTester.issues().insertHotspot(project, file); - UserDto userDto = insertUser(randomAlphanumeric(10)); + UserDto userDto = insertUser(secure().nextAlphanumeric(10)); userSessionRule.logIn(userDto).registerProjects(projectData.getProjectDto()); - UserDto assignee = insertUser(randomAlphanumeric(15)); + UserDto assignee = insertUser(secure().nextAlphanumeric(15)); when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(true); @@ -332,10 +332,10 @@ public class AssignActionIT { ComponentDto file = dbTester.components().insertComponent(newFileDto(project)); IssueDto hotspot = dbTester.issues().insertHotspot(project, file); - UserDto userDto = insertUser(randomAlphanumeric(10)); + UserDto userDto = insertUser(secure().nextAlphanumeric(10)); userSessionRule.logIn(userDto).registerProjects(projectData.getProjectDto()); - UserDto assignee = insertUser(randomAlphanumeric(15)); + UserDto assignee = insertUser(secure().nextAlphanumeric(15)); when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(false); @@ -352,10 +352,10 @@ public class AssignActionIT { ComponentDto file = dbTester.components().insertComponent(newFileDto(project)); IssueDto hotspot = dbTester.issues().insertHotspot(project, file); - UserDto userDto = insertUser(randomAlphanumeric(10)); + UserDto userDto = insertUser(secure().nextAlphanumeric(10)); userSessionRule.logIn(userDto).registerProjects(projectData.getProjectDto()); - UserDto assignee = insertUser(randomAlphanumeric(15)); + UserDto assignee = insertUser(secure().nextAlphanumeric(15)); when(branchDto.getBranchType()).thenReturn(BranchType.BRANCH); String projectUuid = "projectUuid"; when(branchDto.getProjectUuid()).thenReturn(projectUuid); @@ -372,10 +372,10 @@ public class AssignActionIT { ComponentDto file = dbTester.components().insertComponent(newFileDto(project)); IssueDto hotspot = dbTester.issues().insertHotspot(project, file); - UserDto userDto = insertUser(randomAlphanumeric(10)); + UserDto userDto = insertUser(secure().nextAlphanumeric(10)); userSessionRule.logIn(userDto).registerProjects(projectData.getProjectDto()); - UserDto assignee = insertUser(randomAlphanumeric(15)); + UserDto assignee = insertUser(secure().nextAlphanumeric(15)); when(branchDto.getBranchType()).thenReturn(BranchType.PULL_REQUEST); when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(assignee), any(IssueChangeContext.class))).thenReturn(true); @@ -391,10 +391,10 @@ public class AssignActionIT { ComponentDto file = dbTester.components().insertComponent(newFileDto(project)); IssueDto hotspot = dbTester.issues().insertHotspot(project, file); - UserDto userDto = insertUser(randomAlphanumeric(10)); + UserDto userDto = insertUser(secure().nextAlphanumeric(10)); userSessionRule.logIn(userDto).registerProjects(projectData.getProjectDto()); - String notExistingUserLogin = randomAlphanumeric(10); + String notExistingUserLogin = secure().nextAlphanumeric(10); assertThatThrownBy(() -> executeRequest(hotspot, notExistingUserLogin, null)) .isInstanceOf(NotFoundException.class) @@ -412,7 +412,7 @@ public class AssignActionIT { h.setResolution(resolution); }); - UserDto userDto = insertUser(randomAlphanumeric(10)); + UserDto userDto = insertUser(secure().nextAlphanumeric(10)); userSessionRule.logIn(userDto).registerProjects(projectData.getProjectDto()); String login = userSessionRule.getLogin(); @@ -442,7 +442,7 @@ public class AssignActionIT { h.setResolution(resolution); }); - UserDto userDto = insertUser(randomAlphanumeric(10)); + UserDto userDto = insertUser(secure().nextAlphanumeric(10)); userSessionRule.logIn(userDto).registerProjects(projectData.getProjectDto()); String login = userSessionRule.getLogin(); @@ -465,7 +465,7 @@ public class AssignActionIT { userSessionRule.anonymous(); - UserDto assignee = insertUser(randomAlphanumeric(15)); + UserDto assignee = insertUser(secure().nextAlphanumeric(15)); String login = assignee.getLogin(); assertThatThrownBy(() -> executeRequest(hotspot, login, null)) @@ -479,7 +479,7 @@ public class AssignActionIT { ComponentDto file = dbTester.components().insertComponent(newFileDto(project.getMainBranchComponent())); IssueDto hotspot = dbTester.issues().insertHotspot(project.getMainBranchComponent(), file); - UserDto me = insertAndLoginAsUserWithProjectUserPermission(randomAlphanumeric(10), project.getProjectDto(), UserRole.CODEVIEWER); + UserDto me = insertAndLoginAsUserWithProjectUserPermission(secure().nextAlphanumeric(10), project.getProjectDto(), UserRole.CODEVIEWER); when(issueFieldsSetter.assign(eq(hotspot.toDefaultIssue()), userMatcher(me), any(IssueChangeContext.class))).thenReturn(true); @@ -493,10 +493,10 @@ public class AssignActionIT { public void wsExecution_whenHotspotDoesNotExist_shouldFail() { ProjectData projectData = dbTester.components().insertPublicProject(); ComponentDto project = projectData.getMainBranchComponent(); - UserDto me = insertUser(randomAlphanumeric(10)); + UserDto me = insertUser(secure().nextAlphanumeric(10)); userSessionRule.logIn().registerProjects(projectData.getProjectDto()); - String notExistingHotspotKey = randomAlphanumeric(10); + String notExistingHotspotKey = secure().nextAlphanumeric(10); String login = me.getLogin(); assertThatThrownBy(() -> executeRequest(notExistingHotspotKey, login, null)) .isInstanceOf(NotFoundException.class) @@ -514,7 +514,7 @@ public class AssignActionIT { .setStatus(status) .setType(ruleType)); - UserDto me = insertUser(randomAlphanumeric(10)); + UserDto me = insertUser(secure().nextAlphanumeric(10)); userSessionRule.logIn().registerProjects(projectData.getProjectDto()); String login = me.getLogin(); @@ -546,7 +546,7 @@ public class AssignActionIT { ComponentDto file = dbTester.components().insertComponent(newFileDto(project)); RuleDto rule = newRule(SECURITY_HOTSPOT); IssueDto issue = dbTester.issues().insertHotspot(rule, project, file, t -> t.setStatus(STATUS_CLOSED)); - UserDto me = insertUser(randomAlphanumeric(10)); + UserDto me = insertUser(secure().nextAlphanumeric(10)); userSessionRule.logIn().registerProjects(projectData.getProjectDto()); String login = me.getLogin(); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/ChangeStatusActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/ChangeStatusActionIT.java index 44af6e70472..ac068b2cd0f 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/ChangeStatusActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/ChangeStatusActionIT.java @@ -65,7 +65,7 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; @@ -140,7 +140,7 @@ public class ChangeStatusActionIT { @Test public void fails_with_IAE_if_parameter_status_is_missing() { - String key = randomAlphabetic(12); + String key = secure().nextAlphabetic(12); userSessionRule.logIn(); TestRequest request = actionTester.newRequest() .setParam("hotspot", key); @@ -153,7 +153,7 @@ public class ChangeStatusActionIT { @Test @UseDataProvider("badStatuses") public void fail_with_IAE_if_status_value_is_neither_REVIEWED_nor_TO_REVIEW(String badStatus) { - String key = randomAlphabetic(12); + String key = secure().nextAlphabetic(12); userSessionRule.logIn(); TestRequest request = actionTester.newRequest() .setParam("hotspot", key) @@ -170,7 +170,7 @@ public class ChangeStatusActionIT { Issue.STATUSES.stream() .filter(t -> !t.equals(STATUS_TO_REVIEW)) .filter(t -> !t.equals(STATUS_REVIEWED)), - Stream.of(randomAlphabetic(22), "")) + Stream.of(secure().nextAlphabetic(22), "")) .map(t -> new Object[] {t}) .toArray(Object[][]::new); } @@ -178,7 +178,7 @@ public class ChangeStatusActionIT { @Test @UseDataProvider("badResolutions") public void fail_with_IAE_if_resolution_value_is_neither_FIXED_nor_SAFE(String validStatus, String badResolution) { - String key = randomAlphabetic(12); + String key = secure().nextAlphabetic(12); userSessionRule.logIn(); TestRequest request = actionTester.newRequest() .setParam("hotspot", key) @@ -202,7 +202,7 @@ public class ChangeStatusActionIT { @Test @UseDataProvider("validResolutions") public void fail_with_IAE_if_status_is_TO_REVIEW_and_resolution_is_set(String resolution) { - String key = randomAlphabetic(12); + String key = secure().nextAlphabetic(12); userSessionRule.logIn(); TestRequest request = actionTester.newRequest() .setParam("hotspot", key) @@ -224,7 +224,7 @@ public class ChangeStatusActionIT { } public void fail_with_IAE_if_status_is_RESOLVED_and_resolution_is_not_set() { - String key = randomAlphabetic(12); + String key = secure().nextAlphabetic(12); userSessionRule.logIn(); TestRequest request = actionTester.newRequest() .setParam("hotspot", key) @@ -238,7 +238,7 @@ public class ChangeStatusActionIT { @Test @UseDataProvider("validStatusAndResolutions") public void fails_with_NotFoundException_if_hotspot_does_not_exist(String status, @Nullable String resolution) { - String key = randomAlphabetic(12); + String key = secure().nextAlphabetic(12); userSessionRule.logIn(); TestRequest request = actionTester.newRequest() .setParam("hotspot", key) @@ -586,7 +586,7 @@ public class ChangeStatusActionIT { ComponentDto file = dbTester.components().insertComponent(newFileDto(project)); IssueDto hotspot = dbTester.issues().insertHotspot(project, file, h -> h.setStatus(currentStatus).setResolution(currentResolution)); when(transitionService.doTransition(any(), any(), any())).thenReturn(transitionDone); - String comment = randomAlphabetic(12); + String comment = secure().nextAlphabetic(12); newRequest(hotspot, newStatus, newResolution, comment).execute().assertNoContent(); @@ -644,7 +644,7 @@ public class ChangeStatusActionIT { .addProjectPermission(UserRole.SECURITYHOTSPOT_ADMIN, projectData.getProjectDto()); ComponentDto file = dbTester.components().insertComponent(newFileDto(project)); IssueDto hotspot = dbTester.issues().insertHotspot(project, file, h -> h.setStatus(status).setResolution(resolution)); - String comment = randomAlphabetic(12); + String comment = secure().nextAlphabetic(12); newRequest(hotspot, status, resolution, comment).execute().assertNoContent(); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/SearchActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/SearchActionIT.java index 893a8214476..6c636202e6e 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/SearchActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/SearchActionIT.java @@ -88,8 +88,7 @@ import static java.util.Collections.singleton; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; @@ -214,8 +213,8 @@ public class SearchActionIT { @Test public void fail_with_IAE_if_parameter_branch_is_used_without_parameter_project() { TestRequest request = actionTester.newRequest() - .setParam(PARAM_HOTSPOTS, randomAlphabetic(2)) - .setParam(PARAM_BRANCH, randomAlphabetic(1)); + .setParam(PARAM_HOTSPOTS, secure().nextAlphabetic(2)) + .setParam(PARAM_BRANCH, secure().nextAlphabetic(1)); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) @@ -225,8 +224,8 @@ public class SearchActionIT { @Test public void fail_with_IAE_if_parameter_pullRequest_is_used_without_parameter_project() { TestRequest request = actionTester.newRequest() - .setParam(PARAM_HOTSPOTS, randomAlphabetic(2)) - .setParam(PARAM_PULL_REQUEST, randomAlphabetic(1)); + .setParam(PARAM_HOTSPOTS, secure().nextAlphabetic(2)) + .setParam(PARAM_PULL_REQUEST, secure().nextAlphabetic(1)); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) @@ -236,9 +235,9 @@ public class SearchActionIT { @Test public void fail_with_IAE_if_both_parameters_pullRequest_and_branch_are_provided() { TestRequest request = actionTester.newRequest() - .setParam(PARAM_PROJECT, randomAlphabetic(2)) - .setParam(PARAM_BRANCH, randomAlphabetic(1)) - .setParam(PARAM_PULL_REQUEST, randomAlphabetic(1)); + .setParam(PARAM_PROJECT, secure().nextAlphabetic(2)) + .setParam(PARAM_BRANCH, secure().nextAlphabetic(1)) + .setParam(PARAM_PULL_REQUEST, secure().nextAlphabetic(1)); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) @@ -249,7 +248,7 @@ public class SearchActionIT { @UseDataProvider("badStatuses") public void fails_with_IAE_if_status_parameter_is_neither_TO_REVIEW_or_REVIEWED(String badStatus) { TestRequest request = actionTester.newRequest() - .setParam(PARAM_PROJECT, randomAlphabetic(13)) + .setParam(PARAM_PROJECT, secure().nextAlphabetic(13)) .setParam(PARAM_STATUS, badStatus); assertThatThrownBy(request::execute) @@ -261,7 +260,7 @@ public class SearchActionIT { public static Object[][] badStatuses() { return Stream.concat( Issue.STATUSES.stream(), - Stream.of(randomAlphabetic(3))) + Stream.of(secure().nextAlphabetic(3))) .filter(t -> !STATUS_REVIEWED.equals(t)) .filter(t -> !STATUS_TO_REVIEW.equals(t)) .map(t -> new Object[] {t}) @@ -272,7 +271,7 @@ public class SearchActionIT { @UseDataProvider("validStatusesAndResolutions") public void fail_with_IAE_if_parameter_status_is_specified_with_hotspots_parameter(String status, @Nullable String notUsed) { TestRequest request = actionTester.newRequest() - .setParam(PARAM_HOTSPOTS, randomAlphabetic(12)) + .setParam(PARAM_HOTSPOTS, secure().nextAlphabetic(12)) .setParam(PARAM_STATUS, status); assertThatThrownBy(request::execute) @@ -284,7 +283,7 @@ public class SearchActionIT { @UseDataProvider("badResolutions") public void fails_with_IAE_if_resolution_parameter_is_neither_FIXED_nor_SAFE(String badResolution) { TestRequest request = actionTester.newRequest() - .setParam(PARAM_PROJECT, randomAlphabetic(13)) + .setParam(PARAM_PROJECT, secure().nextAlphabetic(13)) .setParam(PARAM_STATUS, STATUS_TO_REVIEW) .setParam(PARAM_RESOLUTION, badResolution); @@ -298,7 +297,7 @@ public class SearchActionIT { return Stream.of( Issue.RESOLUTIONS.stream(), Issue.SECURITY_HOTSPOT_RESOLUTIONS.stream(), - Stream.of(randomAlphabetic(4))) + Stream.of(secure().nextAlphabetic(4))) .flatMap(t -> t) .filter(t -> !RESOLUTION_TYPES.contains(t)) .map(t -> new Object[] {t}) @@ -309,7 +308,7 @@ public class SearchActionIT { @UseDataProvider("fixedOrSafeResolution") public void fails_with_IAE_if_resolution_is_provided_with_status_TO_REVIEW(String resolution) { TestRequest request = actionTester.newRequest() - .setParam(PARAM_PROJECT, randomAlphabetic(13)) + .setParam(PARAM_PROJECT, secure().nextAlphabetic(13)) .setParam(PARAM_STATUS, STATUS_TO_REVIEW) .setParam(PARAM_RESOLUTION, resolution); @@ -322,7 +321,7 @@ public class SearchActionIT { @UseDataProvider("fixedOrSafeResolution") public void fails_with_IAE_if_resolution_is_provided_with_hotspots_parameter(String resolution) { TestRequest request = actionTester.newRequest() - .setParam(PARAM_HOTSPOTS, randomAlphabetic(13)) + .setParam(PARAM_HOTSPOTS, secure().nextAlphabetic(13)) .setParam(PARAM_RESOLUTION, resolution); assertThatThrownBy(request::execute) @@ -340,7 +339,7 @@ public class SearchActionIT { @Test public void fails_with_NotFoundException_if_project_does_not_exist() { - String key = randomAlphabetic(12); + String key = secure().nextAlphabetic(12); TestRequest request = actionTester.newRequest() .setParam(PARAM_PROJECT, key); @@ -775,7 +774,7 @@ public class SearchActionIT { IssueDto[] assigneeHotspots = IntStream.range(0, 1 + RANDOM.nextInt(10)) .mapToObj(i -> { RuleDto rule = newRule(SECURITY_HOTSPOT); - insertHotspot(rule, project1, file1, randomAlphabetic(5)); + insertHotspot(rule, project1, file1, secure().nextAlphabetic(5)); return insertHotspot(rule, project1, file1, assigneeUuid); }) .toArray(IssueDto[]::new); @@ -937,7 +936,7 @@ public class SearchActionIT { RuleDto rule = newRule(SECURITY_HOTSPOT); IssueDto unresolvedHotspot = insertHotspot(rule, project, file, t -> t.setResolution(null)); // unrealistic case since a resolution must be set, but shows a limit of current implementation (resolution is enough) - IssueDto badlyResolved = insertHotspot(rule, project, file, t -> t.setStatus(STATUS_TO_REVIEW).setResolution(randomAlphabetic(5))); + IssueDto badlyResolved = insertHotspot(rule, project, file, t -> t.setStatus(STATUS_TO_REVIEW).setResolution(secure().nextAlphabetic(5))); IssueDto badlyReviewed = insertHotspot(rule, project, file, t -> t.setStatus(STATUS_REVIEWED).setResolution(null)); IssueDto badlyClosedHotspot = insertHotspot(rule, project, file, t -> t.setStatus(STATUS_CLOSED).setResolution(null)); indexIssues(); @@ -981,11 +980,11 @@ public class SearchActionIT { RuleDto rule = newRule(SECURITY_HOTSPOT); IssueDto hotspot = insertHotspot(rule, project, file, t -> t - .setStatus(randomAlphabetic(11)) + .setStatus(secure().nextAlphabetic(11)) .setLine(RANDOM.nextInt(230)) - .setMessage(randomAlphabetic(10)) - .setAssigneeUuid(randomAlphabetic(9)) - .setAuthorLogin(randomAlphabetic(8)) + .setMessage(secure().nextAlphabetic(10)) + .setAssigneeUuid(secure().nextAlphabetic(9)) + .setAuthorLogin(secure().nextAlphabetic(8)) .setStatus(status) .setResolution(resolution)); indexIssues(); @@ -1141,7 +1140,7 @@ public class SearchActionIT { public void returns_branch_field_of_components_of_branch() { ProjectData projectData = dbTester.components().insertPublicProject(); ComponentDto project = projectData.getMainBranchComponent(); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = dbTester.components().insertProjectBranch(project, b -> b.setKey(branchName)); userSessionRule.registerProjects(projectData.getProjectDto()); indexPermissions(); @@ -1178,7 +1177,7 @@ public class SearchActionIT { public void returns_pullRequest_field_of_components_of_pullRequest() { ProjectData projectData = dbTester.components().insertPublicProject(); ComponentDto project = projectData.getMainBranchComponent(); - String pullRequestKey = randomAlphanumeric(100); + String pullRequestKey = secure().nextAlphanumeric(100); ComponentDto pullRequest = dbTester.components().insertProjectBranch(project, t -> t.setBranchType(BranchType.PULL_REQUEST) .setKey(pullRequestKey)); userSessionRule.registerProjects(projectData.getProjectDto()); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/ShowActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/ShowActionIT.java index 66c2cb4026a..6186a797096 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/ShowActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/hotspot/ws/ShowActionIT.java @@ -64,11 +64,11 @@ import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleTesting; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserTesting; +import org.sonar.server.common.avatar.AvatarResolver; +import org.sonar.server.common.avatar.AvatarResolverImpl; import org.sonar.server.es.EsTester; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; -import org.sonar.server.common.avatar.AvatarResolver; -import org.sonar.server.common.avatar.AvatarResolverImpl; import org.sonar.server.issue.IssueChangeWSSupport; import org.sonar.server.issue.IssueChangeWSSupport.FormattingContext; import org.sonar.server.issue.IssueChangeWSSupport.Load; @@ -86,8 +86,7 @@ import org.sonarqube.ws.Common.User; import org.sonarqube.ws.Hotspots; import static java.util.Collections.emptySet; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; @@ -148,7 +147,7 @@ public class ShowActionIT { @Test public void fails_with_NotFoundException_if_hotspot_does_not_exist() { - String key = randomAlphabetic(12); + String key = secure().nextAlphabetic(12); TestRequest request = actionTester.newRequest() .setParam("hotspot", key); @@ -559,7 +558,7 @@ public class ShowActionIT { return RuleDescriptionSectionDto.builder() .uuid(uuidFactory.create()) .key(assessTheProblemSectionKey) - .content(randomAlphabetic(200)) + .content(secure().nextAlphabetic(200)) .build(); } @@ -723,7 +722,7 @@ public class ShowActionIT { userSessionRule.registerProjects(projectData.getProjectDto()); ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent)); RuleDto rule = newRule(SECURITY_HOTSPOT); - IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file, t -> t.setAssigneeUuid(randomAlphabetic(10))); + IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file, t -> t.setAssigneeUuid(secure().nextAlphabetic(10))); mockChangelogAndCommentsFormattingContext(); Hotspots.ShowWsResponse response = newRequest(hotspot) @@ -802,7 +801,7 @@ public class ShowActionIT { userSessionRule.registerProjects(projectData.getProjectDto()); ComponentDto file = dbTester.components().insertComponent(newFileDto(mainBranchComponent)); RuleDto rule = newRule(SECURITY_HOTSPOT); - String authorLogin = randomAlphabetic(10); + String authorLogin = secure().nextAlphabetic(10); IssueDto hotspot = dbTester.issues().insertHotspot(rule, mainBranchComponent, file, t -> t.setAuthorLogin(authorLogin)); mockChangelogAndCommentsFormattingContext(); @@ -974,7 +973,7 @@ public class ShowActionIT { public void returns_branch_but_no_pullRequest_on_component_and_project_on_non_main_branch() { ProjectData projectData = dbTester.components().insertPublicProject(); ComponentDto mainBranchComponent = projectData.getMainBranchComponent(); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = dbTester.components().insertProjectBranch(mainBranchComponent, b -> b.setKey(branchName)); userSessionRule.addProjectBranchMapping(mainBranchComponent.uuid(), branch); ComponentDto file = dbTester.components().insertComponent(newFileDto(branch, mainBranchComponent.uuid())); @@ -997,7 +996,7 @@ public class ShowActionIT { public void returns_pullRequest_but_no_branch_on_component_and_project_on_pullRequest() { ProjectData projectData = dbTester.components().insertPublicProject(); ComponentDto mainBranchComponent = projectData.getMainBranchComponent(); - String pullRequestKey = randomAlphanumeric(100); + String pullRequestKey = secure().nextAlphanumeric(100); ComponentDto pullRequest = dbTester.components().insertProjectBranch(mainBranchComponent, t -> t.setBranchType(BranchType.PULL_REQUEST).setKey(pullRequestKey)); userSessionRule.addProjectBranchMapping(mainBranchComponent.uuid(), pullRequest); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/IssueChangeWSSupportIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/IssueChangeWSSupportIT.java index 9103fc33a68..a3e189f00c1 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/IssueChangeWSSupportIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/IssueChangeWSSupportIT.java @@ -57,7 +57,7 @@ import org.sonarqube.ws.Common.Comment; import static java.util.Collections.emptySet; import static java.util.Collections.singleton; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.utils.DateUtils.formatDateTime; @@ -177,7 +177,7 @@ public class IssueChangeWSSupportIT { UserDto user1 = dbTester.users().insertUser(); UserDto user2 = dbTester.users().insertUser(); UserDto user3 = dbTester.users().insertUser(); - String uuid = randomAlphabetic(30); + String uuid = secure().nextAlphabetic(30); IssueChangeDto fieldChangeUser1 = newFieldChange(issue) .setUserUuid(user1.getUuid()) .setChangeData(new FieldDiffs().setDiff("f_change_user_1", null, null).toEncodedString()); @@ -209,7 +209,7 @@ public class IssueChangeWSSupportIT { UserDto user1 = dbTester.users().insertUser(); UserDto user2 = dbTester.users().insertUser(); UserDto user3 = dbTester.users().insertUser(); - String uuid = randomAlphabetic(30); + String uuid = secure().nextAlphabetic(30); IssueChangeDto issueChangeUser1 = newComment(issue).setUserUuid(user1.getUuid()); IssueChangeDto issueChangeUser2a = newComment(issue).setUserUuid(user2.getUuid()); IssueChangeDto issueChangeUser2b = newComment(issue).setUserUuid(user2.getUuid()); @@ -234,7 +234,7 @@ public class IssueChangeWSSupportIT { UserDto user2 = dbTester.users().insertUser(); UserDto user3 = dbTester.users().insertUser(); UserDto user4 = dbTester.users().insertUser(); - String uuid = randomAlphabetic(30); + String uuid = secure().nextAlphabetic(30); IssueChangeDto issueChangeUser1 = newComment(issue).setUserUuid(user1.getUuid()); IssueChangeDto issueChangeUser2a = newComment(issue).setUserUuid(user2.getUuid()); IssueChangeDto issueChangeUser2b = newComment(issue).setUserUuid(user2.getUuid()); @@ -280,7 +280,7 @@ public class IssueChangeWSSupportIT { ComponentDto file3 = insertFile(); ComponentDto file4 = insertFile(); ComponentDto file5 = insertFile(); - String uuid = randomAlphabetic(30); + String uuid = secure().nextAlphabetic(30); IssueChangeDto fileChangeFile1 = newFieldChange(issue) .setChangeData(new FieldDiffs().setDiff("file", file1.uuid(), null).toEncodedString()); IssueChangeDto fileChangeFile2 = newFieldChange(issue) @@ -417,7 +417,7 @@ public class IssueChangeWSSupportIT { public void newFormattingContext_comments_without_userUuid_or_with_unknown_userUuid_are_not_updatable(Load load) { IssueDto issue = dbTester.issues().insertIssue(); UserDto user1 = dbTester.users().insertUser(); - String uuid = randomAlphabetic(30); + String uuid = secure().nextAlphabetic(30); IssueChangeDto issueChangeUser1 = newComment(issue); IssueChangeDto issueChangeUserUnknown = newComment(issue).setUserUuid(uuid); insertInRandomOrder(Arrays.asList(issueChangeUser1, issueChangeUserUnknown)); @@ -434,7 +434,7 @@ public class IssueChangeWSSupportIT { IssueDto issue = dbTester.issues().insertIssue(); UserDto user1 = dbTester.users().insertUser(); UserDto user2 = dbTester.users().insertUser(); - String uuid = randomAlphabetic(30); + String uuid = secure().nextAlphabetic(30); IssueChangeDto issueChangeUser1 = newComment(issue).setUserUuid(user1.getUuid()); IssueChangeDto issueChangeUser2 = newComment(issue).setUserUuid(user2.getUuid()); IssueChangeDto issueChangeUserUnknown = newComment(issue).setUserUuid(uuid); @@ -454,7 +454,7 @@ public class IssueChangeWSSupportIT { UserDto user1 = dbTester.users().insertUser(); UserDto user2 = dbTester.users().insertUser(); userSessionRule.logIn(user2); - String uuid = randomAlphabetic(30); + String uuid = secure().nextAlphabetic(30); IssueChangeDto issueChangeUser1a = newComment(issue).setUserUuid(user1.getUuid()); IssueChangeDto issueChangeUser1b = newComment(issue).setUserUuid(user1.getUuid()); IssueChangeDto issueChangeUser2a = newComment(issue).setUserUuid(user2.getUuid()); @@ -552,7 +552,7 @@ public class IssueChangeWSSupportIT { IssueDto issue1 = dbTester.issues().insertIssue(); UserDto user1 = dbTester.users().insertUser(); UserDto user2 = dbTester.users().insertUser(t -> t.setActive(false)); - String uuid = randomAlphabetic(22); + String uuid = secure().nextAlphabetic(22); dbTester.issues().insertChange(newFieldChange(issue1) .setUserUuid(user1.getUuid()) .setChangeData(new FieldDiffs() diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/PullTaintActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/PullTaintActionIT.java index 963d8e8771f..17cebf289af 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/PullTaintActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/PullTaintActionIT.java @@ -61,7 +61,7 @@ import org.sonarqube.ws.Issues; import static java.lang.String.format; import static java.util.stream.Collectors.toList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; @@ -409,7 +409,7 @@ public class PullTaintActionIT { RuleDto javaRule = db.rules().insert(r -> r.setRepositoryKey("javasecurity")); RuleDto javaScriptRule = db.rules().insert(r -> r.setRepositoryKey("javascript")); - String ruledescriptionContextKey = randomAlphabetic(6); + String ruledescriptionContextKey = secure().nextAlphabetic(6); IssueDto issueDto = issueDbTester.insertIssue(p -> p.setSeverity("MINOR") .setManualSeverity(true) .setMessage("openIssue") diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/SearchActionComponentsIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/SearchActionComponentsIT.java index 634f923fd93..6d9040f36bd 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/SearchActionComponentsIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/issue/ws/SearchActionComponentsIT.java @@ -59,7 +59,7 @@ import org.sonarqube.ws.Issues.Component; import org.sonarqube.ws.Issues.Issue; import org.sonarqube.ws.Issues.SearchWsResponse; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.resources.Qualifiers.APP; @@ -571,7 +571,7 @@ public class SearchActionComponentsIT { ComponentDto file = db.components().insertComponent(newFileDto(project)); IssueDto issue = db.issues().insertIssue(rule, project, file); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(BRANCH).setKey(branchName)); ComponentDto branchFile = db.components().insertComponent(newFileDto(branch, project.uuid())); IssueDto branchIssue = db.issues().insertIssue(rule, branch, branchFile); @@ -609,7 +609,7 @@ public class SearchActionComponentsIT { ComponentDto project = projectData.getMainBranchComponent(); ComponentDto projectFile = db.components().insertComponent(newFileDto(project)); IssueDto projectIssue = db.issues().insertIssue(rule, project, projectFile); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(BRANCH).setKey(branchName)); ComponentDto branchFile = db.components().insertComponent(newFileDto(branch, project.uuid())); IssueDto branchIssue = db.issues().insertIssue(rule, branch, branchFile); @@ -636,7 +636,7 @@ public class SearchActionComponentsIT { ComponentDto projectFile = db.components().insertComponent(newFileDto(project)); IssueDto projectIssue = db.issues().insertIssue(rule, project, projectFile); - String pullRequestKey = randomAlphanumeric(100); + String pullRequestKey = secure().nextAlphanumeric(100); ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey)); ComponentDto pullRequestFile = db.components().insertComponent(newFileDto(pullRequest, project.uuid())); IssueDto pullRequestIssue = db.issues().insertIssue(rule, pullRequest, pullRequestFile); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/projectanalysis/ws/DeleteActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/projectanalysis/ws/DeleteActionIT.java index 382f8184d18..4a24f568793 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/projectanalysis/ws/DeleteActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/projectanalysis/ws/DeleteActionIT.java @@ -93,7 +93,7 @@ public class DeleteActionIT { @Test public void fail_when_analysis_is_new_code_period_baseline() { - String analysisUuid = RandomStringUtils.randomAlphabetic(12); + String analysisUuid = RandomStringUtils.secure().nextAlphabetic(12); ProjectData project = db.components().insertPrivateProject(); SnapshotDto analysis = db.components().insertSnapshot(newAnalysis(project.getMainBranchDto()).setUuid(analysisUuid).setLast(false)); db.newCodePeriods().insert(new NewCodePeriodDto() diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/DestroyActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/DestroyActionIT.java index b7d547ffc42..789fed95cc0 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/DestroyActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/DestroyActionIT.java @@ -40,7 +40,7 @@ import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static java.lang.String.valueOf; -import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; @@ -249,8 +249,8 @@ public class DestroyActionIT { private void insertARandomCondition(QualityGateDto qualityGate) { QualityGateConditionDto condition = new QualityGateConditionDto() - .setUuid(randomAlphanumeric(40)) - .setMetricUuid(randomAlphanumeric(40)) + .setUuid(secure().nextAlphanumeric(40)) + .setMetricUuid(secure().nextAlphanumeric(40)) .setQualityGateUuid(qualityGate.getUuid()); db.getDbClient().gateConditionDao().insert(condition, db.getSession()); db.commit(); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/ProjectStatusActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/ProjectStatusActionIT.java index 8e339b42eef..e4ba5c13330 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/ProjectStatusActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/ProjectStatusActionIT.java @@ -50,7 +50,7 @@ import org.sonarqube.ws.Qualitygates.ProjectStatusResponse.Status; import static java.lang.String.format; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; @@ -236,7 +236,7 @@ public class ProjectStatusActionIT { public void return_live_status_when_branch_is_referenced_by_its_key() throws IOException { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(mainBranch, b -> b.setKey(branchName)); dbClient.snapshotDao().insert(dbSession, newAnalysis(branch) @@ -261,7 +261,7 @@ public class ProjectStatusActionIT { public void return_live_status_when_pull_request_is_referenced_by_its_key() throws IOException { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); - String pullRequestKey = RandomStringUtils.randomAlphanumeric(100); + String pullRequestKey = RandomStringUtils.secure().nextAlphanumeric(100); ComponentDto pr = db.components().insertProjectBranch(mainBranch, branch -> branch.setBranchType(BranchType.PULL_REQUEST) .setKey(pullRequestKey)); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/QProfileRuleImplIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/QProfileRuleImplIT.java index a35fe2ade7f..309292a3f82 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/QProfileRuleImplIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/QProfileRuleImplIT.java @@ -66,7 +66,7 @@ import static java.util.Collections.singletonList; import static java.util.Map.entry; import static java.util.Map.of; import static java.util.Map.ofEntries; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; @@ -958,8 +958,8 @@ class QProfileRuleImplIT { @Test void bulk_activation() { int bulkSize = SearchOptions.MAX_PAGE_SIZE + 10 + new Random().nextInt(100); - String language = randomAlphanumeric(10); - String repositoryKey = randomAlphanumeric(10); + String language = secure().nextAlphanumeric(10); + String repositoryKey = secure().nextAlphanumeric(10); QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(language)); List rules = new ArrayList<>(); @@ -984,8 +984,8 @@ class QProfileRuleImplIT { @Test void bulk_deactivation() { int bulkSize = SearchOptions.MAX_PAGE_SIZE + 10 + new Random().nextInt(100); - String language = randomAlphanumeric(10); - String repositoryKey = randomAlphanumeric(10); + String language = secure().nextAlphanumeric(10); + String repositoryKey = secure().nextAlphanumeric(10); QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(language)); List rules = new ArrayList<>(); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/RegisterQualityProfilesNotificationIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/RegisterQualityProfilesNotificationIT.java index a94ff75156c..2cbacb0e67c 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/RegisterQualityProfilesNotificationIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/RegisterQualityProfilesNotificationIT.java @@ -71,7 +71,7 @@ import org.sonar.server.util.TypeValidations; import static com.google.common.base.Preconditions.checkState; import static java.util.Collections.singleton; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; @@ -374,6 +374,6 @@ public class RegisterQualityProfilesNotificationIT { } private static String newLanguageKey() { - return randomAlphanumeric(20).toLowerCase(); + return secure().nextAlphanumeric(20).toLowerCase(); } } diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ActivateRuleActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ActivateRuleActionIT.java index 18e8d23386b..72e33b8b962 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ActivateRuleActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ActivateRuleActionIT.java @@ -47,7 +47,7 @@ import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; @@ -92,7 +92,7 @@ class ActivateRuleActionIT { TestRequest request = ws.newRequest() .setMethod("POST") .setParam(PARAM_RULE, RuleTesting.newRule().getKey().toString()) - .setParam(PARAM_KEY, randomAlphanumeric(UUID_SIZE)); + .setParam(PARAM_KEY, secure().nextAlphanumeric(UUID_SIZE)); assertThatThrownBy(() -> request.execute()) .isInstanceOf(UnauthorizedException.class); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ActivateRulesActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ActivateRulesActionIT.java index 3c3ffc6d4aa..900de2cf852 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ActivateRulesActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ActivateRulesActionIT.java @@ -38,7 +38,7 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; @@ -133,7 +133,7 @@ class ActivateRulesActionIT { void fail_if_not_logged_in() { TestRequest request = ws.newRequest() .setMethod("POST") - .setParam(PARAM_TARGET_KEY, randomAlphanumeric(UUID_SIZE)); + .setParam(PARAM_TARGET_KEY, secure().nextAlphanumeric(UUID_SIZE)); assertThatThrownBy(() -> request.execute()) .isInstanceOf(UnauthorizedException.class); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ChangeParentActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ChangeParentActionIT.java index 6712cd354c7..1a29b094687 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ChangeParentActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ChangeParentActionIT.java @@ -65,7 +65,7 @@ import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters; import static java.util.Arrays.asList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; @@ -89,8 +89,8 @@ public class ChangeParentActionIT { private RuleIndexer ruleIndexer; private ActiveRuleIndexer activeRuleIndexer; private WsActionTester ws; - private Language language = LanguageTesting.newLanguage(randomAlphanumeric(20)); - private String ruleRepository = randomAlphanumeric(5); + private Language language = LanguageTesting.newLanguage(secure().nextAlphanumeric(20)); + private String ruleRepository = secure().nextAlphanumeric(5); private QProfileTreeImpl qProfileTree; private SonarQubeVersion sonarQubeVersion; @@ -373,7 +373,7 @@ public class ChangeParentActionIT { } private RuleDto createRule() { - RuleDto rule = RuleTesting.newRule(RuleKey.of(ruleRepository, randomAlphanumeric(5))) + RuleDto rule = RuleTesting.newRule(RuleKey.of(ruleRepository, secure().nextAlphanumeric(5))) .setLanguage(language.getKey()) .setSeverity(Severity.BLOCKER) .setStatus(RuleStatus.READY); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/DeactivateRuleActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/DeactivateRuleActionIT.java index fbb963c029e..e950a21bab8 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/DeactivateRuleActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/DeactivateRuleActionIT.java @@ -44,7 +44,7 @@ import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; @@ -123,7 +123,7 @@ public class DeactivateRuleActionIT { TestRequest request = ws.newRequest() .setMethod("POST") .setParam(PARAM_RULE, RuleTesting.newRule().getKey().toString()) - .setParam(PARAM_KEY, randomAlphanumeric(UUID_SIZE)); + .setParam(PARAM_KEY, secure().nextAlphanumeric(UUID_SIZE)); assertThatThrownBy(request::execute) .isInstanceOf(UnauthorizedException.class); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/DeactivateRulesActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/DeactivateRulesActionIT.java index ca95745839d..9f863094cae 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/DeactivateRulesActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/DeactivateRulesActionIT.java @@ -36,7 +36,7 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; @@ -131,7 +131,7 @@ public class DeactivateRulesActionIT { public void fail_if_not_logged_in() { TestRequest request = ws.newRequest() .setMethod("POST") - .setParam(PARAM_TARGET_KEY, randomAlphanumeric(UUID_SIZE)); + .setParam(PARAM_TARGET_KEY, secure().nextAlphanumeric(UUID_SIZE)); assertThatThrownBy(request::execute) .isInstanceOf(UnauthorizedException.class); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/rule/ws/SearchActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/rule/ws/SearchActionIT.java index 768a7225065..20f6b3cc1a0 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/rule/ws/SearchActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/rule/ws/SearchActionIT.java @@ -89,7 +89,7 @@ import static java.util.Arrays.stream; import static java.util.Collections.emptySet; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; @@ -628,7 +628,7 @@ public class SearchActionIT { @Test public void return_lang_key_field_when_language_name_is_not_available() { - String unknownLanguage = "unknown_" + randomAlphanumeric(5); + String unknownLanguage = "unknown_" + secure().nextAlphanumeric(5); RuleDto rule = db.rules().insert(r -> r.setLanguage(unknownLanguage)); indexRules(); @@ -882,7 +882,7 @@ public class SearchActionIT { tuple(ruleParam1.getName(), ruleParam1.getDefaultValue()), tuple(ruleParam2.getName(), ruleParam2.getDefaultValue())); - String unknownProfile = "unknown_profile" + randomAlphanumeric(5); + String unknownProfile = "unknown_profile" + secure().nextAlphanumeric(5); assertThatThrownBy(() -> { ws.newRequest() diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/source/ws/LinesActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/source/ws/LinesActionIT.java index 17b7caf6b89..fea1aa3d69b 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/source/ws/LinesActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/source/ws/LinesActionIT.java @@ -49,7 +49,7 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyString; @@ -125,7 +125,7 @@ public class LinesActionIT { public void branch() { ProjectData project = db.components().insertPrivateProject(); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(project.getMainBranchComponent(), b -> b.setKey(branchName)); ComponentDto file = db.components().insertComponent(newFileDto(branch, project.mainBranchUuid())); db.getDbClient().fileSourceDao().insert(db.getSession(), new FileSourceDto() @@ -151,7 +151,7 @@ public class LinesActionIT { public void pull_request() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); - String pullRequestKey = randomAlphanumeric(100); + String pullRequestKey = secure().nextAlphanumeric(100); ComponentDto branch = db.components().insertProjectBranch(mainBranch, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey)); ComponentDto file = db.components().insertComponent(newFileDto(branch, mainBranch.uuid())); db.getDbClient().fileSourceDao().insert(db.getSession(), new FileSourceDto() diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/source/ws/RawActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/source/ws/RawActionIT.java index 65d673385d2..04909d0c278 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/source/ws/RawActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/source/ws/RawActionIT.java @@ -35,7 +35,7 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.component.ComponentTesting.newFileDto; @@ -77,7 +77,7 @@ public class RawActionIT { public void raw_from_branch_file() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.addProjectPermission(UserRole.CODEVIEWER, project); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName)); userSession.addProjectBranchMapping(project.uuid(), branch); ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid())); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/CurrentActionHomepageIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/CurrentActionHomepageIT.java index 6d699f34f3b..78714e541de 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/CurrentActionHomepageIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/CurrentActionHomepageIT.java @@ -46,7 +46,7 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Users.CurrentWsResponse; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -176,7 +176,7 @@ public class CurrentActionHomepageIT { public void return_homepage_when_set_to_a_branch() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto project = projectData.getMainBranchComponent(); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName)); UserDto user = db.users().insertUser(u -> u.setHomepageType("PROJECT").setHomepageParameter(branch.uuid())); userSessionRule.logIn(user).addProjectPermission(USER, projectData.getProjectDto()); diff --git a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/SetHomepageActionIT.java b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/SetHomepageActionIT.java index 81be9933807..58def6da21e 100644 --- a/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/SetHomepageActionIT.java +++ b/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/SetHomepageActionIT.java @@ -33,7 +33,7 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.user.ws.SetHomepageAction.PARAM_COMPONENT; @@ -98,7 +98,7 @@ public class SetHomepageActionIT { @Test public void set_branch_homepage() { ComponentDto mainBranch = db.components().insertPublicProject().getMainBranchComponent(); - String branchName = randomAlphanumeric(248); + String branchName = secure().nextAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(mainBranch, b -> b.setKey(branchName)); UserDto user = db.users().insertUser(); userSession.logIn(user); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/ETagUtilsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/ETagUtilsTest.java index 6cc77b6217d..0e09285dac6 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/ETagUtilsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/ETagUtilsTest.java @@ -21,7 +21,7 @@ package org.sonar.server.badge.ws; import org.junit.Test; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; @@ -29,12 +29,12 @@ public class ETagUtilsTest { @Test public void getETag_should_start_with_W_SLASH() { - assertThat(ETagUtils.getETag(randomAlphanumeric(15))).startsWith("W/"); + assertThat(ETagUtils.getETag(secure().nextAlphanumeric(15))).startsWith("W/"); } @Test public void getETag_should_return_same_value_for_same_input() { - String input = randomAlphanumeric(200); + String input = secure().nextAlphanumeric(200); assertThat(ETagUtils.getETag(input)).isEqualTo(ETagUtils.getETag(input)); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/queue/BranchSupportTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/queue/BranchSupportTest.java index 4d58bed4faa..243f940431e 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/queue/BranchSupportTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/queue/BranchSupportTest.java @@ -33,8 +33,7 @@ import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.server.ce.queue.BranchSupport.ComponentKey; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; @@ -52,7 +51,7 @@ public class BranchSupportTest { @Test public void createComponentKey_of_main_branch() { - String projectKey = randomAlphanumeric(12); + String projectKey = secure().nextAlphanumeric(12); ComponentKey componentKey = underTestNoBranch.createComponentKey(projectKey, NO_CHARACTERISTICS); @@ -65,7 +64,7 @@ public class BranchSupportTest { @Test public void createComponentKey_whenCharacteristicsIsRandom_returnsComponentKey() { - String projectKey = randomAlphanumeric(12); + String projectKey = secure().nextAlphanumeric(12); Map nonEmptyMap = newRandomNonEmptyMap(); ComponentKey componentKey = underTestWithBranch.createComponentKey(projectKey, nonEmptyMap); @@ -79,7 +78,7 @@ public class BranchSupportTest { @Test public void createComponentKey_whenCharacteristicsIsBranchRelated_delegates() { - String projectKey = randomAlphanumeric(12); + String projectKey = secure().nextAlphanumeric(12); Map nonEmptyMap = Map.of(PULL_REQUEST, "PR-2"); ComponentKey expected = mock(ComponentKey.class); when(branchSupportDelegate.createComponentKey(projectKey, nonEmptyMap)).thenReturn(expected); @@ -120,7 +119,7 @@ public class BranchSupportTest { public static Object[][] nullOrNonEmpty() { return new Object[][] { {null}, - {randomAlphabetic(5)}, + {secure().nextAlphabetic(5)}, }; } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/NewComponentTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/NewComponentTest.java index 4553c0bc973..ab704771472 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/NewComponentTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/NewComponentTest.java @@ -23,7 +23,7 @@ import org.junit.Test; import org.sonar.server.common.component.NewComponent; import static com.google.common.base.Strings.repeat; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.resources.Qualifiers.PROJECT; @@ -136,7 +136,7 @@ public class NewComponentTest { public void isProject_shouldReturnFalse_whenQualifierIsNotProject() { NewComponent newComponent = underTest.setKey(KEY) .setName(NAME) - .setQualifier(randomAlphabetic(4)) + .setQualifier(secure().nextAlphabetic(4)) .build(); assertThat(newComponent.isProject()).isFalse(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/ComponentsWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/ComponentsWsTest.java index 2f5f926500e..ce74853a116 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/ComponentsWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/ComponentsWsTest.java @@ -24,13 +24,13 @@ import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.sonarqube.ws.client.component.ComponentsWsParameters.CONTROLLER_COMPONENTS; public class ComponentsWsTest { - private final String actionKey = randomAlphanumeric(10); + private final String actionKey = secure().nextAlphanumeric(10); private final ComponentsWsAction action = new ComponentsWsAction() { @Override diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/ClusterHealthTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/ClusterHealthTest.java index c750e0251cd..05d33c01828 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/ClusterHealthTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/ClusterHealthTest.java @@ -32,7 +32,7 @@ import org.sonar.process.cluster.health.NodeHealth; import static java.util.stream.Collectors.toSet; import static java.util.stream.Stream.concat; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder; @@ -120,7 +120,7 @@ public class ClusterHealthTest { private Health randomHealth() { Health.Builder healthBuilder = Health.builder(); healthBuilder.setStatus(Health.Status.values()[random.nextInt(Health.Status.values().length)]); - IntStream.range(0, random.nextInt(3)).mapToObj(i -> randomAlphanumeric(3)).forEach(healthBuilder::addCause); + IntStream.range(0, random.nextInt(3)).mapToObj(i -> secure().nextAlphanumeric(3)).forEach(healthBuilder::addCause); return healthBuilder.build(); } @@ -134,8 +134,8 @@ public class ClusterHealthTest { .setDetails( NodeDetails.newNodeDetailsBuilder() .setType(random.nextBoolean() ? NodeDetails.Type.SEARCH : NodeDetails.Type.APPLICATION) - .setName(randomAlphanumeric(3)) - .setHost(randomAlphanumeric(4)) + .setName(secure().nextAlphanumeric(3)) + .setHost(secure().nextAlphanumeric(4)) .setPort(1 + random.nextInt(344)) .setStartedAt(1 + random.nextInt(999)) .build()) @@ -153,7 +153,7 @@ public class ClusterHealthTest { return NodeDetails.newNodeDetailsBuilder() .setType(NodeDetails.Type.APPLICATION) .setName(nodeName) - .setHost(randomAlphanumeric(4)) + .setHost(secure().nextAlphanumeric(4)) .setPort(3000) .setStartedAt(1_000L) .build(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthCheckerImplTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthCheckerImplTest.java index 395f083273a..edbd4a67eb6 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthCheckerImplTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthCheckerImplTest.java @@ -36,7 +36,7 @@ import org.sonar.server.common.health.ClusterHealthCheck; import org.sonar.server.common.health.NodeHealthCheck; import org.sonar.server.platform.NodeInformation; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.same; @@ -106,7 +106,7 @@ public class HealthCheckerImplTest { @Test public void checkNode_returns_causes_of_all_NodeHealthCheck_whichever_their_status() { NodeHealthCheck[] nodeHealthChecks = IntStream.range(0, 1 + random.nextInt(20)) - .mapToObj(s -> new HardcodedHealthNodeCheck(IntStream.range(0, random.nextInt(3)).mapToObj(i -> randomAlphanumeric(3)).toArray(String[]::new))) + .mapToObj(s -> new HardcodedHealthNodeCheck(IntStream.range(0, random.nextInt(3)).mapToObj(i -> secure().nextAlphanumeric(3)).toArray(String[]::new))) .map(NodeHealthCheck.class::cast) .toArray(NodeHealthCheck[]::new); String[] expected = Arrays.stream(nodeHealthChecks).map(NodeHealthCheck::check).flatMap(s -> s.getCauses().stream()).toArray(String[]::new); @@ -192,7 +192,7 @@ public class HealthCheckerImplTest { public void checkCluster_returns_causes_of_all_ClusterHealthChecks_whichever_their_status() { when(nodeInformation.isStandalone()).thenReturn(false); List causesGroups = IntStream.range(0, 1 + random.nextInt(20)) - .mapToObj(s -> IntStream.range(0, random.nextInt(3)).mapToObj(i -> randomAlphanumeric(3)).toArray(String[]::new)) + .mapToObj(s -> IntStream.range(0, random.nextInt(3)).mapToObj(i -> secure().nextAlphanumeric(3)).toArray(String[]::new)) .toList(); ClusterHealthCheck[] clusterHealthChecks = causesGroups.stream() .map(HardcodedHealthClusterCheck::new) @@ -242,8 +242,8 @@ public class HealthCheckerImplTest { .setStatus(NodeHealth.Status.values()[random.nextInt(NodeHealth.Status.values().length)]) .setDetails(newNodeDetailsBuilder() .setType(random.nextBoolean() ? NodeDetails.Type.APPLICATION : NodeDetails.Type.SEARCH) - .setName(randomAlphanumeric(10)) - .setHost(randomAlphanumeric(5)) + .setName(secure().nextAlphanumeric(10)) + .setHost(secure().nextAlphanumeric(5)) .setPort(1 + random.nextInt(333)) .setStartedAt(1 + random.nextInt(444)) .build()) diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthTest.java index 5660068d49a..9417a15e888 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthTest.java @@ -27,7 +27,7 @@ import java.util.stream.IntStream; import org.assertj.core.api.AbstractCharSequenceAssert; import org.junit.Test; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.ThrowableAssert.ThrowingCallable; @@ -36,7 +36,7 @@ public class HealthTest { private final Random random = new Random(); private final Health.Status anyStatus = Health.Status.values()[random.nextInt(Health.Status.values().length)]; - private final Set randomCauses = IntStream.range(0, random.nextInt(5)).mapToObj(s -> randomAlphanumeric(3)).collect(Collectors.toSet()); + private final Set randomCauses = IntStream.range(0, random.nextInt(5)).mapToObj(s -> secure().nextAlphanumeric(3)).collect(Collectors.toSet()); @Test public void build_throws_NPE_if_status_is_null() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/NodeHealthModuleTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/NodeHealthModuleTest.java index 2b772c675ae..ae7fb3b6c5c 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/NodeHealthModuleTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/NodeHealthModuleTest.java @@ -32,7 +32,7 @@ import org.sonar.process.cluster.health.SharedHealthStateImpl; import org.sonar.process.cluster.hz.HazelcastMember; import static java.lang.String.valueOf; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -48,10 +48,10 @@ public class NodeHealthModuleTest { Server server = mock(Server.class); NetworkUtils networkUtils = mock(NetworkUtils.class); // settings required by NodeHealthProvider - mapSettings.setProperty("sonar.cluster.node.name", randomAlphanumeric(3)); + mapSettings.setProperty("sonar.cluster.node.name", secure().nextAlphanumeric(3)); mapSettings.setProperty("sonar.cluster.node.port", valueOf(1 + random.nextInt(10))); when(server.getStartedAt()).thenReturn(new Date()); - when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(12)); + when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(12)); // upper level dependencies container.add( mock(System2.class), diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/NodeHealthProviderImplTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/NodeHealthProviderImplTest.java index eba8e68eb37..c3e384d14b8 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/NodeHealthProviderImplTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/NodeHealthProviderImplTest.java @@ -30,8 +30,7 @@ import org.sonar.process.NetworkUtils; import org.sonar.process.cluster.health.NodeDetails; import org.sonar.process.cluster.health.NodeHealth; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; @@ -57,7 +56,7 @@ public class NodeHealthProviderImplTest { @Test public void constructor_thows_NPE_if_NetworkUtils_getHostname_returns_null() { - mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); + mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(3)); assertThatThrownBy(() -> new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils)) .isInstanceOf(NullPointerException.class); @@ -65,8 +64,8 @@ public class NodeHealthProviderImplTest { @Test public void constructor_throws_ISE_if_node_port_property_is_not_set() { - mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); - when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(23)); + mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(3)); + when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(23)); assertThatThrownBy(() -> new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils)) .isInstanceOf(IllegalStateException.class) @@ -85,9 +84,9 @@ public class NodeHealthProviderImplTest { public void get_returns_HEALTH_status_and_causes_from_HealthChecker_checkNode() { setRequiredPropertiesForConstructor(); setStartedAt(); - when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(4)); + when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(4)); Health.Status randomStatus = Health.Status.values()[random.nextInt(Health.Status.values().length)]; - String[] expected = IntStream.range(0, random.nextInt(4)).mapToObj(s -> randomAlphabetic(55)).toArray(String[]::new); + String[] expected = IntStream.range(0, random.nextInt(4)).mapToObj(s -> secure().nextAlphabetic(55)).toArray(String[]::new); Health.Builder healthBuilder = Health.builder() .setStatus(randomStatus); Arrays.stream(expected).forEach(healthBuilder::addCause); @@ -104,7 +103,7 @@ public class NodeHealthProviderImplTest { public void get_returns_APPLICATION_type() { setRequiredPropertiesForConstructor(); setStartedAt(); - when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(23)); + when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(23)); when(healthChecker.checkNode()).thenReturn(Health.builder() .setStatus(Health.Status.values()[random.nextInt(Health.Status.values().length)]) .build()); @@ -117,7 +116,7 @@ public class NodeHealthProviderImplTest { @Test public void get_returns_name_and_port_from_properties_at_constructor_time() { - String name = randomAlphanumeric(3); + String name = secure().nextAlphanumeric(3); int port = 1 + random.nextInt(4); mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), name); mapSettings.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), port); @@ -125,7 +124,7 @@ public class NodeHealthProviderImplTest { when(healthChecker.checkNode()).thenReturn(Health.builder() .setStatus(Health.Status.values()[random.nextInt(Health.Status.values().length)]) .build()); - when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(3)); + when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(3)); NodeHealthProviderImpl underTest = new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils); NodeHealth nodeHealth = underTest.get(); @@ -144,8 +143,8 @@ public class NodeHealthProviderImplTest { @Test public void get_returns_host_from_property_if_set_at_constructor_time() { - String host = randomAlphanumeric(4); - mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); + String host = secure().nextAlphanumeric(4); + mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(3)); mapSettings.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), 1 + random.nextInt(4)); mapSettings.setProperty(CLUSTER_NODE_HOST.getKey(), host); setStartedAt(); @@ -159,7 +158,7 @@ public class NodeHealthProviderImplTest { assertThat(nodeHealth.getDetails().getHost()).isEqualTo(host); // change values in properties - mapSettings.setProperty(CLUSTER_NODE_HOST.getKey(), randomAlphanumeric(66)); + mapSettings.setProperty(CLUSTER_NODE_HOST.getKey(), secure().nextAlphanumeric(66)); NodeHealth newNodeHealth = underTest.get(); @@ -177,7 +176,7 @@ public class NodeHealthProviderImplTest { } private void getReturnsHostnameFromNetworkUtils(String hostPropertyValue) { - String host = randomAlphanumeric(3); + String host = secure().nextAlphanumeric(3); setRequiredPropertiesForConstructor(); if (hostPropertyValue != null) { mapSettings.setProperty(CLUSTER_NODE_HOST.getKey(), hostPropertyValue); @@ -194,7 +193,7 @@ public class NodeHealthProviderImplTest { assertThat(nodeHealth.getDetails().getHost()).isEqualTo(host); // change hostname - when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(4)); + when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(4)); NodeHealth newNodeHealth = underTest.get(); @@ -204,7 +203,7 @@ public class NodeHealthProviderImplTest { @Test public void get_returns_started_from_server_startedAt_at_constructor_time() { setRequiredPropertiesForConstructor(); - when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(4)); + when(networkUtils.getHostname()).thenReturn(secure().nextAlphanumeric(4)); Date date = new Date(); when(server.getStartedAt()).thenReturn(date); when(healthChecker.checkNode()).thenReturn(Health.builder() @@ -229,7 +228,7 @@ public class NodeHealthProviderImplTest { } private void setRequiredPropertiesForConstructor() { - mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); + mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), secure().nextAlphanumeric(3)); mapSettings.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), 1 + random.nextInt(4)); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/hotspot/ws/HotspotsWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/hotspot/ws/HotspotsWsTest.java index 91b7e70abeb..4df7445326d 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/hotspot/ws/HotspotsWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/hotspot/ws/HotspotsWsTest.java @@ -27,7 +27,7 @@ import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; public class HotspotsWsTest { @@ -35,7 +35,7 @@ public class HotspotsWsTest { @Test public void define_controller() { String[] actionKeys = IntStream.range(0, 1 + new Random().nextInt(12)) - .mapToObj(i -> i + randomAlphanumeric(10)) + .mapToObj(i -> i + secure().nextAlphanumeric(10)) .toArray(String[]::new); HotspotsWsAction[] actions = Arrays.stream(actionKeys) .map(actionKey -> new HotspotsWsAction() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchResponseFormatFormatOperationTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchResponseFormatFormatOperationTest.java index 422f1d870b3..a9c02e9ca39 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchResponseFormatFormatOperationTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchResponseFormatFormatOperationTest.java @@ -51,7 +51,7 @@ import org.sonarqube.ws.Issues.Operation; import static java.lang.System.currentTimeMillis; import static java.util.stream.Collectors.toList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.ArgumentMatchers.any; @@ -173,15 +173,15 @@ class SearchResponseFormatFormatOperationTest { private static IssueDto createIssue() { RuleDto ruleDto = newRule(); - String projectUuid = "project_uuid_" + randomAlphanumeric(5); + String projectUuid = "project_uuid_" + secure().nextAlphanumeric(5); ComponentDto projectDto = newPrivateProjectDto(); projectDto.setBranchUuid(projectUuid); - return newIssue(ruleDto, projectUuid, "project_key_" + randomAlphanumeric(5), projectDto); + return newIssue(ruleDto, projectUuid, "project_key_" + secure().nextAlphanumeric(5), projectDto); } @Test void formatOperation_should_add_branch_on_issue() { - String branchName = randomAlphanumeric(5); + String branchName = secure().nextAlphanumeric(5); searchResponseData = newSearchResponseDataBranch(branchName); Operation result = searchResponseFormat.formatOperation(searchResponseData, true); assertThat(result.getIssue().getBranch()).isEqualTo(branchName); @@ -206,8 +206,8 @@ class SearchResponseFormatFormatOperationTest { @Test void formatOperation_should_add_external_rule_engine_on_issue() { issueDto.setExternal(true); - String expected = randomAlphanumeric(5); - issueDto.setRuleKey(EXTERNAL_RULE_REPO_PREFIX + expected, randomAlphanumeric(5)); + String expected = secure().nextAlphanumeric(5); + issueDto.setRuleKey(EXTERNAL_RULE_REPO_PREFIX + expected, secure().nextAlphanumeric(5)); Operation result = searchResponseFormat.formatOperation(searchResponseData, true); @@ -237,7 +237,7 @@ class SearchResponseFormatFormatOperationTest { @Test void formatOperation_should_add_scope_main_on_issue_when_not_unit_test_file() { - componentDto.setQualifier(randomAlphanumeric(5)); + componentDto.setQualifier(secure().nextAlphanumeric(5)); Operation result = searchResponseFormat.formatOperation(searchResponseData, true); @@ -326,9 +326,9 @@ class SearchResponseFormatFormatOperationTest { issueDto = newIssue(ruleDto, component.branchUuid(), component.getKey(), component) .setType(CODE_SMELL) .setCleanCodeAttribute(CleanCodeAttribute.CLEAR) - .setRuleDescriptionContextKey("context_key_" + randomAlphanumeric(5)) + .setRuleDescriptionContextKey("context_key_" + secure().nextAlphanumeric(5)) .setAssigneeUuid(userDto.getUuid()) - .setResolution("resolution_" + randomAlphanumeric(5)) + .setResolution("resolution_" + secure().nextAlphanumeric(5)) .setIssueCreationDate(new Date(currentTimeMillis() - 2_000)) .setIssueUpdateDate(new Date(currentTimeMillis() - 1_000)) .setIssueCloseDate(new Date(currentTimeMillis())); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/NewCodePeriodsWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/NewCodePeriodsWsTest.java index 58ff9a327b4..69e5c3b1e7c 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/NewCodePeriodsWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/NewCodePeriodsWsTest.java @@ -25,12 +25,12 @@ import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.core.documentation.DocumentationLinkGenerator; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class NewCodePeriodsWsTest { - private String actionKey = randomAlphanumeric(10); + private String actionKey = secure().nextAlphanumeric(10); private DocumentationLinkGenerator documentationLinkGenerator = mock(DocumentationLinkGenerator.class); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/HealthActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/HealthActionTest.java index 08837be6532..f085045ffd3 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/HealthActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/HealthActionTest.java @@ -48,8 +48,7 @@ import org.sonarqube.ws.System; import static java.util.Collections.emptySet; import static java.util.Collections.singleton; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.ThrowableAssert.ThrowingCallable; @@ -180,7 +179,7 @@ public class HealthActionTest { Health.Status randomStatus = Health.Status.values()[new Random().nextInt(Health.Status.values().length)]; Health.Builder builder = Health.builder() .setStatus(randomStatus); - IntStream.range(0, new Random().nextInt(5)).mapToObj(i -> RandomStringUtils.randomAlphanumeric(3)).forEach(builder::addCause); + IntStream.range(0, new Random().nextInt(5)).mapToObj(i -> RandomStringUtils.secure().nextAlphanumeric(3)).forEach(builder::addCause); Health health = builder.build(); when(healthChecker.checkNode()).thenReturn(health); when(nodeInformation.isStandalone()).thenReturn(true); @@ -195,7 +194,7 @@ public class HealthActionTest { public void response_contains_status_and_causes_from_HealthChecker_checkCluster_when_standalone() { authenticateWithRandomMethod(); Health.Status randomStatus = Health.Status.values()[random.nextInt(Health.Status.values().length)]; - String[] causes = IntStream.range(0, random.nextInt(33)).mapToObj(i -> randomAlphanumeric(4)).toArray(String[]::new); + String[] causes = IntStream.range(0, random.nextInt(33)).mapToObj(i -> secure().nextAlphanumeric(4)).toArray(String[]::new); Health.Builder healthBuilder = Health.builder() .setStatus(randomStatus); Arrays.stream(causes).forEach(healthBuilder::addCause); @@ -268,12 +267,12 @@ public class HealthActionTest { private NodeHealth randomNodeHealth() { NodeHealth.Builder builder = newNodeHealthBuilder() .setStatus(NodeHealth.Status.values()[random.nextInt(NodeHealth.Status.values().length)]); - IntStream.range(0, random.nextInt(4)).mapToObj(i -> randomAlphabetic(5)).forEach(builder::addCause); + IntStream.range(0, random.nextInt(4)).mapToObj(i -> secure().nextAlphabetic(5)).forEach(builder::addCause); return builder.setDetails( newNodeDetailsBuilder() .setType(random.nextBoolean() ? NodeDetails.Type.APPLICATION : NodeDetails.Type.SEARCH) - .setName(randomAlphanumeric(3)) - .setHost(randomAlphanumeric(4)) + .setName(secure().nextAlphanumeric(3)) + .setHost(secure().nextAlphanumeric(4)) .setPort(1 + random.nextInt(3)) .setStartedAt(1 + random.nextInt(23)) .build()) @@ -283,7 +282,7 @@ public class HealthActionTest { private NodeHealth randomNodeHealth(NodeDetails.Type type, String name, String host, int port, long started) { NodeHealth.Builder builder = newNodeHealthBuilder() .setStatus(NodeHealth.Status.values()[random.nextInt(NodeHealth.Status.values().length)]); - IntStream.range(0, random.nextInt(4)).mapToObj(i -> randomAlphabetic(5)).forEach(builder::addCause); + IntStream.range(0, random.nextInt(4)).mapToObj(i -> secure().nextAlphabetic(5)).forEach(builder::addCause); return builder.setDetails( newNodeDetailsBuilder() .setType(type) diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SafeModeHealthActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SafeModeHealthActionTest.java index c4d3aca4363..63645093980 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SafeModeHealthActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SafeModeHealthActionTest.java @@ -35,7 +35,7 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.System; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; @@ -105,7 +105,7 @@ public class SafeModeHealthActionTest { Health.Status randomStatus = Health.Status.values()[new Random().nextInt(Health.Status.values().length)]; Health.Builder builder = Health.builder() .setStatus(randomStatus); - IntStream.range(0, new Random().nextInt(5)).mapToObj(i -> RandomStringUtils.randomAlphanumeric(3)).forEach(builder::addCause); + IntStream.range(0, new Random().nextInt(5)).mapToObj(i -> RandomStringUtils.secure().nextAlphanumeric(3)).forEach(builder::addCause); Health health = builder.build(); when(healthChecker.checkNode()).thenReturn(health); TestRequest request = underTest.newRequest(); @@ -119,7 +119,7 @@ public class SafeModeHealthActionTest { public void response_contains_status_and_causes_from_HealthChecker_checkCluster() { authenticateWithPasscode(); Health.Status randomStatus = Health.Status.values()[random.nextInt(Health.Status.values().length)]; - String[] causes = IntStream.range(0, random.nextInt(33)).mapToObj(i -> randomAlphanumeric(4)).toArray(String[]::new); + String[] causes = IntStream.range(0, random.nextInt(33)).mapToObj(i -> secure().nextAlphanumeric(4)).toArray(String[]::new); Health.Builder healthBuilder = Health.builder() .setStatus(randomStatus); Arrays.stream(causes).forEach(healthBuilder::addCause); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/builtin/BuiltInQPChangeNotificationTemplateTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/builtin/BuiltInQPChangeNotificationTemplateTest.java index ebc80eda297..825714b097c 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/builtin/BuiltInQPChangeNotificationTemplateTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/builtin/BuiltInQPChangeNotificationTemplateTest.java @@ -26,7 +26,7 @@ import org.sonar.api.platform.Server; import org.sonar.server.issue.notification.EmailMessage; import org.sonar.server.qualityprofile.builtin.BuiltInQPChangeNotificationBuilder.Profile; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -40,7 +40,7 @@ public class BuiltInQPChangeNotificationTemplateTest { @Before public void setUp() { - when(server.getPublicRootUrl()).thenReturn("http://" + randomAlphanumeric(10)); + when(server.getPublicRootUrl()).thenReturn("http://" + secure().nextAlphanumeric(10)); } @Test @@ -164,12 +164,12 @@ public class BuiltInQPChangeNotificationTemplateTest { @Test public void notification_contains_many_profiles() { - String profileName1 = "profile1_" + randomAlphanumeric(20); - String languageKey1 = "langkey1_" + randomAlphanumeric(20); - String languageName1 = "langName1_" + randomAlphanumeric(20); - String profileName2 = "profile2_" + randomAlphanumeric(20); - String languageKey2 = "langkey2_" + randomAlphanumeric(20); - String languageName2 = "langName2_" + randomAlphanumeric(20); + String profileName1 = "profile1_" + secure().nextAlphanumeric(20); + String languageKey1 = "langkey1_" + secure().nextAlphanumeric(20); + String languageName1 = "langName1_" + secure().nextAlphanumeric(20); + String profileName2 = "profile2_" + secure().nextAlphanumeric(20); + String languageKey2 = "langkey2_" + secure().nextAlphanumeric(20); + String languageName2 = "langName2_" + secure().nextAlphanumeric(20); BuiltInQPChangeNotificationBuilder notification = new BuiltInQPChangeNotificationBuilder() .addProfile(Profile.newBuilder() .setProfileName(profileName1) @@ -196,13 +196,13 @@ public class BuiltInQPChangeNotificationTemplateTest { @Test public void notification_contains_profiles_sorted_by_language_then_by_profile_name() { - String languageKey1 = "langkey1_" + randomAlphanumeric(20); - String languageName1 = "langName1_" + randomAlphanumeric(20); - String languageKey2 = "langKey2_" + randomAlphanumeric(20); - String languageName2 = "langName2_" + randomAlphanumeric(20); - String profileName1 = "profile1_" + randomAlphanumeric(20); - String profileName2 = "profile2_" + randomAlphanumeric(20); - String profileName3 = "profile3_" + randomAlphanumeric(20); + String languageKey1 = "langkey1_" + secure().nextAlphanumeric(20); + String languageName1 = "langName1_" + secure().nextAlphanumeric(20); + String languageKey2 = "langKey2_" + secure().nextAlphanumeric(20); + String languageName2 = "langName2_" + secure().nextAlphanumeric(20); + String profileName1 = "profile1_" + secure().nextAlphanumeric(20); + String profileName2 = "profile2_" + secure().nextAlphanumeric(20); + String profileName3 = "profile3_" + secure().nextAlphanumeric(20); BuiltInQPChangeNotificationBuilder notification = new BuiltInQPChangeNotificationBuilder() .addProfile(Profile.newBuilder().setProfileName(profileName3).setLanguageKey(languageKey2).setLanguageName(languageName2).build()) .addProfile(Profile.newBuilder().setProfileName(profileName2).setLanguageKey(languageKey1).setLanguageName(languageName1).build()) @@ -270,14 +270,14 @@ public class BuiltInQPChangeNotificationTemplateTest { } private static String newProfileName() { - return "profileName_" + randomAlphanumeric(20); + return "profileName_" + secure().nextAlphanumeric(20); } private static String newLanguageName() { - return "languageName_" + randomAlphanumeric(20); + return "languageName_" + secure().nextAlphanumeric(20); } private static String newLanguageKey() { - return "languageKey_" + randomAlphanumeric(20); + return "languageKey_" + secure().nextAlphanumeric(20); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/builtin/BuiltInQPChangeNotificationTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/builtin/BuiltInQPChangeNotificationTest.java index a117b35432f..df972889d2f 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/builtin/BuiltInQPChangeNotificationTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/builtin/BuiltInQPChangeNotificationTest.java @@ -24,7 +24,7 @@ import org.junit.Test; import org.sonar.api.notifications.Notification; import org.sonar.server.qualityprofile.builtin.BuiltInQPChangeNotificationBuilder.Profile; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; @@ -45,9 +45,9 @@ public class BuiltInQPChangeNotificationTest { @Test public void serialize_and_parse_single_profile() { - String profileName = randomAlphanumeric(20); - String languageKey = randomAlphanumeric(20); - String languageName = randomAlphanumeric(20); + String profileName = secure().nextAlphanumeric(20); + String languageKey = secure().nextAlphanumeric(20); + String languageName = secure().nextAlphanumeric(20); int newRules = RANDOM.nextInt(5000); int updatedRules = RANDOM.nextInt(5000); int removedRules = RANDOM.nextInt(5000); @@ -76,12 +76,12 @@ public class BuiltInQPChangeNotificationTest { @Test public void serialize_and_parse_multiple_profiles() { - String profileName1 = randomAlphanumeric(20); - String languageKey1 = randomAlphanumeric(20); - String languageName1 = randomAlphanumeric(20); - String profileName2 = randomAlphanumeric(20); - String languageKey2 = randomAlphanumeric(20); - String languageName2 = randomAlphanumeric(20); + String profileName1 = secure().nextAlphanumeric(20); + String languageKey1 = secure().nextAlphanumeric(20); + String languageName1 = secure().nextAlphanumeric(20); + String profileName2 = secure().nextAlphanumeric(20); + String languageKey2 = secure().nextAlphanumeric(20); + String languageName2 = secure().nextAlphanumeric(20); BuiltInQPChangeNotification notification = new BuiltInQPChangeNotificationBuilder() .addProfile(Profile.newBuilder() @@ -103,9 +103,9 @@ public class BuiltInQPChangeNotificationTest { @Test public void serialize_and_parse_max_values() { - String profileName = randomAlphanumeric(20); - String languageKey = randomAlphanumeric(20); - String languageName = randomAlphanumeric(20); + String profileName = secure().nextAlphanumeric(20); + String languageKey = secure().nextAlphanumeric(20); + String languageName = secure().nextAlphanumeric(20); int newRules = Integer.MAX_VALUE; int updatedRules = Integer.MAX_VALUE; int removedRules = Integer.MAX_VALUE; diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/builtin/BuiltInQualityProfilesUpdateListenerTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/builtin/BuiltInQualityProfilesUpdateListenerTest.java index 39bbce9ec89..ec04de8cec4 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/builtin/BuiltInQualityProfilesUpdateListenerTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/builtin/BuiltInQualityProfilesUpdateListenerTest.java @@ -36,7 +36,7 @@ import org.sonar.server.qualityprofile.ActiveRuleChange; import org.sonar.server.qualityprofile.builtin.BuiltInQPChangeNotificationBuilder.Profile; import static java.util.Arrays.asList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; @@ -175,7 +175,7 @@ public class BuiltInQualityProfilesUpdateListenerTest { } private static String randomLowerCaseText() { - return randomAlphanumeric(20).toLowerCase(); + return secure().nextAlphanumeric(20).toLowerCase(); } private void enableNotificationInGlobalSettings() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/UsersWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/UsersWsTest.java index 41296e7c148..bab65d42ece 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/UsersWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/UsersWsTest.java @@ -24,7 +24,7 @@ import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.server.ws.ServletFilterHandler; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; public class UsersWsTest { @@ -49,7 +49,7 @@ public class UsersWsTest { @Override public void define(WebService.NewController context) { - context.createAction(randomAlphanumeric(10)).setHandler(ServletFilterHandler.INSTANCE); + context.createAction(secure().nextAlphanumeric(10)).setHandler(ServletFilterHandler.INSTANCE); } } diff --git a/sonar-core/src/test/java/org/sonar/core/platform/ServerIdTest.java b/sonar-core/src/test/java/org/sonar/core/platform/ServerIdTest.java index 792687975de..f7f9466feb2 100644 --- a/sonar-core/src/test/java/org/sonar/core/platform/ServerIdTest.java +++ b/sonar-core/src/test/java/org/sonar/core/platform/ServerIdTest.java @@ -30,7 +30,7 @@ import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.apache.commons.lang3.StringUtils.repeat; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -82,12 +82,12 @@ public class ServerIdTest { @DataProvider public static Object[][] wrongFormatWithDatabaseId() { String onlySplitChar = repeat(SPLIT_CHARACTER + "", DATABASE_ID_LENGTH); - String startWithSplitChar = SPLIT_CHARACTER + randomAlphabetic(DATABASE_ID_LENGTH - 1); + String startWithSplitChar = SPLIT_CHARACTER + secure().nextAlphabetic(DATABASE_ID_LENGTH - 1); Stream databaseIds = Stream.of( OLD_UUID_FORMAT, - randomAlphabetic(NOT_UUID_DATASET_ID_LENGTH), - randomAlphabetic(UUID_DATASET_ID_LENGTH), + secure().nextAlphabetic(NOT_UUID_DATASET_ID_LENGTH), + secure().nextAlphabetic(UUID_DATASET_ID_LENGTH), repeat(SPLIT_CHARACTER + "", NOT_UUID_DATASET_ID_LENGTH), repeat(SPLIT_CHARACTER + "", UUID_DATASET_ID_LENGTH)); @@ -95,8 +95,8 @@ public class ServerIdTest { .flatMap(datasetId -> Stream.of( startWithSplitChar + SPLIT_CHARACTER + datasetId, onlySplitChar + SPLIT_CHARACTER + datasetId, - startWithSplitChar + randomAlphabetic(1) + datasetId, - onlySplitChar + randomAlphabetic(1) + datasetId)) + startWithSplitChar + secure().nextAlphabetic(1) + datasetId, + onlySplitChar + secure().nextAlphabetic(1) + datasetId)) .flatMap(serverId -> Stream.of( serverId, " " + serverId, @@ -132,9 +132,9 @@ public class ServerIdTest { public static Object[][] validOldFormatServerIds() { return new Object[][] { {OLD_UUID_FORMAT}, - {randomAlphabetic(NOT_UUID_DATASET_ID_LENGTH)}, + {secure().nextAlphabetic(NOT_UUID_DATASET_ID_LENGTH)}, {repeat(SPLIT_CHARACTER + "", NOT_UUID_DATASET_ID_LENGTH)}, - {randomAlphabetic(UUID_DATASET_ID_LENGTH)}, + {secure().nextAlphabetic(UUID_DATASET_ID_LENGTH)}, {repeat(SPLIT_CHARACTER + "", UUID_DATASET_ID_LENGTH)} }; } @@ -155,37 +155,37 @@ public class ServerIdTest { @DataProvider public static Object[][] validServerIdWithDatabaseId() { return new Object[][] { - {randomAlphabetic(DATABASE_ID_LENGTH), randomAlphabetic(NOT_UUID_DATASET_ID_LENGTH)}, - {randomAlphabetic(DATABASE_ID_LENGTH), randomAlphabetic(UUID_DATASET_ID_LENGTH)}, - {randomAlphabetic(DATABASE_ID_LENGTH), repeat(SPLIT_CHARACTER + "", NOT_UUID_DATASET_ID_LENGTH)}, - {randomAlphabetic(DATABASE_ID_LENGTH), repeat(SPLIT_CHARACTER + "", UUID_DATASET_ID_LENGTH)}, - {randomAlphabetic(DATABASE_ID_LENGTH), OLD_UUID_FORMAT}, + {secure().nextAlphabetic(DATABASE_ID_LENGTH), secure().nextAlphabetic(NOT_UUID_DATASET_ID_LENGTH)}, + {secure().nextAlphabetic(DATABASE_ID_LENGTH), secure().nextAlphabetic(UUID_DATASET_ID_LENGTH)}, + {secure().nextAlphabetic(DATABASE_ID_LENGTH), repeat(SPLIT_CHARACTER + "", NOT_UUID_DATASET_ID_LENGTH)}, + {secure().nextAlphabetic(DATABASE_ID_LENGTH), repeat(SPLIT_CHARACTER + "", UUID_DATASET_ID_LENGTH)}, + {secure().nextAlphabetic(DATABASE_ID_LENGTH), OLD_UUID_FORMAT}, }; } @Test public void parse_does_not_support_deprecated_server_id_with_database_id() { - assertThatThrownBy(() -> ServerId.parse(randomAlphabetic(DATABASE_ID_LENGTH) + SPLIT_CHARACTER + randomAlphabetic(DEPRECATED_SERVER_ID_LENGTH))) + assertThatThrownBy(() -> ServerId.parse(secure().nextAlphabetic(DATABASE_ID_LENGTH) + SPLIT_CHARACTER + secure().nextAlphabetic(DEPRECATED_SERVER_ID_LENGTH))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("serverId does not have a supported length"); } @Test public void of_throws_NPE_if_datasetId_is_null() { - assertThatThrownBy(() -> ServerId.of(randomAlphabetic(DATABASE_ID_LENGTH), null)) + assertThatThrownBy(() -> ServerId.of(secure().nextAlphabetic(DATABASE_ID_LENGTH), null)) .isInstanceOf(NullPointerException.class); } @Test public void of_throws_IAE_if_datasetId_is_empty() { - assertThatThrownBy(() -> ServerId.of(randomAlphabetic(DATABASE_ID_LENGTH), "")) + assertThatThrownBy(() -> ServerId.of(secure().nextAlphabetic(DATABASE_ID_LENGTH), "")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Illegal datasetId length (0)"); } @Test public void of_throws_IAE_if_databaseId_is_empty() { - assertThatThrownBy(() -> ServerId.of("", randomAlphabetic(UUID_DATASET_ID_LENGTH))) + assertThatThrownBy(() -> ServerId.of("", secure().nextAlphabetic(UUID_DATASET_ID_LENGTH))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Illegal databaseId length (0)"); } @@ -193,7 +193,7 @@ public class ServerIdTest { @Test @UseDataProvider("datasetIdSupportedLengths") public void of_accepts_null_databaseId(int datasetIdLength) { - String datasetId = randomAlphabetic(datasetIdLength); + String datasetId = secure().nextAlphabetic(datasetIdLength); ServerId serverId = ServerId.of(null, datasetId); assertThat(serverId.getDatabaseId()).isEmpty(); @@ -203,8 +203,8 @@ public class ServerIdTest { @Test @UseDataProvider("illegalDatabaseIdLengths") public void of_throws_IAE_if_databaseId_length_is_not_8(int illegalDatabaseIdLengths) { - String databaseId = randomAlphabetic(illegalDatabaseIdLengths); - String datasetId = randomAlphabetic(UUID_DATASET_ID_LENGTH); + String databaseId = secure().nextAlphabetic(illegalDatabaseIdLengths); + String datasetId = secure().nextAlphabetic(UUID_DATASET_ID_LENGTH); assertThatThrownBy(() -> ServerId.of(databaseId, datasetId)) .isInstanceOf(IllegalArgumentException.class) @@ -222,8 +222,8 @@ public class ServerIdTest { @Test @UseDataProvider("illegalDatasetIdLengths") public void of_throws_IAE_if_datasetId_length_is_not_8(int illegalDatasetIdLengths) { - String datasetId = randomAlphabetic(illegalDatasetIdLengths); - String databaseId = randomAlphabetic(DATABASE_ID_LENGTH); + String datasetId = secure().nextAlphabetic(illegalDatasetIdLengths); + String databaseId = secure().nextAlphabetic(DATABASE_ID_LENGTH); assertThatThrownBy(() -> ServerId.of(databaseId, datasetId)) .isInstanceOf(IllegalArgumentException.class) @@ -243,10 +243,10 @@ public class ServerIdTest { @Test @UseDataProvider("datasetIdSupportedLengths") public void equals_is_based_on_databaseId_and_datasetId(int datasetIdLength) { - String databaseId = randomAlphabetic(DATABASE_ID_LENGTH - 1) + 'a'; - String otherDatabaseId = randomAlphabetic(DATABASE_ID_LENGTH - 1) + 'b'; - String datasetId = randomAlphabetic(datasetIdLength - 1) + 'a'; - String otherDatasetId = randomAlphabetic(datasetIdLength - 1) + 'b'; + String databaseId = secure().nextAlphabetic(DATABASE_ID_LENGTH - 1) + 'a'; + String otherDatabaseId = secure().nextAlphabetic(DATABASE_ID_LENGTH - 1) + 'b'; + String datasetId = secure().nextAlphabetic(datasetIdLength - 1) + 'a'; + String otherDatasetId = secure().nextAlphabetic(datasetIdLength - 1) + 'b'; ServerId newServerId = ServerId.of(databaseId, datasetId); assertThat(newServerId) @@ -269,10 +269,10 @@ public class ServerIdTest { @Test @UseDataProvider("datasetIdSupportedLengths") public void hashcode_is_based_on_databaseId_and_datasetId(int datasetIdLength) { - String databaseId = randomAlphabetic(DATABASE_ID_LENGTH - 1) + 'a'; - String otherDatabaseId = randomAlphabetic(DATABASE_ID_LENGTH - 1) + 'b'; - String datasetId = randomAlphabetic(datasetIdLength - 1) + 'a'; - String otherDatasetId = randomAlphabetic(datasetIdLength - 1) + 'b'; + String databaseId = secure().nextAlphabetic(DATABASE_ID_LENGTH - 1) + 'a'; + String otherDatabaseId = secure().nextAlphabetic(DATABASE_ID_LENGTH - 1) + 'b'; + String datasetId = secure().nextAlphabetic(datasetIdLength - 1) + 'a'; + String otherDatasetId = secure().nextAlphabetic(datasetIdLength - 1) + 'b'; ServerId newServerId = ServerId.of(databaseId, datasetId); assertThat(newServerId) diff --git a/sonar-plugin-api-impl/src/test/java/org/sonar/api/config/internal/MapSettingsTest.java b/sonar-plugin-api-impl/src/test/java/org/sonar/api/config/internal/MapSettingsTest.java index 590788fd9af..6af058de1c2 100644 --- a/sonar-plugin-api-impl/src/test/java/org/sonar/api/config/internal/MapSettingsTest.java +++ b/sonar-plugin-api-impl/src/test/java/org/sonar/api/config/internal/MapSettingsTest.java @@ -42,7 +42,7 @@ import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.System2; import static java.util.Collections.singletonList; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.ThrowableAssert.ThrowingCallable; @@ -79,14 +79,14 @@ public class MapSettingsTest { public void set_throws_NPE_if_key_is_null() { MapSettings underTest = new MapSettings(); - expectKeyNullNPE(() -> underTest.set(null, randomAlphanumeric(3))); + expectKeyNullNPE(() -> underTest.set(null, secure().nextAlphanumeric(3))); } @Test public void set_throws_NPE_if_value_is_null() { MapSettings underTest = new MapSettings(); - assertThatThrownBy(() -> underTest.set(randomAlphanumeric(3), null)) + assertThatThrownBy(() -> underTest.set(secure().nextAlphanumeric(3), null)) .isInstanceOf(NullPointerException.class) .hasMessage("value can't be null"); } @@ -95,7 +95,7 @@ public class MapSettingsTest { public void set_accepts_empty_value_and_trims_it() { MapSettings underTest = new MapSettings(); Random random = new Random(); - String key = randomAlphanumeric(3); + String key = secure().nextAlphanumeric(3); underTest.set(key, blank(random)); @@ -118,7 +118,7 @@ public class MapSettingsTest { @Test public void set_property_string_throws_NPE_if_key_is_null() { - String key = randomAlphanumeric(3); + String key = secure().nextAlphanumeric(3); Settings underTest = new MapSettings(new PropertyDefinitions(System2.INSTANCE, singletonList(PropertyDefinition.builder(key).multiValues(true).build()))); @@ -139,7 +139,7 @@ public class MapSettingsTest { Random random = new Random(); String blankBefore = blank(random); String blankAfter = blank(random); - String key = randomAlphanumeric(3); + String key = secure().nextAlphanumeric(3); setPropertyCaller.accept(underTest, blankBefore + key + blankAfter); @@ -148,7 +148,7 @@ public class MapSettingsTest { @Test public void set_property_string_array_trims_key() { - String key = randomAlphanumeric(3); + String key = secure().nextAlphanumeric(3); Settings underTest = new MapSettings(new PropertyDefinitions(System2.INSTANCE, singletonList(PropertyDefinition.builder(key).multiValues(true).build()))); @@ -188,8 +188,8 @@ public class MapSettingsTest { Random random = new Random(); String blankBefore = blank(random); String blankAfter = blank(random); - String key = randomAlphanumeric(3); - String value = randomAlphanumeric(3); + String key = secure().nextAlphanumeric(3); + String value = secure().nextAlphanumeric(3); underTest.setProperty(key, blankBefore + value + blankAfter); diff --git a/sonar-plugin-api-impl/src/test/java/org/sonar/api/config/internal/MultivaluePropertyTest.java b/sonar-plugin-api-impl/src/test/java/org/sonar/api/config/internal/MultivaluePropertyTest.java index 9e09ecd2031..1452e78d673 100644 --- a/sonar-plugin-api-impl/src/test/java/org/sonar/api/config/internal/MultivaluePropertyTest.java +++ b/sonar-plugin-api-impl/src/test/java/org/sonar/api/config/internal/MultivaluePropertyTest.java @@ -27,7 +27,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import static java.util.function.UnaryOperator.identity; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.config.internal.MultivalueProperty.parseAsCsv; @@ -114,9 +114,9 @@ public class MultivaluePropertyTest { @DataProvider public static Object[][] plains() { return new Object[][] { - {randomAlphanumeric(1)}, - {randomAlphanumeric(2)}, - {randomAlphanumeric(3 + new Random().nextInt(5))} + {secure().nextAlphanumeric(1)}, + {secure().nextAlphanumeric(2)}, + {secure().nextAlphanumeric(3 + new Random().nextInt(5))} }; } @@ -147,7 +147,7 @@ public class MultivaluePropertyTest { @Test public void trimAccordingToStringTrim() { - String str = randomAlphanumeric(4); + String str = secure().nextAlphanumeric(4); for (int i = 0; i <= ' '; i++) { String prefixed = (char) i + str; String suffixed = (char) i + str; @@ -166,11 +166,11 @@ public class MultivaluePropertyTest { String threePlusEmpty = randomTrimmedChars(3 + random.nextInt(5), random); String onePlusEmpty = randomTrimmedChars(1 + random.nextInt(5), random); - String plain = randomAlphanumeric(1); - String plainWithtrimmable = randomAlphanumeric(2) + onePlusEmpty + randomAlphanumeric(3); - String quotedWithSeparator = '"' + randomAlphanumeric(3) + ',' + randomAlphanumeric(2) + '"'; - String quotedWithDoubleSeparator = '"' + randomAlphanumeric(3) + ",," + randomAlphanumeric(2) + '"'; - String quotedWithtrimmable = '"' + randomAlphanumeric(3) + onePlusEmpty + randomAlphanumeric(2) + '"'; + String plain = secure().nextAlphanumeric(1); + String plainWithtrimmable = secure().nextAlphanumeric(2) + onePlusEmpty + secure().nextAlphanumeric(3); + String quotedWithSeparator = '"' + secure().nextAlphanumeric(3) + ',' + secure().nextAlphanumeric(2) + '"'; + String quotedWithDoubleSeparator = '"' + secure().nextAlphanumeric(3) + ",," + secure().nextAlphanumeric(2) + '"'; + String quotedWithtrimmable = '"' + secure().nextAlphanumeric(3) + onePlusEmpty + secure().nextAlphanumeric(2) + '"'; String[] empties = {oneEmpty, twoEmpty, threePlusEmpty}; String[] strings = {plain, plainWithtrimmable, diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/ProjectInfoTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/ProjectInfoTest.java index 943a40144c0..b27bfdd4423 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/ProjectInfoTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/ProjectInfoTest.java @@ -34,7 +34,7 @@ import org.sonar.api.CoreProperties; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.MessageException; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; @@ -79,7 +79,7 @@ class ProjectInfoTest { @Test void fail_with_too_long_version() { - String version = randomAlphabetic(101); + String version = secure().nextAlphabetic(101); settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01"); settings.setProperty(CoreProperties.PROJECT_VERSION_PROPERTY, version); @@ -91,7 +91,7 @@ class ProjectInfoTest { @Test void fail_with_too_long_buildString() { - String buildString = randomAlphabetic(101); + String buildString = secure().nextAlphabetic(101); settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01"); settings.setProperty(CoreProperties.BUILD_STRING_PROPERTY, buildString); @@ -114,7 +114,7 @@ class ProjectInfoTest { @Test void getProjectVersion_contains_value_of_property() { - String value = RandomStringUtils.randomAlphabetic(10); + String value = RandomStringUtils.secure().nextAlphabetic(10); settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01"); settings.setProperty(CoreProperties.PROJECT_VERSION_PROPERTY, value); @@ -136,7 +136,7 @@ class ProjectInfoTest { @Test void getBuildString_contains_value_of_property() { - String value = RandomStringUtils.randomAlphabetic(10); + String value = RandomStringUtils.secure().nextAlphabetic(10); settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01"); settings.setProperty(CoreProperties.BUILD_STRING_PROPERTY, value); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/externalissue/ExternalIssueImporterTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/externalissue/ExternalIssueImporterTest.java index e8ff234901d..1daf50a155c 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/externalissue/ExternalIssueImporterTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/externalissue/ExternalIssueImporterTest.java @@ -43,7 +43,7 @@ import org.sonar.api.testfixtures.log.LogTester; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.issue.impact.Severity.BLOCKER; @@ -102,7 +102,7 @@ public class ExternalIssueImporterTest { ExternalIssueReport.Issue input = new ExternalIssueReport.Issue(); input.primaryLocation = new ExternalIssueReport.Location(); input.primaryLocation.filePath = sourceFile.getProjectRelativePath(); - input.primaryLocation.message = randomAlphabetic(5); + input.primaryLocation.message = secure().nextAlphabetic(5); runOn(input); @@ -254,7 +254,7 @@ public class ExternalIssueImporterTest { input.type = "BUG"; input.primaryLocation = new ExternalIssueReport.Location(); input.primaryLocation.filePath = sourceFile.getProjectRelativePath(); - input.primaryLocation.message = randomAlphabetic(5); + input.primaryLocation.message = secure().nextAlphabetic(5); report.issues = new ExternalIssueReport.Issue[]{input}; ExternalIssueImporter underTest = new ExternalIssueImporter(this.context, report); @@ -381,14 +381,14 @@ public class ExternalIssueImporterTest { private ExternalIssueReport.Issue newIssue(@Nullable ExternalIssueReport.TextRange textRange) { ExternalIssueReport.Issue input = new ExternalIssueReport.Issue(); - input.engineId = randomAlphabetic(5); - input.ruleId = randomAlphabetic(5); + input.engineId = secure().nextAlphabetic(5); + input.ruleId = secure().nextAlphabetic(5); input.severity = "CRITICAL"; input.type = "BUG"; input.effortMinutes = random.nextInt(Integer.MAX_VALUE); input.primaryLocation = new ExternalIssueReport.Location(); input.primaryLocation.filePath = sourceFile.getProjectRelativePath(); - input.primaryLocation.message = randomAlphabetic(5); + input.primaryLocation.message = secure().nextAlphabetic(5); input.primaryLocation.textRange = textRange; return input; } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/MetadataPublisherTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/MetadataPublisherTest.java index 91607834d0d..129a3c79450 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/MetadataPublisherTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/report/MetadataPublisherTest.java @@ -60,7 +60,7 @@ import org.sonar.scanner.scm.ScmConfiguration; import org.sonar.scanner.scm.ScmRevision; import static java.util.Collections.emptyMap; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import static org.mockito.ArgumentMatchers.any; @@ -179,7 +179,7 @@ public class MetadataPublisherTest { @DataProvider public static Object[][] projectVersions() { - String version = randomAlphabetic(15); + String version = secure().nextAlphabetic(15); return new Object[][] { {null, ""}, {"", ""}, @@ -201,7 +201,7 @@ public class MetadataPublisherTest { @DataProvider public static Object[][] buildStrings() { - String randomBuildString = randomAlphabetic(15); + String randomBuildString = secure().nextAlphabetic(15); return new Object[][] { {null, ""}, {"", ""}, diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scm/git/ChangedFileTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scm/git/ChangedFileTest.java index 1bb25a29438..20ee5a69035 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scm/git/ChangedFileTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scm/git/ChangedFileTest.java @@ -27,7 +27,7 @@ import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.fs.internal.SensorStrategy; import static org.apache.commons.lang3.RandomStringUtils.random; -import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; +import static org.apache.commons.lang3.RandomStringUtils.secure; import static org.assertj.core.api.Assertions.assertThat; public class ChangedFileTest { @@ -87,7 +87,7 @@ public class ChangedFileTest { random(5), InputFile.Type.MAIN, random(5), - Integer.parseInt(randomNumeric(5)), + Integer.parseInt(secure().nextNumeric(5)), new SensorStrategy(), oldRelativePath); } diff --git a/sonar-ws/src/test/java/org/sonarqube/ws/client/HttpConnectorTest.java b/sonar-ws/src/test/java/org/sonarqube/ws/client/HttpConnectorTest.java index 981d0eb145d..411dd9b9bbc 100644 --- a/sonar-ws/src/test/java/org/sonarqube/ws/client/HttpConnectorTest.java +++ b/sonar-ws/src/test/java/org/sonarqube/ws/client/HttpConnectorTest.java @@ -251,7 +251,7 @@ public class HttpConnectorTest { @Test public void systemPassCode_sets_header_when_value_is_not_null() throws InterruptedException { answerHelloWorld(); - String systemPassCode = new Random().nextBoolean() ? "" : RandomStringUtils.randomAlphanumeric(21); + String systemPassCode = new Random().nextBoolean() ? "" : RandomStringUtils.secure().nextAlphanumeric(21); underTest = HttpConnector.newBuilder() .url(serverUrl) .systemPassCode(systemPassCode)