diff --git a/packages/google-auth/google/auth/crypt/__init__.py b/packages/google-auth/google/auth/crypt/__init__.py index e56bc7b82df7..59519b475e5b 100644 --- a/packages/google-auth/google/auth/crypt/__init__.py +++ b/packages/google-auth/google/auth/crypt/__init__.py @@ -38,14 +38,35 @@ """ from google.auth.crypt import base -from google.auth.crypt import es -from google.auth.crypt import es256 from google.auth.crypt import rsa -EsSigner = es.EsSigner -EsVerifier = es.EsVerifier -ES256Signer = es256.ES256Signer -ES256Verifier = es256.ES256Verifier +# google.auth.crypt.es depends on the crytpography module which may not be +# successfully imported depending on the system. +try: + from google.auth.crypt import es + from google.auth.crypt import es256 +except ImportError: # pragma: NO COVER + es = None # type: ignore + es256 = None # type: ignore + +if es is not None and es256 is not None: # pragma: NO COVER + __all__ = [ + "EsSigner", + "EsVerifier", + "ES256Signer", + "ES256Verifier", + "RSASigner", + "RSAVerifier", + "Signer", + "Verifier", + ] + + EsSigner = es.EsSigner + EsVerifier = es.EsVerifier + ES256Signer = es256.ES256Signer + ES256Verifier = es256.ES256Verifier +else: # pragma: NO COVER + __all__ = ["RSASigner", "RSAVerifier", "Signer", "Verifier"] # Aliases to maintain the v1.0.0 interface, as the crypt module was split @@ -82,15 +103,3 @@ class to use for verification. This can be used to select different if verifier.verify(message, signature): return True return False - - -__all__ = [ - "EsSigner", - "EsVerifier", - "ES256Signer", - "ES256Verifier", - "RSASigner", - "RSAVerifier", - "Signer", - "Verifier", -] diff --git a/packages/google-auth/google/auth/crypt/_python_rsa.py b/packages/google-auth/google/auth/crypt/_python_rsa.py index d9305e835dc9..e553c25ed564 100644 --- a/packages/google-auth/google/auth/crypt/_python_rsa.py +++ b/packages/google-auth/google/auth/crypt/_python_rsa.py @@ -22,7 +22,6 @@ from __future__ import absolute_import import io -import warnings from pyasn1.codec.der import decoder # type: ignore from pyasn1_modules import pem # type: ignore @@ -40,11 +39,6 @@ _PKCS8_MARKER = ("-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----") _PKCS8_SPEC = PrivateKeyInfo() -_warning_msg = ( - "The 'rsa' library is deprecated and will be removed in a future release. " - "Please migrate to 'cryptography'." -) - def _bit_list_to_bytes(bit_list): """Converts an iterable of 1s and 0s to bytes. @@ -70,21 +64,12 @@ def _bit_list_to_bytes(bit_list): class RSAVerifier(base.Verifier): """Verifies RSA cryptographic signatures using public keys. - .. deprecated:: - The `rsa` library has been archived. Please migrate to - `cryptography`. - Args: public_key (rsa.key.PublicKey): The public key used to verify signatures. """ def __init__(self, public_key): - warnings.warn( - _warning_msg, - category=DeprecationWarning, - stacklevel=2, - ) self._pubkey = public_key @_helpers.copy_docstring(base.Verifier) @@ -131,10 +116,6 @@ def from_string(cls, public_key): class RSASigner(base.Signer, base.FromServiceAccountMixin): """Signs messages with an RSA private key. - .. deprecated:: - The `rsa` library has been archived. Please migrate to - `cryptography`. - Args: private_key (rsa.key.PrivateKey): The private key to sign with. key_id (str): Optional key ID used to identify this private key. This @@ -143,11 +124,6 @@ class RSASigner(base.Signer, base.FromServiceAccountMixin): """ def __init__(self, private_key, key_id=None): - warnings.warn( - _warning_msg, - category=DeprecationWarning, - stacklevel=2, - ) self._key = private_key self._key_id = key_id diff --git a/packages/google-auth/google/auth/crypt/es.py b/packages/google-auth/google/auth/crypt/es.py index dbbe56b3f8fb..f9466af3c44f 100644 --- a/packages/google-auth/google/auth/crypt/es.py +++ b/packages/google-auth/google/auth/crypt/es.py @@ -102,7 +102,7 @@ def verify(self, message: bytes, signature: bytes) -> bool: @classmethod def from_string(cls, public_key: Union[str, bytes]) -> "EsVerifier": - """Construct a Verifier instance from a public key or public + """Construct an Verifier instance from a public key or public certificate string. Args: @@ -110,7 +110,7 @@ def from_string(cls, public_key: Union[str, bytes]) -> "EsVerifier": x509 public key certificate. Returns: - google.auth.crypt.Verifier: The constructed verifier. + Verifier: The constructed verifier. Raises: ValueError: If the public key can't be parsed. diff --git a/packages/google-auth/google/auth/crypt/rsa.py b/packages/google-auth/google/auth/crypt/rsa.py index 639be9069549..ed842d1eb8ef 100644 --- a/packages/google-auth/google/auth/crypt/rsa.py +++ b/packages/google-auth/google/auth/crypt/rsa.py @@ -12,121 +12,19 @@ # See the License for the specific language governing permissions and # limitations under the License. -""" -RSA cryptography signer and verifier. +"""RSA cryptography signer and verifier.""" -This file provides a shared wrapper, that defers to _python_rsa or _cryptography_rsa -for implmentations using different third party libraries -""" -from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey -from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey +try: + # Prefer cryptograph-based RSA implementation. + from google.auth.crypt import _cryptography_rsa -from google.auth import _helpers -from google.auth.crypt import _cryptography_rsa -from google.auth.crypt import base + RSASigner = _cryptography_rsa.RSASigner + RSAVerifier = _cryptography_rsa.RSAVerifier +except ImportError: # pragma: NO COVER + # Fallback to pure-python RSA implementation if cryptography is + # unavailable. + from google.auth.crypt import _python_rsa -RSA_KEY_MODULE_PREFIX = "rsa.key" - - -class RSAVerifier(base.Verifier): - """Verifies RSA cryptographic signatures using public keys. - - Args: - public_key (Union["rsa.key.PublicKey", cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey]): - The public key used to verify signatures. - Raises: - ImportError: if called with an rsa.key.PublicKey, when the rsa library is not installed - ValueError: if an unrecognized public key is provided - """ - - def __init__(self, public_key): - module_str = public_key.__class__.__module__ - if isinstance(public_key, RSAPublicKey): - impl_lib = _cryptography_rsa - elif module_str.startswith(RSA_KEY_MODULE_PREFIX): - from google.auth.crypt import _python_rsa - - impl_lib = _python_rsa - else: - raise ValueError(f"unrecognized public key type: {type(public_key)}") - self._impl = impl_lib.RSAVerifier(public_key) - - @_helpers.copy_docstring(base.Verifier) - def verify(self, message, signature): - return self._impl.verify(message, signature) - - @classmethod - def from_string(cls, public_key): - """Construct a Verifier instance from a public key or public - certificate string. - - Args: - public_key (Union[str, bytes]): The public key in PEM format or the - x509 public key certificate. - - Returns: - google.auth.crypt.Verifier: The constructed verifier. - - Raises: - ValueError: If the public_key can't be parsed. - """ - instance = cls.__new__(cls) - instance._impl = _cryptography_rsa.RSAVerifier.from_string(public_key) - return instance - - -class RSASigner(base.Signer, base.FromServiceAccountMixin): - """Signs messages with an RSA private key. - - Args: - private_key (Union["rsa.key.PrivateKey", cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey]): - The private key to sign with. - key_id (str): Optional key ID used to identify this private key. This - can be useful to associate the private key with its associated - public key or certificate. - - Raises: - ImportError: if called with an rsa.key.PrivateKey, when the rsa library is not installed - ValueError: if an unrecognized public key is provided - """ - - def __init__(self, private_key, key_id=None): - module_str = private_key.__class__.__module__ - if isinstance(private_key, RSAPrivateKey): - impl_lib = _cryptography_rsa - elif module_str.startswith(RSA_KEY_MODULE_PREFIX): - from google.auth.crypt import _python_rsa - - impl_lib = _python_rsa - else: - raise ValueError(f"unrecognized private key type: {type(private_key)}") - self._impl = impl_lib.RSASigner(private_key, key_id=key_id) - - @property # type: ignore - @_helpers.copy_docstring(base.Signer) - def key_id(self): - return self._impl.key_id - - @_helpers.copy_docstring(base.Signer) - def sign(self, message): - return self._impl.sign(message) - - @classmethod - def from_string(cls, key, key_id=None): - """Construct a Signer instance from a private key in PEM format. - - Args: - key (str): Private key in PEM format. - key_id (str): An optional key id used to identify the private key. - - Returns: - google.auth.crypt.Signer: The constructed signer. - - Raises: - ValueError: If the key cannot be parsed as PKCS#1 or PKCS#8 in - PEM format. - """ - instance = cls.__new__(cls) - instance._impl = _cryptography_rsa.RSASigner.from_string(key, key_id=key_id) - return instance + RSASigner = _python_rsa.RSASigner # type: ignore + RSAVerifier = _python_rsa.RSAVerifier # type: ignore diff --git a/packages/google-auth/noxfile.py b/packages/google-auth/noxfile.py index ca829fa96030..251f5bc772a4 100644 --- a/packages/google-auth/noxfile.py +++ b/packages/google-auth/noxfile.py @@ -41,7 +41,7 @@ "3.13", "3.14", ] -ALL_PYTHON = UNIT_TEST_PYTHON_VERSIONS.copy() +ALL_PYTHON = UNIT_TEST_PYTHON_VERSIONS ALL_PYTHON.extend(["3.7"]) # Error if a python version is missing @@ -100,7 +100,7 @@ def blacken(session): @nox.session(python=DEFAULT_PYTHON_VERSION) def mypy(session): """Verify type hints are mypy compatible.""" - session.install("-e", ".[aiohttp,rsa]") + session.install("-e", ".[aiohttp]") session.install( "mypy", "types-certifi", @@ -115,29 +115,16 @@ def mypy(session): @nox.session(python=ALL_PYTHON) -@nox.parametrize(["install_deprecated_extras"], (True, False)) -def unit(session, install_deprecated_extras): +def unit(session): # Install all test dependencies, then install this package in-place. if session.python in ("3.7",): session.skip("Python 3.7 is no longer supported") - min_py, max_py = UNIT_TEST_PYTHON_VERSIONS[0], UNIT_TEST_PYTHON_VERSIONS[-1] - if not install_deprecated_extras and session.python not in (min_py, max_py): - # only run double tests on first and last supported versions - session.skip( - f"Extended tests only run on boundary Python versions ({min_py}, {max_py}) to reduce CI load." - ) constraints_path = str( CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" ) - extras_str = "testing" - if install_deprecated_extras: - # rsa and oauth2client were both archived and support dropped, - # but we still test old code paths - session.install("oauth2client") - extras_str += ",rsa" - session.install("-e", f".[{extras_str}]", "-c", constraints_path) + session.install("-e", ".[testing]", "-c", constraints_path) session.run( "pytest", f"--junitxml=unit_{session.python}_sponge_log.xml", @@ -148,7 +135,6 @@ def unit(session, install_deprecated_extras): "--cov-report=term-missing", "tests", "tests_async", - *session.posargs, ) diff --git a/packages/google-auth/setup.py b/packages/google-auth/setup.py index 8a66b7c39d0e..74036339aedf 100644 --- a/packages/google-auth/setup.py +++ b/packages/google-auth/setup.py @@ -18,39 +18,42 @@ from setuptools import find_namespace_packages from setuptools import setup -cryptography_base_require = [ - "cryptography >= 38.0.3", -] DEPENDENCIES = ( "pyasn1-modules>=0.2.1", - cryptography_base_require, + # rsa==4.5 is the last version to support 2.7 + # https://github.com/sybrenstuvel/python-rsa/issues/152#issuecomment-643470233 + "rsa>=3.1.4,<5", ) +cryptography_base_require = [ + "cryptography >= 38.0.3", +] + requests_extra_require = ["requests >= 2.20.0, < 3.0.0"] aiohttp_extra_require = ["aiohttp >= 3.6.2, < 4.0.0", *requests_extra_require] -pyjwt_extra_require = ["pyjwt>=2.0"] +pyjwt_extra_require = ["pyjwt>=2.0", *cryptography_base_require] reauth_extra_require = ["pyu2f>=0.1.5"] -# TODO(https://github.com/googleapis/google-auth-library-python/issues/1738): Add bounds for pyopenssl dependency. -enterprise_cert_extra_require = ["pyopenssl"] +# TODO(https://github.com/googleapis/google-auth-library-python/issues/1738): Add bounds for cryptography and pyopenssl dependencies. +enterprise_cert_extra_require = ["cryptography", "pyopenssl"] -pyopenssl_extra_require = ["pyopenssl>=20.0.0"] +pyopenssl_extra_require = ["pyopenssl>=20.0.0", cryptography_base_require] # TODO(https://github.com/googleapis/google-auth-library-python/issues/1739): Add bounds for urllib3 and packaging dependencies. urllib3_extra_require = ["urllib3", "packaging"] -rsa_extra_require = ["rsa>=3.1.4,<5"] - # Unit test requirements. testing_extra_require = [ # TODO(https://github.com/googleapis/google-auth-library-python/issues/1735): Remove `grpcio` from testing requirements once an extra is added for `grpcio` dependency. "grpcio", "flask", "freezegun", + # TODO(https://github.com/googleapis/google-auth-library-python/issues/1736): Remove `oauth2client` from testing requirements once an extra is added for `oauth2client` dependency. + "oauth2client", *pyjwt_extra_require, "pytest", "pytest-cov", @@ -73,7 +76,6 @@ ] extras = { - # Note: cryptography was made into a required dependency. Extra is kept for backwards compatibility "cryptography": cryptography_base_require, "aiohttp": aiohttp_extra_require, "enterprise_cert": enterprise_cert_extra_require, @@ -83,7 +85,6 @@ "requests": requests_extra_require, "testing": testing_extra_require, "urllib3": urllib3_extra_require, - "rsa": rsa_extra_require, # TODO(https://github.com/googleapis/google-auth-library-python/issues/1735): Add an extra for `grpcio` dependency. # TODO(https://github.com/googleapis/google-auth-library-python/issues/1736): Add an extra for `oauth2client` dependency. } diff --git a/packages/google-auth/testing/constraints-3.8.txt b/packages/google-auth/testing/constraints-3.8.txt index 3ca0e8edb179..5eba7b60e183 100644 --- a/packages/google-auth/testing/constraints-3.8.txt +++ b/packages/google-auth/testing/constraints-3.8.txt @@ -7,6 +7,7 @@ # Then this file should have foo==1.14.0 pyasn1-modules==0.2.1 setuptools==40.3.0 +rsa==3.1.4 cryptography==38.0.3 aiohttp==3.6.2 requests==2.20.0 diff --git a/packages/google-auth/tests/crypt/test__python_rsa.py b/packages/google-auth/tests/crypt/test__python_rsa.py index 7d0b651e3380..ee14ed9f3f8f 100644 --- a/packages/google-auth/tests/crypt/test__python_rsa.py +++ b/packages/google-auth/tests/crypt/test__python_rsa.py @@ -19,11 +19,7 @@ from pyasn1_modules import pem # type: ignore import pytest # type: ignore - -try: - import rsa -except ImportError: - pytest.skip("rsa module not available", allow_module_level=True) +import rsa # type: ignore from google.auth import _helpers from google.auth.crypt import _python_rsa @@ -195,13 +191,3 @@ def test_from_service_account_file(self): assert signer.key_id == SERVICE_ACCOUNT_INFO[base._JSON_FILE_PRIVATE_KEY_ID] assert isinstance(signer._key, rsa.key.PrivateKey) - - -class TestModule(object): - def test_import_warning(self): - from google.auth.crypt import _python_rsa - - with pytest.warns(DeprecationWarning, match="The 'rsa' library is deprecated"): - _python_rsa.RSAVerifier(None) - with pytest.warns(DeprecationWarning, match="The 'rsa' library is deprecated"): - _python_rsa.RSASigner(None) diff --git a/packages/google-auth/tests/crypt/test_rsa.py b/packages/google-auth/tests/crypt/test_rsa.py deleted file mode 100644 index a54beb7632cf..000000000000 --- a/packages/google-auth/tests/crypt/test_rsa.py +++ /dev/null @@ -1,185 +0,0 @@ -# Copyright 2026 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -from unittest import mock - -from cryptography.hazmat import backends -from cryptography.hazmat.primitives import serialization -import pytest - -try: - import rsa as rsa_lib - from google.auth.crypt import _python_rsa -except ImportError: - rsa_lib = None # type: ignore - _pyrhon_rsa = None # type: ignore - -from google.auth.crypt import _cryptography_rsa -from google.auth.crypt import rsa - - -DATA_DIR = os.path.join(os.path.dirname(__file__), "..", "data") - - -@pytest.fixture -def private_key_bytes(): - with open(os.path.join(DATA_DIR, "privatekey.pem"), "rb") as fh: - return fh.read() - - -@pytest.fixture -def public_key_bytes(): - with open(os.path.join(DATA_DIR, "privatekey.pub"), "rb") as fh: - return fh.read() - - -@pytest.fixture -def cryptography_private_key(private_key_bytes): - return serialization.load_pem_private_key( - private_key_bytes, password=None, backend=backends.default_backend() - ) - - -@pytest.fixture -def rsa_private_key(private_key_bytes): - return rsa_lib.PrivateKey.load_pkcs1(private_key_bytes) - - -@pytest.fixture -def cryptography_public_key(public_key_bytes): - return serialization.load_pem_public_key( - public_key_bytes, backend=backends.default_backend() - ) - - -@pytest.fixture -def rsa_public_key(public_key_bytes): - return rsa_lib.PublicKey.load_pkcs1(public_key_bytes) - - -class TestRSAVerifier: - def test_init_with_cryptography_key(self, cryptography_public_key): - verifier = rsa.RSAVerifier(cryptography_public_key) - assert isinstance(verifier._impl, _cryptography_rsa.RSAVerifier) - assert verifier._impl._pubkey == cryptography_public_key - - @pytest.mark.skipif(not rsa_lib, reason="rsa library not installed") - def test_init_with_rsa_key(self, rsa_public_key): - verifier = rsa.RSAVerifier(rsa_public_key) - assert isinstance(verifier._impl, _python_rsa.RSAVerifier) - assert verifier._impl._pubkey == rsa_public_key - - @pytest.mark.skipif(not rsa_lib, reason="rsa library not installed") - def test_warning_with_rsa(self, rsa_public_key): - with pytest.warns(DeprecationWarning, match="The 'rsa' library is deprecated"): - rsa.RSAVerifier(rsa_public_key) - - def test_init_with_unknown_key(self): - unknown_key = object() - - with pytest.raises(ValueError): - rsa.RSAVerifier(unknown_key) - - def test_verify_delegates(self, cryptography_public_key): - verifier = rsa.RSAVerifier(cryptography_public_key) - - # Mock the implementation's verify method - with mock.patch.object( - verifier._impl, "verify", return_value=True - ) as mock_verify: - result = verifier.verify(b"message", b"signature") - assert result is True - mock_verify.assert_called_once_with(b"message", b"signature") - - @mock.patch("google.auth.crypt.rsa._cryptography_rsa") - def test_from_string_cryptography(self, mock_crypto, public_key_bytes): - expected_verifier = mock.Mock() - mock_crypto.RSAVerifier.from_string.return_value = expected_verifier - - result = rsa.RSAVerifier.from_string(public_key_bytes) - - assert result._impl == expected_verifier - mock_crypto.RSAVerifier.from_string.assert_called_once_with(public_key_bytes) - - -class TestRSASigner: - def test_init_with_cryptography_key(self, cryptography_private_key): - signer = rsa.RSASigner(cryptography_private_key, key_id="123") - assert isinstance(signer._impl, _cryptography_rsa.RSASigner) - assert signer._impl._key == cryptography_private_key - assert signer._impl.key_id == "123" - - @pytest.mark.skipif(not rsa_lib, reason="rsa library not installed") - def test_init_with_rsa_key(self, rsa_private_key): - signer = rsa.RSASigner(rsa_private_key, key_id="123") - assert isinstance(signer._impl, _python_rsa.RSASigner) - assert signer._impl._key == rsa_private_key - assert signer._impl.key_id == "123" - - @pytest.mark.skipif(not rsa_lib, reason="rsa library not installed") - def test_warning_with_rsa(self, rsa_private_key): - with pytest.warns(DeprecationWarning, match="The 'rsa' library is deprecated"): - rsa.RSASigner(rsa_private_key, key_id="123") - - def test_init_with_unknown_key(self): - unknown_key = object() - - with pytest.raises(ValueError): - rsa.RSASigner(unknown_key) - - def test_sign_delegates(self, cryptography_private_key): - signer = rsa.RSASigner(cryptography_private_key) - - with mock.patch.object( - signer._impl, "sign", return_value=b"signature" - ) as mock_sign: - result = signer.sign(b"message") - assert result == b"signature" - mock_sign.assert_called_once_with(b"message") - - @mock.patch("google.auth.crypt.rsa._cryptography_rsa") - def test_from_string_delegates_to_cryptography( - self, mock_crypto, private_key_bytes - ): - expected_signer = mock.Mock() - mock_crypto.RSASigner.from_string.return_value = expected_signer - - result = rsa.RSASigner.from_string(private_key_bytes, key_id="123") - - assert result._impl == expected_signer - mock_crypto.RSASigner.from_string.assert_called_once_with( - private_key_bytes, key_id="123" - ) - - def test_end_to_end_cryptography_lib(self, private_key_bytes, public_key_bytes): - signer = rsa.RSASigner.from_string(private_key_bytes) - message = b"Hello World" - sig = signer.sign(message) - verifier = rsa.RSAVerifier.from_string(public_key_bytes) - result = verifier.verify(message, sig) - assert result is True - assert isinstance(verifier._impl, _cryptography_rsa.RSAVerifier) - assert isinstance(signer._impl, _cryptography_rsa.RSASigner) - - @pytest.mark.skipif(not rsa_lib, reason="rsa library not installed") - def test_end_to_end_rsa_lib(self, rsa_private_key, rsa_public_key): - signer = rsa.RSASigner(rsa_private_key) - message = b"Hello World" - sig = signer.sign(message) - verifier = rsa.RSAVerifier(rsa_public_key) - result = verifier.verify(message, sig) - assert bool(result) is True - assert isinstance(verifier._impl, _python_rsa.RSAVerifier) - assert isinstance(signer._impl, _python_rsa.RSASigner) diff --git a/packages/google-auth/tests/test_jwt.py b/packages/google-auth/tests/test_jwt.py index 4c5988469494..9502bc32ee87 100644 --- a/packages/google-auth/tests/test_jwt.py +++ b/packages/google-auth/tests/test_jwt.py @@ -129,7 +129,7 @@ def factory( # False is specified to remove the signer's key id for testing # headers without key ids. if key_id is False: - signer._impl._key_id = None + signer._key_id = None key_id = None if use_es256_signer: