Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#100: Fix retrieval of authentication tokens on Github enterprise hosts #115

Merged
merged 2 commits into from
May 24, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ public void load(CoreExtension.Context context) {
PropertyDefinition.builder(GraphqlCheckRunProvider.PULL_REQUEST_GITHUB_URL)
.category(PULL_REQUEST_CATEGORY_LABEL).subCategory(GITHUB_INTEGRATION_SUBCATEGORY_LABEL)
.onQualifiers(Qualifiers.APP).name("The API URL for a GitHub instance").description(
"The API url for a GitHub instance. https://api.github.com/ for github.com, https://github.saobby.my.eu.orgpany.com/api/ when using GitHub Enterprise")
"The API url for a GitHub instance. https://api.github.com/ for github.com, https://github.saobby.my.eu.orgpany.com/api/v3 when using GitHub Enterprise")
.type(PropertyType.STRING).defaultValue("https://api.github.com").build(),

PropertyDefinition.builder(PullRequestBuildStatusDecorator.PULL_REQUEST_COMMENT_SUMMARY_ENABLED).category(PULL_REQUEST_CATEGORY_LABEL).subCategory(GENERAL)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public RepositoryAuthenticationToken getInstallationToken(String apiUrl, String

ObjectMapper objectMapper = new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

URLConnection appConnection = urlProvider.createUrlConnection(apiUrl + "/app/installations");
URLConnection appConnection = urlProvider.createUrlConnection(getV3Url(apiUrl) + "/app/installations");
appConnection.setRequestProperty(ACCEPT_HEADER, APP_PREVIEW_ACCEPT_HEADER);
appConnection.setRequestProperty(AUTHORIZATION_HEADER, BEARER_AUTHORIZATION_HEADER_PREFIX + jwtToken);

Expand Down Expand Up @@ -144,6 +144,15 @@ private Optional<RepositoryAuthenticationToken> findRepositoryAuthenticationToke
return findRepositoryAuthenticationToken(appToken, nextLink.get(), projectPath, objectMapper);
}

private static String getV3Url(String apiUrl) {
if (apiUrl.endsWith("/")) {
apiUrl = apiUrl.substring(0, apiUrl.length() - 1);
}
if (apiUrl.endsWith("/api")) {
apiUrl = apiUrl + "/v3";
}
return apiUrl;
}

