bitting 1.2.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.
bitting/hashing.py ADDED
@@ -0,0 +1,502 @@
1
+ """Key hashing: a protocol plus scrypt (stdlib) and Argon2id (optional) backends.
2
+
3
+ Why memory-hard hashing?
4
+ ========================
5
+ An API key store is only as safe as its weakest link if the database
6
+ leaks. Fast hashes such as SHA-256 let an attacker test *billions* of
7
+ candidate keys per second on commodity GPUs. Memory-hard KDFs (scrypt,
8
+ Argon2id) are deliberately expensive in both time and memory, reducing
9
+ offline guessing to a crawl. bitting therefore hashes keys with scrypt
10
+ by default — using only the standard library — and offers Argon2id via
11
+ the optional ``bitting[argon2]`` extra.
12
+
13
+ Encoded format
14
+ ==============
15
+ Hashes are self-describing so parameters can be tuned per deployment and
16
+ per key::
17
+
18
+ $scrypt$n=16384$r=8$p=1$<salt-b64>$<hash-b64>
19
+ $argon2id$v=19$m=65536,t=3,p=1$<salt-b64>$<hash-b64>
20
+
21
+ Verification is constant-time (:func:`hmac.compare_digest`).
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import base64
27
+ import hashlib
28
+ import hmac
29
+ import os
30
+ import re
31
+ from typing import Protocol, runtime_checkable
32
+
33
+ from .errors import ConfigurationError
34
+
35
+ __all__ = ["DEFAULT_SCRYPT_N", "Argon2Hasher", "Hasher", "ScryptHasher"]
36
+
37
+
38
+ @runtime_checkable
39
+ class Hasher(Protocol):
40
+ """Anything that can hash and verify raw API keys."""
41
+
42
+ @property
43
+ def algorithm(self) -> str:
44
+ """Short algorithm identifier used in the encoded hash."""
45
+ ...
46
+
47
+ def hash(self, raw: str) -> str:
48
+ """Hash a raw key, returning a self-describing encoded string."""
49
+ ...
50
+
51
+ def verify(self, raw: str, encoded: str) -> bool:
52
+ """Constant-time verification of a raw key against an encoded hash."""
53
+ ...
54
+
55
+
56
+ #: Default scrypt CPU/memory cost (2**14 = 16 MiB per hash).
57
+ DEFAULT_SCRYPT_N = 2**14
58
+
59
+ #: Upper bound on scrypt memory use when ``maxmem`` is not given (1 GiB).
60
+ #: Configurations that would need more are rejected at construction.
61
+ SCRYPT_MAXMEM_CEILING = 1024 * 1024 * 1024
62
+
63
+ # Sanity bounds for parameters read back from a *stored* encoded hash.
64
+ # A crafted store record must not be able to force absurd CPU or memory
65
+ # use at verification time.
66
+ _SCRYPT_MAX_N = 2**22
67
+ _SCRYPT_MAX_R = 64
68
+ _SCRYPT_MAX_P = 64
69
+ _ARGON2_MAX_T = 2**16
70
+ _ARGON2_MAX_M = 2**20 # KiB (1 GiB)
71
+ _ARGON2_MAX_P = 64
72
+ #: Shortest digest both hashers will verify (bytes).
73
+ _MIN_DIGEST_LENGTH = 16
74
+ #: Longest salt/digest both hashers will accept from a stored encoded
75
+ #: hash (bytes). Bounds the allocation a crafted record can force.
76
+ _MAX_SALT_LENGTH = 512
77
+ _MAX_DIGEST_LENGTH = 512
78
+ #: Ceiling on total Argon2id work (time_cost * memory_cost in KiB-passes)
79
+ #: accepted from a *stored* hash unless it matches the hasher's own
80
+ #: configuration. 2**23 allows e.g. t=8 x 1 GiB or t=64 x 128 MiB while
81
+ #: rejecting pathological combinations (t=1024 x 256 MiB ≈ minutes of CPU).
82
+ _ARGON2_MAX_WORK = 2**23
83
+ #: Independent ceiling on stored Argon2id time_cost (passes).
84
+ _ARGON2_MAX_T_STRICT = 4096
85
+
86
+ #: Total scrypt work (``n * r * p``) of the documented default profile.
87
+ #: Used as the floor for the stored-hash work budget below.
88
+ _SCRYPT_DEFAULT_WORK = DEFAULT_SCRYPT_N * 8 * 1
89
+ #: How much more work a *stored* scrypt hash may demand than this
90
+ #: deployment's own configured profile. Per-parameter bounds and
91
+ #: ``maxmem`` alone do not bound CPU: ``n=131072, r=2, p=64`` fits in
92
+ #: 32 MiB yet costs ~67x the default profile (measured: ~4 s per verify).
93
+ #: Stored parameters that match the hasher's own configuration exactly
94
+ #: are always accepted, so deliberately heavy deployments keep working.
95
+ _SCRYPT_MAX_WORK_FACTOR = 4
96
+
97
+ #: Canonical parameter syntax for stored encoded hashes. Anchored and
98
+ #: digits-only: rejects ``n=+256``, ``n=256=999``, ``n=1_024``, ``n= 256``
99
+ #: and renamed keys, all of which ``int(part.split("=")[1])`` accepted.
100
+ _SCRYPT_PARAM_RES = (
101
+ re.compile(r"n=([0-9]+)"),
102
+ re.compile(r"r=([0-9]+)"),
103
+ re.compile(r"p=([0-9]+)"),
104
+ )
105
+ _ARGON2_PARAM_RE = re.compile(r"([mtp])=([0-9]+)")
106
+
107
+
108
+ def _require_int(name: str, value: int) -> None:
109
+ if isinstance(value, bool) or not isinstance(value, int):
110
+ raise ConfigurationError(f"{name} must be an int")
111
+
112
+
113
+ def _scrypt_memory(n: int, r: int, p: int) -> int:
114
+ """Bytes of memory OpenSSL's scrypt needs for these parameters."""
115
+ return 128 * r * (n + p)
116
+
117
+
118
+ def _b64encode(data: bytes) -> str:
119
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
120
+
121
+
122
+ def _b64decode(text: str) -> bytes:
123
+ padding = "=" * (-len(text) % 4)
124
+ return base64.urlsafe_b64decode(text + padding)
125
+
126
+
127
+ class ScryptHasher:
128
+ """Memory-hard hasher backed by :func:`hashlib.scrypt` (stdlib only).
129
+
130
+ Args:
131
+ n: CPU/memory cost (must be a power of two). Default ``2**14``
132
+ (~16 MiB per hash) — a deliberate middle ground between
133
+ verification latency and offline-guessing resistance.
134
+ r: Block size for scrypt.
135
+ p: Parallelization factor.
136
+ salt_length: Random salt length in bytes (16 recommended).
137
+ dklen: Derived key length in bytes (>= 16).
138
+ maxmem: Maximum bytes scrypt may allocate. By default it is
139
+ derived from the configured parameters (plus slack), so any
140
+ internally consistent configuration works; configurations
141
+ whose derived limit would exceed 1 GiB are rejected at
142
+ construction instead of failing on every hash.
143
+
144
+ Raises:
145
+ ConfigurationError: If parameters are out of range or exceed
146
+ the memory ceiling.
147
+ """
148
+
149
+ def __init__(
150
+ self,
151
+ *,
152
+ n: int = DEFAULT_SCRYPT_N,
153
+ r: int = 8,
154
+ p: int = 1,
155
+ salt_length: int = 16,
156
+ dklen: int = 32,
157
+ maxmem: int | None = None,
158
+ ) -> None:
159
+ for name, value in (
160
+ ("n", n),
161
+ ("r", r),
162
+ ("p", p),
163
+ ("salt_length", salt_length),
164
+ ("dklen", dklen),
165
+ ):
166
+ _require_int(name, value)
167
+ if maxmem is not None:
168
+ _require_int("maxmem", maxmem)
169
+ if n < 2 or n & (n - 1):
170
+ raise ConfigurationError("scrypt n must be a power of two >= 2")
171
+ if r < 1 or p < 1:
172
+ raise ConfigurationError("scrypt r and p must be >= 1")
173
+ if r == 1 and n >= 2**16:
174
+ # OpenSSL rejects this combination at hash() time with a raw
175
+ # ValueError ("memory limit exceeded") *regardless of maxmem*
176
+ # (verified: n=2**16..2**22, r=1, maxmem up to 2**31-2 all fail;
177
+ # r>=2 works throughout the documented range). The parameters are
178
+ # in-bounds and under the memory ceiling, so construction used to
179
+ # succeed and every hash() then crashed — contradicting the
180
+ # documented "any consistent configuration up to 1 GiB works"
181
+ # (same defect class as the bricked-key fix).
182
+ # Fail fast with a clear error instead.
183
+ raise ConfigurationError(
184
+ f"scrypt r=1 with n>=2**16 is rejected by OpenSSL regardless of "
185
+ f"maxmem; use r>=2 or lower n (got n={n}, r=1)"
186
+ )
187
+ # Construction bounds mirror the sanity bounds verify() enforces on
188
+ # *stored* hashes (see _SCRYPT_MAX_*). Without them a hasher can be
189
+ # configured to issue keys whose stored parameters verification then
190
+ # rejects outright — keys that hash fine but never verify
191
+ # (silently bricked keys). Parameters equal to this hasher's
192
+ # own configuration are always accepted at verification time, so any
193
+ # in-bounds configuration keeps working after upgrades/downgrades.
194
+ if n > _SCRYPT_MAX_N:
195
+ raise ConfigurationError(
196
+ f"scrypt n must be <= {_SCRYPT_MAX_N} so issued keys stay verifiable (got {n})"
197
+ )
198
+ if r > _SCRYPT_MAX_R:
199
+ raise ConfigurationError(
200
+ f"scrypt r must be <= {_SCRYPT_MAX_R} so issued keys stay verifiable (got {r})"
201
+ )
202
+ if p > _SCRYPT_MAX_P:
203
+ raise ConfigurationError(
204
+ f"scrypt p must be <= {_SCRYPT_MAX_P} so issued keys stay verifiable (got {p})"
205
+ )
206
+ if salt_length < 8:
207
+ raise ConfigurationError("salt_length must be >= 8 bytes")
208
+ if salt_length > _MAX_SALT_LENGTH:
209
+ raise ConfigurationError(
210
+ f"salt_length must be <= {_MAX_SALT_LENGTH} bytes (got {salt_length})"
211
+ )
212
+ if dklen < _MIN_DIGEST_LENGTH:
213
+ raise ConfigurationError(f"dklen must be >= {_MIN_DIGEST_LENGTH} bytes")
214
+ if dklen > _MAX_DIGEST_LENGTH:
215
+ raise ConfigurationError(f"dklen must be <= {_MAX_DIGEST_LENGTH} bytes (got {dklen})")
216
+ required = _scrypt_memory(n, r, p)
217
+ if maxmem is None:
218
+ if required > SCRYPT_MAXMEM_CEILING:
219
+ raise ConfigurationError(
220
+ f"scrypt parameters need {required / 1024**2:.0f} MiB, above the "
221
+ f"{SCRYPT_MAXMEM_CEILING / 1024**2:.0f} MiB ceiling; lower n/r or "
222
+ "pass maxmem explicitly"
223
+ )
224
+ maxmem = required + 32 * 1024 * 1024 # slack for runtime overhead
225
+ elif maxmem < required:
226
+ raise ConfigurationError(
227
+ f"maxmem ({maxmem / 1024**2:.0f} MiB) is below what n={n}, r={r}, "
228
+ f"p={p} requires ({required / 1024**2:.0f} MiB)"
229
+ )
230
+ if maxmem >= 2**31 - 1:
231
+ # OpenSSL rejects maxmem >= 2**31-1 at hash time with a raw
232
+ # ValueError; fail at construction with a clear error instead.
233
+ raise ConfigurationError("maxmem must be smaller than 2147483647 (OpenSSL limit)")
234
+ self.n = n
235
+ self.r = r
236
+ self.p = p
237
+ self.salt_length = salt_length
238
+ self.dklen = dklen
239
+ self._maxmem = maxmem
240
+
241
+ @property
242
+ def algorithm(self) -> str:
243
+ return "scrypt"
244
+
245
+ def _derive(self, raw: str, salt: bytes) -> bytes:
246
+ return hashlib.scrypt(
247
+ raw.encode("utf-8"),
248
+ salt=salt,
249
+ n=self.n,
250
+ r=self.r,
251
+ p=self.p,
252
+ dklen=self.dklen,
253
+ maxmem=self._maxmem,
254
+ )
255
+
256
+ def hash(self, raw: str) -> str:
257
+ salt = os.urandom(self.salt_length)
258
+ derived = self._derive(raw, salt)
259
+ return f"$scrypt$n={self.n}$r={self.r}$p={self.p}${_b64encode(salt)}${_b64encode(derived)}"
260
+
261
+ def verify(self, raw: str, encoded: str) -> bool:
262
+ if not isinstance(encoded, str):
263
+ # Fail safe on corrupt records instead of raising AttributeError.
264
+ return False
265
+ try:
266
+ scheme, n_part, r_part, p_part, salt_b64, hash_b64 = encoded.split("$")[1:]
267
+ if scheme != "scrypt":
268
+ return False
269
+ # Canonical parameter syntax only: the key name must match and
270
+ # the value must be plain digits (no sign, whitespace, "_"
271
+ # separators or a second "=").
272
+ matches = [
273
+ pattern.fullmatch(part)
274
+ for pattern, part in zip(_SCRYPT_PARAM_RES, (n_part, r_part, p_part), strict=True)
275
+ ]
276
+ if any(m is None for m in matches):
277
+ return False
278
+ n, r, p = (int(m.group(1)) for m in matches if m is not None)
279
+ # Parameters matching this hasher's own configuration are always
280
+ # allowed (mirrors Argon2Hasher): a key issued by *this* hasher
281
+ # must verify no matter what the generic bounds are. Parameters
282
+ # from a *stored* (potentially crafted) hash are only trusted
283
+ # within sane bounds — a crafted record must not force absurd
284
+ # KDF memory (hard-capped by maxmem) or per-parameter work.
285
+ own_config = n == self.n and r == self.r and p == self.p
286
+ if not own_config and not (
287
+ 2 <= n <= _SCRYPT_MAX_N and 1 <= r <= _SCRYPT_MAX_R and 1 <= p <= _SCRYPT_MAX_P
288
+ ):
289
+ return False
290
+ # Per-parameter bounds and maxmem bound *memory*, not *CPU*:
291
+ # p multiplies CPU without multiplying memory. Bound the total
292
+ # work relative to this deployment's own profile, mirroring the
293
+ # Argon2id total-work cap. The hasher's exact own configuration
294
+ # is always allowed so heavy deployments keep verifying, and the
295
+ # default profile's work is the floor so keys issued at the
296
+ # documented default keep verifying on cheaper deployments.
297
+ work_budget = max(
298
+ _SCRYPT_MAX_WORK_FACTOR * self.n * self.r * self.p, _SCRYPT_DEFAULT_WORK
299
+ )
300
+ if not own_config and n * r * p > work_budget:
301
+ return False
302
+ salt = _b64decode(salt_b64)
303
+ expected = _b64decode(hash_b64)
304
+ if not (
305
+ _MIN_DIGEST_LENGTH <= len(expected) <= _MAX_DIGEST_LENGTH
306
+ and 1 <= len(salt) <= _MAX_SALT_LENGTH
307
+ ):
308
+ return False
309
+ except (ValueError, IndexError):
310
+ return False
311
+ try:
312
+ derived = hashlib.scrypt(
313
+ raw.encode("utf-8"),
314
+ salt=salt,
315
+ n=n,
316
+ r=r,
317
+ p=p,
318
+ dklen=len(expected),
319
+ maxmem=self._maxmem,
320
+ )
321
+ except ValueError:
322
+ return False
323
+ return hmac.compare_digest(derived, expected)
324
+
325
+
326
+ class Argon2Hasher:
327
+ """Argon2id hasher using ``argon2-cffi`` (optional dependency; install
328
+ the ``argon2`` extra or ``pip install argon2-cffi`` directly).
329
+
330
+ Parameters mirror the argon2 low-level API. Defaults follow the
331
+ RFC 9106 recommended first-choice: Argon2id, 64 MiB, t=3, p=1.
332
+
333
+ Raises:
334
+ ConfigurationError: If ``argon2-cffi`` is not installed or
335
+ parameters are invalid.
336
+ """
337
+
338
+ def __init__(
339
+ self,
340
+ *,
341
+ time_cost: int = 3,
342
+ memory_cost: int = 65536,
343
+ parallelism: int = 1,
344
+ salt_length: int = 16,
345
+ hash_length: int = 32,
346
+ ) -> None:
347
+ try:
348
+ from argon2 import Type
349
+ from argon2.exceptions import HashingError
350
+ from argon2.low_level import hash_secret_raw
351
+ except ModuleNotFoundError as exc: # pragma: no cover - exercised via importorskip
352
+ raise ConfigurationError(
353
+ "Argon2Hasher requires the optional dependency argon2-cffi; "
354
+ "install it with: pip install argon2-cffi"
355
+ ) from exc
356
+ for name, value in (
357
+ ("time_cost", time_cost),
358
+ ("memory_cost", memory_cost),
359
+ ("parallelism", parallelism),
360
+ ("salt_length", salt_length),
361
+ ("hash_length", hash_length),
362
+ ):
363
+ _require_int(name, value)
364
+ if time_cost < 1 or parallelism < 1:
365
+ raise ConfigurationError("argon2 time_cost and parallelism must be >= 1")
366
+ if memory_cost < 8:
367
+ raise ConfigurationError("argon2 memory_cost must be >= 8 KiB")
368
+ if salt_length < 8:
369
+ raise ConfigurationError("salt_length must be >= 8 bytes")
370
+ if salt_length > _MAX_SALT_LENGTH:
371
+ raise ConfigurationError(
372
+ f"salt_length must be <= {_MAX_SALT_LENGTH} bytes (got {salt_length})"
373
+ )
374
+ if hash_length < _MIN_DIGEST_LENGTH:
375
+ raise ConfigurationError(f"hash_length must be >= {_MIN_DIGEST_LENGTH} bytes")
376
+ if hash_length > _MAX_DIGEST_LENGTH:
377
+ raise ConfigurationError(
378
+ f"hash_length must be <= {_MAX_DIGEST_LENGTH} bytes (got {hash_length})"
379
+ )
380
+ if memory_cost < 8 * parallelism:
381
+ # argon2 rejects this combination only when hashing; fail at
382
+ # construction instead so misconfiguration surfaces early.
383
+ raise ConfigurationError(
384
+ f"argon2 memory_cost must be >= 8 * parallelism "
385
+ f"({8 * parallelism} KiB for parallelism={parallelism})"
386
+ )
387
+ # Construction bounds mirror the sanity bounds verify() enforces on
388
+ # *stored* hashes (see _ARGON2_MAX_*). Without them a hasher can be
389
+ # configured to issue keys whose stored parameters verification then
390
+ # rejects outright — keys that hash fine but never verify (the same
391
+ # fixed for scrypt). Parameters equal to this hasher's
392
+ # own configuration are always accepted at verification time, so any
393
+ # in-bounds configuration keeps working after upgrades/downgrades.
394
+ if time_cost > _ARGON2_MAX_T:
395
+ raise ConfigurationError(
396
+ f"argon2 time_cost must be <= {_ARGON2_MAX_T} so issued keys "
397
+ f"stay verifiable (got {time_cost})"
398
+ )
399
+ if memory_cost > _ARGON2_MAX_M:
400
+ raise ConfigurationError(
401
+ f"argon2 memory_cost must be <= {_ARGON2_MAX_M} KiB so issued "
402
+ f"keys stay verifiable (got {memory_cost})"
403
+ )
404
+ if parallelism > _ARGON2_MAX_P:
405
+ raise ConfigurationError(
406
+ f"argon2 parallelism must be <= {_ARGON2_MAX_P} so issued keys "
407
+ f"stay verifiable (got {parallelism})"
408
+ )
409
+ self.time_cost = time_cost
410
+ self.memory_cost = memory_cost
411
+ self.parallelism = parallelism
412
+ self.salt_length = salt_length
413
+ self.hash_length = hash_length
414
+ self._type = Type
415
+ self._hash_secret_raw = hash_secret_raw
416
+ # argon2-cffi raises its own exception type (not ValueError) when
417
+ # stored hash parameters are invalid; verify() must catch it too.
418
+ self._hashing_error: type[Exception] = HashingError
419
+
420
+ @property
421
+ def algorithm(self) -> str:
422
+ return "argon2id"
423
+
424
+ def hash(self, raw: str) -> str:
425
+ salt = os.urandom(self.salt_length)
426
+ derived = self._hash_secret_raw(
427
+ secret=raw.encode("utf-8"),
428
+ salt=salt,
429
+ time_cost=self.time_cost,
430
+ memory_cost=self.memory_cost,
431
+ parallelism=self.parallelism,
432
+ hash_len=self.hash_length,
433
+ type=self._type.ID,
434
+ )
435
+ return (
436
+ f"$argon2id$v=19$m={self.memory_cost},t={self.time_cost},p={self.parallelism}"
437
+ f"${_b64encode(salt)}${_b64encode(derived)}"
438
+ )
439
+
440
+ def verify(self, raw: str, encoded: str) -> bool:
441
+ if not isinstance(encoded, str):
442
+ # Fail safe on corrupt records instead of raising AttributeError.
443
+ return False
444
+ try:
445
+ scheme, version, params_part, salt_b64, hash_b64 = encoded.split("$")[1:]
446
+ if scheme != "argon2id" or version != "v=19":
447
+ return False
448
+ # Exactly the three canonical parameters, each appearing once,
449
+ # digits-only. Duplicate keys previously let a later "m=8"
450
+ # silently override an earlier "m=65536".
451
+ items = params_part.split(",")
452
+ parsed_params = [_ARGON2_PARAM_RE.fullmatch(item) for item in items]
453
+ if len(items) != 3 or any(m is None for m in parsed_params):
454
+ return False
455
+ params = {m.group(1): int(m.group(2)) for m in parsed_params if m is not None}
456
+ if len(params) != 3:
457
+ return False
458
+ # Parameters matching this hasher's own configuration are always
459
+ # allowed: a key issued by *this* hasher must verify no matter
460
+ # what the generic bounds are (mirrors ScryptHasher). Parameters
461
+ # from a *stored* (potentially crafted) hash are only trusted
462
+ # within the sanity bounds below, and — beyond them — within the
463
+ # total-work envelope: a crafted record combining a large pass
464
+ # count with a large memory cost must not force a multi-minute,
465
+ # 1 GiB KDF run per verification.
466
+ own_config = (
467
+ params.get("t", 0) == self.time_cost
468
+ and params.get("m", 0) == self.memory_cost
469
+ and params.get("p", 0) == self.parallelism
470
+ )
471
+ if not own_config and not (
472
+ 1 <= params.get("t", 0) <= _ARGON2_MAX_T
473
+ and 8 <= params.get("m", 0) <= _ARGON2_MAX_M
474
+ and 1 <= params.get("p", 0) <= _ARGON2_MAX_P
475
+ ):
476
+ return False
477
+ salt = _b64decode(salt_b64)
478
+ expected = _b64decode(hash_b64)
479
+ if not (
480
+ _MIN_DIGEST_LENGTH <= len(expected) <= _MAX_DIGEST_LENGTH
481
+ and 1 <= len(salt) <= _MAX_SALT_LENGTH
482
+ ):
483
+ return False
484
+ if not own_config and (
485
+ params["t"] > _ARGON2_MAX_T_STRICT or params["t"] * params["m"] > _ARGON2_MAX_WORK
486
+ ):
487
+ return False
488
+ except (ValueError, IndexError):
489
+ return False
490
+ try:
491
+ derived = self._hash_secret_raw(
492
+ secret=raw.encode("utf-8"),
493
+ salt=salt,
494
+ time_cost=params["t"],
495
+ memory_cost=params["m"],
496
+ parallelism=params["p"],
497
+ hash_len=len(expected),
498
+ type=self._type.ID,
499
+ )
500
+ except (KeyError, ValueError, self._hashing_error):
501
+ return False
502
+ return hmac.compare_digest(derived, expected)
@@ -0,0 +1,5 @@
1
+ """Framework integrations for bitting."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __all__ = ["fastapi"]