Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Key Vault] Generate Administration with TypeSpec #36915

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@
from azure.core.tracing.decorator import distributed_trace

from ._enums import KeyVaultRoleScope
from ._generated.models import (
Permission,
RoleAssignmentCreateParameters,
RoleAssignmentProperties,
RoleDefinitionCreateParameters,
RoleDefinitionProperties,
)
from ._models import KeyVaultPermission, KeyVaultRoleAssignment, KeyVaultRoleDefinition
from ._internal import KeyVaultClientBase

Expand Down Expand Up @@ -59,13 +66,12 @@ def create_role_assignment(
"""
assignment_name = name or uuid4()

create_parameters = self._client.role_assignments.models.RoleAssignmentCreateParameters(
properties=self._client.role_assignments.models.RoleAssignmentProperties(
create_parameters = RoleAssignmentCreateParameters(
properties=RoleAssignmentProperties(
principal_id=principal_id, role_definition_id=str(definition_id)
)
)
assignment = self._client.role_assignments.create(
vault_base_url=self._vault_url,
scope=scope,
role_assignment_name=str(assignment_name),
parameters=create_parameters,
Expand All @@ -90,7 +96,7 @@ def delete_role_assignment(
"""
try:
self._client.role_assignments.delete(
vault_base_url=self._vault_url, scope=scope, role_assignment_name=str(name), **kwargs
scope=scope, role_assignment_name=str(name), **kwargs
)
except ResourceNotFoundError:
pass
Expand All @@ -111,7 +117,7 @@ def get_role_assignment(
:rtype: ~azure.keyvault.administration.KeyVaultRoleAssignment
"""
assignment = self._client.role_assignments.get(
vault_base_url=self._vault_url, scope=scope, role_assignment_name=str(name), **kwargs
scope=scope, role_assignment_name=str(name), **kwargs
)
return KeyVaultRoleAssignment._from_generated(assignment)

Expand All @@ -129,7 +135,6 @@ def list_role_assignments(
:rtype: ~azure.core.paging.ItemPaged[~azure.keyvault.administration.KeyVaultRoleAssignment]
"""
return self._client.role_assignments.list_for_scope(
vault_base_url=self._vault_url,
scope=scope,
cls=lambda result: [KeyVaultRoleAssignment._from_generated(a) for a in result],
**kwargs
Expand Down Expand Up @@ -175,7 +180,7 @@ def set_role_definition(
:rtype: ~azure.keyvault.administration.KeyVaultRoleDefinition
"""
role_permissions = [
self._client.role_definitions.models.Permission(
Permission(
actions=p.actions,
not_actions=p.not_actions,
data_actions=p.data_actions,
Expand All @@ -184,16 +189,15 @@ def set_role_definition(
for p in permissions or []
]

properties = self._client.role_definitions.models.RoleDefinitionProperties(
properties = RoleDefinitionProperties(
role_name=role_name,
description=description,
permissions=role_permissions,
assignable_scopes=assignable_scopes,
)
parameters = self._client.role_definitions.models.RoleDefinitionCreateParameters(properties=properties)
parameters = RoleDefinitionCreateParameters(properties=properties)

definition = self._client.role_definitions.create_or_update(
vault_base_url=self._vault_url,
scope=scope,
role_definition_name=str(name or uuid4()),
parameters=parameters,
Expand All @@ -217,7 +221,7 @@ def get_role_definition(
:rtype: ~azure.keyvault.administration.KeyVaultRoleDefinition
"""
definition = self._client.role_definitions.get(
vault_base_url=self._vault_url, scope=scope, role_definition_name=str(name), **kwargs
scope=scope, role_definition_name=str(name), **kwargs
)
return KeyVaultRoleDefinition._from_generated(definition)

Expand All @@ -238,7 +242,7 @@ def delete_role_definition(
"""
try:
self._client.role_definitions.delete(
vault_base_url=self._vault_url, scope=scope, role_definition_name=str(name), **kwargs
scope=scope, role_definition_name=str(name), **kwargs
)
except ResourceNotFoundError:
pass
Expand All @@ -257,7 +261,6 @@ def list_role_definitions(
:rtype: ~azure.core.paging.ItemPaged[~azure.keyvault.administration.KeyVaultRoleDefinition]
"""
return self._client.role_definitions.list(
vault_base_url=self._vault_url,
scope=scope,
cls=lambda result: [KeyVaultRoleDefinition._from_generated(d) for d in result],
**kwargs
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,14 +116,13 @@ def begin_backup( # pylint: disable=docstring-missing-param,docstring-keyword-s
) from ex

pipeline_response = self._client.full_backup_status(
vault_base_url=self._vault_url, job_id=job_id, cls=lambda pipeline_response, _, __: pipeline_response
job_id=job_id, cls=lambda pipeline_response, _, __: pipeline_response
)
if "azure-asyncoperation" not in pipeline_response.http_response.headers:
pipeline_response.http_response.headers["azure-asyncoperation"] = status_url
status_response = base64.b64encode(pickle.dumps(pipeline_response)).decode("ascii")

return self._client.begin_full_backup(
vault_base_url=self._vault_url,
azure_storage_blob_container_uri=sas_parameter,
cls=KeyVaultBackupResult._from_generated, # pylint: disable=protected-access
continuation_token=status_response,
Expand Down Expand Up @@ -220,7 +219,7 @@ def begin_restore( # pylint: disable=docstring-missing-param,docstring-keyword-
) from ex

pipeline_response = self._client.restore_status(
vault_base_url=self._vault_url, job_id=job_id, cls=lambda pipeline_response, _, __: pipeline_response
job_id=job_id, cls=lambda pipeline_response, _, __: pipeline_response
)
if "azure-asyncoperation" not in pipeline_response.http_response.headers:
pipeline_response.http_response.headers["azure-asyncoperation"] = status_url
Expand All @@ -246,7 +245,6 @@ def begin_restore( # pylint: disable=docstring-missing-param,docstring-keyword-
)

return client_method(
vault_base_url=self._vault_url,
restore_blob_details=restore_details,
cls=lambda *_: None, # poller.result() returns None
continuation_token=status_response,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,31 @@
# --------------------------------------------------------------------------
# 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.
# Code generated by Microsoft (R) Python Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
# pylint: disable=wrong-import-position

from ._client import KeyVaultClient
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from ._patch import * # pylint: disable=unused-wildcard-import

from ._client import KeyVaultClient # type: ignore
from ._version import VERSION

__version__ = VERSION

try:
from ._patch import __all__ as _patch_all
from ._patch import * # pylint: disable=unused-wildcard-import
from ._patch import *
except ImportError:
_patch_all = []
from ._patch import patch_sdk as _patch_sdk

__all__ = [
"KeyVaultClient",
]
__all__.extend([p for p in _patch_all if p not in __all__])
__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore

_patch_sdk()
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,48 @@
# --------------------------------------------------------------------------
# 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.
# Code generated by Microsoft (R) Python Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------

from copy import deepcopy
from typing import Any
from typing import Any, TYPE_CHECKING
from typing_extensions import Self

from azure.core import PipelineClient
from azure.core.pipeline import policies
from azure.core.rest import HttpRequest, HttpResponse

from . import models as _models
from ._configuration import KeyVaultClientConfiguration
from ._serialization import Deserializer, Serializer
from .operations import KeyVaultClientOperationsMixin, RoleAssignmentsOperations, RoleDefinitionsOperations

if TYPE_CHECKING:
from azure.core.credentials import TokenCredential

class KeyVaultClient(KeyVaultClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword

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_5.operations.RoleDefinitionsOperations
:ivar role_assignments: RoleAssignmentsOperations operations
:vartype role_assignments: azure.keyvault.v7_5.operations.RoleAssignmentsOperations
:keyword api_version: Api Version. Default value is "7.5". Note that overriding this default
value may result in unsupported behavior.
:vartype role_assignments: azure.keyvault.administration.operations.RoleAssignmentsOperations
:ivar role_definitions: RoleDefinitionsOperations operations
:vartype role_definitions: azure.keyvault.administration.operations.RoleDefinitionsOperations
:param vault_base_url: Required.
:type vault_base_url: str
:param credential: Credential used to authenticate requests to the service. Required.
:type credential: ~azure.core.credentials.TokenCredential
:keyword api_version: The API version to use for this operation. Default value is
"7.6-preview.1". Note that overriding this default value may result in unsupported behavior.
:paramtype api_version: str
: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: # pylint: disable=missing-client-constructor-parameter-credential
def __init__(self, vault_base_url: str, credential: "TokenCredential", **kwargs: Any) -> None:
_endpoint = "{vaultBaseUrl}"
self._config = KeyVaultClientConfiguration(**kwargs)
self._config = KeyVaultClientConfiguration(vault_base_url=vault_base_url, credential=credential, **kwargs)
_policies = kwargs.pop("policies", None)
if _policies is None:
_policies = [
Expand All @@ -56,15 +63,13 @@ def __init__(self, **kwargs: Any) -> None: # pylint: disable=missing-client-con
]
self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs)

client_models = {k: v for k, v in _models._models.__dict__.items() if isinstance(v, type)}
client_models.update({k: v for k, v in _models.__dict__.items() if isinstance(v, type)})
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize = Serializer()
self._deserialize = Deserializer()
self._serialize.client_side_validation = False
self.role_definitions = RoleDefinitionsOperations(
self.role_assignments = RoleAssignmentsOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.role_assignments = RoleAssignmentsOperations(
self.role_definitions = RoleDefinitionsOperations(
self._client, self._config, self._serialize, self._deserialize
)

Expand All @@ -87,13 +92,19 @@ def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs:
"""

request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
path_format_arguments = {
"vaultBaseUrl": self._serialize.url(
"self._config.vault_base_url", self._config.vault_base_url, "str", skip_quote=True
),
}

request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments)
return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore

def close(self) -> None:
self._client.close()

def __enter__(self) -> "KeyVaultClient":
def __enter__(self) -> Self:
self._client.__enter__()
return self

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@
# --------------------------------------------------------------------------
# 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.
# Code generated by Microsoft (R) Python Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------

from typing import Any
from typing import Any, TYPE_CHECKING

from azure.core.pipeline import policies

VERSION = "unknown"
from ._version import VERSION

if TYPE_CHECKING:
from azure.core.credentials import TokenCredential


class KeyVaultClientConfiguration: # pylint: disable=too-many-instance-attributes
Expand All @@ -19,16 +22,28 @@ class KeyVaultClientConfiguration: # pylint: disable=too-many-instance-attribut
Note that all parameters used to create this instance are saved as instance
attributes.

:keyword api_version: Api Version. Default value is "7.5". Note that overriding this default
value may result in unsupported behavior.
:param vault_base_url: Required.
:type vault_base_url: str
:param credential: Credential used to authenticate requests to the service. Required.
:type credential: ~azure.core.credentials.TokenCredential
:keyword api_version: The API version to use for this operation. Default value is
"7.6-preview.1". Note that overriding this default value may result in unsupported behavior.
:paramtype api_version: str
"""

def __init__(self, **kwargs: Any) -> None:
api_version: str = kwargs.pop("api_version", "7.5")
def __init__(self, vault_base_url: str, credential: "TokenCredential", **kwargs: Any) -> None:
api_version: str = kwargs.pop("api_version", "7.6-preview.1")

if vault_base_url is None:
raise ValueError("Parameter 'vault_base_url' must not be None.")
if credential is None:
raise ValueError("Parameter 'credential' must not be None.")

self.vault_base_url = vault_base_url
self.credential = credential
self.api_version = api_version
kwargs.setdefault("sdk_moniker", "keyvault/{}".format(VERSION))
self.credential_scopes = kwargs.pop("credential_scopes", ["https://vault.azure.net/.default"])
kwargs.setdefault("sdk_moniker", "keyvault-administration/{}".format(VERSION))
self.polling_interval = kwargs.get("polling_interval", 30)
self._configure(**kwargs)

Expand All @@ -42,3 +57,7 @@ def _configure(self, **kwargs: Any) -> None:
self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs)
self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs)
self.authentication_policy = kwargs.get("authentication_policy")
if self.credential and not self.authentication_policy:
self.authentication_policy = policies.BearerTokenCredentialPolicy(
self.credential, *self.credential_scopes, **kwargs
)
Loading
Loading