-
Notifications
You must be signed in to change notification settings - Fork 373
/
__init__.py
2707 lines (2369 loc) · 90.8 KB
/
__init__.py
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
from __future__ import unicode_literals
import json
import os
from base64 import b64encode
from hvac import aws_utils, exceptions, adapters, utils, api
from hvac.constants.client import DEPRECATED_PROPERTIES, DEFAULT_URL
from hvac.utils import generate_property_deprecation_message
try:
import hcl
has_hcl_parser = True
except ImportError:
has_hcl_parser = False
class Client(object):
"""The hvac Client class for HashiCorp's Vault."""
def __init__(self, url=None, token=None,
cert=None, verify=True, timeout=30, proxies=None,
allow_redirects=True, session=None, adapter=adapters.JSONAdapter,
namespace=None, **kwargs):
"""Creates a new hvac client instance.
:param url: Base URL for the Vault instance being addressed.
:type url: str
:param token: Authentication token to include in requests sent to Vault.
:type token: str
:param cert: Certificates for use in requests sent to the Vault instance. This should be a tuple with the
certificate and then key.
:type cert: tuple
:param verify: Either a boolean to indicate whether TLS verification should be performed when sending requests to Vault,
or a string pointing at the CA bundle to use for verification. See http://docs.python-requests.org/en/master/user/advanced/#ssl-cert-verification.
:type verify: Union[bool,str]
:param timeout: The timeout value for requests sent to Vault.
:type timeout: int
:param proxies: Proxies to use when performing requests.
See: http://docs.python-requests.org/en/master/user/advanced/#proxies
:type proxies: dict
:param allow_redirects: Whether to follow redirects when sending requests to Vault.
:type allow_redirects: bool
:param session: Optional session object to use when performing request.
:type session: request.Session
:param adapter: Optional class to be used for performing requests. If none is provided, defaults to
hvac.adapters.JSONRequest
:type adapter: hvac.adapters.Adapter
:param kwargs: Additional parameters to pass to the adapter constructor.
:type kwargs: dict
:param namespace: Optional Vault Namespace.
:type namespace: str
"""
token = token if token is not None else utils.get_token_from_env()
url = url if url else os.getenv('VAULT_ADDR', DEFAULT_URL)
self._adapter = adapter(
base_uri=url,
token=token,
cert=cert,
verify=verify,
timeout=timeout,
proxies=proxies,
allow_redirects=allow_redirects,
session=session,
namespace=namespace,
**kwargs
)
# Instantiate API classes to be exposed as properties on this class starting with auth method classes.
self._auth = api.AuthMethods(adapter=self._adapter)
self._secrets = api.SecretsEngines(adapter=self._adapter)
self._sys = api.SystemBackend(adapter=self._adapter)
def __getattr__(self, name):
return utils.getattr_with_deprecated_properties(
obj=self,
item=name,
deprecated_properties=DEPRECATED_PROPERTIES
)
@property
def adapter(self):
return self._adapter
@adapter.setter
def adapter(self, adapter):
self._adapter = adapter
@property
def url(self):
return self._adapter.base_uri
@url.setter
def url(self, url):
self._adapter.base_uri = url
@property
def token(self):
return self._adapter.token
@token.setter
def token(self, token):
self._adapter.token = token
@property
def session(self):
return self._adapter.session
@session.setter
def session(self, session):
self._adapter.session = session
@property
def allow_redirects(self):
return self._adapter.allow_redirects
@allow_redirects.setter
def allow_redirects(self, allow_redirects):
self._adapter.allow_redirects = allow_redirects
@property
def auth(self):
"""Accessor for the Client instance's auth methods. Provided via the :py:class:`hvac.api.AuthMethods` class.
:return: This Client instance's associated Auth instance.
:rtype: hvac.api.AuthMethods
"""
return self._auth
@property
def secrets(self):
"""Accessor for the Client instance's secrets engines. Provided via the :py:class:`hvac.api.SecretsEngines` class.
:return: This Client instance's associated SecretsEngines instance.
:rtype: hvac.api.SecretsEngines
"""
return self._secrets
@property
def sys(self):
"""Accessor for the Client instance's system backend methods.
Provided via the :py:class:`hvac.api.SystemBackend` class.
:return: This Client instance's associated SystemBackend instance.
:rtype: hvac.api.SystemBackend
"""
return self._sys
@property
def generate_root_status(self):
return self.sys.read_root_generation_progress()
@property
def key_status(self):
"""GET /sys/key-status
:return: Information about the current encryption key used by Vault.
:rtype: dict
"""
return self.sys.get_encryption_key_status()['data']
@property
def rekey_status(self):
return self.sys.read_rekey_progress()
@property
def ha_status(self):
"""Read the high availability status and current leader instance of Vault.
:return: The JSON response returned by read_leader_status()
:rtype: dict
"""
return self.sys.read_leader_status()
@property
def seal_status(self):
"""Read the seal status of the Vault.
This is an unauthenticated endpoint.
Supported methods:
GET: /sys/seal-status. Produces: 200 application/json
:return: The JSON response of the request.
:rtype: dict
"""
return self.sys.read_seal_status()
def read(self, path, wrap_ttl=None):
"""GET /<path>
:param path:
:type path:
:param wrap_ttl:
:type wrap_ttl:
:return:
:rtype:
"""
try:
return self._adapter.get('/v1/{0}'.format(path), wrap_ttl=wrap_ttl)
except exceptions.InvalidPath:
return None
def list(self, path):
"""GET /<path>?list=true
:param path:
:type path:
:return:
:rtype:
"""
try:
payload = {
'list': True
}
return self._adapter.get('/v1/{0}'.format(path), params=payload)
except exceptions.InvalidPath:
return None
def write(self, path, wrap_ttl=None, **kwargs):
"""POST /<path>
:param path:
:type path:
:param wrap_ttl:
:type wrap_ttl:
:param kwargs:
:type kwargs:
:return:
:rtype:
"""
return self._adapter.post('/v1/{0}'.format(path), json=kwargs, wrap_ttl=wrap_ttl)
def delete(self, path):
"""DELETE /<path>
:param path:
:type path:
:return:
:rtype:
"""
self._adapter.delete('/v1/{0}'.format(path))
def get_policy(self, name, parse=False):
"""Retrieve the policy body for the named policy.
:param name: The name of the policy to retrieve.
:type name: str | unicode
:param parse: Specifies whether to parse the policy body using pyhcl or not.
:type parse: bool
:return: The (optionally parsed) policy body for the specified policy.
:rtype: str | dict
"""
try:
policy = self.sys.read_policy(name=name)['data']['rules']
except exceptions.InvalidPath:
return None
if parse:
if not has_hcl_parser:
raise ImportError('pyhcl is required for policy parsing')
policy = hcl.loads(policy)
return policy
def revoke_self_token(self):
"""PUT /auth/token/revoke-self
:return:
:rtype:
"""
self._adapter.put('/v1/auth/token/revoke-self')
def create_token(self, role=None, token_id=None, policies=None, meta=None,
no_parent=False, lease=None, display_name=None,
num_uses=None, no_default_policy=False,
ttl=None, orphan=False, wrap_ttl=None, renewable=None,
explicit_max_ttl=None, period=None, token_type=None):
"""POST /auth/token/create
POST /auth/token/create/<role>
POST /auth/token/create-orphan
:param role:
:type role:
:param token_id:
:type token_id:
:param policies:
:type policies:
:param meta:
:type meta:
:param no_parent:
:type no_parent:
:param lease:
:type lease:
:param display_name:
:type display_name:
:param num_uses:
:type num_uses:
:param no_default_policy:
:type no_default_policy:
:param ttl:
:type ttl:
:param orphan:
:type orphan:
:param wrap_ttl:
:type wrap_ttl:
:param renewable:
:type renewable:
:param explicit_max_ttl:
:type explicit_max_ttl:
:param period:
:type period:
:param token_type:
:type token_type:
:return:
:rtype:
"""
params = {
'id': token_id,
'policies': policies,
'meta': meta,
'no_parent': no_parent,
'display_name': display_name,
'num_uses': num_uses,
'no_default_policy': no_default_policy,
'renewable': renewable
}
if lease:
params['lease'] = lease
else:
params['ttl'] = ttl
params['explicit_max_ttl'] = explicit_max_ttl
if explicit_max_ttl:
params['explicit_max_ttl'] = explicit_max_ttl
if period:
params['period'] = period
if token_type:
params['type'] = token_type
if orphan:
return self._adapter.post('/v1/auth/token/create-orphan', json=params, wrap_ttl=wrap_ttl)
elif role:
return self._adapter.post('/v1/auth/token/create/{0}'.format(role), json=params, wrap_ttl=wrap_ttl)
else:
return self._adapter.post('/v1/auth/token/create', json=params, wrap_ttl=wrap_ttl)
def lookup_token(self, token=None, accessor=False, wrap_ttl=None):
"""GET /auth/token/lookup/<token>
GET /auth/token/lookup-accessor/<token-accessor>
GET /auth/token/lookup-self
:param token:
:type token: str.
:param accessor:
:type accessor: str.
:param wrap_ttl:
:type wrap_ttl: int.
:return:
:rtype:
"""
token_param = {
'token': token,
}
accessor_param = {
'accessor': token,
}
if token:
if accessor:
path = '/v1/auth/token/lookup-accessor'
return self._adapter.post(path, json=accessor_param, wrap_ttl=wrap_ttl)
else:
path = '/v1/auth/token/lookup'
return self._adapter.post(path, json=token_param)
else:
path = '/v1/auth/token/lookup-self'
return self._adapter.get(path, wrap_ttl=wrap_ttl)
def revoke_token(self, token, orphan=False, accessor=False):
"""POST /auth/token/revoke
POST /auth/token/revoke-orphan
POST /auth/token/revoke-accessor
:param token:
:type token:
:param orphan:
:type orphan:
:param accessor:
:type accessor:
:return:
:rtype:
"""
if accessor and orphan:
msg = "revoke_token does not support 'orphan' and 'accessor' flags together"
raise exceptions.InvalidRequest(msg)
elif accessor:
params = {'accessor': token}
self._adapter.post('/v1/auth/token/revoke-accessor', json=params)
elif orphan:
params = {'token': token}
self._adapter.post('/v1/auth/token/revoke-orphan', json=params)
else:
params = {'token': token}
self._adapter.post('/v1/auth/token/revoke', json=params)
def revoke_token_prefix(self, prefix):
"""POST /auth/token/revoke-prefix/<prefix>
:param prefix:
:type prefix:
:return:
:rtype:
"""
self._adapter.post('/v1/auth/token/revoke-prefix/{0}'.format(prefix))
def renew_token(self, token=None, increment=None, wrap_ttl=None):
"""POST /auth/token/renew
POST /auth/token/renew-self
:param token:
:type token:
:param increment:
:type increment:
:param wrap_ttl:
:type wrap_ttl:
:return:
:rtype:
For calls expecting to hit the renew-self endpoint please use the "renew_self_token" method instead
"""
params = {
'increment': increment,
}
if token is not None:
params['token'] = token
return self._adapter.post('/v1/auth/token/renew', json=params, wrap_ttl=wrap_ttl)
else:
generate_property_deprecation_message("1.0.0", "renew_token() without token param", "renew_self_token() without token param", "renew_self_token")
return self.renew_self_token(increment=increment, wrap_ttl=wrap_ttl)
def renew_self_token(self, increment=None, wrap_ttl=None):
"""
POST /auth/token/renew-self
:param increment:
:type increment:
:param wrap_ttl:
:type wrap_ttl:
:return:
:rtype:
"""
params = {
'increment': increment,
}
return self._adapter.post('/v1/auth/token/renew-self', json=params, wrap_ttl=wrap_ttl)
def create_token_role(self, role,
allowed_policies=None, disallowed_policies=None,
orphan=None, period=None, renewable=None,
path_suffix=None, explicit_max_ttl=None):
"""POST /auth/token/roles/<role>
:param role:
:type role:
:param allowed_policies:
:type allowed_policies:
:param disallowed_policies:
:type disallowed_policies:
:param orphan:
:type orphan:
:param period:
:type period:
:param renewable:
:type renewable:
:param path_suffix:
:type path_suffix:
:param explicit_max_ttl:
:type explicit_max_ttl:
:return:
:rtype:
"""
params = {
'allowed_policies': allowed_policies,
'disallowed_policies': disallowed_policies,
'orphan': orphan,
'period': period,
'renewable': renewable,
'path_suffix': path_suffix,
'explicit_max_ttl': explicit_max_ttl
}
return self._adapter.post('/v1/auth/token/roles/{0}'.format(role), json=params)
def token_role(self, role):
"""Returns the named token role.
:param role:
:type role:
:return:
:rtype:
"""
return self.read('auth/token/roles/{0}'.format(role))
def delete_token_role(self, role):
"""Deletes the named token role.
:param role:
:type role:
:return:
:rtype:
"""
return self.delete('auth/token/roles/{0}'.format(role))
def list_token_roles(self):
"""GET /auth/token/roles?list=true
:return:
:rtype:
"""
return self.list('auth/token/roles')
def logout(self, revoke_token=False):
"""Clears the token used for authentication, optionally revoking it before doing so.
:param revoke_token:
:type revoke_token:
:return:
:rtype:
"""
if revoke_token:
self.revoke_self_token()
self.token = None
def is_authenticated(self):
"""Helper method which returns the authentication status of the client
:return:
:rtype:
"""
if not self.token:
return False
try:
self.lookup_token()
return True
except exceptions.Forbidden:
return False
except exceptions.InvalidPath:
return False
except exceptions.InvalidRequest:
return False
def auth_app_id(self, app_id, user_id, mount_point='app-id', use_token=True):
"""POST /auth/<mount point>/login
:param app_id:
:type app_id:
:param user_id:
:type user_id:
:param mount_point:
:type mount_point:
:param use_token:
:type use_token:
:return:
:rtype:
"""
params = {
'app_id': app_id,
'user_id': user_id,
}
return self.login('/v1/auth/{0}/login'.format(mount_point), json=params, use_token=use_token)
def auth_tls(self, mount_point='cert', use_token=True):
"""POST /auth/<mount point>/login
:param mount_point:
:type mount_point:
:param use_token:
:type use_token:
:return:
:rtype:
"""
return self.login('/v1/auth/{0}/login'.format(mount_point), use_token=use_token)
def auth_userpass(self, username, password, mount_point='userpass', use_token=True, **kwargs):
"""POST /auth/<mount point>/login/<username>
:param username:
:type username:
:param password:
:type password:
:param mount_point:
:type mount_point:
:param use_token:
:type use_token:
:param kwargs:
:type kwargs:
:return:
:rtype:
"""
params = {
'password': password,
}
params.update(kwargs)
return self.login('/v1/auth/{0}/login/{1}'.format(mount_point, username), json=params, use_token=use_token)
@utils.deprecated_method(
to_be_removed_in_version='0.11.2',
new_method=api.auth_methods.Aws.iam_login,
)
def auth_aws_iam(self, access_key, secret_key, session_token=None, header_value=None, mount_point='aws', role='', use_token=True, region='us-east-1'):
"""POST /auth/<mount point>/login
:param access_key: AWS IAM access key ID
:type access_key: str
:param secret_key: AWS IAM secret access key
:type secret_key: str
:param session_token: Optional AWS IAM session token retrieved via a GetSessionToken AWS API request.
see: https://docs.aws.amazon.com/STS/latest/APIReference/API_GetSessionToken.html
:type session_token: str
:param header_value: Vault allows you to require an additional header, X-Vault-AWS-IAM-Server-ID, to be present
to mitigate against different types of replay attacks. Depending on the configuration of the AWS auth
backend, providing a argument to this optional parameter may be required.
:type header_value: str
:param mount_point: The "path" the AWS auth backend was mounted on. Vault currently defaults to "aws". "aws-ec2"
is the default argument for backwards comparability within this module.
:type mount_point: str
: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.
:type role: str
:param use_token: If True, uses the token in the response received from the auth request to set the "token"
attribute on the current Client class instance.
:type use_token: bool.
:return: The response from the AWS IAM login request attempt.
:rtype: requests.Response
"""
request = aws_utils.generate_sigv4_auth_request(header_value=header_value)
auth = aws_utils.SigV4Auth(access_key, secret_key, session_token, region)
auth.add_auth(request)
# https://github.com/hashicorp/vault/blob/master/builtin/credential/aws/cli.go
headers = json.dumps({k: [request.headers[k]] for k in request.headers})
params = {
'iam_http_request_method': request.method,
'iam_request_url': b64encode(request.url.encode('utf-8')).decode('utf-8'),
'iam_request_headers': b64encode(headers.encode('utf-8')).decode('utf-8'),
'iam_request_body': b64encode(request.body.encode('utf-8')).decode('utf-8'),
'role': role,
}
return self.login('/v1/auth/{0}/login'.format(mount_point), json=params, use_token=use_token)
@utils.deprecated_method(
to_be_removed_in_version='0.11.2',
new_method=api.auth_methods.Aws.ec2_login,
)
def auth_ec2(self, pkcs7, nonce=None, role=None, use_token=True, mount_point='aws-ec2'):
"""POST /auth/<mount point>/login
:param pkcs7: PKCS#7 version of an AWS Instance Identity Document from the EC2 Metadata Service.
:type pkcs7: str.
:param nonce: Optional nonce returned as part of the original authentication request. Not required if the backend
has "allow_instance_migration" or "disallow_reauthentication" options turned on.
:type nonce: str.
:param role: Identifier for the AWS auth backend role being requested.
:type role: str.
:param use_token: If True, uses the token in the response received from the auth request to set the "token"
attribute on the current Client class instance.
:type use_token: bool.
:param mount_point: The "path" the AWS auth backend was mounted on. Vault currently defaults to "aws". "aws-ec2"
is the default argument for backwards comparability within this module.
:type mount_point: str.
:return: parsed JSON response from the auth POST request
:rtype: dict.
"""
params = {'pkcs7': pkcs7}
if nonce:
params['nonce'] = nonce
if role:
params['role'] = role
return self.login('/v1/auth/{0}/login'.format(mount_point), json=params, use_token=use_token)
def create_userpass(self, username, password, policies, mount_point='userpass', **kwargs):
"""POST /auth/<mount point>/users/<username>
:param username:
:type username:
:param password:
:type password:
:param policies:
:type policies:
:param mount_point:
:type mount_point:
:param kwargs:
:type kwargs:
:return:
:rtype:
"""
# Users can have more than 1 policy. It is easier for the user to pass in the
# policies as a list so if they do, we need to convert to a , delimited string.
if isinstance(policies, (list, set, tuple)):
policies = ','.join(policies)
params = {
'password': password,
'policies': policies
}
params.update(kwargs)
return self._adapter.post('/v1/auth/{}/users/{}'.format(mount_point, username), json=params)
def list_userpass(self, mount_point='userpass'):
"""GET /auth/<mount point>/users?list=true
:param mount_point:
:type mount_point:
:return:
:rtype:
"""
try:
return self._adapter.get('/v1/auth/{}/users'.format(mount_point), params={'list': True})
except exceptions.InvalidPath:
return None
def read_userpass(self, username, mount_point='userpass'):
"""GET /auth/<mount point>/users/<username>
:param username:
:type username:
:param mount_point:
:type mount_point:
:return:
:rtype:
"""
return self._adapter.get('/v1/auth/{}/users/{}'.format(mount_point, username))
def update_userpass_policies(self, username, policies, mount_point='userpass'):
"""POST /auth/<mount point>/users/<username>/policies
:param username:
:type username:
:param policies:
:type policies:
:param mount_point:
:type mount_point:
:return:
:rtype:
"""
# userpass can have more than 1 policy. It is easier for the user to pass in the
# policies as a list so if they do, we need to convert to a , delimited string.
if isinstance(policies, (list, set, tuple)):
policies = ','.join(policies)
params = {
'policies': policies
}
return self._adapter.post('/v1/auth/{}/users/{}/policies'.format(mount_point, username), json=params)
def update_userpass_password(self, username, password, mount_point='userpass'):
"""POST /auth/<mount point>/users/<username>/password
:param username:
:type username:
:param password:
:type password:
:param mount_point:
:type mount_point:
:return:
:rtype:
"""
params = {
'password': password
}
return self._adapter.post('/v1/auth/{}/users/{}/password'.format(mount_point, username), json=params)
def delete_userpass(self, username, mount_point='userpass'):
"""DELETE /auth/<mount point>/users/<username>
:param username:
:type username:
:param mount_point:
:type mount_point:
:return:
:rtype:
"""
return self._adapter.delete('/v1/auth/{}/users/{}'.format(mount_point, username))
def create_app_id(self, app_id, policies, display_name=None, mount_point='app-id', **kwargs):
"""POST /auth/<mount point>/map/app-id/<app_id>
:param app_id:
:type app_id:
:param policies:
:type policies:
:param display_name:
:type display_name:
:param mount_point:
:type mount_point:
:param kwargs:
:type kwargs:
:return:
:rtype:
"""
# app-id can have more than 1 policy. It is easier for the user to pass in the
# policies as a list so if they do, we need to convert to a , delimited string.
if isinstance(policies, (list, set, tuple)):
policies = ','.join(policies)
params = {
'value': policies
}
# Only use the display_name if it has a value. Made it a named param for user
# convienence instead of leaving it as part of the kwargs
if display_name:
params['display_name'] = display_name
params.update(kwargs)
return self._adapter.post('/v1/auth/{}/map/app-id/{}'.format(mount_point, app_id), json=params)
def get_app_id(self, app_id, mount_point='app-id', wrap_ttl=None):
"""GET /auth/<mount_point>/map/app-id/<app_id>
:param app_id:
:type app_id:
:param mount_point:
:type mount_point:
:param wrap_ttl:
:type wrap_ttl:
:return:
:rtype:
"""
path = '/v1/auth/{0}/map/app-id/{1}'.format(mount_point, app_id)
return self._adapter.get(path, wrap_ttl=wrap_ttl)
def delete_app_id(self, app_id, mount_point='app-id'):
"""DELETE /auth/<mount_point>/map/app-id/<app_id>
:param app_id:
:type app_id:
:param mount_point:
:type mount_point:
:return:
:rtype:
"""
return self._adapter.delete('/v1/auth/{0}/map/app-id/{1}'.format(mount_point, app_id))
def create_user_id(self, user_id, app_id, cidr_block=None, mount_point='app-id', **kwargs):
"""POST /auth/<mount point>/map/user-id/<user_id>
:param user_id:
:type user_id:
:param app_id:
:type app_id:
:param cidr_block:
:type cidr_block:
:param mount_point:
:type mount_point:
:param kwargs:
:type kwargs:
:return:
:rtype:
"""
# user-id can be associated to more than 1 app-id (aka policy). It is easier for the user to
# pass in the policies as a list so if they do, we need to convert to a , delimited string.
if isinstance(app_id, (list, set, tuple)):
app_id = ','.join(app_id)
params = {
'value': app_id
}
# Only use the cidr_block if it has a value. Made it a named param for user
# convienence instead of leaving it as part of the kwargs
if cidr_block:
params['cidr_block'] = cidr_block
params.update(kwargs)
return self._adapter.post('/v1/auth/{}/map/user-id/{}'.format(mount_point, user_id), json=params)
def get_user_id(self, user_id, mount_point='app-id', wrap_ttl=None):
"""GET /auth/<mount_point>/map/user-id/<user_id>
:param user_id:
:type user_id:
:param mount_point:
:type mount_point:
:param wrap_ttl:
:type wrap_ttl:
:return:
:rtype:
"""
path = '/v1/auth/{0}/map/user-id/{1}'.format(mount_point, user_id)
return self._adapter.get(path, wrap_ttl=wrap_ttl)
def delete_user_id(self, user_id, mount_point='app-id'):
"""DELETE /auth/<mount_point>/map/user-id/<user_id>
:param user_id:
:type user_id:
:param mount_point:
:type mount_point:
:return:
:rtype:
"""
return self._adapter.delete('/v1/auth/{0}/map/user-id/{1}'.format(mount_point, user_id))
@utils.deprecated_method(
to_be_removed_in_version='0.11.2',
new_method=api.auth_methods.Aws.configure,
)
def create_vault_ec2_client_configuration(self, access_key, secret_key, endpoint=None, mount_point='aws-ec2'):
"""POST /auth/<mount_point>/config/client
Configure the credentials required to perform API calls to AWS as well as custom endpoints to talk to AWS APIs.
The instance identity document fetched from the PKCS#7 signature will provide the EC2 instance ID. The
credentials configured using this endpoint will be used to query the status of the instances via
DescribeInstances API. If static credentials are not provided using this endpoint, then the credentials will be
retrieved from the environment variables AWS_ACCESS_KEY, AWS_SECRET_KEY and AWS_REGION respectively. If the
credentials are still not found and if the method is configured on an EC2 instance with metadata querying
capabilities, the credentials are fetched automatically
:param access_key: AWS Access key with permissions to query AWS APIs. The permissions required depend on the
specific configurations. If using the iam auth method without inferencing, then no credentials are
necessary. If using the ec2 auth method or using the iam auth method with inferencing, then these
credentials need access to ec2:DescribeInstances. If additionally a bound_iam_role is specified, then these
credentials also need access to iam:GetInstanceProfile. If, however, an alternate sts configuration is set
for the target account, then the credentials must be permissioned to call sts:AssumeRole on the configured
role, and that role must have the permissions described here.
:type access_key: str|unicode
:param secret_key: AWS Secret key with permissions to query AWS APIs.
:type secret_key: str|unicode
:param endpoint: URL to override the default generated endpoint for making AWS EC2 API calls.
:type endpoint: str|unicode
:param mount_point: The "path" the AWS auth backend was mounted on. Vault currently defaults to "aws". "aws-ec2"
is the default argument for backwards comparability within this module.
:type mount_point: str|unicode
:return: The response of the request.
:rtype: requests.Response
"""
params = {
'access_key': access_key,
'secret_key': secret_key
}
if endpoint is not None:
params['endpoint'] = endpoint
return self._adapter.post('/v1/auth/{0}/config/client'.format(mount_point), json=params)
@utils.deprecated_method(
to_be_removed_in_version='0.11.2',
new_method=api.auth_methods.Aws.read_config,
)
def get_vault_ec2_client_configuration(self, mount_point='aws-ec2'):
"""GET /auth/<mount_point>/config/client
:param mount_point:
:type mount_point:
:return:
:rtype:
"""
return self._adapter.get('/v1/auth/{0}/config/client'.format(mount_point))
@utils.deprecated_method(
to_be_removed_in_version='0.11.2',
new_method=api.auth_methods.Aws.delete_config,
)
def delete_vault_ec2_client_configuration(self, mount_point='aws-ec2'):
"""DELETE /auth/<mount_point>/config/client
:param mount_point:
:type mount_point:
:return:
:rtype:
"""