From c9eb033485a214e2fbd5644cd3a1415f786754ed Mon Sep 17 00:00:00 2001 From: Matthias Valvekens Date: Tue, 5 Mar 2024 03:57:41 +0100 Subject: [PATCH] Improve error handling for PKCS#11 init issues --- pyhanko/sign/pkcs11.py | 24 ++++++++++++------------ pyhanko_tests/test_pkcs11.py | 14 ++++++++++++++ 2 files changed, 26 insertions(+), 12 deletions(-) diff --git a/pyhanko/sign/pkcs11.py b/pyhanko/sign/pkcs11.py index d0abb53f..7f6d8786 100644 --- a/pyhanko/sign/pkcs11.py +++ b/pyhanko/sign/pkcs11.py @@ -720,12 +720,17 @@ def _instantiate(self) -> PKCS11Signer: config = self.config pin = self._handle_pin() - self._session = session = open_pkcs11_session( - config.module_path, - slot_no=config.slot_no, - token_criteria=config.token_criteria, - user_pin=pin, - ) + try: + self._session = session = open_pkcs11_session( + config.module_path, + slot_no=config.slot_no, + token_criteria=config.token_criteria, + user_pin=pin, + ) + except pkcs11.PKCS11Error as ex: + raise SigningError( + f"PKCS#11 error while opening session to {config.module_path}: [{type(ex).__name__}] {ex}" + ) from ex return PKCS11Signer( session, config.cert_label, @@ -741,12 +746,7 @@ def _instantiate(self) -> PKCS11Signer: ) def __enter__(self): - try: - return self._instantiate() - except pkcs11.PKCS11Error as ex: # pragma: nocover - raise SigningError( - f"PKCS#11 error: [{type(ex).__name__}] {ex}" - ) from ex + return self._instantiate() async def __aenter__(self): loop = asyncio.get_running_loop() diff --git a/pyhanko_tests/test_pkcs11.py b/pyhanko_tests/test_pkcs11.py index 645f3ecb..8487365d 100644 --- a/pyhanko_tests/test_pkcs11.py +++ b/pyhanko_tests/test_pkcs11.py @@ -410,6 +410,20 @@ def test_simple_sign_from_config(): val_trusted(emb) +def test_config_init_failure_signing_error(): + config = PKCS11SignatureConfig( + module_path='.', + token_criteria=TokenCriteria('testrsa'), + cert_label=SIGNER_LABEL, + user_pin='1234', + other_certs_to_pull=None, + ) + + with pytest.raises(SigningError, match='error while opening session'): + with PKCS11SigningContext(config): + pass + + @freeze_time('2020-11-01') def test_sign_skip_login_fail(): w = IncrementalPdfFileWriter(BytesIO(MINIMAL))