Skip to content

Commit 3c95039

Browse files
authored
[Identity] Remove dependency on six (#30613)
Compatibility with Python 2.7 is no longer needed, so this finishes up the six cleanup. Signed-off-by: Paul Van Eck <paulvaneck@microsoft.com>
1 parent b499caa commit 3c95039

27 files changed

Lines changed: 61 additions & 81 deletions

sdk/identity/azure-identity/CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@
1111
### Bugs Fixed
1212

1313
### Other Changes
14+
1415
- VisualStudioCodeCredential prints an informative error message when used (as it is currently broken) ([#30385](https://github.com/Azure/azure-sdk-for-python/pull/30385))
16+
- Removed dependency on `six`. ([#30613](https://github.com/Azure/azure-sdk-for-python/pull/30613))
1517

1618
## 1.13.0 (2023-05-11)
1719

sdk/identity/azure-identity/azure/identity/_credentials/azd_cli.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
import subprocess
1212
import sys
1313
from typing import Any, Dict, List, Optional
14-
import six
1514

1615
from azure.core.credentials import AccessToken
1716
from azure.core.exceptions import ClientAuthenticationError
@@ -206,8 +205,8 @@ def _run_command(command: str, timeout: int) -> str:
206205
except OSError as ex:
207206
# failed to execute 'cmd' or '/bin/sh'
208207
error = CredentialUnavailableError(message="Failed to execute '{}'".format(args[0]))
209-
six.raise_from(error, ex)
208+
raise error from ex
210209
except Exception as ex: # pylint:disable=broad-except
211210
# could be a timeout, for example
212211
error = CredentialUnavailableError(message="Failed to invoke the Azure Developer CLI")
213-
six.raise_from(error, ex)
212+
raise error from ex

sdk/identity/azure-identity/azure/identity/_credentials/azure_cli.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
import sys
1212
import time
1313
from typing import List, Optional, Any, Dict
14-
import six
1514

1615
from azure.core.credentials import AccessToken
1716
from azure.core.exceptions import ClientAuthenticationError
@@ -184,8 +183,8 @@ def _run_command(command: str, timeout: int) -> str:
184183
except OSError as ex:
185184
# failed to execute 'cmd' or '/bin/sh'
186185
error = CredentialUnavailableError(message="Failed to execute '{}'".format(args[0]))
187-
six.raise_from(error, ex)
186+
raise error from ex
188187
except Exception as ex: # pylint:disable=broad-except
189188
# could be a timeout, for example
190189
error = CredentialUnavailableError(message="Failed to invoke the Azure CLI")
191-
six.raise_from(error, ex)
190+
raise error from ex

sdk/identity/azure-identity/azure/identity/_credentials/azure_powershell.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
import subprocess
88
import sys
99
from typing import List, Tuple, Optional, Any
10-
import six
1110

1211
from azure.core.credentials import AccessToken
1312
from azure.core.exceptions import ClientAuthenticationError
@@ -135,7 +134,7 @@ def run_command_line(command_line: List[str], timeout: int) -> str:
135134
message="Failed to invoke PowerShell.\n"
136135
"To mitigate this issue, please refer to the troubleshooting guidelines here at "
137136
"https://aka.ms/azsdk/python/identity/powershellcredential/troubleshoot.")
138-
six.raise_from(error, ex)
137+
raise error from ex
139138

140139
raise_for_error(proc.returncode, stdout, stderr)
141140
return stdout

sdk/identity/azure-identity/azure/identity/_credentials/certificate.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
from cryptography.hazmat.primitives import hashes, serialization
1010
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
1111
from cryptography.hazmat.backends import default_backend
12-
import six
1312

1413
from .._internal import validate_tenant_id
1514
from .._internal.client_credential_base import ClientCredentialBase
@@ -118,7 +117,7 @@ def load_pkcs12_certificate(
118117
)
119118
except ValueError as ex:
120119
# mentioning PEM here because we raise this error when certificate_data is garbage
121-
six.raise_from(ValueError("Failed to deserialize certificate in PEM or PKCS12 format"), ex)
120+
raise ValueError("Failed to deserialize certificate in PEM or PKCS12 format") from ex
122121
if not private_key:
123122
raise ValueError("The certificate must include its private key")
124123
if not cert:
@@ -154,8 +153,9 @@ def get_client_credential(
154153
raise ValueError('CertificateCredential requires a value for either "certificate_path" or "certificate_data"')
155154

156155
if password:
157-
# if password is already bytes, this won't change its encoding
158-
password = six.ensure_binary(password, "utf-8")
156+
# if password is already bytes, no need to encode.
157+
if isinstance(password, str):
158+
password = password.encode("utf-8")
159159
password = cast("Optional[bytes]", password)
160160

161161
if b"-----BEGIN" in certificate_data:
@@ -175,9 +175,9 @@ def get_client_credential(
175175
try:
176176
# the JWT needs the whole chain but load_pem_x509_certificate deserializes only the signing cert
177177
chain = extract_cert_chain(cert.pem_bytes)
178-
client_credential["public_certificate"] = six.ensure_str(chain)
178+
client_credential["public_certificate"] = chain.decode("utf-8")
179179
except ValueError as ex:
180180
# we shouldn't land here--cryptography already loaded the cert and would have raised if it were malformed
181-
six.raise_from(ValueError("Malformed certificate"), ex)
181+
raise ValueError("Malformed certificate") from ex
182182

183183
return client_credential

sdk/identity/azure-identity/azure/identity/_credentials/imds.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@
55
import os
66
from typing import Any, Optional, Dict
77

8-
import six
9-
108
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError
119
from azure.core.pipeline.transport import HttpRequest
1210
from azure.core.credentials import AccessToken
@@ -83,7 +81,7 @@ def _request_token(self, *scopes: str, **kwargs: Any) -> AccessToken:
8381
self._error_message = (
8482
"ManagedIdentityCredential authentication unavailable, no response from the IMDS endpoint."
8583
)
86-
six.raise_from(CredentialUnavailableError(self._error_message), ex)
84+
raise CredentialUnavailableError(self._error_message) from ex
8785

8886
if not self._endpoint_available:
8987
raise CredentialUnavailableError(self._error_message)
@@ -100,8 +98,8 @@ def _request_token(self, *scopes: str, **kwargs: Any) -> AccessToken:
10098
self._error_message += "The requested identity has not been assigned to this resource."
10199
else:
102100
self._error_message += "No identity has been assigned to this resource."
103-
six.raise_from(CredentialUnavailableError(message=self._error_message), ex)
101+
raise CredentialUnavailableError(message=self._error_message) from ex
104102

105103
# any other error is unexpected
106-
six.raise_from(ClientAuthenticationError(message=ex.message, response=ex.response), ex)
104+
raise ClientAuthenticationError(message=ex.message, response=ex.response) from ex
107105
return token

sdk/identity/azure-identity/azure/identity/_credentials/on_behalf_of.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import time
66
from typing import Any, Optional
77

8-
import six
98
import msal
109

1110
from azure.core.credentials import AccessToken
@@ -89,7 +88,7 @@ def __init__(
8988
message = (
9089
'"client_certificate" is not a valid certificate in PEM or PKCS12 format'
9190
)
92-
six.raise_from(ValueError(message), ex)
91+
raise ValueError(message) from ex
9392
elif client_secret:
9493
credential = client_secret
9594
else:

sdk/identity/azure-identity/azure/identity/_internal/aad_client_base.py

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
from uuid import uuid4
1111
from typing import TYPE_CHECKING, List, Any, Iterable, Optional, Union, Dict
1212

13-
import six
1413
from msal import TokenCache
1514

1615
from azure.core.pipeline import PipelineResponse
@@ -208,22 +207,15 @@ def _get_jwt_assertion_request(
208207

209208
def _get_client_certificate_assertion(self, certificate: AadClientCertificate, **kwargs: Any) -> str:
210209
now = int(time.time())
211-
header = six.ensure_binary(
212-
json.dumps({"typ": "JWT", "alg": "RS256", "x5t": certificate.thumbprint}), encoding="utf-8"
213-
)
214-
payload = six.ensure_binary(
215-
json.dumps(
216-
{
217-
"jti": str(uuid4()),
218-
"aud": self._get_token_url(**kwargs),
219-
"iss": self._client_id,
220-
"sub": self._client_id,
221-
"nbf": now,
222-
"exp": now + (60 * 30),
223-
}
224-
),
225-
encoding="utf-8",
226-
)
210+
header = json.dumps({"typ": "JWT", "alg": "RS256", "x5t": certificate.thumbprint}).encode("utf-8")
211+
payload = json.dumps({
212+
"jti": str(uuid4()),
213+
"aud": self._get_token_url(**kwargs),
214+
"iss": self._client_id,
215+
"sub": self._client_id,
216+
"nbf": now,
217+
"exp": now + (60 * 30),
218+
}).encode("utf-8")
227219
jws = base64.urlsafe_b64encode(header) + b"." + base64.urlsafe_b64encode(payload)
228220
signature = certificate.sign(jws)
229221
jwt_bytes = jws + b"." + base64.urlsafe_b64encode(signature)

sdk/identity/azure-identity/azure/identity/_internal/aadclient_certificate.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
from cryptography.hazmat.primitives.asymmetric import padding
1010
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
1111
from cryptography.hazmat.backends import default_backend
12-
import six
1312

1413

1514
class AadClientCertificate:
@@ -30,7 +29,7 @@ def __init__(
3029

3130
cert = x509.load_pem_x509_certificate(pem_bytes, default_backend())
3231
fingerprint = cert.fingerprint(hashes.SHA1()) # nosec
33-
self._thumbprint = six.ensure_str(base64.urlsafe_b64encode(fingerprint), encoding="utf-8")
32+
self._thumbprint = base64.urlsafe_b64encode(fingerprint).decode("utf-8")
3433

3534
@property
3635
def thumbprint(self) -> str:

sdk/identity/azure-identity/azure/identity/_internal/decorators.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
import json
88
import base64
99

10-
from six import raise_from
1110
from azure.core.exceptions import ClientAuthenticationError
1211

1312
from .utils import within_credential_chain
@@ -76,6 +75,6 @@ def wrapper(*args, **kwargs):
7675
raise
7776
except Exception as ex: # pylint:disable=broad-except
7877
auth_error = ClientAuthenticationError(message="Authentication failed: {}".format(ex))
79-
raise_from(auth_error, ex)
78+
raise auth_error from ex
8079

8180
return wrapper

0 commit comments

Comments
 (0)