Debian Codegraph @

src/nitrokey/trussed/_base.py

raw
1 # Copyright 2021-2024 Nitrokey Developers
2 #
3 # Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4 # http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5 # http://opensource.org/licenses/MIT>, at your option. This file may not be
6 # copied, modified, or distributed except according to those terms.
7
8 from abc import ABC, abstractmethod
9 from enum import Enum
10 from types import TracebackType
11 from typing import Optional, TypeVar
12
13 from nitrokey import _VID_NITROKEY
14
15 from ._utils import Uuid
16
17 T = TypeVar("T", bound="TrussedBase")
18
19
20 class Model(Enum):
21 NK3 = "Nitrokey 3"
22 NKPK = "Nitrokey Passkey"
23
24 def __str__(self) -> str:
25 return self.value
26
27 @classmethod
28 def from_str(cls, s: str) -> "Model":
29 for model in cls:
30 if model.value == s:
31 return model
32 raise ValueError(f"Unknown model {s}")
33
34
35 class TrussedBase(ABC):
36 """
37 Base class for Nitrokey devices using the Trussed framework and running
38 the firmware or the bootloader.
39 """
40
41 def __enter__(self: T) -> T:
42 return self
43
44 def __exit__(
45 self,
46 exc_type: Optional[type[BaseException]],
47 exc_val: Optional[BaseException],
48 exc_tb: Optional[TracebackType],
49 ) -> None:
50 self.close()
51
52 def _validate_vid_pid(self, vid: int, pid: int) -> None:
53 if (vid, pid) != (self.vid, self.pid):
54 raise ValueError(
55 f"Not a {self.name} device: expected VID:PID "
56 f"{self.vid:x}:{self.pid:x}, got {vid:x}:{pid:x}"
57 )
58
59 @property
60 @abstractmethod
61 def model(self) -> Model: ...
62
63 @property
64 def vid(self) -> int:
65 return _VID_NITROKEY
66
67 @property
68 @abstractmethod
69 def pid(self) -> int: ...
70
71 @property
72 @abstractmethod
73 def path(self) -> Optional[str]: ...
74
75 @property
76 @abstractmethod
77 def name(self) -> str: ...
78
79 @abstractmethod
80 def close(self) -> None: ...
81
82 @abstractmethod
83 def reboot(self) -> bool: ...
84
85 @abstractmethod
86 def uuid(self) -> Optional[Uuid]: ...