From e3e434a7cc0a1325eea153341c075cc9c9e32ceb Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Mon, 15 Jun 2020 16:32:04 -0700 Subject: [PATCH 1/5] package scaffold --- .../CHANGELOG.md | 3 + .../azure-keyvault-administration/MANIFEST.in | 5 ++ .../azure-keyvault-administration/README.md | 29 ++++++ .../azure/__init__.py | 5 ++ .../azure/keyvault/__init__.py | 5 ++ .../keyvault/administration/_sdk_moniker.py | 7 ++ .../azure/keyvault/administration/_version.py | 6 ++ .../keyvault/administration/aio/__init__.py | 4 + .../azure-keyvault-administration/conftest.py | 8 ++ .../dev_requirements.txt | 7 ++ .../sdk_packaging.toml | 2 + .../azure-keyvault-administration/setup.cfg | 2 + .../azure-keyvault-administration/setup.py | 88 +++++++++++++++++++ shared_requirements.txt | 2 + 14 files changed, 173 insertions(+) create mode 100644 sdk/keyvault/azure-keyvault-administration/CHANGELOG.md create mode 100644 sdk/keyvault/azure-keyvault-administration/MANIFEST.in create mode 100644 sdk/keyvault/azure-keyvault-administration/README.md create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/__init__.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/__init__.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_sdk_moniker.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_version.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/aio/__init__.py create mode 100644 sdk/keyvault/azure-keyvault-administration/conftest.py create mode 100644 sdk/keyvault/azure-keyvault-administration/dev_requirements.txt create mode 100644 sdk/keyvault/azure-keyvault-administration/sdk_packaging.toml create mode 100644 sdk/keyvault/azure-keyvault-administration/setup.cfg create mode 100644 sdk/keyvault/azure-keyvault-administration/setup.py diff --git a/sdk/keyvault/azure-keyvault-administration/CHANGELOG.md b/sdk/keyvault/azure-keyvault-administration/CHANGELOG.md new file mode 100644 index 000000000000..332564950c28 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/CHANGELOG.md @@ -0,0 +1,3 @@ +# Release History + +## 1.0.0b1 (Unreleased) diff --git a/sdk/keyvault/azure-keyvault-administration/MANIFEST.in b/sdk/keyvault/azure-keyvault-administration/MANIFEST.in new file mode 100644 index 000000000000..d1b90ace051f --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/MANIFEST.in @@ -0,0 +1,5 @@ +include *.md +include azure/__init__.py +include azure/keyvault/__init__.py +recursive-include samples *.py +recursive-include tests *.py \ No newline at end of file diff --git a/sdk/keyvault/azure-keyvault-administration/README.md b/sdk/keyvault/azure-keyvault-administration/README.md new file mode 100644 index 000000000000..f4333cb7ed36 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/README.md @@ -0,0 +1,29 @@ +# Azure Key Vault Administration client library for Python + +## Getting started + +## Key concepts + +## Examples + +## Troubleshooting + +## Next steps + +## Contributing +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit https://cla.microsoft.com. + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct][code_of_conduct]. For more information, +see the Code of Conduct FAQ or contact opencode@microsoft.com with any +additional questions or comments. + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python%2Fsdk%2Fkeyvault%2Fazure-keyvault-administration%2FFREADME.png) diff --git a/sdk/keyvault/azure-keyvault-administration/azure/__init__.py b/sdk/keyvault/azure-keyvault-administration/azure/__init__.py new file mode 100644 index 000000000000..679ab6995134 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/__init__.py @@ -0,0 +1,5 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/__init__.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/__init__.py new file mode 100644 index 000000000000..679ab6995134 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/__init__.py @@ -0,0 +1,5 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_sdk_moniker.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_sdk_moniker.py new file mode 100644 index 000000000000..0327b8f929e9 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_sdk_moniker.py @@ -0,0 +1,7 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from ._version import VERSION + +SDK_MONIKER = "keyvault-administration/{}".format(VERSION) diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_version.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_version.py new file mode 100644 index 000000000000..ac9f392f513e --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_version.py @@ -0,0 +1,6 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +VERSION = "1.0.0b1" diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/aio/__init__.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/aio/__init__.py new file mode 100644 index 000000000000..b74cfa3b899c --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/aio/__init__.py @@ -0,0 +1,4 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ diff --git a/sdk/keyvault/azure-keyvault-administration/conftest.py b/sdk/keyvault/azure-keyvault-administration/conftest.py new file mode 100644 index 000000000000..445dcb60c7d2 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/conftest.py @@ -0,0 +1,8 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import sys + +if sys.version_info < (3, 5, 3): + collect_ignore_glob = ["*_async.py"] diff --git a/sdk/keyvault/azure-keyvault-administration/dev_requirements.txt b/sdk/keyvault/azure-keyvault-administration/dev_requirements.txt new file mode 100644 index 000000000000..6641317a8516 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/dev_requirements.txt @@ -0,0 +1,7 @@ +-e ../../../tools/azure-devtools +-e ../../../tools/azure-sdk-tools +-e ../../core/azure-core +-e ../../identity/azure-identity +-e ../azure-mgmt-keyvault +../azure-keyvault-nspkg +aiohttp>=3.0; python_version >= '3.5' diff --git a/sdk/keyvault/azure-keyvault-administration/sdk_packaging.toml b/sdk/keyvault/azure-keyvault-administration/sdk_packaging.toml new file mode 100644 index 000000000000..e7687fdae93b --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/sdk_packaging.toml @@ -0,0 +1,2 @@ +[packaging] +auto_update = false \ No newline at end of file diff --git a/sdk/keyvault/azure-keyvault-administration/setup.cfg b/sdk/keyvault/azure-keyvault-administration/setup.cfg new file mode 100644 index 000000000000..3c6e79cf31da --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/setup.cfg @@ -0,0 +1,2 @@ +[bdist_wheel] +universal=1 diff --git a/sdk/keyvault/azure-keyvault-administration/setup.py b/sdk/keyvault/azure-keyvault-administration/setup.py new file mode 100644 index 000000000000..6c58718383f5 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/setup.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python + +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +# pylint:disable=missing-docstring + +import re +import os.path +from io import open +from setuptools import find_packages, setup + +# Change the PACKAGE_NAME only to change folder and different name +PACKAGE_NAME = "azure-keyvault-administration" +PACKAGE_PPRINT_NAME = "Key Vault Administration" + +# a-b-c => a/b/c +PACKAGE_FOLDER_PATH = PACKAGE_NAME.replace("-", "/") +# a-b-c => a.b.c +NAMESPACE_NAME = PACKAGE_NAME.replace("-", ".") + +# azure v0.x is not compatible with this package +# azure v0.x used to have a __version__ attribute (newer versions don't) +try: + import azure + + try: + VER = azure.__version__ # type: ignore + raise Exception( + "This package is incompatible with azure=={}. ".format(VER) + 'Uninstall it with "pip uninstall azure".' + ) + except AttributeError: + pass +except ImportError: + pass + +# Version extraction inspired from 'requests' +with open(os.path.join(PACKAGE_FOLDER_PATH, "_version.py"), "r") as fd: + VERSION = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) + +if not VERSION: + raise RuntimeError("Cannot find version information") + +with open("README.md", encoding="utf-8") as f: + README = f.read() +with open("CHANGELOG.md", encoding="utf-8") as f: + CHANGELOG = f.read() + +setup( + name=PACKAGE_NAME, + version=VERSION, + description="Microsoft Azure {} Client Library for Python".format(PACKAGE_PPRINT_NAME), + long_description=README + "\n\n" + CHANGELOG, + long_description_content_type="text/markdown", + license="MIT License", + author="Microsoft Corporation", + author_email="azurekeyvault@microsoft.com", + url="https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-administration", + classifiers=[ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 2", + "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.5", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "License :: OSI Approved :: MIT License", + ], + zip_safe=False, + packages=find_packages( + exclude=[ + "samples", + "tests", + # Exclude packages that will be covered by PEP420 or nspkg + "azure", + "azure.keyvault", + ] + ), + install_requires=["azure-core<2.0.0,>=1.7.0", "msrest>=0.6.0"], + extras_require={ + ":python_version<'3.0'": ["azure-keyvault-nspkg"], + ":python_version<'3.4'": ["enum34>=1.0.4"], + ":python_version<'3.5'": ["typing"], + }, +) diff --git a/shared_requirements.txt b/shared_requirements.txt index 4cd58d2e5a4f..12a7c2eb6943 100644 --- a/shared_requirements.txt +++ b/shared_requirements.txt @@ -119,12 +119,14 @@ isodate>=0.6.0 #override azure-cosmos azure-core<2.0.0,>=1.0.0 #override azure-eventhub azure-core<2.0.0,>=1.5.0 #override azure-identity azure-core<2.0.0,>=1.0.0 +#override azure-keyvault-administration msrest>=0.6.0 #override azure-keyvault-certificates msrest>=0.6.0 #override azure-keyvault-keys msrest>=0.6.0 #override azure-keyvault-secrets msrest>=0.6.0 #override azure-keyvault-certificates azure-core<2.0.0,>=1.7.0 #override azure-keyvault-keys azure-core<2.0.0,>=1.7.0 #override azure-keyvault-secrets azure-core<2.0.0,>=1.7.0 +#override azure-keyvault-administration azure-core<2.0.0,>=1.7.0 #override azure-ai-textanalytics msrest>=0.6.0 #override azure-ai-textanalytics azure-core<2.0.0,>=1.4.0 #override azure-search-documents azure-core<2.0.0,>=1.4.0 From 6bb9954540373f9e328f69543fcb27985e787d70 Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Mon, 15 Jun 2020 16:16:55 -0700 Subject: [PATCH 2/5] generated code --- .../azure/keyvault/administration/__init__.py | 5 + .../administration/_generated/__init__.py | 16 + .../_generated/_configuration.py | 49 ++ .../_generated/_key_vault_client.py | 116 +++ .../_generated/_operations_mixin.py | 195 +++++ .../administration/_generated/_version.py | 8 + .../administration/_generated/aio/__init__.py | 10 + .../_generated/aio/_configuration_async.py | 47 ++ .../_generated/aio/_key_vault_client_async.py | 116 +++ .../_generated/aio/_operations_mixin_async.py | 191 +++++ .../administration/_generated/models.py | 7 + .../administration/_generated/py.typed | 1 + .../_generated/v7_2_preview/__init__.py | 16 + .../_generated/v7_2_preview/_configuration.py | 52 ++ .../v7_2_preview/_key_vault_client.py | 64 ++ .../_generated/v7_2_preview/_metadata.json | 131 ++++ .../_generated/v7_2_preview/aio/__init__.py | 10 + .../v7_2_preview/aio/_configuration_async.py | 46 ++ .../aio/_key_vault_client_async.py | 56 ++ .../aio/operations_async/__init__.py | 17 + .../_key_vault_client_operations_async.py | 504 +++++++++++++ .../_role_assignments_operations_async.py | 311 ++++++++ .../_role_definitions_operations_async.py | 123 ++++ .../v7_2_preview/models/__init__.py | 70 ++ .../_generated/v7_2_preview/models/_models.py | 618 ++++++++++++++++ .../v7_2_preview/models/_models_py3.py | 688 ++++++++++++++++++ .../v7_2_preview/operations/__init__.py | 17 + .../_key_vault_client_operations.py | 516 +++++++++++++ .../_role_assignments_operations.py | 319 ++++++++ .../_role_definitions_operations.py | 128 ++++ .../_generated/v7_2_preview/py.typed | 1 + 31 files changed, 4448 insertions(+) create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/__init__.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/__init__.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/_configuration.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/_key_vault_client.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/_operations_mixin.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/_version.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/aio/__init__.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/aio/_configuration_async.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/aio/_key_vault_client_async.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/aio/_operations_mixin_async.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/models.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/py.typed create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/__init__.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/_configuration.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/_key_vault_client.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/_metadata.json create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/__init__.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/_configuration_async.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/_key_vault_client_async.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/operations_async/__init__.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/operations_async/_key_vault_client_operations_async.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/operations_async/_role_assignments_operations_async.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/operations_async/_role_definitions_operations_async.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/models/__init__.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/models/_models.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/models/_models_py3.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/operations/__init__.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/operations/_key_vault_client_operations.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/operations/_role_assignments_operations.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/operations/_role_definitions_operations.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/py.typed diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/__init__.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/__init__.py new file mode 100644 index 000000000000..679ab6995134 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/__init__.py @@ -0,0 +1,5 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/__init__.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/__init__.py new file mode 100644 index 000000000000..a6c1f9b7a792 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/__init__.py @@ -0,0 +1,16 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._key_vault_client import KeyVaultClient +__all__ = ['KeyVaultClient'] + +try: + from ._patch import patch_sdk # type: ignore + patch_sdk() +except ImportError: + pass diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/_configuration.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/_configuration.py new file mode 100644 index 000000000000..fea6e56a754e --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/_configuration.py @@ -0,0 +1,49 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- +from typing import Any + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies + +from ._version import VERSION + + +class KeyVaultClientConfiguration(Configuration): + """Configuration for KeyVaultClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + """ + + def __init__( + self, + **kwargs # type: Any + ): + # type: (...) -> None + super(KeyVaultClientConfiguration, self).__init__(**kwargs) + + kwargs.setdefault('sdk_moniker', 'azure-keyvault/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs # type: Any + ): + # type: (...) -> None + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or policies.HttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/_key_vault_client.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/_key_vault_client.py new file mode 100644 index 000000000000..f7e0861520ea --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/_key_vault_client.py @@ -0,0 +1,116 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from azure.core import PipelineClient +from msrest import Serializer, Deserializer + +from azure.profiles import KnownProfiles, ProfileDefinition +from azure.profiles.multiapiclient import MultiApiClientMixin +from ._configuration import KeyVaultClientConfiguration +from ._operations_mixin import KeyVaultClientOperationsMixin +class _SDKClient(object): + def __init__(self, *args, **kwargs): + """This is a fake class to support current implemetation of MultiApiClientMixin." + Will be removed in final version of multiapi azure-core based client + """ + pass + +class KeyVaultClient(KeyVaultClientOperationsMixin, MultiApiClientMixin, _SDKClient): + """The key vault client performs cryptographic key operations and vault operations against the Key Vault service. + + This ready contains multiple API versions, to help you deal with all of the Azure clouds + (Azure Stack, Azure Government, Azure China, etc.). + By default, it uses the latest API version available on public Azure. + For production, you should stick to a particular api-version and/or profile. + The profile sets a mapping between an operation group and its API version. + The api-version parameter sets the default API version if the operation + group is not described in the profile. + :param str api_version: API version to use if no profile is provided, or if + missing in profile. + :param profile: A profile definition, from KnownProfiles to dict. + :type profile: azure.profiles.KnownProfiles + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + """ + + DEFAULT_API_VERSION = '7.2-preview' + _PROFILE_TAG = "azure.keyvault.KeyVaultClient" + LATEST_PROFILE = ProfileDefinition({ + _PROFILE_TAG: { + None: DEFAULT_API_VERSION, + }}, + _PROFILE_TAG + " latest" + ) + + def __init__( + self, + api_version=None, + profile=KnownProfiles.default, + **kwargs # type: Any + ): + if api_version == '7.2-preview': + base_url = '{vaultBaseUrl}' + else: + raise NotImplementedError("APIVersion {} is not available".format(api_version)) + self._config = KeyVaultClientConfiguration(**kwargs) + self._client = PipelineClient(base_url=base_url, config=self._config, **kwargs) + super(KeyVaultClient, self).__init__( + api_version=api_version, + profile=profile + ) + + @classmethod + def _models_dict(cls, api_version): + return {k: v for k, v in cls.models(api_version).__dict__.items() if isinstance(v, type)} + + @classmethod + def models(cls, api_version=DEFAULT_API_VERSION): + """Module depends on the API version: + + * 7.2-preview: :mod:`v7_2_preview.models` + """ + if api_version == '7.2-preview': + from .v7_2_preview import models + return models + raise NotImplementedError("APIVersion {} is not available".format(api_version)) + + @property + def role_assignments(self): + """Instance depends on the API version: + + * 7.2-preview: :class:`RoleAssignmentsOperations` + """ + api_version = self._get_api_version('role_assignments') + if api_version == '7.2-preview': + from .v7_2_preview.operations import RoleAssignmentsOperations as OperationClass + else: + raise NotImplementedError("APIVersion {} is not available".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def role_definitions(self): + """Instance depends on the API version: + + * 7.2-preview: :class:`RoleDefinitionsOperations` + """ + api_version = self._get_api_version('role_definitions') + if api_version == '7.2-preview': + from .v7_2_preview.operations import RoleDefinitionsOperations as OperationClass + else: + raise NotImplementedError("APIVersion {} is not available".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + def close(self): + self._client.close() + def __enter__(self): + self._client.__enter__() + return self + def __exit__(self, *exc_details): + self._client.__exit__(*exc_details) diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/_operations_mixin.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/_operations_mixin.py new file mode 100644 index 000000000000..f49ed4894e09 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/_operations_mixin.py @@ -0,0 +1,195 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- +from msrest import Serializer, Deserializer +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.polling.base_polling import LROBasePolling + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union + + +class KeyVaultClientOperationsMixin(object): + + def begin_full_backup( + self, + vault_base_url, # type: str + azure_storage_blob_container_uri=None, # type: Optional["models.SASTokenParameter"] + **kwargs # type: Any + ): + """Creates a full backup using a user-provided SAS token to an Azure blob storage container. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param azure_storage_blob_container_uri: Azure blob shared access signature token pointing to a + valid Azure blob container where full backup needs to be stored. This token needs to be valid + for at least next 24 hours from the time of making this call. + :type azure_storage_blob_container_uri: ~azure.keyvault.v7_2.models.SASTokenParameter + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: True for ARMPolling, False for no polling, or a + polling object for personal polling strategy + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either FullBackupOperation or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.keyvault.v7_2.models.FullBackupOperation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + api_version = self._get_api_version('begin_full_backup') + if api_version == '7.2-preview': + from .v7_2_preview.operations import KeyVaultClientOperationsMixin as OperationClass + else: + raise NotImplementedError("APIVersion {} is not available".format(api_version)) + mixin_instance = OperationClass() + mixin_instance._client = self._client + mixin_instance._config = self._config + mixin_instance._serialize = Serializer(self._models_dict(api_version)) + mixin_instance._deserialize = Deserializer(self._models_dict(api_version)) + return mixin_instance.begin_full_backup(vault_base_url, azure_storage_blob_container_uri, **kwargs) + + def begin_full_restore_operation( + self, + vault_base_url, # type: str + restore_blob_details=None, # type: Optional["models.RestoreOperationParameters"] + **kwargs # type: Any + ): + """Restores all key materials using the SAS token pointing to a previously stored Azure Blob + storage backup folder. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param restore_blob_details: The Azure blob SAS token pointing to a folder where the previous + successful full backup was stored. + :type restore_blob_details: ~azure.keyvault.v7_2.models.RestoreOperationParameters + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: True for ARMPolling, False for no polling, or a + polling object for personal polling strategy + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either RestoreOperation or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.keyvault.v7_2.models.RestoreOperation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + api_version = self._get_api_version('begin_full_restore_operation') + if api_version == '7.2-preview': + from .v7_2_preview.operations import KeyVaultClientOperationsMixin as OperationClass + else: + raise NotImplementedError("APIVersion {} is not available".format(api_version)) + mixin_instance = OperationClass() + mixin_instance._client = self._client + mixin_instance._config = self._config + mixin_instance._serialize = Serializer(self._models_dict(api_version)) + mixin_instance._deserialize = Deserializer(self._models_dict(api_version)) + return mixin_instance.begin_full_restore_operation(vault_base_url, restore_blob_details, **kwargs) + + def begin_selective_key_restore_operation( + self, + vault_base_url, # type: str + key_name, # type: str + restore_blob_details=None, # type: Optional["models.SelectiveKeyRestoreOperationParameters"] + **kwargs # type: Any + ): + """Restores all key versions of a given key using user supplied SAS token pointing to a previously + stored Azure Blob storage backup folder. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param key_name: The name of the key to be restored from the user supplied backup. + :type key_name: str + :param restore_blob_details: The Azure blob SAS token pointing to a folder where the previous + successful full backup was stored. + :type restore_blob_details: ~azure.keyvault.v7_2.models.SelectiveKeyRestoreOperationParameters + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: True for ARMPolling, False for no polling, or a + polling object for personal polling strategy + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either SelectiveKeyRestoreOperation or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.keyvault.v7_2.models.SelectiveKeyRestoreOperation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + api_version = self._get_api_version('begin_selective_key_restore_operation') + if api_version == '7.2-preview': + from .v7_2_preview.operations import KeyVaultClientOperationsMixin as OperationClass + else: + raise NotImplementedError("APIVersion {} is not available".format(api_version)) + mixin_instance = OperationClass() + mixin_instance._client = self._client + mixin_instance._config = self._config + mixin_instance._serialize = Serializer(self._models_dict(api_version)) + mixin_instance._deserialize = Deserializer(self._models_dict(api_version)) + return mixin_instance.begin_selective_key_restore_operation(vault_base_url, key_name, restore_blob_details, **kwargs) + + def full_backup_status( + self, + vault_base_url, # type: str + job_id, # type: str + **kwargs # type: Any + ): + """Returns the status of full backup operation. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param job_id: The id returned as part of the backup request. + :type job_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FullBackupOperation, or the result of cls(response) + :rtype: ~azure.keyvault.v7_2.models.FullBackupOperation + :raises: ~azure.core.exceptions.HttpResponseError + """ + api_version = self._get_api_version('full_backup_status') + if api_version == '7.2-preview': + from .v7_2_preview.operations import KeyVaultClientOperationsMixin as OperationClass + else: + raise NotImplementedError("APIVersion {} is not available".format(api_version)) + mixin_instance = OperationClass() + mixin_instance._client = self._client + mixin_instance._config = self._config + mixin_instance._serialize = Serializer(self._models_dict(api_version)) + mixin_instance._deserialize = Deserializer(self._models_dict(api_version)) + return mixin_instance.full_backup_status(vault_base_url, job_id, **kwargs) + + def restore_status( + self, + vault_base_url, # type: str + job_id, # type: str + **kwargs # type: Any + ): + """Returns the status of restore operation. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param job_id: The Job Id returned part of the restore operation. + :type job_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RestoreOperation, or the result of cls(response) + :rtype: ~azure.keyvault.v7_2.models.RestoreOperation + :raises: ~azure.core.exceptions.HttpResponseError + """ + api_version = self._get_api_version('restore_status') + if api_version == '7.2-preview': + from .v7_2_preview.operations import KeyVaultClientOperationsMixin as OperationClass + else: + raise NotImplementedError("APIVersion {} is not available".format(api_version)) + mixin_instance = OperationClass() + mixin_instance._client = self._client + mixin_instance._config = self._config + mixin_instance._serialize = Serializer(self._models_dict(api_version)) + mixin_instance._deserialize = Deserializer(self._models_dict(api_version)) + return mixin_instance.restore_status(vault_base_url, job_id, **kwargs) diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/_version.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/_version.py new file mode 100644 index 000000000000..a30a458f8b5b --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/_version.py @@ -0,0 +1,8 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +VERSION = "0.1.0" \ No newline at end of file diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/aio/__init__.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/aio/__init__.py new file mode 100644 index 000000000000..71ceadebe430 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/aio/__init__.py @@ -0,0 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._key_vault_client_async import KeyVaultClient +__all__ = ['KeyVaultClient'] diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/aio/_configuration_async.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/aio/_configuration_async.py new file mode 100644 index 000000000000..6725478d133d --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/aio/_configuration_async.py @@ -0,0 +1,47 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- +from typing import Any + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies + +from .._version import VERSION + + +class KeyVaultClientConfiguration(Configuration): + """Configuration for KeyVaultClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + """ + + def __init__( + self, + **kwargs # type: Any + ) -> None: + super(KeyVaultClientConfiguration, self).__init__(**kwargs) + + kwargs.setdefault('sdk_moniker', 'azure-keyvault/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs: Any + ) -> None: + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or policies.HttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/aio/_key_vault_client_async.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/aio/_key_vault_client_async.py new file mode 100644 index 000000000000..24bb6d619c51 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/aio/_key_vault_client_async.py @@ -0,0 +1,116 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from azure.core import AsyncPipelineClient +from msrest import Serializer, Deserializer + +from azure.profiles import KnownProfiles, ProfileDefinition +from azure.profiles.multiapiclient import MultiApiClientMixin +from ._configuration_async import KeyVaultClientConfiguration +from ._operations_mixin_async import KeyVaultClientOperationsMixin +class _SDKClient(object): + def __init__(self, *args, **kwargs): + """This is a fake class to support current implemetation of MultiApiClientMixin." + Will be removed in final version of multiapi azure-core based client + """ + pass + +class KeyVaultClient(KeyVaultClientOperationsMixin, MultiApiClientMixin, _SDKClient): + """The key vault client performs cryptographic key operations and vault operations against the Key Vault service. + + This ready contains multiple API versions, to help you deal with all of the Azure clouds + (Azure Stack, Azure Government, Azure China, etc.). + By default, it uses the latest API version available on public Azure. + For production, you should stick to a particular api-version and/or profile. + The profile sets a mapping between an operation group and its API version. + The api-version parameter sets the default API version if the operation + group is not described in the profile. + :param str api_version: API version to use if no profile is provided, or if + missing in profile. + :param profile: A profile definition, from KnownProfiles to dict. + :type profile: azure.profiles.KnownProfiles + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + """ + + DEFAULT_API_VERSION = '7.2-preview' + _PROFILE_TAG = "azure.keyvault.KeyVaultClient" + LATEST_PROFILE = ProfileDefinition({ + _PROFILE_TAG: { + None: DEFAULT_API_VERSION, + }}, + _PROFILE_TAG + " latest" + ) + + def __init__( + self, + api_version=None, + profile=KnownProfiles.default, + **kwargs # type: Any + ) -> None: + if api_version == '7.2-preview': + base_url = '{vaultBaseUrl}' + else: + raise NotImplementedError("APIVersion {} is not available".format(api_version)) + self._config = KeyVaultClientConfiguration(**kwargs) + self._client = AsyncPipelineClient(base_url=base_url, config=self._config, **kwargs) + super(KeyVaultClient, self).__init__( + api_version=api_version, + profile=profile + ) + + @classmethod + def _models_dict(cls, api_version): + return {k: v for k, v in cls.models(api_version).__dict__.items() if isinstance(v, type)} + + @classmethod + def models(cls, api_version=DEFAULT_API_VERSION): + """Module depends on the API version: + + * 7.2-preview: :mod:`v7_2_preview.models` + """ + if api_version == '7.2-preview': + from ..v7_2_preview import models + return models + raise NotImplementedError("APIVersion {} is not available".format(api_version)) + + @property + def role_assignments(self): + """Instance depends on the API version: + + * 7.2-preview: :class:`RoleAssignmentsOperations` + """ + api_version = self._get_api_version('role_assignments') + if api_version == '7.2-preview': + from ..v7_2_preview.aio.operations_async import RoleAssignmentsOperations as OperationClass + else: + raise NotImplementedError("APIVersion {} is not available".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + @property + def role_definitions(self): + """Instance depends on the API version: + + * 7.2-preview: :class:`RoleDefinitionsOperations` + """ + api_version = self._get_api_version('role_definitions') + if api_version == '7.2-preview': + from ..v7_2_preview.aio.operations_async import RoleDefinitionsOperations as OperationClass + else: + raise NotImplementedError("APIVersion {} is not available".format(api_version)) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + + async def close(self): + await self._client.close() + async def __aenter__(self): + await self._client.__aenter__() + return self + async def __aexit__(self, *exc_details): + await self._client.__aexit__(*exc_details) diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/aio/_operations_mixin_async.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/aio/_operations_mixin_async.py new file mode 100644 index 000000000000..19f1dfa324e2 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/aio/_operations_mixin_async.py @@ -0,0 +1,191 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- +from msrest import Serializer, Deserializer +from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.polling.async_base_polling import AsyncLROBasePolling + + +class KeyVaultClientOperationsMixin(object): + + async def begin_full_backup( + self, + vault_base_url: str, + azure_storage_blob_container_uri: Optional["models.SASTokenParameter"] = None, + **kwargs + ) -> AsyncLROPoller["models.FullBackupOperation"]: + """Creates a full backup using a user-provided SAS token to an Azure blob storage container. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param azure_storage_blob_container_uri: Azure blob shared access signature token pointing to a + valid Azure blob container where full backup needs to be stored. This token needs to be valid + for at least next 24 hours from the time of making this call. + :type azure_storage_blob_container_uri: ~azure.keyvault.v7_2.models.SASTokenParameter + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: True for ARMPolling, False for no polling, or a + polling object for personal polling strategy + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either FullBackupOperation or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.keyvault.v7_2.models.FullBackupOperation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + api_version = self._get_api_version('begin_full_backup') + if api_version == '7.2-preview': + from ..v7_2_preview.aio.operations_async import KeyVaultClientOperationsMixin as OperationClass + else: + raise NotImplementedError("APIVersion {} is not available".format(api_version)) + mixin_instance = OperationClass() + mixin_instance._client = self._client + mixin_instance._config = self._config + mixin_instance._serialize = Serializer(self._models_dict(api_version)) + mixin_instance._deserialize = Deserializer(self._models_dict(api_version)) + return await mixin_instance.begin_full_backup(vault_base_url, azure_storage_blob_container_uri, **kwargs) + + async def begin_full_restore_operation( + self, + vault_base_url: str, + restore_blob_details: Optional["models.RestoreOperationParameters"] = None, + **kwargs + ) -> AsyncLROPoller["models.RestoreOperation"]: + """Restores all key materials using the SAS token pointing to a previously stored Azure Blob + storage backup folder. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param restore_blob_details: The Azure blob SAS token pointing to a folder where the previous + successful full backup was stored. + :type restore_blob_details: ~azure.keyvault.v7_2.models.RestoreOperationParameters + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: True for ARMPolling, False for no polling, or a + polling object for personal polling strategy + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either RestoreOperation or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.keyvault.v7_2.models.RestoreOperation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + api_version = self._get_api_version('begin_full_restore_operation') + if api_version == '7.2-preview': + from ..v7_2_preview.aio.operations_async import KeyVaultClientOperationsMixin as OperationClass + else: + raise NotImplementedError("APIVersion {} is not available".format(api_version)) + mixin_instance = OperationClass() + mixin_instance._client = self._client + mixin_instance._config = self._config + mixin_instance._serialize = Serializer(self._models_dict(api_version)) + mixin_instance._deserialize = Deserializer(self._models_dict(api_version)) + return await mixin_instance.begin_full_restore_operation(vault_base_url, restore_blob_details, **kwargs) + + async def begin_selective_key_restore_operation( + self, + vault_base_url: str, + key_name: str, + restore_blob_details: Optional["models.SelectiveKeyRestoreOperationParameters"] = None, + **kwargs + ) -> AsyncLROPoller["models.SelectiveKeyRestoreOperation"]: + """Restores all key versions of a given key using user supplied SAS token pointing to a previously + stored Azure Blob storage backup folder. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param key_name: The name of the key to be restored from the user supplied backup. + :type key_name: str + :param restore_blob_details: The Azure blob SAS token pointing to a folder where the previous + successful full backup was stored. + :type restore_blob_details: ~azure.keyvault.v7_2.models.SelectiveKeyRestoreOperationParameters + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: True for ARMPolling, False for no polling, or a + polling object for personal polling strategy + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either SelectiveKeyRestoreOperation or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.keyvault.v7_2.models.SelectiveKeyRestoreOperation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + api_version = self._get_api_version('begin_selective_key_restore_operation') + if api_version == '7.2-preview': + from ..v7_2_preview.aio.operations_async import KeyVaultClientOperationsMixin as OperationClass + else: + raise NotImplementedError("APIVersion {} is not available".format(api_version)) + mixin_instance = OperationClass() + mixin_instance._client = self._client + mixin_instance._config = self._config + mixin_instance._serialize = Serializer(self._models_dict(api_version)) + mixin_instance._deserialize = Deserializer(self._models_dict(api_version)) + return await mixin_instance.begin_selective_key_restore_operation(vault_base_url, key_name, restore_blob_details, **kwargs) + + async def full_backup_status( + self, + vault_base_url: str, + job_id: str, + **kwargs + ) -> "models.FullBackupOperation": + """Returns the status of full backup operation. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param job_id: The id returned as part of the backup request. + :type job_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FullBackupOperation, or the result of cls(response) + :rtype: ~azure.keyvault.v7_2.models.FullBackupOperation + :raises: ~azure.core.exceptions.HttpResponseError + """ + api_version = self._get_api_version('full_backup_status') + if api_version == '7.2-preview': + from ..v7_2_preview.aio.operations_async import KeyVaultClientOperationsMixin as OperationClass + else: + raise NotImplementedError("APIVersion {} is not available".format(api_version)) + mixin_instance = OperationClass() + mixin_instance._client = self._client + mixin_instance._config = self._config + mixin_instance._serialize = Serializer(self._models_dict(api_version)) + mixin_instance._deserialize = Deserializer(self._models_dict(api_version)) + return await mixin_instance.full_backup_status(vault_base_url, job_id, **kwargs) + + async def restore_status( + self, + vault_base_url: str, + job_id: str, + **kwargs + ) -> "models.RestoreOperation": + """Returns the status of restore operation. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param job_id: The Job Id returned part of the restore operation. + :type job_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RestoreOperation, or the result of cls(response) + :rtype: ~azure.keyvault.v7_2.models.RestoreOperation + :raises: ~azure.core.exceptions.HttpResponseError + """ + api_version = self._get_api_version('restore_status') + if api_version == '7.2-preview': + from ..v7_2_preview.aio.operations_async import KeyVaultClientOperationsMixin as OperationClass + else: + raise NotImplementedError("APIVersion {} is not available".format(api_version)) + mixin_instance = OperationClass() + mixin_instance._client = self._client + mixin_instance._config = self._config + mixin_instance._serialize = Serializer(self._models_dict(api_version)) + mixin_instance._deserialize = Deserializer(self._models_dict(api_version)) + return await mixin_instance.restore_status(vault_base_url, job_id, **kwargs) diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/models.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/models.py new file mode 100644 index 000000000000..ef435f1d9667 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/models.py @@ -0,0 +1,7 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from .v7_2_preview.models import * diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/py.typed b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/__init__.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/__init__.py new file mode 100644 index 000000000000..a6c1f9b7a792 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/__init__.py @@ -0,0 +1,16 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._key_vault_client import KeyVaultClient +__all__ = ['KeyVaultClient'] + +try: + from ._patch import patch_sdk # type: ignore + patch_sdk() +except ImportError: + pass diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/_configuration.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/_configuration.py new file mode 100644 index 000000000000..f6a651dad142 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/_configuration.py @@ -0,0 +1,52 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any + +VERSION = "unknown" + +class KeyVaultClientConfiguration(Configuration): + """Configuration for KeyVaultClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + """ + + def __init__( + self, + **kwargs # type: Any + ): + # type: (...) -> None + super(KeyVaultClientConfiguration, self).__init__(**kwargs) + + self.api_version = "7.2-preview" + kwargs.setdefault('sdk_moniker', 'keyvault/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs # type: Any + ): + # type: (...) -> None + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or policies.HttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/_key_vault_client.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/_key_vault_client.py new file mode 100644 index 000000000000..91acb44b0c6b --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/_key_vault_client.py @@ -0,0 +1,64 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.core import PipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any + +from ._configuration import KeyVaultClientConfiguration +from .operations import KeyVaultClientOperationsMixin +from .operations import RoleDefinitionsOperations +from .operations import RoleAssignmentsOperations +from . import models + + +class KeyVaultClient(KeyVaultClientOperationsMixin): + """The key vault client performs cryptographic key operations and vault operations against the Key Vault service. + + :ivar role_definitions: RoleDefinitionsOperations operations + :vartype role_definitions: azure.keyvault.v7_2.operations.RoleDefinitionsOperations + :ivar role_assignments: RoleAssignmentsOperations operations + :vartype role_assignments: azure.keyvault.v7_2.operations.RoleAssignmentsOperations + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + """ + + def __init__( + self, + **kwargs # type: Any + ): + # type: (...) -> None + base_url = '{vaultBaseUrl}' + self._config = KeyVaultClientConfiguration(**kwargs) + self._client = PipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + + self.role_definitions = RoleDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.role_assignments = RoleAssignmentsOperations( + self._client, self._config, self._serialize, self._deserialize) + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> KeyVaultClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/_metadata.json b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/_metadata.json new file mode 100644 index 000000000000..2e1b4f3b0f3c --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/_metadata.json @@ -0,0 +1,131 @@ +{ + "chosen_version": "7.2-preview", + "total_api_version_list": ["7.2-preview"], + "client": { + "name": "KeyVaultClient", + "filename": "_key_vault_client", + "description": "The key vault client performs cryptographic key operations and vault operations against the Key Vault service.", + "base_url": null, + "custom_base_url": "\u0027{vaultBaseUrl}\u0027", + "azure_arm": false + }, + "global_parameters": { + "sync_method": { + }, + "async_method": { + }, + "constant": { + }, + "call": "" + }, + "config": { + "credential": false, + "credential_scopes": null, + "credential_default_policy_type": "BearerTokenCredentialPolicy", + "credential_default_policy_type_has_async_version": true + }, + "operation_groups": { + "role_definitions": "RoleDefinitionsOperations", + "role_assignments": "RoleAssignmentsOperations" + }, + "operation_mixins": { + "_full_backup_initial" : { + "sync": { + "signature": "def _full_backup_initial(\n self,\n vault_base_url, # type: str\n azure_storage_blob_container_uri=None, # type: Optional[\"models.SASTokenParameter\"]\n **kwargs # type: Any\n):\n", + "doc": "\"\"\"\n\n:param vault_base_url: The vault name, for example https://myvault.vault.azure.net.\n:type vault_base_url: str\n:param azure_storage_blob_container_uri: Azure blob shared access signature token pointing to a\n valid Azure blob container where full backup needs to be stored. This token needs to be valid\n for at least next 24 hours from the time of making this call.\n:type azure_storage_blob_container_uri: ~azure.keyvault.v7_2.models.SASTokenParameter\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: FullBackupOperation, or the result of cls(response)\n:rtype: ~azure.keyvault.v7_2.models.FullBackupOperation\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" + }, + "async": { + "coroutine": true, + "signature": "async def _full_backup_initial(\n self,\n vault_base_url: str,\n azure_storage_blob_container_uri: Optional[\"models.SASTokenParameter\"] = None,\n **kwargs\n) -\u003e \"models.FullBackupOperation\":\n", + "doc": "\"\"\"\n\n:param vault_base_url: The vault name, for example https://myvault.vault.azure.net.\n:type vault_base_url: str\n:param azure_storage_blob_container_uri: Azure blob shared access signature token pointing to a\n valid Azure blob container where full backup needs to be stored. This token needs to be valid\n for at least next 24 hours from the time of making this call.\n:type azure_storage_blob_container_uri: ~azure.keyvault.v7_2.models.SASTokenParameter\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: FullBackupOperation, or the result of cls(response)\n:rtype: ~azure.keyvault.v7_2.models.FullBackupOperation\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" + }, + "call": "vault_base_url, azure_storage_blob_container_uri" + }, + "begin_full_backup" : { + "sync": { + "signature": "def begin_full_backup(\n self,\n vault_base_url, # type: str\n azure_storage_blob_container_uri=None, # type: Optional[\"models.SASTokenParameter\"]\n **kwargs # type: Any\n):\n", + "doc": "\"\"\"Creates a full backup using a user-provided SAS token to an Azure blob storage container.\n\n:param vault_base_url: The vault name, for example https://myvault.vault.azure.net.\n:type vault_base_url: str\n:param azure_storage_blob_container_uri: Azure blob shared access signature token pointing to a\n valid Azure blob container where full backup needs to be stored. This token needs to be valid\n for at least next 24 hours from the time of making this call.\n:type azure_storage_blob_container_uri: ~azure.keyvault.v7_2.models.SASTokenParameter\n:keyword callable cls: A custom type or function that will be passed the direct response\n:keyword str continuation_token: A continuation token to restart a poller from a saved state.\n:keyword polling: True for ARMPolling, False for no polling, or a\n polling object for personal polling strategy\n:paramtype polling: bool or ~azure.core.polling.PollingMethod\n:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.\n:return: An instance of LROPoller that returns either FullBackupOperation or the result of cls(response)\n:rtype: ~azure.core.polling.LROPoller[~azure.keyvault.v7_2.models.FullBackupOperation]\n:raises ~azure.core.exceptions.HttpResponseError:\n\"\"\"" + }, + "async": { + "coroutine": true, + "signature": "async def begin_full_backup(\n self,\n vault_base_url: str,\n azure_storage_blob_container_uri: Optional[\"models.SASTokenParameter\"] = None,\n **kwargs\n) -\u003e AsyncLROPoller[\"models.FullBackupOperation\"]:\n", + "doc": "\"\"\"Creates a full backup using a user-provided SAS token to an Azure blob storage container.\n\n:param vault_base_url: The vault name, for example https://myvault.vault.azure.net.\n:type vault_base_url: str\n:param azure_storage_blob_container_uri: Azure blob shared access signature token pointing to a\n valid Azure blob container where full backup needs to be stored. This token needs to be valid\n for at least next 24 hours from the time of making this call.\n:type azure_storage_blob_container_uri: ~azure.keyvault.v7_2.models.SASTokenParameter\n:keyword callable cls: A custom type or function that will be passed the direct response\n:keyword str continuation_token: A continuation token to restart a poller from a saved state.\n:keyword polling: True for ARMPolling, False for no polling, or a\n polling object for personal polling strategy\n:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod\n:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.\n:return: An instance of AsyncLROPoller that returns either FullBackupOperation or the result of cls(response)\n:rtype: ~azure.core.polling.AsyncLROPoller[~azure.keyvault.v7_2.models.FullBackupOperation]\n:raises ~azure.core.exceptions.HttpResponseError:\n\"\"\"" + }, + "call": "vault_base_url, azure_storage_blob_container_uri" + }, + "full_backup_status" : { + "sync": { + "signature": "def full_backup_status(\n self,\n vault_base_url, # type: str\n job_id, # type: str\n **kwargs # type: Any\n):\n", + "doc": "\"\"\"Returns the status of full backup operation.\n\n:param vault_base_url: The vault name, for example https://myvault.vault.azure.net.\n:type vault_base_url: str\n:param job_id: The id returned as part of the backup request.\n:type job_id: str\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: FullBackupOperation, or the result of cls(response)\n:rtype: ~azure.keyvault.v7_2.models.FullBackupOperation\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" + }, + "async": { + "coroutine": true, + "signature": "async def full_backup_status(\n self,\n vault_base_url: str,\n job_id: str,\n **kwargs\n) -\u003e \"models.FullBackupOperation\":\n", + "doc": "\"\"\"Returns the status of full backup operation.\n\n:param vault_base_url: The vault name, for example https://myvault.vault.azure.net.\n:type vault_base_url: str\n:param job_id: The id returned as part of the backup request.\n:type job_id: str\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: FullBackupOperation, or the result of cls(response)\n:rtype: ~azure.keyvault.v7_2.models.FullBackupOperation\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" + }, + "call": "vault_base_url, job_id" + }, + "_full_restore_operation_initial" : { + "sync": { + "signature": "def _full_restore_operation_initial(\n self,\n vault_base_url, # type: str\n restore_blob_details=None, # type: Optional[\"models.RestoreOperationParameters\"]\n **kwargs # type: Any\n):\n", + "doc": "\"\"\"\n\n:param vault_base_url: The vault name, for example https://myvault.vault.azure.net.\n:type vault_base_url: str\n:param restore_blob_details: The Azure blob SAS token pointing to a folder where the previous\n successful full backup was stored.\n:type restore_blob_details: ~azure.keyvault.v7_2.models.RestoreOperationParameters\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: RestoreOperation, or the result of cls(response)\n:rtype: ~azure.keyvault.v7_2.models.RestoreOperation\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" + }, + "async": { + "coroutine": true, + "signature": "async def _full_restore_operation_initial(\n self,\n vault_base_url: str,\n restore_blob_details: Optional[\"models.RestoreOperationParameters\"] = None,\n **kwargs\n) -\u003e \"models.RestoreOperation\":\n", + "doc": "\"\"\"\n\n:param vault_base_url: The vault name, for example https://myvault.vault.azure.net.\n:type vault_base_url: str\n:param restore_blob_details: The Azure blob SAS token pointing to a folder where the previous\n successful full backup was stored.\n:type restore_blob_details: ~azure.keyvault.v7_2.models.RestoreOperationParameters\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: RestoreOperation, or the result of cls(response)\n:rtype: ~azure.keyvault.v7_2.models.RestoreOperation\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" + }, + "call": "vault_base_url, restore_blob_details" + }, + "begin_full_restore_operation" : { + "sync": { + "signature": "def begin_full_restore_operation(\n self,\n vault_base_url, # type: str\n restore_blob_details=None, # type: Optional[\"models.RestoreOperationParameters\"]\n **kwargs # type: Any\n):\n", + "doc": "\"\"\"Restores all key materials using the SAS token pointing to a previously stored Azure Blob\nstorage backup folder.\n\n:param vault_base_url: The vault name, for example https://myvault.vault.azure.net.\n:type vault_base_url: str\n:param restore_blob_details: The Azure blob SAS token pointing to a folder where the previous\n successful full backup was stored.\n:type restore_blob_details: ~azure.keyvault.v7_2.models.RestoreOperationParameters\n:keyword callable cls: A custom type or function that will be passed the direct response\n:keyword str continuation_token: A continuation token to restart a poller from a saved state.\n:keyword polling: True for ARMPolling, False for no polling, or a\n polling object for personal polling strategy\n:paramtype polling: bool or ~azure.core.polling.PollingMethod\n:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.\n:return: An instance of LROPoller that returns either RestoreOperation or the result of cls(response)\n:rtype: ~azure.core.polling.LROPoller[~azure.keyvault.v7_2.models.RestoreOperation]\n:raises ~azure.core.exceptions.HttpResponseError:\n\"\"\"" + }, + "async": { + "coroutine": true, + "signature": "async def begin_full_restore_operation(\n self,\n vault_base_url: str,\n restore_blob_details: Optional[\"models.RestoreOperationParameters\"] = None,\n **kwargs\n) -\u003e AsyncLROPoller[\"models.RestoreOperation\"]:\n", + "doc": "\"\"\"Restores all key materials using the SAS token pointing to a previously stored Azure Blob\nstorage backup folder.\n\n:param vault_base_url: The vault name, for example https://myvault.vault.azure.net.\n:type vault_base_url: str\n:param restore_blob_details: The Azure blob SAS token pointing to a folder where the previous\n successful full backup was stored.\n:type restore_blob_details: ~azure.keyvault.v7_2.models.RestoreOperationParameters\n:keyword callable cls: A custom type or function that will be passed the direct response\n:keyword str continuation_token: A continuation token to restart a poller from a saved state.\n:keyword polling: True for ARMPolling, False for no polling, or a\n polling object for personal polling strategy\n:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod\n:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.\n:return: An instance of AsyncLROPoller that returns either RestoreOperation or the result of cls(response)\n:rtype: ~azure.core.polling.AsyncLROPoller[~azure.keyvault.v7_2.models.RestoreOperation]\n:raises ~azure.core.exceptions.HttpResponseError:\n\"\"\"" + }, + "call": "vault_base_url, restore_blob_details" + }, + "restore_status" : { + "sync": { + "signature": "def restore_status(\n self,\n vault_base_url, # type: str\n job_id, # type: str\n **kwargs # type: Any\n):\n", + "doc": "\"\"\"Returns the status of restore operation.\n\n:param vault_base_url: The vault name, for example https://myvault.vault.azure.net.\n:type vault_base_url: str\n:param job_id: The Job Id returned part of the restore operation.\n:type job_id: str\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: RestoreOperation, or the result of cls(response)\n:rtype: ~azure.keyvault.v7_2.models.RestoreOperation\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" + }, + "async": { + "coroutine": true, + "signature": "async def restore_status(\n self,\n vault_base_url: str,\n job_id: str,\n **kwargs\n) -\u003e \"models.RestoreOperation\":\n", + "doc": "\"\"\"Returns the status of restore operation.\n\n:param vault_base_url: The vault name, for example https://myvault.vault.azure.net.\n:type vault_base_url: str\n:param job_id: The Job Id returned part of the restore operation.\n:type job_id: str\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: RestoreOperation, or the result of cls(response)\n:rtype: ~azure.keyvault.v7_2.models.RestoreOperation\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" + }, + "call": "vault_base_url, job_id" + }, + "_selective_key_restore_operation_initial" : { + "sync": { + "signature": "def _selective_key_restore_operation_initial(\n self,\n vault_base_url, # type: str\n key_name, # type: str\n restore_blob_details=None, # type: Optional[\"models.SelectiveKeyRestoreOperationParameters\"]\n **kwargs # type: Any\n):\n", + "doc": "\"\"\"\n\n:param vault_base_url: The vault name, for example https://myvault.vault.azure.net.\n:type vault_base_url: str\n:param key_name: The name of the key to be restored from the user supplied backup.\n:type key_name: str\n:param restore_blob_details: The Azure blob SAS token pointing to a folder where the previous\n successful full backup was stored.\n:type restore_blob_details: ~azure.keyvault.v7_2.models.SelectiveKeyRestoreOperationParameters\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: SelectiveKeyRestoreOperation, or the result of cls(response)\n:rtype: ~azure.keyvault.v7_2.models.SelectiveKeyRestoreOperation\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" + }, + "async": { + "coroutine": true, + "signature": "async def _selective_key_restore_operation_initial(\n self,\n vault_base_url: str,\n key_name: str,\n restore_blob_details: Optional[\"models.SelectiveKeyRestoreOperationParameters\"] = None,\n **kwargs\n) -\u003e \"models.SelectiveKeyRestoreOperation\":\n", + "doc": "\"\"\"\n\n:param vault_base_url: The vault name, for example https://myvault.vault.azure.net.\n:type vault_base_url: str\n:param key_name: The name of the key to be restored from the user supplied backup.\n:type key_name: str\n:param restore_blob_details: The Azure blob SAS token pointing to a folder where the previous\n successful full backup was stored.\n:type restore_blob_details: ~azure.keyvault.v7_2.models.SelectiveKeyRestoreOperationParameters\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: SelectiveKeyRestoreOperation, or the result of cls(response)\n:rtype: ~azure.keyvault.v7_2.models.SelectiveKeyRestoreOperation\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" + }, + "call": "vault_base_url, key_name, restore_blob_details" + }, + "begin_selective_key_restore_operation" : { + "sync": { + "signature": "def begin_selective_key_restore_operation(\n self,\n vault_base_url, # type: str\n key_name, # type: str\n restore_blob_details=None, # type: Optional[\"models.SelectiveKeyRestoreOperationParameters\"]\n **kwargs # type: Any\n):\n", + "doc": "\"\"\"Restores all key versions of a given key using user supplied SAS token pointing to a previously\nstored Azure Blob storage backup folder.\n\n:param vault_base_url: The vault name, for example https://myvault.vault.azure.net.\n:type vault_base_url: str\n:param key_name: The name of the key to be restored from the user supplied backup.\n:type key_name: str\n:param restore_blob_details: The Azure blob SAS token pointing to a folder where the previous\n successful full backup was stored.\n:type restore_blob_details: ~azure.keyvault.v7_2.models.SelectiveKeyRestoreOperationParameters\n:keyword callable cls: A custom type or function that will be passed the direct response\n:keyword str continuation_token: A continuation token to restart a poller from a saved state.\n:keyword polling: True for ARMPolling, False for no polling, or a\n polling object for personal polling strategy\n:paramtype polling: bool or ~azure.core.polling.PollingMethod\n:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.\n:return: An instance of LROPoller that returns either SelectiveKeyRestoreOperation or the result of cls(response)\n:rtype: ~azure.core.polling.LROPoller[~azure.keyvault.v7_2.models.SelectiveKeyRestoreOperation]\n:raises ~azure.core.exceptions.HttpResponseError:\n\"\"\"" + }, + "async": { + "coroutine": true, + "signature": "async def begin_selective_key_restore_operation(\n self,\n vault_base_url: str,\n key_name: str,\n restore_blob_details: Optional[\"models.SelectiveKeyRestoreOperationParameters\"] = None,\n **kwargs\n) -\u003e AsyncLROPoller[\"models.SelectiveKeyRestoreOperation\"]:\n", + "doc": "\"\"\"Restores all key versions of a given key using user supplied SAS token pointing to a previously\nstored Azure Blob storage backup folder.\n\n:param vault_base_url: The vault name, for example https://myvault.vault.azure.net.\n:type vault_base_url: str\n:param key_name: The name of the key to be restored from the user supplied backup.\n:type key_name: str\n:param restore_blob_details: The Azure blob SAS token pointing to a folder where the previous\n successful full backup was stored.\n:type restore_blob_details: ~azure.keyvault.v7_2.models.SelectiveKeyRestoreOperationParameters\n:keyword callable cls: A custom type or function that will be passed the direct response\n:keyword str continuation_token: A continuation token to restart a poller from a saved state.\n:keyword polling: True for ARMPolling, False for no polling, or a\n polling object for personal polling strategy\n:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod\n:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.\n:return: An instance of AsyncLROPoller that returns either SelectiveKeyRestoreOperation or the result of cls(response)\n:rtype: ~azure.core.polling.AsyncLROPoller[~azure.keyvault.v7_2.models.SelectiveKeyRestoreOperation]\n:raises ~azure.core.exceptions.HttpResponseError:\n\"\"\"" + }, + "call": "vault_base_url, key_name, restore_blob_details" + } + }, + "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.exceptions\": [\"HttpResponseError\", \"ResourceExistsError\", \"ResourceNotFoundError\", \"map_error\"], \"azure.core.pipeline\": [\"PipelineResponse\"], \"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"], \"azure.core.polling\": [\"LROPoller\", \"NoPolling\", \"PollingMethod\"], \"azure.core.polling.base_polling\": [\"LROBasePolling\"]}, \"stdlib\": {\"warnings\": [null]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Callable\", \"Dict\", \"Generic\", \"Optional\", \"TypeVar\", \"Union\"]}}}", + "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.exceptions\": [\"HttpResponseError\", \"ResourceExistsError\", \"ResourceNotFoundError\", \"map_error\"], \"azure.core.pipeline\": [\"PipelineResponse\"], \"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"], \"azure.core.polling\": [\"AsyncLROPoller\", \"AsyncNoPolling\", \"AsyncPollingMethod\"], \"azure.core.polling.async_base_polling\": [\"AsyncLROBasePolling\"]}, \"stdlib\": {\"warnings\": [null]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Callable\", \"Dict\", \"Generic\", \"Optional\", \"TypeVar\", \"Union\"]}}}" +} \ No newline at end of file diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/__init__.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/__init__.py new file mode 100644 index 000000000000..71ceadebe430 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/__init__.py @@ -0,0 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._key_vault_client_async import KeyVaultClient +__all__ = ['KeyVaultClient'] diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/_configuration_async.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/_configuration_async.py new file mode 100644 index 000000000000..5abffe30345d --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/_configuration_async.py @@ -0,0 +1,46 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies + +VERSION = "unknown" + +class KeyVaultClientConfiguration(Configuration): + """Configuration for KeyVaultClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + """ + + def __init__( + self, + **kwargs: Any + ) -> None: + super(KeyVaultClientConfiguration, self).__init__(**kwargs) + + self.api_version = "7.2-preview" + kwargs.setdefault('sdk_moniker', 'keyvault/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs: Any + ) -> None: + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or policies.HttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/_key_vault_client_async.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/_key_vault_client_async.py new file mode 100644 index 000000000000..9b3ec815b8e8 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/_key_vault_client_async.py @@ -0,0 +1,56 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any + +from azure.core import AsyncPipelineClient +from msrest import Deserializer, Serializer + +from ._configuration_async import KeyVaultClientConfiguration +from .operations_async import KeyVaultClientOperationsMixin +from .operations_async import RoleDefinitionsOperations +from .operations_async import RoleAssignmentsOperations +from .. import models + + +class KeyVaultClient(KeyVaultClientOperationsMixin): + """The key vault client performs cryptographic key operations and vault operations against the Key Vault service. + + :ivar role_definitions: RoleDefinitionsOperations operations + :vartype role_definitions: azure.keyvault.v7_2.aio.operations_async.RoleDefinitionsOperations + :ivar role_assignments: RoleAssignmentsOperations operations + :vartype role_assignments: azure.keyvault.v7_2.aio.operations_async.RoleAssignmentsOperations + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + """ + + def __init__( + self, + **kwargs: Any + ) -> None: + base_url = '{vaultBaseUrl}' + self._config = KeyVaultClientConfiguration(**kwargs) + self._client = AsyncPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + + self.role_definitions = RoleDefinitionsOperations( + self._client, self._config, self._serialize, self._deserialize) + self.role_assignments = RoleAssignmentsOperations( + self._client, self._config, self._serialize, self._deserialize) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "KeyVaultClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/operations_async/__init__.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/operations_async/__init__.py new file mode 100644 index 000000000000..1934ebc06adf --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/operations_async/__init__.py @@ -0,0 +1,17 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._key_vault_client_operations_async import KeyVaultClientOperationsMixin +from ._role_definitions_operations_async import RoleDefinitionsOperations +from ._role_assignments_operations_async import RoleAssignmentsOperations + +__all__ = [ + 'KeyVaultClientOperationsMixin', + 'RoleDefinitionsOperations', + 'RoleAssignmentsOperations', +] diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/operations_async/_key_vault_client_operations_async.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/operations_async/_key_vault_client_operations_async.py new file mode 100644 index 000000000000..2aa256e4d1b0 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/operations_async/_key_vault_client_operations_async.py @@ -0,0 +1,504 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union +import warnings + +from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.polling.async_base_polling import AsyncLROBasePolling + +from ... import models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class KeyVaultClientOperationsMixin: + + async def _full_backup_initial( + self, + vault_base_url: str, + azure_storage_blob_container_uri: Optional["models.SASTokenParameter"] = None, + **kwargs + ) -> "models.FullBackupOperation": + cls = kwargs.pop('cls', None) # type: ClsType["models.FullBackupOperation"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + api_version = "7.2-preview" + content_type = kwargs.pop("content_type", "application/json") + + # Construct URL + url = self._full_backup_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = 'application/json' + + body_content_kwargs = {} # type: Dict[str, Any] + if azure_storage_blob_container_uri is not None: + body_content = self._serialize.body(azure_storage_blob_container_uri, 'SASTokenParameter') + else: + body_content = None + body_content_kwargs['content'] = body_content + request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize(models.KeyVaultError, response) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers['Azure-AsyncOperation']=self._deserialize('str', response.headers.get('Azure-AsyncOperation')) + deserialized = self._deserialize('FullBackupOperation', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + _full_backup_initial.metadata = {'url': '/backup'} # type: ignore + + async def begin_full_backup( + self, + vault_base_url: str, + azure_storage_blob_container_uri: Optional["models.SASTokenParameter"] = None, + **kwargs + ) -> AsyncLROPoller["models.FullBackupOperation"]: + """Creates a full backup using a user-provided SAS token to an Azure blob storage container. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param azure_storage_blob_container_uri: Azure blob shared access signature token pointing to a + valid Azure blob container where full backup needs to be stored. This token needs to be valid + for at least next 24 hours from the time of making this call. + :type azure_storage_blob_container_uri: ~azure.keyvault.v7_2.models.SASTokenParameter + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: True for ARMPolling, False for no polling, or a + polling object for personal polling strategy + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either FullBackupOperation or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.keyvault.v7_2.models.FullBackupOperation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', False) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["models.FullBackupOperation"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._full_backup_initial( + vault_base_url=vault_base_url, + azure_storage_blob_container_uri=azure_storage_blob_container_uri, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + response_headers = {} + response = pipeline_response.http_response + response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers['Azure-AsyncOperation']=self._deserialize('str', response.headers.get('Azure-AsyncOperation')) + deserialized = self._deserialize('FullBackupOperation', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + return deserialized + + if polling is True: polling_method = AsyncLROBasePolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_full_backup.metadata = {'url': '/backup'} # type: ignore + + async def full_backup_status( + self, + vault_base_url: str, + job_id: str, + **kwargs + ) -> "models.FullBackupOperation": + """Returns the status of full backup operation. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param job_id: The id returned as part of the backup request. + :type job_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FullBackupOperation, or the result of cls(response) + :rtype: ~azure.keyvault.v7_2.models.FullBackupOperation + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["models.FullBackupOperation"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + api_version = "7.2-preview" + + # Construct URL + url = self.full_backup_status.metadata['url'] # type: ignore + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + 'jobId': self._serialize.url("job_id", job_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = 'application/json' + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize(models.KeyVaultError, response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize('FullBackupOperation', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + full_backup_status.metadata = {'url': '/backup/{jobId}/pending'} # type: ignore + + async def _full_restore_operation_initial( + self, + vault_base_url: str, + restore_blob_details: Optional["models.RestoreOperationParameters"] = None, + **kwargs + ) -> "models.RestoreOperation": + cls = kwargs.pop('cls', None) # type: ClsType["models.RestoreOperation"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + api_version = "7.2-preview" + content_type = kwargs.pop("content_type", "application/json") + + # Construct URL + url = self._full_restore_operation_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = 'application/json' + + body_content_kwargs = {} # type: Dict[str, Any] + if restore_blob_details is not None: + body_content = self._serialize.body(restore_blob_details, 'RestoreOperationParameters') + else: + body_content = None + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize(models.KeyVaultError, response) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers['Azure-AsyncOperation']=self._deserialize('str', response.headers.get('Azure-AsyncOperation')) + deserialized = self._deserialize('RestoreOperation', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + _full_restore_operation_initial.metadata = {'url': '/restore'} # type: ignore + + async def begin_full_restore_operation( + self, + vault_base_url: str, + restore_blob_details: Optional["models.RestoreOperationParameters"] = None, + **kwargs + ) -> AsyncLROPoller["models.RestoreOperation"]: + """Restores all key materials using the SAS token pointing to a previously stored Azure Blob + storage backup folder. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param restore_blob_details: The Azure blob SAS token pointing to a folder where the previous + successful full backup was stored. + :type restore_blob_details: ~azure.keyvault.v7_2.models.RestoreOperationParameters + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: True for ARMPolling, False for no polling, or a + polling object for personal polling strategy + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either RestoreOperation or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.keyvault.v7_2.models.RestoreOperation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', False) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["models.RestoreOperation"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._full_restore_operation_initial( + vault_base_url=vault_base_url, + restore_blob_details=restore_blob_details, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + response_headers = {} + response = pipeline_response.http_response + response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers['Azure-AsyncOperation']=self._deserialize('str', response.headers.get('Azure-AsyncOperation')) + deserialized = self._deserialize('RestoreOperation', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + return deserialized + + if polling is True: polling_method = AsyncLROBasePolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_full_restore_operation.metadata = {'url': '/restore'} # type: ignore + + async def restore_status( + self, + vault_base_url: str, + job_id: str, + **kwargs + ) -> "models.RestoreOperation": + """Returns the status of restore operation. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param job_id: The Job Id returned part of the restore operation. + :type job_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RestoreOperation, or the result of cls(response) + :rtype: ~azure.keyvault.v7_2.models.RestoreOperation + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["models.RestoreOperation"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + api_version = "7.2-preview" + + # Construct URL + url = self.restore_status.metadata['url'] # type: ignore + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + 'jobId': self._serialize.url("job_id", job_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = 'application/json' + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize(models.KeyVaultError, response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize('RestoreOperation', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + restore_status.metadata = {'url': '/restore/{jobId}/pending'} # type: ignore + + async def _selective_key_restore_operation_initial( + self, + vault_base_url: str, + key_name: str, + restore_blob_details: Optional["models.SelectiveKeyRestoreOperationParameters"] = None, + **kwargs + ) -> "models.SelectiveKeyRestoreOperation": + cls = kwargs.pop('cls', None) # type: ClsType["models.SelectiveKeyRestoreOperation"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + api_version = "7.2-preview" + content_type = kwargs.pop("content_type", "application/json") + + # Construct URL + url = self._selective_key_restore_operation_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + 'keyName': self._serialize.url("key_name", key_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = 'application/json' + + body_content_kwargs = {} # type: Dict[str, Any] + if restore_blob_details is not None: + body_content = self._serialize.body(restore_blob_details, 'SelectiveKeyRestoreOperationParameters') + else: + body_content = None + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize(models.KeyVaultError, response) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers['Azure-AsyncOperation']=self._deserialize('str', response.headers.get('Azure-AsyncOperation')) + deserialized = self._deserialize('SelectiveKeyRestoreOperation', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + _selective_key_restore_operation_initial.metadata = {'url': '/keys/{keyName}/restore'} # type: ignore + + async def begin_selective_key_restore_operation( + self, + vault_base_url: str, + key_name: str, + restore_blob_details: Optional["models.SelectiveKeyRestoreOperationParameters"] = None, + **kwargs + ) -> AsyncLROPoller["models.SelectiveKeyRestoreOperation"]: + """Restores all key versions of a given key using user supplied SAS token pointing to a previously + stored Azure Blob storage backup folder. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param key_name: The name of the key to be restored from the user supplied backup. + :type key_name: str + :param restore_blob_details: The Azure blob SAS token pointing to a folder where the previous + successful full backup was stored. + :type restore_blob_details: ~azure.keyvault.v7_2.models.SelectiveKeyRestoreOperationParameters + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: True for ARMPolling, False for no polling, or a + polling object for personal polling strategy + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either SelectiveKeyRestoreOperation or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.keyvault.v7_2.models.SelectiveKeyRestoreOperation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', False) # type: Union[bool, AsyncPollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["models.SelectiveKeyRestoreOperation"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = await self._selective_key_restore_operation_initial( + vault_base_url=vault_base_url, + key_name=key_name, + restore_blob_details=restore_blob_details, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + response_headers = {} + response = pipeline_response.http_response + response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers['Azure-AsyncOperation']=self._deserialize('str', response.headers.get('Azure-AsyncOperation')) + deserialized = self._deserialize('SelectiveKeyRestoreOperation', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + return deserialized + + if polling is True: polling_method = AsyncLROBasePolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs) + elif polling is False: polling_method = AsyncNoPolling() + else: polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_selective_key_restore_operation.metadata = {'url': '/keys/{keyName}/restore'} # type: ignore diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/operations_async/_role_assignments_operations_async.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/operations_async/_role_assignments_operations_async.py new file mode 100644 index 000000000000..156ca54342fa --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/operations_async/_role_assignments_operations_async.py @@ -0,0 +1,311 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest + +from ... import models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class RoleAssignmentsOperations: + """RoleAssignmentsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.keyvault.v7_2.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + async def delete( + self, + vault_base_url: str, + scope: str, + role_assignment_name: str, + **kwargs + ) -> "models.RoleAssignment": + """Deletes a role assignment. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param scope: The scope of the role assignment to delete. + :type scope: str + :param role_assignment_name: The name of the role assignment to delete. + :type role_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment, or the result of cls(response) + :rtype: ~azure.keyvault.v7_2.models.RoleAssignment + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["models.RoleAssignment"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + api_version = "7.2-preview" + + # Construct URL + url = self.delete.metadata['url'] # type: ignore + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = 'application/json' + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize(models.KeyVaultError, response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize('RoleAssignment', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + delete.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + + async def create( + self, + vault_base_url: str, + scope: str, + role_assignment_name: str, + parameters: "models.RoleAssignmentCreateParameters", + **kwargs + ) -> "models.RoleAssignment": + """Creates a role assignment. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param scope: The scope of the role assignment to create. + :type scope: str + :param role_assignment_name: The name of the role assignment to create. It can be any valid + GUID. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. + :type parameters: ~azure.keyvault.v7_2.models.RoleAssignmentCreateParameters + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment, or the result of cls(response) + :rtype: ~azure.keyvault.v7_2.models.RoleAssignment + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["models.RoleAssignment"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + api_version = "7.2-preview" + content_type = kwargs.pop("content_type", "application/json") + + # Construct URL + url = self.create.metadata['url'] # type: ignore + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = 'application/json' + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize(models.KeyVaultError, response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize('RoleAssignment', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + create.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + + async def get( + self, + vault_base_url: str, + scope: str, + role_assignment_name: str, + **kwargs + ) -> "models.RoleAssignment": + """Get the specified role assignment. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param scope: The scope of the role assignment. + :type scope: str + :param role_assignment_name: The name of the role assignment to get. + :type role_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment, or the result of cls(response) + :rtype: ~azure.keyvault.v7_2.models.RoleAssignment + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["models.RoleAssignment"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + api_version = "7.2-preview" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = 'application/json' + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize(models.KeyVaultError, response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize('RoleAssignment', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + + def list_for_scope( + self, + vault_base_url: str, + scope: str, + filter: Optional[str] = None, + **kwargs + ) -> AsyncIterable["models.RoleAssignmentListResult"]: + """Gets role assignments for a scope. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param scope: The scope of the role assignments. + :type scope: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + assignments at or above the scope. Use $filter=principalId eq {id} to return all role + assignments at, above or below the scope for the specified principal. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.keyvault.v7_2.models.RoleAssignmentListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["models.RoleAssignmentListResult"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + api_version = "7.2-preview" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = 'application/json' + + if not next_link: + # Construct URL + url = self.list_for_scope.metadata['url'] # type: ignore + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + if filter is not None: + query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + } + url = self._client.format_url(url, **path_format_arguments) + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize(models.KeyVaultError, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/operations_async/_role_definitions_operations_async.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/operations_async/_role_definitions_operations_async.py new file mode 100644 index 000000000000..2fa72d1ca4d5 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/aio/operations_async/_role_definitions_operations_async.py @@ -0,0 +1,123 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest + +from ... import models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class RoleDefinitionsOperations: + """RoleDefinitionsOperations async operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.keyvault.v7_2.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = models + + def __init__(self, client, config, serializer, deserializer) -> None: + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + vault_base_url: str, + scope: str, + filter: Optional[str] = None, + **kwargs + ) -> AsyncIterable["models.RoleDefinitionListResult"]: + """Get all role definitions that are applicable at scope and above. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param scope: The scope of the role definition. + :type scope: str + :param filter: The filter to apply on the operation. Use atScopeAndBelow filter to search below + the given scope as well. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleDefinitionListResult or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.keyvault.v7_2.models.RoleDefinitionListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["models.RoleDefinitionListResult"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + api_version = "7.2-preview" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = 'application/json' + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + if filter is not None: + query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + } + url = self._client.format_url(url, **path_format_arguments) + request = self._client.get(url, query_parameters, header_parameters) + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize('RoleDefinitionListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize(models.KeyVaultError, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return AsyncItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleDefinitions'} # type: ignore diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/models/__init__.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/models/__init__.py new file mode 100644 index 000000000000..cbd7e3697d36 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/models/__init__.py @@ -0,0 +1,70 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +try: + from ._models_py3 import Attributes + from ._models_py3 import Error + from ._models_py3 import FullBackupOperation + from ._models_py3 import KeyVaultError + from ._models_py3 import Permission + from ._models_py3 import RestoreOperation + from ._models_py3 import RestoreOperationParameters + from ._models_py3 import RoleAssignment + from ._models_py3 import RoleAssignmentCreateParameters + from ._models_py3 import RoleAssignmentFilter + from ._models_py3 import RoleAssignmentListResult + from ._models_py3 import RoleAssignmentProperties + from ._models_py3 import RoleAssignmentPropertiesWithScope + from ._models_py3 import RoleDefinition + from ._models_py3 import RoleDefinitionFilter + from ._models_py3 import RoleDefinitionListResult + from ._models_py3 import SASTokenParameter + from ._models_py3 import SelectiveKeyRestoreOperation + from ._models_py3 import SelectiveKeyRestoreOperationParameters +except (SyntaxError, ImportError): + from ._models import Attributes # type: ignore + from ._models import Error # type: ignore + from ._models import FullBackupOperation # type: ignore + from ._models import KeyVaultError # type: ignore + from ._models import Permission # type: ignore + from ._models import RestoreOperation # type: ignore + from ._models import RestoreOperationParameters # type: ignore + from ._models import RoleAssignment # type: ignore + from ._models import RoleAssignmentCreateParameters # type: ignore + from ._models import RoleAssignmentFilter # type: ignore + from ._models import RoleAssignmentListResult # type: ignore + from ._models import RoleAssignmentProperties # type: ignore + from ._models import RoleAssignmentPropertiesWithScope # type: ignore + from ._models import RoleDefinition # type: ignore + from ._models import RoleDefinitionFilter # type: ignore + from ._models import RoleDefinitionListResult # type: ignore + from ._models import SASTokenParameter # type: ignore + from ._models import SelectiveKeyRestoreOperation # type: ignore + from ._models import SelectiveKeyRestoreOperationParameters # type: ignore + +__all__ = [ + 'Attributes', + 'Error', + 'FullBackupOperation', + 'KeyVaultError', + 'Permission', + 'RestoreOperation', + 'RestoreOperationParameters', + 'RoleAssignment', + 'RoleAssignmentCreateParameters', + 'RoleAssignmentFilter', + 'RoleAssignmentListResult', + 'RoleAssignmentProperties', + 'RoleAssignmentPropertiesWithScope', + 'RoleDefinition', + 'RoleDefinitionFilter', + 'RoleDefinitionListResult', + 'SASTokenParameter', + 'SelectiveKeyRestoreOperation', + 'SelectiveKeyRestoreOperationParameters', +] diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/models/_models.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/models/_models.py new file mode 100644 index 000000000000..99da7b8a82c3 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/models/_models.py @@ -0,0 +1,618 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.exceptions import HttpResponseError +import msrest.serialization + + +class Attributes(msrest.serialization.Model): + """The object attributes managed by the KeyVault service. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param enabled: Determines whether the object is enabled. + :type enabled: bool + :param not_before: Not before date in UTC. + :type not_before: ~datetime.datetime + :param expires: Expiry date in UTC. + :type expires: ~datetime.datetime + :ivar created: Creation time in UTC. + :vartype created: ~datetime.datetime + :ivar updated: Last updated time in UTC. + :vartype updated: ~datetime.datetime + """ + + _validation = { + 'created': {'readonly': True}, + 'updated': {'readonly': True}, + } + + _attribute_map = { + 'enabled': {'key': 'enabled', 'type': 'bool'}, + 'not_before': {'key': 'nbf', 'type': 'unix-time'}, + 'expires': {'key': 'exp', 'type': 'unix-time'}, + 'created': {'key': 'created', 'type': 'unix-time'}, + 'updated': {'key': 'updated', 'type': 'unix-time'}, + } + + def __init__( + self, + **kwargs + ): + super(Attributes, self).__init__(**kwargs) + self.enabled = kwargs.get('enabled', None) + self.not_before = kwargs.get('not_before', None) + self.expires = kwargs.get('expires', None) + self.created = None + self.updated = None + + +class Error(msrest.serialization.Model): + """The key vault server error. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar inner_error: The key vault server error. + :vartype inner_error: ~azure.keyvault.v7_2.models.Error + """ + + _validation = { + 'code': {'readonly': True}, + 'message': {'readonly': True}, + 'inner_error': {'readonly': True}, + } + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + 'inner_error': {'key': 'innererror', 'type': 'Error'}, + } + + def __init__( + self, + **kwargs + ): + super(Error, self).__init__(**kwargs) + self.code = None + self.message = None + self.inner_error = None + + +class FullBackupOperation(msrest.serialization.Model): + """Full backup operation. + + :param status: Status of the backup operation. + :type status: str + :param status_details: The status details of backup operation. + :type status_details: str + :param error: Error encountered, if any, during the full backup operation. + :type error: ~azure.keyvault.v7_2.models.Error + :param start_time: The start time of the backup operation in UTC. + :type start_time: ~datetime.datetime + :param end_time: The end time of the backup operation in UTC. + :type end_time: ~datetime.datetime + :param job_id: Identifier for the full backup operation. + :type job_id: str + :param azure_storage_blob_container_uri: The Azure blob storage container Uri which contains + the full backup. + :type azure_storage_blob_container_uri: str + """ + + _attribute_map = { + 'status': {'key': 'status', 'type': 'str'}, + 'status_details': {'key': 'statusDetails', 'type': 'str'}, + 'error': {'key': 'error', 'type': 'Error'}, + 'start_time': {'key': 'startTime', 'type': 'unix-time'}, + 'end_time': {'key': 'endTime', 'type': 'unix-time'}, + 'job_id': {'key': 'jobId', 'type': 'str'}, + 'azure_storage_blob_container_uri': {'key': 'azureStorageBlobContainerUri', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(FullBackupOperation, self).__init__(**kwargs) + self.status = kwargs.get('status', None) + self.status_details = kwargs.get('status_details', None) + self.error = kwargs.get('error', None) + self.start_time = kwargs.get('start_time', None) + self.end_time = kwargs.get('end_time', None) + self.job_id = kwargs.get('job_id', None) + self.azure_storage_blob_container_uri = kwargs.get('azure_storage_blob_container_uri', None) + + +class KeyVaultError(msrest.serialization.Model): + """The key vault error exception. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar error: The key vault server error. + :vartype error: ~azure.keyvault.v7_2.models.Error + """ + + _validation = { + 'error': {'readonly': True}, + } + + _attribute_map = { + 'error': {'key': 'error', 'type': 'Error'}, + } + + def __init__( + self, + **kwargs + ): + super(KeyVaultError, self).__init__(**kwargs) + self.error = None + + +class Permission(msrest.serialization.Model): + """Role definition permissions. + + :param actions: Allowed actions. + :type actions: list[str] + :param not_actions: Denied actions. + :type not_actions: list[str] + :param data_actions: Allowed Data actions. + :type data_actions: list[str] + :param not_data_actions: Denied Data actions. + :type not_data_actions: list[str] + """ + + _attribute_map = { + 'actions': {'key': 'actions', 'type': '[str]'}, + 'not_actions': {'key': 'notActions', 'type': '[str]'}, + 'data_actions': {'key': 'dataActions', 'type': '[str]'}, + 'not_data_actions': {'key': 'notDataActions', 'type': '[str]'}, + } + + def __init__( + self, + **kwargs + ): + super(Permission, self).__init__(**kwargs) + self.actions = kwargs.get('actions', None) + self.not_actions = kwargs.get('not_actions', None) + self.data_actions = kwargs.get('data_actions', None) + self.not_data_actions = kwargs.get('not_data_actions', None) + + +class RestoreOperation(msrest.serialization.Model): + """Restore operation. + + :param status: Status of the restore operation. + :type status: str + :param status_details: The status details of restore operation. + :type status_details: str + :param error: Error encountered, if any, during the restore operation. + :type error: ~azure.keyvault.v7_2.models.Error + :param job_id: Identifier for the restore operation. + :type job_id: str + :param start_time: The start time of the restore operation. + :type start_time: ~datetime.datetime + :param end_time: The end time of the restore operation. + :type end_time: ~datetime.datetime + """ + + _attribute_map = { + 'status': {'key': 'status', 'type': 'str'}, + 'status_details': {'key': 'statusDetails', 'type': 'str'}, + 'error': {'key': 'error', 'type': 'Error'}, + 'job_id': {'key': 'jobId', 'type': 'str'}, + 'start_time': {'key': 'startTime', 'type': 'unix-time'}, + 'end_time': {'key': 'endTime', 'type': 'unix-time'}, + } + + def __init__( + self, + **kwargs + ): + super(RestoreOperation, self).__init__(**kwargs) + self.status = kwargs.get('status', None) + self.status_details = kwargs.get('status_details', None) + self.error = kwargs.get('error', None) + self.job_id = kwargs.get('job_id', None) + self.start_time = kwargs.get('start_time', None) + self.end_time = kwargs.get('end_time', None) + + +class RestoreOperationParameters(msrest.serialization.Model): + """RestoreOperationParameters. + + All required parameters must be populated in order to send to Azure. + + :param sas_token_parameters: Required. + :type sas_token_parameters: ~azure.keyvault.v7_2.models.SASTokenParameter + :param folder_to_restore: Required. The Folder name of the blob where the previous successful + full backup was stored. + :type folder_to_restore: str + """ + + _validation = { + 'sas_token_parameters': {'required': True}, + 'folder_to_restore': {'required': True}, + } + + _attribute_map = { + 'sas_token_parameters': {'key': 'sasTokenParameters', 'type': 'SASTokenParameter'}, + 'folder_to_restore': {'key': 'folderToRestore', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(RestoreOperationParameters, self).__init__(**kwargs) + self.sas_token_parameters = kwargs['sas_token_parameters'] + self.folder_to_restore = kwargs['folder_to_restore'] + + +class RoleAssignment(msrest.serialization.Model): + """Role Assignments. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The role assignment ID. + :vartype id: str + :ivar name: The role assignment name. + :vartype name: str + :ivar type: The role assignment type. + :vartype type: str + :param properties: Role assignment properties. + :type properties: ~azure.keyvault.v7_2.models.RoleAssignmentPropertiesWithScope + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': 'RoleAssignmentPropertiesWithScope'}, + } + + def __init__( + self, + **kwargs + ): + super(RoleAssignment, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.properties = kwargs.get('properties', None) + + +class RoleAssignmentCreateParameters(msrest.serialization.Model): + """Role assignment create parameters. + + All required parameters must be populated in order to send to Azure. + + :param properties: Required. Role assignment properties. + :type properties: ~azure.keyvault.v7_2.models.RoleAssignmentProperties + """ + + _validation = { + 'properties': {'required': True}, + } + + _attribute_map = { + 'properties': {'key': 'properties', 'type': 'RoleAssignmentProperties'}, + } + + def __init__( + self, + **kwargs + ): + super(RoleAssignmentCreateParameters, self).__init__(**kwargs) + self.properties = kwargs['properties'] + + +class RoleAssignmentFilter(msrest.serialization.Model): + """Role Assignments filter. + + :param principal_id: Returns role assignment of the specific principal. + :type principal_id: str + """ + + _attribute_map = { + 'principal_id': {'key': 'principalId', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(RoleAssignmentFilter, self).__init__(**kwargs) + self.principal_id = kwargs.get('principal_id', None) + + +class RoleAssignmentListResult(msrest.serialization.Model): + """Role assignment list operation result. + + :param value: Role assignment list. + :type value: list[~azure.keyvault.v7_2.models.RoleAssignment] + :param next_link: The URL to use for getting the next set of results. + :type next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[RoleAssignment]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(RoleAssignmentListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + self.next_link = kwargs.get('next_link', None) + + +class RoleAssignmentProperties(msrest.serialization.Model): + """Role assignment properties. + + All required parameters must be populated in order to send to Azure. + + :param role_definition_id: Required. The role definition ID used in the role assignment. + :type role_definition_id: str + :param principal_id: Required. The principal ID assigned to the role. This maps to the ID + inside the Active Directory. It can point to a user, service principal, or security group. + :type principal_id: str + """ + + _validation = { + 'role_definition_id': {'required': True}, + 'principal_id': {'required': True}, + } + + _attribute_map = { + 'role_definition_id': {'key': 'roleDefinitionId', 'type': 'str'}, + 'principal_id': {'key': 'principalId', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(RoleAssignmentProperties, self).__init__(**kwargs) + self.role_definition_id = kwargs['role_definition_id'] + self.principal_id = kwargs['principal_id'] + + +class RoleAssignmentPropertiesWithScope(msrest.serialization.Model): + """Role assignment properties with scope. + + :param scope: The role assignment scope. + :type scope: str + :param role_definition_id: The role definition ID. + :type role_definition_id: str + :param principal_id: The principal ID. + :type principal_id: str + """ + + _attribute_map = { + 'scope': {'key': 'scope', 'type': 'str'}, + 'role_definition_id': {'key': 'roleDefinitionId', 'type': 'str'}, + 'principal_id': {'key': 'principalId', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(RoleAssignmentPropertiesWithScope, self).__init__(**kwargs) + self.scope = kwargs.get('scope', None) + self.role_definition_id = kwargs.get('role_definition_id', None) + self.principal_id = kwargs.get('principal_id', None) + + +class RoleDefinition(msrest.serialization.Model): + """Role definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The role definition ID. + :vartype id: str + :ivar name: The role definition name. + :vartype name: str + :ivar type: The role definition type. + :vartype type: str + :param role_name: The role name. + :type role_name: str + :param description: The role definition description. + :type description: str + :param role_type: The role type. + :type role_type: str + :param permissions: Role definition permissions. + :type permissions: list[~azure.keyvault.v7_2.models.Permission] + :param assignable_scopes: Role definition assignable scopes. + :type assignable_scopes: list[str] + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'role_name': {'key': 'properties.roleName', 'type': 'str'}, + 'description': {'key': 'properties.description', 'type': 'str'}, + 'role_type': {'key': 'properties.type', 'type': 'str'}, + 'permissions': {'key': 'properties.permissions', 'type': '[Permission]'}, + 'assignable_scopes': {'key': 'properties.assignableScopes', 'type': '[str]'}, + } + + def __init__( + self, + **kwargs + ): + super(RoleDefinition, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.role_name = kwargs.get('role_name', None) + self.description = kwargs.get('description', None) + self.role_type = kwargs.get('role_type', None) + self.permissions = kwargs.get('permissions', None) + self.assignable_scopes = kwargs.get('assignable_scopes', None) + + +class RoleDefinitionFilter(msrest.serialization.Model): + """Role Definitions filter. + + :param role_name: Returns role definition with the specific name. + :type role_name: str + """ + + _attribute_map = { + 'role_name': {'key': 'roleName', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(RoleDefinitionFilter, self).__init__(**kwargs) + self.role_name = kwargs.get('role_name', None) + + +class RoleDefinitionListResult(msrest.serialization.Model): + """Role definition list operation result. + + :param value: Role definition list. + :type value: list[~azure.keyvault.v7_2.models.RoleDefinition] + :param next_link: The URL to use for getting the next set of results. + :type next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[RoleDefinition]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(RoleDefinitionListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + self.next_link = kwargs.get('next_link', None) + + +class SASTokenParameter(msrest.serialization.Model): + """SASTokenParameter. + + All required parameters must be populated in order to send to Azure. + + :param storage_resource_uri: Required. Azure Blob storage container Uri. + :type storage_resource_uri: str + :param token: Required. The SAS token pointing to an Azure Blob storage container. + :type token: str + """ + + _validation = { + 'storage_resource_uri': {'required': True}, + 'token': {'required': True}, + } + + _attribute_map = { + 'storage_resource_uri': {'key': 'storageResourceUri', 'type': 'str'}, + 'token': {'key': 'token', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(SASTokenParameter, self).__init__(**kwargs) + self.storage_resource_uri = kwargs['storage_resource_uri'] + self.token = kwargs['token'] + + +class SelectiveKeyRestoreOperation(msrest.serialization.Model): + """Selective Key Restore operation. + + :param status: Status of the restore operation. + :type status: str + :param status_details: The status details of restore operation. + :type status_details: str + :param error: Error encountered, if any, during the selective key restore operation. + :type error: ~azure.keyvault.v7_2.models.Error + :param job_id: Identifier for the selective key restore operation. + :type job_id: str + :param start_time: The start time of the restore operation. + :type start_time: ~datetime.datetime + :param end_time: The end time of the restore operation. + :type end_time: ~datetime.datetime + """ + + _attribute_map = { + 'status': {'key': 'status', 'type': 'str'}, + 'status_details': {'key': 'statusDetails', 'type': 'str'}, + 'error': {'key': 'error', 'type': 'Error'}, + 'job_id': {'key': 'jobId', 'type': 'str'}, + 'start_time': {'key': 'startTime', 'type': 'unix-time'}, + 'end_time': {'key': 'endTime', 'type': 'unix-time'}, + } + + def __init__( + self, + **kwargs + ): + super(SelectiveKeyRestoreOperation, self).__init__(**kwargs) + self.status = kwargs.get('status', None) + self.status_details = kwargs.get('status_details', None) + self.error = kwargs.get('error', None) + self.job_id = kwargs.get('job_id', None) + self.start_time = kwargs.get('start_time', None) + self.end_time = kwargs.get('end_time', None) + + +class SelectiveKeyRestoreOperationParameters(msrest.serialization.Model): + """SelectiveKeyRestoreOperationParameters. + + All required parameters must be populated in order to send to Azure. + + :param sas_token_parameters: Required. + :type sas_token_parameters: ~azure.keyvault.v7_2.models.SASTokenParameter + :param folder: Required. The Folder name of the blob where the previous successful full backup + was stored. + :type folder: str + """ + + _validation = { + 'sas_token_parameters': {'required': True}, + 'folder': {'required': True}, + } + + _attribute_map = { + 'sas_token_parameters': {'key': 'sasTokenParameters', 'type': 'SASTokenParameter'}, + 'folder': {'key': 'folder', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(SelectiveKeyRestoreOperationParameters, self).__init__(**kwargs) + self.sas_token_parameters = kwargs['sas_token_parameters'] + self.folder = kwargs['folder'] diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/models/_models_py3.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/models/_models_py3.py new file mode 100644 index 000000000000..dab1cd313c38 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/models/_models_py3.py @@ -0,0 +1,688 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import datetime +from typing import List, Optional + +from azure.core.exceptions import HttpResponseError +import msrest.serialization + + +class Attributes(msrest.serialization.Model): + """The object attributes managed by the KeyVault service. + + Variables are only populated by the server, and will be ignored when sending a request. + + :param enabled: Determines whether the object is enabled. + :type enabled: bool + :param not_before: Not before date in UTC. + :type not_before: ~datetime.datetime + :param expires: Expiry date in UTC. + :type expires: ~datetime.datetime + :ivar created: Creation time in UTC. + :vartype created: ~datetime.datetime + :ivar updated: Last updated time in UTC. + :vartype updated: ~datetime.datetime + """ + + _validation = { + 'created': {'readonly': True}, + 'updated': {'readonly': True}, + } + + _attribute_map = { + 'enabled': {'key': 'enabled', 'type': 'bool'}, + 'not_before': {'key': 'nbf', 'type': 'unix-time'}, + 'expires': {'key': 'exp', 'type': 'unix-time'}, + 'created': {'key': 'created', 'type': 'unix-time'}, + 'updated': {'key': 'updated', 'type': 'unix-time'}, + } + + def __init__( + self, + *, + enabled: Optional[bool] = None, + not_before: Optional[datetime.datetime] = None, + expires: Optional[datetime.datetime] = None, + **kwargs + ): + super(Attributes, self).__init__(**kwargs) + self.enabled = enabled + self.not_before = not_before + self.expires = expires + self.created = None + self.updated = None + + +class Error(msrest.serialization.Model): + """The key vault server error. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar inner_error: The key vault server error. + :vartype inner_error: ~azure.keyvault.v7_2.models.Error + """ + + _validation = { + 'code': {'readonly': True}, + 'message': {'readonly': True}, + 'inner_error': {'readonly': True}, + } + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + 'inner_error': {'key': 'innererror', 'type': 'Error'}, + } + + def __init__( + self, + **kwargs + ): + super(Error, self).__init__(**kwargs) + self.code = None + self.message = None + self.inner_error = None + + +class FullBackupOperation(msrest.serialization.Model): + """Full backup operation. + + :param status: Status of the backup operation. + :type status: str + :param status_details: The status details of backup operation. + :type status_details: str + :param error: Error encountered, if any, during the full backup operation. + :type error: ~azure.keyvault.v7_2.models.Error + :param start_time: The start time of the backup operation in UTC. + :type start_time: ~datetime.datetime + :param end_time: The end time of the backup operation in UTC. + :type end_time: ~datetime.datetime + :param job_id: Identifier for the full backup operation. + :type job_id: str + :param azure_storage_blob_container_uri: The Azure blob storage container Uri which contains + the full backup. + :type azure_storage_blob_container_uri: str + """ + + _attribute_map = { + 'status': {'key': 'status', 'type': 'str'}, + 'status_details': {'key': 'statusDetails', 'type': 'str'}, + 'error': {'key': 'error', 'type': 'Error'}, + 'start_time': {'key': 'startTime', 'type': 'unix-time'}, + 'end_time': {'key': 'endTime', 'type': 'unix-time'}, + 'job_id': {'key': 'jobId', 'type': 'str'}, + 'azure_storage_blob_container_uri': {'key': 'azureStorageBlobContainerUri', 'type': 'str'}, + } + + def __init__( + self, + *, + status: Optional[str] = None, + status_details: Optional[str] = None, + error: Optional["Error"] = None, + start_time: Optional[datetime.datetime] = None, + end_time: Optional[datetime.datetime] = None, + job_id: Optional[str] = None, + azure_storage_blob_container_uri: Optional[str] = None, + **kwargs + ): + super(FullBackupOperation, self).__init__(**kwargs) + self.status = status + self.status_details = status_details + self.error = error + self.start_time = start_time + self.end_time = end_time + self.job_id = job_id + self.azure_storage_blob_container_uri = azure_storage_blob_container_uri + + +class KeyVaultError(msrest.serialization.Model): + """The key vault error exception. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar error: The key vault server error. + :vartype error: ~azure.keyvault.v7_2.models.Error + """ + + _validation = { + 'error': {'readonly': True}, + } + + _attribute_map = { + 'error': {'key': 'error', 'type': 'Error'}, + } + + def __init__( + self, + **kwargs + ): + super(KeyVaultError, self).__init__(**kwargs) + self.error = None + + +class Permission(msrest.serialization.Model): + """Role definition permissions. + + :param actions: Allowed actions. + :type actions: list[str] + :param not_actions: Denied actions. + :type not_actions: list[str] + :param data_actions: Allowed Data actions. + :type data_actions: list[str] + :param not_data_actions: Denied Data actions. + :type not_data_actions: list[str] + """ + + _attribute_map = { + 'actions': {'key': 'actions', 'type': '[str]'}, + 'not_actions': {'key': 'notActions', 'type': '[str]'}, + 'data_actions': {'key': 'dataActions', 'type': '[str]'}, + 'not_data_actions': {'key': 'notDataActions', 'type': '[str]'}, + } + + def __init__( + self, + *, + actions: Optional[List[str]] = None, + not_actions: Optional[List[str]] = None, + data_actions: Optional[List[str]] = None, + not_data_actions: Optional[List[str]] = None, + **kwargs + ): + super(Permission, self).__init__(**kwargs) + self.actions = actions + self.not_actions = not_actions + self.data_actions = data_actions + self.not_data_actions = not_data_actions + + +class RestoreOperation(msrest.serialization.Model): + """Restore operation. + + :param status: Status of the restore operation. + :type status: str + :param status_details: The status details of restore operation. + :type status_details: str + :param error: Error encountered, if any, during the restore operation. + :type error: ~azure.keyvault.v7_2.models.Error + :param job_id: Identifier for the restore operation. + :type job_id: str + :param start_time: The start time of the restore operation. + :type start_time: ~datetime.datetime + :param end_time: The end time of the restore operation. + :type end_time: ~datetime.datetime + """ + + _attribute_map = { + 'status': {'key': 'status', 'type': 'str'}, + 'status_details': {'key': 'statusDetails', 'type': 'str'}, + 'error': {'key': 'error', 'type': 'Error'}, + 'job_id': {'key': 'jobId', 'type': 'str'}, + 'start_time': {'key': 'startTime', 'type': 'unix-time'}, + 'end_time': {'key': 'endTime', 'type': 'unix-time'}, + } + + def __init__( + self, + *, + status: Optional[str] = None, + status_details: Optional[str] = None, + error: Optional["Error"] = None, + job_id: Optional[str] = None, + start_time: Optional[datetime.datetime] = None, + end_time: Optional[datetime.datetime] = None, + **kwargs + ): + super(RestoreOperation, self).__init__(**kwargs) + self.status = status + self.status_details = status_details + self.error = error + self.job_id = job_id + self.start_time = start_time + self.end_time = end_time + + +class RestoreOperationParameters(msrest.serialization.Model): + """RestoreOperationParameters. + + All required parameters must be populated in order to send to Azure. + + :param sas_token_parameters: Required. + :type sas_token_parameters: ~azure.keyvault.v7_2.models.SASTokenParameter + :param folder_to_restore: Required. The Folder name of the blob where the previous successful + full backup was stored. + :type folder_to_restore: str + """ + + _validation = { + 'sas_token_parameters': {'required': True}, + 'folder_to_restore': {'required': True}, + } + + _attribute_map = { + 'sas_token_parameters': {'key': 'sasTokenParameters', 'type': 'SASTokenParameter'}, + 'folder_to_restore': {'key': 'folderToRestore', 'type': 'str'}, + } + + def __init__( + self, + *, + sas_token_parameters: "SASTokenParameter", + folder_to_restore: str, + **kwargs + ): + super(RestoreOperationParameters, self).__init__(**kwargs) + self.sas_token_parameters = sas_token_parameters + self.folder_to_restore = folder_to_restore + + +class RoleAssignment(msrest.serialization.Model): + """Role Assignments. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The role assignment ID. + :vartype id: str + :ivar name: The role assignment name. + :vartype name: str + :ivar type: The role assignment type. + :vartype type: str + :param properties: Role assignment properties. + :type properties: ~azure.keyvault.v7_2.models.RoleAssignmentPropertiesWithScope + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'properties': {'key': 'properties', 'type': 'RoleAssignmentPropertiesWithScope'}, + } + + def __init__( + self, + *, + properties: Optional["RoleAssignmentPropertiesWithScope"] = None, + **kwargs + ): + super(RoleAssignment, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.properties = properties + + +class RoleAssignmentCreateParameters(msrest.serialization.Model): + """Role assignment create parameters. + + All required parameters must be populated in order to send to Azure. + + :param properties: Required. Role assignment properties. + :type properties: ~azure.keyvault.v7_2.models.RoleAssignmentProperties + """ + + _validation = { + 'properties': {'required': True}, + } + + _attribute_map = { + 'properties': {'key': 'properties', 'type': 'RoleAssignmentProperties'}, + } + + def __init__( + self, + *, + properties: "RoleAssignmentProperties", + **kwargs + ): + super(RoleAssignmentCreateParameters, self).__init__(**kwargs) + self.properties = properties + + +class RoleAssignmentFilter(msrest.serialization.Model): + """Role Assignments filter. + + :param principal_id: Returns role assignment of the specific principal. + :type principal_id: str + """ + + _attribute_map = { + 'principal_id': {'key': 'principalId', 'type': 'str'}, + } + + def __init__( + self, + *, + principal_id: Optional[str] = None, + **kwargs + ): + super(RoleAssignmentFilter, self).__init__(**kwargs) + self.principal_id = principal_id + + +class RoleAssignmentListResult(msrest.serialization.Model): + """Role assignment list operation result. + + :param value: Role assignment list. + :type value: list[~azure.keyvault.v7_2.models.RoleAssignment] + :param next_link: The URL to use for getting the next set of results. + :type next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[RoleAssignment]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[List["RoleAssignment"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + super(RoleAssignmentListResult, self).__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class RoleAssignmentProperties(msrest.serialization.Model): + """Role assignment properties. + + All required parameters must be populated in order to send to Azure. + + :param role_definition_id: Required. The role definition ID used in the role assignment. + :type role_definition_id: str + :param principal_id: Required. The principal ID assigned to the role. This maps to the ID + inside the Active Directory. It can point to a user, service principal, or security group. + :type principal_id: str + """ + + _validation = { + 'role_definition_id': {'required': True}, + 'principal_id': {'required': True}, + } + + _attribute_map = { + 'role_definition_id': {'key': 'roleDefinitionId', 'type': 'str'}, + 'principal_id': {'key': 'principalId', 'type': 'str'}, + } + + def __init__( + self, + *, + role_definition_id: str, + principal_id: str, + **kwargs + ): + super(RoleAssignmentProperties, self).__init__(**kwargs) + self.role_definition_id = role_definition_id + self.principal_id = principal_id + + +class RoleAssignmentPropertiesWithScope(msrest.serialization.Model): + """Role assignment properties with scope. + + :param scope: The role assignment scope. + :type scope: str + :param role_definition_id: The role definition ID. + :type role_definition_id: str + :param principal_id: The principal ID. + :type principal_id: str + """ + + _attribute_map = { + 'scope': {'key': 'scope', 'type': 'str'}, + 'role_definition_id': {'key': 'roleDefinitionId', 'type': 'str'}, + 'principal_id': {'key': 'principalId', 'type': 'str'}, + } + + def __init__( + self, + *, + scope: Optional[str] = None, + role_definition_id: Optional[str] = None, + principal_id: Optional[str] = None, + **kwargs + ): + super(RoleAssignmentPropertiesWithScope, self).__init__(**kwargs) + self.scope = scope + self.role_definition_id = role_definition_id + self.principal_id = principal_id + + +class RoleDefinition(msrest.serialization.Model): + """Role definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: The role definition ID. + :vartype id: str + :ivar name: The role definition name. + :vartype name: str + :ivar type: The role definition type. + :vartype type: str + :param role_name: The role name. + :type role_name: str + :param description: The role definition description. + :type description: str + :param role_type: The role type. + :type role_type: str + :param permissions: Role definition permissions. + :type permissions: list[~azure.keyvault.v7_2.models.Permission] + :param assignable_scopes: Role definition assignable scopes. + :type assignable_scopes: list[str] + """ + + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + + _attribute_map = { + 'id': {'key': 'id', 'type': 'str'}, + 'name': {'key': 'name', 'type': 'str'}, + 'type': {'key': 'type', 'type': 'str'}, + 'role_name': {'key': 'properties.roleName', 'type': 'str'}, + 'description': {'key': 'properties.description', 'type': 'str'}, + 'role_type': {'key': 'properties.type', 'type': 'str'}, + 'permissions': {'key': 'properties.permissions', 'type': '[Permission]'}, + 'assignable_scopes': {'key': 'properties.assignableScopes', 'type': '[str]'}, + } + + def __init__( + self, + *, + role_name: Optional[str] = None, + description: Optional[str] = None, + role_type: Optional[str] = None, + permissions: Optional[List["Permission"]] = None, + assignable_scopes: Optional[List[str]] = None, + **kwargs + ): + super(RoleDefinition, self).__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.role_name = role_name + self.description = description + self.role_type = role_type + self.permissions = permissions + self.assignable_scopes = assignable_scopes + + +class RoleDefinitionFilter(msrest.serialization.Model): + """Role Definitions filter. + + :param role_name: Returns role definition with the specific name. + :type role_name: str + """ + + _attribute_map = { + 'role_name': {'key': 'roleName', 'type': 'str'}, + } + + def __init__( + self, + *, + role_name: Optional[str] = None, + **kwargs + ): + super(RoleDefinitionFilter, self).__init__(**kwargs) + self.role_name = role_name + + +class RoleDefinitionListResult(msrest.serialization.Model): + """Role definition list operation result. + + :param value: Role definition list. + :type value: list[~azure.keyvault.v7_2.models.RoleDefinition] + :param next_link: The URL to use for getting the next set of results. + :type next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[RoleDefinition]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__( + self, + *, + value: Optional[List["RoleDefinition"]] = None, + next_link: Optional[str] = None, + **kwargs + ): + super(RoleDefinitionListResult, self).__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class SASTokenParameter(msrest.serialization.Model): + """SASTokenParameter. + + All required parameters must be populated in order to send to Azure. + + :param storage_resource_uri: Required. Azure Blob storage container Uri. + :type storage_resource_uri: str + :param token: Required. The SAS token pointing to an Azure Blob storage container. + :type token: str + """ + + _validation = { + 'storage_resource_uri': {'required': True}, + 'token': {'required': True}, + } + + _attribute_map = { + 'storage_resource_uri': {'key': 'storageResourceUri', 'type': 'str'}, + 'token': {'key': 'token', 'type': 'str'}, + } + + def __init__( + self, + *, + storage_resource_uri: str, + token: str, + **kwargs + ): + super(SASTokenParameter, self).__init__(**kwargs) + self.storage_resource_uri = storage_resource_uri + self.token = token + + +class SelectiveKeyRestoreOperation(msrest.serialization.Model): + """Selective Key Restore operation. + + :param status: Status of the restore operation. + :type status: str + :param status_details: The status details of restore operation. + :type status_details: str + :param error: Error encountered, if any, during the selective key restore operation. + :type error: ~azure.keyvault.v7_2.models.Error + :param job_id: Identifier for the selective key restore operation. + :type job_id: str + :param start_time: The start time of the restore operation. + :type start_time: ~datetime.datetime + :param end_time: The end time of the restore operation. + :type end_time: ~datetime.datetime + """ + + _attribute_map = { + 'status': {'key': 'status', 'type': 'str'}, + 'status_details': {'key': 'statusDetails', 'type': 'str'}, + 'error': {'key': 'error', 'type': 'Error'}, + 'job_id': {'key': 'jobId', 'type': 'str'}, + 'start_time': {'key': 'startTime', 'type': 'unix-time'}, + 'end_time': {'key': 'endTime', 'type': 'unix-time'}, + } + + def __init__( + self, + *, + status: Optional[str] = None, + status_details: Optional[str] = None, + error: Optional["Error"] = None, + job_id: Optional[str] = None, + start_time: Optional[datetime.datetime] = None, + end_time: Optional[datetime.datetime] = None, + **kwargs + ): + super(SelectiveKeyRestoreOperation, self).__init__(**kwargs) + self.status = status + self.status_details = status_details + self.error = error + self.job_id = job_id + self.start_time = start_time + self.end_time = end_time + + +class SelectiveKeyRestoreOperationParameters(msrest.serialization.Model): + """SelectiveKeyRestoreOperationParameters. + + All required parameters must be populated in order to send to Azure. + + :param sas_token_parameters: Required. + :type sas_token_parameters: ~azure.keyvault.v7_2.models.SASTokenParameter + :param folder: Required. The Folder name of the blob where the previous successful full backup + was stored. + :type folder: str + """ + + _validation = { + 'sas_token_parameters': {'required': True}, + 'folder': {'required': True}, + } + + _attribute_map = { + 'sas_token_parameters': {'key': 'sasTokenParameters', 'type': 'SASTokenParameter'}, + 'folder': {'key': 'folder', 'type': 'str'}, + } + + def __init__( + self, + *, + sas_token_parameters: "SASTokenParameter", + folder: str, + **kwargs + ): + super(SelectiveKeyRestoreOperationParameters, self).__init__(**kwargs) + self.sas_token_parameters = sas_token_parameters + self.folder = folder diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/operations/__init__.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/operations/__init__.py new file mode 100644 index 000000000000..fbdd39654293 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/operations/__init__.py @@ -0,0 +1,17 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._key_vault_client_operations import KeyVaultClientOperationsMixin +from ._role_definitions_operations import RoleDefinitionsOperations +from ._role_assignments_operations import RoleAssignmentsOperations + +__all__ = [ + 'KeyVaultClientOperationsMixin', + 'RoleDefinitionsOperations', + 'RoleAssignmentsOperations', +] diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/operations/_key_vault_client_operations.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/operations/_key_vault_client_operations.py new file mode 100644 index 000000000000..3c12ff62a347 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/operations/_key_vault_client_operations.py @@ -0,0 +1,516 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.polling.base_polling import LROBasePolling + +from .. import models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class KeyVaultClientOperationsMixin(object): + + def _full_backup_initial( + self, + vault_base_url, # type: str + azure_storage_blob_container_uri=None, # type: Optional["models.SASTokenParameter"] + **kwargs # type: Any + ): + # type: (...) -> "models.FullBackupOperation" + cls = kwargs.pop('cls', None) # type: ClsType["models.FullBackupOperation"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + api_version = "7.2-preview" + content_type = kwargs.pop("content_type", "application/json") + + # Construct URL + url = self._full_backup_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = 'application/json' + + body_content_kwargs = {} # type: Dict[str, Any] + if azure_storage_blob_container_uri is not None: + body_content = self._serialize.body(azure_storage_blob_container_uri, 'SASTokenParameter') + else: + body_content = None + body_content_kwargs['content'] = body_content + request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize(models.KeyVaultError, response) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers['Azure-AsyncOperation']=self._deserialize('str', response.headers.get('Azure-AsyncOperation')) + deserialized = self._deserialize('FullBackupOperation', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + _full_backup_initial.metadata = {'url': '/backup'} # type: ignore + + def begin_full_backup( + self, + vault_base_url, # type: str + azure_storage_blob_container_uri=None, # type: Optional["models.SASTokenParameter"] + **kwargs # type: Any + ): + # type: (...) -> LROPoller["models.FullBackupOperation"] + """Creates a full backup using a user-provided SAS token to an Azure blob storage container. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param azure_storage_blob_container_uri: Azure blob shared access signature token pointing to a + valid Azure blob container where full backup needs to be stored. This token needs to be valid + for at least next 24 hours from the time of making this call. + :type azure_storage_blob_container_uri: ~azure.keyvault.v7_2.models.SASTokenParameter + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: True for ARMPolling, False for no polling, or a + polling object for personal polling strategy + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either FullBackupOperation or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.keyvault.v7_2.models.FullBackupOperation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', False) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["models.FullBackupOperation"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._full_backup_initial( + vault_base_url=vault_base_url, + azure_storage_blob_container_uri=azure_storage_blob_container_uri, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + response_headers = {} + response = pipeline_response.http_response + response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers['Azure-AsyncOperation']=self._deserialize('str', response.headers.get('Azure-AsyncOperation')) + deserialized = self._deserialize('FullBackupOperation', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + return deserialized + + if polling is True: polling_method = LROBasePolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_full_backup.metadata = {'url': '/backup'} # type: ignore + + def full_backup_status( + self, + vault_base_url, # type: str + job_id, # type: str + **kwargs # type: Any + ): + # type: (...) -> "models.FullBackupOperation" + """Returns the status of full backup operation. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param job_id: The id returned as part of the backup request. + :type job_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: FullBackupOperation, or the result of cls(response) + :rtype: ~azure.keyvault.v7_2.models.FullBackupOperation + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["models.FullBackupOperation"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + api_version = "7.2-preview" + + # Construct URL + url = self.full_backup_status.metadata['url'] # type: ignore + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + 'jobId': self._serialize.url("job_id", job_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = 'application/json' + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize(models.KeyVaultError, response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize('FullBackupOperation', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + full_backup_status.metadata = {'url': '/backup/{jobId}/pending'} # type: ignore + + def _full_restore_operation_initial( + self, + vault_base_url, # type: str + restore_blob_details=None, # type: Optional["models.RestoreOperationParameters"] + **kwargs # type: Any + ): + # type: (...) -> "models.RestoreOperation" + cls = kwargs.pop('cls', None) # type: ClsType["models.RestoreOperation"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + api_version = "7.2-preview" + content_type = kwargs.pop("content_type", "application/json") + + # Construct URL + url = self._full_restore_operation_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = 'application/json' + + body_content_kwargs = {} # type: Dict[str, Any] + if restore_blob_details is not None: + body_content = self._serialize.body(restore_blob_details, 'RestoreOperationParameters') + else: + body_content = None + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize(models.KeyVaultError, response) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers['Azure-AsyncOperation']=self._deserialize('str', response.headers.get('Azure-AsyncOperation')) + deserialized = self._deserialize('RestoreOperation', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + _full_restore_operation_initial.metadata = {'url': '/restore'} # type: ignore + + def begin_full_restore_operation( + self, + vault_base_url, # type: str + restore_blob_details=None, # type: Optional["models.RestoreOperationParameters"] + **kwargs # type: Any + ): + # type: (...) -> LROPoller["models.RestoreOperation"] + """Restores all key materials using the SAS token pointing to a previously stored Azure Blob + storage backup folder. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param restore_blob_details: The Azure blob SAS token pointing to a folder where the previous + successful full backup was stored. + :type restore_blob_details: ~azure.keyvault.v7_2.models.RestoreOperationParameters + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: True for ARMPolling, False for no polling, or a + polling object for personal polling strategy + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either RestoreOperation or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.keyvault.v7_2.models.RestoreOperation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', False) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["models.RestoreOperation"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._full_restore_operation_initial( + vault_base_url=vault_base_url, + restore_blob_details=restore_blob_details, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + response_headers = {} + response = pipeline_response.http_response + response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers['Azure-AsyncOperation']=self._deserialize('str', response.headers.get('Azure-AsyncOperation')) + deserialized = self._deserialize('RestoreOperation', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + return deserialized + + if polling is True: polling_method = LROBasePolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_full_restore_operation.metadata = {'url': '/restore'} # type: ignore + + def restore_status( + self, + vault_base_url, # type: str + job_id, # type: str + **kwargs # type: Any + ): + # type: (...) -> "models.RestoreOperation" + """Returns the status of restore operation. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param job_id: The Job Id returned part of the restore operation. + :type job_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RestoreOperation, or the result of cls(response) + :rtype: ~azure.keyvault.v7_2.models.RestoreOperation + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["models.RestoreOperation"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + api_version = "7.2-preview" + + # Construct URL + url = self.restore_status.metadata['url'] # type: ignore + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + 'jobId': self._serialize.url("job_id", job_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = 'application/json' + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize(models.KeyVaultError, response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize('RestoreOperation', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + restore_status.metadata = {'url': '/restore/{jobId}/pending'} # type: ignore + + def _selective_key_restore_operation_initial( + self, + vault_base_url, # type: str + key_name, # type: str + restore_blob_details=None, # type: Optional["models.SelectiveKeyRestoreOperationParameters"] + **kwargs # type: Any + ): + # type: (...) -> "models.SelectiveKeyRestoreOperation" + cls = kwargs.pop('cls', None) # type: ClsType["models.SelectiveKeyRestoreOperation"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + api_version = "7.2-preview" + content_type = kwargs.pop("content_type", "application/json") + + # Construct URL + url = self._selective_key_restore_operation_initial.metadata['url'] # type: ignore + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + 'keyName': self._serialize.url("key_name", key_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = 'application/json' + + body_content_kwargs = {} # type: Dict[str, Any] + if restore_blob_details is not None: + body_content = self._serialize.body(restore_blob_details, 'SelectiveKeyRestoreOperationParameters') + else: + body_content = None + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize(models.KeyVaultError, response) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers['Azure-AsyncOperation']=self._deserialize('str', response.headers.get('Azure-AsyncOperation')) + deserialized = self._deserialize('SelectiveKeyRestoreOperation', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + _selective_key_restore_operation_initial.metadata = {'url': '/keys/{keyName}/restore'} # type: ignore + + def begin_selective_key_restore_operation( + self, + vault_base_url, # type: str + key_name, # type: str + restore_blob_details=None, # type: Optional["models.SelectiveKeyRestoreOperationParameters"] + **kwargs # type: Any + ): + # type: (...) -> LROPoller["models.SelectiveKeyRestoreOperation"] + """Restores all key versions of a given key using user supplied SAS token pointing to a previously + stored Azure Blob storage backup folder. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param key_name: The name of the key to be restored from the user supplied backup. + :type key_name: str + :param restore_blob_details: The Azure blob SAS token pointing to a folder where the previous + successful full backup was stored. + :type restore_blob_details: ~azure.keyvault.v7_2.models.SelectiveKeyRestoreOperationParameters + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: True for ARMPolling, False for no polling, or a + polling object for personal polling strategy + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :return: An instance of LROPoller that returns either SelectiveKeyRestoreOperation or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.keyvault.v7_2.models.SelectiveKeyRestoreOperation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + polling = kwargs.pop('polling', False) # type: Union[bool, PollingMethod] + cls = kwargs.pop('cls', None) # type: ClsType["models.SelectiveKeyRestoreOperation"] + lro_delay = kwargs.pop( + 'polling_interval', + self._config.polling_interval + ) + cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + if cont_token is None: + raw_result = self._selective_key_restore_operation_initial( + vault_base_url=vault_base_url, + key_name=key_name, + restore_blob_details=restore_blob_details, + cls=lambda x,y,z: x, + **kwargs + ) + + kwargs.pop('error_map', None) + kwargs.pop('content_type', None) + + def get_long_running_output(pipeline_response): + response_headers = {} + response = pipeline_response.http_response + response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers['Azure-AsyncOperation']=self._deserialize('str', response.headers.get('Azure-AsyncOperation')) + deserialized = self._deserialize('SelectiveKeyRestoreOperation', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + return deserialized + + if polling is True: polling_method = LROBasePolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs) + elif polling is False: polling_method = NoPolling() + else: polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output + ) + else: + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_selective_key_restore_operation.metadata = {'url': '/keys/{keyName}/restore'} # type: ignore diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/operations/_role_assignments_operations.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/operations/_role_assignments_operations.py new file mode 100644 index 000000000000..eb04fd51c698 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/operations/_role_assignments_operations.py @@ -0,0 +1,319 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse + +from .. import models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class RoleAssignmentsOperations(object): + """RoleAssignmentsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.keyvault.v7_2.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def delete( + self, + vault_base_url, # type: str + scope, # type: str + role_assignment_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "models.RoleAssignment" + """Deletes a role assignment. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param scope: The scope of the role assignment to delete. + :type scope: str + :param role_assignment_name: The name of the role assignment to delete. + :type role_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment, or the result of cls(response) + :rtype: ~azure.keyvault.v7_2.models.RoleAssignment + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["models.RoleAssignment"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + api_version = "7.2-preview" + + # Construct URL + url = self.delete.metadata['url'] # type: ignore + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = 'application/json' + + request = self._client.delete(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize(models.KeyVaultError, response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize('RoleAssignment', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + delete.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + + def create( + self, + vault_base_url, # type: str + scope, # type: str + role_assignment_name, # type: str + parameters, # type: "models.RoleAssignmentCreateParameters" + **kwargs # type: Any + ): + # type: (...) -> "models.RoleAssignment" + """Creates a role assignment. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param scope: The scope of the role assignment to create. + :type scope: str + :param role_assignment_name: The name of the role assignment to create. It can be any valid + GUID. + :type role_assignment_name: str + :param parameters: Parameters for the role assignment. + :type parameters: ~azure.keyvault.v7_2.models.RoleAssignmentCreateParameters + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment, or the result of cls(response) + :rtype: ~azure.keyvault.v7_2.models.RoleAssignment + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["models.RoleAssignment"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + api_version = "7.2-preview" + content_type = kwargs.pop("content_type", "application/json") + + # Construct URL + url = self.create.metadata['url'] # type: ignore + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = 'application/json' + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(parameters, 'RoleAssignmentCreateParameters') + body_content_kwargs['content'] = body_content + request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize(models.KeyVaultError, response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize('RoleAssignment', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + create.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + + def get( + self, + vault_base_url, # type: str + scope, # type: str + role_assignment_name, # type: str + **kwargs # type: Any + ): + # type: (...) -> "models.RoleAssignment" + """Get the specified role assignment. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param scope: The scope of the role assignment. + :type scope: str + :param role_assignment_name: The name of the role assignment to get. + :type role_assignment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: RoleAssignment, or the result of cls(response) + :rtype: ~azure.keyvault.v7_2.models.RoleAssignment + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["models.RoleAssignment"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + api_version = "7.2-preview" + + # Construct URL + url = self.get.metadata['url'] # type: ignore + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + 'roleAssignmentName': self._serialize.url("role_assignment_name", role_assignment_name, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = 'application/json' + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize(models.KeyVaultError, response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize('RoleAssignment', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + get.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}'} # type: ignore + + def list_for_scope( + self, + vault_base_url, # type: str + scope, # type: str + filter=None, # type: Optional[str] + **kwargs # type: Any + ): + # type: (...) -> Iterable["models.RoleAssignmentListResult"] + """Gets role assignments for a scope. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param scope: The scope of the role assignments. + :type scope: str + :param filter: The filter to apply on the operation. Use $filter=atScope() to return all role + assignments at or above the scope. Use $filter=principalId eq {id} to return all role + assignments at, above or below the scope for the specified principal. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleAssignmentListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.keyvault.v7_2.models.RoleAssignmentListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["models.RoleAssignmentListResult"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + api_version = "7.2-preview" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = 'application/json' + + if not next_link: + # Construct URL + url = self.list_for_scope.metadata['url'] # type: ignore + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + if filter is not None: + query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + } + url = self._client.format_url(url, **path_format_arguments) + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('RoleAssignmentListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize(models.KeyVaultError, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list_for_scope.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleAssignments'} # type: ignore diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/operations/_role_definitions_operations.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/operations/_role_definitions_operations.py new file mode 100644 index 000000000000..ba3d7a757dc5 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/operations/_role_definitions_operations.py @@ -0,0 +1,128 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse + +from .. import models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class RoleDefinitionsOperations(object): + """RoleDefinitionsOperations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.keyvault.v7_2.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + vault_base_url, # type: str + scope, # type: str + filter=None, # type: Optional[str] + **kwargs # type: Any + ): + # type: (...) -> Iterable["models.RoleDefinitionListResult"] + """Get all role definitions that are applicable at scope and above. + + :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. + :type vault_base_url: str + :param scope: The scope of the role definition. + :type scope: str + :param filter: The filter to apply on the operation. Use atScopeAndBelow filter to search below + the given scope as well. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either RoleDefinitionListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.keyvault.v7_2.models.RoleDefinitionListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["models.RoleDefinitionListResult"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + api_version = "7.2-preview" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = 'application/json' + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + } + url = self._client.format_url(url, **path_format_arguments) + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + if filter is not None: + query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + path_format_arguments = { + 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), + 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + } + url = self._client.format_url(url, **path_format_arguments) + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('RoleDefinitionListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + error = self._deserialize(models.KeyVaultError, response) + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/{scope}/providers/Microsoft.Authorization/roleDefinitions'} # type: ignore diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/py.typed b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_generated/v7_2_preview/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file From 0ec0acb55d5e26b903a2eb8696b1924ba2704a74 Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Tue, 16 Jun 2020 15:47:54 -0700 Subject: [PATCH 3/5] copy shared code --- .../administration/_internal/__init__.py | 57 +++++++ .../administration/_internal/_polling.py | 135 +++++++++++++++++ .../_internal/_polling_async.py | 72 +++++++++ .../_internal/async_challenge_auth_policy.py | 79 ++++++++++ .../_internal/async_client_base.py | 81 ++++++++++ .../_internal/challenge_auth_policy.py | 140 ++++++++++++++++++ .../administration/_internal/client_base.py | 106 +++++++++++++ .../administration/_internal/exceptions.py | 57 +++++++ .../_internal/http_challenge.py | 114 ++++++++++++++ .../_internal/http_challenge_cache.py | 89 +++++++++++ .../administration/_internal/multi_api.py | 73 +++++++++ .../tests/_shared/__init__.py | 4 + .../tests/_shared/helpers.py | 102 +++++++++++++ .../tests/_shared/helpers_async.py | 49 ++++++ .../tests/_shared/json_attribute_matcher.py | 18 +++ .../tests/_shared/preparer.py | 29 ++++ .../tests/_shared/preparer_async.py | 19 +++ .../tests/_shared/test_case.py | 46 ++++++ .../tests/_shared/test_case_async.py | 54 +++++++ 19 files changed, 1324 insertions(+) create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/__init__.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/_polling.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/_polling_async.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/async_challenge_auth_policy.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/async_client_base.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/challenge_auth_policy.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/client_base.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/exceptions.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/http_challenge.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/http_challenge_cache.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/multi_api.py create mode 100644 sdk/keyvault/azure-keyvault-administration/tests/_shared/__init__.py create mode 100644 sdk/keyvault/azure-keyvault-administration/tests/_shared/helpers.py create mode 100644 sdk/keyvault/azure-keyvault-administration/tests/_shared/helpers_async.py create mode 100644 sdk/keyvault/azure-keyvault-administration/tests/_shared/json_attribute_matcher.py create mode 100644 sdk/keyvault/azure-keyvault-administration/tests/_shared/preparer.py create mode 100644 sdk/keyvault/azure-keyvault-administration/tests/_shared/preparer_async.py create mode 100644 sdk/keyvault/azure-keyvault-administration/tests/_shared/test_case.py create mode 100644 sdk/keyvault/azure-keyvault-administration/tests/_shared/test_case_async.py diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/__init__.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/__init__.py new file mode 100644 index 000000000000..a8fd2a41d71f --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/__init__.py @@ -0,0 +1,57 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from collections import namedtuple + +try: + import urllib.parse as parse +except ImportError: + # pylint:disable=import-error + import urlparse as parse # type: ignore + +from .challenge_auth_policy import ChallengeAuthPolicy, ChallengeAuthPolicyBase +from .client_base import KeyVaultClientBase +from .http_challenge import HttpChallenge +from . import http_challenge_cache as HttpChallengeCache + +__all__ = [ + "ChallengeAuthPolicy", + "ChallengeAuthPolicyBase", + "HttpChallenge", + "HttpChallengeCache", + "KeyVaultClientBase", +] + +_VaultId = namedtuple("VaultId", ["vault_url", "collection", "name", "version"]) + + +def parse_vault_id(url): + try: + parsed_uri = parse.urlparse(url) + except Exception: # pylint: disable=broad-except + raise ValueError("'{}' is not not a valid url".format(url)) + if not (parsed_uri.scheme and parsed_uri.hostname): + raise ValueError("'{}' is not not a valid url".format(url)) + + path = list(filter(None, parsed_uri.path.split("/"))) + + if len(path) < 2 or len(path) > 3: + raise ValueError("'{}' is not not a valid vault url".format(url)) + + return _VaultId( + vault_url="{}://{}".format(parsed_uri.scheme, parsed_uri.hostname), + collection=path[0], + name=path[1], + version=path[2] if len(path) == 3 else None, + ) + + +try: + # pylint:disable=unused-import + from .async_challenge_auth_policy import AsyncChallengeAuthPolicy + from .async_client_base import AsyncKeyVaultClientBase + + __all__.extend(["AsyncChallengeAuthPolicy", "AsyncKeyVaultClientBase"]) +except (SyntaxError, ImportError): + pass diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/_polling.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/_polling.py new file mode 100644 index 000000000000..df63ad0a70ec --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/_polling.py @@ -0,0 +1,135 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +import time +import threading +import uuid +from typing import TYPE_CHECKING + +from azure.core.polling import PollingMethod, LROPoller, NoPolling +from azure.core.exceptions import ResourceNotFoundError, HttpResponseError + +try: + from urlparse import urlparse # type: ignore # pylint: disable=unused-import +except ImportError: + from urllib.parse import urlparse + +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.common import with_current_context + +if TYPE_CHECKING: + # pylint: disable=ungrouped-imports + from typing import Any, Callable, Union, List, Optional + +logger = logging.getLogger(__name__) + + +class KeyVaultOperationPoller(LROPoller): + """Poller for long running operations where calling result() doesn't wait for operation to complete. + """ + + # pylint: disable=arguments-differ + def __init__(self, polling_method): + # type: (PollingMethod) -> None + super(KeyVaultOperationPoller, self).__init__(None, None, None, NoPolling()) + self._polling_method = polling_method + + # pylint: disable=arguments-differ + def result(self): + # type: () -> Any + """Returns a representation of the final resource without waiting for the operation to complete. + + :returns: The deserialized resource of the long running operation + :raises ~azure.core.exceptions.HttpResponseError: Server problem with the query. + """ + return self._polling_method.resource() + + @distributed_trace + def wait(self, timeout=None): + # type: (Optional[int]) -> None + """Wait on the long running operation for a number of seconds. + + You can check if this call has ended with timeout with the "done()" method. + + :param int timeout: Period of time to wait for the long running + operation to complete (in seconds). + :raises ~azure.core.exceptions.HttpResponseError: Server problem with the query. + """ + + if not self._polling_method.finished(): + self._done = threading.Event() + self._thread = threading.Thread( + target=with_current_context(self._start), name="KeyVaultOperationPoller({})".format(uuid.uuid4()) + ) + self._thread.daemon = True + self._thread.start() + + if self._thread is None: + return + self._thread.join(timeout=timeout) + try: + # Let's handle possible None in forgiveness here + raise self._exception # type: ignore + except TypeError: # Was None + pass + + +class DeleteRecoverPollingMethod(PollingMethod): + """Poller for deleting resources, and recovering deleted resources, in vaults with soft-delete enabled. + + This works by polling for the existence of the deleted or recovered resource. When a resource is deleted, Key Vault + immediately removes it from its collection. However, the resource will not immediately appear in the deleted + collection. Key Vault will therefore respond 404 to GET requests for the deleted resource; when it responds 2xx, + the resource exists in the deleted collection i.e. its deletion is complete. + + Similarly, while recovering a deleted resource, Key Vault will respond 404 to GET requests for the non-deleted + resource; when it responds 2xx, the resource exists in the non-deleted collection, i.e. its recovery is complete. + """ + def __init__(self, command, final_resource, finished, interval=2): + self._command = command + self._resource = final_resource + self._polling_interval = interval + self._finished = finished + + def _update_status(self): + # type: () -> None + try: + self._command() + self._finished = True + except ResourceNotFoundError: + pass + except HttpResponseError as e: + # If we are polling on get_deleted_* and we don't have get permissions, we will get + # ResourceNotFoundError until the resource is recovered, at which point we'll get a 403. + if e.status_code == 403: + self._finished = True + else: + raise + + def initialize(self, client, initial_response, deserialization_callback): + pass + + def run(self): + # type: () -> None + try: + while not self.finished(): + self._update_status() + if not self.finished(): + time.sleep(self._polling_interval) + except Exception as e: + logger.warning(str(e)) + raise + + def finished(self): + # type: () -> bool + return self._finished + + def resource(self): + # type: () -> Any + return self._resource + + def status(self): + # type: () -> str + return "finished" if self._finished else "polling" diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/_polling_async.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/_polling_async.py new file mode 100644 index 000000000000..d3fc83105927 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/_polling_async.py @@ -0,0 +1,72 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +import asyncio +import logging +from typing import TYPE_CHECKING + +from azure.core.polling import AsyncPollingMethod +from azure.core.exceptions import ResourceNotFoundError, HttpResponseError + +if TYPE_CHECKING: + # pylint:disable=ungrouped-imports + from typing import Any, Callable, Union + +logger = logging.getLogger(__name__) + + +class AsyncDeleteRecoverPollingMethod(AsyncPollingMethod): + """Poller for deleting resources, and recovering deleted resources, in vaults with soft-delete enabled. + + This works by polling for the existence of the deleted or recovered resource. When a resource is deleted, Key Vault + immediately removes it from its collection. However, the resource will not immediately appear in the deleted + collection. Key Vault will therefore respond 404 to GET requests for the deleted resource; when it responds 2xx, + the resource exists in the deleted collection i.e. its deletion is complete. + + Similarly, while recovering a deleted resource, Key Vault will respond 404 to GET requests for the non-deleted + resource; when it responds 2xx, the resource exists in the non-deleted collection, i.e. its recovery is complete. + """ + + def __init__(self, command, final_resource, finished, interval=2): + self._command = command + self._resource = final_resource + self._polling_interval = interval + self._finished = finished + + def initialize(self, client, initial_response, deserialization_callback): + pass + + async def _update_status(self) -> None: + try: + await self._command() + self._finished = True + except ResourceNotFoundError: + pass + except HttpResponseError as e: + # If we are polling on get_deleted_* and we don't have get permissions, we will get + # ResourceNotFoundError until the resource is recovered, at which point we'll get a 403. + if e.status_code == 403: + self._finished = True + else: + raise + + async def run(self) -> None: + try: + while not self.finished(): + await self._update_status() + if not self.finished(): + await asyncio.sleep(self._polling_interval) + except Exception as e: + logger.warning(str(e)) + raise + + def finished(self) -> bool: + return self._finished + + def resource(self) -> "Any": + return self._resource + + def status(self) -> str: + return "finished" if self._finished else "polling" diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/async_challenge_auth_policy.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/async_challenge_auth_policy.py new file mode 100644 index 000000000000..97f1d093e20f --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/async_challenge_auth_policy.py @@ -0,0 +1,79 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Policy implementing Key Vault's challenge authentication protocol. + +Normally the protocol is only used for the client's first service request, upon which: +1. The challenge authentication policy sends a copy of the request, without authorization or content. +2. Key Vault responds 401 with a header (the 'challenge') detailing how the client should authenticate such a request. +3. The policy authenticates according to the challenge and sends the original request with authorization. + +The policy caches the challenge and thus knows how to authenticate future requests. However, authentication +requirements can change. For example, a vault may move to a new tenant. In such a case the policy will attempt the +protocol again. +""" +from typing import TYPE_CHECKING + +from azure.core.pipeline.policies import AsyncHTTPPolicy + +from . import HttpChallengeCache +from .challenge_auth_policy import _enforce_tls, _get_challenge_request, _update_challenge, ChallengeAuthPolicyBase + +if TYPE_CHECKING: + from typing import Any + from azure.core.credentials_async import AsyncTokenCredential + from azure.core.pipeline import PipelineRequest + from azure.core.pipeline.transport import AsyncHttpResponse + from . import HttpChallenge + + +class AsyncChallengeAuthPolicy(ChallengeAuthPolicyBase, AsyncHTTPPolicy): + """policy for handling HTTP authentication challenges""" + + def __init__(self, credential: "AsyncTokenCredential", **kwargs: "Any") -> None: + self._credential = credential + super(AsyncChallengeAuthPolicy, self).__init__(**kwargs) + + async def send(self, request: "PipelineRequest") -> "AsyncHttpResponse": + _enforce_tls(request) + + challenge = HttpChallengeCache.get_challenge_for_url(request.http_request.url) + if not challenge: + challenge_request = _get_challenge_request(request) + challenger = await self.next.send(challenge_request) + try: + challenge = _update_challenge(request, challenger) + except ValueError: + # didn't receive the expected challenge -> nothing more this policy can do + return challenger + + await self._handle_challenge(request, challenge) + response = await self.next.send(request) + + if response.http_response.status_code == 401: + # any cached token must be invalid + self._token = None + + # cached challenge could be outdated; maybe this response has a new one? + try: + challenge = _update_challenge(request, response) + except ValueError: + # 401 with no legible challenge -> nothing more this policy can do + return response + + await self._handle_challenge(request, challenge) + response = await self.next.send(request) + + return response + + async def _handle_challenge(self, request: "PipelineRequest", challenge: "HttpChallenge") -> None: + """authenticate according to challenge, add Authorization header to request""" + + if self._need_new_token: + # azure-identity credentials require an AADv2 scope but the challenge may specify an AADv1 resource + scope = challenge.get_scope() or challenge.get_resource() + "/.default" + self._token = await self._credential.get_token(scope) + + # ignore mypy's warning because although self._token is Optional, get_token raises when it fails to get a token + request.http_request.headers["Authorization"] = "Bearer {}".format(self._token.token) # type: ignore diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/async_client_base.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/async_client_base.py new file mode 100644 index 000000000000..84c827a3a938 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/async_client_base.py @@ -0,0 +1,81 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import TYPE_CHECKING + +from azure.core.pipeline import AsyncPipeline + +from . import AsyncChallengeAuthPolicy +from .client_base import _get_policies +from .multi_api import load_generated_api + +if TYPE_CHECKING: + try: + # pylint:disable=unused-import + from typing import Any + from azure.core.configuration import Configuration + from azure.core.pipeline.transport import AsyncHttpTransport + from azure.core.credentials_async import AsyncTokenCredential + except ImportError: + # AsyncTokenCredential is a typing_extensions.Protocol; we don't depend on that package + pass + + +def _build_pipeline(config: "Configuration", transport: "AsyncHttpTransport" = None, **kwargs: "Any") -> AsyncPipeline: + policies = _get_policies(config, **kwargs) + if transport is None: + from azure.core.pipeline.transport import AioHttpTransport + + transport = AioHttpTransport(**kwargs) + + return AsyncPipeline(transport, policies=policies) + + +class AsyncKeyVaultClientBase(object): + def __init__(self, vault_url: str, credential: "AsyncTokenCredential", **kwargs: "Any") -> None: + if not credential: + raise ValueError( + "credential should be an object supporting the AsyncTokenCredential protocol, " + "such as a credential from azure-identity" + ) + if not vault_url: + raise ValueError("vault_url must be the URL of an Azure Key Vault") + + self._vault_url = vault_url.strip(" /") + client = kwargs.get("generated_client") + if client: + # caller provided a configured client -> nothing left to initialize + self._client = client + return + + api_version = kwargs.pop("api_version", None) + generated = load_generated_api(api_version, aio=True) + + pipeline = kwargs.pop("pipeline", None) + if not pipeline: + config = generated.config_cls(credential, **kwargs) + config.authentication_policy = AsyncChallengeAuthPolicy(credential) + pipeline = _build_pipeline(config, **kwargs) + + # generated clients don't use their credentials parameter + self._client = generated.client_cls(credentials="", pipeline=pipeline) + self._models = generated.models + + @property + def vault_url(self) -> str: + return self._vault_url + + async def __aenter__(self) -> "AsyncKeyVaultClientBase": + await self._client.__aenter__() + return self + + async def __aexit__(self, *args: "Any") -> None: + await self._client.__aexit__(*args) + + async def close(self) -> None: + """Close sockets opened by the client. + + Calling this method is unnecessary when using the client as a context manager. + """ + await self._client.__aexit__() diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/challenge_auth_policy.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/challenge_auth_policy.py new file mode 100644 index 000000000000..fca7dc6f01d2 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/challenge_auth_policy.py @@ -0,0 +1,140 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Policy implementing Key Vault's challenge authentication protocol. + +Normally the protocol is only used for the client's first service request, upon which: +1. The challenge authentication policy sends a copy of the request, without authorization or content. +2. Key Vault responds 401 with a header (the 'challenge') detailing how the client should authenticate such a request. +3. The policy authenticates according to the challenge and sends the original request with authorization. + +The policy caches the challenge and thus knows how to authenticate future requests. However, authentication +requirements can change. For example, a vault may move to a new tenant. In such a case the policy will attempt the +protocol again. +""" + +import copy +import time + +from azure.core.exceptions import ServiceRequestError +from azure.core.pipeline import PipelineContext, PipelineRequest +from azure.core.pipeline.policies import HTTPPolicy +from azure.core.pipeline.transport import HttpRequest + +from .http_challenge import HttpChallenge +from . import http_challenge_cache as ChallengeCache + +try: + from typing import TYPE_CHECKING +except ImportError: + TYPE_CHECKING = False + +if TYPE_CHECKING: + from typing import Any, Dict, Optional + from azure.core.credentials import AccessToken, TokenCredential + from azure.core.pipeline.transport import HttpResponse + + +def _enforce_tls(request): + # type: (PipelineRequest) -> None + if not request.http_request.url.lower().startswith("https"): + raise ServiceRequestError( + "Bearer token authentication is not permitted for non-TLS protected (non-https) URLs." + ) + + +def _get_challenge_request(request): + # type: (PipelineRequest) -> PipelineRequest + + # The challenge request is intended to provoke an authentication challenge from Key Vault, to learn how the + # service request should be authenticated. It should be identical to the service request but with no body. + challenge_request = HttpRequest( + request.http_request.method, request.http_request.url, headers=request.http_request.headers + ) + challenge_request.headers["Content-Length"] = "0" + + options = copy.deepcopy(request.context.options) + context = PipelineContext(request.context.transport, **options) + + return PipelineRequest(http_request=challenge_request, context=context) + + +def _update_challenge(request, challenger): + # type: (HttpRequest, HttpResponse) -> HttpChallenge + """parse challenge from challenger, cache it, return it""" + + challenge = HttpChallenge( + request.http_request.url, + challenger.http_response.headers.get("WWW-Authenticate"), + response_headers=challenger.http_response.headers, + ) + ChallengeCache.set_challenge_for_url(request.http_request.url, challenge) + return challenge + + +class ChallengeAuthPolicyBase(object): + """Sans I/O base for challenge authentication policies""" + + def __init__(self, **kwargs): + self._token = None # type: Optional[AccessToken] + super(ChallengeAuthPolicyBase, self).__init__(**kwargs) + + @property + def _need_new_token(self): + # type: () -> bool + return not self._token or self._token.expires_on - time.time() < 300 + + +class ChallengeAuthPolicy(ChallengeAuthPolicyBase, HTTPPolicy): + """policy for handling HTTP authentication challenges""" + + def __init__(self, credential, **kwargs): + # type: (TokenCredential, **Any) -> None + self._credential = credential + super(ChallengeAuthPolicy, self).__init__(**kwargs) + + def send(self, request): + # type: (PipelineRequest) -> HttpResponse + _enforce_tls(request) + + challenge = ChallengeCache.get_challenge_for_url(request.http_request.url) + if not challenge: + challenge_request = _get_challenge_request(request) + challenger = self.next.send(challenge_request) + try: + challenge = _update_challenge(request, challenger) + except ValueError: + # didn't receive the expected challenge -> nothing more this policy can do + return challenger + + self._handle_challenge(request, challenge) + response = self.next.send(request) + + if response.http_response.status_code == 401: + # any cached token must be invalid + self._token = None + + # cached challenge could be outdated; maybe this response has a new one? + try: + challenge = _update_challenge(request, response) + except ValueError: + # 401 with no legible challenge -> nothing more this policy can do + return response + + self._handle_challenge(request, challenge) + response = self.next.send(request) + + return response + + def _handle_challenge(self, request, challenge): + # type: (PipelineRequest, HttpChallenge) -> None + """authenticate according to challenge, add Authorization header to request""" + + if self._need_new_token: + # azure-identity credentials require an AADv2 scope but the challenge may specify an AADv1 resource + scope = challenge.get_scope() or challenge.get_resource() + "/.default" + self._token = self._credential.get_token(scope) + + # ignore mypy's warning because although self._token is Optional, get_token raises when it fails to get a token + request.http_request.headers["Authorization"] = "Bearer {}".format(self._token.token) # type: ignore diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/client_base.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/client_base.py new file mode 100644 index 000000000000..b1e1a2e997d2 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/client_base.py @@ -0,0 +1,106 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import TYPE_CHECKING + +from azure.core.pipeline import Pipeline +from azure.core.pipeline.policies import ( + ContentDecodePolicy, + UserAgentPolicy, + DistributedTracingPolicy, + HttpLoggingPolicy, +) +from azure.core.pipeline.transport import RequestsTransport + +from .multi_api import load_generated_api +from .challenge_auth_policy import ChallengeAuthPolicy +from .._user_agent import USER_AGENT + +if TYPE_CHECKING: + # pylint:disable=unused-import + from typing import Any + from azure.core.credentials import TokenCredential + from azure.core.pipeline.transport import HttpTransport + from azure.core.configuration import Configuration + + +def _get_policies(config, **kwargs): + logging_policy = HttpLoggingPolicy(**kwargs) + logging_policy.allowed_header_names.add("x-ms-keyvault-network-info") + + return [ + config.headers_policy, + UserAgentPolicy(base_user_agent=USER_AGENT, **kwargs), + config.proxy_policy, + ContentDecodePolicy(), + config.redirect_policy, + config.retry_policy, + config.authentication_policy, + config.logging_policy, + DistributedTracingPolicy(**kwargs), + logging_policy, + ] + + +def _build_pipeline(config, transport=None, **kwargs): + # type: (Configuration, HttpTransport, **Any) -> Pipeline + policies = _get_policies(config) + if transport is None: + transport = RequestsTransport(**kwargs) + + return Pipeline(transport, policies=policies) + + +class KeyVaultClientBase(object): + def __init__(self, vault_url, credential, **kwargs): + # type: (str, TokenCredential, **Any) -> None + if not credential: + raise ValueError( + "credential should be an object supporting the TokenCredential protocol, " + "such as a credential from azure-identity" + ) + if not vault_url: + raise ValueError("vault_url must be the URL of an Azure Key Vault") + + self._vault_url = vault_url.strip(" /") + client = kwargs.get("generated_client") + if client: + # caller provided a configured client -> nothing left to initialize + self._client = client + return + + api_version = kwargs.pop("api_version", None) + generated = load_generated_api(api_version) + + pipeline = kwargs.pop("pipeline", None) + if not pipeline: + config = generated.config_cls(credential, **kwargs) + config.authentication_policy = ChallengeAuthPolicy(credential) + pipeline = _build_pipeline(config, **kwargs) + + # generated clients don't use their credentials parameter + self._client = generated.client_cls(credentials="", pipeline=pipeline) + self._models = generated.models + + @property + def vault_url(self): + # type: () -> str + return self._vault_url + + def __enter__(self): + # type: () -> KeyVaultClientBase + self._client.__enter__() + return self + + def __exit__(self, *args): + # type: (*Any) -> None + self._client.__exit__(*args) + + def close(self): + # type: () -> None + """Close sockets opened by the client. + + Calling this method is unnecessary when using the client as a context manager. + """ + self._client.__exit__() diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/exceptions.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/exceptions.py new file mode 100644 index 000000000000..407c7d872c79 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/exceptions.py @@ -0,0 +1,57 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from collections import defaultdict +import functools +from typing import TYPE_CHECKING + +from azure.core.exceptions import DecodeError, HttpResponseError, ResourceExistsError, ResourceNotFoundError +from azure.core.pipeline.policies import ContentDecodePolicy + +if TYPE_CHECKING: + # pylint:disable=unused-import,ungrouped-imports + from typing import Optional, Type + from azure.core.pipeline.transport import HttpResponse + + +def _get_exception_for_key_vault_error(cls, response): + # type: (Type[HttpResponseError], HttpResponse) -> HttpResponseError + """Construct cls (HttpResponseError or subclass thereof) with Key Vault's error message.""" + + try: + body = ContentDecodePolicy.deserialize_from_http_generics(response) + message = "({}) {}".format(body["error"]["code"], body["error"]["message"]) # type: Optional[str] + except (DecodeError, KeyError): + # Key Vault error response bodies should have the expected shape and be deserializable. + # If we somehow land here, we'll take HttpResponse's default message. + message = None + + return cls(message=message, response=response) + + +# errors map to HttpResponseError... +_default = functools.partial(_get_exception_for_key_vault_error, HttpResponseError) + +# ...unless this mapping specifies another type +_code_to_core_error = {404: ResourceNotFoundError, 409: ResourceExistsError} + + +class _ErrorMap(defaultdict): + """A dict whose 'get' method returns a default value. + + defaultdict would be preferable but defaultdict.get returns None for keys having no value + (azure.core.exceptions.map_error calls error_map.get) + """ + + def get(self, key, value=None): # pylint:disable=unused-argument + return self[key] + + +# map status codes to callables returning appropriate azure-core errors +error_map = _ErrorMap(lambda: _default, + { + status_code: functools.partial(_get_exception_for_key_vault_error, cls) + for status_code, cls in _code_to_core_error.items() + } +) diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/http_challenge.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/http_challenge.py new file mode 100644 index 000000000000..c762e1ae50ef --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/http_challenge.py @@ -0,0 +1,114 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +try: + import urllib.parse as parse +except ImportError: + import urlparse as parse # type: ignore + + +class HttpChallenge(object): + def __init__(self, request_uri, challenge, response_headers=None): + """ Parses an HTTP WWW-Authentication Bearer challenge from a server. """ + self.source_authority = self._validate_request_uri(request_uri) + self.source_uri = request_uri + self._parameters = {} + + # get the scheme of the challenge and remove from the challenge string + trimmed_challenge = self._validate_challenge(challenge) + split_challenge = trimmed_challenge.split(" ", 1) + self.scheme = split_challenge[0] + trimmed_challenge = split_challenge[1] + + # split trimmed challenge into comma-separated name=value pairs. Values are expected + # to be surrounded by quotes which are stripped here. + for item in trimmed_challenge.split(","): + # process name=value pairs + comps = item.split("=") + if len(comps) == 2: + key = comps[0].strip(' "') + value = comps[1].strip(' "') + if key: + self._parameters[key] = value + + # minimum set of parameters + if not self._parameters: + raise ValueError("Invalid challenge parameters") + + # must specify authorization or authorization_uri + if "authorization" not in self._parameters and "authorization_uri" not in self._parameters: + raise ValueError("Invalid challenge parameters") + + # if the response headers were supplied + if response_headers: + # get the message signing key and message key encryption key from the headers + self.server_signature_key = response_headers.get("x-ms-message-signing-key", None) + self.server_encryption_key = response_headers.get("x-ms-message-encryption-key", None) + + def is_bearer_challenge(self): + """ Tests whether the HttpChallenge a Bearer challenge. + rtype: bool """ + if not self.scheme: + return False + + return self.scheme.lower() == "bearer" + + def is_pop_challenge(self): + """ Tests whether the HttpChallenge is a proof of possession challenge. + rtype: bool """ + if not self.scheme: + return False + + return self.scheme.lower() == "pop" + + def get_value(self, key): + return self._parameters.get(key) + + def get_authorization_server(self): + """ Returns the URI for the authorization server if present, otherwise empty string. """ + value = "" + for key in ["authorization_uri", "authorization"]: + value = self.get_value(key) or "" + if value: + break + return value + + def get_resource(self): + """ Returns the resource if present, otherwise empty string. """ + return self.get_value("resource") or "" + + def get_scope(self): + """ Returns the scope if present, otherwise empty string. """ + return self.get_value("scope") or "" + + def supports_pop(self): + """ Returns True if challenge supports pop token auth else False """ + return self._parameters.get("supportspop", "").lower() == "true" + + def supports_message_protection(self): + """ Returns True if challenge vault supports message protection """ + return self.supports_pop() and self.server_encryption_key and self.server_signature_key + + # pylint:disable=no-self-use + def _validate_challenge(self, challenge): + """ Verifies that the challenge is a valid auth challenge and returns the key=value pairs. """ + if not challenge: + raise ValueError("Challenge cannot be empty") + + return challenge.strip() + + # pylint:disable=no-self-use + def _validate_request_uri(self, uri): + """ Extracts the host authority from the given URI. """ + if not uri: + raise ValueError("request_uri cannot be empty") + + uri = parse.urlparse(uri) + if not uri.netloc: + raise ValueError("request_uri must be an absolute URI") + + if uri.scheme.lower() not in ["http", "https"]: + raise ValueError("request_uri must be HTTP or HTTPS") + + return uri.netloc diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/http_challenge_cache.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/http_challenge_cache.py new file mode 100644 index 000000000000..07cda1366aa8 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/http_challenge_cache.py @@ -0,0 +1,89 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import threading + +try: + import urllib.parse as parse +except ImportError: + import urlparse as parse # type: ignore + +try: + from typing import TYPE_CHECKING +except ImportError: + TYPE_CHECKING = False + +if TYPE_CHECKING: + # pylint: disable=unused-import + from typing import Dict + from .http_challenge import HttpChallenge + + +_cache = {} # type: Dict[str, HttpChallenge] +_lock = threading.Lock() + + +def get_challenge_for_url(url): + """ Gets the challenge for the cached URL. + :param url: the URL the challenge is cached for. + :rtype: HttpBearerChallenge """ + + if not url: + raise ValueError("URL cannot be None") + + key = _get_cache_key(url) + + with _lock: + return _cache.get(key) + + +def _get_cache_key(url): + """Use the URL's netloc as cache key except when the URL specifies the default port for its scheme. In that case + use the netloc without the port. That is to say, https://foo.bar and https://foo.bar:443 are considered equivalent. + + This equivalency prevents an unnecessary challenge when using Key Vault's paging API. The Key Vault client doesn't + specify ports, but Key Vault's next page links do, so a redundant challenge would otherwise be executed when the + client requests the next page.""" + + parsed = parse.urlparse(url) + if parsed.scheme == "https" and parsed.port == 443: + return parsed.netloc[:-4] + return parsed.netloc + + +def remove_challenge_for_url(url): + """ Removes the cached challenge for the specified URL. + :param url: the URL for which to remove the cached challenge """ + if not url: + raise ValueError("URL cannot be empty") + + url = parse.urlparse(url) + + with _lock: + del _cache[url.netloc] + + +def set_challenge_for_url(url, challenge): + """ Caches the challenge for the specified URL. + :param url: the URL for which to cache the challenge + :param challenge: the challenge to cache """ + if not url: + raise ValueError("URL cannot be empty") + + if not challenge: + raise ValueError("Challenge cannot be empty") + + src_url = parse.urlparse(url) + if src_url.netloc != challenge.source_authority: + raise ValueError("Source URL and Challenge URL do not match") + + with _lock: + _cache[src_url.netloc] = challenge + + +def clear(): + """ Clears the cache. """ + + with _lock: + _cache.clear() diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/multi_api.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/multi_api.py new file mode 100644 index 000000000000..15cb1b2186e5 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/multi_api.py @@ -0,0 +1,73 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from collections import namedtuple +from enum import Enum +from typing import TYPE_CHECKING + +from ._generated.v7_1_preview.version import VERSION as V7_1_PREVIEW_VERSION +from ._generated.v7_0.version import VERSION as V7_0_VERSION +from ._generated.v2016_10_01.version import VERSION as V2016_10_01_VERSION + +if TYPE_CHECKING: + from typing import Union + + +class ApiVersion(Enum): + """Key Vault API versions supported by this package""" + + #: this is the default version + V7_1_preview = V7_1_PREVIEW_VERSION + V7_0 = V7_0_VERSION + V2016_10_01 = V2016_10_01_VERSION + + +DEFAULT_VERSION = ApiVersion.V7_1_preview + +GeneratedApi = namedtuple("GeneratedApi", ("models", "client_cls", "config_cls")) + + +def load_generated_api(api_version, aio=False): + # type: (Union[ApiVersion, str], bool) -> GeneratedApi + api_version = api_version or DEFAULT_VERSION + try: + # api_version could be a string; map it to an instance of ApiVersion + # (this is a no-op if it's already an instance of ApiVersion) + api_version = ApiVersion(api_version) + except ValueError: + # api_version is unknown to ApiVersion + raise NotImplementedError( + "This package doesn't support API version '{}'. ".format(api_version) + + "Supported versions: {}".format(", ".join(v.value for v in ApiVersion)) + ) + + if api_version == ApiVersion.V7_1_preview: + from ._generated.v7_1_preview import models + + if aio: + from ._generated.v7_1_preview.aio import KeyVaultClient + from ._generated.v7_1_preview.aio._configuration_async import KeyVaultClientConfiguration + else: + from ._generated.v7_1_preview import KeyVaultClient # type: ignore + from ._generated.v7_1_preview._configuration import KeyVaultClientConfiguration # type: ignore + elif api_version == ApiVersion.V7_0: + from ._generated.v7_0 import models # type: ignore + + if aio: + from ._generated.v7_0.aio import KeyVaultClient # type: ignore + from ._generated.v7_0.aio._configuration_async import KeyVaultClientConfiguration # type: ignore + else: + from ._generated.v7_0 import KeyVaultClient # type: ignore + from ._generated.v7_0._configuration import KeyVaultClientConfiguration # type: ignore + elif api_version == ApiVersion.V2016_10_01: + from ._generated.v2016_10_01 import models # type: ignore + + if aio: + from ._generated.v2016_10_01.aio import KeyVaultClient # type: ignore + from ._generated.v2016_10_01.aio._configuration_async import KeyVaultClientConfiguration # type: ignore + else: + from ._generated.v2016_10_01 import KeyVaultClient # type: ignore + from ._generated.v2016_10_01._configuration import KeyVaultClientConfiguration # type: ignore + + return GeneratedApi(models=models, client_cls=KeyVaultClient, config_cls=KeyVaultClientConfiguration) diff --git a/sdk/keyvault/azure-keyvault-administration/tests/_shared/__init__.py b/sdk/keyvault/azure-keyvault-administration/tests/_shared/__init__.py new file mode 100644 index 000000000000..b74cfa3b899c --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/tests/_shared/__init__.py @@ -0,0 +1,4 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ diff --git a/sdk/keyvault/azure-keyvault-administration/tests/_shared/helpers.py b/sdk/keyvault/azure-keyvault-administration/tests/_shared/helpers.py new file mode 100644 index 000000000000..8df36215388e --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/tests/_shared/helpers.py @@ -0,0 +1,102 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import json +import six + +try: + from unittest import mock +except ImportError: # python < 3.3 + import mock # type: ignore + + +class Request: + def __init__( + self, + base_url=None, + url=None, + authority=None, + url_substring=None, + method=None, + required_headers=None, + required_data=None, + required_params=None, + ): + self.authority = authority + self.base_url = base_url + self.method = method + self.url = url + self.url_substring = url_substring + self.required_headers = required_headers or {} + self.required_data = required_data or {} + self.required_params = required_params or {} + + def assert_matches(self, request): + discrepancies = [] + + def add_discrepancy(name, expected, actual): + discrepancies.append("{}:\n\t expected: {}\n\t actual: {}".format(name, expected, actual)) + + if self.base_url and self.base_url != request.url.split("?")[0]: + add_discrepancy("base url", self.base_url, request.url) + + if self.url and self.url != request.url: + add_discrepancy("url", self.url, request.url) + + if self.url_substring and self.url_substring not in request.url: + add_discrepancy("url substring", self.url_substring, request.url) + + parsed = six.moves.urllib_parse.urlparse(request.url) + if self.authority and parsed.netloc != self.authority: + add_discrepancy("authority", self.authority, parsed.netloc) + + if self.method and request.method != self.method: + add_discrepancy("method", self.method, request.method) + + for param, expected_value in self.required_params.items(): + actual_value = request.query.get(param) + if actual_value != expected_value: + add_discrepancy(param, expected_value, actual_value) + + for header, expected_value in self.required_headers.items(): + actual_value = request.headers.get(header) + + # UserAgentPolicy appends the value of $AZURE_HTTP_USER_AGENT, which is set in + # pipelines, so we accept a user agent which merely contains the expected value + if header.lower() == "user-agent": + if expected_value not in actual_value: + add_discrepancy("user-agent", "contains " + expected_value, actual_value) + elif actual_value != expected_value: + add_discrepancy(header, expected_value, actual_value) + + for field, expected_value in self.required_data.items(): + actual_value = request.body.get(field) + if actual_value != expected_value: + add_discrepancy("form field", expected_value, actual_value) + + assert not discrepancies, "Unexpected request\n\t" + "\n\t".join(discrepancies) + + +def mock_response(status_code=200, headers=None, json_payload=None): + response = mock.Mock(status_code=status_code, headers=headers or {}) + if json_payload is not None: + response.text = lambda encoding=None: json.dumps(json_payload) + response.headers["content-type"] = "application/json" + response.content_type = "application/json" + return response + + +def validating_transport(requests, responses): + if len(requests) != len(responses): + raise ValueError("each request must have one response") + + sessions = zip(requests, responses) + sessions = (s for s in sessions) # 2.7's zip returns a list, and nesting a generator doesn't break it for 3.x + + def validate_request(request, **kwargs): # pylint:disable=unused-argument + expected_request, response = next(sessions) + expected_request.assert_matches(request) + return response + + return mock.Mock(send=validate_request) diff --git a/sdk/keyvault/azure-keyvault-administration/tests/_shared/helpers_async.py b/sdk/keyvault/azure-keyvault-administration/tests/_shared/helpers_async.py new file mode 100644 index 000000000000..d887c739758c --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/tests/_shared/helpers_async.py @@ -0,0 +1,49 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import asyncio +import functools +import sys +from unittest import mock + +from .helpers import validating_transport + + +def get_completed_future(result=None): + future = asyncio.Future() + future.set_result(result) + return future + + +def wrap_in_future(fn): + """Return a completed Future whose result is the return of fn. + + Added to simplify using unittest.Mock in async code. Python 3.8's AsyncMock would be preferable. + """ + + @functools.wraps(fn) + def wrapper(*args, **kwargs): + result = fn(*args, **kwargs) + return get_completed_future(result) + + return wrapper + + +class AsyncMockTransport(mock.MagicMock): + """Mock with do-nothing aenter/exit for mocking async transport. + + This is unnecessary on 3.8+, where MagicMocks implement aenter/exit. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + if sys.version_info < (3, 8): + self.__aenter__ = mock.Mock(return_value=get_completed_future()) + self.__aexit__ = mock.Mock(return_value=get_completed_future()) + + +def async_validating_transport(requests, responses): + sync_transport = validating_transport(requests, responses) + return AsyncMockTransport(send=wrap_in_future(sync_transport.send)) diff --git a/sdk/keyvault/azure-keyvault-administration/tests/_shared/json_attribute_matcher.py b/sdk/keyvault/azure-keyvault-administration/tests/_shared/json_attribute_matcher.py new file mode 100644 index 000000000000..bf79ad588082 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/tests/_shared/json_attribute_matcher.py @@ -0,0 +1,18 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import json + +import six + +_has_json_body = lambda req: req.body and "json" in req.headers.get("Content-Type", "") + + +def json_attribute_matcher(r1, r2): + """Tests whether two vcr.py requests have JSON content with identical attributes (ignoring values).""" + + if _has_json_body(r1) and _has_json_body(r2): + c1 = json.loads(six.ensure_str(r1.body)) + c2 = json.loads(six.ensure_str(r2.body)) + assert sorted(c1.keys()) == sorted(c2.keys()) diff --git a/sdk/keyvault/azure-keyvault-administration/tests/_shared/preparer.py b/sdk/keyvault/azure-keyvault-administration/tests/_shared/preparer.py new file mode 100644 index 000000000000..ea9a7a63d986 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/tests/_shared/preparer.py @@ -0,0 +1,29 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +try: + from unittest.mock import Mock +except ImportError: # python < 3.3 + from mock import Mock + +from azure.core.credentials import AccessToken +from azure.identity import EnvironmentCredential +from devtools_testutils import AzureMgmtPreparer + + +class KeyVaultClientPreparer(AzureMgmtPreparer): + def __init__(self, client_cls, name_prefix="vault", random_name_enabled=True, **kwargs): + super(KeyVaultClientPreparer, self).__init__(name_prefix, 24, random_name_enabled=random_name_enabled, **kwargs) + self._client_cls = client_cls + + def create_credential(self): + if self.is_live: + return EnvironmentCredential() + + return Mock(get_token=lambda *_: AccessToken("fake-token", 0)) + + def create_resource(self, _, **kwargs): + credential = self.create_credential() + client = self._client_cls(kwargs.get("vault_uri"), credential, **self.client_kwargs) + return {"client": client} diff --git a/sdk/keyvault/azure-keyvault-administration/tests/_shared/preparer_async.py b/sdk/keyvault/azure-keyvault-administration/tests/_shared/preparer_async.py new file mode 100644 index 000000000000..bf49a31304cc --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/tests/_shared/preparer_async.py @@ -0,0 +1,19 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from unittest.mock import Mock + +from azure.core.credentials import AccessToken +from azure.identity.aio import EnvironmentCredential + +from .preparer import KeyVaultClientPreparer as _KeyVaultClientPreparer +from .helpers_async import get_completed_future + + +class KeyVaultClientPreparer(_KeyVaultClientPreparer): + def create_credential(self): + if self.is_live: + return EnvironmentCredential() + + return Mock(get_token=lambda *_: get_completed_future(AccessToken("fake-token", 0))) diff --git a/sdk/keyvault/azure-keyvault-administration/tests/_shared/test_case.py b/sdk/keyvault/azure-keyvault-administration/tests/_shared/test_case.py new file mode 100644 index 000000000000..c6716ea2574e --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/tests/_shared/test_case.py @@ -0,0 +1,46 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import time + +from azure_devtools.scenario_tests.patches import patch_time_sleep_api +from devtools_testutils import AzureMgmtTestCase + + +class KeyVaultTestCase(AzureMgmtTestCase): + def __init__(self, *args, **kwargs): + if "match_body" not in kwargs: + kwargs["match_body"] = True + + super(KeyVaultTestCase, self).__init__(*args, **kwargs) + self.replay_patches.append(patch_time_sleep_api) + + def setUp(self): + self.list_test_size = 7 + super(KeyVaultTestCase, self).setUp() + + def _poll_until_no_exception(self, fn, expected_exception, max_retries=20, retry_delay=3): + """polling helper for live tests because some operations take an unpredictable amount of time to complete""" + + for i in range(max_retries): + try: + return fn() + except expected_exception: + if i == max_retries - 1: + raise + if self.is_live: + time.sleep(retry_delay) + + def _poll_until_exception(self, fn, expected_exception, max_retries=20, retry_delay=3): + """polling helper for live tests because some operations take an unpredictable amount of time to complete""" + + for _ in range(max_retries): + try: + fn() + if self.is_live: + time.sleep(retry_delay) + except expected_exception: + return + + self.fail("expected exception {expected_exception} was not raised") diff --git a/sdk/keyvault/azure-keyvault-administration/tests/_shared/test_case_async.py b/sdk/keyvault/azure-keyvault-administration/tests/_shared/test_case_async.py new file mode 100644 index 000000000000..07991be314ff --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/tests/_shared/test_case_async.py @@ -0,0 +1,54 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import asyncio + +from azure_devtools.scenario_tests.patches import mock_in_unit_test +from devtools_testutils import AzureMgmtTestCase + + +def skip_sleep(unit_test): + async def immediate_return(_): + return + + return mock_in_unit_test(unit_test, "asyncio.sleep", immediate_return) + + +class KeyVaultTestCase(AzureMgmtTestCase): + def __init__(self, *args, match_body=True, **kwargs): + super().__init__(*args, match_body=match_body, **kwargs) + self.replay_patches.append(skip_sleep) + + def setUp(self): + self.list_test_size = 7 + super(KeyVaultTestCase, self).setUp() + + async def _poll_until_no_exception(self, fn, *resource_names, expected_exception, max_retries=20, retry_delay=3): + """polling helper for live tests because some operations take an unpredictable amount of time to complete""" + + for name in resource_names: + for i in range(max_retries): + try: + # TODO: better for caller to apply args to fn; could also gather + await fn(name) + break + except expected_exception: + if i == max_retries - 1: + raise + if self.is_live: + await asyncio.sleep(retry_delay) + + async def _poll_until_exception(self, fn, *resource_names, expected_exception, max_retries=20, retry_delay=3): + """polling helper for live tests because some operations take an unpredictable amount of time to complete""" + + for name in resource_names: + for _ in range(max_retries): + try: + # TODO: better for caller to apply args to fn; could also gather + await fn(name) + if self.is_live: + await asyncio.sleep(retry_delay) + except expected_exception: + return + self.fail("expected exception {expected_exception} was not raised") From a848ef95405d23a527a4ba82c4cfa3347c639779 Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Mon, 22 Jun 2020 14:59:04 -0700 Subject: [PATCH 4/5] tweak shared code --- .../administration/_internal/__init__.py | 1 + .../administration/_internal/_polling.py | 135 ------------------ .../_internal/_polling_async.py | 72 ---------- .../administration/_internal/api_version.py | 15 ++ .../_internal/async_client_base.py | 62 ++++---- .../administration/_internal/client_base.py | 80 +++++------ .../administration/_internal/multi_api.py | 73 ---------- 7 files changed, 86 insertions(+), 352 deletions(-) delete mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/_polling.py delete mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/_polling_async.py create mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/api_version.py delete mode 100644 sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/multi_api.py diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/__init__.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/__init__.py index a8fd2a41d71f..e13f15a61c71 100644 --- a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/__init__.py +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/__init__.py @@ -15,6 +15,7 @@ from .http_challenge import HttpChallenge from . import http_challenge_cache as HttpChallengeCache + __all__ = [ "ChallengeAuthPolicy", "ChallengeAuthPolicyBase", diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/_polling.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/_polling.py deleted file mode 100644 index df63ad0a70ec..000000000000 --- a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/_polling.py +++ /dev/null @@ -1,135 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -import logging -import time -import threading -import uuid -from typing import TYPE_CHECKING - -from azure.core.polling import PollingMethod, LROPoller, NoPolling -from azure.core.exceptions import ResourceNotFoundError, HttpResponseError - -try: - from urlparse import urlparse # type: ignore # pylint: disable=unused-import -except ImportError: - from urllib.parse import urlparse - -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.common import with_current_context - -if TYPE_CHECKING: - # pylint: disable=ungrouped-imports - from typing import Any, Callable, Union, List, Optional - -logger = logging.getLogger(__name__) - - -class KeyVaultOperationPoller(LROPoller): - """Poller for long running operations where calling result() doesn't wait for operation to complete. - """ - - # pylint: disable=arguments-differ - def __init__(self, polling_method): - # type: (PollingMethod) -> None - super(KeyVaultOperationPoller, self).__init__(None, None, None, NoPolling()) - self._polling_method = polling_method - - # pylint: disable=arguments-differ - def result(self): - # type: () -> Any - """Returns a representation of the final resource without waiting for the operation to complete. - - :returns: The deserialized resource of the long running operation - :raises ~azure.core.exceptions.HttpResponseError: Server problem with the query. - """ - return self._polling_method.resource() - - @distributed_trace - def wait(self, timeout=None): - # type: (Optional[int]) -> None - """Wait on the long running operation for a number of seconds. - - You can check if this call has ended with timeout with the "done()" method. - - :param int timeout: Period of time to wait for the long running - operation to complete (in seconds). - :raises ~azure.core.exceptions.HttpResponseError: Server problem with the query. - """ - - if not self._polling_method.finished(): - self._done = threading.Event() - self._thread = threading.Thread( - target=with_current_context(self._start), name="KeyVaultOperationPoller({})".format(uuid.uuid4()) - ) - self._thread.daemon = True - self._thread.start() - - if self._thread is None: - return - self._thread.join(timeout=timeout) - try: - # Let's handle possible None in forgiveness here - raise self._exception # type: ignore - except TypeError: # Was None - pass - - -class DeleteRecoverPollingMethod(PollingMethod): - """Poller for deleting resources, and recovering deleted resources, in vaults with soft-delete enabled. - - This works by polling for the existence of the deleted or recovered resource. When a resource is deleted, Key Vault - immediately removes it from its collection. However, the resource will not immediately appear in the deleted - collection. Key Vault will therefore respond 404 to GET requests for the deleted resource; when it responds 2xx, - the resource exists in the deleted collection i.e. its deletion is complete. - - Similarly, while recovering a deleted resource, Key Vault will respond 404 to GET requests for the non-deleted - resource; when it responds 2xx, the resource exists in the non-deleted collection, i.e. its recovery is complete. - """ - def __init__(self, command, final_resource, finished, interval=2): - self._command = command - self._resource = final_resource - self._polling_interval = interval - self._finished = finished - - def _update_status(self): - # type: () -> None - try: - self._command() - self._finished = True - except ResourceNotFoundError: - pass - except HttpResponseError as e: - # If we are polling on get_deleted_* and we don't have get permissions, we will get - # ResourceNotFoundError until the resource is recovered, at which point we'll get a 403. - if e.status_code == 403: - self._finished = True - else: - raise - - def initialize(self, client, initial_response, deserialization_callback): - pass - - def run(self): - # type: () -> None - try: - while not self.finished(): - self._update_status() - if not self.finished(): - time.sleep(self._polling_interval) - except Exception as e: - logger.warning(str(e)) - raise - - def finished(self): - # type: () -> bool - return self._finished - - def resource(self): - # type: () -> Any - return self._resource - - def status(self): - # type: () -> str - return "finished" if self._finished else "polling" diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/_polling_async.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/_polling_async.py deleted file mode 100644 index d3fc83105927..000000000000 --- a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/_polling_async.py +++ /dev/null @@ -1,72 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -import asyncio -import logging -from typing import TYPE_CHECKING - -from azure.core.polling import AsyncPollingMethod -from azure.core.exceptions import ResourceNotFoundError, HttpResponseError - -if TYPE_CHECKING: - # pylint:disable=ungrouped-imports - from typing import Any, Callable, Union - -logger = logging.getLogger(__name__) - - -class AsyncDeleteRecoverPollingMethod(AsyncPollingMethod): - """Poller for deleting resources, and recovering deleted resources, in vaults with soft-delete enabled. - - This works by polling for the existence of the deleted or recovered resource. When a resource is deleted, Key Vault - immediately removes it from its collection. However, the resource will not immediately appear in the deleted - collection. Key Vault will therefore respond 404 to GET requests for the deleted resource; when it responds 2xx, - the resource exists in the deleted collection i.e. its deletion is complete. - - Similarly, while recovering a deleted resource, Key Vault will respond 404 to GET requests for the non-deleted - resource; when it responds 2xx, the resource exists in the non-deleted collection, i.e. its recovery is complete. - """ - - def __init__(self, command, final_resource, finished, interval=2): - self._command = command - self._resource = final_resource - self._polling_interval = interval - self._finished = finished - - def initialize(self, client, initial_response, deserialization_callback): - pass - - async def _update_status(self) -> None: - try: - await self._command() - self._finished = True - except ResourceNotFoundError: - pass - except HttpResponseError as e: - # If we are polling on get_deleted_* and we don't have get permissions, we will get - # ResourceNotFoundError until the resource is recovered, at which point we'll get a 403. - if e.status_code == 403: - self._finished = True - else: - raise - - async def run(self) -> None: - try: - while not self.finished(): - await self._update_status() - if not self.finished(): - await asyncio.sleep(self._polling_interval) - except Exception as e: - logger.warning(str(e)) - raise - - def finished(self) -> bool: - return self._finished - - def resource(self) -> "Any": - return self._resource - - def status(self) -> str: - return "finished" if self._finished else "polling" diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/api_version.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/api_version.py new file mode 100644 index 000000000000..ce44867820f8 --- /dev/null +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/api_version.py @@ -0,0 +1,15 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from enum import Enum + + +class ApiVersion(str, Enum): + """Key Vault API versions supported by this package""" + + #: this is the default version + V7_2_preview = "7.2-preview" + + +DEFAULT_VERSION = ApiVersion.V7_2_preview diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/async_client_base.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/async_client_base.py index 84c827a3a938..815ce86516d4 100644 --- a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/async_client_base.py +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/async_client_base.py @@ -3,12 +3,11 @@ # Licensed under the MIT License. # ------------------------------------ from typing import TYPE_CHECKING - -from azure.core.pipeline import AsyncPipeline - +from azure.core.pipeline.policies import HttpLoggingPolicy from . import AsyncChallengeAuthPolicy -from .client_base import _get_policies -from .multi_api import load_generated_api +from .client_base import ApiVersion, DEFAULT_VERSION +from .._sdk_moniker import SDK_MONIKER +from .._generated.aio import KeyVaultClient as _KeyVaultClient if TYPE_CHECKING: try: @@ -22,16 +21,6 @@ pass -def _build_pipeline(config: "Configuration", transport: "AsyncHttpTransport" = None, **kwargs: "Any") -> AsyncPipeline: - policies = _get_policies(config, **kwargs) - if transport is None: - from azure.core.pipeline.transport import AioHttpTransport - - transport = AioHttpTransport(**kwargs) - - return AsyncPipeline(transport, policies=policies) - - class AsyncKeyVaultClientBase(object): def __init__(self, vault_url: str, credential: "AsyncTokenCredential", **kwargs: "Any") -> None: if not credential: @@ -49,18 +38,39 @@ def __init__(self, vault_url: str, credential: "AsyncTokenCredential", **kwargs: self._client = client return - api_version = kwargs.pop("api_version", None) - generated = load_generated_api(api_version, aio=True) + api_version = kwargs.pop("api_version", DEFAULT_VERSION) pipeline = kwargs.pop("pipeline", None) - if not pipeline: - config = generated.config_cls(credential, **kwargs) - config.authentication_policy = AsyncChallengeAuthPolicy(credential) - pipeline = _build_pipeline(config, **kwargs) - - # generated clients don't use their credentials parameter - self._client = generated.client_cls(credentials="", pipeline=pipeline) - self._models = generated.models + transport = kwargs.pop("transport", None) + http_logging_policy = HttpLoggingPolicy(**kwargs) + http_logging_policy.allowed_header_names.update( + { + "x-ms-keyvault-network-info", + "x-ms-keyvault-region", + "x-ms-keyvault-service-version" + } + ) + + if not transport and not pipeline: + from azure.core.pipeline.transport import AioHttpTransport + transport = AioHttpTransport(**kwargs) + + try: + self._client = _KeyVaultClient( + api_version=api_version, + pipeline=pipeline, + transport=transport, + authentication_policy=AsyncChallengeAuthPolicy(credential), + sdk_moniker=SDK_MONIKER, + http_logging_policy=http_logging_policy, + **kwargs + ) + self._models = _KeyVaultClient.models(api_version=api_version) + except NotImplementedError: + raise NotImplementedError( + "This package doesn't support API version '{}'. ".format(api_version) + + "Supported versions: {}".format(", ".join(v.value for v in ApiVersion)) + ) @property def vault_url(self) -> str: @@ -78,4 +88,4 @@ async def close(self) -> None: Calling this method is unnecessary when using the client as a context manager. """ - await self._client.__aexit__() + await self._client.close() diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/client_base.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/client_base.py index b1e1a2e997d2..132492f976ae 100644 --- a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/client_base.py +++ b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/client_base.py @@ -3,53 +3,29 @@ # Licensed under the MIT License. # ------------------------------------ from typing import TYPE_CHECKING +from enum import Enum -from azure.core.pipeline import Pipeline -from azure.core.pipeline.policies import ( - ContentDecodePolicy, - UserAgentPolicy, - DistributedTracingPolicy, - HttpLoggingPolicy, -) from azure.core.pipeline.transport import RequestsTransport +from azure.core.pipeline.policies import HttpLoggingPolicy -from .multi_api import load_generated_api -from .challenge_auth_policy import ChallengeAuthPolicy -from .._user_agent import USER_AGENT +from . import ChallengeAuthPolicy +from .._generated import KeyVaultClient as _KeyVaultClient +from .._sdk_moniker import SDK_MONIKER if TYPE_CHECKING: - # pylint:disable=unused-import + # pylint:disable=unused-import,ungrouped-imports from typing import Any from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpTransport - from azure.core.configuration import Configuration -def _get_policies(config, **kwargs): - logging_policy = HttpLoggingPolicy(**kwargs) - logging_policy.allowed_header_names.add("x-ms-keyvault-network-info") +class ApiVersion(str, Enum): + """Key Vault API versions supported by this package""" - return [ - config.headers_policy, - UserAgentPolicy(base_user_agent=USER_AGENT, **kwargs), - config.proxy_policy, - ContentDecodePolicy(), - config.redirect_policy, - config.retry_policy, - config.authentication_policy, - config.logging_policy, - DistributedTracingPolicy(**kwargs), - logging_policy, - ] + #: this is the default version + V7_2_preview = "7.2-preview" -def _build_pipeline(config, transport=None, **kwargs): - # type: (Configuration, HttpTransport, **Any) -> Pipeline - policies = _get_policies(config) - if transport is None: - transport = RequestsTransport(**kwargs) - - return Pipeline(transport, policies=policies) +DEFAULT_VERSION = ApiVersion.V7_2_preview class KeyVaultClientBase(object): @@ -70,18 +46,30 @@ def __init__(self, vault_url, credential, **kwargs): self._client = client return - api_version = kwargs.pop("api_version", None) - generated = load_generated_api(api_version) + api_version = kwargs.pop("api_version", DEFAULT_VERSION) pipeline = kwargs.pop("pipeline", None) - if not pipeline: - config = generated.config_cls(credential, **kwargs) - config.authentication_policy = ChallengeAuthPolicy(credential) - pipeline = _build_pipeline(config, **kwargs) - - # generated clients don't use their credentials parameter - self._client = generated.client_cls(credentials="", pipeline=pipeline) - self._models = generated.models + transport = kwargs.pop("transport", RequestsTransport(**kwargs)) + http_logging_policy = HttpLoggingPolicy(**kwargs) + http_logging_policy.allowed_header_names.update( + {"x-ms-keyvault-network-info", "x-ms-keyvault-region", "x-ms-keyvault-service-version"} + ) + try: + self._client = _KeyVaultClient( + api_version=api_version, + pipeline=pipeline, + transport=transport, + authentication_policy=ChallengeAuthPolicy(credential), + sdk_moniker=SDK_MONIKER, + http_logging_policy=http_logging_policy, + **kwargs + ) + self._models = _KeyVaultClient.models(api_version=api_version) + except NotImplementedError: + raise NotImplementedError( + "This package doesn't support API version '{}'. ".format(api_version) + + "Supported versions: {}".format(", ".join(v.value for v in ApiVersion)) + ) @property def vault_url(self): @@ -103,4 +91,4 @@ def close(self): Calling this method is unnecessary when using the client as a context manager. """ - self._client.__exit__() + self._client.close() diff --git a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/multi_api.py b/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/multi_api.py deleted file mode 100644 index 15cb1b2186e5..000000000000 --- a/sdk/keyvault/azure-keyvault-administration/azure/keyvault/administration/_internal/multi_api.py +++ /dev/null @@ -1,73 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -from collections import namedtuple -from enum import Enum -from typing import TYPE_CHECKING - -from ._generated.v7_1_preview.version import VERSION as V7_1_PREVIEW_VERSION -from ._generated.v7_0.version import VERSION as V7_0_VERSION -from ._generated.v2016_10_01.version import VERSION as V2016_10_01_VERSION - -if TYPE_CHECKING: - from typing import Union - - -class ApiVersion(Enum): - """Key Vault API versions supported by this package""" - - #: this is the default version - V7_1_preview = V7_1_PREVIEW_VERSION - V7_0 = V7_0_VERSION - V2016_10_01 = V2016_10_01_VERSION - - -DEFAULT_VERSION = ApiVersion.V7_1_preview - -GeneratedApi = namedtuple("GeneratedApi", ("models", "client_cls", "config_cls")) - - -def load_generated_api(api_version, aio=False): - # type: (Union[ApiVersion, str], bool) -> GeneratedApi - api_version = api_version or DEFAULT_VERSION - try: - # api_version could be a string; map it to an instance of ApiVersion - # (this is a no-op if it's already an instance of ApiVersion) - api_version = ApiVersion(api_version) - except ValueError: - # api_version is unknown to ApiVersion - raise NotImplementedError( - "This package doesn't support API version '{}'. ".format(api_version) - + "Supported versions: {}".format(", ".join(v.value for v in ApiVersion)) - ) - - if api_version == ApiVersion.V7_1_preview: - from ._generated.v7_1_preview import models - - if aio: - from ._generated.v7_1_preview.aio import KeyVaultClient - from ._generated.v7_1_preview.aio._configuration_async import KeyVaultClientConfiguration - else: - from ._generated.v7_1_preview import KeyVaultClient # type: ignore - from ._generated.v7_1_preview._configuration import KeyVaultClientConfiguration # type: ignore - elif api_version == ApiVersion.V7_0: - from ._generated.v7_0 import models # type: ignore - - if aio: - from ._generated.v7_0.aio import KeyVaultClient # type: ignore - from ._generated.v7_0.aio._configuration_async import KeyVaultClientConfiguration # type: ignore - else: - from ._generated.v7_0 import KeyVaultClient # type: ignore - from ._generated.v7_0._configuration import KeyVaultClientConfiguration # type: ignore - elif api_version == ApiVersion.V2016_10_01: - from ._generated.v2016_10_01 import models # type: ignore - - if aio: - from ._generated.v2016_10_01.aio import KeyVaultClient # type: ignore - from ._generated.v2016_10_01.aio._configuration_async import KeyVaultClientConfiguration # type: ignore - else: - from ._generated.v2016_10_01 import KeyVaultClient # type: ignore - from ._generated.v2016_10_01._configuration import KeyVaultClientConfiguration # type: ignore - - return GeneratedApi(models=models, client_cls=KeyVaultClient, config_cls=KeyVaultClientConfiguration) From a780c19a79aac0495322406802920f77ef2b8f59 Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Thu, 20 Aug 2020 08:53:39 -0700 Subject: [PATCH 5/5] require azure-common --- sdk/keyvault/azure-keyvault-administration/setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/keyvault/azure-keyvault-administration/setup.py b/sdk/keyvault/azure-keyvault-administration/setup.py index 6c58718383f5..f65c42761597 100644 --- a/sdk/keyvault/azure-keyvault-administration/setup.py +++ b/sdk/keyvault/azure-keyvault-administration/setup.py @@ -79,7 +79,7 @@ "azure.keyvault", ] ), - install_requires=["azure-core<2.0.0,>=1.7.0", "msrest>=0.6.0"], + install_requires=["azure-common~=1.1", "azure-core<2.0.0,>=1.7.0", "msrest>=0.6.0"], extras_require={ ":python_version<'3.0'": ["azure-keyvault-nspkg"], ":python_version<'3.4'": ["enum34>=1.0.4"],