private static PrivateKey createPrivateKey(String apiPrivateKey) throws IOException {
try (PEMParser pemParser = new PEMParser(new StringReader(apiPrivateKey))) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ public void createCheckRun(AnalysisDetails analysisDetails, UnifyConfiguration u

GraphQLRequestEntity.RequestBuilder graphQLRequestEntityBuilder =
graphqlProvider.createRequestBuilder()
.url(apiUrl + "/graphql")
.url(getGraphqlUrl(apiUrl))
.headers(headers)
.request(CreateCheckRun.class)
.arguments(new Arguments("createCheckRun", new Argument<>("input", repositoryInputObjectBuilder
Expand Down Expand Up @@ -239,6 +239,18 @@ private List<InputObject<Object>> createAnnotations(List<PostAnalysisIssueVisito
}).collect(Collectors.toList());
}

private static String getGraphqlUrl(String apiUrl) {
if (apiUrl.endsWith("/")) {
apiUrl = apiUrl.substring(0, apiUrl.length() - 1);
}
if (apiUrl.endsWith("/v3")) {
apiUrl = apiUrl.substring(0, apiUrl.length() - 3);
}
apiUrl = apiUrl + "/graphql";

return apiUrl;
}

private static CheckAnnotationLevel mapToGithubAnnotationLevel(String sonarqubeSeverity) {
switch (sonarqubeSeverity) {
case Severity.INFO:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,30 @@ public class RestApplicationAuthenticationProviderTest {

@Test
public void testTokenRetrievedHappyPath() throws IOException {
testTokenForUrl("apiUrl", "apiUrl/app/installations");
}

@Test
public void testTokenRetrievedHappyPathApiPath() throws IOException {
testTokenForUrl("apiUrl/api", "apiUrl/api/v3/app/installations");
}

@Test
public void testTokenRetrievedHappyPathApiPathTrailingSlash() throws IOException {
testTokenForUrl("apiUrl/api/", "apiUrl/api/v3/app/installations");
}

@Test
public void testTokenRetrievedHappyPathV3Path() throws IOException {
testTokenForUrl("apiUrl/api/v3", "apiUrl/api/v3/app/installations");
}

@Test
public void testTokenRetrievedHappyPathV3PathTrailingSlash() throws IOException {
testTokenForUrl("apiUrl/api/v3/", "apiUrl/api/v3/app/installations");
}

private void testTokenForUrl(String apiUrl, String fullUrl) throws IOException {
UrlConnectionProvider urlProvider = mock(UrlConnectionProvider.class);
Clock clock = Clock.fixed(Instant.ofEpochMilli(123456789L), ZoneId.of("UTC"));

Expand All @@ -74,8 +98,7 @@ public void testTokenRetrievedHappyPath() throws IOException {
"\"}]}").getBytes(StandardCharsets.UTF_8))).when(repositoriesUrlConnection).getInputStream();
doReturn(repositoriesUrlConnection).when(urlProvider).createUrlConnection("repositories_url");

String apiUrl = "apiUrl";
doReturn(installationsUrlConnection).when(urlProvider).createUrlConnection(eq(apiUrl + "/app/installations"));
doReturn(installationsUrlConnection).when(urlProvider).createUrlConnection(eq(fullUrl));

String appId = "appID";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,17 +189,40 @@ public void createCheckRunExceptionOnInvalidIssueSeverity() throws IOException,

@Test
public void createCheckRunHappyPathOkStatus() throws IOException, GeneralSecurityException {
createCheckRunHappyPath(QualityGate.Status.OK);
createCheckRunHappyPath(QualityGate.Status.OK, "http://api.target.domain", "http://api.target.domain/graphql");
}

@Test
public void createCheckRunHappyPathErrorStatus() throws IOException, GeneralSecurityException {
createCheckRunHappyPath(QualityGate.Status.ERROR);
public void createCheckRunHappyPathOkStatusTrailingSlash() throws IOException, GeneralSecurityException {
createCheckRunHappyPath(QualityGate.Status.OK, "http://api.target.domain/", "http://api.target.domain/graphql");
}

@Test
public void createCheckRunHappyPathOkStatusApiPath() throws IOException, GeneralSecurityException {
createCheckRunHappyPath(QualityGate.Status.OK, "http://api.target.domain/api", "http://api.target.domain/api/graphql");
}

@Test
public void createCheckRunHappyPathOkStatusApiPathTrailingSlash() throws IOException, GeneralSecurityException {
createCheckRunHappyPath(QualityGate.Status.OK, "http://api.target.domain/api/", "http://api.target.domain/api/graphql");
}

@Test
public void createCheckRunHappyPathOkStatusV3Path() throws IOException, GeneralSecurityException {
createCheckRunHappyPath(QualityGate.Status.OK, "http://api.target.domain/api/v3", "http://api.target.domain/api/graphql");
}

@Test
public void createCheckRunHappyPathOkStatusV3PathTrailingSlash() throws IOException, GeneralSecurityException {
createCheckRunHappyPath(QualityGate.Status.OK, "http://api.target.domain/api/v3/", "http://api.target.domain/api/graphql");
}

@Test
public void createCheckRunHappyPathErrorStatus() throws IOException, GeneralSecurityException {
createCheckRunHappyPath(QualityGate.Status.ERROR, "http://abc.de/", "http://abc.de/graphql");
}

private void createCheckRunHappyPath(QualityGate.Status status) throws IOException, GeneralSecurityException {
private void createCheckRunHappyPath(QualityGate.Status status, String basePath, String fullPath) throws IOException, GeneralSecurityException {
String[] messageInput = {
"issue 1",
"issue 2",
Expand Down Expand Up @@ -319,7 +342,7 @@ private void createCheckRunHappyPath(QualityGate.Status status) throws IOExcepti
when(analysisDetails.getPostAnalysisIssueVisitor()).thenReturn(postAnalysisIssueVisitor);

when(configuration.get(anyString())).then(i -> Optional.of(i.getArgument(0)));
when(configuration.get(GraphqlCheckRunProvider.PULL_REQUEST_GITHUB_URL)).thenReturn(Optional.of("http://host.name"));
when(configuration.get(GraphqlCheckRunProvider.PULL_REQUEST_GITHUB_URL)).thenReturn(Optional.of(basePath));

ArgumentCaptor<String> authenticationProviderArgumentCaptor = ArgumentCaptor.forClass(String.class);
RepositoryAuthenticationToken repositoryAuthenticationToken = mock(RepositoryAuthenticationToken.class);
Expand Down Expand Up @@ -379,7 +402,7 @@ private void createCheckRunHappyPath(QualityGate.Status status) throws IOExcepti
headers.put("Accept", "application/vnd.github.antiope-preview+json");


verify(requestBuilders.get(0)).url(eq("http://host.name/graphql"));
verify(requestBuilders.get(0)).url(eq(fullPath));
verify(requestBuilders.get(0)).headers(eq(headers));
verify(requestBuilders.get(0)).requestMethod(eq(GraphQLTemplate.GraphQLMethod.MUTATE));
verify(requestBuilders.get(0)).build();
Expand All @@ -392,7 +415,7 @@ private void createCheckRunHappyPath(QualityGate.Status status) throws IOExcepti
assertEquals("input", argumentsArgumentCaptor.getValue().getArguments().get(0).getKey());

assertEquals(
Arrays.asList("http://host.name", "sonar.alm.github.app.id", "sonar.alm.github.app.privateKey.secured",
Arrays.asList(basePath, "sonar.alm.github.app.id", "sonar.alm.github.app.privateKey.secured",
"sonar.pullrequest.github.repository"),
authenticationProviderArgumentCaptor.getAllValues());

Expand Down