Skip to content
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
16 changes: 14 additions & 2 deletions packages/google-auth/google/auth/jwt.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,15 +63,27 @@
except ImportError: # pragma: NO COVER
es = None # type: ignore

try:
from google.auth.crypt import pqc
except ImportError: # pragma: NO COVER
pqc = None # type: ignore

_DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
_DEFAULT_MAX_CACHE_SIZE = 10
_ALGORITHM_TO_VERIFIER_CLASS = {"RS256": crypt.RSAVerifier}
_CRYPTOGRAPHY_BASED_ALGORITHMS = frozenset(["ES256", "ES384"])
_CRYPTOGRAPHY_BASED_ALGORITHMS = frozenset(
["ES256", "ES384", "ML-DSA-44", "ML-DSA-65", "ML-DSA-87"]
)

if es is not None: # pragma: NO COVER
_ALGORITHM_TO_VERIFIER_CLASS["ES256"] = es.EsVerifier # type: ignore
_ALGORITHM_TO_VERIFIER_CLASS["ES384"] = es.EsVerifier # type: ignore

if pqc is not None: # pragma: NO COVER
_ALGORITHM_TO_VERIFIER_CLASS["ML-DSA-44"] = pqc.PqcVerifier # type: ignore
_ALGORITHM_TO_VERIFIER_CLASS["ML-DSA-65"] = pqc.PqcVerifier # type: ignore
_ALGORITHM_TO_VERIFIER_CLASS["ML-DSA-87"] = pqc.PqcVerifier # type: ignore


