Skip to content

Commit

Permalink
refactor(google): Update google credentials to latest style. (#526)
Browse files Browse the repository at this point in the history
  • Loading branch information
Matt Duftler committed Oct 23, 2019
1 parent 3e7076d commit 008689f
Show file tree
Hide file tree
Showing 8 changed files with 62 additions and 56 deletions.
1 change: 1 addition & 0 deletions igor-web/igor-web.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ dependencies {

implementation "com.google.apis:google-api-services-cloudbuild"
implementation "com.google.apis:google-api-services-storage"
implementation 'com.google.auth:google-auth-library-oauth2-http'
implementation "com.netflix.spinnaker.kork:kork-config"
implementation "com.netflix.spinnaker.kork:kork-core"
implementation "com.netflix.spinnaker.kork:kork-artifacts"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

package com.netflix.spinnaker.igor.config.auth

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential
import com.google.auth.oauth2.GoogleCredentials
import com.netflix.spinnaker.igor.config.JenkinsProperties
import com.squareup.okhttp.Credentials
import groovy.util.logging.Slf4j
Expand Down Expand Up @@ -71,20 +71,17 @@ class AuthRequestInterceptor implements RequestInterceptor {

static class GoogleBearerTokenHeaderSupplier implements AuthorizationHeaderSupplier {

private GoogleCredential credential
private GoogleCredentials credentials

GoogleBearerTokenHeaderSupplier(String jsonPath, List<String> scopes) {
InputStream is = new File(jsonPath).newInputStream()
credential = GoogleCredential.fromStream(is).createScoped(scopes)
credentials = GoogleCredentials.fromStream(is).createScoped(scopes)
}

String toString() {
log.debug("Including Google Bearer token in Authorization header")
if (credential.expirationTimeMilliseconds < System.currentTimeMillis()) {
log.info("Google OAuth Access token expired. Refreshing.")
credential.refreshToken()
}
return credential.accessToken
credentials.refreshIfExpired()
return credentials.accessToken.tokenValue
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,16 @@

package com.netflix.spinnaker.igor.gcb;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.cloudbuild.v1.CloudBuild;
import com.google.api.services.storage.Storage;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
Expand All @@ -47,8 +50,8 @@ public CloudBuildFactory(HttpTransport httpTransport) {
this(httpTransport, null);
}

public CloudBuild getCloudBuild(GoogleCredential credential, String applicationName) {
HttpRequestInitializer requestInitializer = getRequestInitializer(credential);
public CloudBuild getCloudBuild(GoogleCredentials credentials, String applicationName) {
HttpRequestInitializer requestInitializer = getRequestInitializer(credentials);
CloudBuild.Builder builder =
new CloudBuild.Builder(httpTransport, jsonFactory, requestInitializer)
.setApplicationName(applicationName);
Expand All @@ -59,8 +62,8 @@ public CloudBuild getCloudBuild(GoogleCredential credential, String applicationN
return builder.build();
}

public Storage getCloudStorage(GoogleCredential credential, String applicationName) {
HttpRequestInitializer requestInitializer = getRequestInitializer(credential);
public Storage getCloudStorage(GoogleCredentials credentials, String applicationName) {
HttpRequestInitializer requestInitializer = getRequestInitializer(credentials);
Storage.Builder builder =
new Storage.Builder(httpTransport, jsonFactory, requestInitializer)
.setApplicationName(applicationName);
Expand All @@ -71,11 +74,13 @@ public Storage getCloudStorage(GoogleCredential credential, String applicationNa
return builder.build();
}

private HttpRequestInitializer getRequestInitializer(GoogleCredential credential) {
return request -> {
credential.initialize(request);
request.setConnectTimeout(connectTimeoutSec * 1000);
request.setReadTimeout(readTimeoutSec * 1000);
private HttpRequestInitializer getRequestInitializer(GoogleCredentials credentials) {
return new HttpCredentialsAdapter(credentials) {
public void initialize(HttpRequest request) throws IOException {
super.initialize(request);
request.setConnectTimeout(connectTimeoutSec * 1000);
request.setReadTimeout(readTimeoutSec * 1000);
}
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

package com.netflix.spinnaker.igor.gcb;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.auth.oauth2.GoogleCredentials;
import com.netflix.spinnaker.igor.config.GoogleCloudBuildProperties;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
Expand All @@ -28,24 +28,24 @@
@ConditionalOnProperty("gcb.enabled")
@RequiredArgsConstructor
public class GoogleCloudBuildAccountFactory {
private final GoogleCredentialService credentialService;
private final GoogleCredentialsService credentialService;
private final GoogleCloudBuildClient.Factory googleCloudBuildClientFactory;
private final GoogleCloudBuildCache.Factory googleCloudBuildCacheFactory;
private final GoogleCloudBuildParser googleCloudBuildParser;

public GoogleCloudBuildAccount build(GoogleCloudBuildProperties.Account account) {
GoogleCredential credential = getCredential(account);
GoogleCredentials credentials = getCredentials(account);

GoogleCloudBuildClient client =
googleCloudBuildClientFactory.create(credential, account.getProject());
googleCloudBuildClientFactory.create(credentials, account.getProject());
return new GoogleCloudBuildAccount(
client,
googleCloudBuildCacheFactory.create(account.getName()),
googleCloudBuildParser,
new GoogleCloudBuildArtifactFetcher(client));
}

private GoogleCredential getCredential(GoogleCloudBuildProperties.Account account) {
private GoogleCredentials getCredentials(GoogleCloudBuildProperties.Account account) {
String jsonKey = account.getJsonKey();
if (StringUtils.isEmpty(jsonKey)) {
return credentialService.getApplicationDefault();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@

package com.netflix.spinnaker.igor.gcb;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.services.cloudbuild.v1.CloudBuild;
import com.google.api.services.cloudbuild.v1.model.Build;
import com.google.api.services.cloudbuild.v1.model.Operation;
import com.google.api.services.storage.Storage;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.io.InputStream;
import lombok.AccessLevel;
Expand All @@ -43,9 +43,9 @@ public static class Factory {
private final GoogleCloudBuildExecutor executor;
private final String applicationName;

public GoogleCloudBuildClient create(GoogleCredential credential, String projectId) {
CloudBuild cloudBuild = cloudBuildFactory.getCloudBuild(credential, applicationName);
Storage cloudStorage = cloudBuildFactory.getCloudStorage(credential, applicationName);
public GoogleCloudBuildClient create(GoogleCredentials credentials, String projectId) {
CloudBuild cloudBuild = cloudBuildFactory.getCloudBuild(credentials, applicationName);
Storage cloudStorage = cloudBuildFactory.getCloudStorage(credentials, applicationName);
return new GoogleCloudBuildClient(projectId, cloudBuild, cloudStorage, executor);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,22 @@

package com.netflix.spinnaker.igor.gcb;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.services.cloudbuild.v1.CloudBuildScopes;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
* Factory for calling Google API code to create a GoogleCredential, either from application default
* credentials or from a supplied path to a JSON key.
* Factory for calling Google API code to create a GoogleCredentials, either from application
* default credentials or from a supplied path to a JSON key.
*/
@Component
@ConditionalOnProperty("gcb.enabled")
public class GoogleCredentialService {
GoogleCredential getFromKey(String jsonPath) {
public class GoogleCredentialsService {
GoogleCredentials getFromKey(String jsonPath) {
try {
InputStream stream = getCredentialAsStream(jsonPath);
return loadCredential(stream);
Expand All @@ -40,9 +40,13 @@ GoogleCredential getFromKey(String jsonPath) {
}
}

GoogleCredential getApplicationDefault() {
GoogleCredentials getApplicationDefault() {
try {
return GoogleCredential.getApplicationDefault();
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();

return credentials.createScopedRequired()
? credentials.createScoped(CloudBuildScopes.all())
: credentials;
} catch (IOException e) {
throw new RuntimeException(e);
}
Expand All @@ -57,7 +61,7 @@ private InputStream getCredentialAsStream(String jsonPath) {
}
}

private GoogleCredential loadCredential(InputStream stream) throws IOException {
return GoogleCredential.fromStream(stream).createScoped(CloudBuildScopes.all());
private GoogleCredentials loadCredential(InputStream stream) throws IOException {
return GoogleCredentials.fromStream(stream).createScoped(CloudBuildScopes.all());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,27 +18,27 @@

import static org.mockito.Mockito.*;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.auth.oauth2.GoogleCredentials;
import com.netflix.spinnaker.igor.config.GoogleCloudBuildProperties;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class GoogleCloudBuildAccountFactoryTest {
private GoogleCredentialService googleCredentialService = mock(GoogleCredentialService.class);
private GoogleCredentialsService googleCredentialsService = mock(GoogleCredentialsService.class);
private GoogleCloudBuildClient.Factory googleCloudBuildClientFactory =
mock(GoogleCloudBuildClient.Factory.class);
private GoogleCloudBuildCache.Factory googleCloudBuildCacheFactory =
mock(GoogleCloudBuildCache.Factory.class);
private GoogleCloudBuildParser googleCloudBuildParser = new GoogleCloudBuildParser();

private GoogleCredential googleCredential = mock(GoogleCredential.class);
private GoogleCredentials googleCredentials = mock(GoogleCredentials.class);
private GoogleCloudBuildClient googleCloudBuildClient = mock(GoogleCloudBuildClient.class);

private GoogleCloudBuildAccountFactory googleCloudBuildAccountFactory =
new GoogleCloudBuildAccountFactory(
googleCredentialService,
googleCredentialsService,
googleCloudBuildClientFactory,
googleCloudBuildCacheFactory,
googleCloudBuildParser);
Expand All @@ -48,31 +48,31 @@ public void applicationDefaultCredentials() {
GoogleCloudBuildProperties.Account accountConfig = getBaseAccount();
accountConfig.setJsonKey("");

when(googleCredentialService.getApplicationDefault()).thenReturn(googleCredential);
when(googleCloudBuildClientFactory.create(eq(googleCredential), any(String.class)))
when(googleCredentialsService.getApplicationDefault()).thenReturn(googleCredentials);
when(googleCloudBuildClientFactory.create(eq(googleCredentials), any(String.class)))
.thenReturn(googleCloudBuildClient);

GoogleCloudBuildAccount account = googleCloudBuildAccountFactory.build(accountConfig);

verify(googleCredentialService).getApplicationDefault();
verify(googleCredentialService, never()).getFromKey(any());
verify(googleCloudBuildClientFactory).create(eq(googleCredential), any(String.class));
verify(googleCredentialsService).getApplicationDefault();
verify(googleCredentialsService, never()).getFromKey(any());
verify(googleCloudBuildClientFactory).create(eq(googleCredentials), any(String.class));
}

@Test
public void jsonCredentials() {
GoogleCloudBuildProperties.Account accountConfig = getBaseAccount();
accountConfig.setJsonKey("/path/to/file");

when(googleCredentialService.getFromKey("/path/to/file")).thenReturn(googleCredential);
when(googleCloudBuildClientFactory.create(eq(googleCredential), any(String.class)))
when(googleCredentialsService.getFromKey("/path/to/file")).thenReturn(googleCredentials);
when(googleCloudBuildClientFactory.create(eq(googleCredentials), any(String.class)))
.thenReturn(googleCloudBuildClient);

GoogleCloudBuildAccount account = googleCloudBuildAccountFactory.build(accountConfig);

verify(googleCredentialService, never()).getApplicationDefault();
verify(googleCredentialService).getFromKey("/path/to/file");
verify(googleCloudBuildClientFactory).create(eq(googleCredential), any(String.class));
verify(googleCredentialsService, never()).getApplicationDefault();
verify(googleCredentialsService).getFromKey("/path/to/file");
verify(googleCloudBuildClientFactory).create(eq(googleCredentials), any(String.class));
}

private GoogleCloudBuildProperties.Account getBaseAccount() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,10 @@

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.testing.auth.oauth2.MockTokenServerTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.cloudbuild.v1.CloudBuildScopes;
import com.google.auth.oauth2.GoogleCredentials;
import com.netflix.spectator.api.NoopRegistry;
import com.netflix.spectator.api.Registry;
import java.io.IOException;
Expand Down Expand Up @@ -61,10 +60,10 @@ CloudBuildFactory cloudBuildFactory(

@Bean
@Primary
GoogleCredentialService googleCredentialService() {
return new GoogleCredentialService() {
GoogleCredentialsService googleCredentialService() {
return new GoogleCredentialsService() {
@Override
GoogleCredential getFromKey(String jsonPath) {
GoogleCredentials getFromKey(String jsonPath) {
if (!jsonPath.equals("/path/to/some/file")) {
return null;
}
Expand All @@ -77,7 +76,7 @@ GoogleCredential getFromKey(String jsonPath) {
new MockTokenServerTransport("https://accounts.google.com/o/oauth2/auth");
mockTransport.addServiceAccount(
"test-account@spinnaker-gcb-test.iam.gserviceaccount.com", "test-token");
return GoogleCredential.fromStream(is, mockTransport, JacksonFactory.getDefaultInstance())
return GoogleCredentials.fromStream(is, () -> mockTransport)
.createScoped(CloudBuildScopes.all());
} catch (IOException e) {
throw new RuntimeException(e);
Expand Down

0 comments on commit 008689f

Please sign in to comment.