Skip to content

Commit

Permalink
Add typehints and mypy.
Browse files Browse the repository at this point in the history
  • Loading branch information
dainnilsson committed Apr 13, 2021
1 parent ac42906 commit 10238f2
Show file tree
Hide file tree
Showing 12 changed files with 636 additions and 604 deletions.
5 changes: 5 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,8 @@ repos:
hooks:
- id: bandit
exclude: ^tests/
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.782
hooks:
- id: mypy
exclude: ^(tests|docs)/ # keep in sync with mypy.ini
1 change: 1 addition & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ def get_version():
# ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx_autodoc_typehints",
"sphinx.ext.doctest",
"sphinx.ext.intersphinx",
"sphinx.ext.viewcode",
Expand Down
5 changes: 5 additions & 0 deletions mypy.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[mypy]
files = yubihsm/

[mypy-usb.*]
ignore_missing_imports = True
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ usb = ["pyusb"]
pytest = "^6.0"
Sphinx = "^3.5.3"
sphinx-rtd-theme = "^0.5.1"
sphinx-autodoc-typehints = "^1.11.1"

[build-system]
requires = ["poetry-core>=1.0.0"]
Expand Down
3 changes: 2 additions & 1 deletion tests/device/test_logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from yubihsm.exceptions import YubiHsmDeviceError, YubiHsmInvalidResponseError
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from dataclasses import replace
import os
import time
import struct
Expand Down Expand Up @@ -84,7 +85,7 @@ def test_wrong_chain(session):
with pytest.raises(ValueError):
session.get_log_entries(logs.pop()) # Wrong number

wrong_line = last_line._replace(digest=os.urandom(16))
wrong_line = replace(last_line, digest=os.urandom(16))
with pytest.raises(YubiHsmInvalidResponseError):
session.get_log_entries(wrong_line)

Expand Down
14 changes: 13 additions & 1 deletion yubihsm/backends/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,21 @@

from urllib import parse
import re
import abc
from typing import Optional


def get_backend(url=None):
class YhsmBackend(abc.ABC):
"""Provides low-level communication with a YubiHSM."""

def transceive(self, msg: bytes) -> bytes:
"""Send a verbatim message."""

def close(self):
"""Closes the connection to the YubiHSM."""


def get_backend(url: Optional[str] = None) -> YhsmBackend:
"""Returns a backend suitable for the given URL."""
url = url or "http://localhost:12345"
parsed = parse.urlparse(url)
Expand Down
11 changes: 8 additions & 3 deletions yubihsm/backends/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,22 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from . import YhsmBackend
from ..exceptions import YubiHsmConnectionError
from requests.exceptions import RequestException
from urllib import parse
import requests
from typing import Optional, Union, Tuple


class HttpBackend(object):
class HttpBackend(YhsmBackend):
"""A backend for communicating with a YubiHSM connector over HTTP."""

def __init__(self, url="http://localhost:12345", timeout=None):
def __init__(
self,
url: str = "http://localhost:12345",
timeout: Optional[Union[Tuple[int, int], int]] = None,
):
"""Constructs a new HttpBackend, connecting to the given URL.
The URL should be a http(s) URL to a running YubiHSM connector.
Expand All @@ -40,7 +46,6 @@ def __init__(self, url="http://localhost:12345", timeout=None):
self._session.headers.update({"Content-Type": "application/octet-stream"})

def transceive(self, msg):
"""Send a verbatim message."""
try:
resp = self._session.post(url=self._url, data=msg, timeout=self._timeout)
resp.raise_for_status()
Expand Down
10 changes: 5 additions & 5 deletions yubihsm/backends/usb.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,24 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from . import YhsmBackend
from ..exceptions import YubiHsmConnectionError
import usb.core
import usb.util
from typing import Optional


YUBIHSM_VID = 0x1050
YUBIHSM_PID = 0x0030


class UsbBackend(object):
class UsbBackend(YhsmBackend):
"""A backend for communicating with a YubiHSM directly over USB."""

def __init__(self, serial=None):
def __init__(self, serial: Optional[int] = None):
"""Construct a UsbBackend, connected to a YubiHSM via USB.
:param int serial: (optional) The serial number of the YubiHSM to
connect to.
:param serial: (optional) The serial number of the YubiHSM to connect to.
"""
for device in usb.core.find(
find_all=True, idVendor=YUBIHSM_VID, idProduct=YUBIHSM_PID
Expand All @@ -53,7 +54,6 @@ def __init__(self, serial=None):
self.timeout = 300

def transceive(self, msg):
"""Send a verbatim message."""
try:
sent = self._device.write(0x01, msg, self.timeout * 1000)
if sent != len(msg):
Expand Down
Loading

0 comments on commit 10238f2

Please sign in to comment.