File: approle.py

package info (click to toggle)
python-hvac 2.3.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,800 kB
  • sloc: python: 29,360; makefile: 42; sh: 14
file content (510 lines) | stat: -rw-r--r-- 20,691 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/env python
"""APPROLE methods module."""
import json
from hvac import exceptions, utils
from hvac.api.vault_api_base import VaultApiBase
from hvac.constants.approle import DEFAULT_MOUNT_POINT, ALLOWED_TOKEN_TYPES
from hvac.utils import validate_list_of_strings_param, list_to_comma_delimited


class AppRole(VaultApiBase):
    """USERPASS Auth Method (API).
    Reference: https://www.vaultproject.io/api-docs/auth/approle/index.html
    """

    def create_or_update_approle(
        self,
        role_name,
        bind_secret_id=None,
        secret_id_bound_cidrs=None,
        secret_id_num_uses=None,
        secret_id_ttl=None,
        enable_local_secret_ids=None,
        token_ttl=None,
        token_max_ttl=None,
        token_policies=None,
        token_bound_cidrs=None,
        token_explicit_max_ttl=None,
        token_no_default_policy=None,
        token_num_uses=None,
        token_period=None,
        token_type=None,
        mount_point=DEFAULT_MOUNT_POINT,
    ):
        """
        Create/update approle.

        Supported methods:
            POST: /auth/{mount_point}/role/{role_name}. Produces: 204 (empty body)

        :param role_name: The name for the approle.
        :type role_name: str | unicode
        :param bind_secret_id: Require secret_id to be presented when logging in using this approle.
        :type bind_secret_id: bool
        :param secret_id_bound_cidrs: Blocks of IP addresses which can perform login operations.
        :type secret_id_bound_cidrs: list
        :param secret_id_num_uses: Number of times any secret_id can be used to fetch a token.
            A value of zero allows unlimited uses.
        :type secret_id_num_uses: int
        :param secret_id_ttl: Duration after which a secret_id expires. This can be specified
            as an integer number of seconds or as a duration value like "5m".
        :type secret_id_ttl: str | unicode
        :param enable_local_secret_ids: Secret IDs generated using role will be cluster local.
        :type enable_local_secret_ids: bool
        :param token_ttl: Incremental lifetime for generated tokens. This can be specified
            as an integer number of seconds or as a duration value like "5m".
        :type token_ttl: str | unicode
        :param token_max_ttl: Maximum lifetime for generated tokens: This can be specified
            as an integer number of seconds or as a duration value like "5m".
        :type token_max_ttl: str | unicode
        :param token_policies: List of policies to encode onto generated tokens.
        :type token_policies: list
        :param token_bound_cidrs: Blocks of IP addresses which can authenticate successfully.
        :type token_bound_cidrs: list
        :param token_explicit_max_ttl: If set, will encode an explicit max TTL onto the token. This can be specified
            as an integer number of seconds or as a duration value like "5m".
        :type token_explicit_max_ttl: str | unicode
        :param token_no_default_policy: Do not add the default policy to generated tokens, use only tokens
            specified in token_policies.
        :type token_no_default_policy: bool
        :param token_num_uses: Maximum number of times a generated token may be used. A value of zero
            allows unlimited uses.
        :type token_num_uses: int
        :param token_period: The period, if any, to set on the token. This can be specified
            as an integer number of seconds or as a duration value like "5m".
        :type token_period: str | unicode
        :param token_type: The type of token that should be generated, can be "service", "batch", or "default".
        :type token_type: str | unicode
        :param mount_point: The "path" the method/backend was mounted on.
        :type mount_point: str | unicode
        """
        list_of_strings_params = {
            "secret_id_bound_cidrs": secret_id_bound_cidrs,
            "token_policies": token_policies,
            "token_bound_cidrs": token_bound_cidrs,
        }

        if token_type is not None and token_type not in ALLOWED_TOKEN_TYPES:
            error_msg = 'unsupported token_type argument provided "{arg}", supported types: "{token_types}"'
            raise exceptions.ParamValidationError(
                error_msg.format(
                    arg=token_type,
                    token_types=",".join(ALLOWED_TOKEN_TYPES),
                )
            )

        params = dict()

        for param_name, param_argument in list_of_strings_params.items():
            validate_list_of_strings_param(
                param_name=param_name,
                param_argument=param_argument,
            )
            if param_argument is not None:
                params[param_name] = list_to_comma_delimited(param_argument)

        params.update(
            utils.remove_nones(
                {
                    "bind_secret_id": bind_secret_id,
                    "secret_id_num_uses": secret_id_num_uses,
                    "secret_id_ttl": secret_id_ttl,
                    "enable_local_secret_ids": enable_local_secret_ids,
                    "token_ttl": token_ttl,
                    "token_max_ttl": token_max_ttl,
                    "token_explicit_max_ttl": token_explicit_max_ttl,
                    "token_no_default_policy": token_no_default_policy,
                    "token_num_uses": token_num_uses,
                    "token_period": token_period,
                    "token_type": token_type,
                }
            )
        )

        api_path = utils.format_url(
            "/v1/auth/{mount_point}/role/{name}",
            mount_point=mount_point,
            name=role_name,
        )
        return self._adapter.post(url=api_path, json=params)

    def list_roles(self, mount_point=DEFAULT_MOUNT_POINT):
        """
        List existing roles created in the auth method.

        Supported methods:
            LIST: /auth/{mount_point}/role. Produces: 200 application/json

        :param mount_point: The "path" the method/backend was mounted on.
        :type mount_point: str | unicode
        :return: The JSON response of the list_roles request.
        :rtype: dict
        """
        api_path = utils.format_url(
            "/v1/auth/{mount_point}/role", mount_point=mount_point
        )
        return self._adapter.list(url=api_path)

    def read_role(self, role_name, mount_point=DEFAULT_MOUNT_POINT):
        """
        Read role in the auth method.

        Supported methods:
            GET: /auth/{mount_point}/role/{role_name}. Produces: 200 application/json

        :param role_name: The name for the role.
        :type role_name: str | unicode
        :param mount_point: The "path" the method/backend was mounted on.
        :type mount_point: str | unicode
        :return: The JSON response of the read_role request.
        :rtype: dict
        """
        api_path = utils.format_url(
            "/v1/auth/{mount_point}/role/{role_name}",
            mount_point=mount_point,
            role_name=role_name,
        )
        return self._adapter.get(url=api_path)

    def delete_role(self, role_name, mount_point=DEFAULT_MOUNT_POINT):
        """
        Delete role in the auth method.

        Supported methods:
            DELETE: /auth/{mount_point}/role/{role_name}. Produces: 204 (empty body)

        :param role_name: The name for the role.
        :type role_name: str | unicode
        :param mount_point: The "path" the method/backend was mounted on.
        :type mount_point: str | unicode
        """
        api_path = utils.format_url(
            "/v1/auth/{mount_point}/role/{role_name}",
            mount_point=mount_point,
            role_name=role_name,
        )
        return self._adapter.delete(url=api_path)

    def read_role_id(self, role_name, mount_point=DEFAULT_MOUNT_POINT):
        """
        Reads the Role ID of a role in the auth method.

        Supported methods:
            GET: /auth/{mount_point}/role/{role_name}/role-id. Produces: 200 application/json

        :param role_name: The name for the role.
        :type role_name: str | unicode
        :param mount_point: The "path" the method/backend was mounted on.
        :type mount_point: str | unicode
        :return: The JSON response of the read_role_id request.
        :rtype: dict
        """
        api_path = utils.format_url(
            "/v1/auth/{mount_point}/role/{role_name}/role-id",
            mount_point=mount_point,
            role_name=role_name,
        )
        return self._adapter.get(url=api_path)

    def update_role_id(self, role_name, role_id, mount_point=DEFAULT_MOUNT_POINT):
        """
        Updates the Role ID of a role in the auth method.

        Supported methods:
            POST: /auth/{mount_point}/role/{role_name}/role-id. Produces: 200 application/json

        :param role_name: The name for the role.
        :type role_name: str | unicode
        :param role_id: New value for the Role ID.
        :type role_id: str | unicode
        :param mount_point: The "path" the method/backend was mounted on.
        :type mount_point: str | unicode
        :return: The JSON response of the read_role_id request.
        :rtype: dict
        """
        params = {"role_id": role_id}

        api_path = utils.format_url(
            "/v1/auth/{mount_point}/role/{role_name}/role-id",
            mount_point=mount_point,
            role_name=role_name,
        )
        return self._adapter.post(url=api_path, json=params)

    def generate_secret_id(
        self,
        role_name,
        metadata=None,
        cidr_list=None,
        token_bound_cidrs=None,
        mount_point=DEFAULT_MOUNT_POINT,
        wrap_ttl=None,
    ):
        """
        Generates and issues a new Secret ID on a role in the auth method.

        Supported methods:
            POST: /auth/{mount_point}/role/{role_name}/secret-id. Produces: 200 application/json

        :param role_name: The name for the role.
        :type role_name: str | unicode
        :param metadata: Metadata to be tied to the Secret ID.
        :type metadata: dict
        :param cidr_list: Blocks of IP addresses which can perform login operations.
        :type cidr_list: list
        :param token_bound_cidrs: Blocks of IP addresses which can authenticate successfully.
        :type token_bound_cidrs: list
        :param mount_point: The "path" the method/backend was mounted on.
        :type mount_point: str | unicode
        :param wrap_ttl: Returns the request as a response-wrapping token.
            Can be either an integer number of seconds or a string duration of seconds (`15s`), minutes (`20m`), or hours (`25h`).
        :type wrap_ttl: int | str
        :return: The JSON response of the read_role_id request.
        :rtype: dict
        """
        if metadata is not None and not isinstance(metadata, dict):
            error_msg = 'unsupported metadata argument provided "{arg}" ({arg_type}), required type: dict"'
            raise exceptions.ParamValidationError(
                error_msg.format(
                    arg=metadata,
                    arg_type=type(metadata),
                )
            )

        params = {}
        if metadata:
            params = {"metadata": json.dumps(metadata)}

        list_of_strings_params = {
            "cidr_list": cidr_list,
            "token_bound_cidrs": token_bound_cidrs,
        }
        for param_name, param_argument in list_of_strings_params.items():
            validate_list_of_strings_param(
                param_name=param_name,
                param_argument=param_argument,
            )
            if param_argument is not None:
                params[param_name] = list_to_comma_delimited(param_argument)

        api_path = utils.format_url(
            "/v1/auth/{mount_point}/role/{role_name}/secret-id",
            mount_point=mount_point,
            role_name=role_name,
        )
        return self._adapter.post(url=api_path, json=params, wrap_ttl=wrap_ttl)

    def create_custom_secret_id(
        self,
        role_name,
        secret_id,
        metadata=None,
        cidr_list=None,
        token_bound_cidrs=None,
        mount_point=DEFAULT_MOUNT_POINT,
        wrap_ttl=None,
    ):
        """
        Generates and issues a new Secret ID on a role in the auth method.

        Supported methods:
            POST: /auth/{mount_point}/role/{role_name}/custom-secret-id. Produces: 200 application/json

        :param role_name: The name for the role.
        :type role_name: str | unicode
        :param secret_id: The Secret ID to read.
        :type secret_id: str | unicode
        :param metadata: Metadata to be tied to the Secret ID.
        :type metadata: dict
        :param cidr_list: Blocks of IP addresses which can perform login operations.
        :type cidr_list: list
        :param token_bound_cidrs: Blocks of IP addresses which can authenticate successfully.
        :type token_bound_cidrs: list
        :param mount_point: The "path" the method/backend was mounted on.
        :type mount_point: str | unicode
        :param wrap_ttl: Returns the request as a response-wrapping token.
            Can be either an integer number of seconds or a string duration of seconds (`15s`), minutes (`20m`), or hours (`25h`).
        :type wrap_ttl: int | str
        :return: The JSON response of the read_role_id request.
        :rtype: dict
        """
        if metadata is not None and not isinstance(metadata, dict):
            error_msg = 'unsupported metadata argument provided "{arg}" ({arg_type}), required type: dict"'
            raise exceptions.ParamValidationError(
                error_msg.format(
                    arg=metadata,
                    arg_type=type(metadata),
                )
            )

        params = {"secret_id": secret_id}

        if metadata:
            params["metadata"] = json.dumps(metadata)

        list_of_strings_params = {
            "cidr_list": cidr_list,
            "token_bound_cidrs": token_bound_cidrs,
        }
        for param_name, param_argument in list_of_strings_params.items():
            validate_list_of_strings_param(
                param_name=param_name,
                param_argument=param_argument,
            )
            if param_argument is not None:
                params[param_name] = list_to_comma_delimited(param_argument)

        api_path = utils.format_url(
            "/v1/auth/{mount_point}/role/{role_name}/custom-secret-id",
            mount_point=mount_point,
            role_name=role_name,
        )
        return self._adapter.post(url=api_path, json=params, wrap_ttl=wrap_ttl)

    def read_secret_id(self, role_name, secret_id, mount_point=DEFAULT_MOUNT_POINT):
        """
        Read the properties of a Secret ID for a role in the auth method.

        Supported methods:
            POST: /auth/{mount_point}/role/{role_name}/secret-id/lookup. Produces: 200 application/json

        :param role_name: The name for the role
        :type role_name: str | unicode
        :param secret_id: The Secret ID to read.
        :type secret_id: str | unicode
        :param mount_point: The "path" the method/backend was mounted on.
        :type mount_point: str | unicode
        :return: The JSON response of the read_role_id request.
        :rtype: dict
        """
        params = {"secret_id": secret_id}
        api_path = utils.format_url(
            "/v1/auth/{mount_point}/role/{role_name}/secret-id/lookup",
            mount_point=mount_point,
            role_name=role_name,
        )
        return self._adapter.post(url=api_path, json=params)

    def destroy_secret_id(self, role_name, secret_id, mount_point=DEFAULT_MOUNT_POINT):
        """
        Destroys a Secret ID for a role in the auth method.

        Supported methods:
            POST: /auth/{mount_point}/role/{role_name}/secret-id/destroy. Produces 204 (empty body)

        :param role_name: The name for the role
        :type role_name: str | unicode
        :param secret_id: The Secret ID to read.
        :type secret_id: str | unicode
        :param mount_point: The "path" the method/backend was mounted on.
        :type mount_point: str | unicode
        """
        params = {"secret_id": secret_id}
        api_path = utils.format_url(
            "/v1/auth/{mount_point}/role/{role_name}/secret-id/destroy",
            mount_point=mount_point,
            role_name=role_name,
        )
        return self._adapter.post(url=api_path, json=params)

    def list_secret_id_accessors(self, role_name, mount_point=DEFAULT_MOUNT_POINT):
        """
        Lists accessors of all issued Secret IDs for a role in the auth method.

        Supported methods:
            LIST: /auth/{mount_point}/role/{role_name}/secret-id. Produces: 200 application/json

        :param role_name: The name for the role
        :type role_name: str | unicode
        :param mount_point: The "path" the method/backend was mounted on.
        :type mount_point: str | unicode
        :return: The JSON response of the read_role_id request.
        :rtype: dict
        """
        api_path = utils.format_url(
            "/v1/auth/{mount_point}/role/{role_name}/secret-id",
            mount_point=mount_point,
            role_name=role_name,
        )
        return self._adapter.list(url=api_path)

    def read_secret_id_accessor(
        self, role_name, secret_id_accessor, mount_point=DEFAULT_MOUNT_POINT
    ):
        """
        Read the properties of a Secret ID for a role in the auth method.

        Supported methods:
            POST: /auth/{mount_point}/role/{role_name}/secret-id-accessor/lookup. Produces: 200 application/json

        :param role_name: The name for the role
        :type role_name: str | unicode
        :param secret_id_accessor: The accessor for the Secret ID to read.
        :type secret_id_accessor: str | unicode
        :param mount_point: The "path" the method/backend was mounted on.
        :type mount_point: str | unicode
        :return: The JSON response of the read_role_id request.
        :rtype: dict
        """
        params = {"secret_id_accessor": secret_id_accessor}
        api_path = utils.format_url(
            "/v1/auth/{mount_point}/role/{role_name}/secret-id-accessor/lookup",
            mount_point=mount_point,
            role_name=role_name,
        )
        return self._adapter.post(url=api_path, json=params)

    def destroy_secret_id_accessor(
        self, role_name, secret_id_accessor, mount_point=DEFAULT_MOUNT_POINT
    ):
        """
        Destroys a Secret ID for a role in the auth method.

        Supported methods:
            POST: /auth/{mount_point}/role/{role_name}/secret-id-accessor/destroy. Produces: 204 (empty body)

        :param role_name: The name for the role
        :type role_name: str | unicode
        :param secret_id_accessor: The accessor for the Secret ID to read.
        :type secret_id_accessor: str | unicode
        :param mount_point: The "path" the method/backend was mounted on.
        :type mount_point: str | unicode
        """
        params = {"secret_id_accessor": secret_id_accessor}
        api_path = utils.format_url(
            "/v1/auth/{mount_point}/role/{role_name}/secret-id-accessor/destroy",
            mount_point=mount_point,
            role_name=role_name,
        )
        return self._adapter.post(url=api_path, json=params)

    def login(
        self, role_id, secret_id=None, use_token=True, mount_point=DEFAULT_MOUNT_POINT
    ):
        """
        Login with APPROLE credentials.

        Supported methods:
            POST: /auth/{mount_point}/login. Produces: 200 application/json

        :param role_id: Role ID of the role.
        :type role_id: str | unicode
        :param secret_id: Secret ID of the role.
        :type secret_id: str | unicode
        :param use_token: if True, uses the token in the response received from the auth request to set the "token"
            attribute on the the :py:meth:`hvac.adapters.Adapter` instance under the _adapter Client attribute.
        :type use_token: bool
        :param mount_point: The "path" the method/backend was mounted on.
        :type mount_point: str | unicode
        :return: The JSON response of the read_role_id request.
        :rtype: dict
        """
        params = {"role_id": role_id, "secret_id": secret_id}
        api_path = utils.format_url(
            "/v1/auth/{mount_point}/login", mount_point=mount_point
        )
        return self._adapter.login(
            url=api_path,
            use_token=use_token,
            json=params,
        )