Skip to content

Commit

Permalink
Improve error handling for PKCS#11 init issues
Browse files Browse the repository at this point in the history
  • Loading branch information
MatthiasValvekens committed Mar 5, 2024
1 parent 43afd54 commit c9eb033
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 12 deletions.
24 changes: 12 additions & 12 deletions pyhanko/sign/pkcs11.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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()
Expand Down
14 changes: 14 additions & 0 deletions pyhanko_tests/test_pkcs11.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down

0 comments on commit c9eb033

Please sign in to comment.