| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from abc import abstractmethod |
| 4 |
from typing import Optional, Tuple, Type, TypeVar |
| 5 |
|
| 6 |
from .base_state import BaseState |
| 7 |
from .crypto_provider import HashFunction |
| 8 |
from .identity_key_pair import IdentityKeyPair |
| 9 |
from .migrations import parse_base_state_model |
| 10 |
from .models import BaseStateModel |
| 11 |
from .signed_pre_key_pair import SignedPreKeyPair |
| 12 |
from .types import Bundle, IdentityKeyFormat, Header, JSONObject |
| 13 |
|
| 14 |
|
| 15 |
__all__ = [ |
| 16 |
"State" |
| 17 |
] |
| 18 |
|
| 19 |
|
| 20 |
StateTypeT = TypeVar("StateTypeT", bound="State") |
| 21 |
|
| 22 |
|
| 23 |
class State(BaseState): |
| 24 |
""" |
| 25 |
This class is the core of this X3DH implementation. It manages the own :class:`~x3dh.types.Bundle` and |
| 26 |
offers methods to perform key agreements with other parties. Use :class:`~x3dh.base_state.BaseState` |
| 27 |
directly if manual state management is needed. Note that you can still use the methods available for |
| 28 |
manual state management, but doing so shouldn't be required. |
| 29 |
|
| 30 |
Warning: |
| 31 |
:meth:`rotate_signed_pre_key` should be called periodically to check whether the signed pre key needs |
| 32 |
to be rotated and to perform the rotation if necessary. |
| 33 |
""" |
| 34 |
|
| 35 |
def __init__(self) -> None: |
| 36 |
super().__init__() |
| 37 |
|
| 38 |
# Just the type definitions here |
| 39 |
self.__signed_pre_key_rotation_period: int |
| 40 |
self.__pre_key_refill_threshold: int |
| 41 |
self.__pre_key_refill_target: int |
| 42 |
|
| 43 |
@classmethod |
| 44 |
def create( |
| 45 |
cls: Type[StateTypeT], |
| 46 |
identity_key_format: IdentityKeyFormat, |
| 47 |
hash_function: HashFunction, |
| 48 |
info: bytes, |
| 49 |
identity_key_pair: Optional[IdentityKeyPair] = None, |
| 50 |
signed_pre_key_rotation_period: int = 7 * 24 * 60 * 60, |
| 51 |
pre_key_refill_threshold: int = 99, |
| 52 |
pre_key_refill_target: int = 100 |
| 53 |
) -> StateTypeT: |
| 54 |
""" |
| 55 |
Args: |
| 56 |
identity_key_format: The format in which the identity public key is included in bundles/headers. |
| 57 |
hash_function: A 256 or 512-bit hash function. |
| 58 |
info: A (byte) string identifying the application. |
| 59 |
signed_pre_key_rotation_period: Rotate the signed pre key after this amount of time in seconds. |
| 60 |
pre_key_refill_threshold: Threshold for refilling the pre keys. |
| 61 |
pre_key_refill_target: When less then ``pre_key_refill_threshold`` pre keys are available, |
| 62 |
generate new ones until there are ``pre_key_refill_target`` pre keys again. |
| 63 |
identity_key_pair: If set, use the given identity key pair instead of generating a new one. |
| 64 |
|
| 65 |
Returns: |
| 66 |
A configured instance of :class:`~x3dh.state.State`. |
| 67 |
""" |
| 68 |
# pylint: disable=protected-access |
| 69 |
|
| 70 |
if signed_pre_key_rotation_period < 1: |
| 71 |
raise ValueError( |
| 72 |
"Invalid value passed for the `signed_pre_key_rotation_period` parameter. The signed pre key" |
| 73 |
" rotation period must be at least one day." |
| 74 |
) |
| 75 |
|
| 76 |
if not 1 <= pre_key_refill_threshold <= pre_key_refill_target: |
| 77 |
raise ValueError( |
| 78 |
"Invalid value(s) passed for the `pre_key_refill_threshold` / `pre_key_refill_target`" |
| 79 |
" parameter(s). `pre_key_refill_threshold` must be greater than or equal to '1' and lower" |
| 80 |
" than or equal to `pre_key_refill_target`." |
| 81 |
) |
| 82 |
|
| 83 |
self = super().create(identity_key_format, hash_function, info, identity_key_pair) |
| 84 |
|
| 85 |
self.__signed_pre_key_rotation_period = signed_pre_key_rotation_period |
| 86 |
self.__pre_key_refill_threshold = pre_key_refill_threshold |
| 87 |
self.__pre_key_refill_target = pre_key_refill_target |
| 88 |
|
| 89 |
self.generate_pre_keys(pre_key_refill_target) |
| 90 |
|
| 91 |
# I believe this is a false positive by pylint |
| 92 |
self._publish_bundle(self.bundle) # pylint: disable=no-member |
| 93 |
|
| 94 |
return self |
| 95 |
|
| 96 |
#################### |
| 97 |
# abstract methods # |
| 98 |
#################### |
| 99 |
|
| 100 |
@abstractmethod |
| 101 |
def _publish_bundle(self, bundle: Bundle) -> None: |
| 102 |
""" |
| 103 |
Args: |
| 104 |
bundle: The bundle to publish, overwriting previously published data. |
| 105 |
|
| 106 |
Note: |
| 107 |
In addition to publishing the bundle, this method can be used as a trigger to persist the state. |
| 108 |
Persisting the state in this method guarantees always remaining up-to-date. |
| 109 |
|
| 110 |
Note: |
| 111 |
This method is called from :meth:`create`, before :meth:`create` has returned the instance. Thus, |
| 112 |
modifications to the object (``self``, in case of subclasses) may not have happened when this |
| 113 |
method is called. |
| 114 |
|
| 115 |
Note: |
| 116 |
Even though this method is expected to perform I/O, it is deliberately not marked as async, since |
| 117 |
completion of the I/O operation is not a requirement for the program flow to continue, and making |
| 118 |
this method async would complicate API design with regards to inheritance from |
| 119 |
:class:`~x3dh.base_state.BaseState`. |
| 120 |
""" |
| 121 |
|
| 122 |
raise NotImplementedError("Create a subclass of State and implement `_publish_bundle`.") |
| 123 |
|
| 124 |
################# |
| 125 |
# serialization # |
| 126 |
################# |
| 127 |
|
| 128 |
@classmethod |
| 129 |
def from_model( |
| 130 |
cls: Type[StateTypeT], |
| 131 |
model: BaseStateModel, |
| 132 |
identity_key_format: IdentityKeyFormat, |
| 133 |
hash_function: HashFunction, |
| 134 |
info: bytes, |
| 135 |
signed_pre_key_rotation_period: int = 7 * 24 * 60 * 60, |
| 136 |
pre_key_refill_threshold: int = 99, |
| 137 |
pre_key_refill_target: int = 100 |
| 138 |
) -> StateTypeT: |
| 139 |
""" |
| 140 |
Args: |
| 141 |
model: The pydantic model holding the internal state of a :class:`State`, as produced by |
| 142 |
:attr:`~x3dh.base_state.BaseState.model`. |
| 143 |
identity_key_format: The format in which the identity public key is included in bundles/headers. |
| 144 |
hash_function: A 256 or 512-bit hash function. |
| 145 |
info: A (byte) string identifying the application. |
| 146 |
signed_pre_key_rotation_period: Rotate the signed pre key after this amount of time in seconds. |
| 147 |
pre_key_refill_threshold: Threshold for refilling the pre keys. |
| 148 |
pre_key_refill_target: When less then ``pre_key_refill_threshold`` pre keys are available, |
| 149 |
generate new ones until there are ``pre_key_refill_target`` pre keys again. |
| 150 |
|
| 151 |
Returns: |
| 152 |
A configured instance of :class:`State`, with internal state restored from the model. |
| 153 |
|
| 154 |
Warning: |
| 155 |
Migrations are not provided via the :attr:`~x3dh.base_state.BaseState.model`/:meth:`from_model` |
| 156 |
API. Use :attr:`~x3dh.base_state.BaseState.json`/:meth:`from_json` instead. Refer to |
| 157 |
:ref:`serialization_and_migration` in the documentation for details. |
| 158 |
""" |
| 159 |
# pylint: disable=protected-access |
| 160 |
|
| 161 |
if signed_pre_key_rotation_period < 1: |
| 162 |
raise ValueError( |
| 163 |
"Invalid value passed for the `signed_pre_key_rotation_period` parameter. The signed pre key" |
| 164 |
" rotation period must be at least one day." |
| 165 |
) |
| 166 |
|
| 167 |
if not 1 <= pre_key_refill_threshold <= pre_key_refill_target: |
| 168 |
raise ValueError( |
| 169 |
"Invalid value(s) passed for the `pre_key_refill_threshold` / `pre_key_refill_target`" |
| 170 |
" parameter(s). `pre_key_refill_threshold` must be greater than or equal to '1' and lower" |
| 171 |
" than or equal to `pre_key_refill_target`." |
| 172 |
) |
| 173 |
|
| 174 |
self = super().from_model(model, identity_key_format, hash_function, info) |
| 175 |
|
| 176 |
self.__signed_pre_key_rotation_period = signed_pre_key_rotation_period |
| 177 |
self.__pre_key_refill_threshold = pre_key_refill_threshold |
| 178 |
self.__pre_key_refill_target = pre_key_refill_target |
| 179 |
|
| 180 |
self.rotate_signed_pre_key() |
| 181 |
|
| 182 |
return self |
| 183 |
|
| 184 |
@classmethod |
| 185 |
def from_json( |
| 186 |
cls: Type[StateTypeT], |
| 187 |
serialized: JSONObject, |
| 188 |
identity_key_format: IdentityKeyFormat, |
| 189 |
hash_function: HashFunction, |
| 190 |
info: bytes, |
| 191 |
signed_pre_key_rotation_period: int = 7 * 24 * 60 * 60, |
| 192 |
pre_key_refill_threshold: int = 99, |
| 193 |
pre_key_refill_target: int = 100 |
| 194 |
) -> Tuple[StateTypeT, bool]: |
| 195 |
""" |
| 196 |
Args: |
| 197 |
serialized: A JSON-serializable Python object holding the internal state of a :class:`State`, |
| 198 |
as produced by :attr:`~x3dh.base_state.BaseState.json`. |
| 199 |
identity_key_format: The format in which the identity public key is included in bundles/headers. |
| 200 |
hash_function: A 256 or 512-bit hash function. |
| 201 |
info: A (byte) string identifying the application. |
| 202 |
signed_pre_key_rotation_period: Rotate the signed pre key after this amount of time in seconds. |
| 203 |
pre_key_refill_threshold: Threshold for refilling the pre keys. |
| 204 |
pre_key_refill_target: When less then ``pre_key_refill_threshold`` pre keys are available, |
| 205 |
generate new ones until there are ``pre_key_refill_target`` pre keys again. |
| 206 |
|
| 207 |
Returns: |
| 208 |
A configured instance of :class:`State`, with internal state restored from the serialized data, |
| 209 |
and a flag that indicates whether the bundle needed to be published. The latter was part of the |
| 210 |
pre-stable serialization format and is handled automatically by this :meth:`from_json` |
| 211 |
implementation. |
| 212 |
""" |
| 213 |
# pylint: disable=protected-access |
| 214 |
|
| 215 |
model, bundle_needs_publish = parse_base_state_model(serialized) |
| 216 |
|
| 217 |
self = cls.from_model( |
| 218 |
model, |
| 219 |
identity_key_format, |
| 220 |
hash_function, |
| 221 |
info, |
| 222 |
signed_pre_key_rotation_period, |
| 223 |
pre_key_refill_threshold, |
| 224 |
pre_key_refill_target |
| 225 |
) |
| 226 |
|
| 227 |
if bundle_needs_publish: |
| 228 |
# I believe this is a false positive by pylint |
| 229 |
self._publish_bundle(self.bundle) # pylint: disable=no-member |
| 230 |
|
| 231 |
return self, False |
| 232 |
|
| 233 |
################################# |
| 234 |
# key generation and management # |
| 235 |
################################# |
| 236 |
|
| 237 |
def rotate_signed_pre_key(self, force: bool = False) -> None: |
| 238 |
""" |
| 239 |
Check whether the signed pre key is due for rotation, and rotate it if necessary. Call this method |
| 240 |
periodically to make sure the signed pre key is always up to date. |
| 241 |
|
| 242 |
Args: |
| 243 |
force: Whether to force rotation regardless of the age of the current signed pre key. |
| 244 |
""" |
| 245 |
|
| 246 |
if force or self.signed_pre_key_age() > self.__signed_pre_key_rotation_period: |
| 247 |
super().rotate_signed_pre_key() |
| 248 |
|
| 249 |
self._publish_bundle(self.bundle) |
| 250 |
|
| 251 |
################# |
| 252 |
# key agreement # |
| 253 |
################# |
| 254 |
|
| 255 |
async def get_shared_secret_passive( |
| 256 |
self, |
| 257 |
header: Header, |
| 258 |
associated_data_appendix: bytes = b"", |
| 259 |
require_pre_key: bool = True |
| 260 |
) -> Tuple[bytes, bytes, SignedPreKeyPair]: |
| 261 |
""" |
| 262 |
Perform an X3DH key agreement, passively. |
| 263 |
|
| 264 |
Args: |
| 265 |
header: The header received from the active party. |
| 266 |
associated_data_appendix: Additional information to append to the associated data, like usernames, |
| 267 |
certificates or other identifying information. |
| 268 |
require_pre_key: Use this flag to abort the key agreement if the active party did not use a pre |
| 269 |
key. |
| 270 |
|
| 271 |
Returns: |
| 272 |
The shared secret and the associated data shared between both parties, and the signed pre key pair |
| 273 |
that was used during the key exchange, for use by follow-up protocols. |
| 274 |
|
| 275 |
Raises: |
| 276 |
KeyAgreementException: If an error occurs during the key agreement. The exception message will |
| 277 |
contain (human-readable) details. |
| 278 |
""" |
| 279 |
|
| 280 |
shared_secret, associated_data, signed_pre_key_pair = await super().get_shared_secret_passive( |
| 281 |
header, |
| 282 |
associated_data_appendix, |
| 283 |
require_pre_key |
| 284 |
) |
| 285 |
|
| 286 |
# If a pre key was used, remove it from the pool and refill the pool if necessary |
| 287 |
if header.pre_key is not None: |
| 288 |
self.delete_pre_key(header.pre_key) |
| 289 |
|
| 290 |
if self.get_num_visible_pre_keys() < self.__pre_key_refill_threshold: |
| 291 |
self.generate_pre_keys(self.__pre_key_refill_target - self.get_num_visible_pre_keys()) |
| 292 |
|
| 293 |
self._publish_bundle(self.bundle) |
| 294 |
|
| 295 |
return shared_secret, associated_data, signed_pre_key_pair |