Skip to content

Commit

Permalink
Added VaultClientTokenSupplier
Browse files Browse the repository at this point in the history
  • Loading branch information
artem-v committed Apr 9, 2021
1 parent eade98b commit 5cbdb7d
Show file tree
Hide file tree
Showing 3 changed files with 198 additions and 43 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package io.scalecube.security.vault;

import static io.scalecube.utils.MaskUtil.mask;

import com.bettercloud.vault.VaultConfig;
import com.bettercloud.vault.VaultException;
import io.scalecube.config.utils.ThrowableUtil;
import io.scalecube.config.vault.EnvironmentVaultTokenSupplier;
import io.scalecube.config.vault.KubernetesVaultTokenSupplier;
import io.scalecube.config.vault.VaultTokenSupplier;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

public final class VaultClientTokenSupplier {

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

private String vaultAddress;
private String vaultToken;
private String vaultRole;

public VaultClientTokenSupplier() {}

private VaultClientTokenSupplier(VaultClientTokenSupplier other) {
this.vaultAddress = other.vaultAddress;
this.vaultToken = other.vaultToken;
this.vaultRole = other.vaultRole;
}

private VaultClientTokenSupplier copy() {
return new VaultClientTokenSupplier(this);
}

private void validate() {
if (isNullOrNoneOrEmpty(vaultAddress)) {
throw new IllegalArgumentException("Vault address is required");
}
if (isNullOrNoneOrEmpty(vaultToken) && isNullOrNoneOrEmpty(vaultRole)) {
throw new IllegalArgumentException(
"Vault auth scheme is required (specify either VAULT_ROLE or VAULT_TOKEN)");
}
}

/**
* Setter for vaultAddress.
*
* @param vaultAddress vaultAddress
* @return new instance with applied setting
*/
public VaultClientTokenSupplier vaultAddress(String vaultAddress) {
final VaultClientTokenSupplier c = copy();
c.vaultAddress = vaultAddress;
return c;
}

/**
* Setter for vaultToken.
*
* @param vaultToken vaultToken
* @return new instance with applied setting
*/
public VaultClientTokenSupplier vaultToken(String vaultToken) {
final VaultClientTokenSupplier c = copy();
c.vaultToken = vaultToken;
return c;
}

/**
* Setter for vaultRole.
*
* @param vaultRole vaultRole
* @return new instance with applied setting
*/
public VaultClientTokenSupplier vaultRole(String vaultRole) {
final VaultClientTokenSupplier c = copy();
c.vaultRole = vaultRole;
return c;
}

/**
* Obtains vault client token.
*
* @return vault client token
*/
public Mono<String> getToken() {
return Mono.fromRunnable(this::validate)
.then(Mono.fromCallable(this::getToken0))
.subscribeOn(Schedulers.boundedElastic())
.doOnSubscribe(s -> LOGGER.debug("[getToken] Getting vault client token"))
.doOnSuccess(s -> LOGGER.debug("[getToken][success] result: {}", mask(s)))
.doOnError(th -> LOGGER.error("[getToken][error] cause: {}", th.toString()));
}

private String getToken0() {
try {
VaultTokenSupplier vaultTokenSupplier;
VaultConfig vaultConfig;

if (!isNullOrNoneOrEmpty(vaultRole)) {
if (!isNullOrNoneOrEmpty(vaultToken)) {
LOGGER.warn(
"Taking KubernetesVaultTokenSupplier by precedence rule, "
+ "ignoring EnvironmentVaultTokenSupplier "
+ "(specify either VAULT_ROLE or VAULT_TOKEN, not both)");
}
vaultTokenSupplier = new KubernetesVaultTokenSupplier().vaultRole(vaultRole);
vaultConfig = new VaultConfig().address(vaultAddress).build();
} else {
vaultTokenSupplier = new EnvironmentVaultTokenSupplier();
vaultConfig = new VaultConfig().address(vaultAddress).token(vaultToken).build();
}

return vaultTokenSupplier.getToken(vaultConfig);
} catch (VaultException e) {
throw ThrowableUtil.propagate(e);
}
}

private static boolean isNullOrNoneOrEmpty(String value) {
return Objects.isNull(value)
|| "none".equalsIgnoreCase(value)
|| "null".equals(value)
|| value.isEmpty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ private VaultServiceRolesInstaller(VaultServiceRolesInstaller other) {
this.roleTtl = other.roleTtl;
}

private VaultServiceRolesInstaller copy() {
return new VaultServiceRolesInstaller(this);
}

/**
* Setter for vaultAddress.
*
Expand Down Expand Up @@ -156,8 +160,8 @@ public VaultServiceRolesInstaller roleTtl(String roleTtl) {
}

/**
* Reads {@code serviceRolesFileName (access-file.yaml)} and builds micro-infrastructure for
* machine-to-machine authentication in the vault.
* Reads {@code inputFileName} and builds vault oidc micro-infrastructure (identity roles and
* keys) to use it for machine-to-machine authentication.
*/
public void install() {
if (isNullOrNoneOrEmpty(vaultAddress)) {
Expand Down Expand Up @@ -259,10 +263,6 @@ private String buildVaultIdentityRoleUri(String roleName) {
.toString();
}

private VaultServiceRolesInstaller copy() {
return new VaultServiceRolesInstaller(this);
}

private static boolean isNullOrNoneOrEmpty(String value) {
return Objects.isNull(value)
|| "none".equalsIgnoreCase(value)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
package io.scalecube.security.vault;

import static io.scalecube.utils.MaskUtil.mask;

import com.bettercloud.vault.json.Json;
import com.bettercloud.vault.rest.Rest;
import com.bettercloud.vault.rest.RestException;
import com.bettercloud.vault.rest.RestResponse;
import io.scalecube.utils.MaskUtil;
import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.function.BiFunction;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.Exceptions;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

public final class VaultServiceTokenSupplier {

Expand All @@ -22,7 +24,7 @@ public final class VaultServiceTokenSupplier {

private String serviceRole;
private String vaultAddress;
private Supplier<String> vaultTokenSupplier;
private Mono<String> vaultTokenSupplier;
private BiFunction<String, Map<String, String>, String> serviceTokenNameBuilder;

public VaultServiceTokenSupplier() {}
Expand All @@ -34,6 +36,18 @@ private VaultServiceTokenSupplier(VaultServiceTokenSupplier other) {
this.serviceTokenNameBuilder = other.serviceTokenNameBuilder;
}

private VaultServiceTokenSupplier copy() {
return new VaultServiceTokenSupplier(this);
}

private void validate() {
Objects.requireNonNull(serviceRole, "VaultServiceTokenSupplier.serviceRole");
Objects.requireNonNull(vaultAddress, "VaultServiceTokenSupplier.vaultAddress");
Objects.requireNonNull(vaultTokenSupplier, "VaultServiceTokenSupplier.vaultTokenSupplier");
Objects.requireNonNull(
serviceTokenNameBuilder, "VaultServiceTokenSupplier.serviceTokenNameBuilder");
}

/**
* Setter for serviceRole.
*
Expand Down Expand Up @@ -64,7 +78,7 @@ public VaultServiceTokenSupplier vaultAddress(String vaultAddress) {
* @param vaultTokenSupplier vaultTokenSupplier
* @return new instance with applied setting
*/
public VaultServiceTokenSupplier vaultTokenSupplier(Supplier<String> vaultTokenSupplier) {
public VaultServiceTokenSupplier vaultTokenSupplier(Mono<String> vaultTokenSupplier) {
final VaultServiceTokenSupplier c = copy();
c.vaultTokenSupplier = vaultTokenSupplier;
return c;
Expand All @@ -85,59 +99,72 @@ public VaultServiceTokenSupplier serviceTokenNameBuilder(
}

/**
* Returns credentials as {@code Map<String, String>} for the given args.
* Obtains vault service token (aka identity token or oidc token).
*
* @param tags tags attributes
* @param tags tags attributes; along with {@code serviceRole} will be applied on {@code
* serviceTokenNameBuilder}
* @return vault service token
*/
public Mono<String> getServiceToken(Map<String, String> tags) {
return Mono.fromCallable(vaultTokenSupplier::get)
.map(vaultToken -> rpcGetServiceToken(tags, vaultToken))
.doOnNext(response -> verifyOk(response.getStatus()))
.map(
response ->
Json.parse(new String(response.getBody()))
.asObject()
.get("data")
.asObject()
.get("token")
.asString())
.doOnSuccess(
creds ->
LOGGER.info(
"[rpcGetServiceToken] Successfully obtained vault service token: {}",
MaskUtil.mask(creds)));
public Mono<String> getToken(Map<String, String> tags) {
return Mono.fromRunnable(this::validate)
.then(Mono.defer(() -> vaultTokenSupplier))
.flatMap(
vaultToken -> {
final String uri = buildServiceTokenUri(tags);
return Mono.fromCallable(() -> rpcGetToken(uri, vaultToken))
.subscribeOn(Schedulers.boundedElastic())
.doOnSubscribe(
s ->
LOGGER.debug(
"[getToken] Getting vault service token, uri='{}', tags={}",
uri,
tags))
.doOnSuccess(
s ->
LOGGER.debug(
"[getToken][success] uri='{}', tags={}, result: {}",
uri,
tags,
mask(s)))
.doOnError(
th ->
LOGGER.error(
"[getToken][error] uri='{}', tags={}, cause: {}",
uri,
tags,
th.toString()));
});
}

private RestResponse rpcGetServiceToken(Map<String, String> tags, String vaultToken) {
String uri = buildVaultServiceTokenUri(tags);
LOGGER.info("[rpcGetServiceToken] Getting vault service token (uri='{}')", uri);
private String rpcGetToken(String uri, String vaultToken) {
try {
return new Rest().header(VAULT_TOKEN_HEADER, vaultToken).url(uri).get();
final RestResponse response =
new Rest().header(VAULT_TOKEN_HEADER, vaultToken).url(uri).get();

verifyOk(response.getStatus());

return Json.parse(new String(response.getBody()))
.asObject()
.get("data")
.asObject()
.get("token")
.asString();
} catch (RestException e) {
LOGGER.error(
"[rpcGetServiceToken] Failed to get vault service token (uri='{}'), cause: {}",
uri,
e.toString());
throw Exceptions.propagate(e);
}
}

private static void verifyOk(int status) {
if (status != 200) {
LOGGER.error("[rpcGetServiceToken] Not expected status ({}) returned", status);
LOGGER.error("[rpcGetToken] Not expected status ({}) returned", status);
throw new IllegalStateException("Not expected status returned, status=" + status);
}
}

private String buildVaultServiceTokenUri(Map<String, String> tags) {
private String buildServiceTokenUri(Map<String, String> tags) {
return new StringJoiner("/", vaultAddress, "")
.add("v1/identity/oidc/token")
.add(serviceTokenNameBuilder.apply(serviceRole, tags))
.toString();
}

private VaultServiceTokenSupplier copy() {
return new VaultServiceTokenSupplier(this);
}
}

0 comments on commit 5cbdb7d

Please sign in to comment.