-
Notifications
You must be signed in to change notification settings - Fork 225
Expand file tree
/
Copy pathAuth.java
More file actions
1383 lines (1312 loc) · 66.5 KB
/
Auth.java
File metadata and controls
1383 lines (1312 loc) · 66.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.bettercloud.vault.api;
import com.bettercloud.vault.Vault;
import com.bettercloud.vault.VaultConfig;
import com.bettercloud.vault.VaultException;
import com.bettercloud.vault.json.Json;
import com.bettercloud.vault.json.JsonObject;
import com.bettercloud.vault.response.AuthResponse;
import com.bettercloud.vault.response.LogicalResponse;
import com.bettercloud.vault.response.LookupResponse;
import com.bettercloud.vault.rest.Rest;
import com.bettercloud.vault.rest.RestResponse;
import lombok.Getter;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* <p>The implementing class for operations on Vault's <code>/v1/auth/*</code> REST endpoints.</p>
*
* <p>This class is not intended to be constructed directly. Rather, it is meant to used by way of <code>Vault</code>
* in a DSL-style builder pattern. See the Javadoc comments of each <code>public</code> method for usage examples.</p>
*
* @see Vault#auth()
*/
public class Auth {
/**
* <p>A container for all of the options that can be passed to the createToken(TokenRequest) method, to
* avoid that method having an excessive number of parameters (with <code>null</code> typically passed to most
* of them).</p>
*
* <p>All properties here are optional. Use of this class resembles a builder pattern (i.e. call the mutator method
* for each property you wish to set), but this class lacks a final <code>build()</code> method as no
* post-initialization logic is necessary.</p>
*/
public static class TokenRequest implements Serializable {
@Getter private UUID id;
@Getter private List<String> polices;
@Getter private Map<String, String> meta;
@Getter private Boolean noParent;
@Getter private Boolean noDefaultPolicy;
@Getter private String ttl;
@Getter private String displayName;
@Getter private Long numUses;
@Getter private String role;
/**
* @param id (optional) The ID of the client token. Can only be specified by a root token. Otherwise, the token ID is a randomly generated UUID.
* @return This object, with its id field populated
*/
public TokenRequest id(final UUID id) {
this.id = id;
return this;
}
/**
* @param polices (optional) A list of policies for the token. This must be a subset of the policies belonging to the token
* @return This object, with its polices field populated
*/
public TokenRequest polices(final List<String> polices) {
this.polices = polices;
return this;
}
/**
* @param meta (optional) A map of string to string valued metadata. This is passed through to the audit backends.
* @return This object, with its meta field populated
*/
public TokenRequest meta(final Map<String, String> meta) {
this.meta = meta;
return this;
}
/**
* @param noParent (optional) If true and set by a root caller, the token will not have the parent token of the caller. This creates a token with no parent.
* @return This object, with its noParent field populated
*/
public TokenRequest noParent(final Boolean noParent) {
this.noParent = noParent;
return this;
}
/**
* @param noDefaultPolicy (optional) If <code>true</code> the default policy will not be a part of this token's policy set.
* @return This object, with its noDefaultPolicy field populated
*/
public TokenRequest noDefaultPolicy(final Boolean noDefaultPolicy) {
this.noDefaultPolicy = noDefaultPolicy;
return this;
}
/**
* @param ttl (optional) The TTL period of the token, provided as "1h", where hour is the largest suffix. If not provided, the token is valid for the default lease TTL, or indefinitely if the root policy is used.
* @return This object, with its ttl field populated
*/
public TokenRequest ttl(final String ttl) {
this.ttl = ttl;
return this;
}
/**
*
* @param displayName (optional) The display name of the token. Defaults to "token".
* @return This object, with its displayName field populated
*/
public TokenRequest displayName(final String displayName) {
this.displayName = displayName;
return this;
}
/**
* @param numUses (optional) The maximum uses for the given token. This can be used to create a one-time-token or limited use token. Defaults to 0, which has no limit to the number of uses.
* @return This object, with its numUses field populated
*/
public TokenRequest numUses(final Long numUses) {
this.numUses = numUses;
return this;
}
/**
* @param role (optional) The role the token will be created with. Default is no role.
* @return This object, with its role field populated
*/
public TokenRequest role(final String role) {
this.role = role;
return this;
}
}
private final VaultConfig config;
public Auth(final VaultConfig config) {
this.config = config;
}
/**
* <p>Operation to create an authentication token. Relies on another token already being present in
* the <code>VaultConfig</code> instance. Example usage:</p>
*
* <blockquote>
* <pre>{@code
* final VaultConfig config = new VaultConfig().address(...).token(...).build();
* final Vault vault = new Vault(config);
* final AuthResponse response = vault.auth().createToken(new TokenRequest().withTtl("1h"));
*
* final String token = response.getAuthClientToken();
* }</pre>
* </blockquote>
*
* @param tokenRequest A container of optional configuration parameters
* @return The auth token, with additional response metadata
* @throws VaultException If any error occurs, or unexpected response received from Vault
*/
public AuthResponse createToken(final TokenRequest tokenRequest) throws VaultException{
return createToken(tokenRequest, "token");
}
/**
* <p>Operation to create an authentication token. Relies on another token already being present in
* the <code>VaultConfig</code> instance. Example usage:</p>
*
* <blockquote>
* <pre>{@code
* final VaultConfig config = new VaultConfig().address(...).token(...).build();
* final Vault vault = new Vault(config);
* final AuthResponse response = vault.auth().createToken(new TokenRequest().withTtl("1h"));
*
* final String token = response.getAuthClientToken();
* }</pre>
* </blockquote>
*
* @param tokenRequest A container of optional configuration parameters
* @param tokenAuthMount The mount name of the token authentication back end. If null, defaults to "token"
* @return The auth token, with additional response metadata
* @throws VaultException If any error occurs, or unexpected response received from Vault
*/
public AuthResponse createToken(final TokenRequest tokenRequest, final String tokenAuthMount) throws VaultException {
int retryCount = 0;
final String mount = tokenAuthMount != null ? tokenAuthMount : "token";
while (true) {
try {
// Parse parameters to JSON
final JsonObject jsonObject = Json.object();
if (tokenRequest.id != null) jsonObject.add("id", tokenRequest.id.toString());
if (tokenRequest.polices != null && !tokenRequest.polices.isEmpty()) {
jsonObject.add("policies", Json.array(tokenRequest.polices.toArray(new String[tokenRequest.polices.size()])));//NOPMD
}
if (tokenRequest.meta != null && !tokenRequest.meta.isEmpty()) {
final JsonObject metaMap = Json.object();
for (final Map.Entry<String, String> entry : tokenRequest.meta.entrySet()) {
metaMap.add(entry.getKey(), entry.getValue());
}
jsonObject.add("meta", metaMap);
}
if (tokenRequest.noParent != null) jsonObject.add("no_parent", tokenRequest.noParent);
if (tokenRequest.noDefaultPolicy != null) jsonObject.add("no_default_policy", tokenRequest.noDefaultPolicy);
if (tokenRequest.ttl != null) jsonObject.add("ttl", tokenRequest.ttl);
if (tokenRequest.displayName != null) jsonObject.add("display_name", tokenRequest.displayName);
if (tokenRequest.numUses != null) jsonObject.add("num_uses", tokenRequest.numUses);
final String requestJson = jsonObject.toString();
final StringBuilder urlBuilder = new StringBuilder(config.getAddress()).append("/v1/auth/" + mount + "/create");//NOPMD
if (tokenRequest.role != null) {
urlBuilder.append("/").append(tokenRequest.role);
}
final String url = urlBuilder.toString();
// HTTP request to Vault
final RestResponse restResponse = new Rest()//NOPMD
.url(url)
.header("X-Vault-Token", config.getToken())
.body(requestJson.getBytes("UTF-8"))
.connectTimeoutSeconds(config.getOpenTimeout())
.readTimeoutSeconds(config.getReadTimeout())
.sslVerification(config.getSslConfig().isVerify())
.sslContext(config.getSslConfig().getSslContext())
.post();
// Validate restResponse
if (restResponse.getStatus() != 200) {
throw createFailedRestCallException(restResponse);
}
final String mimeType = restResponse.getMimeType() == null ? "null" : restResponse.getMimeType();
if (!mimeType.equals("application/json")) {
throw new VaultException("Vault responded with MIME type: " + mimeType, restResponse.getStatus());
}
return new AuthResponse(restResponse, retryCount);
} catch (final Exception e) {
// If there are retries to perform, then pause for the configured interval and then execute the loop again...
if (retryCount < config.getMaxRetries()) {
retryCount++;
try {
final int retryIntervalMilliseconds = config.getRetryIntervalMilliseconds();
Thread.sleep(retryIntervalMilliseconds);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else if (e instanceof VaultException) {
// ... otherwise, give up.
throw (VaultException) e;
} else {
throw new VaultException(e);
}
}
}
}
/**
* <p>Basic login operation to authenticate to an app-id backend. Example usage:</p>
*
* <blockquote>
* <pre>{@code
* final AuthResponse response = vault.auth().loginByAppID("app-id/login", "app_id", "user_id");
*
* final String token = response.getAuthClientToken();
* }</pre>
* </blockquote>
*
* <strong>NOTE: </strong> As of Vault 0.6.1, Hashicorp has deprecated the App ID authentication backend in
* favor of AppRole. This method will be removed at some point after this backend has been eliminated from Vault.
*
* @param path The path on which the authentication is performed (e.g. <code>auth/app-id/login</code>)
* @param appId The app-id used for authentication
* @param userId The user-id used for authentication
* @return The auth token, with additional response metadata
* @throws VaultException If any error occurs, or unexpected response received from Vault
*/
@Deprecated
public AuthResponse loginByAppID(final String path, final String appId, final String userId) throws VaultException {
int retryCount = 0;
while (true) {
try {
// HTTP request to Vault
final String requestJson = Json.object().add("app_id", appId).add("user_id", userId).toString();
final RestResponse restResponse = new Rest()//NOPMD
.url(config.getAddress() + "/v1/auth/" + path)
.body(requestJson.getBytes("UTF-8"))
.connectTimeoutSeconds(config.getOpenTimeout())
.readTimeoutSeconds(config.getReadTimeout())
.sslVerification(config.getSslConfig().isVerify())
.sslContext(config.getSslConfig().getSslContext())
.post();
// Validate restResponse
if (restResponse.getStatus() != 200) {
throw createFailedRestCallException(restResponse);
}
final String mimeType = restResponse.getMimeType() == null ? "null" : restResponse.getMimeType();
if (!mimeType.equals("application/json")) {
throw new VaultException("Vault responded with MIME type: " + mimeType, restResponse.getStatus());
}
return new AuthResponse(restResponse, retryCount);
} catch (Exception e) {
// If there are retries to perform, then pause for the configured interval and then execute the loop again...
if (retryCount < config.getMaxRetries()) {
retryCount++;
try {
final int retryIntervalMilliseconds = config.getRetryIntervalMilliseconds();
Thread.sleep(retryIntervalMilliseconds);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else if (e instanceof VaultException) {
// ... otherwise, give up.
throw (VaultException) e;
} else {
throw new VaultException(e);
}
}
}
}
/**
* <p>Basic login operation to authenticate to an app-role backend. This version of the overloaded method assumes
* that the auth backend is mounted on the default path (i.e. "/v1/auth/approle"). Example usage:</p>
*
* <blockquote>
* <pre>{@code
* final AuthResponse response = vault.auth().loginByAppRole(9e1aede8-dcc6-a293-8223-f0d824a467ed", "9ff4b26e-6460-834c-b925-a940eddb6880");
*
* final String token = response.getAuthClientToken();
* }</pre>
* </blockquote>
*
* @param roleId The role-id used for authentication
* @param secretId The secret-id used for authentication
* @return The auth token, with additional response metadata
* @throws VaultException If any error occurs, or unexpected response received from Vault
*/
public AuthResponse loginByAppRole(final String roleId, final String secretId) throws VaultException {
return loginByAppRole("approle", roleId, secretId);
}
/**
* <p>Basic login operation to authenticate to an app-role backend. This version of the overloaded method
* requires you to explicitly specify the path on which the auth backend is mounted, following the "/v1/auth/"
* prefix. Example usage:</p>
*
* <blockquote>
* <pre>{@code
* final AuthResponse response = vault.auth().loginByAppRole("approle", "9e1aede8-dcc6-a293-8223-f0d824a467ed", "9ff4b26e-6460-834c-b925-a940eddb6880");
*
* final String token = response.getAuthClientToken();
* }</pre>
* </blockquote>
*
* NOTE: I hate that this method takes the custom mount path as its first parameter, while all of the other
* methods in this class take it as the last parameter (a better practice). I just didn't think about it
* during code review. Now it's difficult to deprecate this, since a version of the method with path as
* the final parameter would have the same method signature.
*
* I may or may not change this in some future breaking-change major release, especially if we keep adding
* similar overloaded methods elsewhere and need the global consistency. At any rate, going forward no new
* methods should take a custom path as the first parameter.
*
* @param path The path on which the authentication is performed, following the "/v1/auth/" prefix (e.g. "approle")
* @param roleId The role-id used for authentication
* @param secretId The secret-id used for authentication
* @return The auth token, with additional response metadata
* @throws VaultException If any error occurs, or unexpected response received from Vault
*/
public AuthResponse loginByAppRole(final String path, final String roleId, final String secretId) throws VaultException {
int retryCount = 0;
while (true) {
try {
// HTTP request to Vault
final String requestJson = Json.object().add("role_id", roleId).add("secret_id", secretId).toString();
final RestResponse restResponse = new Rest()//NOPMD
.url(config.getAddress() + "/v1/auth/" + path + "/login")
.body(requestJson.getBytes("UTF-8"))
.connectTimeoutSeconds(config.getOpenTimeout())
.readTimeoutSeconds(config.getReadTimeout())
.sslVerification(config.getSslConfig().isVerify())
.sslContext(config.getSslConfig().getSslContext())
.post();
// Validate restResponse
if (restResponse.getStatus() != 200) {
throw createFailedRestCallException(restResponse);
}
final String mimeType = restResponse.getMimeType() == null ? "null" : restResponse.getMimeType();
if (!mimeType.equals("application/json")) {
throw new VaultException("Vault responded with MIME type: " + mimeType, restResponse.getStatus());
}
return new AuthResponse(restResponse, retryCount);
} catch (Exception e) {
// If there are retries to perform, then pause for the configured interval and then execute the loop again...
if (retryCount < config.getMaxRetries()) {
retryCount++;
try {
final int retryIntervalMilliseconds = config.getRetryIntervalMilliseconds();
Thread.sleep(retryIntervalMilliseconds);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else if (e instanceof VaultException) {
// ... otherwise, give up.
throw (VaultException) e;
} else {
throw new VaultException(e);
}
}
}
}
/**
* <p>Basic login operation to authenticate to a Username & Password backend. Example usage:</p>
*
* <blockquote>
* <pre>{@code
* final AuthResponse response = vault.auth().loginByUserPass("test", "password");
*
* final String token = response.getAuthClientToken();
* }</pre>
* </blockquote>
*
* @param username The username used for authentication
* @param password The password used for authentication
* @return The auth token, with additional response metadata
* @throws VaultException If any error occurs, or unexpected response received from Vault
*/
public AuthResponse loginByUserPass(final String username, final String password) throws VaultException {
return loginByUserPass(username, password, "userpass");
}
/**
* <p>Basic login operation to authenticate to a Username & Password backend. Example usage:</p>
*
* <blockquote>
* <pre>{@code
* final AuthResponse response = vault.auth().loginByUserPass("test", "password");
*
* final String token = response.getAuthClientToken();
* }</pre>
* </blockquote>
*
* @param username The username used for authentication
* @param password The password used for authentication
* @param userpassAuthMount The mount name of the userpass authentication back end. If null, defaults to "userpass"
* @return The auth token, with additional response metadata
* @throws VaultException If any error occurs, or unexpected response received from Vault
*/
public AuthResponse loginByUserPass(final String username, final String password, final String userpassAuthMount) throws VaultException {
int retryCount = 0;
final String mount = userpassAuthMount != null ? userpassAuthMount : "userpass";
while (true) {
try {
// HTTP request to Vault
final String requestJson = Json.object().add("password", password).toString();
final RestResponse restResponse = new Rest()//NOPMD
.url(config.getAddress() + "/v1/auth/" + mount + "/login/" + username)
.body(requestJson.getBytes("UTF-8"))
.connectTimeoutSeconds(config.getOpenTimeout())
.readTimeoutSeconds(config.getReadTimeout())
.sslVerification(config.getSslConfig().isVerify())
.sslContext(config.getSslConfig().getSslContext())
.post();
// Validate restResponse
if (restResponse.getStatus() != 200) {
throw createFailedRestCallException(restResponse);
}
final String mimeType = restResponse.getMimeType() == null ? "null" : restResponse.getMimeType();
if (!mimeType.equals("application/json")) {
throw new VaultException("Vault responded with MIME type: " + mimeType, restResponse.getStatus());
}
return new AuthResponse(restResponse, retryCount);
} catch (Exception e) {
// If there are retries to perform, then pause for the configured interval and then execute the loop again...
if (retryCount < config.getMaxRetries()) {
retryCount++;
try {
final int retryIntervalMilliseconds = config.getRetryIntervalMilliseconds();
Thread.sleep(retryIntervalMilliseconds);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else if (e instanceof VaultException) {
// ... otherwise, give up.
throw (VaultException) e;
} else {
throw new VaultException(e);
}
}
}
}
/**
* <p>Basic login operation to authenticate to a LDAP backend. Example usage:</p>
*
* <blockquote>
* <pre>{@code
* final AuthResponse response = vault.auth().loginByLDAP("test", "password");
*
* final String token = response.getAuthClientToken();
* }</pre>
* </blockquote>
*
* @param username The username used for authentication
* @param password The password used for authentication
* @return The auth token, with additional response metadata
* @throws VaultException If any error occurs, or unexpected response received from Vault
*/
public AuthResponse loginByLDAP(final String username, final String password) throws VaultException {
// TODO: Determine a way to feasibly add integration test coverage
return loginByLDAP(username, password, "ldap");
}
/**
* <p>Basic login operation to authenticate to a LDAP backend. Example usage:</p>
*
* <blockquote>
* <pre>{@code
* final AuthResponse response = vault.auth().loginByLDAP("test", "password");
*
* final String token = response.getAuthClientToken();
* }</pre>
* </blockquote>
*
* @param username The username used for authentication
* @param password The password used for authentication
* @param ldapAuthMount The mount name of the ldap authentication back end. If null, defaults to "ldap"
* @return The auth token, with additional response metadata
* @throws VaultException If any error occurs, or unexpected response received from Vault
*/
public AuthResponse loginByLDAP(final String username, final String password, final String ldapAuthMount) throws VaultException {
final String mount = ldapAuthMount != null ? ldapAuthMount : "ldap";
// LDAP has the same API like Username & Password backend
return loginByUserPass(username, password, mount);
}
/**
* <p>Basic login operation to authenticate to a AWS backend using EC2 authentication. Example usage:</p>
*
* <blockquote>
* <pre>{@code
* final AuthResponse response = vault.auth().loginByAwsEc2("my-role", "identity", "signature", "nonce", null);
*
* final String token = response.getAuthClientToken();
* }</pre>
* </blockquote>
*
* @param role Name of the role against which the login is being attempted. If role is not specified, then the login endpoint
* looks for a role bearing the name of the AMI ID of the EC2 instance that is trying to login if using the ec2
* auth method, or the "friendly name" (i.e., role name or username) of the IAM principal authenticated.
* If a matching role is not found, login fails.
* @param identity Base64 encoded EC2 instance identity document.
* @param signature Base64 encoded SHA256 RSA signature of the instance identity document.
* @param nonce Client nonce used for authentication. If null, a new nonce will be generated by Vault
* @param awsAuthMount AWS auth mount
*
* @return The auth token, with additional response metadata
*
* @throws VaultException If any error occurs, or unexpected response received from Vault
*/
// TODO: Needs integration test coverage if possible
public AuthResponse loginByAwsEc2(final String role, final String identity, final String signature, final String nonce, final String awsAuthMount) throws VaultException {
int retryCount = 0;
final String mount = awsAuthMount != null ? awsAuthMount : "aws";
while (true) {
try {
// HTTP request to Vault
final JsonObject request = Json.object().add("identity", identity)
.add("signature", signature);
if(role != null) {
request.add("role", role);
}
if(nonce != null) {
request.add("nonce", nonce);
}
final String requestJson = request.toString();
final RestResponse restResponse = new Rest()//NOPMD
.url(config.getAddress() + "/v1/auth/" + mount + "/login")
.body(requestJson.getBytes("UTF-8"))
.connectTimeoutSeconds(config.getOpenTimeout())
.readTimeoutSeconds(config.getReadTimeout())
.sslVerification(config.getSslConfig().isVerify())
.sslContext(config.getSslConfig().getSslContext())
.post();
// Validate restResponse
if (restResponse.getStatus() != 200) {
throw createFailedRestCallException(restResponse);
}
final String mimeType = restResponse.getMimeType() == null ? "null" : restResponse.getMimeType();
if (!mimeType.equals("application/json")) {
throw new VaultException("Vault responded with MIME type: " + mimeType, restResponse.getStatus());
}
return new AuthResponse(restResponse, retryCount);
} catch (Exception e) {
// If there are retries to perform, then pause for the configured interval and then execute the loop again...
if (retryCount < config.getMaxRetries()) {
retryCount++;
try {
final int retryIntervalMilliseconds = config.getRetryIntervalMilliseconds();
Thread.sleep(retryIntervalMilliseconds);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else if (e instanceof VaultException) {
// ... otherwise, give up.
throw (VaultException) e;
} else {
throw new VaultException(e);
}
}
}
}
/**
* <p>Basic login operation to authenticate to a AWS backend using EC2 authentication. Example usage:</p>
*
* <blockquote>
* <pre>{@code
* final AuthResponse response = vault.auth().loginByAwsEc2("my-role", "pkcs7", "nonce", null);
*
* final String token = response.getAuthClientToken();
* }</pre>
* </blockquote>
*
* @param role Name of the role against which the login is being attempted. If role is not specified, then the login endpoint
* looks for a role bearing the name of the AMI ID of the EC2 instance that is trying to login if using the ec2
* auth method, or the "friendly name" (i.e., role name or username) of the IAM principal authenticated.
* If a matching role is not found, login fails.
* @param pkcs7 PKCS7 signature of the identity document with all \n characters removed.
* @param nonce Client nonce used for authentication. If null, a new nonce will be generated by Vault
* @param awsAuthMount AWS auth mount
*
* @return The auth token, with additional response metadata
*
* @throws VaultException If any error occurs, or unexpected response received from Vault
*/
// TODO: Needs integration test coverage if possible
public AuthResponse loginByAwsEc2(final String role, final String pkcs7, final String nonce, final String awsAuthMount) throws VaultException {
int retryCount = 0;
final String mount = awsAuthMount != null ? awsAuthMount : "aws";
while (true) {
try {
// HTTP request to Vault
final JsonObject request = Json.object().add("pkcs7", pkcs7);
if(role != null) {
request.add("role", role);
}
if(nonce != null) {
request.add("nonce", nonce);
}
final String requestJson = request.toString();
final RestResponse restResponse = new Rest()//NOPMD
.url(config.getAddress() + "/v1/auth/" + mount + "/login")
.body(requestJson.getBytes("UTF-8"))
.connectTimeoutSeconds(config.getOpenTimeout())
.readTimeoutSeconds(config.getReadTimeout())
.sslVerification(config.getSslConfig().isVerify())
.sslContext(config.getSslConfig().getSslContext())
.post();
// Validate restResponse
if (restResponse.getStatus() != 200) {
throw createFailedRestCallException(restResponse);
}
final String mimeType = restResponse.getMimeType() == null ? "null" : restResponse.getMimeType();
if (!mimeType.equals("application/json")) {
throw new VaultException("Vault responded with MIME type: " + mimeType, restResponse.getStatus());
}
return new AuthResponse(restResponse, retryCount);
} catch (Exception e) {
// If there are retries to perform, then pause for the configured interval and then execute the loop again...
if (retryCount < config.getMaxRetries()) {
retryCount++;
try {
final int retryIntervalMilliseconds = config.getRetryIntervalMilliseconds();
Thread.sleep(retryIntervalMilliseconds);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else if (e instanceof VaultException) {
// ... otherwise, give up.
throw (VaultException) e;
} else {
throw new VaultException(e);
}
}
}
}
private VaultException createFailedRestCallException(RestResponse restResponse) {
return new VaultException(String.format("Vault responded with HTTP status code: %s - Response Body: %s",
restResponse.getStatus(), new String(restResponse.getBody())), restResponse.getStatus());
}
/**
* <p>Basic login operation to authenticate to a AWS backend using IAM authentication. Example usage:</p>
*
* <blockquote>
* <pre>{@code
* final AuthResponse response = vault.auth().loginByAwsIam("my-role", "pkcs7", "nonce", null);
*
* final String token = response.getAuthClientToken();
* }</pre>
* </blockquote>
*
* @param role Name of the role against which the login is being attempted. If role is not specified, then the login endpoint
* looks for a role bearing the name of the AMI ID of the EC2 instance that is trying to login if using the ec2
* auth method, or the "friendly name" (i.e., role name or username) of the IAM principal authenticated.
* If a matching role is not found, login fails.
* @param iamRequestUrl PKCS7 signature of the identity document with all \n characters removed.Base64-encoded HTTP URL used in the signed request.
* Most likely just aHR0cHM6Ly9zdHMuYW1hem9uYXdzLmNvbS8= (base64-encoding of https://sts.amazonaws.com/) as most requests will
* probably use POST with an empty URI.
* @param iamRequestBody Base64-encoded body of the signed request. Most likely QWN0aW9uPUdldENhbGxlcklkZW50aXR5JlZlcnNpb249MjAxMS0wNi0xNQ== which is
* the base64 encoding of Action=GetCallerIdentity&Version=2011-06-15.
* @param iamRequestHeaders Request headers
* @param awsAuthMount AWS auth mount
*
* @return The auth token, with additional response metadata
*
* @throws VaultException If any error occurs, or unexpected response received from Vault
*/
public AuthResponse loginByAwsIam(final String role, final String iamRequestUrl, final String iamRequestBody, final String iamRequestHeaders, final String awsAuthMount) throws VaultException {
int retryCount = 0;
final String mount = awsAuthMount != null ? awsAuthMount : "aws";
while (true) {
try {
// HTTP request to Vault
final JsonObject request = Json.object().add("iam_request_url", iamRequestUrl)
.add("iam_request_body", iamRequestBody)
.add("iam_request_headers", iamRequestHeaders)
.add("iam_http_request_method", "POST");
if(role != null) {
request.add("role", role);
}
final String requestJson = request.toString();
final RestResponse restResponse = new Rest()//NOPMD
.url(config.getAddress() + "/v1/auth/" + mount + "/login")
.body(requestJson.getBytes("UTF-8"))
.connectTimeoutSeconds(config.getOpenTimeout())
.readTimeoutSeconds(config.getReadTimeout())
.sslVerification(config.getSslConfig().isVerify())
.sslContext(config.getSslConfig().getSslContext())
.post();
// Validate restResponse
if (restResponse.getStatus() != 200) {
throw createFailedRestCallException(restResponse);
}
final String mimeType = restResponse.getMimeType() == null ? "null" : restResponse.getMimeType();
if (!mimeType.equals("application/json")) {
throw new VaultException("Vault responded with MIME type: " + mimeType, restResponse.getStatus());
}
return new AuthResponse(restResponse, retryCount);
} catch (Exception e) {
// If there are retries to perform, then pause for the configured interval and then execute the loop again...
if (retryCount < config.getMaxRetries()) {
retryCount++;
try {
final int retryIntervalMilliseconds = config.getRetryIntervalMilliseconds();
Thread.sleep(retryIntervalMilliseconds);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else if (e instanceof VaultException) {
// ... otherwise, give up.
throw (VaultException) e;
} else {
throw new VaultException(e);
}
}
}
}
/**
* <p>Basic login operation to authenticate to an github backend. Example usage:</p>
*
* <blockquote>
* <pre>{@code
* final AuthResponse response = vault.auth().loginByGithub("githubToken");
*
* final String token = response.getAuthClientToken();
* }</pre>
* </blockquote>
*
* @param githubToken The app-id used for authentication
* @return The auth token, with additional response metadata
* @throws VaultException If any error occurs, or unexpected response received from Vault
*/
public AuthResponse loginByGithub(final String githubToken) throws VaultException {
return loginByGithub(githubToken, "github");
}
/**
* <p>Basic login operation to authenticate to an github backend. Example usage:</p>
*
* <blockquote>
* <pre>{@code
* final AuthResponse response = vault.auth().loginByGithub("githubToken");
*
* final String token = response.getAuthClientToken();
* }</pre>
* </blockquote>
*
* @param githubToken The app-id used for authentication
* @param githubAuthMount The mount name of the github authentication back end. If null, defaults to "github"
* @return The auth token, with additional response metadata
* @throws VaultException If any error occurs, or unexpected response received from Vault
*/
public AuthResponse loginByGithub(final String githubToken, final String githubAuthMount) throws VaultException {
// TODO: Add (optional?) integration test coverage
int retryCount = 0;
final String mount = githubAuthMount != null ? githubAuthMount : "github";
while (true) {
try {
// HTTP request to Vault
final String requestJson = Json.object().add("token", githubToken).toString();
final RestResponse restResponse = new Rest()//NOPMD
.url(config.getAddress() + "/v1/auth/" + mount + "/login")
.body(requestJson.getBytes("UTF-8"))
.connectTimeoutSeconds(config.getOpenTimeout())
.readTimeoutSeconds(config.getReadTimeout())
.sslVerification(config.getSslConfig().isVerify())
.sslContext(config.getSslConfig().getSslContext())
.post();
// Validate restResponse
if (restResponse.getStatus() != 200) {
throw new VaultException("Vault responded with HTTP status code: " + restResponse.getStatus(), restResponse.getStatus());
}
final String mimeType = restResponse.getMimeType() == null ? "null" : restResponse.getMimeType();
if (!mimeType.equals("application/json")) {
throw new VaultException("Vault responded with MIME type: " + mimeType, restResponse.getStatus());
}
return new AuthResponse(restResponse, retryCount);
} catch (Exception e) {
// If there are retries to perform, then pause for the configured interval and then execute the loop again...
if (retryCount < config.getMaxRetries()) {
retryCount++;
try {
final int retryIntervalMilliseconds = config.getRetryIntervalMilliseconds();
Thread.sleep(retryIntervalMilliseconds);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else if (e instanceof VaultException) {
// ... otherwise, give up.
throw (VaultException) e;
} else {
throw new VaultException(e);
}
}
}
}
/**
* <p>Basic login operation to authenticate to an GCP backend. Example usage:</p>
*
* <blockquote>
* <pre>{@code
* final AuthResponse response = vault.auth().loginByGCP("dev", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...");
*
* final String token = response.getAuthClientToken();
* }</pre>
* </blockquote>
*
* @param role The gcp role used for authentication
* @param jwt The JWT token for the role
* @return The auth token, with additional response metadata
* @throws VaultException If any error occurs, or unexpected response received from Vault
*/
// TODO: Needs integration test coverage if possible
public AuthResponse loginByGCP(final String role, final String jwt) throws VaultException {
int retryCount = 0;
while (true) {
try {
// HTTP request to Vault
final String requestJson = Json.object().add("role", role).add("jwt", jwt).toString();
final RestResponse restResponse = new Rest()
.url(config.getAddress() + "/v1/auth/gcp/login")
.body(requestJson.getBytes("UTF-8"))
.connectTimeoutSeconds(config.getOpenTimeout())
.readTimeoutSeconds(config.getReadTimeout())
.sslVerification(config.getSslConfig().isVerify())
.sslContext(config.getSslConfig().getSslContext())
.post();
// Validate restResponse
if (restResponse.getStatus() != 200) {
throw new VaultException("Vault responded with HTTP status code: " + restResponse.getStatus(), restResponse.getStatus());
}
final String mimeType = restResponse.getMimeType() == null ? "null" : restResponse.getMimeType();
if (!mimeType.equals("application/json")) {
throw new VaultException("Vault responded with MIME type: " + mimeType, restResponse.getStatus());
}
return new AuthResponse(restResponse, retryCount);
} catch (Exception e) {
// If there are retries to perform, then pause for the configured interval and then execute the loop again...
if (retryCount < config.getMaxRetries()) {
retryCount++;
try {
final int retryIntervalMilliseconds = config.getRetryIntervalMilliseconds();
Thread.sleep(retryIntervalMilliseconds);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else if (e instanceof VaultException) {
// ... otherwise, give up.
throw (VaultException) e;
} else {
throw new VaultException(e);
}
}
}
}
/**
* <p>Basic login operation to authenticate using Vault's TLS Certificate auth backend. Example usage:</p>
*
* <blockquote>
* <pre>{@code
* final SslConfig sslConfig = new SslConfig()
* .keystore("keystore.jks")
* .truststore("truststore.jks")
* .build();
* final VaultConfig vaultConfig = new VaultConfig()
* .address("https://127.0.0.1:8200")
* .sslConfig(sslConfig)
* .build();
* final Vault vault = new Vault(vaultConfig);
*
* final AuthResponse response = vault.auth().loginByCert();
* final String token = response.getAuthClientToken();
* }</pre>
* </blockquote>
*
* @return The auth token, with additional response metadata
* @throws VaultException If any error occurs, or unexpected response received from Vault
*/
public AuthResponse loginByCert() throws VaultException {
return loginByCert("cert");
}
/**
* <p>Basic login operation to authenticate using Vault's TLS Certificate auth backend. Example usage:</p>
*
* <blockquote>
* <pre>{@code
* final SslConfig sslConfig = new SslConfig()
* .keystore("keystore.jks")
* .truststore("truststore.jks")
* .build();
* final VaultConfig vaultConfig = new VaultConfig()
* .address("https://127.0.0.1:8200")
* .sslConfig(sslConfig)
* .build();
* final Vault vault = new Vault(vaultConfig);
*
* final AuthResponse response = vault.auth().loginByCert();
* final String token = response.getAuthClientToken();
* }</pre>
* </blockquote>
*
* @param certAuthMount The mount name of the cert authentication back end. If null, defaults to "cert"
* @return The auth token, with additional response metadata
* @throws VaultException If any error occurs, or unexpected response received from Vault
*/
public AuthResponse loginByCert(final String certAuthMount) throws VaultException {
int retryCount = 0;
final String mount = certAuthMount != null ? certAuthMount : "cert";
while (true) {
try {
final RestResponse restResponse = new Rest()//NOPMD
.url(config.getAddress() + "/v1/auth/" + mount + "/login")
.connectTimeoutSeconds(config.getOpenTimeout())
.readTimeoutSeconds(config.getReadTimeout())
.sslVerification(config.getSslConfig().isVerify())
.sslContext(config.getSslConfig().getSslContext())
.post();
// Validate restResponse
if (restResponse.getStatus() != 200) {
throw new VaultException("Vault responded with HTTP status code: " + restResponse.getStatus(),
restResponse.getStatus());
}
final String mimeType = restResponse.getMimeType() == null ? "null" : restResponse.getMimeType();
if (!mimeType.equals("application/json")) {
throw new VaultException("Vault responded with MIME type: " + mimeType, restResponse.getStatus());
}
return new AuthResponse(restResponse, retryCount);
} catch (Exception e) {