Java源码示例:com.bettercloud.vault.Vault
示例1
@BeforeClass
public static void init() throws Exception {
daprRun = startDaprApp(
SecretsClientIT.class.getSimpleName(),
EmptyService.SUCCESS_MESSAGE,
EmptyService.class,
false,
5000
);
VaultConfig vaultConfig = new VaultConfig()
.address(LOCAL_VAULT_ADDRESS)
.token(LOCAL_VAULT_TOKEN)
.prefixPath(PREFIX)
.build();
vault = new Vault(vaultConfig);
}
示例2
@SuppressFBWarnings(value = "DMI_HARDCODED_ABSOLUTE_FILENAME")
public void authenticate(Vault vault, VaultConfig config) throws VaultException, VaultPluginException {
if (isTokenTTLExpired()) {
try (Stream<String> input = Files.lines(Paths.get(SERVICE_ACCOUNT_TOKEN_PATH)) ) {
this.jwt = input.collect(Collectors.joining());
} catch (IOException e) {
throw new VaultPluginException("could not get JWT from Service Account Token", e);
}
// authenticate
currentAuthToken = vault.auth()
.loginByJwt(mountPath, kubernetes.getRole(), this.jwt)
.getAuthClientToken();
config.token(currentAuthToken).build();
LOGGER.log(Level.FINE, "Login to Vault using Kubernetes successful");
getTTLExpiryOfCurrentToken(vault);
} else {
// make sure current auth token is set in config
config.token(currentAuthToken).build();
}
}
示例3
public VaultAccessor init() {
try {
config.build();
if (credential == null) {
vault = new Vault(config);
} else {
vault = credential.authorizeWithVault(config);
}
vault.withRetries(maxRetries, retryIntervalMilliseconds);
} catch (VaultException e) {
throw new VaultPluginException("failed to connect to vault", e);
}
return this;
}
示例4
public void getTTLExpiryOfCurrentToken(Vault vault) {
int tokenTTL = 0;
try {
// save token TTL
tokenTTL = (int)vault.auth().lookupSelf().getTTL();
} catch (VaultException e) {
LOGGER.log(Level.WARNING, "Could not determine token expiration. " +
"Check if token is allowed to access auth/token/lookup-self. " +
"Assuming token TTL expired.", e);
}
tokenExpiration = Calendar.getInstance();
tokenExpiration.add(Calendar.SECOND, tokenTTL);
}
示例5
public void authenticate(Vault vault, VaultConfig config) throws VaultException {
if (isTokenTTLExpired()) {
// authenticate
currentAuthToken = vault.auth()
.loginByAppRole(mountPath, appRole.getAppRole(), appRole.getAppRoleSecret())
.getAuthClientToken();
config.token(currentAuthToken).build();
LOGGER.log(Level.FINE, "Login to Vault using AppRole/SecretID successful");
getTTLExpiryOfCurrentToken(vault);
} else {
// make sure current auth token is set in config
config.token(currentAuthToken).build();
}
}
示例6
public void authenticate(Vault vault, VaultConfig config) throws VaultException {
if (isTokenTTLExpired()) {
// authenticate
currentAuthToken = vault.auth()
.loginByUserPass(userPass.getUsername(), userPass.getPassword(), mountPath)
.getAuthClientToken();
config.token(currentAuthToken).build();
LOGGER.log(Level.FINE, "Login to Vault using AppRole/SecretID successful");
getTTLExpiryOfCurrentToken(vault);
} else {
// make sure current auth token is set in config
config.token(currentAuthToken).build();
}
}
示例7
@Override
public String getToken(Vault vault) {
try {
return vault.auth().loginByAppRole(path, roleId, Secret.toString(secretId))
.getAuthClientToken();
} catch (VaultException e) {
throw new VaultPluginException("could not log in into vault", e);
}
}
示例8
@Override
public String getToken(Vault vault) {
try {
return vault.auth().loginByGithub(Secret.toString(accessToken)).getAuthClientToken();
} catch (VaultException e) {
throw new VaultPluginException("could not log in into vault", e);
}
}
示例9
private String getToken(AbstractVaultTokenCredential credentials) {
try {
VaultConfig config = new VaultConfig().address(vaultAddr);
if (StringUtils.isNotEmpty(vaultNamespace)) {
config.nameSpace(vaultNamespace);
}
config.build();
return credentials.getToken(new Vault(config));
} catch (VaultException e) {
throw new VaultPluginException("could not log in into vault", e);
}
}
示例10
/**
* Constructs an instance of the Vault driver, using sensible defaults.
*
* @return
* @throws VaultException
*/
public Vault getVault() throws VaultException {
final VaultConfig config =
new VaultConfig()
.address(getAddress())
.openTimeout(5)
.readTimeout(30)
.sslConfig(new SslConfig().pemFile(new File(CERT_PEMFILE)).build())
.build();
return getVault(config, MAX_RETRIES, RETRY_MILLIS);
}
示例11
/**
* Constructs an instance of the Vault driver with sensible defaults, configured to use the supplied token
* for authentication.
*
* @param token
* @return
* @throws VaultException
*/
public Vault getVault(final String token) throws VaultException {
final VaultConfig config =
new VaultConfig()
.address(getAddress())
.token(token)
.openTimeout(5)
.readTimeout(30)
.sslConfig(new SslConfig().pemFile(new File(CERT_PEMFILE)).build())
.build();
return new Vault(config).withRetries(MAX_RETRIES, RETRY_MILLIS);
}
示例12
/**
* Constructs an instance of the Vault driver using a custom Vault config.
*
* @return
* @throws VaultException
*/
public Vault getRootVaultWithCustomVaultConfig(VaultConfig vaultConfig) throws VaultException {
final VaultConfig config =
vaultConfig
.address(getAddress())
.token(rootToken)
.openTimeout(5)
.readTimeout(30)
.sslConfig(new SslConfig().pemFile(new File(CERT_PEMFILE)).build())
.build();
return new Vault(config).withRetries(MAX_RETRIES, RETRY_MILLIS);
}
示例13
public static VaultAppRoleCredential createTokenCredential(final String credentialId) {
Vault vault = mock(Vault.class, withSettings().serializable());
VaultAppRoleCredential cred = mock(VaultAppRoleCredential.class,
withSettings().serializable());
when(cred.getId()).thenReturn(credentialId);
when(cred.getDescription()).thenReturn("description");
when(cred.getRoleId()).thenReturn("role-id-" + credentialId);
when(cred.getSecretId()).thenReturn(Secret.fromString("secret-id-" + credentialId));
when(cred.authorizeWithVault(any())).thenReturn(vault);
return cred;
}
示例14
@Test
public void shouldInjectCredentialsForAppRole() {
final String credentialsId = "creds";
final String vaultAddr = "https://localhost:8200";
final String token = "fakeToken";
final String jobId = "testJob";
story.addStep(new Statement() {
@Override
public void evaluate() throws Throwable {
VaultAppRoleCredential c = mock(VaultAppRoleCredential.class);
when(c.getToken(any(Vault.class))).thenReturn(token);
when(c.getId()).thenReturn(credentialsId);
CredentialsProvider.lookupStores(story.j.jenkins).iterator().next()
.addCredentials(Domain.global(), c);
WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, jobId);
p.setDefinition(new CpsFlowDefinition(""
+ "node {\n"
+ " withCredentials([[$class: 'VaultTokenCredentialBinding', addrVariable: 'VAULT_ADDR', tokenVariable: 'VAULT_TOKEN', credentialsId: '"
+ credentialsId + "', vaultAddr: '" + vaultAddr + "']]) {\n"
+ " " + getShellString() + " 'echo " + getVariable("VAULT_ADDR") + ":"
+ getVariable("VAULT_TOKEN") + " > script'\n"
+ " }\n"
+ "}", true));
WorkflowRun b = p.scheduleBuild2(0).waitForStart();
story.j.assertBuildStatus(Result.SUCCESS, story.j.waitForCompletion(b));
story.j.assertLogNotContains(token, b);
FilePath script = story.j.jenkins.getWorkspaceFor(p).child("script");
assertEquals(vaultAddr + ":" + token, script.readToString().trim());
}
});
}
示例15
@Test
public void writeAndReadMultipleValues() throws VaultException {
try (
VaultContainer vaultContainer = new VaultContainer<>()
.withVaultToken(VAULT_TOKEN)
) {
vaultContainer.start();
final VaultConfig config = new VaultConfig()
.address("http://" + vaultContainer.getHost() + ":" + vaultContainer.getFirstMappedPort())
.token(VAULT_TOKEN)
.build();
final Vault vault = new Vault(config);
final Map<String, Object> secrets = new HashMap<>();
secrets.put("value", "world");
secrets.put("other_value", "another world");
// Write operation
final LogicalResponse writeResponse = vault.logical()
.write("secret/hello", secrets);
assertThat(writeResponse.getRestResponse().getStatus()).isEqualTo(200);
// Read operation
final Map<String, String> value = vault.logical()
.read("secret/hello")
.getData();
assertThat(value)
.containsEntry("value", "world")
.containsEntry("other_value", "another world");
}
}
示例16
public void authenticate(Vault vault, VaultConfig config) throws VaultException {
// No special mechanism - token already exists
config.token(token).build();
}
示例17
@Override
public Vault authorizeWithVault(VaultConfig config) {
Vault vault = new Vault(config);
return new Vault(config.token(getToken(vault)));
}
示例18
@Override
public String getToken(Vault vault) {
return Secret.toString(token);
}
示例19
/**
* <p>Constructs an instance of the Vault driver, providing maximum flexibility to control all options
* explicitly.</p>
*
* <p>If <code>maxRetries</code> and <code>retryMillis</code> are BOTH null, then the <code>Vault</code>
* instance will be constructed with retry logic disabled. If one OR the other are null, the the class-level
* default value will be used in place of the missing one.</p>
*
* @param config
* @param maxRetries
* @param retryMillis
* @return
*/
public Vault getVault(final VaultConfig config, final Integer maxRetries, final Integer retryMillis) {
Vault vault = new Vault(config);
if (maxRetries != null && retryMillis != null) {
vault = vault.withRetries(maxRetries, retryMillis);
} else if (maxRetries != null) {
vault = vault.withRetries(maxRetries, RETRY_MILLIS);
} else if (retryMillis != null) {
vault = vault.withRetries(MAX_RETRIES, retryMillis);
}
return vault;
}
示例20
/**
* Constructs an instance of the Vault driver with sensible defaults, configured to the use the root token
* for authentication.
*
* @return
* @throws VaultException
*/
public Vault getRootVault() throws VaultException {
return getVault(rootToken).withRetries(MAX_RETRIES, RETRY_MILLIS);
}
示例21
void authenticate(Vault vault, VaultConfig config) throws VaultException;
示例22
protected abstract String getToken(Vault vault);
示例23
Vault authorizeWithVault(VaultConfig config);