Polishing.

Convert spaces to tabs. Slightly reorder methods. Make methods static where possible. Add since tags. Reformat code, remove blank lines. Remove local_run_k8s script.

Original pull request: gh-176.
Related ticket: gh-173.
Closes gh-176.
This commit is contained in:
Mark Paluch
2017-11-03 13:12:08 +01:00
parent 4765ccc241
commit 35b8fdb496
9 changed files with 157 additions and 225 deletions

View File

@@ -97,7 +97,7 @@ class ClientAuthenticationFactory {
case KUBERNETES:
return kubernetesAuthentication(vaultProperties);
}
}
throw new UnsupportedOperationException(String.format(
"Client authentication %s not supported",
@@ -226,18 +226,22 @@ class ClientAuthenticationFactory {
}
private ClientAuthentication kubernetesAuthentication(VaultProperties vaultProperties) {
VaultProperties.KubernetesProperties kubernetes = vaultProperties.getKubernetes();
Assert.hasText(kubernetes.getRole(),
"Role (spring.cloud.vault.kubernetes.role) must not be empty");
Assert.hasText(kubernetes.getServiceAccountTokenFile(),
"Role (spring.cloud.vault.kubernetes.service-account-token-file) must not be empty");
Assert.hasText(
kubernetes.getServiceAccountTokenFile(),
"Service account token file (spring.cloud.vault.kubernetes.service-account-token-file) must not be empty");
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder()
.path(kubernetes.getKubernetesPath()).role(kubernetes.getRole())
.jwtSupplier(new KubernetesServiceAccountTokenFile(
kubernetes.getServiceAccountTokenFile()))
.build();
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions
.builder()
.path(kubernetes.getKubernetesPath())
.role(kubernetes.getRole())
.jwtSupplier(
new KubernetesServiceAccountTokenFile(kubernetes
.getServiceAccountTokenFile())).build();
return new KubernetesAuthentication(options, restOperations);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,11 +29,14 @@ import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestOperations;
/**
* Kubernetes implementation of {@link ClientAuthentication}. {@link KubernetesAuthentication}
* uses a Kubernetes Service Account JSON Web Token to login into Vault. JWT and Role are
* sent in the login request to Vault to obtain a {@link VaultToken}.
* Kubernetes implementation of {@link ClientAuthentication}.
* {@link KubernetesAuthentication} uses a Kubernetes Service Account JSON Web Token to
* login into Vault. JWT and Role are sent in the login request to Vault to obtain a
* {@link VaultToken}.
*
* @author Michal Budzyn
* @author Mark Paluch
* @since 1.1
* @see KubernetesAuthenticationOptions
* @see RestOperations
* @see <a href="https://www.vaultproject.io/docs/auth/kubernetes.html">Auth Backend:
@@ -46,14 +49,14 @@ class KubernetesAuthentication implements ClientAuthentication {
private final RestOperations restOperations;
/**
* Create a {@link KubernetesAuthentication} using {@link KubernetesAuthenticationOptions} and
* {@link RestOperations}.
* Create a {@link KubernetesAuthentication} using
* {@link KubernetesAuthenticationOptions} and {@link RestOperations}.
*
* @param options must not be {@literal null}.
* @param restOperations must not be {@literal null}.
*/
KubernetesAuthentication(KubernetesAuthenticationOptions options,
RestOperations restOperations) {
KubernetesAuthentication(KubernetesAuthenticationOptions options,
RestOperations restOperations) {
Assert.notNull(options, "KubeAuthenticationOptions must not be null");
Assert.notNull(restOperations, "RestOperations must not be null");
@@ -62,24 +65,11 @@ class KubernetesAuthentication implements ClientAuthentication {
this.restOperations = restOperations;
}
private static Map<String, String> getKubernetesLogin(String role, String jwt) {
Assert.hasText(role, "role must not be empty");
Assert.hasText(role, "jwt must not be empty");
Map<String, String> login = new HashMap<>();
login.put("jwt", jwt);
login.put("role", role);
return login;
}
@Override
public VaultToken login() throws VaultException {
Map<String, String> login = getKubernetesLogin(options.getRole(),
options.getJwtSupplier().get());
Map<String, String> login = getKubernetesLogin(options.getRole(), options
.getJwtSupplier().get());
try {
VaultResponse response = restOperations.postForObject("auth/{mount}/login",
@@ -99,7 +89,7 @@ class KubernetesAuthentication implements ClientAuthentication {
/*
* @see org.springframework.vault.authentication.LoginTokenUtil#from
*/
private LoginToken from(Map<String, Object> auth) {
private static LoginToken from(Map<String, Object> auth) {
String token = (String) auth.get("client_token");
Boolean renewable = (Boolean) auth.get("renewable");
@@ -115,4 +105,17 @@ class KubernetesAuthentication implements ClientAuthentication {
return LoginToken.of(token);
}
private static Map<String, String> getKubernetesLogin(String role, String jwt) {
Assert.hasText(role, "Role must not be empty");
Assert.hasText(role, "JWT must not be empty");
Map<String, String> login = new HashMap<>();
login.put("jwt", jwt);
login.put("role", role);
return login;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,10 +21,11 @@ import org.springframework.util.Assert;
* Authentication options for {@link KubernetesAuthentication}.
* <p>
* Authentication options provide the path, role and jwt supplier.
* {@link KubernetesAuthentication} can be constructed using {@link #builder()}. Instances of
* this class are immutable once constructed.
* {@link KubernetesAuthentication} can be constructed using {@link #builder()}. Instances
* of this class are immutable once constructed.
*
* @author Michal Budzyn
* @since 1.1
* @see KubernetesAuthentication
* @see #builder()
*/
@@ -38,7 +39,7 @@ class KubernetesAuthenticationOptions {
private final String path;
/**
* The Role.
* Name of the role against which the login is being attempted.
*/
private final String role;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,6 +21,7 @@ package org.springframework.cloud.vault.config;
*
* @author Michal Budzyn
* @see KubernetesAuthentication
* @since 1.1
*/
interface KubernetesJwtSupplier {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,7 +15,6 @@
*/
package org.springframework.cloud.vault.config;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
@@ -29,10 +28,12 @@ import org.springframework.vault.VaultException;
/**
* Mechanism to retrieve a Kubernetes service account token.
* <p>
* A file containing a token for a pods service account is automatically mounted at
* <b>/var/run/secrets/kubernetes.io/serviceaccount/token</b>
* A file containing a token for a pod's service account is automatically mounted at
* {@code /var/run/secrets/kubernetes.io/serviceaccount/token}.
*
* @author Michal Budzyn
* @author Mark Paluch
* @since 1.1
* @see KubernetesJwtSupplier
*/
class KubernetesServiceAccountTokenFile implements KubernetesJwtSupplier {
@@ -44,78 +45,68 @@ class KubernetesServiceAccountTokenFile implements KubernetesJwtSupplier {
private byte[] token;
/**
* Create a new {@link KubernetesServiceAccountTokenFile} pointing to the
* {@link #DEFAULT_KUBERNETES_SERVICE_ACCOUNT_TOKEN_FILE}. Construction fails with an
* exception if the file does not exist.
*
* @throws IllegalArgumentException if the
* {@link #DEFAULT_KUBERNETES_SERVICE_ACCOUNT_TOKEN_FILE} does not exist.
*/
KubernetesServiceAccountTokenFile() {
this(DEFAULT_KUBERNETES_SERVICE_ACCOUNT_TOKEN_FILE);
}
/**
* Create a new {@link KubernetesServiceAccountTokenFile} pointing to the
* {@link #DEFAULT_KUBERNETES_SERVICE_ACCOUNT_TOKEN_FILE}. Construction fails with an
* exception if the file does not exist.
*
* @throws IllegalArgumentException if the
* {@link #DEFAULT_KUBERNETES_SERVICE_ACCOUNT_TOKEN_FILE} does not exist.
*/
KubernetesServiceAccountTokenFile() {
this(DEFAULT_KUBERNETES_SERVICE_ACCOUNT_TOKEN_FILE);
}
/**
* Create a new {@link KubernetesServiceAccountTokenFile}
* {@link KubernetesServiceAccountTokenFile} from a {@code path}.
*
* @param path path to the service account token file.
* @throws IllegalArgumentException if the{@code path} does not exist.
*/
KubernetesServiceAccountTokenFile(String path) {
this(new FileSystemResource(path));
}
/**
* Create a new {@link KubernetesServiceAccountTokenFile}
* {@link KubernetesServiceAccountTokenFile} from a {@code path}.
*
* @param path path to the service account token file.
* @throws IllegalArgumentException if the{@code path} does not exist.
*/
KubernetesServiceAccountTokenFile(String path) {
this(new FileSystemResource(path));
}
/**
* Create a new {@link KubernetesServiceAccountTokenFile}
* {@link KubernetesServiceAccountTokenFile} from a {@link File} handle.
*
* @param file path to the service account token file.
* @throws IllegalArgumentException if the{@code path} does not exist.
*/
KubernetesServiceAccountTokenFile(File file) {
this(new FileSystemResource(file));
}
/**
* Create a new {@link KubernetesServiceAccountTokenFile}
* {@link KubernetesServiceAccountTokenFile} from a {@link Resource} handle.
*
* @param resource resource pointing to the service account token file.
* @throws IllegalArgumentException if the{@code path} does not exist.
*/
KubernetesServiceAccountTokenFile(Resource resource) {
/**
* Create a new {@link KubernetesServiceAccountTokenFile}
* {@link KubernetesServiceAccountTokenFile} from a {@link Resource} handle.
*
* @param resource resource pointing to the service account token file.
* @throws IllegalArgumentException if the{@code path} does not exist.
*/
KubernetesServiceAccountTokenFile(Resource resource) {
Assert.isTrue(resource.exists(),
String.format("Resource %s does not exist", resource));
Assert.isTrue(resource.exists(), String.format("Resource %s does not exist", resource));
try {
this.token = readToken(resource);
}
catch (IOException e) {
throw new VaultException(String.format(
"Kube JWT token retrieval from %s failed", resource), e);
}
}
try {
this.token = readToken(resource);
}
catch (IOException e) {
throw new VaultException(String.format(
"Kube JWT token retrieval from %s failed", resource), e);
}
}
@Override
public String get() {
return new String(token, StandardCharsets.US_ASCII);
}
@Override
public String get() {
return new String(token, StandardCharsets.US_ASCII);
}
/**
* Read the token from {@link Resource}.
*
* @param resource the resource to read from, must not be {@literal null}.
* @return the new byte array that has been copied to (possibly empty).
* @throws IOException in case of I/O errors.
*/
private static byte[] readToken(Resource resource) throws IOException {
/**
* Read the token from {@link Resource}.
*
* @param resource the resource to read from, must not be {@literal null}.
* @return the new byte array that has been copied to (possibly empty).
* @throws IOException in case of I/O errors.
*/
protected static byte[] readToken(Resource resource) throws IOException {
Assert.notNull(resource, "Resource must not be null");
Assert.notNull(resource, "Resource must not be null");
try (InputStream is = resource.getInputStream()) {
return StreamUtils.copyToByteArray(is);
}
}
try (InputStream is = resource.getInputStream()) {
return StreamUtils.copyToByteArray(is);
}
}
}

View File

@@ -100,7 +100,7 @@ public class VaultProperties implements EnvironmentAware {
private AwsIamProperties awsIam = new AwsIamProperties();
private KubernetesProperties kubernetes = new KubernetesProperties();
private KubernetesProperties kubernetes = new KubernetesProperties();
private Ssl ssl = new Ssl();
@@ -253,26 +253,26 @@ public class VaultProperties implements EnvironmentAware {
private String serverName;
}
@Data
public static class KubernetesProperties {
@Data
public static class KubernetesProperties {
/**
* Mount path of the Kubernetes authentication backend.
*/
@NotEmpty
private String kubernetesPath = "kubernetes";
/**
* Mount path of the Kubernetes authentication backend.
*/
@NotEmpty
private String kubernetesPath = "kubernetes";
/**
* The Role.
*/
private String role = null;
/**
* Name of the role against which the login is being attempted.
*/
private String role = "";
/**
* File with service account token.
*/
@NotEmpty
private String serviceAccountTokenFile = "/var/run/secrets/kubernetes.io/serviceaccount/token";
}
/**
* Path to the service account token file.
*/
@NotEmpty
private String serviceAccountTokenFile = "/var/run/secrets/kubernetes.io/serviceaccount/token";
}
@Data
public static class Ssl {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,15 +15,9 @@
*/
package org.springframework.cloud.vault.config;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.jsonPath;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withServerError;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
@@ -34,6 +28,13 @@ import org.springframework.vault.client.VaultClients.PrefixAwareUriTemplateHandl
import org.springframework.vault.support.VaultToken;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.jsonPath;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withServerError;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
/**
* Unit tests for {@link KubernetesAuthentication}.
*
@@ -45,19 +46,20 @@ public class KubernetesAuthenticationUnitTests {
private MockRestServiceServer mockRest;
@Before
public void before() throws Exception {
public void before() {
RestTemplate restTemplate = VaultClients.createRestTemplate();
restTemplate.setUriTemplateHandler(new PrefixAwareUriTemplateHandler());
this.mockRest = MockRestServiceServer.createServer(restTemplate);
this.restTemplate = restTemplate;
}
@Test
public void loginShouldObtainTokenWithStaticJwtSupplier() throws Exception {
public void loginShouldObtainTokenWithStaticJwtSupplier() {
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder()
.role("hello") //
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions
.builder().role("hello") //
.jwtSupplier((new KubernetesJwtSupplier() {
@Override
public String get() {
@@ -69,10 +71,12 @@ public class KubernetesAuthenticationUnitTests {
.andExpect(method(HttpMethod.POST))
.andExpect(jsonPath("$.role").value("hello"))
.andExpect(jsonPath("$.jwt").value("my-jwt-token"))
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
.body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}"));
.andRespond(
withSuccess().contentType(MediaType.APPLICATION_JSON).body(
"{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}"));
KubernetesAuthentication authentication = new KubernetesAuthentication(options, restTemplate);
KubernetesAuthentication authentication = new KubernetesAuthentication(options,
restTemplate);
VaultToken login = authentication.login();
assertThat(login).isInstanceOf(LoginToken.class);
@@ -80,10 +84,10 @@ public class KubernetesAuthenticationUnitTests {
}
@Test(expected = VaultException.class)
public void loginShouldFail() throws Exception {
public void loginShouldFail() {
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder()
.role("hello").jwtSupplier(new KubernetesJwtSupplier() {
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions
.builder().role("hello").jwtSupplier(new KubernetesJwtSupplier() {
@Override
public String get() {
return "my-jwt-token";

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016-2017 the original author or authors.
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,10 +15,6 @@
*/
package org.springframework.cloud.vault.config;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
import static org.springframework.cloud.vault.util.Settings.findWorkDir;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
@@ -29,6 +25,7 @@ import org.assertj.core.util.Files;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@@ -39,6 +36,10 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.StringUtils;
import org.springframework.vault.core.VaultOperations;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
import static org.springframework.cloud.vault.util.Settings.findWorkDir;
/**
* Integration test using config infrastructure with Kubernetes authentication.
*
@@ -56,14 +57,15 @@ public class VaultConfigKubernetesTests {
String configValue;
@BeforeClass
public static void beforeClass() throws Exception {
public static void beforeClass() {
VaultRule vaultRule = new VaultRule();
vaultRule.before();
String minikubeIp = System.getProperty("MINIKUBE_IP");
assumeTrue(StringUtils.hasText(minikubeIp) && vaultRule.prepare().getVersion()
.isGreaterThanOrEqualTo(Version.parse("0.8.3")));
assumeTrue(StringUtils.hasText(minikubeIp)
&& vaultRule.prepare().getVersion()
.isGreaterThanOrEqualTo(Version.parse("0.8.3")));
if (!vaultRule.prepare().hasAuth("kubernetes")) {
vaultRule.prepare().mountAuth("kubernetes");
@@ -100,7 +102,6 @@ public class VaultConfigKubernetesTests {
roleData.put("policies", "testpolicy");
roleData.put("ttl", "1h");
vaultOperations.write("auth/kubernetes/role/my-role", roleData);
}
@Test

View File

@@ -1,73 +0,0 @@
#!/bin/bash
CMD_MINIKUBE=${1:-minikube}
CMD_KUBECTL=${2:-kubectl}
MINIKUBE_OPTS=${3:-}
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
if [ ! -d "work" ]; then
echo "work directory could not be found."
exit 1
fi
mkdir -p work/minikube
SERVICE_ACCOUNT_TOKEN_FILE=work/minikube/hello-minikube-token
SERVICE_ACCOUNT_CA_CRT=work/minikube/ca.crt
function is_cluster_running() {
local _running=$(${CMD_MINIKUBE} status | grep "cluster: Running" || true)
echo "$_running"
}
if [[ -z "$(is_cluster_running)" ]]; then
${CMD_MINIKUBE} start "${MINIKUBE_OPTS}"
while [[ -z "$(is_cluster_running)" ]]; do
echo "Wait for minikube cluster to be up"
sleep 1
done
fi
export MINIKUBE_IP=$(${CMD_MINIKUBE} ip)
echo "MINIKUBE_IP ${MINIKUBE_IP}"
# ensure kubectl context is not stale
${CMD_MINIKUBE} update-context
# https://kubernetes.io/docs/getting-started-guides/minikube/
${CMD_KUBECTL} run hello-minikube --image=gcr.io/google_containers/echoserver:1.4 --port=8080
${CMD_KUBECTL} expose deployment hello-minikube --type=NodePort
# Wait for service to be ready
echo "Wait for hello-minikube service to be ready"
HELLO_MINIKUBE_URL=$(${CMD_MINIKUBE} service hello-minikube --url --interval 5 --wait 120)
if [ $? != 0 ] ; then
echo "Error during service startup"
echo "In case of DNS problems try 'VBoxManage modifyvm minikube --natdnshostresolver1 on'"
# kubectl get pod -> STATUS: ContainerCreating
exit 1
fi
echo "HELLO_MINIKUBE_URL ${HELLO_MINIKUBE_URL}"
POD_NAME=$(${CMD_KUBECTL} get pod --selector=run=hello-minikube -o jsonpath='{.items..metadata.name}')
# Copy service account token
${CMD_KUBECTL} exec ${POD_NAME} -- cat /var/run/secrets/kubernetes.io/serviceaccount/token > ${SERVICE_ACCOUNT_TOKEN_FILE}
if [ $? != 0 ] ; then
echo "Error while retrieving service account token file"
exit 1
fi
# Copy ca cert
${CMD_KUBECTL} exec ${POD_NAME} -- cat /var/run/secrets/kubernetes.io/serviceaccount/ca.crt > ${SERVICE_ACCOUNT_CA_CRT}
if [ $? != 0 ] ; then
echo "Error while retrieving service account ca.crt"
exit 1
fi
#BASEDIR=`dirname $0`/../../..
#sh <(
#cat <<-EOF
#cd ${BASEDIR} && ${BASEDIR}/src/test/bash/env.sh
#vault auth-enable kubernetes
#vault write auth/kubernetes/config kubernetes_host=https://$(minikube ip):8443 kubernetes_ca_cert=@$HOME/.minikube/ca.crt
#EOF
#)