#5 Role and Secret creation implemented and tested

This commit is contained in:
2016-11-04 23:02:36 +01:00
parent c7b4c46ad2
commit 40742b00de
21 changed files with 1447 additions and 76 deletions

View File

@ -19,8 +19,7 @@ package de.stklcode.jvault.connector;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.stklcode.jvault.connector.exception.*;
import de.stklcode.jvault.connector.model.AuthBackend;
import de.stklcode.jvault.connector.model.Token;
import de.stklcode.jvault.connector.model.*;
import de.stklcode.jvault.connector.model.response.*;
import de.stklcode.jvault.connector.model.response.embedded.AuthMethod;
import org.apache.http.HttpResponse;
@ -44,24 +43,25 @@ import java.util.stream.Collectors;
/**
* Vault Connector implementatin using Vault's HTTP API.
*
* @author Stefan Kalscheuer
* @since 0.1
* @author Stefan Kalscheuer
* @since 0.1
*/
public class HTTPVaultConnector implements VaultConnector {
private static final String PATH_PREFIX = "/v1/";
private static final String PATH_SEAL_STATUS = "sys/seal-status";
private static final String PATH_SEAL = "sys/seal";
private static final String PATH_UNSEAL = "sys/unseal";
private static final String PATH_INIT = "sys/init";
private static final String PATH_AUTH = "sys/auth";
private static final String PATH_TOKEN = "auth/token";
private static final String PATH_LOOKUP = "/lookup";
private static final String PATH_CREATE = "/create";
private static final String PATH_PREFIX = "/v1/";
private static final String PATH_SEAL_STATUS = "sys/seal-status";
private static final String PATH_SEAL = "sys/seal";
private static final String PATH_UNSEAL = "sys/unseal";
private static final String PATH_INIT = "sys/init";
private static final String PATH_AUTH = "sys/auth";
private static final String PATH_TOKEN = "auth/token";
private static final String PATH_LOOKUP = "/lookup";
private static final String PATH_CREATE = "/create";
private static final String PATH_CREATE_ORPHAN = "/create-orphan";
private static final String PATH_AUTH_USERPASS = "auth/userpass/login/";
private static final String PATH_AUTH_APPID = "auth/app-id/";
private static final String PATH_SECRET = "secret";
private static final String PATH_REVOKE = "sys/revoke/";
private static final String PATH_AUTH_APPID = "auth/app-id/";
private static final String PATH_AUTH_APPROLE = "auth/approle/";
private static final String PATH_SECRET = "secret";
private static final String PATH_REVOKE = "sys/revoke/";
private final ObjectMapper jsonMapper;
@ -74,8 +74,8 @@ public class HTTPVaultConnector implements VaultConnector {
/**
* Create connector using hostname and schema.
*
* @param hostname The hostname
* @param useTLS If TRUE, use HTTPS, otherwise HTTP
* @param hostname The hostname
* @param useTLS If TRUE, use HTTPS, otherwise HTTP
*/
public HTTPVaultConnector(String hostname, boolean useTLS) {
this(hostname, useTLS, null);
@ -84,9 +84,9 @@ public class HTTPVaultConnector implements VaultConnector {
/**
* Create connector using hostname, schema and port.
*
* @param hostname The hostname
* @param useTLS If TRUE, use HTTPS, otherwise HTTP
* @param port The port
* @param hostname The hostname
* @param useTLS If TRUE, use HTTPS, otherwise HTTP
* @param port The port
*/
public HTTPVaultConnector(String hostname, boolean useTLS, Integer port) {
this(hostname, useTLS, port, PATH_PREFIX);
@ -95,10 +95,10 @@ public class HTTPVaultConnector implements VaultConnector {
/**
* Create connector using hostname, schame, port and path.
*
* @param hostname The hostname
* @param useTLS If TRUE, use HTTPS, otherwise HTTP
* @param port The port
* @param prefix HTTP API prefix (default: /v1/"
* @param hostname The hostname
* @param useTLS If TRUE, use HTTPS, otherwise HTTP
* @param port The port
* @param prefix HTTP API prefix (default: /v1/"
*/
public HTTPVaultConnector(String hostname, boolean useTLS, Integer port, String prefix) {
this(((useTLS) ? "https" : "http") +
@ -110,7 +110,7 @@ public class HTTPVaultConnector implements VaultConnector {
/**
* Create connector using full URL.
*
* @param baseURL The URL
* @param baseURL The URL
*/
public HTTPVaultConnector(String baseURL) {
this.baseURL = baseURL;
@ -207,31 +207,40 @@ public class HTTPVaultConnector implements VaultConnector {
@Override
public AuthResponse authUserPass(final String username, final String password) throws VaultConnectorException {
Map<String, String> payload = new HashMap<>();
final Map<String, String> payload = new HashMap<>();
payload.put("password", password);
try {
/* Get response */
String response = requestPost(PATH_AUTH_USERPASS + username, payload);
/* Parse response */
AuthResponse upr = jsonMapper.readValue(response, AuthResponse.class);
/* verify response */
this.token = upr.getAuth().getClientToken();
this.tokenTTL = System.currentTimeMillis() + upr.getAuth().getLeaseDuration() * 1000L;
this.authorized = true;
return upr;
} catch (IOException e) {
throw new InvalidResponseException("Unable to parse response", e);
}
return queryAuth(PATH_AUTH_USERPASS + username, payload);
}
@Override
public AuthResponse authAppId(final String appID, final String userID) throws VaultConnectorException {
Map<String, String> payload = new HashMap<>();
final Map<String, String> payload = new HashMap<>();
payload.put("app_id", appID);
payload.put("user_id", userID);
return queryAuth(PATH_AUTH_APPID + "login", payload);
}
@Override
public AuthResponse authAppRole(final String roleID, final String secretID) throws VaultConnectorException {
final Map<String, String> payload = new HashMap<>();
payload.put("role_id", roleID);
if (secretID != null)
payload.put("secret_id", secretID);
return queryAuth(PATH_AUTH_APPROLE + "login", payload);
}
/**
* Query authorization request to given backend
*
* @param path The path to request
* @param payload Payload (credentials)
* @return The AuthResponse
* @throws VaultConnectorException on errors
*/
private AuthResponse queryAuth(final String path, final Map<String, String> payload) throws VaultConnectorException {
try {
/* Get response */
String response = requestPost(PATH_AUTH_APPID + "login", payload);
String response = requestPost(path, payload);
/* Parse response */
AuthResponse auth = jsonMapper.readValue(response, AuthResponse.class);
/* verify response */
@ -273,6 +282,162 @@ public class HTTPVaultConnector implements VaultConnector {
return true;
}
@Override
public boolean createAppRole(final AppRole role) throws VaultConnectorException {
if (!isAuthorized())
throw new AuthorizationRequiredException();
/* Get response */
String response = requestPost(PATH_AUTH_APPROLE + "role/" + role.getName(), role);
/* Response should be code 204 without content */
if (!response.equals(""))
throw new InvalidResponseException("Received response where non was expected.");
/* Set custom ID if provided */
return !(role.getId() != null && !role.getId().isEmpty()) || setAppRoleID(role.getName(), role.getId());
}
@Override
public AppRoleResponse lookupAppRole(final String roleName) throws VaultConnectorException {
if (!isAuthorized())
throw new AuthorizationRequiredException();
/* Request HTTP response and parse Secret */
try {
String response = requestGet(PATH_AUTH_APPROLE + "role/" + roleName, new HashMap<>());
return jsonMapper.readValue(response, AppRoleResponse.class);
} catch (IOException e) {
throw new InvalidResponseException("Unable to parse response", e);
} catch (URISyntaxException ignored) {
/* this should never occur and may leak sensible information */
throw new InvalidRequestException("Invalid URI format.");
}
}
@Override
public boolean deleteAppRole(String roleName) throws VaultConnectorException {
if (!isAuthorized())
throw new AuthorizationRequiredException();
/* Request HTTP response and expect empty result */
String response = requestDelete(PATH_AUTH_APPROLE + "role/" + roleName);
/* Response should be code 204 without content */
if (!response.equals(""))
throw new InvalidResponseException("Received response where non was expected.");
return true;
}
@Override
public String getAppRoleID(final String roleName) throws VaultConnectorException {
if (!isAuthorized())
throw new AuthorizationRequiredException();
/* Request HTTP response and parse Secret */
try {
String response = requestGet(PATH_AUTH_APPROLE + "role/" + roleName + "/role-id", new HashMap<>());
return jsonMapper.readValue(response, RawDataResponse.class).getData().get("role_id").toString();
} catch (IOException e) {
throw new InvalidResponseException("Unable to parse response", e);
} catch (URISyntaxException ignored) {
/* this should never occur and may leak sensible information */
throw new InvalidRequestException("Invalid URI format.");
}
}
@Override
public boolean setAppRoleID(final String roleName, final String roleID) throws VaultConnectorException {
if (!isAuthorized())
throw new AuthorizationRequiredException();
/* Request HTTP response and parse Secret */
Map<String, String> payload = new HashMap<>();
payload.put("role_id", roleID);
String response = requestPost(PATH_AUTH_APPROLE + "role/" + roleName + "/role-id", payload);
/* Response should be code 204 without content */
if (!response.equals(""))
throw new InvalidResponseException("Received response where non was expected.");
return true;
}
@Override
public AppRoleSecretResponse createAppRoleSecret(final String roleName, final AppRoleSecret secret) throws VaultConnectorException {
if (!isAuthorized())
throw new AuthorizationRequiredException();
/* Get response */
String response;
if (secret.getId() != null && !secret.getId().isEmpty())
response = requestPost(PATH_AUTH_APPROLE + "role/" + roleName + "/custom-secret-id", secret);
else
response = requestPost(PATH_AUTH_APPROLE + "role/" + roleName + "/secret-id", secret);
try {
/* Extract the secret ID from response */
return jsonMapper.readValue(response, AppRoleSecretResponse.class);
} catch (IOException e) {
throw new InvalidResponseException("Unable to parse response.");
}
}
@Override
public AppRoleSecretResponse lookupAppRoleSecret(final String roleName, final String secretID) throws VaultConnectorException {
if (!isAuthorized())
throw new AuthorizationRequiredException();
/* Request HTTP response and parse Secret */
try {
String response = requestPost(PATH_AUTH_APPROLE + "role/" + roleName + "/secret-id/lookup", new AppRoleSecret(secretID));
return jsonMapper.readValue(response, AppRoleSecretResponse.class);
} catch (IOException e) {
throw new InvalidResponseException("Unable to parse response", e);
}
}
@Override
public boolean destroyAppRoleSecret(final String roleName, final String secretID) throws VaultConnectorException {
if (!isAuthorized())
throw new AuthorizationRequiredException();
/* Request HTTP response and expect empty result */
String response = requestPost(PATH_AUTH_APPROLE + "role/" + roleName + "/secret-id/destroy", new AppRoleSecret(secretID));
/* Response should be code 204 without content */
if (!response.equals(""))
throw new InvalidResponseException("Received response where non was expected.");
return true;
}
@Override
public List<String> listAppRoles() throws VaultConnectorException {
if (!isAuthorized())
throw new AuthorizationRequiredException();
try {
String response = requestGet(PATH_AUTH_APPROLE + "role?list=true", new HashMap<>());
SecretListResponse secrets = jsonMapper.readValue(response, SecretListResponse.class);
return secrets.getKeys();
} catch (IOException e) {
throw new InvalidResponseException("Unable to parse response", e);
} catch (URISyntaxException ignored) {
/* this should never occur and may leak sensible information */
throw new InvalidRequestException("Invalid URI format.");
}
}
@Override
public List<String> listAppRoleSecretss(final String roleName) throws VaultConnectorException {
if (!isAuthorized())
throw new AuthorizationRequiredException();
try {
String response = requestGet(PATH_AUTH_APPROLE + "role/" + roleName + "/secret-id?list=true", new HashMap<>());
SecretListResponse secrets = jsonMapper.readValue(response, SecretListResponse.class);
return secrets.getKeys();
} catch (IOException e) {
throw new InvalidResponseException("Unable to parse response", e);
} catch (URISyntaxException ignored) {
/* this should never occur and may leak sensible information */
throw new InvalidRequestException("Invalid URI format.");
}
}
@Override
public SecretResponse readSecret(final String key) throws VaultConnectorException {
if (!isAuthorized())
@ -400,10 +565,10 @@ public class HTTPVaultConnector implements VaultConnector {
/**
* Execute HTTP request using POST method.
*
* @param path URL path (relative to base)
* @param payload Map of payload values (will be converted to JSON)
* @return HTTP response
* @throws VaultConnectorException on connection error
* @param path URL path (relative to base)
* @param payload Map of payload values (will be converted to JSON)
* @return HTTP response
* @throws VaultConnectorException on connection error
*/
private String requestPost(final String path, final Object payload) throws VaultConnectorException {
/* Initialize post */
@ -428,10 +593,10 @@ public class HTTPVaultConnector implements VaultConnector {
/**
* Execute HTTP request using PUT method.
*
* @param path URL path (relative to base)
* @param payload Map of payload values (will be converted to JSON)
* @return HTTP response
* @throws VaultConnectorException on connection error
* @param path URL path (relative to base)
* @param payload Map of payload values (will be converted to JSON)
* @return HTTP response
* @throws VaultConnectorException on connection error
*/
private String requestPut(final String path, final Map<String, String> payload) throws VaultConnectorException {
/* Initialize put */
@ -455,9 +620,9 @@ public class HTTPVaultConnector implements VaultConnector {
/**
* Execute HTTP request using DELETE method.
*
* @param path URL path (relative to base)
* @return HTTP response
* @throws VaultConnectorException on connection error
* @param path URL path (relative to base)
* @return HTTP response
* @throws VaultConnectorException on connection error
*/
private String requestDelete(final String path) throws VaultConnectorException {
/* Initialize delete */
@ -472,10 +637,10 @@ public class HTTPVaultConnector implements VaultConnector {
/**
* Execute HTTP request using GET method.
*
* @param path URL path (relative to base)
* @param payload Map of payload values (will be converted to JSON)
* @param path URL path (relative to base)
* @param payload Map of payload values (will be converted to JSON)
* @return HTTP response
* @throws VaultConnectorException on connection error
* @throws VaultConnectorException on connection error
*/
private String requestGet(final String path, final Map<String, String> payload) throws VaultConnectorException, URISyntaxException {
/* Add parameters to URI */
@ -495,9 +660,9 @@ public class HTTPVaultConnector implements VaultConnector {
/**
* Execute prepared HTTP request and return result.
*
* @param base Prepares Request
* @return HTTP response
* @throws VaultConnectorException on connection error
* @param base Prepares Request
* @return HTTP response
* @throws VaultConnectorException on connection error
*/
private String request(HttpRequestBase base) throws VaultConnectorException {
/* Set JSON Header */
@ -512,9 +677,10 @@ public class HTTPVaultConnector implements VaultConnector {
switch (response.getStatusLine().getStatusCode()) {
case 200:
try(BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
return br.lines().collect(Collectors.joining("\n"));
} catch (IOException ignored) { }
} catch (IOException ignored) {
}
case 204:
return "";
case 403:
@ -537,8 +703,7 @@ public class HTTPVaultConnector implements VaultConnector {
}
} catch (IOException e) {
throw new InvalidResponseException("Unable to read response", e);
}
finally {
} finally {
if (response != null && response.getEntity() != null)
try {
EntityUtils.consume(response.getEntity());

View File

@ -17,10 +17,10 @@
package de.stklcode.jvault.connector;
import de.stklcode.jvault.connector.exception.VaultConnectorException;
import de.stklcode.jvault.connector.model.AuthBackend;
import de.stklcode.jvault.connector.model.Token;
import de.stklcode.jvault.connector.model.*;
import de.stklcode.jvault.connector.model.response.*;
import java.util.ArrayList;
import java.util.List;
/**
@ -110,9 +110,34 @@ public interface VaultConnector {
* @param userID The User ID
* @return TRUE on success
* @throws VaultConnectorException on error
* @deprecated As of Vault 0.6.1 App-ID is superseded by AppRole. Consider using {@link #authAppRole} instead.
*/
@Deprecated
AuthResponse authAppId(final String appID, final String userID) throws VaultConnectorException;
/**
* Authorize to Vault using AppRole method without secret ID.
*
* @param roleID The role ID
* @return TRUE on success
* @throws VaultConnectorException on error
* @since 0.4.0
*/
default AuthResponse authAppRole(final String roleID) throws VaultConnectorException {
return authAppRole(roleID, null);
}
/**
* Authorize to Vault using AppRole method.
*
* @param roleID The role ID
* @param secretID The secret ID
* @return TRUE on success
* @throws VaultConnectorException on error
* @since 0.4.0
*/
AuthResponse authAppRole(final String roleID, final String secretID) throws VaultConnectorException;
/**
* Register new App-ID with policy.
*
@ -121,9 +146,188 @@ public interface VaultConnector {
* @param displayName Arbitrary name to display
* @return TRUE on success
* @throws VaultConnectorException on error
* @deprecated As of Vault 0.6.1 App-ID is superseded by AppRole. Consider using {@link #createAppRole} instead.
*/
@Deprecated
boolean registerAppId(final String appID, final String policy, final String displayName) throws VaultConnectorException;
/**
* Register a new AppRole role from given metamodel.
*
* @param role The role
* @return TRUE on success
* @throws VaultConnectorException on error
* @since 0.4.0
*/
boolean createAppRole(final AppRole role) throws VaultConnectorException;
/**
* Register new AppRole role with default policy.
*
* @param roleName The role name
* @return TRUE on success
* @throws VaultConnectorException on error
* @since 0.4.0
*/
default boolean createAppRole(final String roleName) throws VaultConnectorException {
return createAppRole(roleName, new ArrayList<>());
}
/**
* Register new AppRole role with policies.
*
* @param roleName The role name
* @param policies The policies to associate with
* @return TRUE on success
* @throws VaultConnectorException on error
* @since 0.4.0
*/
default boolean createAppRole(final String roleName, final List<String> policies) throws VaultConnectorException {
return createAppRole(roleName, policies, null);
}
/**
* Register new AppRole role with default policy and custom ID.
*
* @param roleName The role name
* @param roleID A custom role ID
* @return TRUE on success
* @throws VaultConnectorException on error
* @since 0.4.0
*/
default boolean createAppRole(final String roleName, final String roleID) throws VaultConnectorException {
return createAppRole(roleName, new ArrayList<>(), roleID);
}
/**
* Register new AppRole role with policies and custom ID.
*
* @param roleName The role name
* @param policies The policies to associate with
* @param roleID A custom role ID
* @return TRUE on success
* @throws VaultConnectorException on error
* @since 0.4.0
*/
default boolean createAppRole(final String roleName, final List<String> policies, final String roleID) throws VaultConnectorException {
return createAppRole(new AppRoleBuilder(roleName).withPolicies(policies).withId(roleID).build());
}
/**
* Delete AppRole role from Vault.
*
* @param roleName The role anme
* @return TRUE on succevss
* @throws VaultConnectorException on error
*/
boolean deleteAppRole(final String roleName) throws VaultConnectorException;
/**
* Lookup an AppRole role.
*
* @param roleName The role name
* @return Result of the lookup
* @throws VaultConnectorException on error
* @since 0.4.0
*/
AppRoleResponse lookupAppRole(final String roleName) throws VaultConnectorException;
/**
* Retrieve ID for an AppRole role.
*
* @param roleName The role name
* @return The role ID
* @throws VaultConnectorException on error
* @since 0.4.0
*/
String getAppRoleID(final String roleName) throws VaultConnectorException;
/**
* Set custom ID for an AppRole role.
*
* @param roleName The role name
* @param roleID The role ID
* @return TRUE on success
* @throws VaultConnectorException on error
* @since 0.4.0
*/
boolean setAppRoleID(final String roleName, final String roleID) throws VaultConnectorException;
/**
* Register new random generated AppRole secret.
*
* @param roleName The role name
* @return The secret ID
* @throws VaultConnectorException on error
* @since 0.4.0
*/
default AppRoleSecretResponse createAppRoleSecret(final String roleName) throws VaultConnectorException {
return createAppRoleSecret(roleName, new AppRoleSecret());
}
/**
* Register new AppRole secret with custom ID.
*
* @param roleName The role name
* @param secretID A custom secret ID
* @return The secret ID
* @throws VaultConnectorException on error
* @since 0.4.0
*/
default AppRoleSecretResponse createAppRoleSecret(final String roleName, final String secretID) throws VaultConnectorException {
return createAppRoleSecret(roleName, new AppRoleSecret(secretID));
}
/**
* Register new AppRole secret with custom ID.
*
* @param roleName The role name
* @param secret The secret meta object
* @return The secret ID
* @throws VaultConnectorException on error
* @since 0.4.0
*/
AppRoleSecretResponse createAppRoleSecret(final String roleName, final AppRoleSecret secret) throws VaultConnectorException;
/**
* Lookup an AppRole secret.
*
* @param roleName The role name
* @param secretID The secret ID
* @return Result of the lookup
* @throws VaultConnectorException on error
* @since 0.4.0
*/
AppRoleSecretResponse lookupAppRoleSecret(final String roleName, final String secretID) throws VaultConnectorException;
/**
* Destroy an AppRole secret.
*
* @param roleName The role name
* @param secretID The secret meta object
* @return The secret ID
* @throws VaultConnectorException on error
* @since 0.4.0
*/
boolean destroyAppRoleSecret(final String roleName, final String secretID) throws VaultConnectorException;
/**
* List existing (accessible) AppRole roles.
*
* @return List of roles
* @throws VaultConnectorException on error
*/
List<String> listAppRoles() throws VaultConnectorException;
/**
* List existing (accessible) secret IDs for AppRole role.
*
* @param roleName The role name
* @return List of roles
* @throws VaultConnectorException on error
*/
List<String> listAppRoleSecretss(final String roleName) throws VaultConnectorException;
/**
* Register User-ID with App-ID
*
@ -131,7 +335,9 @@ public interface VaultConnector {
* @param userID The User-ID
* @return TRUE on success
* @throws VaultConnectorException on error
* @deprecated As of Vault 0.6.1 App-ID is superseded by AppRole. Consider using {@link #createAppRoleSecret} instead.
*/
@Deprecated
boolean registerUserId(final String appID, final String userID) throws VaultConnectorException;
/**
@ -143,7 +349,9 @@ public interface VaultConnector {
* @param userID The User-ID
* @return TRUE on success
* @throws VaultConnectorException on error
* @deprecated As of Vault 0.6.1 App-ID is superseded by AppRole.
*/
@Deprecated
default boolean registerAppUserId(final String appID, final String policy, final String displayName, final String userID) throws VaultConnectorException {
return registerAppId(appID, policy, userID) && registerUserId(appID, userID);
}

View File

@ -0,0 +1,147 @@
/*
* Copyright 2016 Stefan Kalscheuer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.stklcode.jvault.connector.model;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.util.List;
/**
* Vault AppRole role metamodel.
*
* @author Stefan Kalscheuer
* @since 0.4.0
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class AppRole {
@JsonProperty("role_name")
private String name;
@JsonProperty("role_id")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String id;
@JsonProperty("bind_secret_id")
@JsonInclude(JsonInclude.Include.NON_NULL)
private Boolean bindSecretId;
private List<String> boundCidrList;
private List<String> policies;
@JsonProperty("secret_id_num_uses")
@JsonInclude(JsonInclude.Include.NON_NULL)
private Integer secretIdNumUses;
@JsonProperty("secret_id_ttl")
@JsonInclude(JsonInclude.Include.NON_NULL)
private Integer secretIdTtl;
@JsonProperty("token_ttl")
@JsonInclude(JsonInclude.Include.NON_NULL)
private Integer tokenTtl;
@JsonProperty("token_max_ttl")
@JsonInclude(JsonInclude.Include.NON_NULL)
private Integer tokenMaxTtl;
@JsonProperty("period")
@JsonInclude(JsonInclude.Include.NON_NULL)
private Integer period;
public AppRole() {
}
public AppRole(String name, String id, Boolean bindSecretId, List<String> boundCidrList, List<String> policies, Integer secretIdNumUses, Integer secretIdTtl, Integer tokenTtl, Integer tokenMaxTtl, Integer period) {
this.name = name;
this.id = id;
this.bindSecretId = bindSecretId;
this.boundCidrList = boundCidrList;
this.policies = policies;
this.secretIdNumUses = secretIdNumUses;
this.secretIdTtl = secretIdTtl;
this.tokenTtl = tokenTtl;
this.tokenMaxTtl = tokenMaxTtl;
this.period = period;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public Boolean getBindSecretId() {
return bindSecretId;
}
public List<String> getBoundCidrList() {
return boundCidrList;
}
@JsonSetter("bound_cidr_list")
public void setBoundCidrList(List<String> boundCidrList) {
this.boundCidrList = boundCidrList;
}
@JsonGetter("bound_cidr_list")
public String getBoundCidrListString() {
if (boundCidrList == null || boundCidrList.isEmpty())
return "";
return String.join(",", boundCidrList);
}
public List<String> getPolicies() {
return policies;
}
@JsonSetter("policies")
public void setPolicies(List<String> policies) {
this.policies = policies;
}
@JsonGetter("policies")
public String getPoliciesString() {
if (policies == null || policies.isEmpty())
return "";
return String.join(",", policies);
}
public Integer getSecretIdNumUses() {
return secretIdNumUses;
}
public Integer getSecretIdTtl() {
return secretIdTtl;
}
public Integer getTokenTtl() {
return tokenTtl;
}
public Integer getTokenMaxTtl() {
return tokenMaxTtl;
}
public Integer getPeriod() {
return period;
}
}

View File

@ -0,0 +1,209 @@
/*
* Copyright 2016 Stefan Kalscheuer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.stklcode.jvault.connector.model;
import java.util.ArrayList;
import java.util.List;
/**
* A builder for vault AppRole roles..
*
* @author Stefan Kalscheuer
* @since 0.4.0
*/
public class AppRoleBuilder {
private String name;
private String id;
private Boolean bindSecretId;
private List<String> boundCidrList;
private List<String> policies;
private Integer secretIdNumUses;
private Integer secretIdTtl;
private Integer tokenTtl;
private Integer tokenMaxTtl;
private Integer period;
public AppRoleBuilder(String name) {
this.name = name;
}
/**
* Add custom role ID (optional)
*
* @param id the ID
* @return self
*/
public AppRoleBuilder withId(final String id) {
this.id = id;
return this;
}
/**
* Set if role is bound to secret ID
*
* @param bindSecretId the display name
* @return self
*/
public AppRoleBuilder withBindSecretID(final Boolean bindSecretId) {
this.bindSecretId = bindSecretId;
return this;
}
/**
* Bind role to secret ID.
* Convenience method for {@link #withBindSecretID(Boolean)}
*
* @return self
*/
public AppRoleBuilder withBindSecretID() {
return withBindSecretID(true);
}
/**
* Do not bind role to secret ID.
* Convenience method for {@link #withBindSecretID(Boolean)}
*
* @return self
*/
public AppRoleBuilder withoutBindSecretID() {
return withBindSecretID(false);
}
/**
* Set bound CIDR blocks.
*
* @param boundCidrList List of CIDR blocks which can perform login
* @return self
*/
public AppRoleBuilder withBoundCidrList(final List<String> boundCidrList) {
this.boundCidrList = boundCidrList;
return this;
}
/**
* Add a CIDR block to list of bound blocks.
*
* @param cidrBlock the CIDR block
* @return self
*/
public AppRoleBuilder withCidrBlock(final String cidrBlock) {
if (boundCidrList == null)
boundCidrList = new ArrayList<>();
boundCidrList.add(cidrBlock);
return this;
}
/**
* Add given policies
*
* @param policies the policies
* @return self
*/
public AppRoleBuilder withPolicies(final List<String> policies) {
if (this.policies == null)
this.policies = new ArrayList<>();
this.policies.addAll(policies);
return this;
}
/**
* Add a single policy.
*
* @param policy the policy
* @return self
*/
public AppRoleBuilder withPolicy(final String policy) {
if (this.policies == null)
this.policies = new ArrayList<>();
policies.add(policy);
return this;
}
/**
* Set number of uses for sectet IDs.
*
* @param secredIdNumUses the number of uses
* @return self
*/
public AppRoleBuilder withSecretIdNumUses(final Integer secredIdNumUses) {
this.secretIdNumUses = secredIdNumUses;
return this;
}
/**
* Set default sectet ID TTL in seconds.
*
* @param secredIdTtl the TTL
* @return self
*/
public AppRoleBuilder withSecretIdTtl(final Integer secredIdTtl) {
this.secretIdTtl = secredIdTtl;
return this;
}
/**
* Set default token TTL in seconds.
*
* @param tokenTtl the TTL
* @return self
*/
public AppRoleBuilder withTokenTtl(final Integer tokenTtl) {
this.tokenTtl = tokenTtl;
return this;
}
/**
* Set maximum token TTL in seconds.
*
* @param tokenMaxTtl the TTL
* @return self
*/
public AppRoleBuilder withTokenMaxTtl(final Integer tokenMaxTtl) {
this.tokenMaxTtl = tokenMaxTtl;
return this;
}
/**
* Set renewal period for generated token in seconds.
*
* @param period period in seconds
* @return self
*/
public AppRoleBuilder withPeriod(final Integer period) {
this.period = period;
return this;
}
/**
* Build the AppRole role based on given parameters.
*
* @return the role
*/
public AppRole build() {
return new AppRole(name,
id,
bindSecretId,
boundCidrList,
policies,
secretIdNumUses,
secretIdTtl,
tokenTtl,
tokenMaxTtl,
period);
}
}

View File

@ -0,0 +1,121 @@
/*
* Copyright 2016 Stefan Kalscheuer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.stklcode.jvault.connector.model;
import com.fasterxml.jackson.annotation.*;
import java.util.List;
import java.util.Map;
/**
* Vault AppRole role metamodel.
*
* @author Stefan Kalscheuer
* @since 0.4.0
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class AppRoleSecret {
@JsonProperty("secret_id")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String id;
@JsonProperty(value = "secret_id_accessor", access = JsonProperty.Access.WRITE_ONLY)
private String accessor;
@JsonProperty("metadata")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private Map<String, Object> metadata;
private List<String> cidrList;
@JsonProperty(value = "creation_time", access = JsonProperty.Access.WRITE_ONLY)
private String creationTime;
@JsonProperty(value = "expiration_time", access = JsonProperty.Access.WRITE_ONLY)
private String expirationTime;
@JsonProperty(value = "last_updated_time", access = JsonProperty.Access.WRITE_ONLY)
private String lastUpdatedTime;
@JsonProperty(value = "secret_id_num_uses", access = JsonProperty.Access.WRITE_ONLY)
private Integer numUses;
@JsonProperty(value = "secret_id_ttl", access = JsonProperty.Access.WRITE_ONLY)
private Integer ttl;
public AppRoleSecret() {
}
public AppRoleSecret(String id) {
this.id = id;
}
public AppRoleSecret(String id, Map<String, Object> metadata, List<String> cidrList) {
this.id = id;
this.metadata = metadata;
this.cidrList = cidrList;
}
public String getId() {
return id;
}
public String getAccessor() {
return accessor;
}
public Map<String, Object> getMetadata() {
return metadata;
}
public List<String> getCidrList() {
return cidrList;
}
@JsonSetter("cidr_list")
public void setCidrList(List<String> cidrList) {
this.cidrList = cidrList;
}
@JsonGetter("cidr_list")
public String getCidrListString() {
if (cidrList == null || cidrList.isEmpty())
return "";
return String.join(",", cidrList);
}
public String getCreationTime() {
return creationTime;
}
public String getExpirationTime() {
return expirationTime;
}
public String getLastUpdatedTime() {
return lastUpdatedTime;
}
public Integer getNumUses() {
return numUses;
}
public Integer getTtl() {
return ttl;
}
}

View File

@ -25,6 +25,7 @@ package de.stklcode.jvault.connector.model;
public enum AuthBackend {
TOKEN("token"),
APPID("app-id"),
APPROLE("approle"),
USERPASS("userpass"),
UNKNOWN("");

View File

@ -0,0 +1,56 @@
/*
* Copyright 2016 Stefan Kalscheuer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.stklcode.jvault.connector.model.response;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.stklcode.jvault.connector.exception.InvalidResponseException;
import de.stklcode.jvault.connector.model.AppRole;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Vault response for AppRole lookup.
*
* @author Stefan Kalscheuer
* @since 0.4.0
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class AppRoleResponse extends VaultDataResponse {
private AppRole role;
@Override
public void setData(Map<String, Object> data) throws InvalidResponseException {
ObjectMapper mapper = new ObjectMapper();
try {
/* null empty strings on list objects */
Map<String, Object> filteredData = new HashMap<>();
data.forEach((k,v) -> { if (!(v instanceof String && ((String) v).isEmpty())) filteredData.put(k,v); });
this.role = mapper.readValue(mapper.writeValueAsString(filteredData), AppRole.class);
} catch (IOException e) {
e.printStackTrace();
throw new InvalidResponseException();
}
}
public AppRole getRole() {
return role;
}
}

View File

@ -0,0 +1,56 @@
/*
* Copyright 2016 Stefan Kalscheuer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.stklcode.jvault.connector.model.response;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.stklcode.jvault.connector.exception.InvalidResponseException;
import de.stklcode.jvault.connector.model.AppRole;
import de.stklcode.jvault.connector.model.AppRoleSecret;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* Vault response for AppRole lookup.
*
* @author Stefan Kalscheuer
* @since 0.4.0
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class AppRoleSecretResponse extends VaultDataResponse {
private AppRoleSecret secret;
@Override
public void setData(Map<String, Object> data) throws InvalidResponseException {
ObjectMapper mapper = new ObjectMapper();
try {
/* null empty strings on list objects */
Map<String, Object> filteredData = new HashMap<>();
data.forEach((k,v) -> { if (!(v instanceof String && ((String) v).isEmpty())) filteredData.put(k,v); });
this.secret = mapper.readValue(mapper.writeValueAsString(filteredData), AppRoleSecret.class);
} catch (IOException e) {
e.printStackTrace();
throw new InvalidResponseException();
}
}
public AppRoleSecret getSecret() {
return secret;
}
}

View File

@ -0,0 +1,41 @@
/*
* Copyright 2016 Stefan Kalscheuer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.stklcode.jvault.connector.model.response;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.Map;
/**
* Simple Vault data response.
*
* @author Stefan Kalscheuer
* @since 0.4.0
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class RawDataResponse extends VaultDataResponse {
private Map<String, Object> data;
@Override
public void setData(Map<String, Object> data) {
this.data = data;
}
public Map<String, Object> getData() {
return data;
}
}