Skip to content

Commit

Permalink
SCANCLI-150 Use Bearer authentication scheme when a token is provided
Browse files Browse the repository at this point in the history
  • Loading branch information
henryju committed Jun 7, 2024
1 parent 4b99877 commit 6f8f3c3
Show file tree
Hide file tree
Showing 6 changed files with 67 additions and 69 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public void should_succeed_with_self_contained_jre_despite_rubbish_java_home()
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);
Expand All @@ -56,7 +56,7 @@ public void should_fail_without_self_contained_jre_when_rubbish_java_home()
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);
}
Expand Down
16 changes: 8 additions & 8 deletions it/src/test/java/com/sonarsource/scanner/it/MultimoduleTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -79,7 +79,7 @@ public void test_simplest_with_props_on_root() {
*/
@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);
Expand Down Expand Up @@ -111,7 +111,7 @@ public void test_simplest_with_props_on_each_module() {
*/
@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);
Expand Down Expand Up @@ -140,7 +140,7 @@ public void test_deep_path_for_modules() {
*/
@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);
Expand Down Expand Up @@ -169,7 +169,7 @@ public void test_module_path_with_space() {
*/
@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);
Expand Down Expand Up @@ -206,7 +206,7 @@ public void test_overwriting_parent_properties() {
*/
@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);
Expand Down Expand Up @@ -237,7 +237,7 @@ private boolean noMoreModules() {
*/
@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);
Expand All @@ -254,7 +254,7 @@ public void should_fail_if_unexisting_base_dir() {
*/
@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);
Expand Down
51 changes: 35 additions & 16 deletions it/src/test/java/com/sonarsource/scanner/it/ScannerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,22 +27,41 @@
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(
Expand All @@ -56,7 +75,7 @@ public void basedir_contains_sources() {
*/
@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);
Expand All @@ -70,7 +89,7 @@ public void analyzers_can_spawn_processes() {
*/
@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);

Expand All @@ -94,7 +113,7 @@ private void verifyProjectMeasures(Map<String, Measure> projectMeasures, int exp
*/
@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);

Expand All @@ -110,7 +129,7 @@ public void should_override_working_dir_with_relative_path() {
@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);
Expand All @@ -126,7 +145,7 @@ public void should_override_working_dir_with_absolute_path() {
*/
@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();
Expand All @@ -142,16 +161,16 @@ public void should_fail_if_source_dir_does_not_exist() {
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);
}

@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\"," +
Expand All @@ -163,7 +182,7 @@ public void should_use_json_environment_props() {

@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());
Expand All @@ -176,7 +195,7 @@ public void should_use_environment_prop() {

@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\" }");
Expand All @@ -187,7 +206,7 @@ public void should_skip_analysis() {

@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");
Expand All @@ -204,7 +223,7 @@ public void should_fail_if_unable_to_connect() {
@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");
Expand All @@ -221,7 +240,7 @@ public void run_from_external_location() throws IOException {

@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();
Expand All @@ -235,7 +254,7 @@ public void verify_scanner_opts_env_variable_passed_as_jvm_argument() {
@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);
Expand All @@ -248,7 +267,7 @@ public void should_override_project_settings_path() {
@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())
Expand Down
61 changes: 20 additions & 41 deletions it/src/test/java/com/sonarsource/scanner/it/ScannerTestCase.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,24 +19,20 @@
*/
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;
Expand All @@ -45,7 +41,6 @@
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;
Expand All @@ -54,7 +49,6 @@
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";
Expand All @@ -75,11 +69,11 @@ private static Version artifactVersion() {
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(
Expand Down Expand Up @@ -107,54 +101,39 @@ public void resetData() {
.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());
scannerCli.setProperty("sonar.token", 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());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ private static OrchestratorRule createOrchestrator() {
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))
Expand Down
Loading

0 comments on commit 6f8f3c3

Please sign in to comment.