python-vaultwarden2 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- python_vaultwarden2-0.1.0.dist-info/METADATA +69 -0
- python_vaultwarden2-0.1.0.dist-info/RECORD +34 -0
- python_vaultwarden2-0.1.0.dist-info/WHEEL +4 -0
- python_vaultwarden2-0.1.0.dist-info/licenses/LICENSE +202 -0
- vaultwarden2/__init__.py +47 -0
- vaultwarden2/_async/__init__.py +1 -0
- vaultwarden2/_async/account.py +379 -0
- vaultwarden2/_async/admin.py +485 -0
- vaultwarden2/_async/auth.py +218 -0
- vaultwarden2/_async/base.py +462 -0
- vaultwarden2/_async/client.py +130 -0
- vaultwarden2/_async/organizations.py +914 -0
- vaultwarden2/_async/vault.py +970 -0
- vaultwarden2/_core.py +1103 -0
- vaultwarden2/_encode.py +422 -0
- vaultwarden2/_json.py +215 -0
- vaultwarden2/_merge.py +529 -0
- vaultwarden2/_offload.py +65 -0
- vaultwarden2/_sync/__init__.py +1 -0
- vaultwarden2/_sync/account.py +381 -0
- vaultwarden2/_sync/admin.py +487 -0
- vaultwarden2/_sync/auth.py +220 -0
- vaultwarden2/_sync/base.py +464 -0
- vaultwarden2/_sync/client.py +132 -0
- vaultwarden2/_sync/organizations.py +914 -0
- vaultwarden2/_sync/vault.py +968 -0
- vaultwarden2/crypto.py +634 -0
- vaultwarden2/dump.py +362 -0
- vaultwarden2/errors.py +123 -0
- vaultwarden2/export.py +128 -0
- vaultwarden2/models.py +842 -0
- vaultwarden2/py.typed +0 -0
- vaultwarden2/search.py +206 -0
- vaultwarden2/totp.py +214 -0
vaultwarden2/_merge.py
ADDED
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
"""Safe item updates: three-way merge onto the current server version, and verification before upload.
|
|
2
|
+
|
|
3
|
+
The server stores an item's content as one blob and replaces it on every update, so the client must make
|
|
4
|
+
sure nothing is lost. Rules enforced here:
|
|
5
|
+
|
|
6
|
+
* The upload is built from the **current server version**; only the units the caller changed are
|
|
7
|
+
re-encrypted, every other unit keeps the server's ciphertext byte for byte.
|
|
8
|
+
* A unit the caller changed that also changed on the server since it was read is a conflict.
|
|
9
|
+
* Units with recorded parse issues (see ``Cipher.issues``) are never written.
|
|
10
|
+
* Before anything is sent, the payload is decrypted again and every unit is compared with the expected
|
|
11
|
+
result. Any mismatch aborts the write.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import copy
|
|
17
|
+
import dataclasses
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from datetime import UTC, datetime
|
|
20
|
+
from enum import IntEnum
|
|
21
|
+
from typing import TYPE_CHECKING, Any
|
|
22
|
+
|
|
23
|
+
from vaultwarden2 import crypto
|
|
24
|
+
from vaultwarden2._core import IDENTITY_FIELDS, cipher_key, decrypt_cipher
|
|
25
|
+
from vaultwarden2._encode import PASSWORD_HISTORY_SIZE, _encode_generic, format_date
|
|
26
|
+
from vaultwarden2._json import JsonObject
|
|
27
|
+
from vaultwarden2.crypto import SymmetricKey
|
|
28
|
+
from vaultwarden2.errors import ConflictError, CryptoError, UnsafeWriteError
|
|
29
|
+
from vaultwarden2.models import Cipher, CipherType, PasswordHistoryEntry
|
|
30
|
+
|
|
31
|
+
if TYPE_CHECKING:
|
|
32
|
+
from collections.abc import Callable
|
|
33
|
+
|
|
34
|
+
from vaultwarden2._core import UserKeys
|
|
35
|
+
|
|
36
|
+
RESPONSE_ONLY = ('object', 'attachments', 'permissions', 'edit', 'viewPassword', 'organizationUseTotp', 'collectionIds')
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# ---------------------------------------------------------------- canonical form (for diffing and verification)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def canon(value: Any) -> Any:
|
|
43
|
+
"""A comparable form of a model value, used for diffing and verification.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
value: A model, enum, datetime, collection or plain value.
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
Dataclasses as dicts (without ``raw``), datetimes as the millisecond string the server stores, enums as ints,
|
|
50
|
+
tuples as lists; everything else unchanged.
|
|
51
|
+
"""
|
|
52
|
+
if dataclasses.is_dataclass(value) and not isinstance(value, type):
|
|
53
|
+
return {f.name: canon(getattr(value, f.name)) for f in dataclasses.fields(value) if f.name != 'raw'}
|
|
54
|
+
if isinstance(value, datetime):
|
|
55
|
+
return format_date(value)
|
|
56
|
+
if isinstance(value, IntEnum):
|
|
57
|
+
return int(value)
|
|
58
|
+
if isinstance(value, tuple | list):
|
|
59
|
+
return [canon(v) for v in value]
|
|
60
|
+
if isinstance(value, dict):
|
|
61
|
+
return {k: canon(v) for k, v in value.items()}
|
|
62
|
+
return value
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# ---------------------------------------------------------------- update units
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True, slots=True)
|
|
69
|
+
class Unit:
|
|
70
|
+
"""One independently updatable part of an item.
|
|
71
|
+
|
|
72
|
+
Attributes:
|
|
73
|
+
name: The unit name, for example ``login.password``.
|
|
74
|
+
path: Where the unit lives in the item JSON, for example ``('login', 'password')``.
|
|
75
|
+
get: Reads the unit's value from a decrypted item.
|
|
76
|
+
kind: How the unit is encoded: ``enc`` (encrypted string), ``plain``, ``date``, ``uris``, ``fields``,
|
|
77
|
+
``history`` or ``generic`` (re-encrypt changed parts of an arbitrary structure).
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
name: str
|
|
81
|
+
path: tuple[str, ...]
|
|
82
|
+
get: Callable[[Cipher], Any]
|
|
83
|
+
kind: str
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _sub(attr: str, field: str) -> Callable[[Cipher], Any]:
|
|
87
|
+
"""Getter for an attribute of an item's sub-object (for example ``login.username``).
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
attr: The sub-object attribute of the item (``login``, ``card``, ...).
|
|
91
|
+
field: The attribute of the sub-object.
|
|
92
|
+
|
|
93
|
+
Returns:
|
|
94
|
+
A function reading the value, or None when the sub-object is missing.
|
|
95
|
+
"""
|
|
96
|
+
return lambda c: getattr(getattr(c, attr), field) if getattr(c, attr) is not None else None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _data(name: str) -> Callable[[Cipher], Any]:
|
|
100
|
+
"""Getter for one key of ``Cipher.data`` (item types without a dedicated model).
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
name: The JSON key.
|
|
104
|
+
|
|
105
|
+
Returns:
|
|
106
|
+
A function reading the value.
|
|
107
|
+
"""
|
|
108
|
+
return lambda c: c.data.get(name)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def units_for(cipher: Cipher) -> list[Unit]:
|
|
112
|
+
"""All update units of an item, depending on its type.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
cipher: The item.
|
|
116
|
+
|
|
117
|
+
Returns:
|
|
118
|
+
The units: common ones (name, notes, folder, ...) plus the type-specific ones.
|
|
119
|
+
"""
|
|
120
|
+
units = [
|
|
121
|
+
Unit('name', ('name',), lambda c: c.name, 'enc'),
|
|
122
|
+
Unit('notes', ('notes',), lambda c: c.notes, 'enc'),
|
|
123
|
+
Unit('folder_id', ('folderId',), lambda c: c.folder_id, 'plain'),
|
|
124
|
+
Unit('favorite', ('favorite',), lambda c: c.favorite, 'plain'),
|
|
125
|
+
Unit('reprompt', ('reprompt',), lambda c: int(c.reprompt), 'plain'),
|
|
126
|
+
Unit('fields', ('fields',), lambda c: c.fields, 'fields'),
|
|
127
|
+
Unit('password_history', ('passwordHistory',), lambda c: c.password_history, 'history'),
|
|
128
|
+
]
|
|
129
|
+
if cipher.type == CipherType.LOGIN:
|
|
130
|
+
for attr, key in (('username', 'username'), ('password', 'password'), ('totp', 'totp')):
|
|
131
|
+
units.append(Unit(f'login.{attr}', ('login', key), _sub('login', attr), 'enc'))
|
|
132
|
+
units += [
|
|
133
|
+
Unit('login.uris', ('login', 'uris'), _sub('login', 'uris'), 'uris'),
|
|
134
|
+
Unit('login.password_revision_date', ('login', 'passwordRevisionDate'), _sub('login', 'password_revision_date'), 'date'),
|
|
135
|
+
Unit('login.fido2_credentials', ('login', 'fido2Credentials'), _sub('login', 'fido2_credentials'), 'generic'),
|
|
136
|
+
]
|
|
137
|
+
elif cipher.type == CipherType.SECURE_NOTE:
|
|
138
|
+
units.append(Unit('secure_note_type', ('secureNote', 'type'), lambda c: c.secure_note_type, 'plain'))
|
|
139
|
+
elif cipher.type == CipherType.CARD:
|
|
140
|
+
for attr, key in (
|
|
141
|
+
('cardholder_name', 'cardholderName'),
|
|
142
|
+
('brand', 'brand'),
|
|
143
|
+
('number', 'number'),
|
|
144
|
+
('exp_month', 'expMonth'),
|
|
145
|
+
('exp_year', 'expYear'),
|
|
146
|
+
('code', 'code'),
|
|
147
|
+
):
|
|
148
|
+
units.append(Unit(f'card.{attr}', ('card', key), _sub('card', attr), 'enc'))
|
|
149
|
+
elif cipher.type == CipherType.IDENTITY:
|
|
150
|
+
for attr, key in IDENTITY_FIELDS.items():
|
|
151
|
+
units.append(Unit(f'identity.{attr}', ('identity', key), _sub('identity', attr), 'enc'))
|
|
152
|
+
elif cipher.type == CipherType.SSH_KEY:
|
|
153
|
+
for attr, key in (('private_key', 'privateKey'), ('public_key', 'publicKey'), ('key_fingerprint', 'keyFingerprint')):
|
|
154
|
+
units.append(Unit(f'ssh_key.{attr}', ('sshKey', key), _sub('ssh_key', attr), 'enc'))
|
|
155
|
+
else:
|
|
156
|
+
for name in cipher.data:
|
|
157
|
+
units.append(Unit(f'data.{name}', (name,), _data(name), 'generic'))
|
|
158
|
+
return units
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _unit_has_issue(unit: Unit, cipher: Cipher) -> bool:
|
|
162
|
+
"""Whether recorded parse issues concern a unit.
|
|
163
|
+
|
|
164
|
+
Args:
|
|
165
|
+
unit: The unit.
|
|
166
|
+
cipher: The item with its ``issues``.
|
|
167
|
+
|
|
168
|
+
Returns:
|
|
169
|
+
True if an issue path lies inside the unit's JSON path.
|
|
170
|
+
"""
|
|
171
|
+
prefix = '.' + '.'.join(unit.path)
|
|
172
|
+
return any(prefix.lower() in issue.lower().split(':', 1)[0] for issue in cipher.issues)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
# ---------------------------------------------------------------- JSON path helpers
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _find_key(d: dict[str, Any], key: str) -> str:
|
|
179
|
+
"""The existing spelling of a key in a dict, matched case-insensitively.
|
|
180
|
+
|
|
181
|
+
Args:
|
|
182
|
+
d: The dict.
|
|
183
|
+
key: The key.
|
|
184
|
+
|
|
185
|
+
Returns:
|
|
186
|
+
The existing key, or ``key`` itself if absent.
|
|
187
|
+
"""
|
|
188
|
+
return next((k for k in d if k.lower() == key.lower()), key)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _get_path(d: Any, path: tuple[str, ...]) -> Any:
|
|
192
|
+
"""Read a value at a path of case-insensitive keys.
|
|
193
|
+
|
|
194
|
+
Args:
|
|
195
|
+
d: The JSON value.
|
|
196
|
+
path: The keys.
|
|
197
|
+
|
|
198
|
+
Returns:
|
|
199
|
+
The value, or None if any step is missing.
|
|
200
|
+
"""
|
|
201
|
+
for key in path:
|
|
202
|
+
if not isinstance(d, dict):
|
|
203
|
+
return None
|
|
204
|
+
d = d.get(_find_key(d, key))
|
|
205
|
+
return d
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _set_path(d: dict[str, Any], path: tuple[str, ...], value: Any) -> None:
|
|
209
|
+
"""Write a value at a path of case-insensitive keys, creating missing objects.
|
|
210
|
+
|
|
211
|
+
Args:
|
|
212
|
+
d: The JSON object to modify.
|
|
213
|
+
path: The keys.
|
|
214
|
+
value: The value to write.
|
|
215
|
+
"""
|
|
216
|
+
for key in path[:-1]:
|
|
217
|
+
k = _find_key(d, key)
|
|
218
|
+
if not isinstance(d.get(k), dict):
|
|
219
|
+
d[k] = {}
|
|
220
|
+
d = d[k]
|
|
221
|
+
d[_find_key(d, path[-1])] = value
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
# ---------------------------------------------------------------- unit encoders
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _enc(value: str | None, key: SymmetricKey) -> str | None:
|
|
228
|
+
"""Encrypt a string field; None stays None and an empty string stays empty.
|
|
229
|
+
|
|
230
|
+
Args:
|
|
231
|
+
value: The plaintext.
|
|
232
|
+
key: The item key.
|
|
233
|
+
|
|
234
|
+
Returns:
|
|
235
|
+
The encrypted string, ``''`` or None.
|
|
236
|
+
"""
|
|
237
|
+
if value is None:
|
|
238
|
+
return None
|
|
239
|
+
return '' if value == '' else str(crypto.encrypt(value, key))
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _decrypt_or_none(value: Any, key: SymmetricKey) -> str | None:
|
|
243
|
+
"""Decrypt a value if possible, for matching existing entries.
|
|
244
|
+
|
|
245
|
+
Args:
|
|
246
|
+
value: A value from the server JSON.
|
|
247
|
+
key: The item key.
|
|
248
|
+
|
|
249
|
+
Returns:
|
|
250
|
+
The plaintext, or None if the value is not decryptable text.
|
|
251
|
+
"""
|
|
252
|
+
if not isinstance(value, str) or not value:
|
|
253
|
+
return None
|
|
254
|
+
try:
|
|
255
|
+
return crypto.decrypt_str(value, key)
|
|
256
|
+
except CryptoError:
|
|
257
|
+
return None
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _encode_unit(unit: Unit, value: Any, current_raw: Any, key: SymmetricKey) -> Any:
|
|
261
|
+
"""Encode a unit's new value for the upload.
|
|
262
|
+
|
|
263
|
+
Args:
|
|
264
|
+
unit: The unit.
|
|
265
|
+
value: The new value from the edited item.
|
|
266
|
+
current_raw: The current server JSON of the item (for keeping unknown parts).
|
|
267
|
+
key: The item key.
|
|
268
|
+
|
|
269
|
+
Returns:
|
|
270
|
+
The JSON value to write at the unit's path.
|
|
271
|
+
"""
|
|
272
|
+
raw = _get_path(current_raw, unit.path)
|
|
273
|
+
if unit.kind == 'enc':
|
|
274
|
+
return _enc(value, key)
|
|
275
|
+
if unit.kind == 'plain':
|
|
276
|
+
return value
|
|
277
|
+
if unit.kind == 'date':
|
|
278
|
+
return format_date(value) if value else None
|
|
279
|
+
if unit.kind == 'generic':
|
|
280
|
+
return _encode_generic(list(value) if isinstance(value, tuple) else value, raw, key)
|
|
281
|
+
return _encode_list_unit(unit, value, raw if isinstance(raw, list) else [], key)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _encode_list_unit(unit: Unit, value: Any, raw_list: list[Any], key: SymmetricKey) -> Any:
|
|
285
|
+
"""Encode a list unit, keeping each entry's unknown extras by matching entries on their content.
|
|
286
|
+
|
|
287
|
+
URIs are matched by their decrypted URI, custom fields by name, history entries by password and date.
|
|
288
|
+
|
|
289
|
+
Args:
|
|
290
|
+
unit: The unit (``uris``, ``fields`` or ``history``).
|
|
291
|
+
value: The new entries.
|
|
292
|
+
raw_list: The current server JSON list.
|
|
293
|
+
key: The item key.
|
|
294
|
+
|
|
295
|
+
Returns:
|
|
296
|
+
The JSON list.
|
|
297
|
+
|
|
298
|
+
Raises:
|
|
299
|
+
UnsafeWriteError: Unknown unit kind (internal error).
|
|
300
|
+
"""
|
|
301
|
+
if unit.kind == 'uris':
|
|
302
|
+
# Keep each URI's unknown extras by matching on the decrypted URI, not on the position.
|
|
303
|
+
by_uri = {_decrypt_or_none(r.get(_find_key(r, 'uri')), key): r for r in raw_list if isinstance(r, dict)}
|
|
304
|
+
out = []
|
|
305
|
+
for u in value:
|
|
306
|
+
base = copy.deepcopy(by_uri.get(u.uri, {}))
|
|
307
|
+
base[_find_key(base, 'uri')] = _enc(u.uri, key)
|
|
308
|
+
base[_find_key(base, 'uriChecksum')] = _enc(crypto.uri_checksum(u.uri), key) if u.uri is not None else None
|
|
309
|
+
base[_find_key(base, 'match')] = int(u.match) if u.match is not None else None
|
|
310
|
+
out.append(base)
|
|
311
|
+
return out
|
|
312
|
+
if unit.kind == 'fields':
|
|
313
|
+
by_name = {_decrypt_or_none(r.get(_find_key(r, 'name')), key): r for r in raw_list if isinstance(r, dict)}
|
|
314
|
+
out = []
|
|
315
|
+
for f in value:
|
|
316
|
+
base = copy.deepcopy(by_name.get(f.name, {}))
|
|
317
|
+
base.update({_find_key(base, 'name'): _enc(f.name, key), _find_key(base, 'value'): _enc(f.value, key)})
|
|
318
|
+
base[_find_key(base, 'type')] = int(f.type)
|
|
319
|
+
base[_find_key(base, 'linkedId')] = f.linked_id
|
|
320
|
+
out.append(base)
|
|
321
|
+
return out
|
|
322
|
+
if unit.kind == 'history':
|
|
323
|
+
out = []
|
|
324
|
+
for p in value:
|
|
325
|
+
entry = {'password': _enc(p.password, key), 'lastUsedDate': format_date(p.last_used_date or datetime.now(UTC))}
|
|
326
|
+
for r in raw_list: # unchanged entries keep their ciphertext
|
|
327
|
+
if (
|
|
328
|
+
isinstance(r, dict)
|
|
329
|
+
and _decrypt_or_none(r.get(_find_key(r, 'password')), key) == p.password
|
|
330
|
+
and r.get(_find_key(r, 'lastUsedDate')) == entry['lastUsedDate']
|
|
331
|
+
):
|
|
332
|
+
entry = copy.deepcopy(r)
|
|
333
|
+
break
|
|
334
|
+
out.append(entry)
|
|
335
|
+
return out
|
|
336
|
+
raise UnsafeWriteError(f'internal: unknown unit kind {unit.kind}') # pragma: no cover
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
# ---------------------------------------------------------------- update
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def with_dated_history(cipher: Cipher) -> Cipher:
|
|
343
|
+
"""Give undated password history entries the current time, so the upload matches what verification expects.
|
|
344
|
+
|
|
345
|
+
Args:
|
|
346
|
+
cipher: The item.
|
|
347
|
+
|
|
348
|
+
Returns:
|
|
349
|
+
The item, with every history entry dated.
|
|
350
|
+
"""
|
|
351
|
+
if all(p.last_used_date for p in cipher.password_history):
|
|
352
|
+
return cipher
|
|
353
|
+
now = _now_ms()
|
|
354
|
+
return dataclasses.replace(
|
|
355
|
+
cipher, password_history=tuple(p if p.last_used_date else dataclasses.replace(p, last_used_date=now) for p in cipher.password_history)
|
|
356
|
+
)
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _now_ms() -> datetime:
|
|
360
|
+
"""The current time, truncated to milliseconds (the server's precision).
|
|
361
|
+
|
|
362
|
+
Returns:
|
|
363
|
+
The UTC datetime.
|
|
364
|
+
"""
|
|
365
|
+
now = datetime.now(UTC)
|
|
366
|
+
return now.replace(microsecond=now.microsecond // 1000 * 1000)
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def plan_update(edited: Cipher, current_raw: dict[str, Any], keys: UserKeys, user_id: str, *, strict: bool = False) -> dict[str, Any] | None:
|
|
370
|
+
"""Build the verified upload for an edited item on top of its current server version.
|
|
371
|
+
|
|
372
|
+
Args:
|
|
373
|
+
edited: The edited item (read from the server, then changed).
|
|
374
|
+
current_raw: The item's current server JSON.
|
|
375
|
+
keys: The unlocked keys.
|
|
376
|
+
user_id: The logged-in user (sent as ``encryptedFor``).
|
|
377
|
+
strict: Treat any server-side change since the read as a conflict.
|
|
378
|
+
|
|
379
|
+
Returns:
|
|
380
|
+
The request body, or None if nothing changed.
|
|
381
|
+
|
|
382
|
+
Raises:
|
|
383
|
+
ConflictError: A changed unit was also changed on the server (``strict``: anything changed).
|
|
384
|
+
UnsafeWriteError: No ``raw`` (not read from the server), an attempt to change ``id``, ``type`` or
|
|
385
|
+
``organization_id``, a changed unit with parse issues, or failed verification.
|
|
386
|
+
"""
|
|
387
|
+
if not edited.raw:
|
|
388
|
+
raise UnsafeWriteError('update needs an item read from the server (use get_cipher() and dataclasses.replace())')
|
|
389
|
+
original = decrypt_cipher(edited.raw, keys)
|
|
390
|
+
current = decrypt_cipher(current_raw, keys)
|
|
391
|
+
for attr, hint in (('id', ''), ('type', ''), ('organization_id', ' (use move_to_organization)')):
|
|
392
|
+
if canon(getattr(edited, attr)) != canon(getattr(current, attr)) or canon(getattr(edited, attr)) != canon(getattr(original, attr)):
|
|
393
|
+
raise UnsafeWriteError(f'{attr} cannot be changed by an update{hint}')
|
|
394
|
+
if strict and JsonObject(edited.raw).get('revisionDate') != JsonObject(current_raw).get('revisionDate'):
|
|
395
|
+
raise ConflictError('the item changed on the server since it was read (strict mode)')
|
|
396
|
+
|
|
397
|
+
values: dict[str, Any] = {}
|
|
398
|
+
units = {u.name: u for u in units_for(current)}
|
|
399
|
+
for unit in units_for(edited):
|
|
400
|
+
if unit.name not in units:
|
|
401
|
+
raise UnsafeWriteError(f'{unit.name} is not part of this item type')
|
|
402
|
+
mine, before, theirs = canon(unit.get(edited)), canon(unit.get(original)), canon(unit.get(current))
|
|
403
|
+
if mine == before:
|
|
404
|
+
continue
|
|
405
|
+
if theirs not in (before, mine):
|
|
406
|
+
raise ConflictError(f'{unit.name} was changed on the server since the item was read')
|
|
407
|
+
if _unit_has_issue(unit, original) or _unit_has_issue(unit, current):
|
|
408
|
+
raise UnsafeWriteError(f'{unit.name} contains data this library cannot interpret; refusing to overwrite it')
|
|
409
|
+
values[unit.name] = unit.get(edited)
|
|
410
|
+
if not values:
|
|
411
|
+
return None
|
|
412
|
+
|
|
413
|
+
if 'password_history' in values: # entries need a date; set it explicitly so verification compares like with like
|
|
414
|
+
now = _now_ms()
|
|
415
|
+
values['password_history'] = tuple(p if p.last_used_date else dataclasses.replace(p, last_used_date=now) for p in values['password_history'])
|
|
416
|
+
# Password history, as the web vault keeps it: the replaced password goes first (based on the server's list).
|
|
417
|
+
if 'login.password' in values and 'password_history' not in values and current.login and current.login.password:
|
|
418
|
+
now = _now_ms()
|
|
419
|
+
values['password_history'] = (PasswordHistoryEntry(password=current.login.password, last_used_date=now), *current.password_history)[:PASSWORD_HISTORY_SIZE]
|
|
420
|
+
values['login.password_revision_date'] = now
|
|
421
|
+
|
|
422
|
+
key = cipher_key(JsonObject(current_raw), keys)
|
|
423
|
+
body = copy.deepcopy(current_raw)
|
|
424
|
+
for name, value in values.items():
|
|
425
|
+
unit = units[name]
|
|
426
|
+
encoded = _encode_unit(unit, value, current_raw, key)
|
|
427
|
+
_set_path(body, unit.path, encoded)
|
|
428
|
+
if name == 'login.uris': # legacy single-URI field some clients still read
|
|
429
|
+
_set_path(body, ('login', 'uri'), encoded[0][_find_key(encoded[0], 'uri')] if encoded else None)
|
|
430
|
+
body[_find_key(body, 'encryptedFor')] = user_id
|
|
431
|
+
revision = JsonObject(current_raw).get_str('revisionDate')
|
|
432
|
+
if revision:
|
|
433
|
+
body['lastKnownRevisionDate'] = revision
|
|
434
|
+
for response_only in RESPONSE_ONLY:
|
|
435
|
+
for k in [k for k in body if k.lower() == response_only.lower()]:
|
|
436
|
+
del body[k]
|
|
437
|
+
|
|
438
|
+
verify_payload(body, keys, current, values, units)
|
|
439
|
+
return body
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def verify_payload(body: dict[str, Any], keys: UserKeys, base: Cipher, changes: dict[str, Any], units: dict[str, Unit]) -> None:
|
|
443
|
+
"""Decrypt an update payload again and compare every unit with the expected value.
|
|
444
|
+
|
|
445
|
+
Args:
|
|
446
|
+
body: The request body.
|
|
447
|
+
keys: The unlocked keys.
|
|
448
|
+
base: The current server version.
|
|
449
|
+
changes: The new values of the changed units, by unit name.
|
|
450
|
+
units: All units of the item, by name.
|
|
451
|
+
|
|
452
|
+
Raises:
|
|
453
|
+
UnsafeWriteError: The payload does not decrypt, has new issues, or a unit differs from what is expected.
|
|
454
|
+
"""
|
|
455
|
+
try:
|
|
456
|
+
check = decrypt_cipher({**body, 'id': base.id or 'verify'}, keys)
|
|
457
|
+
except CryptoError as e:
|
|
458
|
+
raise UnsafeWriteError(f'payload verification failed: {e}') from e
|
|
459
|
+
new_issues = set(check.issues) - set(base.issues)
|
|
460
|
+
if new_issues:
|
|
461
|
+
raise UnsafeWriteError(f'payload verification failed: {sorted(new_issues)}')
|
|
462
|
+
for name, unit in units.items():
|
|
463
|
+
expected = changes.get(name, unit.get(base)) if name in changes else unit.get(base)
|
|
464
|
+
if canon(unit.get(check)) != canon(expected):
|
|
465
|
+
raise UnsafeWriteError(f'payload verification failed for {name}')
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def verify_new(body: dict[str, Any], keys: UserKeys, intended: Cipher) -> None:
|
|
469
|
+
"""Verify a create or move-to-organization payload against the intended item.
|
|
470
|
+
|
|
471
|
+
Args:
|
|
472
|
+
body: The request body.
|
|
473
|
+
keys: The unlocked keys (including the target organization's key).
|
|
474
|
+
intended: The item as it should be stored.
|
|
475
|
+
|
|
476
|
+
Raises:
|
|
477
|
+
UnsafeWriteError: The payload does not decrypt, has issues, or a unit differs.
|
|
478
|
+
"""
|
|
479
|
+
try:
|
|
480
|
+
check = decrypt_cipher({**body, 'id': intended.id or 'verify'}, keys)
|
|
481
|
+
except CryptoError as e:
|
|
482
|
+
raise UnsafeWriteError(f'payload verification failed: {e}') from e
|
|
483
|
+
if check.issues:
|
|
484
|
+
raise UnsafeWriteError(f'payload verification failed: {list(check.issues)}')
|
|
485
|
+
expected = dataclasses.replace(intended, name=intended.name or '')
|
|
486
|
+
for unit in units_for(expected):
|
|
487
|
+
if canon(unit.get(check)) != canon(unit.get(expected)):
|
|
488
|
+
raise UnsafeWriteError(f'payload verification failed for {unit.name}')
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def verified_encrypt(text: str, key: SymmetricKey) -> str:
|
|
492
|
+
"""Encrypt text and decrypt it again before it is sent.
|
|
493
|
+
|
|
494
|
+
Args:
|
|
495
|
+
text: The plaintext.
|
|
496
|
+
key: The key.
|
|
497
|
+
|
|
498
|
+
Returns:
|
|
499
|
+
The encrypted string.
|
|
500
|
+
|
|
501
|
+
Raises:
|
|
502
|
+
UnsafeWriteError: The round trip failed.
|
|
503
|
+
"""
|
|
504
|
+
encrypted = str(crypto.encrypt(text, key))
|
|
505
|
+
if crypto.decrypt_str(encrypted, key) != text: # pragma: no cover - defensive
|
|
506
|
+
raise UnsafeWriteError('encryption self-check failed')
|
|
507
|
+
return encrypted
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def verify_attachment(request: dict[str, Any], encrypted: bytes, data: bytes, file_name: str, item_key: SymmetricKey) -> None:
|
|
511
|
+
"""Check that the attachment key, file name and content decrypt back before anything is uploaded.
|
|
512
|
+
|
|
513
|
+
Args:
|
|
514
|
+
request: The attachment request (wrapped key and encrypted file name).
|
|
515
|
+
encrypted: The encrypted file content.
|
|
516
|
+
data: The original file content.
|
|
517
|
+
file_name: The original file name.
|
|
518
|
+
item_key: The item key that wraps the attachment key.
|
|
519
|
+
|
|
520
|
+
Raises:
|
|
521
|
+
UnsafeWriteError: Any part does not round-trip.
|
|
522
|
+
"""
|
|
523
|
+
try:
|
|
524
|
+
attachment_key = SymmetricKey.from_bytes(crypto.decrypt(request['key'], item_key))
|
|
525
|
+
ok = crypto.decrypt_str(request['fileName'], item_key) == file_name and crypto.decrypt_buffer(encrypted, attachment_key) == data
|
|
526
|
+
except CryptoError as e:
|
|
527
|
+
raise UnsafeWriteError(f'attachment verification failed: {e}') from e
|
|
528
|
+
if not ok:
|
|
529
|
+
raise UnsafeWriteError('attachment verification failed')
|
vaultwarden2/_offload.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Concurrency helpers in async and sync variants.
|
|
2
|
+
|
|
3
|
+
The async client uses ``arun_cpu`` / ``new_async_lock``; unasyncd renames them to ``run_cpu`` /
|
|
4
|
+
``new_lock`` when it generates the sync client (see ``[tool.unasyncd]`` in pyproject.toml).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import threading
|
|
10
|
+
from typing import TYPE_CHECKING, TypeVar, TypeVarTuple
|
|
11
|
+
|
|
12
|
+
import anyio
|
|
13
|
+
import anyio.to_thread
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from collections.abc import Callable
|
|
17
|
+
|
|
18
|
+
R = TypeVar('R')
|
|
19
|
+
Ts = TypeVarTuple('Ts')
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
async def arun_cpu(func: Callable[[*Ts], R], *args: *Ts) -> R:
|
|
23
|
+
"""Run CPU-heavy work (key derivation, key generation, bulk decryption) in a worker thread.
|
|
24
|
+
|
|
25
|
+
Keeps the event loop responsive.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
func: The function to run.
|
|
29
|
+
*args: Its positional arguments.
|
|
30
|
+
|
|
31
|
+
Returns:
|
|
32
|
+
The function's result.
|
|
33
|
+
"""
|
|
34
|
+
return await anyio.to_thread.run_sync(func, *args)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def run_cpu(func: Callable[[*Ts], R], *args: *Ts) -> R:
|
|
38
|
+
"""Run CPU-heavy work directly (sync client: there is no event loop to protect).
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
func: The function to run.
|
|
42
|
+
*args: Its positional arguments.
|
|
43
|
+
|
|
44
|
+
Returns:
|
|
45
|
+
The function's result.
|
|
46
|
+
"""
|
|
47
|
+
return func(*args)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def new_async_lock() -> anyio.Lock:
|
|
51
|
+
"""A lock guarding token refresh in the async client.
|
|
52
|
+
|
|
53
|
+
Returns:
|
|
54
|
+
A new anyio lock.
|
|
55
|
+
"""
|
|
56
|
+
return anyio.Lock()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def new_lock() -> threading.Lock:
|
|
60
|
+
"""A lock guarding token refresh in the sync client (which may be shared between threads).
|
|
61
|
+
|
|
62
|
+
Returns:
|
|
63
|
+
A new threading lock.
|
|
64
|
+
"""
|
|
65
|
+
return threading.Lock()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Sync client implementation, generated by unasyncd from vaultwarden2._async."""
|