|
3 | 3 | import unittest |
4 | 4 |
|
5 | 5 | from msal import mtls |
6 | | -from msal.application import _load_mtls_cert_material |
| 6 | +from msal.application import ( |
| 7 | + _load_mtls_cert_material, _private_key_to_unencrypted_pem) |
7 | 8 |
|
8 | 9 |
|
9 | 10 | class TestMtlsEndpointTransform(unittest.TestCase): |
@@ -142,5 +143,38 @@ def test_http_client_builds_session_lazily(self): |
142 | 143 | client.close() |
143 | 144 |
|
144 | 145 |
|
| 146 | +class TestUnencryptedPemLoading(unittest.TestCase): |
| 147 | + """_private_key_to_unencrypted_pem pins the cryptography backend and turns |
| 148 | + low-level load failures into a clear, actionable ValueError.""" |
| 149 | + |
| 150 | + @staticmethod |
| 151 | + def _encrypted_pem(passphrase=b"secret"): |
| 152 | + from cryptography.hazmat.primitives import serialization |
| 153 | + from cryptography.hazmat.primitives.asymmetric import rsa |
| 154 | + from cryptography.hazmat.backends import default_backend |
| 155 | + key = rsa.generate_private_key( |
| 156 | + public_exponent=65537, key_size=2048, backend=default_backend()) |
| 157 | + return key.private_bytes( |
| 158 | + serialization.Encoding.PEM, |
| 159 | + serialization.PrivateFormat.PKCS8, |
| 160 | + serialization.BestAvailableEncryption(passphrase)) |
| 161 | + |
| 162 | + def test_encrypted_key_without_passphrase_raises_clear_error(self): |
| 163 | + with self.assertRaises(ValueError) as cm: |
| 164 | + _private_key_to_unencrypted_pem(self._encrypted_pem(), None) |
| 165 | + self.assertIn("passphrase", str(cm.exception)) |
| 166 | + |
| 167 | + def test_garbage_key_raises_clear_error(self): |
| 168 | + with self.assertRaises(ValueError) as cm: |
| 169 | + _private_key_to_unencrypted_pem(b"not a real pem", None) |
| 170 | + self.assertIn("private key for mTLS", str(cm.exception)) |
| 171 | + |
| 172 | + def test_encrypted_key_with_passphrase_round_trips_to_unencrypted_pem(self): |
| 173 | + pem = _private_key_to_unencrypted_pem( |
| 174 | + self._encrypted_pem(b"secret"), b"secret") |
| 175 | + self.assertIn(b"PRIVATE KEY", pem) |
| 176 | + self.assertNotIn(b"ENCRYPTED", pem) |
| 177 | + |
| 178 | + |
145 | 179 | if __name__ == "__main__": |
146 | 180 | unittest.main() |
0 commit comments