o |nhF@sdZddlZddlZddlZddlZddlmZddlZddlm Z  d$ddZ dddd d Z  d%d d Z d%d dZ d&ddZddZd'ddZddZddZddZddZddZd d!Zd"d#ZdS)(z& Misc utility functions and constants N)dedent) exceptionsc Cstjj|||||||d)a7Helper method to raise exceptions based on the status code of a response received back from Vault. :param method: HTTP method of a request to Vault. :type method: str :param url: URL of the endpoint requested in Vault. :type url: str :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 :param text: Optional text of the response. :type text: str :param json: Optional deserialized version of a JSON response (object) :type json: object :raises: hvac.exceptions.InvalidRequest | hvac.exceptions.Unauthorized | hvac.exceptions.Forbidden | hvac.exceptions.InvalidPath | hvac.exceptions.RateLimitExceeded | hvac.exceptions.InternalServerError | hvac.exceptions.VaultNotInitialized | hvac.exceptions.BadGateway | hvac.exceptions.VaultDown | hvac.exceptions.UnexpectedError )errorsmethodurltextjson)r VaultError from_status)rr status_codemessagerrrr 5/usr/local/lib/python3.10/dist-packages/hvac/utils.pyraise_for_errorsrT)positionraise_on_multiplecsfdd}|S)aYA decorator that can be used to define one or more aliases for a parameter, and optionally display a deprecation warning when aliases are used. It can also optionally raise an exception if a value is supplied via multiple names. LIMITATIONS: If the canonical parameter can be specified unnamed (positionally), then its position must be set to correctly detect multiple use and apply precedence. To set multiple aliases with different values for the optional parameters, use the decorator multiple times with the same name. This method will only work properly when the alias parameter is set as a keyword (named) arg, therefore the function in question should ensure that any aliases come after \*args or bare \* (marking keyword-only arguments: https://peps.python.org/pep-3102/). Note also that aliases do not have to appear in the original function's argument list. :param name: The canonical name of the parameter. :type name: str :param aliases: One or more alias names for the parameter. :type aliases: str :param removed_in_version: The version in which the alias will be removed. This should typically have a value. In the rare case that an alias is not deprecated, set this to None. :type removed_in_version: str | None :param position: The 0-based position of the canonical argument if it could be specified positionally. Use None for a keyword-only (named) argument. :type position: int :param raise_on_multiple: When True (default), raise an exception if a value is supplied via multiple names. :type raise_on_multiple: bool cs$tfdd}|S)Nc sd}z|Wnty'dur%z|Wn ty"Ynwd}Ynwd}D]6}||vrbdurEt|d}tj|tdd|sR|vsR|||<n r_tdd|d||=q,|i|S) NFT)to_be_removed_in_versionold_parameter_namenew_parameter_namer category stacklevelz Parameter 'z)' was given a duplicate value via alias ''.)KeyError IndexError&generate_parameter_deprecation_messagewarningswarnDeprecationWarning ValueError)argskwargs has_canonicalaliasdeprecation_message)aliasesrnamerrremoved_in_versionr rwrapperPsH      z5aliased_parameter..decorator..wrapper) functoolswraps)rr)r&r'rrr()rr decoratorOs,z$aliased_parameter..decoratorr )r'r(rrr&r-r r,raliased_parameter4s0r.cCsDd|d|d}|dur|d|d7}|dur |d|7}|S)aGenerate a message to be used when warning about the use of deprecated paramers. :param to_be_removed_in_version: Version of this module the deprecated parameter will be removed in. :type to_be_removed_in_version: str :param old_parameter_name: Deprecated parameter name. :type old_parameter_name: str :param new_parameter_name: Parameter intended to replace the deprecated parameter, if applicable. :type new_parameter_name: str | None :param extra_notes: Optional freeform text used to provide additional context, alternatives, or notes. :type extra_notes: str | None :return: Full deprecation warning message for the indicated parameter. :rtype: str z)Value supplied for deprecated parameter 'z.'. This parameter will be removed in version 'rNz Please use the 'z' parameter moving forward. r )rrr extra_notesr r r rrs rcCs4dj||d}|dur|dur|dj||d7}|S)aGenerate 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 zcCall to deprecated function '{old_method_name}'. This method will be removed in version '{version}')old_method_nameversionNzS Please use the '{method_name}' method on the '{module_name}' class moving forward.) method_name module_nameformat)rr1r3r4r r r r#generate_method_deprecation_messagesr7ClientcCs&dj||d}|dj|||d7}|S)aGenerate 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 zZCall to deprecated property '{name}'. This property will be removed in version '{version}')r'r2zf Please use the '{new_name}' property on the '{module_name}.{new_attribute}' attribute moving forward.)new_namer4 new_attributer5)rold_namer9r:r4r r r r%generate_property_deprecation_messagesr<cCs||vr6t||d|||d|||dd}tj|tddt|||d}t|||d|Stdj|jj |d) aHelper 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: Dict of deprecated properties. Each key is the name of the old property. Each value is a dict with at least a "to_be_removed_in_version" and "client_property" key to be used in the displayed deprecation warning. An optional "new_property" key contains the name of the new property within the "client_property", otherwise the original name is used. :type deprecated_properties: Dict :return: The new property indicated where available. :rtype: object r new_propertyclient_property)rr;r9r:rrz('{class_name}' has no attribute '{item}') class_nameitem) r<getrrrgetattrAttributeErrorr6 __class____name__)objr@deprecated_propertiesr%r>r r r"getattr_with_deprecated_propertiess0 rHcsfdd}|S)anThis is a decorator which can be used to mark methods as deprecated. It will result in a warning being emitted when the function is used. :param to_be_removed_in_version: Version of this module the decorated method will be removed in. :type to_be_removed_in_version: str :param new_method: Method intended to replace the decorated method. This method's docstrings are included in the decorated method's docstring. :type new_method: function :return: Wrapped function that includes a deprecation warning and update docstrings from the replacement method. :rtype: types.FunctionType csdurj}tj}nd\}}tj||dtfdd}r?jdur1jnd}djt|d|_|S|_|S)NNN)rr1r3r4cstjtdd|i|S)Nrr)rrr)r!r"r%rr rnew_funcs z6deprecated_method..decorator..new_funczN/Az {message} Docstring content from this method's replacement copied below: {docstring_copy} )r docstring_copy) rEinspect getmoduler7r*r+__doc__r6r)rnew_method_namenew_module_namerKrL new_methodrrJrr-s. z$deprecated_method..decoratorr )rrSr-r rRrdeprecated_methods +rTcCs^|durg}t|tr|d}t|trtdd|Ds-d}t|j||t|ddS)acValidate that an argument is a list of strings. Returns nothing if valid, raises ParamValidationException if invalid. :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 N,css|]}t|tVqdSN) isinstancestr.0pr r r Ls  z1validate_list_of_strings_param..zTunsupported {param} argument provided "{arg}" ({arg_type}), required type: List[str])paramargarg_type) rWrXsplitlistallrParamValidationErrorr6type param_nameparam_argument error_msgr r rvalidate_list_of_strings_param?s    ricCs|durg}d|S)zConvert a list of strings into a comma-delimited list / string. :param list_param: A list of strings. :type list_param: list :return: Comma-delimited string. :rtype: str NrU)join list_paramr r rlist_to_comma_delimitedYs rmcCsftd}|s-tjd}tj|r-t|}|}Wdn1s(wY|s1dS|S)zGet the token from env var, VAULT_TOKEN. If not set, attempt to get the token from, ~/.vault-token :return: The vault token if set, else None :rtype: str | None VAULT_TOKENz~/.vault-tokenN)osgetenvpath expanduserexistsopenreadstrip)tokentoken_file_pathf_inr r rget_token_from_envfs    rzcCs&t|tr|St|tr|dSgS)zConvert comma-delimited list / string into a list of strings :param list_param: Comma-delimited string :type list_param: str | unicode :return: A list of strings :rtype: list rU)rWrarXr`rkr r rcomma_delimited_to_listys   r{csRddt|tr |g}t|trtfdd|Ds'd}t|j|ddS)aValidate 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 cSs$|}|dr|dsdSdS)Nz-----BEGIN CERTIFICATE-----z-----END CERTIFICATE-----FT)rv startswithendswith)r^r r r _check_pems z'validate_pem_format.._check_pemc3s|]}|VqdSrVr rYr~r rr\s z&validate_pem_format..zGunsupported {param} public key / certificate format, required type: PEM)r]N)rWrXrarbrrcr6rer rrvalidate_pem_formats rcCsdd|DS)zRemoves None values from optional arguments in a parameter dictionary. :param params: The dictionary of parameters to be filtered. :type params: dict :return: A filtered copy of the parameter dictionary. :rtype: dict cSsi|] \}}|dur||qSrVr rZkeyvaluer r r sz remove_nones..)items)paramsr r r remove_noness rcs@ddfdd|D}fdd|D}|j|i|S)aCreates a URL using the specified format after escaping the provided arguments. :param format_str: The URL containing replacement fields. :type format_str: str :param kwargs: Positional replacement field values. :type kwargs: list :param kwargs: Named replacement field values. :type kwargs: dict :return: The formatted URL path with escaped replacement fields. :rtype: str cSst|}|d}tj|S)Nzutf-8)rXencodeurllibparsequote) maybe_str unicode_strutf8_strr r r url_quotes  zformat_url..url_quotecsg|]}|qSr r )rZrrr r szformat_url..csi|] \}}||qSr r rrr rrszformat_url..)rr6) format_strr!r" escaped_argsescaped_kwargsr rr format_urls r)NNNNrI)r8rV)rOr*rMrortextwraprrhvacrrr.rr7r<rHrTrirmrzr{rrrr r r rs8   & Q    *;