ThalesGroup / pycryptoki

Python interface to SafeNet's PKCS11 library implementation
Apache License 2.0
59 stars 22 forks source link

Pythonic open/close interface (adding "with" support) #54

Open zaicruvoir1rominet opened 1 month ago

zaicruvoir1rominet commented 1 month ago

Hi there !

I'm wondering if you would be open to augmenting pycryptoki with context managers (with block ...) support. This would allow exceptions to propagate normally in pycryptoki code and make forgetting to close/logout/finalize/... functions or accidentally calling close/logout/finalize/... functions when you aren't supposed to impossible.

Current situation

import pycryptoki.session_management

pycryptoki.session_management.c_initialize_ex()

# ... some code ...
raise ValueError("There's a problem here !")
# ... some code ...

pycryptoki.session_management.c_finalize_ex()

The above code would prevent pycryptoki's c_finalize_ex to properly execute.

Potential solution

Make open/logout/initialize functions return context managers:

import pycryptoki.session_management

with pycryptoki.session_management.c_initialize_ex():
    # ... some code ...
    raise ValueError("There's a problem here !")
    # ... some code ...

There is no need to call c_finalize_ex, it is automatically executed in case of an exception or when leaving the with block.
(The context manager returned by c_initialize_ex would also be possible to be interpreted as a "normal" return value, in case user want to fetch this, and to avoid introducing breaking changes).

astraw38 commented 1 month ago

Hi @zaicruvoir1rominet , check out the classes here, which can be used:

with Session(slot) as session:
     c_generate_key_ex(session, ...)
zaicruvoir1rominet commented 1 month ago

Nice !

Would you mind me updating the docs, to make these easier to find ?