-
Notifications
You must be signed in to change notification settings - Fork 0
fix: Fix private key normalization error and raise a clear ValueError instead of a pyasn1 error when a private key cannot be loaded
#64
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| import base64 | ||
| import sys | ||
| import unittest | ||
| from unittest.mock import MagicMock, patch | ||
|
|
||
| from .common import load_key | ||
| from mauth_client.lambda_helper import _get_private_key | ||
|
|
||
| PRIVATE_KEY = load_key("priv").strip() | ||
| PRIVATE_KEY_PKCS8 = load_key("pkcs8").strip() | ||
|
|
||
|
|
||
| class TestGetPrivateKey(unittest.TestCase): | ||
| def _get_key(self, configured_key): | ||
| with patch("mauth_client.lambda_helper.Config") as config: | ||
| config.PRIVATE_KEY = configured_key | ||
| return _get_private_key() | ||
|
|
||
| def test_returns_key_unchanged(self): | ||
| self.assertEqual(self._get_key(PRIVATE_KEY), PRIVATE_KEY) | ||
|
|
||
| def test_normalizes_one_liner_with_spaces(self): | ||
| self.assertEqual(self._get_key(PRIVATE_KEY.replace("\n", " ")), PRIVATE_KEY) | ||
|
|
||
| def test_normalizes_one_liner_with_escaped_newlines(self): | ||
| self.assertEqual(self._get_key(PRIVATE_KEY.replace("\n", "\\n")), PRIVATE_KEY) | ||
|
|
||
| def test_returns_pkcs8_key_unchanged(self): | ||
| self.assertEqual(self._get_key(PRIVATE_KEY_PKCS8), PRIVATE_KEY_PKCS8) | ||
|
|
||
| def test_normalizes_pkcs8_one_liner_with_spaces(self): | ||
| self.assertEqual(self._get_key(PRIVATE_KEY_PKCS8.replace("\n", " ")), PRIVATE_KEY_PKCS8) | ||
|
|
||
| def test_normalizes_pkcs8_one_liner_with_escaped_newlines(self): | ||
| self.assertEqual(self._get_key(PRIVATE_KEY_PKCS8.replace("\n", "\\n")), PRIVATE_KEY_PKCS8) | ||
|
|
||
| def test_missing_key(self): | ||
| self.assertIsNone(self._get_key(None)) | ||
|
|
||
| def test_encrypted_key_is_decrypted_with_kms(self): | ||
| ciphertext = base64.b64encode(b"encrypted-key-blob").decode("ascii") | ||
| kms_client = MagicMock() | ||
| kms_client.decrypt.return_value = {"Plaintext": PRIVATE_KEY.replace("\n", "\\n").encode("ascii")} | ||
| boto3 = MagicMock() | ||
| boto3.client.return_value = kms_client | ||
|
|
||
| with patch.dict(sys.modules, {"boto3": boto3}): | ||
| key = self._get_key(ciphertext) | ||
|
|
||
| kms_client.decrypt.assert_called_once_with(CiphertextBlob=b"encrypted-key-blob") | ||
| self.assertEqual(key, PRIVATE_KEY) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| import base64 | ||
| import unittest | ||
|
|
||
| import rsa | ||
| from pyasn1.error import PyAsn1Error | ||
|
|
||
| from .common import load_key | ||
| from mauth_client.rsa_signer import RSASigner | ||
|
|
||
| LOAD_ERROR_MESSAGE = "Unable to load private key as PKCS#1 or PKCS#8 PEM" | ||
|
|
||
| # Valid base64, but the decoded bytes are not a DER structure. This is what a PEM block looks | ||
| # like when the body has been corrupted, e.g. by escaped "\n" sequences being left in the body | ||
| # or by a still-encrypted (KMS ciphertext) value being wrapped in PEM markers. | ||
| GARBAGE_BODY = base64.b64encode(b"this is not DER at all" * 20).decode("ascii") | ||
| GARBAGE_BODY = "\n".join(GARBAGE_BODY[i:i + 64] for i in range(0, len(GARBAGE_BODY), 64)) | ||
|
|
||
| PKCS1_WITH_GARBAGE_BODY = f"-----BEGIN RSA PRIVATE KEY-----\n{GARBAGE_BODY}\n-----END RSA PRIVATE KEY-----" | ||
| PKCS8_WITH_GARBAGE_BODY = f"-----BEGIN PRIVATE KEY-----\n{GARBAGE_BODY}\n-----END PRIVATE KEY-----" | ||
|
|
||
|
|
||
| class LoadPrivateKeyTest(unittest.TestCase): | ||
| def test_loads_pkcs1_key(self): | ||
| self.assertIsInstance(RSASigner(load_key("priv")).private_key, rsa.PrivateKey) | ||
|
|
||
| def test_loads_pkcs8_key(self): | ||
| self.assertIsInstance(RSASigner(load_key("pkcs8")).private_key, rsa.PrivateKey) | ||
|
|
||
| def test_pyasn1_error_is_not_a_value_error(self): | ||
| # Guards the assumption behind KEY_LOAD_ERRORS: catching only ValueError is not enough, | ||
| # because pyasn1 decode failures would escape as PyAsn1Error. | ||
| self.assertFalse(issubclass(PyAsn1Error, ValueError)) | ||
|
|
||
| def test_rsa_raises_pyasn1_error_for_malformed_pkcs1_body(self): | ||
| # Documents the underlying failure the wrapper has to translate: the PEM markers parse, | ||
| # so rsa base64-decodes the body and a PyAsn1Error is triggered in decoder.decode. | ||
| with self.assertRaises(PyAsn1Error): | ||
| rsa.PrivateKey.load_pkcs1(PKCS1_WITH_GARBAGE_BODY.encode("utf-8"), "PEM") | ||
|
|
||
| def test_malformed_pkcs1_body_raises_value_error(self): | ||
| # Regression: the PKCS#1 attempt raises PyAsn1Error, which must be caught so the | ||
| # PKCS#8 fallback runs and a clear ValueError is raised instead of a pyasn1 error. | ||
| with self.assertRaises(ValueError) as ctx: | ||
| RSASigner(PKCS1_WITH_GARBAGE_BODY) | ||
| self.assertEqual(str(ctx.exception), LOAD_ERROR_MESSAGE) | ||
|
|
||
| def test_malformed_pkcs8_body_raises_value_error(self): | ||
| # Regression: here it is the PKCS#8 fallback itself that raises PyAsn1Error. | ||
| with self.assertRaises(ValueError) as ctx: | ||
| RSASigner(PKCS8_WITH_GARBAGE_BODY) | ||
| self.assertEqual(str(ctx.exception), LOAD_ERROR_MESSAGE) | ||
| self.assertIsInstance(ctx.exception.__cause__, PyAsn1Error) | ||
|
|
||
| def test_encrypted_key_wrapped_in_pem_markers_raises_value_error(self): | ||
| # The reported failure mode: a KMS-encrypted key that reached the loader still encrypted. | ||
| ciphertext = base64.b64encode(b"encrypted-key-blob" * 30).decode("ascii") | ||
| pem = f"-----BEGIN RSA PRIVATE KEY-----\n{ciphertext}\n-----END RSA PRIVATE KEY-----" | ||
| with self.assertRaises(ValueError) as ctx: | ||
| RSASigner(pem) | ||
| self.assertEqual(str(ctx.exception), LOAD_ERROR_MESSAGE) | ||
|
|
||
| def test_value_is_not_pem_at_all(self): | ||
| with self.assertRaises(ValueError) as ctx: | ||
| RSASigner("not a key") | ||
| self.assertEqual(str(ctx.exception), LOAD_ERROR_MESSAGE) | ||
|
|
||
| def test_original_error_is_chained(self): | ||
| with self.assertRaises(ValueError) as ctx: | ||
| RSASigner(PKCS1_WITH_GARBAGE_BODY) | ||
| self.assertIsNotNone(ctx.exception.__cause__) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.