Skip to content

Commit

Permalink
Address feedback
Browse files Browse the repository at this point in the history
  • Loading branch information
mccoyp committed Mar 9, 2021
1 parent fb36a25 commit 6c843b8
Show file tree
Hide file tree
Showing 41 changed files with 1,351 additions and 2,319 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def __init__(self, key, credential, **kwargs):
self._local_provider = get_local_cryptography_provider(self._key)
self._initialized = True
except Exception as ex: # pylint:disable=broad-except
raise ValueError("The provided jwk is not valid for local cryptography: {}".format(ex))
six.raise_from(ValueError("The provided jwk is not valid for local cryptography"), ex)
else:
self._local_provider = NoLocalCryptography()
self._initialized = False
Expand All @@ -145,7 +145,7 @@ def key_id(self):
This property may be None when a client is constructed with :func:`from_jwk`.
:rtype: str
:rtype: str or None
"""
if not self._jwk:
return self._key_id.source_id
Expand All @@ -158,7 +158,7 @@ def vault_url(self):
This property may be None when a client is constructed with :func:`from_jwk`.
:rtype: str
:rtype: str or None
"""
return self._vault_url

Expand All @@ -170,13 +170,6 @@ def from_jwk(cls, jwk):
:param jwk: the key's cryptographic material, as a JsonWebKey or dictionary.
:type jwk: JsonWebKey or dict
:rtype: CryptographyClient
.. literalinclude:: ../tests/test_examples_crypto.py
:start-after: [START from_jwk]
:end-before: [END from_jwk]
:caption: Create a CryptographyClient from a JsonWebKey
:language: python
:dedent: 8
"""
if not isinstance(jwk, JsonWebKey):
jwk = JsonWebKey(**jwk)
Expand All @@ -202,7 +195,7 @@ def _initialize(self, **kwargs):

# if we have the key material, create a local crypto provider with it
if self._key:
self._local_provider = get_local_cryptography_provider(self._key, _key_id=self.key_id)
self._local_provider = get_local_cryptography_provider(self._key)
self._initialized = True
else:
# try to get the key again next time unless we know we're forbidden to do so
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,17 @@
from ... import KeyType

if TYPE_CHECKING:
from typing import Any
from ... import JsonWebKey


def get_local_cryptography_provider(key, **kwargs):
# type: (JsonWebKey, **Any) -> LocalCryptographyProvider
def get_local_cryptography_provider(key):
# type: (JsonWebKey) -> LocalCryptographyProvider
if key.kty in (KeyType.ec, KeyType.ec_hsm):
return EllipticCurveCryptographyProvider(key, **kwargs)
return EllipticCurveCryptographyProvider(key)
if key.kty in (KeyType.rsa, KeyType.rsa_hsm):
return RsaCryptographyProvider(key, **kwargs)
return RsaCryptographyProvider(key)
if key.kty in (KeyType.oct, KeyType.oct_hsm):
return SymmetricCryptographyProvider(key, **kwargs)
return SymmetricCryptographyProvider(key)

raise ValueError('Unsupported key type "{}"'.format(key.kty))

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,11 @@


class LocalCryptographyProvider(ABC):
def __init__(self, key, **kwargs):
def __init__(self, key):
# type: (JsonWebKey, **Any) -> None
self._allowed_ops = frozenset(key.key_ops or [])
self._internal_key = self._get_internal_key(key)
self._key = key
self._key_id = kwargs.pop("_key_id", None) or key.kid

@abc.abstractmethod
def _get_internal_key(self, key):
Expand All @@ -48,9 +47,9 @@ def key_id(self):
# type: () -> Optional[str]
"""The full identifier of the provider's key.
:rtype: str
:rtype: str or None
"""
return self._key_id
return self._key.kid

def _raise_if_unsupported(self, operation, algorithm):
# type: (KeyOperation, Algorithm) -> None
Expand All @@ -65,34 +64,34 @@ def encrypt(self, algorithm, plaintext):
# type: (EncryptionAlgorithm, bytes) -> EncryptResult
self._raise_if_unsupported(KeyOperation.encrypt, algorithm)
ciphertext = self._internal_key.encrypt(plaintext, algorithm=algorithm.value)
return EncryptResult(key_id=self._key_id, algorithm=algorithm, ciphertext=ciphertext)
return EncryptResult(key_id=self._key.kid, algorithm=algorithm, ciphertext=ciphertext)

def decrypt(self, algorithm, ciphertext):
# type: (EncryptionAlgorithm, bytes) -> DecryptResult
self._raise_if_unsupported(KeyOperation.decrypt, algorithm)
plaintext = self._internal_key.decrypt(ciphertext, iv=None, algorithm=algorithm.value)
return DecryptResult(key_id=self._key_id, algorithm=algorithm, plaintext=plaintext)
return DecryptResult(key_id=self._key.kid, algorithm=algorithm, plaintext=plaintext)

def wrap_key(self, algorithm, key):
# type: (KeyWrapAlgorithm, bytes) -> WrapResult
self._raise_if_unsupported(KeyOperation.wrap_key, algorithm)
encrypted_key = self._internal_key.wrap_key(key, algorithm=algorithm.value)
return WrapResult(key_id=self._key_id, algorithm=algorithm, encrypted_key=encrypted_key)
return WrapResult(key_id=self._key.kid, algorithm=algorithm, encrypted_key=encrypted_key)

def unwrap_key(self, algorithm, encrypted_key):
# type: (KeyWrapAlgorithm, bytes) -> UnwrapResult
self._raise_if_unsupported(KeyOperation.unwrap_key, algorithm)
unwrapped_key = self._internal_key.unwrap_key(encrypted_key, algorithm=algorithm.value)
return UnwrapResult(key_id=self._key_id, algorithm=algorithm, key=unwrapped_key)
return UnwrapResult(key_id=self._key.kid, algorithm=algorithm, key=unwrapped_key)

def sign(self, algorithm, digest):
# type: (SignatureAlgorithm, bytes) -> SignResult
self._raise_if_unsupported(KeyOperation.sign, algorithm)
signature = self._internal_key.sign(digest, algorithm=algorithm.value)
return SignResult(key_id=self._key_id, algorithm=algorithm, signature=signature)
return SignResult(key_id=self._key.kid, algorithm=algorithm, signature=signature)

def verify(self, algorithm, digest, signature):
# type: (SignatureAlgorithm, bytes, bytes) -> VerifyResult
self._raise_if_unsupported(KeyOperation.verify, algorithm)
is_valid = self._internal_key.verify(digest, signature, algorithm=algorithm.value)
return VerifyResult(key_id=self._key_id, algorithm=algorithm, is_valid=is_valid)
return VerifyResult(key_id=self._key.kid, algorithm=algorithm, is_valid=is_valid)
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import logging
from typing import TYPE_CHECKING

import six
from azure.core.exceptions import HttpResponseError
from azure.core.tracing.decorator_async import distributed_trace_async

Expand Down Expand Up @@ -83,7 +84,7 @@ def __init__(self, key: "Union[KeyVaultKey, str]", credential: "AsyncTokenCreden
self._local_provider = get_local_cryptography_provider(self._key)
self._initialized = True
except Exception as ex: # pylint:disable=broad-except
raise ValueError("The provided jwk is not valid for local cryptography: {}".format(ex))
raise ValueError("The provided jwk is not valid for local cryptography") from ex
else:
self._local_provider = NoLocalCryptography()
self._initialized = False
Expand All @@ -97,7 +98,7 @@ def key_id(self) -> "Optional[str]":
This property may be None when a client is constructed with :func:`from_jwk`.
:rtype: str
:rtype: str or None
"""
if not self._jwk:
return self._key_id.source_id
Expand All @@ -109,7 +110,7 @@ def vault_url(self) -> "Optional[str]":
This property may be None when a client is constructed with :func:`from_jwk`.
:rtype: str
:rtype: str or None
"""
return self._vault_url

Expand All @@ -120,13 +121,6 @@ def from_jwk(cls, jwk: "Union[JsonWebKey, dict]") -> "CryptographyClient":
:param jwk: the key's cryptographic material, as a JsonWebKey or dictionary.
:type jwk: JsonWebKey or dict
:rtype: CryptographyClient
.. literalinclude:: ../tests/test_examples_crypto.py
:start-after: [START from_jwk]
:end-before: [END from_jwk]
:caption: Create a CryptographyClient from a JsonWebKey
:language: python
:dedent: 8
"""
if not isinstance(jwk, JsonWebKey):
jwk = JsonWebKey(**jwk)
Expand All @@ -152,7 +146,7 @@ async def _initialize(self, **kwargs):

