Skip to content

Commit

Permalink
Merge pull request #211 from scalecube/enh1
Browse files Browse the repository at this point in the history
Cosmetic changes. Key changes - VaultClientTokenSupplier.getToken()
  • Loading branch information
artem-v authored Jan 27, 2025
2 parents ceea40e + 36fe859 commit b8e7b5f
Show file tree
Hide file tree
Showing 6 changed files with 74 additions and 65 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
public class EnvironmentVaultTokenSupplier implements VaultTokenSupplier {

public String getToken(VaultConfig config) {
return Objects.requireNonNull(config.getToken(), "vault token");
return Objects.requireNonNull(config.getToken(), "VaultConfig.token is missing");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,10 @@ private KubernetesVaultTokenSupplier(Builder builder) {
public String getToken(VaultConfig config) {
try (Stream<String> stream = Files.lines(Paths.get(serviceAccountTokenPath))) {
String jwt = stream.collect(Collectors.joining());
return Objects.requireNonNull(
new Vault(config)
.auth()
.loginByJwt(vaultJwtProvider, vaultRole, jwt)
.getAuthClientToken(),
"vault token");
return new Vault(config)
.auth()
.loginByJwt(vaultJwtProvider, vaultRole, jwt)
.getAuthClientToken();
} catch (Exception e) {
throw ThrowableUtil.propagate(e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import com.bettercloud.vault.VaultException;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -20,8 +19,8 @@ public class VaultClientTokenSupplier {
* Constructor.
*
* @param vaultAddress vaultAddress
* @param vaultToken vaultToken (must not set be together with vaultRole)
* @param vaultRole vaultRole (must not set be together with vaultToken)
* @param vaultToken vaultToken (must not set be together with {@code vaultRole})
* @param vaultRole vaultRole (must not set be together with {@code vaultToken})
*/
public VaultClientTokenSupplier(String vaultAddress, String vaultToken, String vaultRole) {
this.vaultAddress = vaultAddress;
Expand Down Expand Up @@ -63,11 +62,7 @@ public static VaultClientTokenSupplier supplierByRole(String vaultAddress, Strin
*
* @return future result
*/
public Future<String> getToken() {
return CompletableFuture.supplyAsync(this::getToken0);
}

private String getToken0() {
public CompletableFuture<String> getToken() {
try {
VaultTokenSupplier vaultTokenSupplier;
VaultConfig vaultConfig;
Expand All @@ -87,7 +82,7 @@ private String getToken0() {
vaultConfig = new VaultConfig().address(vaultAddress).token(vaultToken).build();
}

return vaultTokenSupplier.getToken(vaultConfig);
return CompletableFuture.supplyAsync(() -> vaultTokenSupplier.getToken(vaultConfig));
} catch (VaultException e) {
throw new RuntimeException(e);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package io.scalecube.config.vault;

import static io.scalecube.config.vault.VaultInvoker.STATUS_CODE_NOT_FOUND;

import com.bettercloud.vault.EnvironmentLoader;
import com.bettercloud.vault.VaultConfig;
import com.bettercloud.vault.VaultException;
Expand All @@ -11,7 +13,6 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
Expand All @@ -33,7 +34,6 @@ public class VaultConfigSource implements ConfigSource {
private static final Logger LOGGER = LoggerFactory.getLogger(VaultConfigSource.class);

private static final EnvironmentLoader ENVIRONMENT_LOADER = new EnvironmentLoader();

private static final String PATHS_SEPARATOR = ":";

private final VaultInvoker vault;
Expand All @@ -46,7 +46,7 @@ private VaultConfigSource(VaultInvoker vault, Collection<String> secretsPaths) {

@Override
public Map<String, ConfigProperty> loadConfig() {
Map<String, ConfigProperty> result = new HashMap<>();
Map<String, ConfigProperty> propertyMap = new HashMap<>();
for (String path : secretsPaths) {
try {
LogicalResponse response = vault.invoke(vault -> vault.logical().read(path));
Expand All @@ -55,9 +55,9 @@ public Map<String, ConfigProperty> loadConfig() {
.map(LoadedConfigProperty::withNameAndValue)
.map(LoadedConfigProperty.Builder::build)
.collect(Collectors.toMap(LoadedConfigProperty::name, Function.identity()));
result.putAll(pathProps);
propertyMap.putAll(pathProps);
} catch (VaultException ex) {
if (ex.getHttpStatusCode() == 404) {
if (ex.getHttpStatusCode() == STATUS_CODE_NOT_FOUND) {
LOGGER.error("Unable to load config properties from: {}", path);
} else {
throw new ConfigSourceNotAvailableException(ex);
Expand All @@ -67,13 +67,12 @@ public Map<String, ConfigProperty> loadConfig() {
throw new ConfigSourceNotAvailableException(ex);
}
}
return result;
return propertyMap;
}

public static final class Builder {

private Function<VaultInvoker.Builder, VaultInvoker.Builder> builderFunction =
Function.identity();
private Function<VaultInvoker.Builder, VaultInvoker.Builder> builderFunction = b -> b;

private VaultInvoker invoker;

Expand All @@ -89,37 +88,21 @@ public static final class Builder {
public Builder() {}

/**
* Appends {@code secretsPath} to {@code secretsPaths}.
*
* @param secretsPath secretsPath (may contain value with paths separated by {@code :})
* @return this builder
* @deprecated will be removed in future releases without notice, use {@link
* #addSecretsPath(String...)} or {@link #secretsPaths(Collection)}.
*/
@Deprecated
public Builder secretsPath(String secretsPath) {
this.secretsPaths.addAll(toSecretsPaths(Collections.singletonList(secretsPath)));
return this;
}

/**
* Appends one or several secretsPath\es to {@code secretsPaths}.
* Appends secrets paths (each path value may contain values separated by colons).
*
* @param secretsPath one or several secretsPath\es (each value may contain paths separated by
* {@code :})
* @return this builder
* @param secretsPath secretsPath
* @return this
*/
public Builder addSecretsPath(String... secretsPath) {
this.secretsPaths.addAll(toSecretsPaths(Arrays.asList(secretsPath)));
secretsPaths.addAll(toSecretsPaths(Arrays.asList(secretsPath)));
return this;
}

/**
* Setter for {@code secretsPaths}.
* Setter for secrets paths (each path value may contain values separated by colons).
*
* @param secretsPaths collection of secretsPath\es (each value may contain paths separated by
* colon)
* @return this builder
* @param secretsPaths secretsPaths
* @return this
*/
public Builder secretsPaths(Collection<String> secretsPaths) {
this.secretsPaths = toSecretsPaths(secretsPaths);
Expand All @@ -132,31 +115,50 @@ private static Set<String> toSecretsPaths(Collection<String> secretsPaths) {
.collect(Collectors.toSet());
}

public Builder invoker(VaultInvoker invoker) {
this.invoker = invoker;
/**
* Setter for {@link VaultInvoker}.
*
* @param vaultInvoker vaultInvoker
* @return this
*/
public Builder invoker(VaultInvoker vaultInvoker) {
this.invoker = vaultInvoker;
return this;
}

public Builder vault(UnaryOperator<VaultInvoker.Builder> opts) {
this.builderFunction = this.builderFunction.andThen(opts);
/**
* Setter for {@link VaultInvoker.Builder} operator.
*
* @param operator operator for {@link VaultInvoker.Builder}
* @return this
*/
public Builder vault(UnaryOperator<VaultInvoker.Builder> operator) {
this.builderFunction = this.builderFunction.andThen(operator);
return this;
}

/**
* Setter for {@link VaultConfig}.
*
* @param vaultConfig vaultConfig
* @return this
*/
public Builder config(UnaryOperator<VaultConfig> vaultConfig) {
this.builderFunction = this.builderFunction.andThen(b -> b.options(vaultConfig));
return this;
}

public Builder tokenSupplier(VaultTokenSupplier supplier) {
this.builderFunction = this.builderFunction.andThen(b -> b.tokenSupplier(supplier));
return this;
}

/**
* Builds vault config source.
* Setter for {@link VaultTokenSupplier}.
*
* @return instance of {@link VaultConfigSource}
* @param tokenSupplier tokenSupplier
* @return this
*/
public Builder tokenSupplier(VaultTokenSupplier tokenSupplier) {
this.builderFunction = this.builderFunction.andThen(b -> b.tokenSupplier(tokenSupplier));
return this;
}

public VaultConfigSource build() {
return new VaultConfigSource(
invoker != null ? invoker : builderFunction.apply(new VaultInvoker.Builder()).build(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ public class VaultInvoker {

private static final Logger LOGGER = LoggerFactory.getLogger(VaultInvoker.class);

private static final int STATUS_CODE_FORBIDDEN = 403;
public static final int STATUS_CODE_FORBIDDEN = 403;
public static final int STATUS_CODE_NOT_FOUND = 404;
public static final int STATUS_CODE_HEALTH_OK = 200;
public static final int STATUS_CODE_RESPONSE_OK = 200;
public static final int STATUS_CODE_RESPONSE_NO_DATA = 204;
Expand Down Expand Up @@ -173,16 +174,17 @@ private void checkResponse(RestResponse restResponse) throws VaultException {
* We should refresh tokens from Vault before they expire, so we add a MIN_REFRESH_MARGIN margin.
* If the token is valid for less than MIN_REFRESH_MARGIN * 2, we use duration / 2 instead.
*/
private long suggestedRefreshInterval(long duration) {
private static long suggestedRefreshInterval(long duration) {
return duration < MIN_REFRESH_MARGIN * 2 ? duration / 2 : duration - MIN_REFRESH_MARGIN;
}

private String bodyAsString(RestResponse response) {
private static String bodyAsString(RestResponse response) {
return new String(response.getBody(), StandardCharsets.UTF_8);
}

@FunctionalInterface
public interface VaultCall<T extends VaultResponse> {

T apply(Vault vault) throws VaultException;
}

Expand Down Expand Up @@ -213,13 +215,25 @@ public static class Builder {

public Builder() {}

public Builder options(UnaryOperator<VaultConfig> config) {
this.options = this.options.andThen(config);
/**
* Setter for {@link VaultConfig} operator.
*
* @param operator operator for {@link VaultConfig}
* @return this
*/
public Builder options(UnaryOperator<VaultConfig> operator) {
options = options.andThen(operator);
return this;
}

/**
* Setter for {@link VaultTokenSupplier}.
*
* @param supplier vault token supplier
* @return this
*/
public Builder tokenSupplier(VaultTokenSupplier supplier) {
this.tokenSupplier = supplier;
tokenSupplier = supplier;
return this;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ void shouldWorkWhenRegistryIsReloadedAndVaultIsUnSealed() throws InterruptedExce
"vault",
new VaultConfigSource.Builder()
.config(vaultConfig -> vaultConfig.address(address).token(rootToken))
.secretsPath(VAULT_SECRETS_PATH1)
.addSecretsPath(VAULT_SECRETS_PATH1)
.build())
.jmxEnabled(false)
.reloadIntervalSec(1)
Expand Down

0 comments on commit b8e7b5f

Please sign in to comment.