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/_encode.py
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
"""Network-free encoding of models into encrypted request bodies.
|
|
2
|
+
|
|
3
|
+
Updates start from the item's original server JSON (``raw``) and overwrite only what this library models, so
|
|
4
|
+
fields it does not know about (passkeys, new item types, future additions) survive.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import copy
|
|
10
|
+
import dataclasses
|
|
11
|
+
import re
|
|
12
|
+
from dataclasses import replace
|
|
13
|
+
from datetime import UTC, datetime
|
|
14
|
+
from typing import TYPE_CHECKING, Any
|
|
15
|
+
|
|
16
|
+
from vaultwarden2 import crypto
|
|
17
|
+
from vaultwarden2._core import IDENTITY_FIELDS
|
|
18
|
+
from vaultwarden2._json import JsonObject
|
|
19
|
+
from vaultwarden2.crypto import SymmetricKey
|
|
20
|
+
from vaultwarden2.errors import CryptoError, UnsafeWriteError
|
|
21
|
+
from vaultwarden2.models import Card, Cipher, CipherType, Identity, Login, PasswordHistoryEntry, SshKey
|
|
22
|
+
|
|
23
|
+
if TYPE_CHECKING:
|
|
24
|
+
from vaultwarden2._core import UserKeys
|
|
25
|
+
|
|
26
|
+
PASSWORD_HISTORY_SIZE = 5
|
|
27
|
+
"""Entries the web vault keeps in a login's password history."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def format_date(value: datetime) -> str:
|
|
31
|
+
"""Format a timestamp as the official apps send it.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
value: The timestamp; naive values are taken as UTC.
|
|
35
|
+
|
|
36
|
+
Returns:
|
|
37
|
+
ISO-8601 UTC with milliseconds, for example ``2026-01-02T03:04:05.123Z``.
|
|
38
|
+
"""
|
|
39
|
+
if value.tzinfo is None:
|
|
40
|
+
value = value.replace(tzinfo=UTC)
|
|
41
|
+
return value.astimezone(UTC).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _enc(value: str | None, key: SymmetricKey) -> str | None:
|
|
45
|
+
"""Encrypt an optional string.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
value: The plaintext, or None.
|
|
49
|
+
key: The key.
|
|
50
|
+
|
|
51
|
+
Returns:
|
|
52
|
+
The encrypted string, or None.
|
|
53
|
+
"""
|
|
54
|
+
return str(crypto.encrypt(value, key)) if value is not None else None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _merge(raw: Any, values: dict[str, Any]) -> dict[str, Any]:
|
|
58
|
+
"""A copy of a JSON object with values set; existing keys are matched case-insensitively.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
raw: The original object (anything else counts as empty).
|
|
62
|
+
values: The values to set.
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
The merged copy.
|
|
66
|
+
"""
|
|
67
|
+
out: dict[str, Any] = copy.deepcopy(raw) if isinstance(raw, dict) else {}
|
|
68
|
+
lower = {k.lower(): k for k in out}
|
|
69
|
+
for key, value in values.items():
|
|
70
|
+
out.pop(lower.get(key.lower(), key), None)
|
|
71
|
+
out[key] = value
|
|
72
|
+
return out
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _raw_sub(cipher: Cipher, name: str) -> Any:
|
|
76
|
+
"""A sub-object of an item's original JSON.
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
cipher: The item.
|
|
80
|
+
name: The key, for example ``login``.
|
|
81
|
+
|
|
82
|
+
Returns:
|
|
83
|
+
The value, or None.
|
|
84
|
+
"""
|
|
85
|
+
return JsonObject(cipher.raw).get(name)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def encode_login(login: Login, raw: Any, key: SymmetricKey) -> dict[str, Any]:
|
|
89
|
+
"""The encrypted ``login`` object. Passkeys keep their original ciphertext where unchanged.
|
|
90
|
+
|
|
91
|
+
Args:
|
|
92
|
+
login: The login data.
|
|
93
|
+
raw: The original ``login`` JSON (unknown fields are kept).
|
|
94
|
+
key: The item key.
|
|
95
|
+
|
|
96
|
+
Returns:
|
|
97
|
+
The JSON object.
|
|
98
|
+
"""
|
|
99
|
+
raw_uris = JsonObject(raw).get('uris')
|
|
100
|
+
raw_uris = raw_uris if isinstance(raw_uris, list) else []
|
|
101
|
+
uris = []
|
|
102
|
+
for i, u in enumerate(login.uris):
|
|
103
|
+
raw_uri = raw_uris[i] if i < len(raw_uris) else None
|
|
104
|
+
uris.append(
|
|
105
|
+
_merge(
|
|
106
|
+
raw_uri,
|
|
107
|
+
{
|
|
108
|
+
'uri': _enc(u.uri, key),
|
|
109
|
+
'uriChecksum': _enc(crypto.uri_checksum(u.uri), key) if u.uri is not None else None,
|
|
110
|
+
'match': int(u.match) if u.match is not None else None,
|
|
111
|
+
},
|
|
112
|
+
)
|
|
113
|
+
)
|
|
114
|
+
return _merge(
|
|
115
|
+
raw,
|
|
116
|
+
{
|
|
117
|
+
'username': _enc(login.username, key),
|
|
118
|
+
'password': _enc(login.password, key),
|
|
119
|
+
'totp': _enc(login.totp, key),
|
|
120
|
+
'uris': uris,
|
|
121
|
+
'uri': uris[0]['uri'] if uris else None,
|
|
122
|
+
'passwordRevisionDate': format_date(login.password_revision_date) if login.password_revision_date else None,
|
|
123
|
+
'fido2Credentials': _encode_generic(list(login.fido2_credentials), JsonObject(raw).get('fido2Credentials'), key)
|
|
124
|
+
if login.fido2_credentials or JsonObject(raw).get('fido2Credentials')
|
|
125
|
+
else None,
|
|
126
|
+
},
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def encode_card(card: Card, raw: Any, key: SymmetricKey) -> dict[str, Any]:
|
|
131
|
+
"""The encrypted ``card`` object.
|
|
132
|
+
|
|
133
|
+
Args:
|
|
134
|
+
card: The card data.
|
|
135
|
+
raw: The original ``card`` JSON.
|
|
136
|
+
key: The item key.
|
|
137
|
+
|
|
138
|
+
Returns:
|
|
139
|
+
The JSON object.
|
|
140
|
+
"""
|
|
141
|
+
return _merge(
|
|
142
|
+
raw,
|
|
143
|
+
{
|
|
144
|
+
'cardholderName': _enc(card.cardholder_name, key),
|
|
145
|
+
'brand': _enc(card.brand, key),
|
|
146
|
+
'number': _enc(card.number, key),
|
|
147
|
+
'expMonth': _enc(card.exp_month, key),
|
|
148
|
+
'expYear': _enc(card.exp_year, key),
|
|
149
|
+
'code': _enc(card.code, key),
|
|
150
|
+
},
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def encode_identity(identity: Identity, raw: Any, key: SymmetricKey) -> dict[str, Any]:
|
|
155
|
+
"""The encrypted ``identity`` object.
|
|
156
|
+
|
|
157
|
+
Args:
|
|
158
|
+
identity: The identity data.
|
|
159
|
+
raw: The original ``identity`` JSON.
|
|
160
|
+
key: The item key.
|
|
161
|
+
|
|
162
|
+
Returns:
|
|
163
|
+
The JSON object.
|
|
164
|
+
"""
|
|
165
|
+
return _merge(raw, {json_key: _enc(getattr(identity, attr), key) for attr, json_key in IDENTITY_FIELDS.items()})
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def encode_ssh_key(ssh_key: SshKey, raw: Any, key: SymmetricKey) -> dict[str, Any]:
|
|
169
|
+
"""The encrypted ``sshKey`` object.
|
|
170
|
+
|
|
171
|
+
Args:
|
|
172
|
+
ssh_key: The SSH key data.
|
|
173
|
+
raw: The original ``sshKey`` JSON.
|
|
174
|
+
key: The item key.
|
|
175
|
+
|
|
176
|
+
Returns:
|
|
177
|
+
The JSON object.
|
|
178
|
+
"""
|
|
179
|
+
return _merge(
|
|
180
|
+
raw,
|
|
181
|
+
{
|
|
182
|
+
'privateKey': _enc(ssh_key.private_key, key),
|
|
183
|
+
'publicKey': _enc(ssh_key.public_key, key),
|
|
184
|
+
'keyFingerprint': _enc(ssh_key.key_fingerprint, key),
|
|
185
|
+
},
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _encode_generic(value: Any, raw: Any, key: SymmetricKey) -> Any:
|
|
190
|
+
"""Re-encrypt decrypted data of an arbitrary structure (item types without a model, passkeys).
|
|
191
|
+
|
|
192
|
+
Unchanged values keep their original ciphertext; changed values are encrypted if they were encrypted before (or
|
|
193
|
+
are new strings); everything else is sent as it is.
|
|
194
|
+
|
|
195
|
+
Args:
|
|
196
|
+
value: The decrypted value.
|
|
197
|
+
raw: The original JSON value at the same place.
|
|
198
|
+
key: The item key.
|
|
199
|
+
|
|
200
|
+
Returns:
|
|
201
|
+
The JSON value to send.
|
|
202
|
+
"""
|
|
203
|
+
if isinstance(value, dict):
|
|
204
|
+
raw_dict = raw if isinstance(raw, dict) else {}
|
|
205
|
+
return {k: _encode_generic(v, raw_dict.get(k), key) for k, v in value.items()}
|
|
206
|
+
if isinstance(value, list):
|
|
207
|
+
raw_list = raw if isinstance(raw, list) else []
|
|
208
|
+
return [_encode_generic(v, raw_list[i] if i < len(raw_list) else None, key) for i, v in enumerate(value)]
|
|
209
|
+
if isinstance(value, str):
|
|
210
|
+
if crypto.is_enc_string(raw):
|
|
211
|
+
try:
|
|
212
|
+
if crypto.decrypt_str(raw, key) == value:
|
|
213
|
+
return raw
|
|
214
|
+
except CryptoError:
|
|
215
|
+
pass
|
|
216
|
+
return str(crypto.encrypt(value, key))
|
|
217
|
+
return str(crypto.encrypt(value, key)) if raw is None else value
|
|
218
|
+
return value
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _rekey(value: Any, old: SymmetricKey, new: SymmetricKey) -> Any:
|
|
222
|
+
"""Re-encrypt every encrypted string that decrypts with ``old`` (but not ``new``) under ``new``.
|
|
223
|
+
|
|
224
|
+
Args:
|
|
225
|
+
value: A JSON value.
|
|
226
|
+
old: The previous key.
|
|
227
|
+
new: The new key.
|
|
228
|
+
|
|
229
|
+
Returns:
|
|
230
|
+
The value with every encrypted string under ``new``.
|
|
231
|
+
|
|
232
|
+
Raises:
|
|
233
|
+
UnsafeWriteError: An encrypted string decrypts with neither key, or uses a format that cannot be
|
|
234
|
+
re-encrypted.
|
|
235
|
+
"""
|
|
236
|
+
if isinstance(value, dict):
|
|
237
|
+
return {k: _rekey(v, old, new) for k, v in value.items()}
|
|
238
|
+
if isinstance(value, list):
|
|
239
|
+
return [_rekey(v, old, new) for v in value]
|
|
240
|
+
if crypto.is_enc_string(value):
|
|
241
|
+
try:
|
|
242
|
+
crypto.decrypt(value, new)
|
|
243
|
+
except CryptoError:
|
|
244
|
+
try:
|
|
245
|
+
return str(crypto.encrypt(crypto.decrypt(value, old), new))
|
|
246
|
+
except CryptoError as e:
|
|
247
|
+
raise UnsafeWriteError('item holds encrypted data that cannot be re-encrypted for the organization; not moving it') from e
|
|
248
|
+
return value
|
|
249
|
+
if isinstance(value, str) and _OTHER_ENC.match(value):
|
|
250
|
+
raise UnsafeWriteError('item holds encrypted data in a format this library cannot re-encrypt; not moving it')
|
|
251
|
+
return value
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
_OTHER_ENC = re.compile(r'^[3-9]\.[A-Za-z0-9+/=_-]{8,}')
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _key_for(cipher: Cipher, keys: UserKeys) -> SymmetricKey:
|
|
258
|
+
"""The key an item is encrypted with: its item key if ``raw`` has one, else the owner's key.
|
|
259
|
+
|
|
260
|
+
Args:
|
|
261
|
+
cipher: The item.
|
|
262
|
+
keys: The unlocked keys.
|
|
263
|
+
|
|
264
|
+
Returns:
|
|
265
|
+
The key.
|
|
266
|
+
|
|
267
|
+
Raises:
|
|
268
|
+
CryptoError: The organization key is missing.
|
|
269
|
+
"""
|
|
270
|
+
org_id = cipher.organization_id
|
|
271
|
+
if org_id and org_id not in keys.org_keys:
|
|
272
|
+
raise CryptoError(f'no key for organization {org_id}')
|
|
273
|
+
base = keys.org_keys[org_id] if org_id else keys.user_key
|
|
274
|
+
item_key = JsonObject(cipher.raw).get_str('key')
|
|
275
|
+
return SymmetricKey.from_bytes(crypto.decrypt(item_key, base)) if item_key else base
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def encode_share(cipher: Cipher, keys: UserKeys, user_id: str, organization_id: str) -> dict[str, Any]:
|
|
279
|
+
"""Body for moving a personal item into an organization (``cipher`` part of the share request).
|
|
280
|
+
|
|
281
|
+
Everything is re-encrypted with the organization key: modelled fields, the attachment keys
|
|
282
|
+
(``attachments2``) and any other ciphertext in ``raw`` (passkeys, unmodelled types). An item key is dropped.
|
|
283
|
+
|
|
284
|
+
Args:
|
|
285
|
+
cipher: The personal item.
|
|
286
|
+
keys: The unlocked keys, including the organization key.
|
|
287
|
+
user_id: The logged-in user.
|
|
288
|
+
organization_id: The target organization.
|
|
289
|
+
|
|
290
|
+
Returns:
|
|
291
|
+
The ``cipher`` part of the request.
|
|
292
|
+
|
|
293
|
+
Raises:
|
|
294
|
+
CryptoError: The organization key is missing, or an attachment uses the legacy format without own key.
|
|
295
|
+
UnsafeWriteError: The item has parse issues or holds ciphertext that cannot be re-encrypted.
|
|
296
|
+
"""
|
|
297
|
+
if organization_id not in keys.org_keys:
|
|
298
|
+
raise CryptoError(f'no key for organization {organization_id}')
|
|
299
|
+
if cipher.issues:
|
|
300
|
+
raise UnsafeWriteError('the item contains data this library cannot interpret; not moving it')
|
|
301
|
+
old_key, org_key = _key_for(cipher, keys), keys.org_keys[organization_id]
|
|
302
|
+
attachments2 = {}
|
|
303
|
+
for attachment in cipher.attachments:
|
|
304
|
+
if not attachment.key:
|
|
305
|
+
raise CryptoError(f'attachment {attachment.id} uses the legacy format (no own key) and cannot be shared; re-upload it first')
|
|
306
|
+
attachment_key = crypto.decrypt(attachment.key, old_key)
|
|
307
|
+
attachments2[attachment.id] = {
|
|
308
|
+
'fileName': str(crypto.encrypt(attachment.file_name or '', org_key)),
|
|
309
|
+
'key': str(crypto.encrypt(attachment_key, org_key)),
|
|
310
|
+
}
|
|
311
|
+
raw = {k: _rekey(v, old_key, org_key) for k, v in cipher.raw.items() if k.lower() not in {'key', 'organizationid'}}
|
|
312
|
+
body = encode_cipher(replace(cipher, organization_id=organization_id, raw=raw), keys, user_id)
|
|
313
|
+
body['attachments2'] = attachments2
|
|
314
|
+
return body
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def new_item_key(cipher: Cipher, keys: UserKeys) -> str:
|
|
318
|
+
"""A fresh item key for a new item, wrapped with the owner's key (organization or user).
|
|
319
|
+
|
|
320
|
+
Args:
|
|
321
|
+
cipher: The new item.
|
|
322
|
+
keys: The unlocked keys.
|
|
323
|
+
|
|
324
|
+
Returns:
|
|
325
|
+
The wrapped item key.
|
|
326
|
+
"""
|
|
327
|
+
owner_key = _key_for(dataclasses.replace(cipher, raw={}), keys)
|
|
328
|
+
return str(crypto.encrypt(SymmetricKey.generate().to_bytes(), owner_key))
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def encode_cipher(cipher: Cipher, keys: UserKeys, user_id: str) -> dict[str, Any]:
|
|
332
|
+
"""The encrypted request body for creating or updating an item.
|
|
333
|
+
|
|
334
|
+
Args:
|
|
335
|
+
cipher: The item.
|
|
336
|
+
keys: The unlocked keys.
|
|
337
|
+
user_id: The logged-in user (sent as ``encryptedFor``).
|
|
338
|
+
|
|
339
|
+
Returns:
|
|
340
|
+
The request body.
|
|
341
|
+
"""
|
|
342
|
+
key = _key_for(cipher, keys)
|
|
343
|
+
values: dict[str, Any] = {
|
|
344
|
+
'type': int(cipher.type),
|
|
345
|
+
'name': _enc(cipher.name or '', key),
|
|
346
|
+
'notes': _enc(cipher.notes, key),
|
|
347
|
+
'folderId': cipher.folder_id,
|
|
348
|
+
'organizationId': cipher.organization_id,
|
|
349
|
+
'favorite': cipher.favorite,
|
|
350
|
+
'reprompt': int(cipher.reprompt),
|
|
351
|
+
'encryptedFor': user_id,
|
|
352
|
+
'fields': [{'name': _enc(f.name, key), 'value': _enc(f.value, key), 'type': int(f.type), 'linkedId': f.linked_id} for f in cipher.fields],
|
|
353
|
+
'passwordHistory': [
|
|
354
|
+
{'password': _enc(p.password, key), 'lastUsedDate': format_date(p.last_used_date or datetime.now(UTC))} for p in cipher.password_history
|
|
355
|
+
],
|
|
356
|
+
}
|
|
357
|
+
if cipher.raw:
|
|
358
|
+
revision = JsonObject(cipher.raw).get_str('revisionDate')
|
|
359
|
+
if revision:
|
|
360
|
+
values['lastKnownRevisionDate'] = revision
|
|
361
|
+
if cipher.type == CipherType.LOGIN:
|
|
362
|
+
values['login'] = encode_login(cipher.login or Login(), _raw_sub(cipher, 'login'), key)
|
|
363
|
+
elif cipher.type == CipherType.SECURE_NOTE:
|
|
364
|
+
values['secureNote'] = _merge(_raw_sub(cipher, 'secureNote'), {'type': cipher.secure_note_type or 0})
|
|
365
|
+
elif cipher.type == CipherType.CARD:
|
|
366
|
+
values['card'] = encode_card(cipher.card or Card(), _raw_sub(cipher, 'card'), key)
|
|
367
|
+
elif cipher.type == CipherType.IDENTITY:
|
|
368
|
+
values['identity'] = encode_identity(cipher.identity or Identity(), _raw_sub(cipher, 'identity'), key)
|
|
369
|
+
elif cipher.type == CipherType.SSH_KEY:
|
|
370
|
+
values['sshKey'] = encode_ssh_key(cipher.ssh_key or SshKey(), _raw_sub(cipher, 'sshKey'), key)
|
|
371
|
+
else:
|
|
372
|
+
for name, value in cipher.data.items():
|
|
373
|
+
values[name] = _encode_generic(value, _raw_sub(cipher, name), key)
|
|
374
|
+
body = _merge(cipher.raw, values)
|
|
375
|
+
for response_only in ('object', 'attachments', 'permissions', 'edit', 'viewPassword', 'organizationUseTotp', 'collectionIds'):
|
|
376
|
+
for k in [k for k in body if k.lower() == response_only.lower()]:
|
|
377
|
+
del body[k]
|
|
378
|
+
return body
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def with_password_history(new: Cipher, current: Cipher, now: datetime | None = None) -> Cipher:
|
|
382
|
+
"""Apply the web vault's password history rule.
|
|
383
|
+
|
|
384
|
+
If the login password changed and the caller did not touch the history, the previous password is prepended
|
|
385
|
+
(keeping at most 5 entries) and the password revision date is set.
|
|
386
|
+
|
|
387
|
+
Args:
|
|
388
|
+
new: The edited item.
|
|
389
|
+
current: The current server version.
|
|
390
|
+
now: The timestamp for the new history entry; defaults to now.
|
|
391
|
+
|
|
392
|
+
Returns:
|
|
393
|
+
The item with the history applied.
|
|
394
|
+
"""
|
|
395
|
+
if new.login is None or current.login is None:
|
|
396
|
+
return new
|
|
397
|
+
old_pw, new_pw = current.login.password, new.login.password
|
|
398
|
+
if old_pw == new_pw or not old_pw or new.password_history != current.password_history:
|
|
399
|
+
return new
|
|
400
|
+
now = now or datetime.now(UTC)
|
|
401
|
+
history = (PasswordHistoryEntry(password=old_pw, last_used_date=now), *new.password_history)[:PASSWORD_HISTORY_SIZE]
|
|
402
|
+
return replace(new, login=replace(new.login, password_revision_date=now), password_history=history)
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def encode_attachment_request(file_name: str, encrypted_size: int, attachment_key: SymmetricKey, item_key: SymmetricKey) -> dict[str, Any]:
|
|
406
|
+
"""Body for ``POST /api/ciphers/{id}/attachment/v2``.
|
|
407
|
+
|
|
408
|
+
Args:
|
|
409
|
+
file_name: The file name (encrypted with the item key).
|
|
410
|
+
encrypted_size: Size of the encrypted file in bytes.
|
|
411
|
+
attachment_key: The attachment's own key (wrapped with the item key).
|
|
412
|
+
item_key: The item key.
|
|
413
|
+
|
|
414
|
+
Returns:
|
|
415
|
+
The request body.
|
|
416
|
+
"""
|
|
417
|
+
return {
|
|
418
|
+
'key': str(crypto.encrypt(attachment_key.to_bytes(), item_key)),
|
|
419
|
+
'fileName': str(crypto.encrypt(file_name, item_key)),
|
|
420
|
+
'fileSize': encrypted_size,
|
|
421
|
+
'adminRequest': False,
|
|
422
|
+
}
|
vaultwarden2/_json.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""Lenient JSON access for server responses.
|
|
2
|
+
|
|
3
|
+
Vaultwarden JSON mixes camelCase and PascalCase and changes over time. Everything here
|
|
4
|
+
is tolerant: keys are matched case-insensitively, missing keys become ``None``, unknown keys are
|
|
5
|
+
ignored. Callers keep the original object (``raw``) for round-tripping.
|
|
6
|
+
|
|
7
|
+
Tolerance must never hide data loss: when a key is *present* but holds a value of an unexpected
|
|
8
|
+
type, the getter still returns ``None`` but records an issue (``path: problem``). Objects created
|
|
9
|
+
from one root share its issue list, so a whole item's problems end up in one place. Writers refuse
|
|
10
|
+
to touch fields with recorded issues.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from datetime import datetime
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class JsonObject:
|
|
20
|
+
"""Read-only, case-insensitive view of a JSON object that records type problems.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
raw: The decoded JSON value. Anything that is not a dict behaves like an empty object (and is recorded as an
|
|
24
|
+
issue unless it is None).
|
|
25
|
+
path: Location of this object, used in issue messages (for example ``cipher 1234.login``).
|
|
26
|
+
issues: The issue list to append to; objects created from one root share it. A new list by default.
|
|
27
|
+
|
|
28
|
+
Attributes:
|
|
29
|
+
raw: The wrapped dict (the original, with its original key spelling).
|
|
30
|
+
path: Location of this object in issue messages.
|
|
31
|
+
issues: Recorded problems as ``path: problem``; never contains values.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
__slots__ = ('_data', 'issues', 'path', 'raw')
|
|
35
|
+
|
|
36
|
+
raw: dict[str, Any]
|
|
37
|
+
path: str
|
|
38
|
+
issues: list[str]
|
|
39
|
+
|
|
40
|
+
def __init__(self, raw: object, *, path: str = '', issues: list[str] | None = None) -> None:
|
|
41
|
+
self.raw = raw if isinstance(raw, dict) else {}
|
|
42
|
+
self._data = {str(k).lower(): v for k, v in self.raw.items()}
|
|
43
|
+
self.path = path
|
|
44
|
+
self.issues = issues if issues is not None else []
|
|
45
|
+
if raw is not None and not isinstance(raw, dict):
|
|
46
|
+
self.issue('', f'expected an object, got {type(raw).__name__}')
|
|
47
|
+
|
|
48
|
+
def _where(self, key: str) -> str:
|
|
49
|
+
"""Location of a key for issue messages.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
key: The key, or empty for the object itself.
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
``path.key``, or a placeholder for the root.
|
|
56
|
+
"""
|
|
57
|
+
return f'{self.path}.{key}' if self.path and key else (self.path or key or '<root>')
|
|
58
|
+
|
|
59
|
+
def issue(self, key: str, problem: str) -> None:
|
|
60
|
+
"""Record a problem with a key. No value is recorded: it may be secret.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
key: The key the problem concerns (empty for the object itself).
|
|
64
|
+
problem: What is wrong.
|
|
65
|
+
"""
|
|
66
|
+
self.issues.append(f'{self._where(key)}: {problem}')
|
|
67
|
+
|
|
68
|
+
def __contains__(self, key: str) -> bool:
|
|
69
|
+
"""Case-insensitive membership test.
|
|
70
|
+
|
|
71
|
+
Args:
|
|
72
|
+
key: The key.
|
|
73
|
+
|
|
74
|
+
Returns:
|
|
75
|
+
True if the key is present (in any spelling).
|
|
76
|
+
"""
|
|
77
|
+
return key.lower() in self._data
|
|
78
|
+
|
|
79
|
+
def get(self, key: str) -> Any:
|
|
80
|
+
"""The raw value of a key, without type checks.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
key: The key (case-insensitive).
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
The value, or None if absent.
|
|
87
|
+
"""
|
|
88
|
+
return self._data.get(key.lower())
|
|
89
|
+
|
|
90
|
+
def _typed(self, key: str, kind: type | tuple[type, ...], label: str) -> Any:
|
|
91
|
+
"""The value of a key if it has the expected type; records an issue otherwise.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
key: The key.
|
|
95
|
+
kind: The accepted type(s). ``bool`` is only accepted when listed explicitly.
|
|
96
|
+
label: Description of the expected type for the issue message.
|
|
97
|
+
|
|
98
|
+
Returns:
|
|
99
|
+
The value, or None if absent or of another type.
|
|
100
|
+
"""
|
|
101
|
+
v = self.get(key)
|
|
102
|
+
if v is None:
|
|
103
|
+
return None
|
|
104
|
+
if isinstance(v, kind) and not (isinstance(v, bool) and bool not in (kind if isinstance(kind, tuple) else (kind,))):
|
|
105
|
+
return v
|
|
106
|
+
self.issue(key, f'expected {label}, got {type(v).__name__}')
|
|
107
|
+
return None
|
|
108
|
+
|
|
109
|
+
def get_str(self, key: str) -> str | None:
|
|
110
|
+
"""A string value.
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
key: The key.
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
The string, or None if absent or not a string (recorded as issue).
|
|
117
|
+
"""
|
|
118
|
+
return self._typed(key, str, 'a string') # type: ignore[no-any-return]
|
|
119
|
+
|
|
120
|
+
def get_int(self, key: str) -> int | None:
|
|
121
|
+
"""An integer value; numeric strings are accepted.
|
|
122
|
+
|
|
123
|
+
Args:
|
|
124
|
+
key: The key.
|
|
125
|
+
|
|
126
|
+
Returns:
|
|
127
|
+
The integer, or None if absent or not an integer (recorded as issue).
|
|
128
|
+
"""
|
|
129
|
+
v = self.get(key)
|
|
130
|
+
if isinstance(v, str) and v.strip().lstrip('-').isdigit():
|
|
131
|
+
return int(v)
|
|
132
|
+
return self._typed(key, int, 'an integer') # type: ignore[no-any-return]
|
|
133
|
+
|
|
134
|
+
def get_bool(self, key: str, default: bool = False) -> bool:
|
|
135
|
+
"""A boolean value.
|
|
136
|
+
|
|
137
|
+
Args:
|
|
138
|
+
key: The key.
|
|
139
|
+
default: The value when absent or not a boolean.
|
|
140
|
+
|
|
141
|
+
Returns:
|
|
142
|
+
The boolean.
|
|
143
|
+
"""
|
|
144
|
+
v = self._typed(key, bool, 'a boolean')
|
|
145
|
+
return v if isinstance(v, bool) else default
|
|
146
|
+
|
|
147
|
+
def get_datetime(self, key: str) -> datetime | None:
|
|
148
|
+
"""An ISO-8601 timestamp.
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
key: The key.
|
|
152
|
+
|
|
153
|
+
Returns:
|
|
154
|
+
The datetime, or None if absent or unparseable (recorded as issue).
|
|
155
|
+
"""
|
|
156
|
+
v = self.get_str(key)
|
|
157
|
+
if v is None:
|
|
158
|
+
return None
|
|
159
|
+
try:
|
|
160
|
+
return datetime.fromisoformat(v.replace('Z', '+00:00'))
|
|
161
|
+
except ValueError:
|
|
162
|
+
self.issue(key, 'not an ISO-8601 timestamp')
|
|
163
|
+
return None
|
|
164
|
+
|
|
165
|
+
def obj(self, key: str) -> JsonObject | None:
|
|
166
|
+
"""A nested object, sharing this object's issue list.
|
|
167
|
+
|
|
168
|
+
Args:
|
|
169
|
+
key: The key.
|
|
170
|
+
|
|
171
|
+
Returns:
|
|
172
|
+
The nested object, or None if absent or not an object.
|
|
173
|
+
"""
|
|
174
|
+
v = self._typed(key, dict, 'an object')
|
|
175
|
+
return JsonObject(v, path=self._where(key), issues=self.issues) if v is not None else None
|
|
176
|
+
|
|
177
|
+
def objs(self, key: str) -> list[JsonObject]:
|
|
178
|
+
"""A list of nested objects; non-object entries are recorded as issues and skipped.
|
|
179
|
+
|
|
180
|
+
Args:
|
|
181
|
+
key: The key.
|
|
182
|
+
|
|
183
|
+
Returns:
|
|
184
|
+
The nested objects; empty if absent.
|
|
185
|
+
"""
|
|
186
|
+
v = self._typed(key, list, 'a list')
|
|
187
|
+
if v is None:
|
|
188
|
+
return []
|
|
189
|
+
result = []
|
|
190
|
+
for i, item in enumerate(v):
|
|
191
|
+
if isinstance(item, dict):
|
|
192
|
+
result.append(JsonObject(item, path=f'{self._where(key)}[{i}]', issues=self.issues))
|
|
193
|
+
else:
|
|
194
|
+
self.issue(f'{key}[{i}]', f'expected an object, got {type(item).__name__}')
|
|
195
|
+
return result
|
|
196
|
+
|
|
197
|
+
def strs(self, key: str) -> list[str]:
|
|
198
|
+
"""A list of strings; non-string entries are recorded as issues and skipped.
|
|
199
|
+
|
|
200
|
+
Args:
|
|
201
|
+
key: The key.
|
|
202
|
+
|
|
203
|
+
Returns:
|
|
204
|
+
The strings; empty if absent.
|
|
205
|
+
"""
|
|
206
|
+
v = self._typed(key, list, 'a list')
|
|
207
|
+
if v is None:
|
|
208
|
+
return []
|
|
209
|
+
result = []
|
|
210
|
+
for i, item in enumerate(v):
|
|
211
|
+
if isinstance(item, str):
|
|
212
|
+
result.append(item)
|
|
213
|
+
else:
|
|
214
|
+
self.issue(f'{key}[{i}]', f'expected a string, got {type(item).__name__}')
|
|
215
|
+
return result
|