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,487 @@
1
+ # Do not edit this file directly. It has been autogenerated from
2
+ # src/vaultwarden2/_async/admin.py
3
+ """Server administration through the vaultwarden admin panel.
4
+
5
+ Authentication is the server's admin token (``ADMIN_TOKEN``); the panel answers with a session cookie that the
6
+ client renews automatically when it expires. No vault keys are involved.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from datetime import datetime
13
+ from typing import TYPE_CHECKING, Any, Self
14
+
15
+ import httpx2
16
+
17
+ from vaultwarden2 import _core, _offload
18
+ from vaultwarden2._json import JsonObject
19
+ from vaultwarden2.errors import AuthenticationError, UnsafeWriteError, VaultwardenError
20
+ from vaultwarden2.models import AdminMembership, AdminOrganization, AdminUser, MemberStatus, OrganizationUserType
21
+
22
+ from .base import DEFAULT_TIMEOUT, _body, _warn_if_plaintext
23
+
24
+ if TYPE_CHECKING:
25
+ from collections.abc import Mapping
26
+ from types import TracebackType
27
+
28
+ from vaultwarden2.models import AdminOrganizationRef, AdminUserRef
29
+
30
+ REPLACE_ALL_SETTINGS = 'replace-all-settings'
31
+ """Confirmation value for :meth:`AsyncVaultwardenAdmin.set_config`."""
32
+ _CONFIG_KEY = re.compile(r'^_?[a-z][a-z0-9_]*$')
33
+
34
+
35
+ def _admin_datetime(value: str | None) -> datetime | None:
36
+ """Parse a date as the admin panel formats it (``2026-11-28 02:25:26 +00:00``).
37
+
38
+ Args:
39
+ value: The date string, or None.
40
+
41
+ Returns:
42
+ The timezone-aware datetime, or None if missing or ambiguous (no offset).
43
+ """
44
+ if not value:
45
+ return None
46
+ try:
47
+ return datetime.strptime(value, '%Y-%m-%d %H:%M:%S %z')
48
+ except ValueError:
49
+ pass
50
+ try:
51
+ parsed = datetime.fromisoformat(value)
52
+ except ValueError:
53
+ _core.log.warning('cannot interpret admin date %r', value)
54
+ return None
55
+ return parsed if parsed.tzinfo else None # a date without offset would be ambiguous
56
+
57
+
58
+ def _role(value: int | None) -> OrganizationUserType | int | None:
59
+ """An organization role number as enum member (unknown numbers stay ints).
60
+
61
+ Args:
62
+ value: The role number, or None.
63
+
64
+ Returns:
65
+ The role.
66
+ """
67
+ try:
68
+ return OrganizationUserType(value) if value is not None else None
69
+ except ValueError:
70
+ return value
71
+
72
+
73
+ def parse_admin_user(raw: Any) -> AdminUser:
74
+ """Build an [AdminUser][vaultwarden2.models.AdminUser] from an entry of ``/admin/users``.
75
+
76
+ Unexpected fields are logged on the ``vaultwarden2`` logger.
77
+
78
+ Args:
79
+ raw: The user JSON object.
80
+
81
+ Returns:
82
+ The user.
83
+ """
84
+ obj = JsonObject(raw, path=f'admin user {raw.get("id") if isinstance(raw, dict) else "?"}')
85
+ memberships = []
86
+ for o in obj.objs('organizations'):
87
+ status = o.get_int('status')
88
+ try:
89
+ parsed_status: MemberStatus | int | None = MemberStatus(status) if status is not None else None
90
+ except ValueError:
91
+ parsed_status = status
92
+ memberships.append(
93
+ AdminMembership(
94
+ organization_id=o.get_str('id') or '',
95
+ name=o.get_str('name'),
96
+ type=_role(o.get_int('type')),
97
+ status=parsed_status,
98
+ enabled=o.get_bool('enabled', default=True),
99
+ )
100
+ )
101
+ for issue in obj.issues:
102
+ _core.log.warning('cannot interpret server data: %s', issue)
103
+ return AdminUser(
104
+ id=obj.get_str('id') or '',
105
+ email=obj.get_str('email') or '',
106
+ name=obj.get_str('name'),
107
+ enabled=obj.get_bool('userEnabled', default=True),
108
+ email_verified=obj.get_bool('emailVerified'),
109
+ two_factor_enabled=obj.get_bool('twoFactorEnabled'),
110
+ created_at=_admin_datetime(obj.get_str('createdAt')),
111
+ last_active=_admin_datetime(obj.get_str('lastActive')),
112
+ organizations=tuple(memberships),
113
+ raw=obj.raw,
114
+ )
115
+
116
+
117
+ class VaultwardenAdmin:
118
+ """Client for the vaultwarden admin panel (server administration).
119
+
120
+ Separate from the user client: it authenticates with the server's admin token, never with user credentials,
121
+ and needs no vault keys. It logs in on first use and again when the admin session expires (20 minutes by
122
+ default). The token is never shown in ``repr()``. [VaultwardenAdmin][vaultwarden2.VaultwardenAdmin]
123
+ and ``VaultwardenAdmin`` have the same methods.
124
+
125
+ Args:
126
+ base_url: Address of the server, for example ``https://vault.example.org``.
127
+ admin_token: The server's ``ADMIN_TOKEN``. Pass the plain token, also when the server stores it as an
128
+ Argon2 hash.
129
+ timeout: Timeout for every HTTP request, in seconds.
130
+ verify: Verify the server's TLS certificate. Only disable for local testing.
131
+ http_client: A preconfigured httpx2 client; its ``base_url`` must point at the server.
132
+
133
+ Example:
134
+ ```python
135
+ import os
136
+ from vaultwarden2 import VaultwardenAdmin
137
+
138
+ with VaultwardenAdmin('https://vault.example.org', os.environ['VW_ADMIN_TOKEN']) as admin:
139
+ for user in admin.users():
140
+ print(user.email, user.enabled, user.last_active)
141
+ admin.disable_user('former.employee@example.org')
142
+ ```
143
+ """
144
+
145
+ def __init__(
146
+ self,
147
+ base_url: str,
148
+ admin_token: str,
149
+ *,
150
+ timeout: float = DEFAULT_TIMEOUT,
151
+ verify: bool = True,
152
+ http_client: httpx2.Client | None = None,
153
+ ) -> None:
154
+ self.base_url = base_url.rstrip('/')
155
+ _warn_if_plaintext(self.base_url)
156
+ self._token = admin_token
157
+ self._http = http_client or httpx2.Client(base_url=self.base_url, timeout=timeout, verify=verify)
158
+ self._logged_in = False
159
+ self._login_lock = _offload.new_lock()
160
+
161
+ def __repr__(self) -> str:
162
+ """Show the server address, never the admin token.
163
+
164
+ Returns:
165
+ ``VaultwardenAdmin('<base_url>')``.
166
+ """
167
+ return f'{type(self).__name__}({self.base_url!r})'
168
+
169
+ def close(self) -> None:
170
+ """Close the connection pool. The client cannot be used afterwards."""
171
+ self._http.close()
172
+
173
+ def __enter__(self) -> Self:
174
+ """Use the client as a context manager that closes it on exit.
175
+
176
+ Returns:
177
+ The client itself.
178
+ """
179
+ return self
180
+
181
+ def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None:
182
+ """Close the client when leaving the ``with`` block.
183
+
184
+ Args:
185
+ exc_type: Type of the exception that ended the block, if any.
186
+ exc: The exception that ended the block, if any.
187
+ tb: Its traceback, if any.
188
+ """
189
+ self.close()
190
+
191
+ # ------------------------------------------------------------ session
192
+
193
+ def login(self) -> None:
194
+ """Start an admin session. Done automatically on first use and when the session expires.
195
+
196
+ Raises:
197
+ AuthenticationError: Wrong admin token, or the admin panel is disabled on the server.
198
+ RateLimitError: Too many login attempts.
199
+ """
200
+ response = self._http.post('/admin', data={'token': self._token}, headers={'Accept': 'text/html'})
201
+ if response.status_code == httpx2.codes.TOO_MANY_REQUESTS:
202
+ _core.raise_for_status(response.status_code, None)
203
+ if response.status_code != httpx2.codes.OK or 'VW_ADMIN' not in self._http.cookies:
204
+ raise AuthenticationError('admin login failed (wrong admin token, or the admin panel is disabled)')
205
+ self._logged_in = True
206
+
207
+ def logout(self) -> None:
208
+ """End the admin session. The next call logs in again."""
209
+ self._http.get('/admin/logout')
210
+ self._http.cookies.clear()
211
+ self._logged_in = False
212
+
213
+ def _request(self, method: str, path: str, *, json: Any = None, accept_json: bool = True) -> Any:
214
+ """Send a request to the admin panel, logging in (again) when needed.
215
+
216
+ Args:
217
+ method: HTTP method.
218
+ path: Path below ``/admin``.
219
+ json: Request body, sent as JSON.
220
+ accept_json: Ask for a JSON answer.
221
+
222
+ Returns:
223
+ The decoded response.
224
+
225
+ Raises:
226
+ AuthenticationError: The session was rejected even after logging in again.
227
+ ApiError: Any other non-2xx answer.
228
+ """
229
+ for attempt in range(2):
230
+ if not self._logged_in:
231
+ with self._login_lock:
232
+ if not self._logged_in:
233
+ self.login()
234
+ headers = {'Accept': 'application/json'} if accept_json else {}
235
+ response = self._http.request(method, f'/admin{path}', json=json, headers=headers)
236
+ if response.status_code == httpx2.codes.UNAUTHORIZED and attempt == 0:
237
+ self._logged_in = False # session expired: log in again once
238
+ continue
239
+ body = _body(response)
240
+ if response.status_code == httpx2.codes.UNAUTHORIZED:
241
+ raise AuthenticationError('admin session rejected')
242
+ _core.raise_for_status(response.status_code, body if not (isinstance(body, str) and body.lstrip().startswith('<')) else None)
243
+ return body
244
+ raise VaultwardenError('unreachable') # pragma: no cover
245
+
246
+ def _post(self, path: str, json: Any = None) -> Any:
247
+ # The admin endpoints require a JSON content type even without a body.
248
+ """POST to the admin panel; the endpoints require a JSON body, so an empty one is sent if none is given.
249
+
250
+ Args:
251
+ path: Path below ``/admin``.
252
+ json: Request body.
253
+
254
+ Returns:
255
+ The decoded response.
256
+ """
257
+ return self._request('POST', path, json=json if json is not None else {})
258
+
259
+ # ------------------------------------------------------------ users
260
+
261
+ def users(self) -> list[AdminUser]:
262
+ """All user accounts.
263
+
264
+ Returns:
265
+ The users, with status, two-step login state, dates and organization memberships.
266
+ """
267
+ body = self._request('GET', '/users')
268
+ return [parse_admin_user(u) for u in (body if isinstance(body, list) else [])]
269
+
270
+ def get_user(self, user: AdminUserRef) -> AdminUser:
271
+ """One user account.
272
+
273
+ Args:
274
+ user: The user, as [AdminUser][vaultwarden2.models.AdminUser], user id or email address.
275
+
276
+ Returns:
277
+ The user.
278
+
279
+ Raises:
280
+ ApiError: No such user.
281
+ """
282
+ if isinstance(user, AdminUser):
283
+ user = user.id
284
+ if '@' in user:
285
+ return parse_admin_user(self._request('GET', f'/users/by-mail/{user}'))
286
+ return parse_admin_user(self._request('GET', f'/users/{user}'))
287
+
288
+ def _user_id(self, user: AdminUserRef) -> str:
289
+ """Turn a user reference into an id.
290
+
291
+ Args:
292
+ user: A user, id or email.
293
+
294
+ Returns:
295
+ The user id.
296
+ """
297
+ if isinstance(user, AdminUser):
298
+ return user.id
299
+ return (self.get_user(user)).id if '@' in user else user
300
+
301
+ def invite_user(self, email: str) -> AdminUser:
302
+ """Invite a new user; they finish the registration themselves.
303
+
304
+ Args:
305
+ email: The address to invite.
306
+
307
+ Returns:
308
+ The invited (not yet registered) user.
309
+
310
+ Raises:
311
+ ApiError: The user exists already, or invitations are disabled.
312
+ """
313
+ return parse_admin_user(self._post('/invite', {'email': email}))
314
+
315
+ def resend_invite(self, user: AdminUserRef) -> None:
316
+ """Send the invitation mail again.
317
+
318
+ On a server that sends no emails (neither ``SMTP_HOST`` nor ``USE_SENDMAIL`` configured) this does nothing (and reports no error).
319
+
320
+ Args:
321
+ user: The user, as [AdminUser][vaultwarden2.models.AdminUser], user id or email address.
322
+
323
+ Raises:
324
+ ApiError: No such user, or the user already finished the registration.
325
+ """
326
+ self._post(f'/users/{self._user_id(user)}/invite/resend')
327
+
328
+ def disable_user(self, user: AdminUserRef) -> None:
329
+ """Block a user from logging in. All data is kept; undo with ``enable_user``.
330
+
331
+ All the user's sessions end and their devices are removed from the device list.
332
+
333
+ Args:
334
+ user: The user, as [AdminUser][vaultwarden2.models.AdminUser], user id or email address.
335
+ """
336
+ self._post(f'/users/{self._user_id(user)}/disable')
337
+
338
+ def enable_user(self, user: AdminUserRef) -> None:
339
+ """Allow a disabled user to log in again.
340
+
341
+ Args:
342
+ user: The user, as [AdminUser][vaultwarden2.models.AdminUser], user id or email address.
343
+ """
344
+ self._post(f'/users/{self._user_id(user)}/enable')
345
+
346
+ def deauthorize_user(self, user: AdminUserRef) -> None:
347
+ """Log a user out of every device and remove all their devices from the device list.
348
+
349
+ Args:
350
+ user: The user, as [AdminUser][vaultwarden2.models.AdminUser], user id or email address.
351
+ """
352
+ self._post(f'/users/{self._user_id(user)}/deauth')
353
+
354
+ def remove_two_factor(self, user: AdminUserRef) -> None:
355
+ """Remove all two-step login methods of a user, for example after a lost authenticator.
356
+
357
+ Organizations that require two-step login revoke the user's membership, as for any account without it.
358
+
359
+ Args:
360
+ user: The user, as [AdminUser][vaultwarden2.models.AdminUser], user id or email address.
361
+ """
362
+ self._post(f'/users/{self._user_id(user)}/remove-2fa')
363
+
364
+ def delete_user(self, user: AdminUserRef) -> None:
365
+ """Delete a user and all their personal data. This cannot be undone.
366
+
367
+ Args:
368
+ user: The user, as [AdminUser][vaultwarden2.models.AdminUser], user id or email address.
369
+ """
370
+ self._post(f'/users/{self._user_id(user)}/delete')
371
+
372
+ def set_organization_role(self, user: AdminUserRef, organization: AdminOrganizationRef, role: OrganizationUserType) -> None:
373
+ """Change a user's role in an organization.
374
+
375
+ Args:
376
+ user: The user, as [AdminUser][vaultwarden2.models.AdminUser], user id or email address.
377
+ organization: The organization, as [AdminOrganization][vaultwarden2.models.AdminOrganization], id or
378
+ unique name.
379
+ role: The new role.
380
+
381
+ Raises:
382
+ ApiError: The user is not a member, or the change would demote the last owner.
383
+ """
384
+ # this endpoint expects snake_case keys
385
+ payload = {'user_type': int(role), 'user_uuid': self._user_id(user), 'org_uuid': self._organization_id(organization)}
386
+ self._post('/users/org_type', payload)
387
+
388
+ # ------------------------------------------------------------ organizations
389
+
390
+ def organizations(self) -> list[AdminOrganization]:
391
+ """All organizations, with their members and roles.
392
+
393
+ The admin panel has no organization list in JSON, so the organizations are collected from the users'
394
+ memberships. Organizations without any member (vaultwarden does not create those normally) are not listed.
395
+
396
+ Returns:
397
+ The organizations.
398
+ """
399
+ by_id: dict[str, tuple[str | None, list[tuple[AdminUser, OrganizationUserType | int | None]]]] = {}
400
+ for user in self.users():
401
+ for membership in user.organizations:
402
+ entry = by_id.setdefault(membership.organization_id, (membership.name, []))
403
+ entry[1].append((user, membership.type))
404
+ return [AdminOrganization(id=org_id, name=name, members=tuple(members)) for org_id, (name, members) in by_id.items()]
405
+
406
+ def _organization_id(self, organization: AdminOrganizationRef) -> str:
407
+ """Turn an organization reference into an id.
408
+
409
+ Args:
410
+ organization: An organization, its id or its unique name.
411
+
412
+ Returns:
413
+ The organization id.
414
+
415
+ Raises:
416
+ VaultwardenError: Not found, or the name is ambiguous.
417
+ """
418
+ if isinstance(organization, AdminOrganization):
419
+ return organization.id
420
+ orgs = self.organizations()
421
+ if any(o.id == organization for o in orgs):
422
+ return organization
423
+ matches = [o.id for o in orgs if o.name == organization]
424
+ if len(matches) != 1:
425
+ raise VaultwardenError(f'organization {organization!r} not found' if not matches else f'organization name {organization!r} is ambiguous; pass the id')
426
+ return matches[0]
427
+
428
+ def delete_organization(self, organization: AdminOrganizationRef) -> None:
429
+ """Delete an organization with all its items and collections. This cannot be undone.
430
+
431
+ Args:
432
+ organization: The organization, as object, id or unique name.
433
+
434
+ Raises:
435
+ VaultwardenError: The organization was not found or the name is ambiguous.
436
+ """
437
+ self._post(f'/organizations/{self._organization_id(organization)}/delete')
438
+
439
+ # ------------------------------------------------------------ server
440
+
441
+ def diagnostics_config(self) -> dict[str, Any]:
442
+ """The server configuration as in the support report. Secrets are masked.
443
+
444
+ Returns:
445
+ The settings by name (snake_case keys).
446
+ """
447
+ body = self._request('GET', '/diagnostics/config')
448
+ return body if isinstance(body, dict) else {}
449
+
450
+ def set_config(self, settings: Mapping[str, Any], *, confirm: str) -> None:
451
+ """Replace **all** settings saved through the admin panel. Destructive.
452
+
453
+ The server stores exactly what is sent: every saved setting not included here is removed (it falls back to the
454
+ environment or default value), including secrets such as the SMTP password, which ``diagnostics_config`` masks
455
+ and therefore cannot provide. Settings from environment variables are not affected. The server validates the
456
+ result and rejects invalid configurations.
457
+
458
+ Args:
459
+ settings: The complete set of panel settings, with snake_case keys as in vaultwarden's ``config.json``.
460
+ confirm: Must be ``'replace-all-settings'``.
461
+
462
+ Raises:
463
+ UnsafeWriteError: ``confirm`` is missing or wrong, or a key is not a vaultwarden setting name; nothing was
464
+ sent.
465
+ ApiError: The server rejected the configuration.
466
+ """
467
+ if confirm != REPLACE_ALL_SETTINGS:
468
+ raise UnsafeWriteError(f"set_config replaces all saved settings; pass confirm='{REPLACE_ALL_SETTINGS}' to proceed")
469
+ bad = [k for k in settings if not _CONFIG_KEY.match(k)]
470
+ if bad:
471
+ raise UnsafeWriteError(f'not vaultwarden config keys (snake_case expected): {bad}; nothing sent')
472
+ self._post('/config', dict(settings))
473
+
474
+ def backup_database(self) -> str:
475
+ """Ask the server to back up its SQLite database. The backup file stays on the server.
476
+
477
+ Only SQLite servers support this. The server names backups by the second (``db_YYYYMMDD_HHMMSS``), so a
478
+ second backup within the same second fails.
479
+
480
+ Returns:
481
+ The server's message, including the backup file name.
482
+
483
+ Raises:
484
+ ApiError: Not an SQLite server, or the backup failed.
485
+ """
486
+ body = self._post('/config/backup_db')
487
+ return body if isinstance(body, str) else ''