Skip to content

Commit 1bf0c57

Browse files
Merge pull request BetterCloud#50 from EXPEddrewery/master
Add LookupSelf capability to Auth
2 parents 1b2e43f + 2ab06b2 commit 1bf0c57

File tree

3 files changed

+209
-6
lines changed

3 files changed

+209
-6
lines changed

src/main/java/com/bettercloud/vault/api/Auth.java

Lines changed: 55 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import com.bettercloud.vault.json.Json;
66
import com.bettercloud.vault.json.JsonObject;
77
import com.bettercloud.vault.response.AuthResponse;
8+
import com.bettercloud.vault.response.LookupResponse;
89
import com.bettercloud.vault.rest.RestResponse;
910
import com.bettercloud.vault.rest.Rest;
1011

@@ -315,7 +316,7 @@ public AuthResponse createToken(TokenRequest tokenRequest) throws VaultException
315316
.connectTimeoutSeconds(config.getOpenTimeout())
316317
.readTimeoutSeconds(config.getReadTimeout())
317318
.sslPemUTF8(config.getSslPemUTF8())
318-
.sslVerification(config.isSslVerify() != null ? config.isSslVerify() : null)
319+
.sslVerification(config.isSslVerify())
319320
.post();
320321

321322
// Validate restResponse
@@ -380,7 +381,7 @@ public AuthResponse loginByAppID(final String path, final String appId, final St
380381
.connectTimeoutSeconds(config.getOpenTimeout())
381382
.readTimeoutSeconds(config.getReadTimeout())
382383
.sslPemUTF8(config.getSslPemUTF8())
383-
.sslVerification(config.isSslVerify() != null ? config.isSslVerify() : null)
384+
.sslVerification(config.isSslVerify())
384385
.post();
385386

386387
// Validate restResponse
@@ -441,7 +442,7 @@ public AuthResponse loginByAppRole(final String path, final String roleId, final
441442
.connectTimeoutSeconds(config.getOpenTimeout())
442443
.readTimeoutSeconds(config.getReadTimeout())
443444
.sslPemUTF8(config.getSslPemUTF8())
444-
.sslVerification(config.isSslVerify() != null ? config.isSslVerify() : null)
445+
.sslVerification(config.isSslVerify())
445446
.post();
446447

447448
// Validate restResponse
@@ -501,7 +502,7 @@ public AuthResponse loginByUserPass(final String username, final String password
501502
.connectTimeoutSeconds(config.getOpenTimeout())
502503
.readTimeoutSeconds(config.getReadTimeout())
503504
.sslPemUTF8(config.getSslPemUTF8())
504-
.sslVerification(config.isSslVerify() != null ? config.isSslVerify() : null)
505+
.sslVerification(config.isSslVerify())
505506
.post();
506507

507508
// Validate restResponse
@@ -563,7 +564,7 @@ public AuthResponse loginByGithub(final String githubToken) throws VaultExceptio
563564
.connectTimeoutSeconds(config.getOpenTimeout())
564565
.readTimeoutSeconds(config.getReadTimeout())
565566
.sslPemUTF8(config.getSslPemUTF8())
566-
.sslVerification(config.isSslVerify() != null ? config.isSslVerify() : null)
567+
.sslVerification(config.isSslVerify())
567568
.post();
568569

569570
// Validate restResponse
@@ -628,7 +629,7 @@ public AuthResponse renewSelf(final long increment) throws VaultException {
628629
.connectTimeoutSeconds(config.getOpenTimeout())
629630
.readTimeoutSeconds(config.getReadTimeout())
630631
.sslPemUTF8(config.getSslPemUTF8())
631-
.sslVerification(config.isSslVerify() != null ? config.isSslVerify() : null)
632+
.sslVerification(config.isSslVerify())
632633
.post();
633634
// Validate restResponse
634635
if (restResponse.getStatus() != 200) {
@@ -659,4 +660,52 @@ public AuthResponse renewSelf(final long increment) throws VaultException {
659660
}
660661
}
661662

663+
/**
664+
* <p>Returns information about the current client token.</p>
665+
*
666+
* @return The response information returned from Vault
667+
* @throws VaultException If any error occurs, or unexpected response received from Vault
668+
*/
669+
public LookupResponse lookupSelf() throws VaultException {
670+
int retryCount = 0;
671+
while (true) {
672+
try {
673+
// HTTP request to Vault
674+
final RestResponse restResponse = new Rest()//NOPMD
675+
.url(config.getAddress() + "/v1/auth/token/lookup-self")
676+
.header("X-Vault-Token", config.getToken())
677+
.connectTimeoutSeconds(config.getOpenTimeout())
678+
.readTimeoutSeconds(config.getReadTimeout())
679+
.sslPemUTF8(config.getSslPemUTF8())
680+
.sslVerification(config.isSslVerify())
681+
.post();
682+
// Validate restResponse
683+
if (restResponse.getStatus() != 200) {
684+
throw new VaultException("Vault responded with HTTP status code: " + restResponse.getStatus(), restResponse.getStatus());
685+
}
686+
final String mimeType = restResponse.getMimeType();
687+
if (mimeType == null || !"application/json".equals(mimeType)) {
688+
throw new VaultException("Vault responded with MIME type: " + mimeType, restResponse.getStatus());
689+
}
690+
return new LookupResponse(restResponse, retryCount);
691+
} catch (Exception e) {
692+
// If there are retries to perform, then pause for the configured interval and then execute the loop again...
693+
if (retryCount < config.getMaxRetries()) {
694+
retryCount++;
695+
try {
696+
final int retryIntervalMilliseconds = config.getRetryIntervalMilliseconds();
697+
Thread.sleep(retryIntervalMilliseconds);
698+
} catch (InterruptedException e1) {
699+
e1.printStackTrace(); //NOPMD
700+
}
701+
} else if (e instanceof VaultException) { //NOPMD
702+
// ... otherwise, give up.
703+
throw (VaultException) e;
704+
} else {
705+
throw new VaultException(e);
706+
}
707+
}
708+
}
709+
}
710+
662711
}
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
package com.bettercloud.vault.response;
2+
3+
import java.io.UnsupportedEncodingException;
4+
import java.util.ArrayList;
5+
import java.util.List;
6+
7+
import com.bettercloud.vault.json.*;
8+
import com.bettercloud.vault.rest.RestResponse;
9+
10+
/**
11+
* This class is a container for the information returned by Vault in lookup operations on auth backends.
12+
*/
13+
public class LookupResponse extends VaultResponse {
14+
15+
private String accessor;
16+
private long creationTime;
17+
private long creationTTL;
18+
private String displayName;
19+
private long explicitMaxTTL;
20+
private String id;
21+
private Long lastRenewalTime;
22+
private int numUses;
23+
private boolean orphan;
24+
private String path;
25+
private List<String> policies;
26+
private boolean renewable;
27+
private long ttl;
28+
private String username;
29+
30+
/**
31+
* This constructor simply exposes the common base class constructor.
32+
*
33+
* @param restResponse The raw HTTP response from Vault.
34+
* @param retries The number of retry attempts that occurred during the API call (can be zero).
35+
*/
36+
public LookupResponse(final RestResponse restResponse, final int retries) {
37+
super(restResponse, retries);
38+
39+
try {
40+
final String responseJson = new String(restResponse.getBody(), "UTF-8");
41+
final JsonObject jsonObject = Json.parse(responseJson).asObject();
42+
final JsonObject dataJsonObject = jsonObject.get("data").asObject();
43+
44+
accessor = dataJsonObject.getString("accessor", "");
45+
creationTime = dataJsonObject.getLong("creation_time", 0);
46+
creationTTL = dataJsonObject.getLong("creation_ttl", 0);
47+
displayName = dataJsonObject.getString("display_name", "");
48+
explicitMaxTTL = dataJsonObject.getLong("explicit_max_ttl", 0);
49+
id = dataJsonObject.getString("id", "");
50+
final JsonValue lastRenewalTimeJsonValue = dataJsonObject.get("last_renewal_time");
51+
if (lastRenewalTimeJsonValue != null) {
52+
lastRenewalTime = lastRenewalTimeJsonValue.asLong();
53+
}
54+
if (dataJsonObject.get("metadata") != null && !dataJsonObject.get("metadata").toString().equalsIgnoreCase("null")) {
55+
final JsonObject metadata = dataJsonObject.get("metadata").asObject();
56+
username = metadata.getString("username", "");
57+
}
58+
numUses = dataJsonObject.getInt("num_uses", 0);
59+
orphan = dataJsonObject.getBoolean("orphan", true);
60+
path = dataJsonObject.getString("path", "");
61+
final JsonArray policiesJsonArray = dataJsonObject.get("policies").asArray();
62+
policies = new ArrayList<>();
63+
for (final JsonValue policy : policiesJsonArray) {
64+
policies.add(policy.asString());
65+
}
66+
renewable = dataJsonObject.getBoolean("renewable", false);
67+
ttl = dataJsonObject.getLong("ttl", 0);
68+
69+
} catch (UnsupportedEncodingException | ParseException e) {
70+
}
71+
}
72+
73+
public String getAccessor() {
74+
return accessor;
75+
}
76+
77+
public long getCreationTime() {
78+
return creationTime;
79+
}
80+
81+
public long getCreationTTL() {
82+
return creationTTL;
83+
}
84+
85+
public String getDisplayName() {
86+
return displayName;
87+
}
88+
89+
public long getExplicitMaxTTL() {
90+
return explicitMaxTTL;
91+
}
92+
93+
public String getId() {
94+
return id;
95+
}
96+
97+
public Long getLastRenewalTime() {
98+
return lastRenewalTime;
99+
}
100+
101+
public int getNumUses() {
102+
return numUses;
103+
}
104+
105+
public boolean isOrphan() {
106+
return orphan;
107+
}
108+
109+
public String getPath() {
110+
return path;
111+
}
112+
113+
public List<String> getPolicies() {
114+
return policies;
115+
}
116+
117+
public boolean isRenewable() {
118+
return renewable;
119+
}
120+
121+
public long getTTL() {
122+
return ttl;
123+
}
124+
125+
public String getUsername() {
126+
return username;
127+
}
128+
}

src/test-integration/java/com/bettercloud/vault/api/AuthTests.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,14 @@
66
import com.bettercloud.vault.json.Json;
77
import com.bettercloud.vault.response.AuthResponse;
88
import com.bettercloud.vault.response.LogicalResponse;
9+
import com.bettercloud.vault.response.LookupResponse;
910
import org.junit.BeforeClass;
1011
import org.junit.Test;
1112

1213
import java.io.UnsupportedEncodingException;
14+
import java.util.List;
1315

16+
import static junit.framework.Assert.assertTrue;
1417
import static junit.framework.TestCase.assertEquals;
1518
import static junit.framework.TestCase.assertNotNull;
1619
import static junit.framework.TestCase.assertNotSame;
@@ -165,4 +168,27 @@ public void testRenewSelf() throws VaultException, UnsupportedEncodingException
165168
assertEquals(20, explicitLeaseDuration);
166169
}
167170

171+
/**
172+
* Tests token lookup-self for the token auth backend.
173+
*
174+
* @throws VaultException
175+
*/
176+
@Test
177+
public void testLookupSelf() throws VaultException, UnsupportedEncodingException {
178+
// Generate a client token
179+
final VaultConfig authConfig = new VaultConfig(address, rootToken);
180+
final Vault authVault = new Vault(authConfig);
181+
final AuthResponse createResponse = authVault.auth().createToken(null, null, null, null, null, "1h", null, null);
182+
final String token = createResponse.getAuthClientToken();
183+
assertNotNull(token);
184+
assertNotSame("", token.trim());
185+
186+
// Lookup the client token
187+
final VaultConfig lookupConfig = new VaultConfig(address, token);
188+
final Vault lookupVault = new Vault(lookupConfig);
189+
final LookupResponse lookupResponse = lookupVault.auth().lookupSelf();
190+
assertEquals(token, lookupResponse.getId());
191+
assertEquals(3600, lookupResponse.getCreationTTL());
192+
assertTrue(lookupResponse.getTTL()<=3600);
193+
}
168194
}

0 commit comments

Comments
 (0)