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.
vaultwarden2/py.typed ADDED
File without changes
vaultwarden2/search.py ADDED
@@ -0,0 +1,206 @@
1
+ """Finding items locally (the server cannot search encrypted data).
2
+
3
+ * `search`: case-insensitive substring search over name, username, URIs, notes and custom field names.
4
+ * `find_by_uri`: items for a URL. ``mode='host'`` (default) matches items with a URI on exactly the same
5
+ host; ``mode='autofill'`` applies each item's own match setting like browser autofill does. The
6
+ default "base domain" rule needs the Public Suffix List: ``pip install python-vaultwarden2[psl]``; without it
7
+ base-domain matching falls back to host matching (with one logged warning).
8
+
9
+ Archived items and items in the trash are skipped unless ``include_archived`` / ``include_deleted`` is set.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import functools
15
+ import ipaddress
16
+ import logging
17
+ import re
18
+ from typing import TYPE_CHECKING, Literal
19
+ from urllib.parse import urlsplit
20
+
21
+ from vaultwarden2.models import UriMatch
22
+
23
+ if TYPE_CHECKING:
24
+ from collections.abc import Iterable
25
+
26
+ from vaultwarden2.models import Cipher
27
+
28
+ log = logging.getLogger('vaultwarden2')
29
+
30
+ SearchMode = Literal['host', 'autofill']
31
+
32
+
33
+ def _visible(cipher: Cipher, include_archived: bool, include_deleted: bool) -> bool:
34
+ """Whether an item passes the archived / trash filters.
35
+
36
+ Args:
37
+ cipher: The item.
38
+ include_archived: Archived items pass.
39
+ include_deleted: Items in the trash pass.
40
+
41
+ Returns:
42
+ True if the item should be considered.
43
+ """
44
+ return (include_archived or not cipher.is_archived) and (include_deleted or not cipher.is_deleted)
45
+
46
+
47
+ def search(ciphers: Iterable[Cipher], query: str, *, include_archived: bool = False, include_deleted: bool = False) -> list[Cipher]:
48
+ """Find items whose name, username, URIs, notes or custom field names contain ``query``.
49
+
50
+ Case-insensitive. Passwords, hidden field values and other secrets are never searched.
51
+
52
+ Args:
53
+ ciphers: The items to search, for example ``vault.ciphers``.
54
+ query: The text to look for.
55
+ include_archived: Also return archived items.
56
+ include_deleted: Also return items in the trash.
57
+
58
+ Returns:
59
+ The matching items, in the given order.
60
+ """
61
+ needle = query.casefold()
62
+ result = []
63
+ for c in ciphers:
64
+ if not _visible(c, include_archived, include_deleted):
65
+ continue
66
+ haystack = [c.name, c.notes, *(f.name for f in c.fields)]
67
+ if c.login:
68
+ haystack += [c.login.username, *(u.uri for u in c.login.uris)]
69
+ if any(needle in text.casefold() for text in haystack if text):
70
+ result.append(c)
71
+ return result
72
+
73
+
74
+ def _parse(uri: str) -> tuple[str, str]:
75
+ """Split a stored or looked-up URI into host and full URL. URIs without scheme are read as ``http://``.
76
+
77
+ Args:
78
+ uri: The URI.
79
+
80
+ Returns:
81
+ ``(host[:port] lowercased, full URL)``; the host is empty if it cannot be parsed.
82
+ """
83
+ url = uri if '://' in uri else f'http://{uri}'
84
+ try:
85
+ parts = urlsplit(url)
86
+ host = (parts.hostname or '').lower()
87
+ port = parts.port
88
+ except ValueError:
89
+ return '', url
90
+ return (f'{host}:{port}' if port else host), url
91
+
92
+
93
+ @functools.cache
94
+ def _psl() -> object | None:
95
+ """The Public Suffix List, loaded once (optional extra ``psl``).
96
+
97
+ Returns:
98
+ The list, or None if ``publicsuffixlist`` is not installed (logged once).
99
+ """
100
+ try:
101
+ from publicsuffixlist import PublicSuffixList # noqa: PLC0415 - optional extra
102
+
103
+ return PublicSuffixList()
104
+ except ImportError:
105
+ log.warning("base-domain URI matching needs the 'psl' extra (pip install python-vaultwarden2[psl]); matching hosts exactly instead")
106
+ return None
107
+
108
+
109
+ def base_domain(host: str) -> str:
110
+ """The registrable domain of a host, as used by base-domain matching.
111
+
112
+ Needs the ``psl`` extra for correct results with multi-part suffixes such as ``co.uk``; without it the host is
113
+ returned unchanged.
114
+
115
+ Args:
116
+ host: The host name, optionally with port.
117
+
118
+ Returns:
119
+ The registrable domain (``login.example.co.uk`` -> ``example.co.uk``); the host itself for IP addresses,
120
+ ``localhost`` and unknown suffixes.
121
+ """
122
+ name = host.rsplit(':', 1)[0] if host.count(':') == 1 else host
123
+ try:
124
+ ipaddress.ip_address(name.strip('[]'))
125
+ except ValueError:
126
+ psl = _psl()
127
+ suffix = psl.privatesuffix(name) if psl is not None else None # type: ignore[attr-defined]
128
+ return suffix or name
129
+ return name
130
+
131
+
132
+ def _matches(stored: str, match: UriMatch | int | None, target_host: str, target_url: str) -> bool:
133
+ """Whether a stored URI matches a target according to its match rule.
134
+
135
+ Args:
136
+ stored: The stored URI.
137
+ match: The stored match rule; None means base domain.
138
+ target_host: The looked-up host (with port).
139
+ target_url: The looked-up full URL.
140
+
141
+ Returns:
142
+ True on a match.
143
+ """
144
+ stored_host, stored_url = _parse(stored)
145
+ rule = UriMatch.DOMAIN if match is None else match
146
+ if rule == UriMatch.DOMAIN:
147
+ return bool(stored_host) and base_domain(stored_host.split(':')[0]) == base_domain(target_host.split(':', maxsplit=1)[0])
148
+ if rule == UriMatch.HOST:
149
+ return bool(stored_host) and stored_host == target_host
150
+ if rule == UriMatch.STARTS_WITH:
151
+ return target_url.startswith(stored_url)
152
+ if rule == UriMatch.EXACT:
153
+ return target_url == stored_url
154
+ return rule == UriMatch.REGEX and _regex_match(stored, target_url) # NEVER and unknown rules: no match
155
+
156
+
157
+ def _regex_match(pattern: str, url: str) -> bool:
158
+ """Match a stored regular expression; invalid expressions never match.
159
+
160
+ Args:
161
+ pattern: The regular expression.
162
+ url: The URL to test.
163
+
164
+ Returns:
165
+ True on a match.
166
+ """
167
+ try:
168
+ return re.search(pattern, url, re.IGNORECASE) is not None
169
+ except re.error:
170
+ return False
171
+
172
+
173
+ def find_by_uri(
174
+ ciphers: Iterable[Cipher],
175
+ url: str,
176
+ *,
177
+ mode: SearchMode = 'host',
178
+ include_archived: bool = False,
179
+ include_deleted: bool = False,
180
+ ) -> list[Cipher]:
181
+ """Find login items for a URL.
182
+
183
+ Args:
184
+ ciphers: The items to look through, for example ``vault.ciphers``.
185
+ url: The address to look up; the scheme is optional.
186
+ mode: ``'host'``: a stored URI has exactly the same host (and port). ``'autofill'``: each stored URI's own
187
+ match rule (base domain by default, host, starts-with, exact, regular expression, never), as autofill does.
188
+ include_archived: Also return archived items.
189
+ include_deleted: Also return items in the trash.
190
+
191
+ Returns:
192
+ The matching login items, in the given order.
193
+ """
194
+ target_host, target_url = _parse(url)
195
+ result = []
196
+ for c in ciphers:
197
+ if not c.login or not _visible(c, include_archived, include_deleted):
198
+ continue
199
+ for u in c.login.uris:
200
+ if not u.uri:
201
+ continue
202
+ hit = _parse(u.uri)[0] == target_host if mode == 'host' else _matches(u.uri, u.match, target_host, target_url)
203
+ if hit and target_host:
204
+ result.append(c)
205
+ break
206
+ return result
vaultwarden2/totp.py ADDED
@@ -0,0 +1,214 @@
1
+ """Time-based one-time passwords (RFC 6238) from the seeds stored in login items.
2
+
3
+ Accepted seeds, as in the official apps:
4
+
5
+ * a plain base32 secret (any case, spaces allowed): SHA-1, 6 digits, 30 seconds
6
+ * ``otpauth://totp/...?secret=...`` with optional ``algorithm`` (SHA1/SHA256/SHA512), ``digits`` and ``period``
7
+ * ``steam://<secret>``: Steam Guard codes (5 characters)
8
+
9
+ Parsing follows the official apps, so every seed gives the same code as there (checked against their SDK's
10
+ test vectors). The one difference: counter-based ``otpauth://hotp`` seeds are refused, because a
11
+ time-based code for them would never be valid.
12
+ Secrets and codes are never logged; secrets are hidden from ``repr()``.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import hmac
18
+ import math
19
+ import struct
20
+ import time
21
+ from dataclasses import dataclass, field
22
+ from datetime import UTC, datetime
23
+ from typing import Literal
24
+ from urllib.parse import parse_qs, unquote, urlsplit
25
+
26
+ from vaultwarden2.errors import TotpError
27
+
28
+ Algorithm = Literal['SHA1', 'SHA256', 'SHA512']
29
+ _DIGESTS = {'SHA1': 'sha1', 'SHA256': 'sha256', 'SHA512': 'sha512'}
30
+ _STEAM_ALPHABET = '23456789BCDFGHJKMNPQRTVWXY'
31
+ _STEAM_DIGITS = 5
32
+ _BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
33
+
34
+
35
+ @dataclass(frozen=True, slots=True, kw_only=True)
36
+ class TotpSpec:
37
+ """A parsed TOTP seed. The secret never appears in ``repr()``.
38
+
39
+ Attributes:
40
+ secret: The decoded secret.
41
+ kind: ``'totp'`` for standard codes, ``'steam'`` for Steam Guard codes.
42
+ algorithm: The HMAC hash: ``'SHA1'``, ``'SHA256'`` or ``'SHA512'``.
43
+ digits: Code length (5 for Steam).
44
+ period: Seconds each code is valid.
45
+ issuer: The issuer from an ``otpauth://`` URI, if any.
46
+ account: The account name from an ``otpauth://`` URI, if any.
47
+ """
48
+
49
+ secret: bytes = field(repr=False)
50
+ kind: Literal['totp', 'steam'] = 'totp'
51
+ algorithm: Algorithm = 'SHA1'
52
+ digits: int = 6
53
+ period: int = 30
54
+ issuer: str | None = None
55
+ account: str | None = None
56
+
57
+
58
+ @dataclass(frozen=True, slots=True)
59
+ class TotpCode:
60
+ """A one-time code and how long it stays valid. ``str(code)`` is the code itself.
61
+
62
+ Attributes:
63
+ code: The code, for example ``'492039'``.
64
+ period: Seconds each code is valid.
65
+ remaining: Whole seconds until the next code (1 to ``period``).
66
+ valid_until: When the code expires (UTC).
67
+ """
68
+
69
+ code: str
70
+ period: int
71
+ remaining: int
72
+ valid_until: datetime
73
+
74
+ def __str__(self) -> str:
75
+ """The code itself, so ``f'{code}'`` prints it.
76
+
77
+ Returns:
78
+ The code.
79
+ """
80
+ return self.code
81
+
82
+
83
+ def _b32decode(text: str) -> bytes:
84
+ """Decode a base32 secret the way the official apps do: characters outside the base32 alphabet are ignored.
85
+
86
+ Args:
87
+ text: The secret.
88
+
89
+ Returns:
90
+ The decoded bytes (only whole bytes; leftover bits are dropped).
91
+ """
92
+ bits = ''.join(f'{_BASE32.index(c):05b}' for c in text.upper() if c in _BASE32)
93
+ return bytes(int(bits[i : i + 8], 2) for i in range(0, len(bits) - len(bits) % 8, 8))
94
+
95
+
96
+ def _int_param(params: dict[str, list[str]], name: str, default: int) -> int:
97
+ """Read an integer parameter of an ``otpauth://`` URI.
98
+
99
+ Args:
100
+ params: The parsed query parameters (lowercase names).
101
+ name: The parameter name.
102
+ default: The value when absent or not a number (as in the official apps).
103
+
104
+ Returns:
105
+ The value.
106
+ """
107
+ values = params.get(name)
108
+ try:
109
+ return int(values[0]) if values else default
110
+ except ValueError:
111
+ return default
112
+
113
+
114
+ def parse_totp(seed: str) -> TotpSpec:
115
+ """Parse a TOTP seed, with the same rules as the official apps.
116
+
117
+ Characters outside the base32 alphabet are ignored, ``digits`` is limited to 0-10, ``period`` is at least
118
+ 1 and an unknown ``algorithm`` falls back to SHA-1, so every seed the official apps accept gives the same
119
+ code here. Unlike them, counter-based ``otpauth://hotp`` seeds are refused: a time-based code for them
120
+ would never be valid.
121
+
122
+ Args:
123
+ seed: A base32 secret, an ``otpauth://totp/...`` URI or a ``steam://...`` seed.
124
+
125
+ Returns:
126
+ The parsed seed.
127
+
128
+ Raises:
129
+ TotpError: An ``otpauth://hotp`` seed, or an ``otpauth://`` URI that is malformed or has no secret.
130
+ """
131
+ seed = seed.strip()
132
+ lowered = seed.lower()
133
+ if lowered.startswith('steam://'):
134
+ return TotpSpec(secret=_b32decode(seed[len('steam://') :]), kind='steam', digits=_STEAM_DIGITS)
135
+ if lowered.startswith('otpauth://'):
136
+ try:
137
+ parts = urlsplit(seed)
138
+ except ValueError as e:
139
+ raise TotpError('invalid otpauth URI') from e
140
+ if parts.netloc.lower() == 'hotp':
141
+ raise TotpError('counter-based (HOTP) seeds are not supported')
142
+ params = {k.lower(): v for k, v in parse_qs(parts.query).items()}
143
+ if not params.get('secret'):
144
+ raise TotpError('otpauth URI has no secret')
145
+ algorithm = params.get('algorithm', ['SHA1'])[0].upper()
146
+ label = unquote(parts.path.lstrip('/'))
147
+ label_issuer, _, account = label.partition(':') if ':' in label else ('', '', label)
148
+ return TotpSpec(
149
+ secret=_b32decode(params['secret'][0]),
150
+ algorithm=algorithm if algorithm in _DIGESTS else 'SHA1', # type: ignore[arg-type]
151
+ digits=min(max(_int_param(params, 'digits', 6), 0), 10),
152
+ period=max(_int_param(params, 'period', 30), 1),
153
+ issuer=(params.get('issuer') or [label_issuer.strip()])[0] or None,
154
+ account=account.strip() or None,
155
+ )
156
+ return TotpSpec(secret=_b32decode(seed))
157
+
158
+
159
+ def _timestamp(at: datetime | float | None) -> float:
160
+ """Turn the ``at`` argument into a Unix timestamp.
161
+
162
+ Args:
163
+ at: A timezone-aware datetime, a Unix timestamp, or None for now.
164
+
165
+ Returns:
166
+ The timestamp.
167
+
168
+ Raises:
169
+ TotpError: A naive datetime (without time zone) was given.
170
+ """
171
+ if at is None:
172
+ return time.time()
173
+ if isinstance(at, datetime):
174
+ if at.tzinfo is None:
175
+ raise TotpError('pass an aware datetime (with time zone)')
176
+ return at.timestamp()
177
+ return float(at)
178
+
179
+
180
+ def totp_code(seed: str | TotpSpec, at: datetime | float | None = None) -> TotpCode:
181
+ """Compute the one-time code for a seed.
182
+
183
+ Args:
184
+ seed: The seed as text (see ``parse_totp``) or an already parsed seed.
185
+ at: The moment to compute the code for: a timezone-aware datetime or a Unix timestamp. Defaults to now.
186
+
187
+ Returns:
188
+ The code with its remaining validity.
189
+
190
+ Raises:
191
+ TotpError: The seed is malformed or unsupported, or ``at`` is a naive datetime.
192
+
193
+ Example:
194
+ ```python
195
+ from vaultwarden2.totp import totp_code
196
+ print(totp_code('otpauth://totp/Example:alice?secret=JBSWY3DPEHPK3PXP').code)
197
+ ```
198
+ """
199
+ spec = seed if isinstance(seed, TotpSpec) else parse_totp(seed)
200
+ now = _timestamp(at)
201
+ counter = math.floor(now / spec.period)
202
+ digest = hmac.digest(spec.secret, struct.pack('>Q', counter), _DIGESTS[spec.algorithm])
203
+ offset = digest[-1] & 0x0F
204
+ value = struct.unpack('>I', digest[offset : offset + 4])[0] & 0x7FFFFFFF
205
+ if spec.kind == 'steam':
206
+ chars = []
207
+ for _ in range(_STEAM_DIGITS):
208
+ value, index = divmod(value, len(_STEAM_ALPHABET))
209
+ chars.append(_STEAM_ALPHABET[index])
210
+ code = ''.join(chars)
211
+ else:
212
+ code = str(value % 10**spec.digits).zfill(spec.digits)
213
+ end = (counter + 1) * spec.period
214
+ return TotpCode(code=code, period=spec.period, remaining=max(1, math.ceil(end - now)), valid_until=datetime.fromtimestamp(end, UTC))