def encode(signer, payload, header=None, key_id=None):
"""Make a signed JWT.
Expand All @@ -96,7 +108,7 @@ def encode(signer, payload, header=None, key_id=None):
header.update({"typ": "JWT"})

if "alg" not in header:
if es is not None and isinstance(signer, es.EsSigner):
if hasattr(signer, "algorithm"):
header.update({"alg": signer.algorithm})
else:
header.update({"alg": "RS256"})
Expand Down
41 changes: 5 additions & 36 deletions packages/google-auth/tests/test__service_account_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,44 +111,19 @@ def test_from_filename_es384_signer():
assert signer.algorithm == "ES384"


def test_from_dict_mldsa_signer_auto_detect_upgrade_required(monkeypatch):
def test_from_dict_mldsa_signer_auto_detect_without_mldsa(monkeypatch):
if crypt.pqc is not None:
monkeypatch.setattr(crypt.pqc, "mldsa", None)
else:
mock_pqc = mock.Mock()
mock_pqc.mldsa = None
mock_pqc.is_mldsa_key = lambda key: True
mock_pqc.PqcSigner.from_service_account_info = mock.Mock(
side_effect=RuntimeError(
"Post-Quantum ML-DSA Service Account keys require cryptography>=47.0.0. "
"Please upgrade your cryptography library (pip install 'cryptography>=47.0.0')."
)
)
monkeypatch.setattr(crypt, "pqc", mock_pqc)

der_bytes = (
b"\x30\x20\x02\x01\x00\x30\x0b"
b"\x06\x09\x60\x86\x48\x01\x65\x03\x04\x03\x12"
b"\x04\x0a\x04\x08\x00\x00\x00\x00\x00\x00\x00\x00"
)
b64_key = base64.b64encode(der_bytes).decode("ascii")
mldsa_pem = f"-----BEGIN PRIVATE KEY-----\n{b64_key}\n-----END PRIVATE KEY-----"
info = {
"private_key": mldsa_pem,
"private_key": "-----BEGIN PRIVATE KEY-----\ndGVzdA==\n-----END PRIVATE KEY-----",
"private_key_id": "test_mldsa_key_id",
"client_email": "test@example.com",
}
with pytest.raises(RuntimeError) as excinfo:
with pytest.raises(ValueError) as excinfo:
_service_account_info.from_dict(info)

assert (
"Post-Quantum ML-DSA Service Account keys require cryptography>=47.0.0"
in str(excinfo.value)
)
assert (
"Please upgrade your cryptography library (pip install 'cryptography>=47.0.0')"
in str(excinfo.value)
)
assert excinfo.match(r"(?i)(key|PEM)")


def test_from_dict_mldsa_signer_auto_detect_success(monkeypatch):
Expand All @@ -158,13 +133,7 @@ class MockMLDSA65PrivateKey:
mock_mldsa = mock.Mock()
mock_mldsa.MLDSA65PrivateKey = MockMLDSA65PrivateKey

der_bytes = (
b"\x30\x20\x02\x01\x00\x30\x0b"
b"\x06\x09\x60\x86\x48\x01\x65\x03\x04\x03\x12"
b"\x04\x0a\x04\x08\x00\x00\x00\x00\x00\x00\x00\x00"
)
b64_key = base64.b64encode(der_bytes).decode("ascii")
mldsa_pem = f"-----BEGIN PRIVATE KEY-----\n{b64_key}\n-----END PRIVATE KEY-----"
mldsa_pem = "-----BEGIN PRIVATE KEY-----\ndGVzdA==\n-----END PRIVATE KEY-----"
info = {
"private_key": mldsa_pem,
"private_key_id": "test_mldsa_key_id",
Expand Down
108 changes: 108 additions & 0 deletions packages/google-auth/tests/test_jwt.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,38 @@ def test_encode_basic_es384(es384_signer):
assert header == {"typ": "JWT", "alg": "ES384", "kid": es384_signer.key_id}


def test_encode_basic_mldsa(monkeypatch):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The test_encode_basic_mldsa test should be skipped if the pqc module is not available. Use pytest.skip() to skip the entire test.

def test_encode_basic_mldsa(monkeypatch):
    if jwt.pqc is None:
        pytest.skip("pqc is not available")
References
  1. Use pytest.skip() to skip an entire test.

class MockMLDSA65PrivateKey:
def sign(self, message):
return b"mldsa-sig"

mock_mldsa = mock.Mock()
mock_mldsa.MLDSA65PrivateKey = MockMLDSA65PrivateKey
monkeypatch.setattr(crypt.pqc, "mldsa", mock_mldsa)
monkeypatch.setattr(
crypt.pqc.serialization,
"load_pem_private_key",
lambda key, password, backend: MockMLDSA65PrivateKey(),
)

der_bytes = (
b"\x30\x20\x02\x01\x00\x30\x0b"
b"\x06\x09\x60\x86\x48\x01\x65\x03\x04\x03\x12"
b"\x04\x0a\x04\x08\x00\x00\x00\x00\x00\x00\x00\x00"
)
import base64

b64_key = base64.b64encode(der_bytes).decode("ascii")
pem = f"-----BEGIN PRIVATE KEY-----\n{b64_key}\n-----END PRIVATE KEY-----"
mldsa_signer = crypt.PqcSigner.from_string(pem, "key-mldsa-65")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Use crypt.pqc.PqcSigner instead of crypt.PqcSigner because PqcSigner is defined in the pqc submodule and is not directly exposed on the parent crypt module.

Suggested change
mldsa_signer = crypt.PqcSigner.from_string(pem, "key-mldsa-65")
mldsa_signer = crypt.pqc.PqcSigner.from_string(pem, "key-mldsa-65")


test_payload = {"test": "value"}
encoded = jwt.encode(mldsa_signer, test_payload)
header, payload, _, _ = jwt._unverified_decode(encoded)
assert payload == test_payload
assert header == {"typ": "JWT", "alg": "ML-DSA-65", "kid": "key-mldsa-65"}


@pytest.fixture
def token_factory(signer, es256_signer, es384_signer):
def factory(
Expand Down Expand Up @@ -190,6 +222,82 @@ def test_decode_valid_es384(token_factory):
assert payload["metadata"]["meta"] == "data"


def test_decode_valid_mldsa(monkeypatch):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The test_decode_valid_mldsa test should be skipped if the pqc module is not available. Use pytest.skip() to skip the entire test.

def test_decode_valid_mldsa(monkeypatch):
    if jwt.pqc is None:
        pytest.skip("pqc is not available")
References
  1. Use pytest.skip() to skip an entire test.

if jwt.pqc is None:
pytest.skip("pqc is not available")

class MockMLDSA65PrivateKey:
def sign(self, message):
return b"mldsa-sig"

class MockMLDSA65PublicKey:
def verify(self, signature, message):
if signature != b"mldsa-sig":
raise ValueError("Invalid signature")

mock_mldsa = mock.Mock()
mock_mldsa.MLDSA65PrivateKey = MockMLDSA65PrivateKey
mock_mldsa.MLDSA65PublicKey = MockMLDSA65PublicKey
monkeypatch.setattr(crypt.pqc, "mldsa", mock_mldsa)
monkeypatch.setattr(
crypt.pqc.serialization,
"load_pem_private_key",
lambda key, password, backend: MockMLDSA65PrivateKey(),
)
monkeypatch.setattr(
crypt.pqc.serialization,
"load_pem_public_key",
lambda pub, backend: MockMLDSA65PublicKey(),
)

pem = "-----BEGIN PRIVATE KEY-----\ndGVzdA==\n-----END PRIVATE KEY-----"
mldsa_signer = crypt.pqc.PqcSigner.from_string(pem, "key-mldsa-65")

now = _helpers.datetime_to_secs(_helpers.utcnow())
test_payload = {"test": "value", "iat": now, "exp": now + 300}
encoded = jwt.encode(mldsa_signer, test_payload)
payload = jwt.decode(encoded, certs="mock-pubkey")
assert payload == test_payload


def test_decode_valid_mldsa44(monkeypatch):
if jwt.pqc is None:
pytest.skip("pqc is not available")

class MockMLDSA44PrivateKey:
def sign(self, message):
return b"mldsa-44-sig"

class MockMLDSA44PublicKey:
def verify(self, signature, message):
if signature != b"mldsa-44-sig":
raise ValueError("Invalid signature")

mock_mldsa = mock.Mock()
mock_mldsa.MLDSA44PrivateKey = MockMLDSA44PrivateKey
mock_mldsa.MLDSA44PublicKey = MockMLDSA44PublicKey
monkeypatch.setattr(crypt.pqc, "mldsa", mock_mldsa)
monkeypatch.setattr(
crypt.pqc.serialization,
"load_pem_private_key",
lambda key, password, backend: MockMLDSA44PrivateKey(),
)
monkeypatch.setattr(
crypt.pqc.serialization,
"load_pem_public_key",
lambda pub, backend: MockMLDSA44PublicKey(),
)

pem = "-----BEGIN PRIVATE KEY-----\ndGVzdA==\n-----END PRIVATE KEY-----"
mldsa_signer = crypt.pqc.PqcSigner.from_string(pem, "key-mldsa-44")

now = _helpers.datetime_to_secs(_helpers.utcnow())
test_payload = {"test": "value", "iat": now, "exp": now + 300}
encoded = jwt.encode(mldsa_signer, test_payload)
payload = jwt.decode(encoded, certs="mock-pubkey")
assert payload == test_payload


def test_decode_valid_with_audience(token_factory):
payload = jwt.decode(
token_factory(), certs=PUBLIC_CERT_BYTES, audience="audience@example.com"
Expand Down
Loading