File: crypto.py

package info (click to toggle)
mautrix-python 0.20.7-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,812 kB
  • sloc: python: 19,103; makefile: 16
file content (171 lines) | stat: -rw-r--r-- 4,935 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# Copyright (c) 2022 Tulir Asokan
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from typing import Any, Dict, List, NamedTuple, Optional
from enum import IntEnum

from attr import dataclass

from .event import EncryptionAlgorithm, EncryptionKeyAlgorithm, KeyID, ToDeviceEvent
from .primitive import DeviceID, IdentityKey, Signature, SigningKey, UserID
from .util import ExtensibleEnum, SerializableAttrs, field


@dataclass
class UnsignedDeviceInfo(SerializableAttrs):
    device_display_name: Optional[str] = None


@dataclass
class DeviceKeys(SerializableAttrs):
    user_id: UserID
    device_id: DeviceID
    algorithms: List[EncryptionAlgorithm]
    keys: Dict[KeyID, str]
    signatures: Dict[UserID, Dict[KeyID, Signature]]
    unsigned: UnsignedDeviceInfo = None

    def __attrs_post_init__(self) -> None:
        if self.unsigned is None:
            self.unsigned = UnsignedDeviceInfo()

    @property
    def ed25519(self) -> Optional[SigningKey]:
        try:
            return SigningKey(self.keys[KeyID(EncryptionKeyAlgorithm.ED25519, self.device_id)])
        except KeyError:
            return None

    @property
    def curve25519(self) -> Optional[IdentityKey]:
        try:
            return IdentityKey(self.keys[KeyID(EncryptionKeyAlgorithm.CURVE25519, self.device_id)])
        except KeyError:
            return None


class CrossSigningUsage(ExtensibleEnum):
    MASTER = "master"
    SELF = "self_signing"
    USER = "user_signing"


@dataclass
class CrossSigningKeys(SerializableAttrs):
    user_id: UserID
    usage: List[CrossSigningUsage]
    keys: Dict[KeyID, SigningKey]
    signatures: Dict[UserID, Dict[KeyID, Signature]] = field(factory=lambda: {})

    @property
    def first_key(self) -> Optional[SigningKey]:
        try:
            return next(iter(self.keys.values()))
        except StopIteration:
            return None

    @property
    def first_ed25519_key(self) -> Optional[SigningKey]:
        return self.first_key_with_algorithm(EncryptionKeyAlgorithm.ED25519)

    def first_key_with_algorithm(self, alg: EncryptionKeyAlgorithm) -> Optional[SigningKey]:
        if not self.keys:
            return None
        try:
            return next(key for key_id, key in self.keys.items() if key_id.algorithm == alg)
        except StopIteration:
            return None


@dataclass
class QueryKeysResponse(SerializableAttrs):
    device_keys: Dict[UserID, Dict[DeviceID, DeviceKeys]] = field(factory=lambda: {})
    master_keys: Dict[UserID, CrossSigningKeys] = field(factory=lambda: {})
    self_signing_keys: Dict[UserID, CrossSigningKeys] = field(factory=lambda: {})
    user_signing_keys: Dict[UserID, CrossSigningKeys] = field(factory=lambda: {})
    failures: Dict[str, Any] = field(factory=lambda: {})


@dataclass
class ClaimKeysResponse(SerializableAttrs):
    one_time_keys: Dict[UserID, Dict[DeviceID, Dict[KeyID, Any]]]
    failures: Dict[str, Any] = field(factory=lambda: {})


class TrustState(IntEnum):
    BLACKLISTED = -100
    UNVERIFIED = 0
    UNKNOWN_DEVICE = 10
    FORWARDED = 20
    CROSS_SIGNED_UNTRUSTED = 50
    CROSS_SIGNED_TOFU = 100
    CROSS_SIGNED_TRUSTED = 200
    VERIFIED = 300

    def __str__(self) -> str:
        return _trust_state_to_name[self]

    @classmethod
    def parse(cls, val: str) -> "TrustState":
        try:
            return _name_to_trust_state[val]
        except KeyError as e:
            raise ValueError(f"Invalid trust state {val!r}") from e


_trust_state_to_name: Dict[TrustState, str] = {
    val: val.name.lower().replace("_", "-") for val in TrustState
}
_name_to_trust_state: Dict[str, TrustState] = {
    value: key for key, value in _trust_state_to_name.items()
}


@dataclass
class DeviceIdentity:
    user_id: UserID
    device_id: DeviceID
    identity_key: IdentityKey
    signing_key: SigningKey

    trust: TrustState
    deleted: bool
    name: str


@dataclass
class OlmEventKeys(SerializableAttrs):
    ed25519: SigningKey


@dataclass
class DecryptedOlmEvent(ToDeviceEvent, SerializableAttrs):
    keys: OlmEventKeys
    recipient: UserID
    recipient_keys: OlmEventKeys
    sender_device: Optional[DeviceID] = None
    sender_key: IdentityKey = field(hidden=True, default=None)


class TOFUSigningKey(NamedTuple):
    """
    A tuple representing a single cross-signing key. The first value is the current key, and the
    second value is the first seen key. If the values don't match, it means the key is not valid
    for trust-on-first-use.
    """

    key: SigningKey
    first: SigningKey


class CrossSigner(NamedTuple):
    """
    A tuple containing a user ID and a signing key they own.

    The key can either be a device-owned signing key, or one of the user's cross-signing keys.
    """

    user_id: UserID
    key: SigningKey