formatting

This commit is contained in:
spencergibb
2021-07-27 17:01:38 -04:00
parent 64a28c476d
commit cc16375b3f
8 changed files with 76 additions and 130 deletions

View File

@@ -117,7 +117,7 @@ import org.springframework.vault.core.VaultTemplate;
CredhubRepositoryConfiguration.class, SvnRepositoryConfiguration.class, NativeRepositoryConfiguration.class,
GitRepositoryConfiguration.class, RedisRepositoryConfiguration.class, GoogleCloudSourceConfiguration.class,
AwsS3RepositoryConfiguration.class, AwsSecretsManagerRepositoryConfiguration.class,
GoogleSecretManagerRepositoryConfiguration.class, DefaultRepositoryConfiguration.class })
GoogleSecretManagerRepositoryConfiguration.class, DefaultRepositoryConfiguration.class })
public class EnvironmentRepositoryConfiguration {
@Bean
@@ -516,8 +516,7 @@ class GoogleSecretManagerRepositoryConfiguration {
@Bean
public GoogleSecretManagerEnvironmentRepository googleSecretManagerEnvironmentRepository(
GoogleSecretManagerEnvironmentRepositoryFactory factory,
GoogleSecretManagerEnvironmentProperties environmentProperties)
throws Exception {
GoogleSecretManagerEnvironmentProperties environmentProperties) throws Exception {
return factory.build(environmentProperties);
}

View File

@@ -24,8 +24,7 @@ import org.springframework.core.Ordered;
* @author Jose Maria Alvarez
*/
@ConfigurationProperties("spring.cloud.config.server.gcp-secret-manager")
public class GoogleSecretManagerEnvironmentProperties
implements EnvironmentRepositoryProperties {
public class GoogleSecretManagerEnvironmentProperties implements EnvironmentRepositoryProperties {
private int order = Ordered.LOWEST_PRECEDENCE;

View File

@@ -49,14 +49,12 @@ public class GoogleSecretManagerEnvironmentRepository implements EnvironmentRepo
private GoogleConfigProvider configProvider;
public GoogleSecretManagerEnvironmentRepository(
ObjectProvider<HttpServletRequest> request, RestTemplate rest,
GoogleSecretManagerEnvironmentProperties properties) {
public GoogleSecretManagerEnvironmentRepository(ObjectProvider<HttpServletRequest> request, RestTemplate rest,
GoogleSecretManagerEnvironmentProperties properties) {
this.applicationLabel = properties.getApplicationLabel();
this.profileLabel = properties.getProfileLabel();
this.configProvider = new HttpHeaderGoogleConfigProvider(request);
this.accessStrategy = GoogleSecretManagerAccessStrategyFactory.forVersion(rest,
configProvider, properties);
this.accessStrategy = GoogleSecretManagerAccessStrategyFactory.forVersion(rest, configProvider, properties);
this.tokenMandatory = properties.getTokenMandatory();
}
@@ -72,7 +70,7 @@ public class GoogleSecretManagerEnvironmentRepository implements EnvironmentRepo
profile = "default," + profile;
}
String[] profiles = org.springframework.util.StringUtils
.trimArrayElements(org.springframework.util.StringUtils.commaDelimitedListToStringArray(profile));
.trimArrayElements(org.springframework.util.StringUtils.commaDelimitedListToStringArray(profile));
Environment result = new Environment(application, profile, label, null, null);
if (tokenMandatory) {
if (accessStrategy.checkRemotePermissions()) {
@@ -85,13 +83,11 @@ public class GoogleSecretManagerEnvironmentRepository implements EnvironmentRepo
return result;
}
private void addPropertySource(String application, String[] profiles,
Environment result) {
private void addPropertySource(String application, String[] profiles, Environment result) {
for (String profileUnit : profiles) {
Map<?, ?> secrets = getSecrets(application, profileUnit);
if (!secrets.isEmpty()) {
result.add(new PropertySource("gsm:" + application + "-" + profileUnit,
secrets));
result.add(new PropertySource("gsm:" + application + "-" + profileUnit, secrets));
}
}
}
@@ -103,23 +99,16 @@ public class GoogleSecretManagerEnvironmentRepository implements EnvironmentRepo
*/
private Map<?, ?> getSecrets(String application, String profile) {
Map<String, String> result = new HashMap<>();
String prefix = configProvider
.getValue(HttpHeaderGoogleConfigProvider.PREFIX_HEADER, false);
String prefix = configProvider.getValue(HttpHeaderGoogleConfigProvider.PREFIX_HEADER, false);
for (Secret secret : accessStrategy.getSecrets()) {
if (secret.getLabelsOrDefault(applicationLabel, "application")
.equalsIgnoreCase(application)
&& secret.getLabelsOrDefault(profileLabel, "profile")
.equalsIgnoreCase(profile)) {
result.put(accessStrategy.getSecretName(secret), accessStrategy
.getSecretValue(secret, new GoogleSecretComparatorByVersion()));
if (secret.getLabelsOrDefault(applicationLabel, "application").equalsIgnoreCase(application)
&& secret.getLabelsOrDefault(profileLabel, "profile").equalsIgnoreCase(profile)) {
result.put(accessStrategy.getSecretName(secret),
accessStrategy.getSecretValue(secret, new GoogleSecretComparatorByVersion()));
}
else if (StringUtils.isNotBlank(prefix)
&& accessStrategy.getSecretName(secret).startsWith(prefix)) {
result.put(
StringUtils.removeStart(accessStrategy.getSecretName(secret),
prefix),
accessStrategy.getSecretValue(secret,
new GoogleSecretComparatorByVersion()));
else if (StringUtils.isNotBlank(prefix) && accessStrategy.getSecretName(secret).startsWith(prefix)) {
result.put(StringUtils.removeStart(accessStrategy.getSecretName(secret), prefix),
accessStrategy.getSecretValue(secret, new GoogleSecretComparatorByVersion()));
}
}
return result;

View File

@@ -29,17 +29,14 @@ public class GoogleSecretManagerEnvironmentRepositoryFactory implements
private final ObjectProvider<HttpServletRequest> request;
public GoogleSecretManagerEnvironmentRepositoryFactory(
ObjectProvider<HttpServletRequest> request) {
public GoogleSecretManagerEnvironmentRepositoryFactory(ObjectProvider<HttpServletRequest> request) {
this.request = request;
}
@Override
public GoogleSecretManagerEnvironmentRepository build(
GoogleSecretManagerEnvironmentProperties environmentProperties)
throws Exception {
return new GoogleSecretManagerEnvironmentRepository(request, new RestTemplate(),
environmentProperties);
GoogleSecretManagerEnvironmentProperties environmentProperties) throws Exception {
return new GoogleSecretManagerEnvironmentRepository(request, new RestTemplate(), environmentProperties);
}
}

View File

@@ -28,40 +28,33 @@ public final class GoogleSecretManagerAccessStrategyFactory {
throw new IllegalStateException("Can't instantiate an utility class");
}
public static GoogleSecretManagerAccessStrategy forVersion(RestTemplate rest,
GoogleConfigProvider configProvider,
GoogleSecretManagerEnvironmentProperties properties) {
public static GoogleSecretManagerAccessStrategy forVersion(RestTemplate rest, GoogleConfigProvider configProvider,
GoogleSecretManagerEnvironmentProperties properties) {
switch (properties.getVersion()) {
case 1:
try {
return new GoogleSecretManagerV1AccessStrategy(rest, configProvider,
properties.getServiceAccount());
return new GoogleSecretManagerV1AccessStrategy(rest, configProvider, properties.getServiceAccount());
}
catch (Exception e) {
throw new RepositoryException("Cannot create service client", e);
}
default:
throw new IllegalArgumentException(
"No support for given Google Secret manager backend version "
+ properties.getVersion());
"No support for given Google Secret manager backend version " + properties.getVersion());
}
}
public static GoogleSecretManagerAccessStrategy forVersion(RestTemplate rest,
GoogleConfigProvider configProvider,
GoogleSecretManagerEnvironmentProperties properties,
SecretManagerServiceClient client) {
public static GoogleSecretManagerAccessStrategy forVersion(RestTemplate rest, GoogleConfigProvider configProvider,
GoogleSecretManagerEnvironmentProperties properties, SecretManagerServiceClient client) {
switch (properties.getVersion()) {
case 1:
return new GoogleSecretManagerV1AccessStrategy(rest, configProvider,
client);
return new GoogleSecretManagerV1AccessStrategy(rest, configProvider, client);
default:
throw new IllegalArgumentException(
"No support for given Google Secret manager backend version "
+ properties.getVersion());
"No support for given Google Secret manager backend version " + properties.getVersion());
}
}

View File

@@ -55,8 +55,7 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestTemplate;
public class GoogleSecretManagerV1AccessStrategy
implements GoogleSecretManagerAccessStrategy {
public class GoogleSecretManagerV1AccessStrategy implements GoogleSecretManagerAccessStrategy {
private final SecretManagerServiceClient client;
@@ -68,19 +67,14 @@ public class GoogleSecretManagerV1AccessStrategy
private static final String ACCESS_SECRET_PERMISSION = "secretmanager.versions.access";
private static Log logger = LogFactory
.getLog(GoogleSecretManagerV1AccessStrategy.class);
private static Log logger = LogFactory.getLog(GoogleSecretManagerV1AccessStrategy.class);
public GoogleSecretManagerV1AccessStrategy(RestTemplate rest,
GoogleConfigProvider configProvider, String serviceAccountFile)
throws IOException {
public GoogleSecretManagerV1AccessStrategy(RestTemplate rest, GoogleConfigProvider configProvider,
String serviceAccountFile) throws IOException {
if (StringUtils.isNotEmpty(serviceAccountFile)) {
GoogleCredentials creds = GoogleCredentials
.fromStream(new FileInputStream(new File(serviceAccountFile)));
this.client = SecretManagerServiceClient.create(SecretManagerServiceSettings
.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(creds))
.build());
GoogleCredentials creds = GoogleCredentials.fromStream(new FileInputStream(new File(serviceAccountFile)));
this.client = SecretManagerServiceClient.create(SecretManagerServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(creds)).build());
}
else {
this.client = SecretManagerServiceClient.create();
@@ -89,8 +83,8 @@ public class GoogleSecretManagerV1AccessStrategy
this.configProvider = configProvider;
}
public GoogleSecretManagerV1AccessStrategy(RestTemplate rest,
GoogleConfigProvider configProvider, SecretManagerServiceClient client) {
public GoogleSecretManagerV1AccessStrategy(RestTemplate rest, GoogleConfigProvider configProvider,
SecretManagerServiceClient client) {
this.client = client;
this.rest = rest;
this.configProvider = configProvider;
@@ -102,12 +96,11 @@ public class GoogleSecretManagerV1AccessStrategy
ProjectName project = ProjectName.of(getProjectId());
// Create the request.
ListSecretsRequest listSecretRequest = ListSecretsRequest.newBuilder()
.setParent(project.toString()).build();
ListSecretsRequest listSecretRequest = ListSecretsRequest.newBuilder().setParent(project.toString()).build();
// Get all secrets.
SecretManagerServiceClient.ListSecretsPagedResponse pagedListSecretResponse = client
.listSecrets(listSecretRequest);
.listSecrets(listSecretRequest);
List<Secret> result = new ArrayList<Secret>();
pagedListSecretResponse.iterateAll().forEach(result::add);
@@ -120,12 +113,12 @@ public class GoogleSecretManagerV1AccessStrategy
SecretName parent = SecretName.parse(secret.getName());
// Create the request.
ListSecretVersionsRequest listVersionRequest = ListSecretVersionsRequest
.newBuilder().setParent(parent.toString()).build();
ListSecretVersionsRequest listVersionRequest = ListSecretVersionsRequest.newBuilder()
.setParent(parent.toString()).build();
// Get all versions.
SecretManagerServiceClient.ListSecretVersionsPagedResponse pagedListVersionResponse = client
.listSecretVersions(listVersionRequest);
.listSecretVersions(listVersionRequest);
List<SecretVersion> result = new ArrayList<SecretVersion>();
pagedListVersionResponse.iterateAll().forEach(result::add);
return result;
@@ -137,17 +130,16 @@ public class GoogleSecretManagerV1AccessStrategy
List<SecretVersion> versions = getSecretVersions(secret);
SecretVersion winner = null;
for (SecretVersion secretVersion : versions) {
if ((secretVersion.getState()
.getNumber() == SecretVersion.State.ENABLED_VALUE)
&& comparator.compare(secretVersion, winner) > 0) {
if ((secretVersion.getState().getNumber() == SecretVersion.State.ENABLED_VALUE)
&& comparator.compare(secretVersion, winner) > 0) {
winner = secretVersion;
}
}
if (winner != null) {
SecretVersionName name = SecretVersionName.parse(winner.getName());
// Access the secret version.
AccessSecretVersionRequest request = AccessSecretVersionRequest.newBuilder()
.setName(name.toString()).build();
AccessSecretVersionRequest request = AccessSecretVersionRequest.newBuilder().setName(name.toString())
.build();
AccessSecretVersionResponse response = client.accessSecretVersion(request);
result = response.getPayload().getData().toStringUtf8();
}
@@ -166,27 +158,22 @@ public class GoogleSecretManagerV1AccessStrategy
try {
AccessToken accessToken = new AccessToken(getAccessToken(), null);
GoogleCredentials credential = new GoogleCredentials(accessToken);
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
credential);
service = new CloudResourceManager.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(), requestInitializer)
.setApplicationName(APPLICATION_NAME).build();
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credential);
service = new CloudResourceManager.Builder(GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(), requestInitializer).setApplicationName(APPLICATION_NAME)
.build();
List<String> permissionsList = Arrays.asList(ACCESS_SECRET_PERMISSION);
TestIamPermissionsRequest requestBody = new TestIamPermissionsRequest()
.setPermissions(permissionsList);
TestIamPermissionsRequest requestBody = new TestIamPermissionsRequest().setPermissions(permissionsList);
TestIamPermissionsResponse testIamPermissionsResponse = service.projects()
.testIamPermissions(getProjectId(), requestBody).execute();
.testIamPermissions(getProjectId(), requestBody).execute();
if (testIamPermissionsResponse.getPermissions() != null
&& testIamPermissionsResponse.size() >= 1) {
if (testIamPermissionsResponse.getPermissions() != null && testIamPermissionsResponse.size() >= 1) {
return Boolean.TRUE;
}
else {
logger.warn(
"Access token has no permissions to access secrets in project");
logger.warn("Access token has no permissions to access secrets in project");
return Boolean.FALSE;
}
}
@@ -197,26 +184,22 @@ public class GoogleSecretManagerV1AccessStrategy
}
private String getAccessToken() {
return configProvider.getValue(HttpHeaderGoogleConfigProvider.ACCESS_TOKEN_HEADER,
true);
return configProvider.getValue(HttpHeaderGoogleConfigProvider.ACCESS_TOKEN_HEADER, true);
}
/**
* @return
* @return the Project Id.
*/
private String getProjectId() {
String result = null;
try {
result = configProvider
.getValue(HttpHeaderGoogleConfigProvider.PROJECT_ID_HEADER, true);
result = configProvider.getValue(HttpHeaderGoogleConfigProvider.PROJECT_ID_HEADER, true);
}
catch (Exception e) {
// not in GCP
HttpEntity<String> entity = new HttpEntity<String>("parameters",
getMetadataHttpHeaders());
result = rest.exchange(
GoogleSecretManagerEnvironmentProperties.GOOGLE_METADATA_PROJECT_URL,
HttpMethod.GET, entity, String.class).getBody();
HttpEntity<String> entity = new HttpEntity<String>("parameters", getMetadataHttpHeaders());
result = rest.exchange(GoogleSecretManagerEnvironmentProperties.GOOGLE_METADATA_PROJECT_URL, HttpMethod.GET,
entity, String.class).getBody();
}
return result;
}

View File

@@ -53,8 +53,7 @@ public class HttpHeaderGoogleConfigProvider implements GoogleConfigProvider {
}
String value = request.getHeader(key);
if (!StringUtils.hasLength(value) && mandatory) {
throw new IllegalArgumentException(
"Missing required header in HttpServletRequest: " + key);
throw new IllegalArgumentException("Missing required header in HttpServletRequest: " + key);
}
return value;
}

View File

@@ -53,8 +53,8 @@ public class GoogleSecretManagerEnvironmentRepositoryTests {
GoogleSecretManagerEnvironmentProperties properties = new GoogleSecretManagerEnvironmentProperties();
SecretManagerServiceClient mock = mock(SecretManagerServiceClient.class);
properties.setVersion(1);
assertThat(GoogleSecretManagerAccessStrategyFactory.forVersion(null, null,
properties, mock) instanceof GoogleSecretManagerV1AccessStrategy).isTrue();
assertThat(GoogleSecretManagerAccessStrategyFactory.forVersion(null, null, properties,
mock) instanceof GoogleSecretManagerV1AccessStrategy).isTrue();
}
@Test(expected = IllegalArgumentException.class)
@@ -70,19 +70,16 @@ public class GoogleSecretManagerEnvironmentRepositoryTests {
public void testGetSecrets() throws IOException {
RestTemplate rest = mock(RestTemplate.class);
GoogleConfigProvider provider = mock(HttpHeaderGoogleConfigProvider.class);
when(provider.getValue(HttpHeaderGoogleConfigProvider.PROJECT_ID_HEADER, true))
.thenReturn("test-project");
when(provider.getValue(HttpHeaderGoogleConfigProvider.PROJECT_ID_HEADER, true)).thenReturn("test-project");
SecretManagerServiceClient mock = mock(SecretManagerServiceClient.class);
SecretManagerServiceClient.ListSecretsPagedResponse response = mock(
SecretManagerServiceClient.ListSecretsPagedResponse.class);
Secret secret = Secret.newBuilder().setName("projects/test-project/secrets/test")
.build();
Secret secret = Secret.newBuilder().setName("projects/test-project/secrets/test").build();
List<Secret> secrets = new ArrayList<Secret>();
secrets.add(secret);
when(response.iterateAll()).thenReturn(secrets);
Mockito.doReturn(response).when(mock).listSecrets(any(ListSecretsRequest.class));
GoogleSecretManagerV1AccessStrategy strategy = new GoogleSecretManagerV1AccessStrategy(
rest, provider, mock);
GoogleSecretManagerV1AccessStrategy strategy = new GoogleSecretManagerV1AccessStrategy(rest, provider, mock);
assertThat(strategy.getSecrets().size()).isEqualTo(1);
}
@@ -91,27 +88,21 @@ public class GoogleSecretManagerEnvironmentRepositoryTests {
public void testGetSecretValues() throws IOException {
RestTemplate rest = mock(RestTemplate.class);
GoogleConfigProvider provider = mock(HttpHeaderGoogleConfigProvider.class);
when(provider.getValue(HttpHeaderGoogleConfigProvider.PROJECT_ID_HEADER, true))
.thenReturn("test-project");
when(provider.getValue(HttpHeaderGoogleConfigProvider.PROJECT_ID_HEADER, true)).thenReturn("test-project");
SecretManagerServiceClient mock = mock(SecretManagerServiceClient.class);
SecretManagerServiceClient.ListSecretVersionsPagedResponse response = mock(
SecretManagerServiceClient.ListSecretVersionsPagedResponse.class);
SecretVersion secret1 = SecretVersion.newBuilder()
.setName("projects/test-project/secrets/test/versions/1")
SecretVersion secret1 = SecretVersion.newBuilder().setName("projects/test-project/secrets/test/versions/1")
.setState(SecretVersion.State.ENABLED).build();
SecretVersion secret2 = SecretVersion.newBuilder()
.setName("projects/test-project/secrets/test/versions/2")
SecretVersion secret2 = SecretVersion.newBuilder().setName("projects/test-project/secrets/test/versions/2")
.setState(SecretVersion.State.DISABLED).build();
List<SecretVersion> secrets = new ArrayList<SecretVersion>();
secrets.add(secret1);
secrets.add(secret2);
when(response.iterateAll()).thenReturn(secrets);
Mockito.doReturn(response).when(mock)
.listSecretVersions(any(ListSecretVersionsRequest.class));
GoogleSecretManagerV1AccessStrategy strategy = new GoogleSecretManagerV1AccessStrategy(
rest, provider, mock);
AccessSecretVersionResponse accessSecretVersionResponse = mock(
AccessSecretVersionResponse.class);
Mockito.doReturn(response).when(mock).listSecretVersions(any(ListSecretVersionsRequest.class));
GoogleSecretManagerV1AccessStrategy strategy = new GoogleSecretManagerV1AccessStrategy(rest, provider, mock);
AccessSecretVersionResponse accessSecretVersionResponse = mock(AccessSecretVersionResponse.class);
SecretPayload payload = mock(SecretPayload.class);
ByteString data = mock(ByteString.class);
when(accessSecretVersionResponse.getPayload()).thenReturn(payload);
@@ -119,19 +110,15 @@ public class GoogleSecretManagerEnvironmentRepositoryTests {
when(data.toStringUtf8()).thenReturn("test-value");
ArgumentMatcher<AccessSecretVersionRequest> matcher = new ArgumentMatcher<AccessSecretVersionRequest>() {
@Override
public boolean matches(
AccessSecretVersionRequest accessSecretVersionRequest) {
if (accessSecretVersionRequest.getName()
.equals("projects/test-project/secrets/test/versions/1")) {
public boolean matches(AccessSecretVersionRequest accessSecretVersionRequest) {
if (accessSecretVersionRequest.getName().equals("projects/test-project/secrets/test/versions/1")) {
return true;
}
return false;
}
};
Mockito.doReturn(accessSecretVersionResponse).when(mock)
.accessSecretVersion(ArgumentMatchers.argThat(matcher));
assertThat(strategy.getSecretValue(
Secret.newBuilder().setName("projects/test-project/secrets/test").build(),
Mockito.doReturn(accessSecretVersionResponse).when(mock).accessSecretVersion(ArgumentMatchers.argThat(matcher));
assertThat(strategy.getSecretValue(Secret.newBuilder().setName("projects/test-project/secrets/test").build(),
new GoogleSecretComparatorByVersion())).isEqualTo("test-value");
}