]> source.dussan.org Git - sonar-scanner-cli.git/commitdiff
SCANCLI-150 Use Bearer authentication scheme when a token is provided
authorJulien HENRY <julien.henry@sonarsource.com>
Fri, 7 Jun 2024 12:27:40 +0000 (14:27 +0200)
committerJulien HENRY <julien.henry@sonarsource.com>
Fri, 7 Jun 2024 15:24:51 +0000 (17:24 +0200)
it/src/test/java/com/sonarsource/scanner/it/DistributionTest.java
it/src/test/java/com/sonarsource/scanner/it/MultimoduleTest.java
it/src/test/java/com/sonarsource/scanner/it/ScannerTest.java
it/src/test/java/com/sonarsource/scanner/it/ScannerTestCase.java
it/src/test/java/com/sonarsource/scanner/it/SonarScannerTestSuite.java
pom.xml

index 09458dd52b47c988b5b851d5fdb1602d9f3beeed..71192bba442ac5f01c8d2c88f98ee710117e73e5 100644 (file)
@@ -38,7 +38,7 @@ public class DistributionTest extends ScannerTestCase {
     String projectKey = "basedir-with-source";
 
     File projectDir = new File("projects/basedir-with-source");
-    SonarScanner build = newScanner(projectDir, "sonar.projectKey", projectKey)
+    SonarScanner build = newScannerWithAdminCredentials(projectDir, "sonar.projectKey", projectKey)
       .setEnvironmentVariable("JAVA_HOME", "nonexistent")
       .useNative();
     orchestrator.executeBuild(build, true);
@@ -56,7 +56,7 @@ public class DistributionTest extends ScannerTestCase {
     String projectKey = "basedir-with-source";
 
     File projectDir = new File("projects/basedir-with-source");
-    SonarScanner build = newScanner(projectDir, "sonar.projectKey", projectKey)
+    SonarScanner build = newScannerWithAdminCredentials(projectDir, "sonar.projectKey", projectKey)
       .setEnvironmentVariable("JAVA_HOME", "nonexistent");
     orchestrator.executeBuild(build, true);
   }
index 04f6ffc7a1380dfff17670b6b831b3c31923188d..66c338e02ab46c1045cd3ef0c2912e48fe58665d 100644 (file)
@@ -34,7 +34,7 @@ public class MultimoduleTest extends ScannerTestCase {
    */
   @Test
   public void test_simplest_with_props_on_root() {
-    SonarScanner build = newScanner(
+    SonarScanner build = newScannerWithAdminCredentials(
       new File("projects/multi-module/simplest/simplest-with-props-on-root"));
 
     orchestrator.executeBuild(build);
@@ -79,7 +79,7 @@ public class MultimoduleTest extends ScannerTestCase {
    */
   @Test
   public void test_simplest_with_props_on_each_module() {
-    SonarScanner build = newScanner(new File(
+    SonarScanner build = newScannerWithAdminCredentials(new File(
       "projects/multi-module/simplest/simplest-with-props-on-each-module"));
 
     orchestrator.executeBuild(build);
@@ -111,7 +111,7 @@ public class MultimoduleTest extends ScannerTestCase {
    */
   @Test
   public void test_deep_path_for_modules() {
-    SonarScanner build = newScanner(
+    SonarScanner build = newScannerWithAdminCredentials(
       new File("projects/multi-module/customization/deep-path-for-modules"));
 
     orchestrator.executeBuild(build);
@@ -140,7 +140,7 @@ public class MultimoduleTest extends ScannerTestCase {
    */
   @Test
   public void test_module_path_with_space() {
-    SonarScanner build = newScanner(
+    SonarScanner build = newScannerWithAdminCredentials(
       new File("projects/multi-module/customization/module-path-with-space"));
 
     orchestrator.executeBuild(build);
@@ -169,7 +169,7 @@ public class MultimoduleTest extends ScannerTestCase {
    */
   @Test
   public void test_overwriting_parent_properties() {
-    SonarScanner build = newScanner(new File(
+    SonarScanner build = newScannerWithAdminCredentials(new File(
       "projects/multi-module/customization/overwriting-parent-properties"));
 
     orchestrator.executeBuild(build);
@@ -206,7 +206,7 @@ public class MultimoduleTest extends ScannerTestCase {
    */
   @Test
   public void test_using_config_file_property() {
-    SonarScanner build = newScanner(
+    SonarScanner build = newScannerWithAdminCredentials(
       new File("projects/multi-module/advanced/using-config-file-prop"));
 
     orchestrator.executeBuild(build);
@@ -237,7 +237,7 @@ public class MultimoduleTest extends ScannerTestCase {
    */
   @Test
   public void should_fail_if_unexisting_base_dir() {
-    SonarScanner build = newScanner(
+    SonarScanner build = newScannerWithAdminCredentials(
       new File("projects/multi-module/failures/unexisting-base-dir"));
 
     BuildResult result = orchestrator.executeBuildQuietly(build);
@@ -254,7 +254,7 @@ public class MultimoduleTest extends ScannerTestCase {
    */
   @Test
   public void should_fail_if_unexisting_config_file() {
-    SonarScanner build = newScanner(
+    SonarScanner build = newScannerWithAdminCredentials(
       new File("projects/multi-module/failures/unexisting-config-file"));
 
     BuildResult result = orchestrator.executeBuildQuietly(build);
index d6b9bf7740fc7d23aeb57bca33eba424e916a0d4..6381951a1c535aba7ccdf9cc0301d1afde346fcb 100644 (file)
@@ -27,22 +27,41 @@ import java.io.IOException;
 import java.util.Map;
 import java.util.stream.Collectors;
 import org.apache.commons.lang.StringEscapeUtils;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.TemporaryFolder;
 import org.sonarqube.ws.Measures.Measure;
+import org.sonarqube.ws.client.usertokens.GenerateRequest;
+import org.sonarqube.ws.client.usertokens.RevokeRequest;
 
 import static java.lang.Integer.parseInt;
 import static org.assertj.core.api.Assertions.assertThat;
 
 public class ScannerTest extends ScannerTestCase {
 
+  public static final String TOKEN_NAME = "Integration Tests";
+  private static String analysisToken;
   @Rule
   public TemporaryFolder temp = new TemporaryFolder();
 
+  @BeforeClass
+  public static void generateToken() {
+    analysisToken = newAdminWsClient().userTokens()
+      .generate(new GenerateRequest().setName(TOKEN_NAME))
+      .getToken();
+  }
+
+  @AfterClass
+  public static void cleanup() throws Exception {
+    newAdminWsClient().userTokens()
+      .revoke(new RevokeRequest().setName(TOKEN_NAME));
+  }
+
   @Test
   public void basedir_contains_sources() {
-    SonarScanner build = newScanner(new File("projects/basedir-with-source"));
+    SonarScanner build = newScannerWithToken(new File("projects/basedir-with-source"), analysisToken);
     orchestrator.executeBuild(build);
 
     Map<String, Measure> projectMeasures = getMeasures(
@@ -56,7 +75,7 @@ public class ScannerTest extends ScannerTestCase {
    */
   @Test
   public void analyzers_can_spawn_processes() {
-    SonarScanner build = newScanner(new File("projects/simple-js"))
+    SonarScanner build = newScannerWithToken(new File("projects/simple-js"), analysisToken)
       .useNative()
       .setProjectKey("SAMPLE");
     orchestrator.executeBuild(build);
@@ -70,7 +89,7 @@ public class ScannerTest extends ScannerTestCase {
    */
   @Test
   public void should_support_simple_project_keys() {
-    SonarScanner build = newScanner(new File("projects/simple-sample"))
+    SonarScanner build = newScannerWithToken(new File("projects/simple-sample"), analysisToken)
       .setProjectKey("SAMPLE");
     orchestrator.executeBuild(build);
 
@@ -94,7 +113,7 @@ public class ScannerTest extends ScannerTestCase {
    */
   @Test
   public void should_override_working_dir_with_relative_path() {
-    SonarScanner build = newScanner(new File("projects/override-working-dir"))
+    SonarScanner build = newScannerWithToken(new File("projects/override-working-dir"), analysisToken)
       .setProperty("sonar.working.directory", ".overridden-relative-sonar");
     orchestrator.executeBuild(build);
 
@@ -110,7 +129,7 @@ public class ScannerTest extends ScannerTestCase {
   @Test
   public void should_override_working_dir_with_absolute_path() {
     File projectHome = new File("projects/override-working-dir");
-    SonarScanner build = newScanner(projectHome)
+    SonarScanner build = newScannerWithToken(projectHome, analysisToken)
       .setProperty("sonar.working.directory",
         new File(projectHome, ".overridden-absolute-sonar").getAbsolutePath());
     orchestrator.executeBuild(build);
@@ -126,7 +145,7 @@ public class ScannerTest extends ScannerTestCase {
    */
   @Test
   public void should_fail_if_source_dir_does_not_exist() {
-    SonarScanner build = newScanner(new File("projects/bad-source-dirs"));
+    SonarScanner build = newScannerWithToken(new File("projects/bad-source-dirs"), analysisToken);
 
     BuildResult result = orchestrator.executeBuildQuietly(build);
     assertThat(result.getStatus()).isNotZero();
@@ -142,7 +161,7 @@ public class ScannerTest extends ScannerTestCase {
   public void should_enable_verbose() {
     // this line should appear in all versions (LTS-DEV) in debug only
     String expectedLog = "Available languages:";
-    SonarScanner build = newScanner(new File("projects/simple-sample"))
+    SonarScanner build = newScannerWithToken(new File("projects/simple-sample"), analysisToken)
       .setProperty("sonar.verbose", "true");
     String logs = orchestrator.executeBuild(build).getLogs();
     assertThat(logs).contains(expectedLog);
@@ -150,8 +169,8 @@ public class ScannerTest extends ScannerTestCase {
 
   @Test
   public void should_use_json_environment_props() {
-    SonarScanner build = newScanner(
-      new File("projects/simple-sample-no-properties"))
+    SonarScanner build = newScannerWithToken(
+      new File("projects/simple-sample-no-properties"), analysisToken)
       .setEnvironmentVariable("SONARQUBE_SCANNER_PARAMS", "{"
         + "\"sonar.projectKey\" : \"sample\"," +
         "\"sonar.projectName\" : \"Sample, with comma\"," +
@@ -163,7 +182,7 @@ public class ScannerTest extends ScannerTestCase {
 
   @Test
   public void should_use_environment_prop() {
-    SonarScanner build = newScanner(new File("projects/simple-sample"))
+    SonarScanner build = newScannerWithToken(new File("projects/simple-sample"), analysisToken)
       .setEnvironmentVariable("SONAR_HOST_URL", "http://www.google.com/404");
 
     BuildRunner runner = new BuildRunner(orchestrator.getConfiguration());
@@ -176,7 +195,7 @@ public class ScannerTest extends ScannerTestCase {
 
   @Test
   public void should_skip_analysis() {
-    SonarScanner build = newScanner(new File("projects/simple-sample"))
+    SonarScanner build = newScannerWithToken(new File("projects/simple-sample"), analysisToken)
       .setProperty("sonar.host.url", "http://foo")
       .setEnvironmentVariable("SONARQUBE_SCANNER_PARAMS",
         "{ \"sonar.scanner.skip\":\"true\" }");
@@ -187,7 +206,7 @@ public class ScannerTest extends ScannerTestCase {
 
   @Test
   public void should_fail_if_unable_to_connect() {
-    SonarScanner build = newScanner(new File("projects/simple-sample"))
+    SonarScanner build = newScannerWithToken(new File("projects/simple-sample"), analysisToken)
       //env property should be overridden
       .setEnvironmentVariable("SONAR_HOST_URL", "http://www.google.com")
       .setProperty("sonar.host.url", "http://www.google.com/404");
@@ -204,7 +223,7 @@ public class ScannerTest extends ScannerTestCase {
   @Test
   public void run_from_external_location() throws IOException {
     File tempDir = temp.newFolder();
-    SonarScanner build = newScanner(tempDir)
+    SonarScanner build = newScannerWithToken(tempDir, analysisToken)
       .setProperty("sonar.projectBaseDir",
         new File("projects/simple-sample").getAbsolutePath())
       .addArguments("-e");
@@ -221,7 +240,7 @@ public class ScannerTest extends ScannerTestCase {
 
   @Test
   public void verify_scanner_opts_env_variable_passed_as_jvm_argument() {
-    SonarScanner build = newScanner(new File("projects/simple-sample"))
+    SonarScanner build = newScannerWithToken(new File("projects/simple-sample"), analysisToken)
       .setEnvironmentVariable("SONAR_SCANNER_OPTS", "-Xmx1k");
     BuildResult executeBuild = orchestrator.executeBuildQuietly(build);
     assertThat(executeBuild.getLastStatus()).isNotZero();
@@ -235,7 +254,7 @@ public class ScannerTest extends ScannerTestCase {
   @Test
   public void should_override_project_settings_path() {
     File projectHome = new File("projects/override-project-settings-path");
-    SonarScanner build = newScanner(projectHome)
+    SonarScanner build = newScannerWithToken(projectHome, analysisToken)
       .setProperty("project.settings",
         new File(projectHome, "conf/sq-project.properties").getAbsolutePath());
     orchestrator.executeBuild(build);
@@ -248,7 +267,7 @@ public class ScannerTest extends ScannerTestCase {
   @Test
   public void should_override_project_settings_path_using_env_variable() {
     File projectHome = new File("projects/override-project-settings-path");
-    SonarScanner build = newScanner(projectHome)
+    SonarScanner build = newScannerWithToken(projectHome, analysisToken)
       .setEnvironmentVariable("SONARQUBE_SCANNER_PARAMS", "{"
         + "\"project.settings\" : \"" + StringEscapeUtils.escapeJavaScript(
         new File(projectHome, "conf/sq-project.properties").getAbsolutePath())
index 275805062d89b4eb86aff5824011573ecc0a2d10..abb699e567cf12c58cd00e4df6461a20d273241b 100644 (file)
  */
 package com.sonarsource.scanner.it;
 
-import com.sonar.orchestrator.Orchestrator;
 import com.sonar.orchestrator.build.SonarScanner;
+import com.sonar.orchestrator.container.Server;
 import com.sonar.orchestrator.http.HttpMethod;
 import com.sonar.orchestrator.junit4.OrchestratorRule;
 import com.sonar.orchestrator.version.Version;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
-import java.time.LocalDateTime;
-import java.time.ZoneId;
 import java.time.ZonedDateTime;
 import java.time.format.DateTimeFormatter;
-import java.util.List;
 import java.util.Map;
 import java.util.Properties;
 import java.util.function.Function;
 import java.util.stream.Collectors;
-import javax.annotation.CheckForNull;
 import org.apache.commons.lang.StringUtils;
 import org.junit.After;
 import org.junit.ClassRule;
@@ -45,7 +41,6 @@ import org.junit.rules.ExpectedException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.sonarqube.ws.Components.Component;
-import org.sonarqube.ws.Measures;
 import org.sonarqube.ws.Measures.Measure;
 import org.sonarqube.ws.client.HttpConnector;
 import org.sonarqube.ws.client.WsClient;
@@ -54,7 +49,6 @@ import org.sonarqube.ws.client.components.ShowRequest;
 import org.sonarqube.ws.client.measures.ComponentRequest;
 
 import static java.util.Arrays.asList;
-import static java.util.Collections.singletonList;
 
 public abstract class ScannerTestCase {
   private static final String DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZ";
@@ -75,11 +69,11 @@ public abstract class ScannerTestCase {
     if (artifactVersion == null) {
       String scannerVersion = System.getProperty("scanner.version");
       if (StringUtils.isNotBlank(scannerVersion)) {
-        LOG.info("Use provided Scanner version: " + scannerVersion);
+        LOG.info("Use provided Scanner version: {}", scannerVersion);
         artifactVersion = Version.create(scannerVersion);
       } else if (StringUtils.isNotBlank(System.getenv("PROJECT_VERSION"))) {
         scannerVersion = System.getenv("PROJECT_VERSION");
-        LOG.info("Use Scanner version from environment: " + scannerVersion);
+        LOG.info("Use Scanner version from environment: {}", scannerVersion);
         artifactVersion = Version.create(scannerVersion);
       } else {
         try (FileInputStream fis = new FileInputStream(
@@ -107,54 +101,44 @@ public abstract class ScannerTestCase {
       .execute();
   }
 
-  SonarScanner newScanner(File baseDir, String... keyValueProperties) {
+  SonarScanner newScannerWithToken(File baseDir, String token, String... keyValueProperties) {
     SonarScanner scannerCli = SonarScanner.create(baseDir, keyValueProperties);
     scannerCli.setScannerVersion(artifactVersion().toString());
+    if (orchestrator.getServer().version().isGreaterThanOrEquals(10, 0)) {
+      scannerCli.setProperty("sonar.token", token);
+    } else {
+      // Before SQ 10.0, the token was passed through the login property
+      scannerCli.setProperty("sonar.login", token);
+    }
     return scannerCli;
   }
 
-  @CheckForNull
-  static Map<String, Measure> getMeasures(String componentKey,
-    String... metricKeys) {
-    return newWsClient().measures().component(new ComponentRequest()
-      .setComponent(componentKey)
-      .setMetricKeys(asList(metricKeys)))
-      .getComponent().getMeasuresList()
-      .stream()
-      .collect(Collectors.toMap(Measure::getMetric, Function.identity()));
+  SonarScanner newScannerWithAdminCredentials(File baseDir, String... keyValueProperties) {
+    SonarScanner scannerCli = SonarScanner.create(baseDir, keyValueProperties);
+    scannerCli.setScannerVersion(artifactVersion().toString());
+    scannerCli.setProperty("sonar.login", Server.ADMIN_LOGIN);
+    scannerCli.setProperty("sonar.password", Server.ADMIN_PASSWORD);
+    return scannerCli;
   }
 
-  @CheckForNull
-  static Measure getMeasure(String componentKey, String metricKey) {
-    Measures.ComponentWsResponse response = newWsClient().measures()
-      .component(new ComponentRequest()
+  static Map<String, Measure> getMeasures(String componentKey, String... metricKeys) {
+    return newAdminWsClient().measures().component(new ComponentRequest()
         .setComponent(componentKey)
-        .setMetricKeys(singletonList(metricKey)));
-    List<Measure> measures = response.getComponent().getMeasuresList();
-    return measures.size() == 1 ? measures.get(0) : null;
-  }
-
-  @CheckForNull
-  static Integer getMeasureAsInteger(String componentKey, String metricKey) {
-    Measure measure = getMeasure(componentKey, metricKey);
-    return (measure == null) ? null : Integer.parseInt(measure.getValue());
-  }
-
-  @CheckForNull
-  static Double getMeasureAsDouble(String componentKey, String metricKey) {
-    Measure measure = getMeasure(componentKey, metricKey);
-    return (measure == null) ? null : Double.parseDouble(measure.getValue());
+        .setMetricKeys(asList(metricKeys)))
+      .getComponent().getMeasuresList()
+      .stream()
+      .collect(Collectors.toMap(Measure::getMetric, Function.identity()));
   }
 
-  @CheckForNull
   static Component getComponent(String componentKey) {
-    return newWsClient().components()
+    return newAdminWsClient().components()
       .show(new ShowRequest().setComponent(componentKey)).getComponent();
   }
 
-  static WsClient newWsClient() {
+  public static WsClient newAdminWsClient() {
     return WsClientFactories.getDefault().newClient(HttpConnector.newBuilder()
       .url(orchestrator.getServer().getUrl())
+      .credentials(Server.ADMIN_LOGIN, Server.ADMIN_PASSWORD)
       .build());
   }
 
index 8d4df8850f23197253d3b9bf7327acbc0bda83ef..a6a128f597fe63fc9e633d90e4ae5fb8b3fa7989 100644 (file)
@@ -40,7 +40,7 @@ public class SonarScannerTestSuite {
     String sonarVersion = System
       .getProperty("sonar.runtimeVersion", "DEV");
     return OrchestratorRule.builderEnv()
-      .useDefaultAdminCredentialsForBuilds(true)
+      .defaultForceAuthentication()
       .setSonarVersion(sonarVersion)
       .addBundledPluginToKeep("sonar-javascript")
       .addPlugin(MavenLocation.of("org.sonarsource.sonarqube", "sonar-xoo-plugin", sonarVersion))
diff --git a/pom.xml b/pom.xml
index 661a01e1edea88948a3a793a080d36fcfe77d52c..d80a75d15639d20c3be363855cc07a96cb99faa4 100644 (file)
--- a/pom.xml
+++ b/pom.xml
@@ -68,7 +68,7 @@
     <dependency>
       <groupId>org.sonarsource.scanner.lib</groupId>
       <artifactId>sonar-scanner-java-library</artifactId>
-      <version>3.0.0.168</version>
+      <version>3.0.1.175</version>
     </dependency>
     <dependency>
       <groupId>org.slf4j</groupId>