_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 75
19.8k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q22600
|
Transit.generate_random_bytes
|
train
|
def generate_random_bytes(self, n_bytes=32, output_format="base64", mount_point=DEFAULT_MOUNT_POINT):
"""Return high-quality random bytes of the specified length.
Supported methods:
POST: /{mount_point}/random(/{bytes}). Produces: 200 application/json
:param n_bytes: Specifies the number of bytes to return. This value can be specified either in the request body,
or as a part of the URL.
:type n_bytes: int
:param output_format: Specifies the output encoding. Valid options are hex or base64.
:type output_format: str | unicode
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:return: The JSON response of the request.
:rtype: requests.Response
"""
params = {
'bytes': n_bytes,
'format': output_format,
}
api_path = '/v1/{mount_point}/random'.format(mount_point=mount_point)
response = self._adapter.post(
url=api_path,
json=params,
)
return response.json()
|
python
|
{
"resource": ""
}
|
q22601
|
Transit.hash_data
|
train
|
def hash_data(self, hash_input, algorithm="sha2-256", output_format="hex", mount_point=DEFAULT_MOUNT_POINT):
"""Return the cryptographic hash of given data using the specified algorithm.
Supported methods:
POST: /{mount_point}/hash(/{algorithm}). Produces: 200 application/json
:param hash_input: Specifies the base64 encoded input data.
:type hash_input: str | unicode
:param algorithm: Specifies the hash algorithm to use. This can also be specified as part of the URL.
Currently-supported algorithms are: sha2-224, sha2-256, sha2-384, sha2-512
:type algorithm: str | unicode
:param output_format: Specifies the output encoding. This can be either hex or base64.
:type output_format: str | unicode
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:return: The JSON response of the request.
:rtype: requests.Response
"""
if algorithm not in transit_constants.ALLOWED_HASH_DATA_ALGORITHMS:
error_msg = 'invalid algorithm argument provided "{arg}", supported types: "{allowed_types}"'
raise exceptions.ParamValidationError(error_msg.format(
arg=algorithm,
allowed_types=', '.join(transit_constants.ALLOWED_HASH_DATA_ALGORITHMS),
))
if output_format not in transit_constants.ALLOWED_HASH_DATA_FORMATS:
error_msg = 'invalid output_format argument provided "{arg}", supported types: "{allowed_types}"'
raise exceptions.ParamValidationError(error_msg.format(
arg=output_format,
allowed_types=', '.join(transit_constants.ALLOWED_HASH_DATA_FORMATS),
))
params = {
'input': hash_input,
'algorithm': algorithm,
'format': output_format,
}
api_path = '/v1/{mount_point}/hash'.format(mount_point=mount_point)
response = self._adapter.post(
url=api_path,
json=params,
)
return response.json()
|
python
|
{
"resource": ""
}
|
q22602
|
Transit.generate_hmac
|
train
|
def generate_hmac(self, name, hash_input, key_version=None, algorithm="sha2-256", mount_point=DEFAULT_MOUNT_POINT):
"""Return the digest of given data using the specified hash algorithm and the named key.
The key can be of any type supported by transit; the raw key will be marshaled into bytes to be used for the
HMAC function. If the key is of a type that supports rotation, the latest (current) version will be used.
Supported methods:
POST: /{mount_point}/hmac/{name}(/{algorithm}). Produces: 200 application/json
:param name: Specifies the name of the encryption key to generate hmac against. This is specified as part of the
URL.
:type name: str | unicode
:param hash_input: Specifies the base64 encoded input data.
:type input: str | unicode
:param key_version: Specifies the version of the key to use for the operation. If not set, uses the latest
version. Must be greater than or equal to the key's min_encryption_version, if set.
:type key_version: int
:param algorithm: Specifies the hash algorithm to use. This can also be specified as part of the URL.
Currently-supported algorithms are: sha2-224, sha2-256, sha2-384, sha2-512
:type algorithm: str | unicode
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:return: The JSON response of the request.
:rtype: requests.Response
"""
if algorithm not in transit_constants.ALLOWED_HASH_DATA_ALGORITHMS:
error_msg = 'invalid algorithm argument provided "{arg}", supported types: "{allowed_types}"'
raise exceptions.ParamValidationError(error_msg.format(
arg=algorithm,
allowed_types=', '.join(transit_constants.ALLOWED_HASH_DATA_ALGORITHMS),
))
params = {
'input': hash_input,
'key_version': key_version,
'algorithm': algorithm,
}
api_path = '/v1/{mount_point}/hmac/{name}'.format(
mount_point=mount_point,
name=name,
)
resposne = self._adapter.post(
url=api_path,
json=params,
)
return resposne.json()
|
python
|
{
"resource": ""
}
|
q22603
|
Transit.sign_data
|
train
|
def sign_data(self, name, hash_input, key_version=None, hash_algorithm="sha2-256", context="", prehashed=False,
signature_algorithm="pss", mount_point=DEFAULT_MOUNT_POINT):
"""Return the cryptographic signature of the given data using the named key and the specified hash algorithm.
The key must be of a type that supports signing.
Supported methods:
POST: /{mount_point}/sign/{name}(/{hash_algorithm}). Produces: 200 application/json
:param name: Specifies the name of the encryption key to use for signing. This is specified as part of the URL.
:type name: str | unicode
:param hash_input: Specifies the base64 encoded input data.
:type hash_input: str | unicode
:param key_version: Specifies the version of the key to use for signing. If not set, uses the latest version.
Must be greater than or equal to the key's min_encryption_version, if set.
:type key_version: int
:param hash_algorithm: Specifies the hash algorithm to use for supporting key types (notably, not including
ed25519 which specifies its own hash algorithm). This can also be specified as part of the URL.
Currently-supported algorithms are: sha2-224, sha2-256, sha2-384, sha2-512
:type hash_algorithm: str | unicode
:param context: Base64 encoded context for key derivation. Required if key derivation is enabled; currently only
available with ed25519 keys.
:type context: str | unicode
:param prehashed: Set to true when the input is already hashed. If the key type is rsa-2048 or rsa-4096, then
the algorithm used to hash the input should be indicated by the hash_algorithm parameter. Just as the value
to sign should be the base64-encoded representation of the exact binary data you want signed, when set, input
is expected to be base64-encoded binary hashed data, not hex-formatted. (As an example, on the command line,
you could generate a suitable input via openssl dgst -sha256 -binary | base64.)
:type prehashed: bool
:param signature_algorithm: When using a RSA key, specifies the RSA signature algorithm to use for signing.
Supported signature types are: pss, pkcs1v15
:type signature_algorithm: str | unicode
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:return: The JSON response of the request.
:rtype: requests.Response
"""
if hash_algorithm not in transit_constants.ALLOWED_HASH_DATA_ALGORITHMS:
error_msg = 'invalid hash_algorithm argument provided "{arg}", supported types: "{allowed_types}"'
raise exceptions.ParamValidationError(error_msg.format(
arg=hash_algorithm,
allowed_types=', '.join(transit_constants.ALLOWED_HASH_DATA_ALGORITHMS),
))
if signature_algorithm not in transit_constants.ALLOWED_SIGNATURE_ALGORITHMS:
error_msg = 'invalid signature_algorithm argument provided "{arg}", supported types: "{allowed_types}"'
raise exceptions.ParamValidationError(error_msg.format(
arg=signature_algorithm,
allowed_types=', '.join(transit_constants.ALLOWED_SIGNATURE_ALGORITHMS),
))
params = {
'input': hash_input,
'key_version': key_version,
'hash_algorithm': hash_algorithm,
'context': context,
'prehashed': prehashed,
'signature_algorithm': signature_algorithm,
}
api_path = '/v1/{mount_point}/sign/{name}'.format(
mount_point=mount_point,
name=name,
)
response = self._adapter.post(
url=api_path,
json=params,
)
return response.json()
|
python
|
{
"resource": ""
}
|
q22604
|
Transit.backup_key
|
train
|
def backup_key(self, name, mount_point=DEFAULT_MOUNT_POINT):
"""Return a plaintext backup of a named key.
The backup contains all the configuration data and keys of all the versions along with the HMAC key. The
response from this endpoint can be used with the /restore endpoint to restore the key.
Supported methods:
GET: /{mount_point}/backup/{name}. Produces: 200 application/json
:param name: Name of the key.
:type 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 request.
:rtype: requests.Response
"""
api_path = '/v1/{mount_point}/backup/{name}'.format(
mount_point=mount_point,
name=name,
)
response = self._adapter.get(
url=api_path,
)
return response.json()
|
python
|
{
"resource": ""
}
|
q22605
|
Transit.restore_key
|
train
|
def restore_key(self, backup, name=None, force=False, mount_point=DEFAULT_MOUNT_POINT):
"""Restore the backup as a named key.
This will restore the key configurations and all the versions of the named key along with HMAC keys. The input
to this endpoint should be the output of /backup endpoint. For safety, by default the backend will refuse to
restore to an existing key. If you want to reuse a key name, it is recommended you delete the key before
restoring. It is a good idea to attempt restoring to a different key name first to verify that the operation
successfully completes.
Supported methods:
POST: /{mount_point}/restore(/name). Produces: 204 (empty body)
:param backup: Backed up key data to be restored. This should be the output from the /backup endpoint.
:type backup: str | unicode
:param name: If set, this will be the name of the restored key.
:type name: str | unicode
:param force: If set, force the restore to proceed even if a key by this name already exists.
:type force: bool
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:return: The response of the request.
:rtype: requests.Response
"""
params = {
'backup': backup,
'force': force,
}
api_path = '/v1/{mount_point}/restore'.format(mount_point=mount_point)
if name is not None:
api_path = self._adapter.urljoin(api_path, name)
return self._adapter.post(
url=api_path,
json=params,
)
|
python
|
{
"resource": ""
}
|
q22606
|
Transit.trim_key
|
train
|
def trim_key(self, name, min_version, mount_point=DEFAULT_MOUNT_POINT):
"""Trims older key versions setting a minimum version for the keyring.
Once trimmed, previous versions of the key cannot be recovered.
Supported methods:
POST: /{mount_point}/keys/{name}/trim. Produces: 200 application/json
:param name: Specifies the name of the key to be trimmed.
:type name: str | unicode
:param min_version: The minimum version for the key ring. All versions before this version will be permanently
deleted. This value can at most be equal to the lesser of min_decryption_version and min_encryption_version.
This is not allowed to be set when either min_encryption_version or min_decryption_version is set to zero.
:type min_version: int
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:return: The response of the request.
:rtype: requests.Response
"""
params = {
'min_available_version': min_version,
}
api_path = '/v1/{mount_point}/keys/{name}/trim'.format(
mount_point=mount_point,
name=name,
)
return self._adapter.post(
url=api_path,
json=params,
)
|
python
|
{
"resource": ""
}
|
q22607
|
raise_for_error
|
train
|
def raise_for_error(status_code, message=None, errors=None):
"""Helper method to raise exceptions based on the status code of a response received back from Vault.
:param status_code: Status code received in a response from Vault.
:type status_code: int
:param message: Optional message to include in a resulting exception.
:type message: str
:param errors: Optional errors to include in a resulting exception.
:type errors: list | str
:raises: hvac.exceptions.InvalidRequest | hvac.exceptions.Unauthorized | hvac.exceptions.Forbidden |
hvac.exceptions.InvalidPath | hvac.exceptions.RateLimitExceeded | hvac.exceptions.InternalServerError |
hvac.exceptions.VaultNotInitialized | hvac.exceptions.VaultDown | hvac.exceptions.UnexpectedError
"""
if status_code == 400:
raise exceptions.InvalidRequest(message, errors=errors)
elif status_code == 401:
raise exceptions.Unauthorized(message, errors=errors)
elif status_code == 403:
raise exceptions.Forbidden(message, errors=errors)
elif status_code == 404:
raise exceptions.InvalidPath(message, errors=errors)
elif status_code == 429:
raise exceptions.RateLimitExceeded(message, errors=errors)
elif status_code == 500:
raise exceptions.InternalServerError(message, errors=errors)
elif status_code == 501:
raise exceptions.VaultNotInitialized(message, errors=errors)
elif status_code == 503:
raise exceptions.VaultDown(message, errors=errors)
else:
raise exceptions.UnexpectedError(message)
|
python
|
{
"resource": ""
}
|
q22608
|
generate_method_deprecation_message
|
train
|
def generate_method_deprecation_message(to_be_removed_in_version, old_method_name, method_name=None, module_name=None):
"""Generate a message to be used when warning about the use of deprecated methods.
:param to_be_removed_in_version: Version of this module the deprecated method will be removed in.
:type to_be_removed_in_version: str
:param old_method_name: Deprecated method name.
:type old_method_name: str
:param method_name: Method intended to replace the deprecated method indicated. This method's docstrings are
included in the decorated method's docstring.
:type method_name: str
:param module_name: Name of the module containing the new method to use.
:type module_name: str
:return: Full deprecation warning message for the indicated method.
:rtype: str
"""
message = "Call to deprecated function '{old_method_name}'. This method will be removed in version '{version}'".format(
old_method_name=old_method_name,
version=to_be_removed_in_version,
)
if method_name is not None and module_name is not None:
message += " Please use the '{method_name}' method on the '{module_name}' class moving forward.".format(
method_name=method_name,
module_name=module_name,
)
return message
|
python
|
{
"resource": ""
}
|
q22609
|
generate_property_deprecation_message
|
train
|
def generate_property_deprecation_message(to_be_removed_in_version, old_name, new_name, new_attribute,
module_name='Client'):
"""Generate a message to be used when warning about the use of deprecated properties.
:param to_be_removed_in_version: Version of this module the deprecated property will be removed in.
:type to_be_removed_in_version: str
:param old_name: Deprecated property name.
:type old_name: str
:param new_name: Name of the new property name to use.
:type new_name: str
:param new_attribute: The new attribute where the new property can be found.
:type new_attribute: str
:param module_name: Name of the module containing the new method to use.
:type module_name: str
:return: Full deprecation warning message for the indicated property.
:rtype: str
"""
message = "Call to deprecated property '{name}'. This property will be removed in version '{version}'".format(
name=old_name,
version=to_be_removed_in_version,
)
message += " Please use the '{new_name}' property on the '{module_name}.{new_attribute}' attribute moving forward.".format(
new_name=new_name,
module_name=module_name,
new_attribute=new_attribute,
)
return message
|
python
|
{
"resource": ""
}
|
q22610
|
getattr_with_deprecated_properties
|
train
|
def getattr_with_deprecated_properties(obj, item, deprecated_properties):
"""Helper method to use in the getattr method of a class with deprecated properties.
:param obj: Instance of the Class containing the deprecated properties in question.
:type obj: object
:param item: Name of the attribute being requested.
:type item: str
:param deprecated_properties: List of deprecated properties. Each item in the list is a dict with at least a
"to_be_removed_in_version" and "client_property" key to be used in the displayed deprecation warning.
:type deprecated_properties: List[dict]
:return: The new property indicated where available.
:rtype: object
"""
if item in deprecated_properties:
deprecation_message = generate_property_deprecation_message(
to_be_removed_in_version=deprecated_properties[item]['to_be_removed_in_version'],
old_name=item,
new_name=deprecated_properties[item].get('new_property', item),
new_attribute=deprecated_properties[item]['client_property'],
)
warnings.simplefilter('always', DeprecationWarning)
warnings.warn(
message=deprecation_message,
category=DeprecationWarning,
stacklevel=2,
)
warnings.simplefilter('default', DeprecationWarning)
client_property = getattr(obj, deprecated_properties[item]['client_property'])
return getattr(client_property, deprecated_properties[item].get('new_property', item))
raise AttributeError("'{class_name}' has no attribute '{item}'".format(
class_name=obj.__class__.__name__,
item=item,
))
|
python
|
{
"resource": ""
}
|
q22611
|
validate_list_of_strings_param
|
train
|
def validate_list_of_strings_param(param_name, param_argument):
"""Validate that an argument is a list of strings.
:param param_name: The name of the parameter being validated. Used in any resulting exception messages.
:type param_name: str | unicode
:param param_argument: The argument to validate.
:type param_argument: list
:return: True if the argument is validated, False otherwise.
:rtype: bool
"""
if param_argument is None:
param_argument = []
if isinstance(param_argument, str):
param_argument = param_argument.split(',')
if not isinstance(param_argument, list) or not all([isinstance(p, str) for p in param_argument]):
error_msg = 'unsupported {param} argument provided "{arg}" ({arg_type}), required type: List[str]'
raise exceptions.ParamValidationError(error_msg.format(
param=param_name,
arg=param_argument,
arg_type=type(param_argument),
))
|
python
|
{
"resource": ""
}
|
q22612
|
validate_pem_format
|
train
|
def validate_pem_format(param_name, param_argument):
"""Validate that an argument is a PEM-formatted public key or certificate
:param param_name: The name of the parameter being validate. Used in any resulting exception messages.
:type param_name: str | unicode
:param param_argument: The argument to validate
:type param_argument: str | unicode
:return: True if the argument is validate False otherwise
:rtype: bool
"""
def _check_pem(arg):
arg = arg.strip()
if not arg.startswith('-----BEGIN CERTIFICATE-----') \
or not arg.endswith('-----END CERTIFICATE-----'):
return False
return True
if isinstance(param_argument, str):
param_argument = [param_argument]
if not isinstance(param_argument, list) or not all(_check_pem(p) for p in param_argument):
error_msg = 'unsupported {param} public key / certificate format, required type: PEM'
raise exceptions.ParamValidationError(error_msg.format(param=param_name))
|
python
|
{
"resource": ""
}
|
q22613
|
Auth.list_auth_methods
|
train
|
def list_auth_methods(self):
"""List all enabled auth methods.
Supported methods:
GET: /sys/auth. Produces: 200 application/json
:return: The JSON response of the request.
:rtype: dict
"""
api_path = '/v1/sys/auth'
response = self._adapter.get(
url=api_path,
)
return response.json()
|
python
|
{
"resource": ""
}
|
q22614
|
Auth.enable_auth_method
|
train
|
def enable_auth_method(self, method_type, description=None, config=None, plugin_name=None, local=False, path=None):
"""Enable a new auth method.
After enabling, the auth method can be accessed and configured via the auth path specified as part of the URL.
This auth path will be nested under the auth prefix.
Supported methods:
POST: /sys/auth/{path}. Produces: 204 (empty body)
:param method_type: The name of the authentication method type, such as "github" or "token".
:type method_type: str | unicode
:param description: A human-friendly description of the auth method.
:type description: str | unicode
:param config: Configuration options for this auth method. These are the possible values:
* **default_lease_ttl**: The default lease duration, specified as a string duration like "5s" or "30m".
* **max_lease_ttl**: The maximum lease duration, specified as a string duration like "5s" or "30m".
* **audit_non_hmac_request_keys**: Comma-separated list of keys that will not be HMAC'd by audit devices in
the request data object.
* **audit_non_hmac_response_keys**: Comma-separated list of keys that will not be HMAC'd by audit devices in
the response data object.
* **listing_visibility**: Speficies whether to show this mount in the UI-specific listing endpoint.
* **passthrough_request_headers**: Comma-separated list of headers to whitelist and pass from the request to
the backend.
:type config: dict
:param plugin_name: The name of the auth plugin to use based from the name in the plugin catalog. Applies only
to plugin methods.
:type plugin_name: str | unicode
:param local: <Vault enterprise only> Specifies if the auth method is a local only. Local auth methods are not
replicated nor (if a secondary) removed by replication.
:type local: bool
:param path: The path to mount the method on. If not provided, defaults to the value of the "method_type"
argument.
:type path: str | unicode
:return: The response of the request.
:rtype: requests.Response
"""
if path is None:
path = method_type
params = {
'type': method_type,
'description': description,
'config': config,
'plugin_name': plugin_name,
'local': local,
}
api_path = '/v1/sys/auth/{path}'.format(path=path)
return self._adapter.post(
url=api_path,
json=params
)
|
python
|
{
"resource": ""
}
|
q22615
|
Auth.disable_auth_method
|
train
|
def disable_auth_method(self, path):
"""Disable the auth method at the given auth path.
Supported methods:
DELETE: /sys/auth/{path}. Produces: 204 (empty body)
:param path: The path the method was mounted on. If not provided, defaults to the value of the "method_type"
argument.
:type path: str | unicode
:return: The response of the request.
:rtype: requests.Response
"""
api_path = '/v1/sys/auth/{path}'.format(path=path)
return self._adapter.delete(
url=api_path,
)
|
python
|
{
"resource": ""
}
|
q22616
|
Auth.read_auth_method_tuning
|
train
|
def read_auth_method_tuning(self, path):
"""Read the given auth path's configuration.
This endpoint requires sudo capability on the final path, but the same functionality can be achieved without
sudo via sys/mounts/auth/[auth-path]/tune.
Supported methods:
GET: /sys/auth/{path}/tune. Produces: 200 application/json
:param path: The path the method was mounted on. If not provided, defaults to the value of the "method_type"
argument.
:type path: str | unicode
:return: The JSON response of the request.
:rtype: dict
"""
api_path = '/v1/sys/auth/{path}/tune'.format(
path=path,
)
response = self._adapter.get(
url=api_path,
)
return response.json()
|
python
|
{
"resource": ""
}
|
q22617
|
Auth.tune_auth_method
|
train
|
def tune_auth_method(self, path, default_lease_ttl=None, max_lease_ttl=None, description=None,
audit_non_hmac_request_keys=None, audit_non_hmac_response_keys=None, listing_visibility='',
passthrough_request_headers=None):
"""Tune configuration parameters for a given auth path.
This endpoint requires sudo capability on the final path, but the same functionality can be achieved without
sudo via sys/mounts/auth/[auth-path]/tune.
Supported methods:
POST: /sys/auth/{path}/tune. Produces: 204 (empty body)
:param path: The path the method was mounted on. If not provided, defaults to the value of the "method_type"
argument.
:type path: str | unicode
:param default_lease_ttl: Specifies the default time-to-live. If set on a specific auth path, this overrides the
global default.
:type default_lease_ttl: int
:param max_lease_ttl: The maximum time-to-live. If set on a specific auth path, this overrides the global
default.
:type max_lease_ttl: int
:param description: Specifies the description of the mount. This overrides the current stored value, if any.
:type description: str | unicode
:param audit_non_hmac_request_keys: Specifies the list of keys that will not be HMAC'd by audit devices in the
request data object.
:type audit_non_hmac_request_keys: array
:param audit_non_hmac_response_keys: Specifies the list of keys that will not be HMAC'd by audit devices in the
response data object.
:type audit_non_hmac_response_keys: list
:param listing_visibility: Specifies whether to show this mount in the UI-specific listing endpoint. Valid
values are "unauth" or "".
:type listing_visibility: list
:param passthrough_request_headers: List of headers to whitelist and pass from the request to the backend.
:type passthrough_request_headers: list
:return: The response of the request.
:rtype: requests.Response
"""
if listing_visibility not in ['unauth', '']:
error_msg = 'invalid listing_visibility argument provided: "{arg}"; valid values: "unauth" or ""'.format(
arg=listing_visibility,
)
raise exceptions.ParamValidationError(error_msg)
# All parameters are optional for this method. Until/unless we include input validation, we simply loop over the
# parameters and add which parameters are set.
optional_parameters = {
'default_lease_ttl': dict(),
'max_lease_ttl': dict(),
'description': dict(),
'audit_non_hmac_request_keys': dict(comma_delimited_list=True),
'audit_non_hmac_response_keys': dict(comma_delimited_list=True),
'listing_visibility': dict(),
'passthrough_request_headers': dict(comma_delimited_list=True),
}
params = {}
for optional_parameter, parameter_specification in optional_parameters.items():
if locals().get(optional_parameter) is not None:
if parameter_specification.get('comma_delimited_list'):
argument = locals().get(optional_parameter)
validate_list_of_strings_param(optional_parameter, argument)
params[optional_parameter] = list_to_comma_delimited(argument)
else:
params[optional_parameter] = locals().get(optional_parameter)
api_path = '/v1/sys/auth/{path}/tune'.format(path=path)
return self._adapter.post(
url=api_path,
json=params,
)
|
python
|
{
"resource": ""
}
|
q22618
|
Seal.read_seal_status
|
train
|
def read_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
"""
api_path = '/v1/sys/seal-status'
response = self._adapter.get(
url=api_path,
)
return response.json()
|
python
|
{
"resource": ""
}
|
q22619
|
Seal.submit_unseal_key
|
train
|
def submit_unseal_key(self, key=None, reset=False, migrate=False):
"""Enter a single master key share to progress the unsealing of the Vault.
If the threshold number of master key shares is reached, Vault will attempt to unseal the Vault. Otherwise, this
API must be called multiple times until that threshold is met.
Either the key or reset parameter must be provided; if both are provided, reset takes precedence.
Supported methods:
PUT: /sys/unseal. Produces: 200 application/json
:param key: Specifies a single master key share. This is required unless reset is true.
:type key: str | unicode
:param reset: Specifies if previously-provided unseal keys are discarded and the unseal process is reset.
:type reset: bool
:param migrate: Available in 1.0 Beta - Used to migrate the seal from shamir to autoseal or autoseal to shamir.
Must be provided on all unseal key calls.
:type: migrate: bool
:return: The JSON response of the request.
:rtype: dict
"""
params = {
'migrate': migrate,
}
if not reset and key is not None:
params['key'] = key
elif reset:
params['reset'] = reset
api_path = '/v1/sys/unseal'
response = self._adapter.put(
url=api_path,
json=params,
)
return response.json()
|
python
|
{
"resource": ""
}
|
q22620
|
Seal.submit_unseal_keys
|
train
|
def submit_unseal_keys(self, keys, migrate=False):
"""Enter multiple master key share to progress the unsealing of the Vault.
:param keys: List of master key shares.
:type keys: List[str]
:param migrate: Available in 1.0 Beta - Used to migrate the seal from shamir to autoseal or autoseal to shamir.
Must be provided on all unseal key calls.
:type: migrate: bool
:return: The JSON response of the last unseal request.
:rtype: dict
"""
result = None
for key in keys:
result = self.submit_unseal_key(
key=key,
migrate=migrate,
)
if not result['sealed']:
break
return result
|
python
|
{
"resource": ""
}
|
q22621
|
Request.request
|
train
|
def request(self, method, url, headers=None, raise_exception=True, **kwargs):
"""Main method for routing HTTP requests to the configured Vault base_uri.
:param method: HTTP method to use with the request. E.g., GET, POST, etc.
:type method: str
:param url: Partial URL path to send the request to. This will be joined to the end of the instance's base_uri
attribute.
:type url: str | unicode
:param headers: Additional headers to include with the request.
:type headers: dict
:param raise_exception: If True, raise an exception via utils.raise_for_error(). Set this parameter to False to
bypass this functionality.
:type raise_exception: bool
:param kwargs: Additional keyword arguments to include in the requests call.
:type kwargs: dict
:return: The response of the request.
:rtype: requests.Response
"""
if '//' in url:
# Vault CLI treats a double forward slash ('//') as a single forward slash for a given path.
# To avoid issues with the requests module's redirection logic, we perform the same translation here.
logger.warning('Replacing double-slashes ("//") in path with single slash ("/") to avoid Vault redirect response.')
url = url.replace('//', '/')
url = self.urljoin(self.base_uri, url)
if not headers:
headers = {}
if self.token:
headers['X-Vault-Token'] = self.token
if self.namespace:
headers['X-Vault-Namespace'] = self.namespace
wrap_ttl = kwargs.pop('wrap_ttl', None)
if wrap_ttl:
headers['X-Vault-Wrap-TTL'] = str(wrap_ttl)
_kwargs = self._kwargs.copy()
_kwargs.update(kwargs)
response = self.session.request(
method=method,
url=url,
headers=headers,
allow_redirects=self.allow_redirects,
**_kwargs
)
if raise_exception and 400 <= response.status_code < 600:
text = errors = None
if response.headers.get('Content-Type') == 'application/json':
errors = response.json().get('errors')
if errors is None:
text = response.text
utils.raise_for_error(response.status_code, text, errors=errors)
return response
|
python
|
{
"resource": ""
}
|
q22622
|
Key.read_root_generation_progress
|
train
|
def read_root_generation_progress(self):
"""Read the configuration and process of the current root generation attempt.
Supported methods:
GET: /sys/generate-root/attempt. Produces: 200 application/json
:return: The JSON response of the request.
:rtype: dict
"""
api_path = '/v1/sys/generate-root/attempt'
response = self._adapter.get(
url=api_path,
)
return response.json()
|
python
|
{
"resource": ""
}
|
q22623
|
Key.start_root_token_generation
|
train
|
def start_root_token_generation(self, otp=None, pgp_key=None):
"""Initialize a new root generation attempt.
Only a single root generation attempt can take place at a time. One (and only one) of otp or pgp_key are
required.
Supported methods:
PUT: /sys/generate-root/attempt. Produces: 200 application/json
:param otp: Specifies a base64-encoded 16-byte value. The raw bytes of the token will be XOR'd with this value
before being returned to the final unseal key provider.
:type otp: str | unicode
:param pgp_key: Specifies a base64-encoded PGP public key. The raw bytes of the token will be encrypted with
this value before being returned to the final unseal key provider.
:type pgp_key: str | unicode
:return: The JSON response of the request.
:rtype: dict
"""
params = {}
if otp is not None and pgp_key is not None:
raise ParamValidationError('one (and only one) of otp or pgp_key arguments are required')
if otp is not None:
params['otp'] = otp
if pgp_key is not None:
params['pgp_key'] = pgp_key
api_path = '/v1/sys/generate-root/attempt'
response = self._adapter.put(
url=api_path,
json=params
)
return response.json()
|
python
|
{
"resource": ""
}
|
q22624
|
Key.generate_root
|
train
|
def generate_root(self, key, nonce):
"""Enter a single master key share to progress the root generation attempt.
If the threshold number of master key shares is reached, Vault will complete the root generation and issue the
new token. Otherwise, this API must be called multiple times until that threshold is met. The attempt nonce must
be provided with each call.
Supported methods:
PUT: /sys/generate-root/update. Produces: 200 application/json
:param key: Specifies a single master key share.
:type key: str | unicode
:param nonce: The nonce of the attempt.
:type nonce: str | unicode
:return: The JSON response of the request.
:rtype: dict
"""
params = {
'key': key,
'nonce': nonce,
}
api_path = '/v1/sys/generate-root/update'
response = self._adapter.put(
url=api_path,
json=params,
)
return response.json()
|
python
|
{
"resource": ""
}
|
q22625
|
Key.cancel_root_generation
|
train
|
def cancel_root_generation(self):
"""Cancel any in-progress root generation attempt.
This clears any progress made. This must be called to change the OTP or PGP key being used.
Supported methods:
DELETE: /sys/generate-root/attempt. Produces: 204 (empty body)
:return: The response of the request.
:rtype: request.Response
"""
api_path = '/v1/sys/generate-root/attempt'
response = self._adapter.delete(
url=api_path,
)
return response
|
python
|
{
"resource": ""
}
|
q22626
|
Key.get_encryption_key_status
|
train
|
def get_encryption_key_status(self):
"""Read information about the current encryption key used by Vault.
Supported methods:
GET: /sys/key-status. Produces: 200 application/json
:return: JSON response with information regarding the current encryption key used by Vault.
:rtype: dict
"""
api_path = '/v1/sys/key-status'
response = self._adapter.get(
url=api_path,
)
return response.json()
|
python
|
{
"resource": ""
}
|
q22627
|
Key.rotate_encryption_key
|
train
|
def rotate_encryption_key(self):
"""Trigger a rotation of the backend encryption key.
This is the key that is used to encrypt data written to the storage backend, and is not provided to operators.
This operation is done online. Future values are encrypted with the new key, while old values are decrypted with
previous encryption keys.
This path requires sudo capability in addition to update.
Supported methods:
PUT: /sys/rorate. Produces: 204 (empty body)
:return: The response of the request.
:rtype: requests.Response
"""
api_path = '/v1/sys/rotate'
response = self._adapter.put(
url=api_path,
)
return response
|
python
|
{
"resource": ""
}
|
q22628
|
Key.start_rekey
|
train
|
def start_rekey(self, secret_shares=5, secret_threshold=3, pgp_keys=None, backup=False, require_verification=False, recovery_key=False):
"""Initializes a new rekey attempt.
Only a single recovery key rekeyattempt can take place at a time, and changing the parameters of a rekey
requires canceling and starting a new rekey, which will also provide a new nonce.
Supported methods:
PUT: /sys/rekey/init. Produces: 204 (empty body)
PUT: /sys/rekey-recovery-key/init. Produces: 204 (empty body)
:param secret_shares: Specifies the number of shares to split the master key into.
:type secret_shares: int
:param secret_threshold: Specifies the number of shares required to reconstruct the master key. This must be
less than or equal to secret_shares.
:type secret_threshold: int
:param pgp_keys: Specifies an array of PGP public keys used to encrypt the output unseal keys. Ordering is
preserved. The keys must be base64-encoded from their original binary representation. The size of this array
must be the same as secret_shares.
:type pgp_keys: list
:param backup: Specifies if using PGP-encrypted keys, whether Vault should also store a plaintext backup of the
PGP-encrypted keys at core/unseal-keys-backup in the physical storage backend. These can then be retrieved
and removed via the sys/rekey/backup endpoint.
:type backup: bool
:param require_verification: This turns on verification functionality. When verification is turned on, after
successful authorization with the current unseal keys, the new unseal keys are returned but the master key
is not actually rotated. The new keys must be provided to authorize the actual rotation of the master key.
This ensures that the new keys have been successfully saved and protects against a risk of the keys being
lost after rotation but before they can be persisted. This can be used with without pgp_keys, and when used
with it, it allows ensuring that the returned keys can be successfully decrypted before committing to the
new shares, which the backup functionality does not provide.
:param recovery_key: If true, send requests to "rekey-recovery-key" instead of "rekey" api path.
:type recovery_key: bool
:type require_verification: bool
:return: The JSON dict of the response.
:rtype: dict | request.Response
"""
params = {
'secret_shares': secret_shares,
'secret_threshold': secret_threshold,
'require_verification': require_verification,
}
if pgp_keys:
if len(pgp_keys) != secret_shares:
raise ParamValidationError('length of pgp_keys argument must equal secret shares value')
params['pgp_keys'] = pgp_keys
params['backup'] = backup
api_path = '/v1/sys/rekey/init'
if recovery_key:
api_path = '/v1/sys/rekey-recovery-key/init'
response = self._adapter.put(
url=api_path,
json=params,
)
return response.json()
|
python
|
{
"resource": ""
}
|
q22629
|
Key.cancel_rekey
|
train
|
def cancel_rekey(self, recovery_key=False):
"""Cancel any in-progress rekey.
This clears the rekey settings as well as any progress made. This must be called to change the parameters of the
rekey.
Note: Verification is still a part of a rekey. If rekeying is canceled during the verification flow, the current
unseal keys remain valid.
Supported methods:
DELETE: /sys/rekey/init. Produces: 204 (empty body)
DELETE: /sys/rekey-recovery-key/init. Produces: 204 (empty body)
:param recovery_key: If true, send requests to "rekey-recovery-key" instead of "rekey" api path.
:type recovery_key: bool
:return: The response of the request.
:rtype: requests.Response
"""
api_path = '/v1/sys/rekey/init'
if recovery_key:
api_path = '/v1/sys/rekey-recovery-key/init'
response = self._adapter.delete(
url=api_path,
)
return response
|
python
|
{
"resource": ""
}
|
q22630
|
Key.rekey
|
train
|
def rekey(self, key, nonce=None, recovery_key=False):
"""Enter a single recovery key share to progress the rekey of the Vault.
If the threshold number of recovery key shares is reached, Vault will complete the rekey. Otherwise, this API
must be called multiple times until that threshold is met. The rekey nonce operation must be provided with each
call.
Supported methods:
PUT: /sys/rekey/update. Produces: 200 application/json
PUT: /sys/rekey-recovery-key/update. Produces: 200 application/json
:param key: Specifies a single recovery share key.
:type key: str | unicode
:param nonce: Specifies the nonce of the rekey operation.
:type nonce: str | unicode
:param recovery_key: If true, send requests to "rekey-recovery-key" instead of "rekey" api path.
:type recovery_key: bool
:return: The JSON response of the request.
:rtype: dict
"""
params = {
'key': key,
}
if nonce is not None:
params['nonce'] = nonce
api_path = '/v1/sys/rekey/update'
if recovery_key:
api_path = '/v1/sys/rekey-recovery-key/update'
response = self._adapter.put(
url=api_path,
json=params,
)
return response.json()
|
python
|
{
"resource": ""
}
|
q22631
|
Key.rekey_multi
|
train
|
def rekey_multi(self, keys, nonce=None, recovery_key=False):
"""Enter multiple recovery key shares to progress the rekey of the Vault.
If the threshold number of recovery key shares is reached, Vault will complete the rekey.
:param keys: Specifies multiple recovery share keys.
:type keys: list
:param nonce: Specifies the nonce of the rekey operation.
:type nonce: str | unicode
:param recovery_key: If true, send requests to "rekey-recovery-key" instead of "rekey" api path.
:type recovery_key: bool
:return: The last response of the rekey request.
:rtype: response.Request
"""
result = None
for key in keys:
result = self.rekey(
key=key,
nonce=nonce,
recovery_key=recovery_key,
)
if result.get('complete'):
break
return result
|
python
|
{
"resource": ""
}
|
q22632
|
Key.read_backup_keys
|
train
|
def read_backup_keys(self, recovery_key=False):
"""Retrieve the backup copy of PGP-encrypted unseal keys.
The returned value is the nonce of the rekey operation and a map of PGP key fingerprint to hex-encoded
PGP-encrypted key.
Supported methods:
PUT: /sys/rekey/backup. Produces: 200 application/json
PUT: /sys/rekey-recovery-key/backup. Produces: 200 application/json
:param recovery_key: If true, send requests to "rekey-recovery-key" instead of "rekey" api path.
:type recovery_key: bool
:return: The JSON response of the request.
:rtype: dict
"""
api_path = '/v1/sys/rekey/backup'
if recovery_key:
api_path = '/v1/sys/rekey-recovery-key/backup'
response = self._adapter.get(
url=api_path,
)
return response.json()
|
python
|
{
"resource": ""
}
|
q22633
|
Mount.enable_secrets_engine
|
train
|
def enable_secrets_engine(self, backend_type, path=None, description=None, config=None, plugin_name=None,
options=None, local=False, seal_wrap=False):
"""Enable a new secrets engine at the given path.
Supported methods:
POST: /sys/mounts/{path}. Produces: 204 (empty body)
:param backend_type: The name of the backend type, such as "github" or "token".
:type backend_type: str | unicode
:param path: The path to mount the method on. If not provided, defaults to the value of the "method_type"
argument.
:type path: str | unicode
:param description: A human-friendly description of the mount.
:type description: str | unicode
:param config: Configuration options for this mount. These are the possible values:
* **default_lease_ttl**: The default lease duration, specified as a string duration like "5s" or "30m".
* **max_lease_ttl**: The maximum lease duration, specified as a string duration like "5s" or "30m".
* **force_no_cache**: Disable caching.
* **plugin_name**: The name of the plugin in the plugin catalog to use.
* **audit_non_hmac_request_keys**: Comma-separated list of keys that will not be HMAC'd by audit devices in
the request data object.
* **audit_non_hmac_response_keys**: Comma-separated list of keys that will not be HMAC'd by audit devices in
the response data object.
* **listing_visibility**: Specifies whether to show this mount in the UI-specific listing endpoint. ("unauth" or "hidden")
* **passthrough_request_headers**: Comma-separated list of headers to whitelist and pass from the request to
the backend.
:type config: dict
:param options: Specifies mount type specific options that are passed to the backend.
* **version**: <KV> The version of the KV to mount. Set to "2" for mount KV v2.
:type options: dict
:param plugin_name: Specifies the name of the plugin to use based from the name in the plugin catalog. Applies only to plugin backends.
:type plugin_name: str | unicode
:param local: <Vault enterprise only> Specifies if the auth method is a local only. Local auth methods are not
replicated nor (if a secondary) removed by replication.
:type local: bool
:param seal_wrap: <Vault enterprise only> Enable seal wrapping for the mount.
:type seal_wrap: bool
:return: The response of the request.
:rtype: requests.Response
"""
if path is None:
path = backend_type
params = {
'type': backend_type,
'description': description,
'config': config,
'options': options,
'plugin_name': plugin_name,
'local': local,
'seal_wrap': seal_wrap,
}
api_path = '/v1/sys/mounts/{path}'.format(path=path)
return self._adapter.post(
url=api_path,
json=params,
)
|
python
|
{
"resource": ""
}
|
q22634
|
Mount.disable_secrets_engine
|
train
|
def disable_secrets_engine(self, path):
"""Disable the mount point specified by the provided path.
Supported methods:
DELETE: /sys/mounts/{path}. Produces: 204 (empty body)
:param path: Specifies the path where the secrets engine will be mounted. This is specified as part of the URL.
:type path: str | unicode
:return: The response of the request.
:rtype: requests.Response
"""
api_path = '/v1/sys/mounts/{path}'.format(path=path)
return self._adapter.delete(
url=api_path,
)
|
python
|
{
"resource": ""
}
|
q22635
|
Mount.tune_mount_configuration
|
train
|
def tune_mount_configuration(self, path, default_lease_ttl=None, max_lease_ttl=None, description=None,
audit_non_hmac_request_keys=None, audit_non_hmac_response_keys=None,
listing_visibility=None, passthrough_request_headers=None, options=None):
"""Tune configuration parameters for a given mount point.
Supported methods:
POST: /sys/mounts/{path}/tune. Produces: 204 (empty body)
:param path: Specifies the path where the secrets engine will be mounted. This is specified as part of the URL.
:type path: str | unicode
:param mount_point: The path the associated secret backend is mounted
:type mount_point: str
:param description: Specifies the description of the mount. This overrides the current stored value, if any.
:type description: str
:param default_lease_ttl: Default time-to-live. This overrides the global default. A value of 0 is equivalent to
the system default TTL
:type default_lease_ttl: int
:param max_lease_ttl: Maximum time-to-live. This overrides the global default. A value of 0 are equivalent and
set to the system max TTL.
:type max_lease_ttl: int
:param audit_non_hmac_request_keys: Specifies the comma-separated list of keys that will not be HMAC'd by audit
devices in the request data object.
:type audit_non_hmac_request_keys: list
:param audit_non_hmac_response_keys: Specifies the comma-separated list of keys that will not be HMAC'd by audit
devices in the response data object.
:type audit_non_hmac_response_keys: list
:param listing_visibility: Speficies whether to show this mount in the UI-specific listing endpoint. Valid
values are "unauth" or "".
:type listing_visibility: str
:param passthrough_request_headers: Comma-separated list of headers to whitelist and pass from the request
to the backend.
:type passthrough_request_headers: str
:param options: Specifies mount type specific options that are passed to the backend.
* **version**: <KV> The version of the KV to mount. Set to "2" for mount KV v2.
:type options: dict
:return: The response from the request.
:rtype: request.Response
"""
# All parameters are optional for this method. Until/unless we include input validation, we simply loop over the
# parameters and add which parameters are set.
optional_parameters = [
'default_lease_ttl',
'max_lease_ttl',
'description',
'audit_non_hmac_request_keys',
'audit_non_hmac_response_keys',
'listing_visibility',
'passthrough_request_headers',
'options',
]
params = {}
for optional_parameter in optional_parameters:
if locals().get(optional_parameter) is not None:
params[optional_parameter] = locals().get(optional_parameter)
api_path = '/v1/sys/mounts/{path}/tune'.format(path=path)
return self._adapter.post(
url=api_path,
json=params,
)
|
python
|
{
"resource": ""
}
|
q22636
|
Mount.move_backend
|
train
|
def move_backend(self, from_path, to_path):
"""Move an already-mounted backend to a new mount point.
Supported methods:
POST: /sys/remount. Produces: 204 (empty body)
:param from_path: Specifies the previous mount point.
:type from_path: str | unicode
:param to_path: Specifies the new destination mount point.
:type to_path: str | unicode
:return: The response of the request.
:rtype: requests.Response
"""
params = {
'from': from_path,
'to': to_path,
}
api_path = '/v1/sys/remount'
return self._adapter.post(
url=api_path,
json=params,
)
|
python
|
{
"resource": ""
}
|
q22637
|
Kubernetes.configure
|
train
|
def configure(self, kubernetes_host, kubernetes_ca_cert='', token_reviewer_jwt='', pem_keys=None,
mount_point=DEFAULT_MOUNT_POINT):
"""Configure the connection parameters for Kubernetes.
This path honors the distinction between the create and update capabilities inside ACL policies.
Supported methods:
POST: /auth/{mount_point}/config. Produces: 204 (empty body)
:param kubernetes_host: Host must be a host string, a host:port pair, or a URL to the base of the
Kubernetes API server. Example: https://k8s.example.com:443
:type kubernetes_host: str | unicode
:param kubernetes_ca_cert: PEM encoded CA cert for use by the TLS client used to talk with the Kubernetes API.
NOTE: Every line must end with a newline: \n
:type kubernetes_ca_cert: str | unicode
:param token_reviewer_jwt: A service account JWT used to access the TokenReview API to validate other
JWTs during login. If not set the JWT used for login will be used to access the API.
:type token_reviewer_jwt: str | unicode
:param pem_keys: Optional list of PEM-formatted public keys or certificates used to verify the signatures of
Kubernetes service account JWTs. If a certificate is given, its public key will be extracted. Not every
installation of Kubernetes exposes these keys.
:type pem_keys: list
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:return: The response of the configure_method request.
:rtype: requests.Response
"""
if pem_keys is None:
pem_keys = []
list_of_pem_params = {
'kubernetes_ca_cert': kubernetes_ca_cert,
'pem_keys': pem_keys
}
for param_name, param_argument in list_of_pem_params.items():
validate_pem_format(
param_name=param_name,
param_argument=param_argument,
)
params = {
'kubernetes_host': kubernetes_host,
'kubernetes_ca_cert': kubernetes_ca_cert,
'token_reviewer_jwt': token_reviewer_jwt,
'pem_keys': pem_keys,
}
api_path = '/v1/auth/{mount_point}/config'.format(
mount_point=mount_point
)
return self._adapter.post(
url=api_path,
json=params,
)
|
python
|
{
"resource": ""
}
|
q22638
|
Azure.list_roles
|
train
|
def list_roles(self, mount_point=DEFAULT_MOUNT_POINT):
"""List all the roles that are registered with the plugin.
Supported methods:
LIST: /auth/{mount_point}/roles. Produces: 200 application/json
:param mount_point: The "path" the azure auth method was mounted on.
:type mount_point: str | unicode
:return: The "data" key from the JSON response of the request.
:rtype: dict
"""
api_path = '/v1/auth/{mount_point}/roles'.format(mount_point=mount_point)
response = self._adapter.list(
url=api_path
)
return response.json().get('data')
|
python
|
{
"resource": ""
}
|
q22639
|
Azure.login
|
train
|
def login(self, role, jwt, subscription_id=None, resource_group_name=None, vm_name=None, vmss_name=None, use_token=True,
mount_point=DEFAULT_MOUNT_POINT):
"""Fetch a token.
This endpoint takes a signed JSON Web Token (JWT) and a role name for some entity. It verifies the JWT signature
to authenticate that entity and then authorizes the entity for the given role.
Supported methods:
POST: /auth/{mount_point}/login. Produces: 200 application/json
:param role: Name of the role against which the login is being attempted.
:type role: str | unicode
:param jwt: Signed JSON Web Token (JWT) from Azure MSI.
:type jwt: str | unicode
:param subscription_id: The subscription ID for the machine that generated the MSI token. This information can
be obtained through instance metadata.
:type subscription_id: str | unicode
:param resource_group_name: The resource group for the machine that generated the MSI token. This information
can be obtained through instance metadata.
:type resource_group_name: str | unicode
:param vm_name: The virtual machine name for the machine that generated the MSI token. This information can be
obtained through instance metadata. If vmss_name is provided, this value is ignored.
:type vm_name: str | unicode
:param vmss_name: The virtual machine scale set name for the machine that generated the MSI token. This
information can be obtained through instance metadata.
:type vmss_name: 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 _adapater Client attribute.
:type use_token: bool
:param mount_point: The "path" the azure auth method was mounted on.
:type mount_point: str | unicode
:return: The JSON response of the request.
:rtype: dict
"""
params = {
'role': role,
'jwt': jwt,
}
if subscription_id is not None:
params['subscription_id'] = subscription_id
if resource_group_name is not None:
params['resource_group_name'] = resource_group_name
if vm_name is not None:
params['vm_name'] = vm_name
if vmss_name is not None:
params['vmss_name'] = vmss_name
api_path = '/v1/auth/{mount_point}/login'.format(mount_point=mount_point)
response = self._adapter.login(
url=api_path,
use_token=use_token,
json=params,
)
return response
|
python
|
{
"resource": ""
}
|
q22640
|
Audit.enable_audit_device
|
train
|
def enable_audit_device(self, device_type, description=None, options=None, path=None):
"""Enable a new audit device at the supplied path.
The path can be a single word name or a more complex, nested path.
Supported methods:
PUT: /sys/audit/{path}. Produces: 204 (empty body)
:param device_type: Specifies the type of the audit device.
:type device_type: str | unicode
:param description: Human-friendly description of the audit device.
:type description: str | unicode
:param options: Configuration options to pass to the audit device itself. This is
dependent on the audit device type.
:type options: str | unicode
:param path: Specifies the path in which to enable the audit device. This is part of
the request URL.
:type path: str | unicode
:return: The response of the request.
:rtype: requests.Response
"""
if path is None:
path = device_type
params = {
'type': device_type,
'description': description,
'options': options,
}
api_path = '/v1/sys/audit/{path}'.format(path=path)
return self._adapter.post(
url=api_path,
json=params
)
|
python
|
{
"resource": ""
}
|
q22641
|
Audit.disable_audit_device
|
train
|
def disable_audit_device(self, path):
"""Disable the audit device at the given path.
Supported methods:
DELETE: /sys/audit/{path}. Produces: 204 (empty body)
:param path: The path of the audit device to delete. This is part of the request URL.
:type path: str | unicode
:return: The response of the request.
:rtype: requests.Response
"""
api_path = '/v1/sys/audit/{path}'.format(path=path)
return self._adapter.delete(
url=api_path,
)
|
python
|
{
"resource": ""
}
|
q22642
|
Audit.calculate_hash
|
train
|
def calculate_hash(self, path, input_to_hash):
"""Hash the given input data with the specified audit device's hash function and salt.
This endpoint can be used to discover whether a given plaintext string (the input parameter) appears in the
audit log in obfuscated form.
Supported methods:
POST: /sys/audit-hash/{path}. Produces: 204 (empty body)
:param path: The path of the audit device to generate hashes for. This is part of the request URL.
:type path: str | unicode
:param input_to_hash: The input string to hash.
:type input_to_hash: str | unicode
:return: The JSON response of the request.
:rtype: requests.Response
"""
params = {
'input': input_to_hash,
}
api_path = '/v1/sys/audit-hash/{path}'.format(path=path)
response = self._adapter.post(
url=api_path,
json=params
)
return response.json()
|
python
|
{
"resource": ""
}
|
q22643
|
Policy.list_policies
|
train
|
def list_policies(self):
"""List all configured policies.
Supported methods:
GET: /sys/policy. Produces: 200 application/json
:return: The JSON response of the request.
:rtype: dict
"""
api_path = '/v1/sys/policy'
response = self._adapter.get(
url=api_path,
)
return response.json()
|
python
|
{
"resource": ""
}
|
q22644
|
Policy.delete_policy
|
train
|
def delete_policy(self, name):
"""Delete the policy with the given name.
This will immediately affect all users associated with this policy.
Supported methods:
DELETE: /sys/policy/{name}. Produces: 204 (empty body)
:param name: Specifies the name of the policy to delete.
:type name: str | unicode
:return: The response of the request.
:rtype: requests.Response
"""
api_path = '/v1/sys/policy/{name}'.format(name=name)
return self._adapter.delete(
url=api_path,
)
|
python
|
{
"resource": ""
}
|
q22645
|
Client.is_authenticated
|
train
|
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
|
python
|
{
"resource": ""
}
|
q22646
|
Health.read_health_status
|
train
|
def read_health_status(self, standby_ok=False, active_code=200, standby_code=429, dr_secondary_code=472,
performance_standby_code=473, sealed_code=503, uninit_code=501, method='HEAD'):
"""Read the health status of Vault.
This matches the semantics of a Consul HTTP health check and provides a simple way to monitor the health of a
Vault instance.
:param standby_ok: Specifies if being a standby should still return the active status code instead of the
standby status code. This is useful when Vault is behind a non-configurable load balance that just wants a
200-level response.
:type standby_ok: bool
:param active_code: The status code that should be returned for an active node.
:type active_code: int
:param standby_code: Specifies the status code that should be returned for a standby node.
:type standby_code: int
:param dr_secondary_code: Specifies the status code that should be returned for a DR secondary node.
:type dr_secondary_code: int
:param performance_standby_code: Specifies the status code that should be returned for a performance standby
node.
:type performance_standby_code: int
:param sealed_code: Specifies the status code that should be returned for a sealed node.
:type sealed_code: int
:param uninit_code: Specifies the status code that should be returned for a uninitialized node.
:type uninit_code: int
:param method: Supported methods:
HEAD: /sys/health. Produces: 000 (empty body)
GET: /sys/health. Produces: 000 application/json
:type method: str | unicode
:return: The JSON response of the request.
:rtype: requests.Response
"""
params = {
'standby_ok': standby_ok,
'active_code': active_code,
'standby_code': standby_code,
'dr_secondary_code': dr_secondary_code,
'performance_standby_code': performance_standby_code,
'sealed_code': sealed_code,
'uninit_code': uninit_code,
}
if method == 'HEAD':
api_path = '/v1/sys/health'.format()
response = self._adapter.head(
url=api_path,
raise_exception=False,
)
return response
elif method == 'GET':
api_path = '/v1/sys/health'.format()
response = self._adapter.get(
url=api_path,
json=params,
raise_exception=False,
)
return response.json()
else:
error_message = '"method" parameter provided invalid value; HEAD or GET allowed, "{method}" provided'.format(method=method)
raise exceptions.ParamValidationError(error_message)
|
python
|
{
"resource": ""
}
|
q22647
|
Leader.read_leader_status
|
train
|
def read_leader_status(self):
"""Read the high availability status and current leader instance of Vault.
Supported methods:
GET: /sys/leader. Produces: 200 application/json
:return: The JSON response of the request.
:rtype: dict
"""
api_path = '/v1/sys/leader'
response = self._adapter.get(
url=api_path,
)
return response.json()
|
python
|
{
"resource": ""
}
|
q22648
|
Mfa.configure
|
train
|
def configure(self, mount_point, mfa_type='duo', force=False):
"""Configure MFA for a supported method.
This endpoint allows you to turn on multi-factor authentication with a given backend.
Currently only Duo is supported.
Supported methods:
POST: /auth/{mount_point}/mfa_config. Produces: 204 (empty body)
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:param mfa_type: Enables MFA with given backend (available: duo)
:type mfa_type: str | unicode
:param force: If True, make the "mfa_config" request regardless of circumstance. If False (the default), verify
the provided mount_point is available and one of the types of methods supported by this feature.
:type force: bool
:return: The response of the configure MFA request.
:rtype: requests.Response
"""
if mfa_type != 'duo' and not force:
# The situation described via this exception is not likely to change in the future.
# However we provided that flexibility here just in case.
error_msg = 'Unsupported mfa_type argument provided "{arg}", supported types: "{mfa_types}"'
raise exceptions.ParamValidationError(error_msg.format(
mfa_types=','.join(SUPPORTED_MFA_TYPES),
arg=mfa_type,
))
params = {
'type': mfa_type,
}
api_path = '/v1/auth/{mount_point}/mfa_config'.format(
mount_point=mount_point
)
return self._adapter.post(
url=api_path,
json=params,
)
|
python
|
{
"resource": ""
}
|
q22649
|
Mfa.configure_duo_access
|
train
|
def configure_duo_access(self, mount_point, host, integration_key, secret_key):
"""Configure the access keys and host for Duo API connections.
To authenticate users with Duo, the backend needs to know what host to connect to and must authenticate with an
integration key and secret key. This endpoint is used to configure that information.
Supported methods:
POST: /auth/{mount_point}/duo/access. Produces: 204 (empty body)
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:param host: Duo API host
:type host: str | unicode
:param integration_key: Duo integration key
:type integration_key: Duo secret key
:param secret_key: The "path" the method/backend was mounted on.
:type secret_key: str | unicode
:return: The response of the configure_duo_access request.
:rtype: requests.Response
"""
params = {
'host': host,
'ikey': integration_key,
'skey': secret_key,
}
api_path = '/v1/auth/{mount_point}/duo/access'.format(
mount_point=mount_point,
)
return self._adapter.post(
url=api_path,
json=params,
)
|
python
|
{
"resource": ""
}
|
q22650
|
Mfa.configure_duo_behavior
|
train
|
def configure_duo_behavior(self, mount_point, push_info=None, user_agent=None, username_format='%s'):
"""Configure Duo second factor behavior.
This endpoint allows you to configure how the original auth method username maps to the Duo username by
providing a template format string.
Supported methods:
POST: /auth/{mount_point}/duo/config. Produces: 204 (empty body)
:param mount_point: The "path" the method/backend was mounted on.
:type mount_point: str | unicode
:param push_info: A string of URL-encoded key/value pairs that provides additional context about the
authentication attempt in the Duo Mobile app
:type push_info: str | unicode
:param user_agent: User agent to connect to Duo (default "")
:type user_agent: str | unicode
:param username_format: Format string given auth method username as argument to create Duo username
(default '%s')
:type username_format: str | unicode
:return: The response of the configure_duo_behavior request.
:rtype: requests.Response
"""
params = {
'username_format': username_format,
}
if push_info is not None:
params['push_info'] = push_info
if user_agent is not None:
params['user_agent'] = user_agent
api_path = '/v1/auth/{mount_point}/duo/config'.format(
mount_point=mount_point,
)
return self._adapter.post(
url=api_path,
json=params,
)
|
python
|
{
"resource": ""
}
|
q22651
|
KikClient._on_connection_made
|
train
|
def _on_connection_made(self):
"""
Gets called when the TCP connection to kik's servers is done and we are connected.
Now we might initiate a login request or an auth request.
"""
if self.username is not None and self.password is not None and self.kik_node is not None:
# we have all required credentials, we can authenticate
log.info("[+] Establishing authenticated connection using kik node '{}'...".format(self.kik_node))
message = login.EstablishAuthenticatedSessionRequest(self.kik_node, self.username, self.password, self.device_id_override)
self.initial_connection_payload = message.serialize()
else:
self.initial_connection_payload = '<k anon="">'.encode()
self.connection.send_raw_data(self.initial_connection_payload)
|
python
|
{
"resource": ""
}
|
q22652
|
KikClient._establish_authenticated_session
|
train
|
def _establish_authenticated_session(self, kik_node):
"""
Updates the kik node and creates a new connection to kik servers.
This new connection will be initiated with another payload which proves
we have the credentials for a specific user. This is how authentication is done.
:param kik_node: The user's kik node (everything before '@' in JID).
"""
self.kik_node = kik_node
log.info("[+] Closing current connection and creating a new authenticated one.")
self.disconnect()
self._connect()
|
python
|
{
"resource": ""
}
|
q22653
|
KikClient.login
|
train
|
def login(self, username, password, captcha_result=None):
"""
Sends a login request with the given kik username and password
:param username: Your kik username
:param password: Your kik password
:param captcha_result: If this parameter is provided, it is the answer to the captcha given in the previous
login attempt.
"""
self.username = username
self.password = password
login_request = login.LoginRequest(username, password, captcha_result, self.device_id_override, self.android_id_override)
log.info("[+] Logging in with username '{}' and a given password..."
.format(username, '*' * len(password)))
return self._send_xmpp_element(login_request)
|
python
|
{
"resource": ""
}
|
q22654
|
KikClient.register
|
train
|
def register(self, email, username, password, first_name, last_name, birthday="1974-11-20", captcha_result=None):
"""
Sends a register request to sign up a new user to kik with the given details.
"""
self.username = username
self.password = password
register_message = sign_up.RegisterRequest(email, username, password, first_name, last_name, birthday, captcha_result,
self.device_id_override, self.android_id_override)
log.info("[+] Sending sign up request (name: {} {}, email: {})...".format(first_name, last_name, email))
return self._send_xmpp_element(register_message)
|
python
|
{
"resource": ""
}
|
q22655
|
KikClient.send_read_receipt
|
train
|
def send_read_receipt(self, peer_jid: str, receipt_message_id: str, group_jid=None):
"""
Sends a read receipt for a previously sent message, to a specific user or group.
:param peer_jid: The JID of the user to which to send the receipt.
:param receipt_message_id: The message ID that the receipt is sent for
:param group_jid If the receipt is sent for a message that was sent in a group,
this parameter should contain the group's JID
"""
log.info("[+] Sending read receipt to JID {} for message ID {}".format(peer_jid, receipt_message_id))
return self._send_xmpp_element(chatting.OutgoingReadReceipt(peer_jid, receipt_message_id, group_jid))
|
python
|
{
"resource": ""
}
|
q22656
|
KikClient.send_delivered_receipt
|
train
|
def send_delivered_receipt(self, peer_jid: str, receipt_message_id: str):
"""
Sends a receipt indicating that a specific message was received, to another person.
:param peer_jid: The other peer's JID to send to receipt to
:param receipt_message_id: The message ID for which to generate the receipt
"""
log.info("[+] Sending delivered receipt to JID {} for message ID {}".format(peer_jid, receipt_message_id))
return self._send_xmpp_element(chatting.OutgoingDeliveredReceipt(peer_jid, receipt_message_id))
|
python
|
{
"resource": ""
}
|
q22657
|
KikClient.send_is_typing
|
train
|
def send_is_typing(self, peer_jid: str, is_typing: bool):
"""
Updates the 'is typing' status of the bot during a conversation.
:param peer_jid: The JID that the notification will be sent to
:param is_typing: If true, indicates that we're currently typing, or False otherwise.
"""
if self.is_group_jid(peer_jid):
return self._send_xmpp_element(chatting.OutgoingGroupIsTypingEvent(peer_jid, is_typing))
else:
return self._send_xmpp_element(chatting.OutgoingIsTypingEvent(peer_jid, is_typing))
|
python
|
{
"resource": ""
}
|
q22658
|
KikClient.xiphias_get_users
|
train
|
def xiphias_get_users(self, peer_jids: Union[str, List[str]]):
"""
Calls the new format xiphias message to request user data such as profile creation date
and background picture URL.
:param peer_jids: one jid, or a list of jids
"""
return self._send_xmpp_element(xiphias.UsersRequest(peer_jids))
|
python
|
{
"resource": ""
}
|
q22659
|
KikClient.xiphias_get_users_by_alias
|
train
|
def xiphias_get_users_by_alias(self, alias_jids: Union[str, List[str]]):
"""
Like xiphias_get_users, but for aliases instead of jids.
:param alias_jids: one jid, or a list of jids
"""
return self._send_xmpp_element(xiphias.UsersByAliasRequest(alias_jids))
|
python
|
{
"resource": ""
}
|
q22660
|
KikClient.change_group_name
|
train
|
def change_group_name(self, group_jid: str, new_name: str):
"""
Changes the a group's name to something new
:param group_jid: The JID of the group whose name should be changed
:param new_name: The new name to give to the group
"""
log.info("[+] Requesting a group name change for JID {} to '{}'".format(group_jid, new_name))
return self._send_xmpp_element(group_adminship.ChangeGroupNameRequest(group_jid, new_name))
|
python
|
{
"resource": ""
}
|
q22661
|
KikClient.add_peer_to_group
|
train
|
def add_peer_to_group(self, group_jid, peer_jid):
"""
Adds someone to a group
:param group_jid: The JID of the group into which to add a user
:param peer_jid: The JID of the user to add
"""
log.info("[+] Requesting to add user {} into the group {}".format(peer_jid, group_jid))
return self._send_xmpp_element(group_adminship.AddToGroupRequest(group_jid, peer_jid))
|
python
|
{
"resource": ""
}
|
q22662
|
KikClient.remove_peer_from_group
|
train
|
def remove_peer_from_group(self, group_jid, peer_jid):
"""
Kicks someone out of a group
:param group_jid: The group JID from which to remove the user
:param peer_jid: The JID of the user to remove
"""
log.info("[+] Requesting removal of user {} from group {}".format(peer_jid, group_jid))
return self._send_xmpp_element(group_adminship.RemoveFromGroupRequest(group_jid, peer_jid))
|
python
|
{
"resource": ""
}
|
q22663
|
KikClient.ban_member_from_group
|
train
|
def ban_member_from_group(self, group_jid, peer_jid):
"""
Bans a member from the group
:param group_jid: The JID of the relevant group
:param peer_jid: The JID of the user to ban
"""
log.info("[+] Requesting ban of user {} from group {}".format(peer_jid, group_jid))
return self._send_xmpp_element(group_adminship.BanMemberRequest(group_jid, peer_jid))
|
python
|
{
"resource": ""
}
|
q22664
|
KikClient.unban_member_from_group
|
train
|
def unban_member_from_group(self, group_jid, peer_jid):
"""
Undos a ban of someone from a group
:param group_jid: The JID of the relevant group
:param peer_jid: The JID of the user to un-ban from the gorup
"""
log.info("[+] Requesting un-banning of user {} from the group {}".format(peer_jid, group_jid))
return self._send_xmpp_element(group_adminship.UnbanRequest(group_jid, peer_jid))
|
python
|
{
"resource": ""
}
|
q22665
|
KikClient.join_group_with_token
|
train
|
def join_group_with_token(self, group_hashtag, group_jid, join_token):
"""
Tries to join into a specific group, using a cryptographic token that was received earlier from a search
:param group_hashtag: The public hashtag of the group into which to join (like '#Music')
:param group_jid: The JID of the same group
:param join_token: a token that can be extracted in the callback on_group_search_response, after calling
search_group()
"""
log.info("[+] Trying to join the group '{}' with JID {}".format(group_hashtag, group_jid))
return self._send_xmpp_element(roster.GroupJoinRequest(group_hashtag, join_token, group_jid))
|
python
|
{
"resource": ""
}
|
q22666
|
KikClient.leave_group
|
train
|
def leave_group(self, group_jid):
"""
Leaves a specific group
:param group_jid: The JID of the group to leave
"""
log.info("[+] Leaving group {}".format(group_jid))
return self._send_xmpp_element(group_adminship.LeaveGroupRequest(group_jid))
|
python
|
{
"resource": ""
}
|
q22667
|
KikClient.promote_to_admin
|
train
|
def promote_to_admin(self, group_jid, peer_jid):
"""
Turns some group member into an admin
:param group_jid: The group JID for which the member will become an admin
:param peer_jid: The JID of user to turn into an admin
"""
log.info("[+] Promoting user {} to admin in group {}".format(peer_jid, group_jid))
return self._send_xmpp_element(group_adminship.PromoteToAdminRequest(group_jid, peer_jid))
|
python
|
{
"resource": ""
}
|
q22668
|
KikClient.demote_admin
|
train
|
def demote_admin(self, group_jid, peer_jid):
"""
Turns an admin of a group into a regular user with no amidships capabilities.
:param group_jid: The group JID in which the rights apply
:param peer_jid: The admin user to demote
:return:
"""
log.info("[+] Demoting user {} to a regular member in group {}".format(peer_jid, group_jid))
return self._send_xmpp_element(group_adminship.DemoteAdminRequest(group_jid, peer_jid))
|
python
|
{
"resource": ""
}
|
q22669
|
KikClient.add_members
|
train
|
def add_members(self, group_jid, peer_jids: Union[str, List[str]]):
"""
Adds multiple users to a specific group at once
:param group_jid: The group into which to join the users
:param peer_jids: a list (or a single string) of JIDs to add to the group
"""
log.info("[+] Adding some members to the group {}".format(group_jid))
return self._send_xmpp_element(group_adminship.AddMembersRequest(group_jid, peer_jids))
|
python
|
{
"resource": ""
}
|
q22670
|
KikClient.set_profile_picture
|
train
|
def set_profile_picture(self, filename):
"""
Sets the profile picture
:param filename: The filename on disk of the image to set
"""
log.info("[+] Setting the profile picture to file '{}'".format(filename))
profile_pictures.set_profile_picture(filename, self.kik_node + '@talk.kik.com', self.username, self.password)
|
python
|
{
"resource": ""
}
|
q22671
|
KikClient.change_display_name
|
train
|
def change_display_name(self, first_name, last_name):
"""
Changes the display name
:param first_name: The first name
:param last_name: The last name
"""
log.info("[+] Changing the display name to '{} {}'".format(first_name, last_name))
return self._send_xmpp_element(account.ChangeNameRequest(first_name, last_name))
|
python
|
{
"resource": ""
}
|
q22672
|
KikClient.change_password
|
train
|
def change_password(self, new_password, email):
"""
Changes the login password
:param new_password: The new login password to set for the account
:param email: The current email of the account
"""
log.info("[+] Changing the password of the account")
return self._send_xmpp_element(account.ChangePasswordRequest(self.password, new_password, email, self.username))
|
python
|
{
"resource": ""
}
|
q22673
|
KikClient.change_email
|
train
|
def change_email(self, old_email, new_email):
"""
Changes the email of the current account
:param old_email: The current email
:param new_email: The new email to set
"""
log.info("[+] Changing account email to '{}'".format(new_email))
return self._send_xmpp_element(account.ChangeEmailRequest(self.password, old_email, new_email))
|
python
|
{
"resource": ""
}
|
q22674
|
KikClient._send_xmpp_element
|
train
|
def _send_xmpp_element(self, xmpp_element: XMPPElement):
"""
Serializes and sends the given XMPP element to kik servers
:param xmpp_element: The XMPP element to send
:return: The UUID of the element that was sent
"""
while not self.connected:
log.debug("[!] Waiting for connection.")
time.sleep(0.1)
self.loop.call_soon_threadsafe(self.connection.send_raw_data, (xmpp_element.serialize()))
return xmpp_element.message_id
|
python
|
{
"resource": ""
}
|
q22675
|
KikClient._handle_received_k_element
|
train
|
def _handle_received_k_element(self, k_element: BeautifulSoup):
"""
The 'k' element appears to be kik's connection-related stanza.
It lets us know if a connection or a login was successful or not.
:param k_element: The XML element we just received from kik.
"""
if k_element['ok'] == "1":
self.connected = True
if 'ts' in k_element.attrs:
# authenticated!
log.info("[+] Authenticated successfully.")
self.authenticated = True
self.callback.on_authenticated()
elif self.should_login_on_connection:
self.login(self.username, self.password)
self.should_login_on_connection = False
else:
self.callback.on_connection_failed(login.ConnectionFailedResponse(k_element))
|
python
|
{
"resource": ""
}
|
q22676
|
KikClient._kik_connection_thread_function
|
train
|
def _kik_connection_thread_function(self):
"""
The Kik Connection thread main function.
Initiates the asyncio loop and actually connects.
"""
# If there is already a connection going, than wait for it to stop
if self.loop and self.loop.is_running():
self.loop.call_soon_threadsafe(self.connection.close)
log.debug("[!] Waiting for the previous connection to stop.")
while self.loop.is_running():
log.debug("[!] Still Waiting for the previous connection to stop.")
time.sleep(1)
log.info("[+] Initiating the Kik Connection thread and connecting to kik server...")
# create the connection and launch the asyncio loop
self.connection = KikConnection(self.loop, self)
coro = self.loop.create_connection(lambda: self.connection, HOST, PORT, ssl=True)
self.loop.run_until_complete(coro)
log.debug("[!] Running main loop")
self.loop.run_forever()
log.debug("[!] Main loop ended.")
|
python
|
{
"resource": ""
}
|
q22677
|
handle_cancellation
|
train
|
def handle_cancellation(session: CommandSession):
"""
If the input is a string of cancellation word, finish the command session.
"""
def control(value):
if _is_cancellation(value) is True:
session.finish(render_expression(
session.bot.config.SESSION_CANCEL_EXPRESSION))
return value
return control
|
python
|
{
"resource": ""
}
|
q22678
|
on_command
|
train
|
def on_command(name: Union[str, CommandName_T], *,
aliases: Iterable[str] = (),
permission: int = perm.EVERYBODY,
only_to_me: bool = True,
privileged: bool = False,
shell_like: bool = False) -> Callable:
"""
Decorator to register a function as a command.
:param name: command name (e.g. 'echo' or ('random', 'number'))
:param aliases: aliases of command name, for convenient access
:param permission: permission required by the command
:param only_to_me: only handle messages to me
:param privileged: can be run even when there is already a session
:param shell_like: use shell-like syntax to split arguments
"""
def deco(func: CommandHandler_T) -> CommandHandler_T:
if not isinstance(name, (str, tuple)):
raise TypeError('the name of a command must be a str or tuple')
if not name:
raise ValueError('the name of a command must not be empty')
cmd_name = (name,) if isinstance(name, str) else name
cmd = Command(name=cmd_name, func=func, permission=permission,
only_to_me=only_to_me, privileged=privileged)
if shell_like:
async def shell_like_args_parser(session):
session.args['argv'] = shlex.split(session.current_arg)
cmd.args_parser_func = shell_like_args_parser
current_parent = _registry
for parent_key in cmd_name[:-1]:
current_parent[parent_key] = current_parent.get(parent_key) or {}
current_parent = current_parent[parent_key]
current_parent[cmd_name[-1]] = cmd
for alias in aliases:
_aliases[alias] = cmd_name
return CommandFunc(cmd, func)
return deco
|
python
|
{
"resource": ""
}
|
q22679
|
handle_command
|
train
|
async def handle_command(bot: NoneBot, ctx: Context_T) -> bool:
"""
Handle a message as a command.
This function is typically called by "handle_message".
:param bot: NoneBot instance
:param ctx: message context
:return: the message is handled as a command
"""
cmd, current_arg = parse_command(bot, str(ctx['message']).lstrip())
is_privileged_cmd = cmd and cmd.privileged
if is_privileged_cmd and cmd.only_to_me and not ctx['to_me']:
is_privileged_cmd = False
disable_interaction = is_privileged_cmd
if is_privileged_cmd:
logger.debug(f'Command {cmd.name} is a privileged command')
ctx_id = context_id(ctx)
if not is_privileged_cmd:
# wait for 1.5 seconds (at most) if the current session is running
retry = 5
while retry > 0 and \
_sessions.get(ctx_id) and _sessions[ctx_id].running:
retry -= 1
await asyncio.sleep(0.3)
check_perm = True
session = _sessions.get(ctx_id) if not is_privileged_cmd else None
if session:
if session.running:
logger.warning(f'There is a session of command '
f'{session.cmd.name} running, notify the user')
asyncio.ensure_future(send(
bot, ctx,
render_expression(bot.config.SESSION_RUNNING_EXPRESSION)
))
# pretend we are successful, so that NLP won't handle it
return True
if session.is_valid:
logger.debug(f'Session of command {session.cmd.name} exists')
# since it's in a session, the user must be talking to me
ctx['to_me'] = True
session.refresh(ctx, current_arg=str(ctx['message']))
# there is no need to check permission for existing session
check_perm = False
else:
# the session is expired, remove it
logger.debug(f'Session of command {session.cmd.name} is expired')
if ctx_id in _sessions:
del _sessions[ctx_id]
session = None
if not session:
if not cmd:
logger.debug('Not a known command, ignored')
return False
if cmd.only_to_me and not ctx['to_me']:
logger.debug('Not to me, ignored')
return False
session = CommandSession(bot, ctx, cmd, current_arg=current_arg)
logger.debug(f'New session of command {session.cmd.name} created')
return await _real_run_command(session, ctx_id, check_perm=check_perm,
disable_interaction=disable_interaction)
|
python
|
{
"resource": ""
}
|
q22680
|
call_command
|
train
|
async def call_command(bot: NoneBot, ctx: Context_T,
name: Union[str, CommandName_T], *,
current_arg: str = '',
args: Optional[CommandArgs_T] = None,
check_perm: bool = True,
disable_interaction: bool = False) -> bool:
"""
Call a command internally.
This function is typically called by some other commands
or "handle_natural_language" when handling NLPResult object.
Note: If disable_interaction is not True, after calling this function,
any previous command session will be overridden, even if the command
being called here does not need further interaction (a.k.a asking
the user for more info).
:param bot: NoneBot instance
:param ctx: message context
:param name: command name
:param current_arg: command current argument string
:param args: command args
:param check_perm: should check permission before running command
:param disable_interaction: disable the command's further interaction
:return: the command is successfully called
"""
cmd = _find_command(name)
if not cmd:
return False
session = CommandSession(bot, ctx, cmd, current_arg=current_arg, args=args)
return await _real_run_command(session, context_id(session.ctx),
check_perm=check_perm,
disable_interaction=disable_interaction)
|
python
|
{
"resource": ""
}
|
q22681
|
kill_current_session
|
train
|
def kill_current_session(ctx: Context_T) -> None:
"""
Force kill current session of the given context,
despite whether it is running or not.
:param ctx: message context
"""
ctx_id = context_id(ctx)
if ctx_id in _sessions:
del _sessions[ctx_id]
|
python
|
{
"resource": ""
}
|
q22682
|
Command.run
|
train
|
async def run(self, session, *,
check_perm: bool = True,
dry: bool = False) -> bool:
"""
Run the command in a given session.
:param session: CommandSession object
:param check_perm: should check permission before running
:param dry: just check any prerequisite, without actually running
:return: the command is finished (or can be run, given dry == True)
"""
has_perm = await self._check_perm(session) if check_perm else True
if self.func and has_perm:
if dry:
return True
if session.current_arg_filters is not None and \
session.current_key is not None:
# argument-level filters are given, use them
arg = session.current_arg
config = session.bot.config
for f in session.current_arg_filters:
try:
res = f(arg)
if isinstance(res, Awaitable):
res = await res
arg = res
except ValidateError as e:
# validation failed
if config.MAX_VALIDATION_FAILURES > 0:
# should check number of validation failures
session.state['__validation_failure_num'] = \
session.state.get(
'__validation_failure_num', 0) + 1
if session.state['__validation_failure_num'] >= \
config.MAX_VALIDATION_FAILURES:
# noinspection PyProtectedMember
session.finish(render_expression(
config.TOO_MANY_VALIDATION_FAILURES_EXPRESSION
), **session._current_send_kwargs)
failure_message = e.message
if failure_message is None:
failure_message = render_expression(
config.DEFAULT_VALIDATION_FAILURE_EXPRESSION
)
# noinspection PyProtectedMember
session.pause(failure_message,
**session._current_send_kwargs)
# passed all filters
session.state[session.current_key] = arg
else:
# fallback to command-level args_parser_func
if self.args_parser_func:
await self.args_parser_func(session)
if session.current_key is not None and \
session.current_key not in session.state:
# args_parser_func didn't set state, here we set it
session.state[session.current_key] = session.current_arg
await self.func(session)
return True
return False
|
python
|
{
"resource": ""
}
|
q22683
|
Command._check_perm
|
train
|
async def _check_perm(self, session) -> bool:
"""
Check if the session has sufficient permission to
call the command.
:param session: CommandSession object
:return: the session has the permission
"""
return await perm.check_permission(session.bot, session.ctx,
self.permission)
|
python
|
{
"resource": ""
}
|
q22684
|
CommandFunc.args_parser
|
train
|
def args_parser(self, parser_func: CommandHandler_T) -> CommandHandler_T:
"""
Decorator to register a function as the arguments parser of
the corresponding command.
"""
self.cmd.args_parser_func = parser_func
return parser_func
|
python
|
{
"resource": ""
}
|
q22685
|
CommandSession.is_valid
|
train
|
def is_valid(self) -> bool:
"""Check if the session is expired or not."""
if self.bot.config.SESSION_EXPIRE_TIMEOUT and \
self._last_interaction and \
datetime.now() - self._last_interaction > \
self.bot.config.SESSION_EXPIRE_TIMEOUT:
return False
return True
|
python
|
{
"resource": ""
}
|
q22686
|
CommandSession.current_arg_text
|
train
|
def current_arg_text(self) -> str:
"""
Plain text part in the current argument, without any CQ codes.
"""
if self._current_arg_text is None:
self._current_arg_text = Message(
self.current_arg).extract_plain_text()
return self._current_arg_text
|
python
|
{
"resource": ""
}
|
q22687
|
CommandSession.refresh
|
train
|
def refresh(self, ctx: Context_T, *, current_arg: str = '') -> None:
"""
Refill the session with a new message context.
:param ctx: new message context
:param current_arg: new command argument as a string
"""
self.ctx = ctx
self.current_arg = current_arg
self._current_arg_text = None
self._current_arg_images = None
|
python
|
{
"resource": ""
}
|
q22688
|
CommandSession.get
|
train
|
def get(self, key: str, *,
prompt: Optional[Message_T] = None,
arg_filters: Optional[List[Filter_T]] = None,
**kwargs) -> Any:
"""
Get an argument with a given key.
If the argument does not exist in the current session,
a pause exception will be raised, and the caller of
the command will know it should keep the session for
further interaction with the user.
:param key: argument key
:param prompt: prompt to ask the user
:param arg_filters: argument filters for the next user input
:return: the argument value
"""
if key in self.state:
return self.state[key]
self.current_key = key
self.current_arg_filters = arg_filters
self._current_send_kwargs = kwargs
self.pause(prompt, **kwargs)
|
python
|
{
"resource": ""
}
|
q22689
|
CommandSession.get_optional
|
train
|
def get_optional(self, key: str,
default: Optional[Any] = None) -> Optional[Any]:
"""
Simply get a argument with given key.
Deprecated. Use `session.state.get()` instead.
"""
return self.state.get(key, default)
|
python
|
{
"resource": ""
}
|
q22690
|
CommandSession.pause
|
train
|
def pause(self, message: Optional[Message_T] = None, **kwargs) -> None:
"""Pause the session for further interaction."""
if message:
asyncio.ensure_future(self.send(message, **kwargs))
raise _PauseException
|
python
|
{
"resource": ""
}
|
q22691
|
CommandSession.finish
|
train
|
def finish(self, message: Optional[Message_T] = None, **kwargs) -> None:
"""Finish the session."""
if message:
asyncio.ensure_future(self.send(message, **kwargs))
raise _FinishException
|
python
|
{
"resource": ""
}
|
q22692
|
RequestSession.approve
|
train
|
async def approve(self, remark: str = '') -> None:
"""
Approve the request.
:param remark: remark of friend (only works in friend request)
"""
try:
await self.bot.call_action(
action='.handle_quick_operation_async',
self_id=self.ctx.get('self_id'),
context=self.ctx,
operation={'approve': True, 'remark': remark}
)
except CQHttpError:
pass
|
python
|
{
"resource": ""
}
|
q22693
|
RequestSession.reject
|
train
|
async def reject(self, reason: str = '') -> None:
"""
Reject the request.
:param reason: reason to reject (only works in group request)
"""
try:
await self.bot.call_action(
action='.handle_quick_operation_async',
self_id=self.ctx.get('self_id'),
context=self.ctx,
operation={'approve': False, 'reason': reason}
)
except CQHttpError:
pass
|
python
|
{
"resource": ""
}
|
q22694
|
init
|
train
|
def init(config_object: Optional[Any] = None) -> None:
"""
Initialize NoneBot instance.
This function must be called at the very beginning of code,
otherwise the get_bot() function will return None and nothing
is gonna work properly.
:param config_object: configuration object
"""
global _bot
_bot = NoneBot(config_object)
if _bot.config.DEBUG:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
_bot.server_app.before_serving(_start_scheduler)
|
python
|
{
"resource": ""
}
|
q22695
|
run
|
train
|
def run(host: Optional[str] = None, port: Optional[int] = None,
*args, **kwargs) -> None:
"""Run the NoneBot instance."""
get_bot().run(host=host, port=port, *args, **kwargs)
|
python
|
{
"resource": ""
}
|
q22696
|
context_id
|
train
|
def context_id(ctx: Context_T, *,
mode: str = 'default', use_hash: bool = False) -> str:
"""
Calculate a unique id representing the current context.
mode:
default: one id for one context
group: one id for one group or discuss
user: one id for one user
:param ctx: the context dict
:param mode: unique id mode: "default", "group", or "user"
:param use_hash: use md5 to hash the id or not
"""
ctx_id = ''
if mode == 'default':
if ctx.get('group_id'):
ctx_id = f'/group/{ctx["group_id"]}'
elif ctx.get('discuss_id'):
ctx_id = f'/discuss/{ctx["discuss_id"]}'
if ctx.get('user_id'):
ctx_id += f'/user/{ctx["user_id"]}'
elif mode == 'group':
if ctx.get('group_id'):
ctx_id = f'/group/{ctx["group_id"]}'
elif ctx.get('discuss_id'):
ctx_id = f'/discuss/{ctx["discuss_id"]}'
elif ctx.get('user_id'):
ctx_id = f'/user/{ctx["user_id"]}'
elif mode == 'user':
if ctx.get('user_id'):
ctx_id = f'/user/{ctx["user_id"]}'
if ctx_id and use_hash:
ctx_id = hashlib.md5(ctx_id.encode('ascii')).hexdigest()
return ctx_id
|
python
|
{
"resource": ""
}
|
q22697
|
render_expression
|
train
|
def render_expression(expr: Expression_T, *args,
escape_args: bool = True, **kwargs) -> str:
"""
Render an expression to message string.
:param expr: expression to render
:param escape_args: should escape arguments or not
:param args: positional arguments used in str.format()
:param kwargs: keyword arguments used in str.format()
:return: the rendered message
"""
if isinstance(expr, Callable):
expr = expr(*args, **kwargs)
elif isinstance(expr, Sequence) and not isinstance(expr, str):
expr = random.choice(expr)
if escape_args:
for k, v in kwargs.items():
if isinstance(v, str):
kwargs[k] = escape(v)
return expr.format(*args, **kwargs)
|
python
|
{
"resource": ""
}
|
q22698
|
load_plugin
|
train
|
def load_plugin(module_name: str) -> bool:
"""
Load a module as a plugin.
:param module_name: name of module to import
:return: successful or not
"""
try:
module = importlib.import_module(module_name)
name = getattr(module, '__plugin_name__', None)
usage = getattr(module, '__plugin_usage__', None)
_plugins.add(Plugin(module, name, usage))
logger.info(f'Succeeded to import "{module_name}"')
return True
except Exception as e:
logger.error(f'Failed to import "{module_name}", error: {e}')
logger.exception(e)
return False
|
python
|
{
"resource": ""
}
|
q22699
|
load_plugins
|
train
|
def load_plugins(plugin_dir: str, module_prefix: str) -> int:
"""
Find all non-hidden modules or packages in a given directory,
and import them with the given module prefix.
:param plugin_dir: plugin directory to search
:param module_prefix: module prefix used while importing
:return: number of plugins successfully loaded
"""
count = 0
for name in os.listdir(plugin_dir):
path = os.path.join(plugin_dir, name)
if os.path.isfile(path) and \
(name.startswith('_') or not name.endswith('.py')):
continue
if os.path.isdir(path) and \
(name.startswith('_') or not os.path.exists(
os.path.join(path, '__init__.py'))):
continue
m = re.match(r'([_A-Z0-9a-z]+)(.py)?', name)
if not m:
continue
if load_plugin(f'{module_prefix}.{m.group(1)}'):
count += 1
return count
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.