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