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.
@@ -0,0 +1,914 @@
1
+ """Organizations, collections, members, groups and policies."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import replace
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ from vaultwarden2 import _core, _encode, _merge, _offload, crypto
9
+ from vaultwarden2._json import JsonObject
10
+ from vaultwarden2.errors import ApiError, BulkOperationError, NotUnlockedError, UnsafeWriteError, VaultwardenError
11
+ from vaultwarden2.models import (
12
+ Cipher,
13
+ Collection,
14
+ CollectionAccess,
15
+ Group,
16
+ Member,
17
+ Organization,
18
+ OrganizationExport,
19
+ OrganizationUserType,
20
+ Policy,
21
+ PolicyType,
22
+ )
23
+
24
+ if TYPE_CHECKING:
25
+ from collections.abc import Sequence
26
+
27
+ from vaultwarden2.models import CollectionRef, GroupRef, ItemRef, MemberRef, OrganizationRef
28
+
29
+ from . import vault as _vault_mod
30
+ from .base import _collection_access, _collection_id, _item_id
31
+
32
+
33
+ class AsyncOrganizationsMixin(_vault_mod.AsyncVaultMixin):
34
+ """Organizations and everything inside them.
35
+
36
+ Organization items are encrypted with an item key wrapped with the organization key (older items directly with
37
+ the organization key). Every confirmed member receives the organization key encrypted to their own public key. Admin rights in the organization are needed for most operations here.
38
+ """
39
+
40
+ async def create_organization(self, name: str, *, billing_email: str | None = None, collection_name: str = 'Default collection') -> Organization:
41
+ """Create an organization owned by the logged-in user, with one initial collection.
42
+
43
+ The organization key and the organization's RSA key pair are generated on this machine.
44
+
45
+ Args:
46
+ name: The organization name (plain text on the server).
47
+ billing_email: The billing contact. Defaults to the account's email.
48
+ collection_name: Name of the first collection (encrypted).
49
+
50
+ Returns:
51
+ The new organization, with the user as owner.
52
+
53
+ Raises:
54
+ NotUnlockedError: The account has no key pair.
55
+ ApiError: The server refused (for example organization creation is restricted).
56
+ """
57
+ keys = self._require_keys()
58
+ if keys.private_key is None:
59
+ raise NotUnlockedError('account has no key pair')
60
+ profile = self._profile or await self._load_profile()
61
+ payload, org_key = await _offload.arun_cpu(
62
+ _core.organization_payload, name, billing_email or profile.get_str('email') or '', collection_name, keys.private_key.public_key()
63
+ )
64
+ body = JsonObject(await self.request('POST', '/api/organizations', json=payload))
65
+ org_id = body.get_str('id') or ''
66
+ keys.org_keys[org_id] = org_key
67
+ for org in await self.organizations():
68
+ if org.id == org_id:
69
+ return org
70
+ raise ApiError(500, 'created organization not found in profile')
71
+
72
+ async def rename_organization(self, organization: OrganizationRef, name: str, *, billing_email: str | None = None) -> None:
73
+ """Rename an organization (owner only).
74
+
75
+ Args:
76
+ organization: The organization, as object, id or unique name.
77
+ name: The new name.
78
+ billing_email: A new billing email. Defaults to keeping the current one.
79
+
80
+ Raises:
81
+ UnsafeWriteError: The server did not return the current billing email and none was given; nothing was sent.
82
+ VaultwardenError: The organization or a referenced member, group or collection was not found.
83
+ ApiError: Not the owner.
84
+ """
85
+ org_id = await self._resolve_organization(organization)
86
+ if billing_email is None:
87
+ billing_email = JsonObject(await self.request('GET', f'/api/organizations/{org_id}')).get_str('billingEmail')
88
+ if not billing_email:
89
+ raise UnsafeWriteError('the server did not return the billing email; pass billing_email= to avoid clearing it')
90
+ await self.request('PUT', f'/api/organizations/{org_id}', json={'name': name, 'billingEmail': billing_email})
91
+
92
+ async def delete_organization(self, organization: OrganizationRef, password: str) -> None:
93
+ """Delete an organization with all its items and collections. This cannot be undone.
94
+
95
+ Args:
96
+ organization: The organization, as object, id or unique name.
97
+ password: The master password of the owner (the server re-checks it).
98
+
99
+ Raises:
100
+ VaultwardenError: The organization or a referenced member, group or collection was not found.
101
+ ApiError: Wrong password or not the owner.
102
+ """
103
+ org_id = await self._resolve_organization(organization)
104
+ await self.request('DELETE', f'/api/organizations/{org_id}', json={'masterPasswordHash': await self._password_hash(password)})
105
+ self._require_keys().org_keys.pop(org_id, None)
106
+
107
+ async def leave_organization(self, organization: OrganizationRef) -> None:
108
+ """Leave an organization. Its items are no longer accessible afterwards.
109
+
110
+ Args:
111
+ organization: The organization, as object, id or unique name.
112
+
113
+ Raises:
114
+ VaultwardenError: The organization or a referenced member, group or collection was not found.
115
+ ApiError: The server refused (for example the last owner cannot leave).
116
+ """
117
+ org_id = await self._resolve_organization(organization)
118
+ await self.request('POST', f'/api/organizations/{org_id}/leave')
119
+ self._require_keys().org_keys.pop(org_id, None)
120
+
121
+ async def organization_collections(self, organization: OrganizationRef) -> list[Collection]:
122
+ """All collections of an organization (admin view), decrypted.
123
+
124
+ Args:
125
+ organization: The organization, as object, id or unique name.
126
+
127
+ Returns:
128
+ The collections, including ones the user is not assigned to.
129
+
130
+ Raises:
131
+ VaultwardenError: The organization or a referenced member, group or collection was not found.
132
+ """
133
+ org_id = await self._resolve_organization(organization)
134
+ body = JsonObject(await self.request('GET', f'/api/organizations/{org_id}/collections'))
135
+ keys = self._require_keys()
136
+ return [_core.decrypt_collection({**c.raw, 'organizationId': c.get_str('organizationId') or org_id}, keys) for c in body.objs('data')]
137
+
138
+ async def create_collection(
139
+ self,
140
+ organization: OrganizationRef,
141
+ name: str,
142
+ *,
143
+ members: Sequence[tuple[MemberRef, CollectionAccess | None]] = (),
144
+ external_id: str | None = None,
145
+ ) -> Collection:
146
+ """Create a collection.
147
+
148
+ Collections are stored flat. The web vault and the apps nest them by name: `Ops/Servers` is shown inside `Ops`.
149
+
150
+ Args:
151
+ organization: The organization, as object, id or unique name.
152
+ name: The collection name (encrypted with the organization key). Use `/` to nest it under another collection.
153
+ members: Members to give access, as ``(member, access)`` pairs. ``access`` is a
154
+ [CollectionAccess][vaultwarden2.models.CollectionAccess] for read-only / hide-passwords / manage rights,
155
+ or None for normal access. ``member`` is an object, membership id or email.
156
+ external_id: An identifier for directory synchronisation.
157
+
158
+ Returns:
159
+ The new collection.
160
+
161
+ Raises:
162
+ VaultwardenError: The organization or a referenced member, group or collection was not found.
163
+ """
164
+ org_id = await self._resolve_organization(organization)
165
+ org_key = self._org_key(org_id)
166
+ users = [await self._member_access(org_id, member, access) for member, access in members]
167
+ payload = {'name': _merge.verified_encrypt(name, org_key), 'externalId': external_id, 'groups': [], 'users': users}
168
+ body = await self.request('POST', f'/api/organizations/{org_id}/collections', json=payload)
169
+ return _core.decrypt_collection({**body, 'organizationId': org_id}, self._require_keys())
170
+
171
+ async def rename_collection(self, collection: Collection, name: str) -> Collection:
172
+ """Rename a collection; member and group access stay as they are.
173
+
174
+ Args:
175
+ collection: The collection (from ``organization_collections`` or ``collections``).
176
+ name: The new name.
177
+
178
+ Returns:
179
+ The renamed collection.
180
+
181
+ Raises:
182
+ UnsafeWriteError: The server did not return the current access lists, so they could not be kept;
183
+ nothing was sent.
184
+ """
185
+ org_id = collection.organization_id
186
+ details = JsonObject(await self.request('GET', f'/api/organizations/{org_id}/collections/{collection.id}/details'))
187
+ users = await self.request('GET', f'/api/organizations/{org_id}/collections/{collection.id}/users')
188
+ payload = {
189
+ 'name': _merge.verified_encrypt(name, self._org_key(org_id)),
190
+ 'externalId': details.get_str('externalId'),
191
+ 'groups': _existing_list(details.get('groups'), "the collection's group access"),
192
+ 'users': _existing_list(users, "the collection's member access"),
193
+ }
194
+ body = await self.request('PUT', f'/api/organizations/{org_id}/collections/{collection.id}', json=payload)
195
+ return _core.decrypt_collection({**body, 'organizationId': org_id}, self._require_keys())
196
+
197
+ async def delete_collection(self, collection: Collection) -> None:
198
+ """Delete a collection. Its items stay in the organization.
199
+
200
+ Args:
201
+ collection: The collection.
202
+ """
203
+ await self.request('DELETE', f'/api/organizations/{collection.organization_id}/collections/{collection.id}')
204
+
205
+ async def organization_ciphers(self, organization: OrganizationRef) -> list[Cipher]:
206
+ """All items of an organization (admin view), decrypted.
207
+
208
+ Args:
209
+ organization: The organization, as object, id or unique name.
210
+
211
+ Returns:
212
+ The organization's items, including ones in collections the user is not assigned to.
213
+
214
+ Raises:
215
+ CryptoError: An item cannot be decrypted.
216
+ """
217
+ org_id = await self._resolve_organization(organization)
218
+ body = JsonObject(await self.request('GET', '/api/ciphers/organization-details', params={'organizationId': org_id}))
219
+ return await _offload.arun_cpu(_core.decrypt_ciphers, [c.raw for c in body.objs('data')], self._require_keys())
220
+
221
+ async def move_to_organization(self, item: ItemRef, organization: OrganizationRef, collections: Sequence[CollectionRef]) -> Cipher:
222
+ """Move a personal item, with its attachments, into an organization.
223
+
224
+ Everything is re-encrypted with the organization key: fields, attachment keys, and any other ciphertext in the
225
+ item (such as passkeys). The payload is verified before it is sent.
226
+
227
+ Args:
228
+ item: The personal item, as object or id.
229
+ organization: The organization, as object, id or unique name.
230
+ collections: The collections to put the item in (objects or ids); at least one.
231
+
232
+ Returns:
233
+ The item, now owned by the organization.
234
+
235
+ Raises:
236
+ VaultwardenError: No collections given, or the item already belongs to an organization.
237
+ UnsafeWriteError: The item holds data that cannot be re-encrypted (unknown key or format), an old-style
238
+ attachment without its own key, or verification failed. Nothing was sent.
239
+ """
240
+ if not collections:
241
+ raise VaultwardenError('organization items need at least one collection')
242
+ org_id = await self._resolve_organization(organization)
243
+ keys = self._require_keys()
244
+ cipher = await self._resolve_cipher(item)
245
+ if cipher.organization_id:
246
+ raise VaultwardenError('item already belongs to an organization')
247
+ body = await _offload.arun_cpu(_encode.encode_share, cipher, keys, self._user_id(), org_id)
248
+ await _offload.arun_cpu(_merge.verify_new, body, keys, replace(cipher, organization_id=org_id))
249
+ payload = {'cipher': body, 'collectionIds': [_collection_id(c) for c in collections]}
250
+ return _core.decrypt_cipher(await self.request('PUT', f'/api/ciphers/{cipher.id}/share', json=payload), keys)
251
+
252
+ async def set_collections(self, item: ItemRef, collections: Sequence[CollectionRef]) -> Cipher:
253
+ """Replace the collections an organization item belongs to.
254
+
255
+ Args:
256
+ item: The organization item, as object or id.
257
+ collections: The new collections (objects or ids); at least one, so the item stays reachable.
258
+
259
+ Returns:
260
+ The updated item.
261
+
262
+ Raises:
263
+ UnsafeWriteError: The list is empty; nothing was sent.
264
+ """
265
+ if not collections:
266
+ raise UnsafeWriteError('an organization item needs at least one collection')
267
+ item_id = _item_id(item)
268
+ await self.request('PUT', f'/api/ciphers/{item_id}/collections_v2', json={'collectionIds': [_collection_id(c) for c in collections]})
269
+ return await self.get_cipher(item_id)
270
+
271
+ async def members(self, organization: OrganizationRef) -> list[Member]:
272
+ """The members of an organization, with role, status and collection access.
273
+
274
+ Args:
275
+ organization: The organization, as object, id or unique name.
276
+
277
+ Returns:
278
+ One entry per membership (including invited and revoked ones).
279
+ """
280
+ org_id = await self._resolve_organization(organization)
281
+ body = JsonObject(await self.request('GET', f'/api/organizations/{org_id}/users', params={'includeCollections': 'true'}))
282
+ return [_core.parse_member(m.raw, org_id) for m in body.objs('data')]
283
+
284
+ async def _resolve_member(self, org_id: str, member: MemberRef) -> Member:
285
+ """Find a membership by object, id or email.
286
+
287
+ Args:
288
+ org_id: The organization id.
289
+ member: The member reference.
290
+
291
+ Returns:
292
+ The membership.
293
+
294
+ Raises:
295
+ VaultwardenError: No such member.
296
+ """
297
+ for m in await self.members(org_id):
298
+ if m.id == (member.id if isinstance(member, Member) else member) or (isinstance(member, str) and m.email and m.email.lower() == member.lower()):
299
+ return m
300
+ raise VaultwardenError(f'member {member if isinstance(member, str) else member.id!r} not found')
301
+
302
+ async def _member_access(self, org_id: str, member: MemberRef, access: CollectionAccess | None) -> dict[str, Any]:
303
+ """Collection access payload for one member.
304
+
305
+ Args:
306
+ org_id: The organization id.
307
+ member: The member reference.
308
+ access: The access rights, or None for normal access.
309
+
310
+ Returns:
311
+ The access entry as the server expects it.
312
+ """
313
+ resolved = await self._resolve_member(org_id, member)
314
+ return _core.collection_access_payload(replace(access or CollectionAccess(id=''), id=resolved.id))
315
+
316
+ async def invite(
317
+ self,
318
+ organization: OrganizationRef,
319
+ emails: str | Sequence[str],
320
+ *,
321
+ role: OrganizationUserType = OrganizationUserType.USER,
322
+ collections: Sequence[CollectionRef] = (),
323
+ groups: Sequence[GroupRef] = (),
324
+ ) -> None:
325
+ """Invite users to an organization.
326
+
327
+ On servers that send no emails (neither ``SMTP_HOST`` nor ``USE_SENDMAIL`` configured), existing accounts are accepted immediately and only need
328
+ [confirm_member][vaultwarden2.AsyncVaultwardenClient.confirm_member]; otherwise the user accepts the mailed
329
+ invitation first.
330
+
331
+ Args:
332
+ organization: The organization, as object, id or unique name.
333
+ emails: One email address or several.
334
+ role: The role of the new members.
335
+ collections: Collections, as objects or ids, or [CollectionAccess][vaultwarden2.models.CollectionAccess] entries
336
+ to set read-only, hide-passwords or manage rights.
337
+ groups: Groups to add the new members to, as objects, ids or unique names.
338
+
339
+ Raises:
340
+ VaultwardenError: The organization or a referenced member, group or collection was not found.
341
+ ApiError: The server refused (for example already a member, or invitations disabled).
342
+ """
343
+ org_id = await self._resolve_organization(organization)
344
+ payload = {
345
+ 'emails': [emails] if isinstance(emails, str) else list(emails),
346
+ 'type': int(role),
347
+ 'groups': [await self._resolve_group(org_id, g) for g in groups],
348
+ 'collections': [_core.collection_access_payload(_collection_access(c)) for c in collections],
349
+ 'permissions': {},
350
+ }
351
+ await self.request('POST', f'/api/organizations/{org_id}/users/invite', json=payload)
352
+
353
+ async def confirm_member(self, organization: OrganizationRef, member: MemberRef, *, expected_public_key: str | None = None) -> Member:
354
+ """Confirm an accepted member: share the organization key with them.
355
+
356
+ The key is encrypted to the member's public key as provided by the server. A malicious server could substitute
357
+ that key; compare it out of band and pass it as ``expected_public_key`` to rule that out.
358
+
359
+ Args:
360
+ organization: The organization, as object, id or unique name.
361
+ member: The member, as [Member][vaultwarden2.models.Member], membership id or email address.
362
+ expected_public_key: The member's public key (base64, as returned by
363
+ [member_public_key][vaultwarden2.AsyncVaultwardenClient.member_public_key]) verified out of band.
364
+
365
+ Returns:
366
+ The confirmed membership.
367
+
368
+ Raises:
369
+ VaultwardenError: The member has no account yet, or the key does not match ``expected_public_key``
370
+ (nothing was sent).
371
+ """
372
+ org_id = await self._resolve_organization(organization)
373
+ resolved = await self._resolve_member(org_id, member)
374
+ if not resolved.user_id:
375
+ raise VaultwardenError('member has no account yet (invitation not accepted)')
376
+ public_b64 = await self.member_public_key(resolved.user_id)
377
+ if expected_public_key is not None and expected_public_key != public_b64:
378
+ raise VaultwardenError('member public key does not match the expected key; not confirming')
379
+ encrypted = crypto.rsa_encrypt(self._org_key(org_id).to_bytes(), crypto.load_public_key(public_b64))
380
+ await self.request('POST', f'/api/organizations/{org_id}/users/{resolved.id}/confirm', json={'key': str(encrypted)})
381
+ return await self._resolve_member(org_id, resolved.id)
382
+
383
+ async def member_public_key(self, user_id: str) -> str:
384
+ """The public key of a user, as stored on the server.
385
+
386
+ Args:
387
+ user_id: The user id (``Member.user_id``, not the membership id).
388
+
389
+ Returns:
390
+ The base64 public key.
391
+
392
+ Raises:
393
+ ApiError: No such user, or the server returned no key.
394
+ """
395
+ key = JsonObject(await self.request('GET', f'/api/users/{user_id}/public-key')).get_str('publicKey')
396
+ if not key:
397
+ raise ApiError(500, 'server returned no public key')
398
+ return key
399
+
400
+ async def update_member(
401
+ self,
402
+ organization: OrganizationRef,
403
+ member: MemberRef,
404
+ *,
405
+ role: OrganizationUserType | None = None,
406
+ collections: Sequence[CollectionRef] | None = None,
407
+ groups: Sequence[GroupRef] | None = None,
408
+ ) -> Member:
409
+ """Change a member's role, collection access and/or groups.
410
+
411
+ Admins and owners always have access to all collections; the server drops per-collection assignments for them.
412
+
413
+ Args:
414
+ organization: The organization, as object, id or unique name.
415
+ member: The member, as [Member][vaultwarden2.models.Member], membership id or email address.
416
+ role: The new role. None keeps the current one.
417
+ collections: Collections, as objects or ids, or [CollectionAccess][vaultwarden2.models.CollectionAccess] entries
418
+ to set read-only, hide-passwords or manage rights. None keeps the current access; an empty list removes all.
419
+ groups: The groups (objects, ids or unique names). None keeps the current groups.
420
+
421
+ Returns:
422
+ The updated membership.
423
+
424
+ Raises:
425
+ UnsafeWriteError: The server did not return data the update must send back (current access, groups or
426
+ permissions); nothing was sent.
427
+ VaultwardenError: The organization or a referenced member, group or collection was not found.
428
+ """
429
+ org_id = await self._resolve_organization(organization)
430
+ current = await self._resolve_member(org_id, member)
431
+ if collections is None:
432
+ current_access = _existing_list(JsonObject(current.raw).get('collections'), "the member's collection access")
433
+ else:
434
+ current_access = [_core.collection_access_payload(_collection_access(c)) for c in collections]
435
+ # vaultwarden reports every manager as "custom" (type 4); `permissions` is null when the member has no extra
436
+ # permissions (only "manage all collections" is supported, as access_all). Null is sent back as {}, which
437
+ # the server reads the same way. A missing key means the answer is incomplete: refuse.
438
+ if 'permissions' not in JsonObject(current.raw):
439
+ raise UnsafeWriteError("the server did not return the member's permissions; not updating to avoid losing them")
440
+ permissions = JsonObject(current.raw).get('permissions')
441
+ payload = {
442
+ 'type': int(role if role is not None else (current.type if current.type is not None else OrganizationUserType.USER)),
443
+ 'collections': current_access,
444
+ 'groups': [await self._resolve_group(org_id, g) for g in groups] if groups is not None else await self._member_group_ids(org_id, current.id),
445
+ 'permissions': permissions if isinstance(permissions, dict) else {},
446
+ }
447
+ await self.request('PUT', f'/api/organizations/{org_id}/users/{current.id}', json=payload)
448
+ return await self._resolve_member(org_id, current.id)
449
+
450
+ async def revoke_member(self, organization: OrganizationRef, member: MemberRef) -> None:
451
+ """Revoke a member's access. The membership is kept and can be restored.
452
+
453
+ Args:
454
+ organization: The organization, as object, id or unique name.
455
+ member: The member, as [Member][vaultwarden2.models.Member], membership id or email address.
456
+ """
457
+ org_id = await self._resolve_organization(organization)
458
+ await self.request('PUT', f'/api/organizations/{org_id}/users/{(await self._resolve_member(org_id, member)).id}/revoke')
459
+
460
+ async def restore_member(self, organization: OrganizationRef, member: MemberRef) -> None:
461
+ """Restore a revoked member.
462
+
463
+ Args:
464
+ organization: The organization, as object, id or unique name.
465
+ member: The member, as [Member][vaultwarden2.models.Member], membership id or email address.
466
+ """
467
+ org_id = await self._resolve_organization(organization)
468
+ await self.request('PUT', f'/api/organizations/{org_id}/users/{(await self._resolve_member(org_id, member)).id}/restore')
469
+
470
+ async def remove_member(self, organization: OrganizationRef, member: MemberRef) -> None:
471
+ """Remove a member from the organization.
472
+
473
+ Args:
474
+ organization: The organization, as object, id or unique name.
475
+ member: The member, as [Member][vaultwarden2.models.Member], membership id or email address.
476
+ """
477
+ org_id = await self._resolve_organization(organization)
478
+ await self.request('DELETE', f'/api/organizations/{org_id}/users/{(await self._resolve_member(org_id, member)).id}')
479
+
480
+ async def _member_ids(self, org_id: str, members: Sequence[MemberRef] | None, *, status: int | None = None) -> list[str]:
481
+ """Membership ids for member references, or all members with a given status.
482
+
483
+ Args:
484
+ org_id: The organization id.
485
+ members: The member references, or None for all members.
486
+ status: With ``members`` None, only members in this status.
487
+
488
+ Returns:
489
+ The membership ids.
490
+
491
+ Raises:
492
+ VaultwardenError: A referenced member was not found.
493
+ """
494
+ all_members = await self.members(org_id)
495
+ if members is None:
496
+ return [m.id for m in all_members if status is None or m.status == status]
497
+ ids = []
498
+ for ref in members:
499
+ key = ref.id if isinstance(ref, Member) else ref
500
+ match = next((m for m in all_members if m.id == key or (m.email and m.email.lower() == key.lower())), None)
501
+ if match is None:
502
+ raise VaultwardenError(f'member {key!r} not found')
503
+ ids.append(match.id)
504
+ return ids
505
+
506
+ @staticmethod
507
+ def _bulk_result(body: Any) -> None:
508
+ """Raise if a bulk member response reports failures.
509
+
510
+ Args:
511
+ body: The bulk response (``{data: [{id, error}]}``).
512
+
513
+ Raises:
514
+ BulkOperationError: At least one entry failed.
515
+ """
516
+ failures = {}
517
+ for entry in JsonObject(body).objs('data'):
518
+ error = entry.get_str('error')
519
+ if error:
520
+ failures[entry.get_str('id') or '?'] = error
521
+ if failures:
522
+ raise BulkOperationError(failures)
523
+
524
+ async def confirm_members(self, organization: OrganizationRef, members: Sequence[MemberRef] | None = None) -> list[str]:
525
+ """Confirm several accepted members at once.
526
+
527
+ Public keys come from the server unverified; use ``confirm_member`` with ``expected_public_key`` where that
528
+ matters.
529
+
530
+ Args:
531
+ organization: The organization, as object, id or unique name.
532
+ members: The members, each as object, membership id or email address. None confirms every accepted member.
533
+
534
+ Returns:
535
+ The confirmed membership ids.
536
+
537
+ Raises:
538
+ BulkOperationError: Some confirmations failed; the others were applied.
539
+ """
540
+ org_id = await self._resolve_organization(organization)
541
+ ids = await self._member_ids(org_id, members, status=1 if members is None else None)
542
+ if not ids:
543
+ return []
544
+ org_key = self._org_key(org_id)
545
+ body = JsonObject(await self.request('POST', f'/api/organizations/{org_id}/users/public-keys', json={'ids': ids}))
546
+ keys = [
547
+ {'id': entry.get_str('id'), 'key': str(crypto.rsa_encrypt(org_key.to_bytes(), crypto.load_public_key(entry.get_str('key') or '')))}
548
+ for entry in body.objs('data')
549
+ ]
550
+ self._bulk_result(await self.request('POST', f'/api/organizations/{org_id}/users/confirm', json={'keys': keys}))
551
+ return [k['id'] or '' for k in keys]
552
+
553
+ async def remove_members(self, organization: OrganizationRef, members: Sequence[MemberRef]) -> None:
554
+ """Remove several members.
555
+
556
+ Args:
557
+ organization: The organization, as object, id or unique name.
558
+ members: The members, each as object, membership id or email address.
559
+
560
+ Raises:
561
+ BulkOperationError: Some removals failed; the others were applied.
562
+ """
563
+ org_id = await self._resolve_organization(organization)
564
+ ids = await self._member_ids(org_id, members)
565
+ self._bulk_result(await self.request('DELETE', f'/api/organizations/{org_id}/users', json={'ids': ids}))
566
+
567
+ async def revoke_members(self, organization: OrganizationRef, members: Sequence[MemberRef]) -> None:
568
+ """Revoke several members.
569
+
570
+ Args:
571
+ organization: The organization, as object, id or unique name.
572
+ members: The members, each as object, membership id or email address.
573
+
574
+ Raises:
575
+ BulkOperationError: Some failed; the others were applied.
576
+ """
577
+ org_id = await self._resolve_organization(organization)
578
+ ids = await self._member_ids(org_id, members)
579
+ self._bulk_result(await self.request('PUT', f'/api/organizations/{org_id}/users/revoke', json={'ids': ids}))
580
+
581
+ async def restore_members(self, organization: OrganizationRef, members: Sequence[MemberRef]) -> None:
582
+ """Restore several revoked members.
583
+
584
+ Args:
585
+ organization: The organization, as object, id or unique name.
586
+ members: The members, each as object, membership id or email address.
587
+
588
+ Raises:
589
+ BulkOperationError: Some failed; the others were applied.
590
+ """
591
+ org_id = await self._resolve_organization(organization)
592
+ ids = await self._member_ids(org_id, members)
593
+ self._bulk_result(await self.request('PUT', f'/api/organizations/{org_id}/users/restore', json={'ids': ids}))
594
+
595
+ async def groups(self, organization: OrganizationRef) -> list[Group]:
596
+ """The groups of an organization with their collection access.
597
+
598
+ Needs ``ORG_GROUPS_ENABLED=true`` on the server.
599
+
600
+ Args:
601
+ organization: The organization, as object, id or unique name.
602
+
603
+ Returns:
604
+ The groups.
605
+ """
606
+ org_id = await self._resolve_organization(organization)
607
+ body = JsonObject(await self.request('GET', f'/api/organizations/{org_id}/groups/details'))
608
+ return [_core.parse_group(g.raw, org_id) for g in body.objs('data')]
609
+
610
+ async def _resolve_group(self, org_id: str, group: GroupRef) -> str:
611
+ """Turn a group reference into an id.
612
+
613
+ Args:
614
+ org_id: The organization id.
615
+ group: A group, its id or its unique name.
616
+
617
+ Returns:
618
+ The group id.
619
+
620
+ Raises:
621
+ VaultwardenError: Not found, or the name is ambiguous.
622
+ """
623
+ if isinstance(group, Group):
624
+ return group.id
625
+ groups = await self.groups(org_id)
626
+ if any(g.id == group for g in groups):
627
+ return group
628
+ matches = [g.id for g in groups if g.name == group]
629
+ if len(matches) != 1:
630
+ raise VaultwardenError(f'group {group!r} not found' if not matches else f'group name {group!r} is ambiguous; pass the id')
631
+ return matches[0]
632
+
633
+ async def _member_group_ids(self, org_id: str, member_id: str) -> list[str]:
634
+ """The groups a member belongs to.
635
+
636
+ Args:
637
+ org_id: The organization id.
638
+ member_id: The membership id.
639
+
640
+ Returns:
641
+ The group ids.
642
+
643
+ Raises:
644
+ UnsafeWriteError: The server did not return the member's groups.
645
+ """
646
+ body = await self.request('GET', f'/api/organizations/{org_id}/users/{member_id}', params={'includeGroups': 'true'})
647
+ return [g for g in _existing_list(JsonObject(body).get('groups'), "the member's groups") if isinstance(g, str)]
648
+
649
+ async def group_members(self, organization: OrganizationRef, group: GroupRef) -> list[Member]:
650
+ """The members of a group.
651
+
652
+ Args:
653
+ organization: The organization, as object, id or unique name.
654
+ group: The group, as object, id or unique name.
655
+
656
+ Returns:
657
+ The members.
658
+ """
659
+ org_id = await self._resolve_organization(organization)
660
+ group_id = await self._resolve_group(org_id, group)
661
+ ids = set(await self._group_member_ids(org_id, group_id))
662
+ return [m for m in await self.members(org_id) if m.id in ids]
663
+
664
+ async def _group_member_ids(self, org_id: str, group_id: str) -> list[str]:
665
+ """Membership ids of a group.
666
+
667
+ Args:
668
+ org_id: The organization id.
669
+ group_id: The group id.
670
+
671
+ Returns:
672
+ The membership ids.
673
+
674
+ Raises:
675
+ UnsafeWriteError: The server did not return the group's members.
676
+ """
677
+ body = await self.request('GET', f'/api/organizations/{org_id}/groups/{group_id}/users')
678
+ return [i for i in _existing_list(body, "the group's members") if isinstance(i, str)]
679
+
680
+ async def _group_payload(
681
+ self,
682
+ org_id: str,
683
+ name: str,
684
+ collections: Sequence[CollectionRef],
685
+ members: Sequence[MemberRef],
686
+ external_id: str | None,
687
+ ) -> dict[str, Any]:
688
+ """Request body for creating or updating a group.
689
+
690
+ Args:
691
+ org_id: The organization id.
692
+ name: The group name.
693
+ collections: Collection references with access rights.
694
+ members: Member references.
695
+ external_id: The directory-sync identifier.
696
+
697
+ Returns:
698
+ The request body.
699
+ """
700
+ return {
701
+ 'name': name,
702
+ 'accessAll': False,
703
+ 'externalId': external_id,
704
+ 'collections': [_core.collection_access_payload(_collection_access(c)) for c in collections],
705
+ 'users': await self._member_ids(org_id, members) if members else [],
706
+ }
707
+
708
+ async def create_group(
709
+ self,
710
+ organization: OrganizationRef,
711
+ name: str,
712
+ *,
713
+ collections: Sequence[CollectionRef] = (),
714
+ members: Sequence[MemberRef] = (),
715
+ external_id: str | None = None,
716
+ ) -> Group:
717
+ """Create a group.
718
+
719
+ Args:
720
+ organization: The organization, as object, id or unique name.
721
+ name: The group name (plain text on the server).
722
+ collections: Collections, as objects or ids, or [CollectionAccess][vaultwarden2.models.CollectionAccess] entries
723
+ to set read-only, hide-passwords or manage rights.
724
+ members: The members, each as object, membership id or email address.
725
+ external_id: An identifier for directory synchronisation.
726
+
727
+ Returns:
728
+ The new group.
729
+
730
+ Raises:
731
+ VaultwardenError: The organization or a referenced member, group or collection was not found.
732
+ """
733
+ org_id = await self._resolve_organization(organization)
734
+ payload = await self._group_payload(org_id, name, collections, members, external_id)
735
+ body = JsonObject(await self.request('POST', f'/api/organizations/{org_id}/groups', json=payload))
736
+ return await self._get_group(org_id, body.get_str('id') or '')
737
+
738
+ async def _get_group(self, org_id: str, group_id: str) -> Group:
739
+ """One group with its collection access.
740
+
741
+ Args:
742
+ org_id: The organization id.
743
+ group_id: The group id.
744
+
745
+ Returns:
746
+ The group.
747
+ """
748
+ return _core.parse_group(await self.request('GET', f'/api/organizations/{org_id}/groups/{group_id}/details'), org_id)
749
+
750
+ async def update_group(
751
+ self,
752
+ organization: OrganizationRef,
753
+ group: GroupRef,
754
+ *,
755
+ name: str | None = None,
756
+ collections: Sequence[CollectionRef] | None = None,
757
+ members: Sequence[MemberRef] | None = None,
758
+ ) -> Group:
759
+ """Change a group's name, collection access and/or members.
760
+
761
+ Args:
762
+ organization: The organization, as object, id or unique name.
763
+ group: The group, as object, id or unique name.
764
+ name: The new name. None keeps it.
765
+ collections: Collections, as objects or ids, or [CollectionAccess][vaultwarden2.models.CollectionAccess] entries
766
+ to set read-only, hide-passwords or manage rights. None keeps the current access.
767
+ members: The members, each as object, membership id or email address. None keeps the current members.
768
+
769
+ Returns:
770
+ The updated group.
771
+
772
+ Raises:
773
+ UnsafeWriteError: The server did not return the current access or members; nothing was sent.
774
+ VaultwardenError: The organization or a referenced member, group or collection was not found.
775
+ """
776
+ org_id = await self._resolve_organization(organization)
777
+ current = await self._get_group(org_id, await self._resolve_group(org_id, group))
778
+ payload = await self._group_payload(
779
+ org_id,
780
+ name if name is not None else current.name,
781
+ collections if collections is not None else _group_access(current),
782
+ members if members is not None else await self._group_member_ids(org_id, current.id),
783
+ current.external_id,
784
+ )
785
+ await self.request('PUT', f'/api/organizations/{org_id}/groups/{current.id}', json=payload)
786
+ return await self._get_group(org_id, current.id)
787
+
788
+ async def delete_group(self, organization: OrganizationRef, group: GroupRef) -> None:
789
+ """Delete a group. Its members stay in the organization.
790
+
791
+ Args:
792
+ organization: The organization, as object, id or unique name.
793
+ group: The group, as object, id or unique name.
794
+ """
795
+ org_id = await self._resolve_organization(organization)
796
+ await self.request('DELETE', f'/api/organizations/{org_id}/groups/{await self._resolve_group(org_id, group)}')
797
+
798
+ async def policies(self, organization: OrganizationRef) -> list[Policy]:
799
+ """The policies configured for an organization.
800
+
801
+ Args:
802
+ organization: The organization, as object, id or unique name.
803
+
804
+ Returns:
805
+ The configured policies; types that were never configured are not listed.
806
+ """
807
+ org_id = await self._resolve_organization(organization)
808
+ body = JsonObject(await self.request('GET', f'/api/organizations/{org_id}/policies'))
809
+ return [_core.parse_policy(p.raw) for p in body.objs('data')]
810
+
811
+ async def set_policy(
812
+ self, organization: OrganizationRef, policy_type: PolicyType | int, *, enabled: bool = True, data: dict[str, Any] | None = None
813
+ ) -> Policy:
814
+ """Enable or disable a policy and set its options.
815
+
816
+ Careful: policies take effect on existing members immediately. For example, enabling the two-step login policy
817
+ revokes every member without two-step login. Check a policy's effect before enabling it on a live organization.
818
+
819
+ Args:
820
+ organization: The organization, as object, id or unique name.
821
+ policy_type: The policy, see [PolicyType][vaultwarden2.models.PolicyType].
822
+ enabled: Enable (True) or disable (False) the policy.
823
+ data: Policy-specific options with camelCase keys as the server uses them, for example
824
+ ``{'minLength': 20}`` for the password generator policy.
825
+
826
+ Returns:
827
+ The policy as stored.
828
+
829
+ Raises:
830
+ ApiError: The server refused (for example a policy that requires another one first).
831
+ """
832
+ org_id = await self._resolve_organization(organization)
833
+ body = await self.request('PUT', f'/api/organizations/{org_id}/policies/{int(policy_type)}', json={'policy': {'enabled': enabled, 'data': data}})
834
+ return _core.parse_policy(body)
835
+
836
+ async def organization_api_key(self, organization: OrganizationRef, password: str, *, rotate: bool = False) -> tuple[str, str]:
837
+ """The organization API key (owner only).
838
+
839
+ Args:
840
+ organization: The organization, as object, id or unique name.
841
+ password: The owner's master password (the server re-checks it).
842
+ rotate: Issue a new secret and invalidate the old one.
843
+
844
+ Returns:
845
+ ``(client_id, client_secret)``; the client id is ``organization.<id>``.
846
+
847
+ Raises:
848
+ ApiError: Wrong password or not the owner.
849
+ """
850
+ org_id = await self._resolve_organization(organization)
851
+ endpoint = 'rotate-api-key' if rotate else 'api-key'
852
+ body = JsonObject(await self.request('POST', f'/api/organizations/{org_id}/{endpoint}', json={'masterPasswordHash': await self._password_hash(password)}))
853
+ secret = body.get_str('apiKey')
854
+ if not secret:
855
+ raise ApiError(500, 'server returned no apiKey')
856
+ return f'organization.{org_id}', secret
857
+
858
+ async def export_organization(self, organization: OrganizationRef) -> OrganizationExport:
859
+ """All collections and items of an organization, decrypted.
860
+
861
+ Write it out with [to_export_json][vaultwarden2.export.to_export_json] or
862
+ [dump_organization][vaultwarden2.AsyncVaultwardenClient.dump_organization].
863
+
864
+ Args:
865
+ organization: The organization, as object, id or unique name.
866
+
867
+ Returns:
868
+ The collections and items.
869
+
870
+ Raises:
871
+ CryptoError: An item cannot be decrypted.
872
+ """
873
+ org_id = await self._resolve_organization(organization)
874
+ body = JsonObject(await self.request('GET', f'/api/organizations/{org_id}/export'))
875
+ keys = self._require_keys()
876
+ collections = tuple(_core.decrypt_collection({**c.raw, 'organizationId': c.get_str('organizationId') or org_id}, keys) for c in body.objs('collections'))
877
+ ciphers = await _offload.arun_cpu(_core.decrypt_ciphers, [c.raw for c in body.objs('ciphers')], keys)
878
+ return OrganizationExport(organization_id=org_id, collections=collections, ciphers=tuple(ciphers))
879
+
880
+
881
+ def _existing_list(value: Any, what: str) -> list[Any]:
882
+ """A list returned by the server that an update will send back.
883
+
884
+ Refuses instead of sending an empty list in its place, which would clear the data on the server.
885
+
886
+ Args:
887
+ value: The value from the server response.
888
+ what: Description for the error message.
889
+
890
+ Returns:
891
+ The list.
892
+
893
+ Raises:
894
+ UnsafeWriteError: The server did not return a list.
895
+ """
896
+ if not isinstance(value, list):
897
+ raise UnsafeWriteError(f'the server did not return {what}; not updating to avoid clearing it')
898
+ return value
899
+
900
+
901
+ def _group_access(group: Group) -> list[CollectionAccess]:
902
+ """The current collection access of a group, for sending it back unchanged.
903
+
904
+ Args:
905
+ group: The group.
906
+
907
+ Returns:
908
+ The access entries.
909
+
910
+ Raises:
911
+ UnsafeWriteError: The server did not return the group's collection access.
912
+ """
913
+ _existing_list(JsonObject(group.raw).get('collections'), "the group's collection access")
914
+ return list(group.collections)