# if we have the key material, create a local crypto provider with it
if self._key:
self._local_provider = get_local_cryptography_provider(self._key, _key_id=self.key_id)
self._local_provider = get_local_cryptography_provider(self._key)
self._initialized = True
else:
# try to get the key again next time unless we know we're forbidden to do so
Expand Down
1 change: 1 addition & 0 deletions sdk/keyvault/azure-keyvault-keys/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@
"cryptography>=2.1.4",
"msrest>=0.6.21",
"azure-common~=1.1",
"six>=1.9.0"
],
extras_require={
":python_version<'3.0'": ["azure-keyvault-nspkg"],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ interactions:
Content-Type:
- application/json
User-Agent:
- azsdk-python-keyvault-keys/4.3.2 Python/3.5.3 (Windows-10-10.0.19041-SP0)
- azsdk-python-keyvault-keys/4.4.0b3 Python/3.5.3 (Windows-10-10.0.19041-SP0)
method: POST
uri: https://vaultname.vault.azure.net/keys/livekvtesteckeye9470d88/create?api-version=7.2-preview
response:
Expand All @@ -28,7 +28,7 @@ interactions:
content-type:
- application/json; charset=utf-8
date:
- Sat, 06 Feb 2021 02:20:10 GMT
- Tue, 09 Mar 2021 22:53:20 GMT
expires:
- '-1'
pragma:
Expand All @@ -41,11 +41,11 @@ interactions:
x-content-type-options:
- nosniff
x-ms-keyvault-network-info:
- conn_type=Ipv4;addr=174.127.232.53;act_addr_fam=InterNetwork;
- conn_type=Ipv4;addr=172.92.159.124;act_addr_fam=InterNetwork;
x-ms-keyvault-region:
- northeurope
- westus2
x-ms-keyvault-service-version:
- 1.2.164.0
- 1.2.191.0
x-powered-by:
- ASP.NET
status:
Expand All @@ -65,21 +65,21 @@ interactions:
Content-Type:
- application/json
User-Agent:
- azsdk-python-keyvault-keys/4.3.2 Python/3.5.3 (Windows-10-10.0.19041-SP0)
- azsdk-python-keyvault-keys/4.4.0b3 Python/3.5.3 (Windows-10-10.0.19041-SP0)
method: POST
uri: https://vaultname.vault.azure.net/keys/livekvtesteckeye9470d88/create?api-version=7.2-preview
response:
body:
string: '{"key":{"kid":"https://vaultname.vault.azure.net/keys/livekvtesteckeye9470d88/41b7345af65e4e29b0ad3c16103c5cb1","kty":"EC","key_ops":["sign","verify"],"crv":"P-256","x":"xLeGJutfYRgRELSvq0-Yg-q5UmCVaJ8HyBQVi9s98Uk","y":"0MHnZ8jZjyGtp_WUdooqXwqn843uvWUL83SxCrY6nlg"},"attributes":{"enabled":true,"created":1612578012,"updated":1612578012,"recoveryLevel":"Recoverable+Purgeable","recoverableDays":90}}'
string: '{"key":{"kid":"https://vaultname.vault.azure.net/keys/livekvtesteckeye9470d88/eb13ef04092f4155b16356b8d9c41aa1","kty":"EC","key_ops":["sign","verify"],"crv":"P-256","x":"wp9BgBb7rP9GZzC9FC02tSMWDzQHUYE8IyP0mITkBaY","y":"yEW7jd6cAAkDH3b5uxxa2wHTnFjc7iN2xSktLJsTzbo"},"attributes":{"enabled":true,"created":1615330401,"updated":1615330401,"recoveryLevel":"Recoverable+Purgeable","recoverableDays":90}}'
headers:
cache-control:
- no-cache
content-length:
- '402'
- '400'
content-type:
- application/json; charset=utf-8
date:
- Sat, 06 Feb 2021 02:20:11 GMT
- Tue, 09 Mar 2021 22:53:21 GMT
expires:
- '-1'
pragma:
Expand All @@ -89,11 +89,11 @@ interactions:
x-content-type-options:
- nosniff
x-ms-keyvault-network-info:
- conn_type=Ipv4;addr=174.127.232.53;act_addr_fam=InterNetwork;
- conn_type=Ipv4;addr=172.92.159.124;act_addr_fam=InterNetwork;
x-ms-keyvault-region:
- northeurope
- westus2
x-ms-keyvault-service-version:
- 1.2.164.0
- 1.2.191.0
x-powered-by:
- ASP.NET
status:
Expand All @@ -109,21 +109,21 @@ interactions:
Connection:
- keep-alive
User-Agent:
- azsdk-python-keyvault-keys/4.3.2 Python/3.5.3 (Windows-10-10.0.19041-SP0)
- azsdk-python-keyvault-keys/4.4.0b3 Python/3.5.3 (Windows-10-10.0.19041-SP0)
method: GET
uri: https://vaultname.vault.azure.net/keys/livekvtesteckeye9470d88/41b7345af65e4e29b0ad3c16103c5cb1?api-version=7.2-preview
uri: https://vaultname.vault.azure.net/keys/livekvtesteckeye9470d88/eb13ef04092f4155b16356b8d9c41aa1?api-version=7.2-preview
response:
body:
string: '{"key":{"kid":"https://vaultname.vault.azure.net/keys/livekvtesteckeye9470d88/41b7345af65e4e29b0ad3c16103c5cb1","kty":"EC","key_ops":["sign","verify"],"crv":"P-256","x":"xLeGJutfYRgRELSvq0-Yg-q5UmCVaJ8HyBQVi9s98Uk","y":"0MHnZ8jZjyGtp_WUdooqXwqn843uvWUL83SxCrY6nlg"},"attributes":{"enabled":true,"created":1612578012,"updated":1612578012,"recoveryLevel":"Recoverable+Purgeable","recoverableDays":90}}'
string: '{"key":{"kid":"https://vaultname.vault.azure.net/keys/livekvtesteckeye9470d88/eb13ef04092f4155b16356b8d9c41aa1","kty":"EC","key_ops":["sign","verify"],"crv":"P-256","x":"wp9BgBb7rP9GZzC9FC02tSMWDzQHUYE8IyP0mITkBaY","y":"yEW7jd6cAAkDH3b5uxxa2wHTnFjc7iN2xSktLJsTzbo"},"attributes":{"enabled":true,"created":1615330401,"updated":1615330401,"recoveryLevel":"Recoverable+Purgeable","recoverableDays":90}}'
headers:
cache-control:
- no-cache
content-length:
- '402'
- '400'
content-type:
- application/json; charset=utf-8
date:
- Sat, 06 Feb 2021 02:20:12 GMT
- Tue, 09 Mar 2021 22:53:21 GMT
expires:
- '-1'
pragma:
Expand All @@ -133,11 +133,11 @@ interactions:
x-content-type-options:
- nosniff
x-ms-keyvault-network-info:
- conn_type=Ipv4;addr=174.127.232.53;act_addr_fam=InterNetwork;
- conn_type=Ipv4;addr=172.92.159.124;act_addr_fam=InterNetwork;
x-ms-keyvault-region:
- northeurope
- westus2
x-ms-keyvault-service-version:
- 1.2.164.0
- 1.2.191.0
x-powered-by:
- ASP.NET
status:
Expand Down
Loading

0 comments on commit 6c843b8

Please sign in to comment.