bitting 1.2.0__tar.gz
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-1.2.0/CHANGELOG.md +430 -0
- bitting-1.2.0/CONTRIBUTING.md +59 -0
- bitting-1.2.0/CONTRIBUTORS.md +11 -0
- bitting-1.2.0/LICENSE +21 -0
- bitting-1.2.0/MANIFEST.in +15 -0
- bitting-1.2.0/PKG-INFO +309 -0
- bitting-1.2.0/README.md +271 -0
- bitting-1.2.0/SECURITY.md +45 -0
- bitting-1.2.0/examples/basic_usage.py +55 -0
- bitting-1.2.0/examples/fastapi_service.py +54 -0
- bitting-1.2.0/pyproject.toml +108 -0
- bitting-1.2.0/setup.cfg +4 -0
- bitting-1.2.0/src/bitting/__init__.py +78 -0
- bitting-1.2.0/src/bitting/__main__.py +10 -0
- bitting-1.2.0/src/bitting/cli.py +266 -0
- bitting-1.2.0/src/bitting/errors.py +41 -0
- bitting-1.2.0/src/bitting/hashing.py +502 -0
- bitting-1.2.0/src/bitting/integrations/__init__.py +5 -0
- bitting-1.2.0/src/bitting/integrations/fastapi.py +256 -0
- bitting-1.2.0/src/bitting/keys.py +228 -0
- bitting-1.2.0/src/bitting/manager.py +783 -0
- bitting-1.2.0/src/bitting/models.py +194 -0
- bitting-1.2.0/src/bitting/py.typed +0 -0
- bitting-1.2.0/src/bitting/storage.py +608 -0
- bitting-1.2.0/src/bitting/timeutil.py +109 -0
- bitting-1.2.0/src/bitting.egg-info/PKG-INFO +309 -0
- bitting-1.2.0/src/bitting.egg-info/SOURCES.txt +50 -0
- bitting-1.2.0/src/bitting.egg-info/dependency_links.txt +1 -0
- bitting-1.2.0/src/bitting.egg-info/entry_points.txt +2 -0
- bitting-1.2.0/src/bitting.egg-info/requires.txt +14 -0
- bitting-1.2.0/src/bitting.egg-info/top_level.txt +1 -0
- bitting-1.2.0/tests/conftest.py +51 -0
- bitting-1.2.0/tests/test_cli.py +169 -0
- bitting-1.2.0/tests/test_concurrency_regressions.py +826 -0
- bitting-1.2.0/tests/test_fastapi_integration.py +171 -0
- bitting-1.2.0/tests/test_hardening_regressions.py +541 -0
- bitting-1.2.0/tests/test_hashing.py +92 -0
- bitting-1.2.0/tests/test_hashing_hardening.py +117 -0
- bitting-1.2.0/tests/test_keys.py +131 -0
- bitting-1.2.0/tests/test_manager_hardening.py +215 -0
- bitting-1.2.0/tests/test_manager_lifecycle.py +253 -0
- bitting-1.2.0/tests/test_property_based.py +263 -0
- bitting-1.2.0/tests/test_release_hardening.py +82 -0
- bitting-1.2.0/tests/test_rotation_hardening.py +168 -0
- bitting-1.2.0/tests/test_security_regressions.py +311 -0
- bitting-1.2.0/tests/test_storage_hardening.py +157 -0
- bitting-1.2.0/tests/test_storage_memory.py +61 -0
- bitting-1.2.0/tests/test_storage_regressions.py +138 -0
- bitting-1.2.0/tests/test_storage_sqlite.py +129 -0
- bitting-1.2.0/tests/test_thread_safety.py +242 -0
- bitting-1.2.0/tests/test_timeutil.py +63 -0
- bitting-1.2.0/tests/test_validation_regressions.py +481 -0
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented in this file.
|
|
4
|
+
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/);
|
|
5
|
+
this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
|
|
11
|
+
- **`ScryptHasher` rejects `r=1` with `n >= 2^16` at construction**: these
|
|
12
|
+
in-bounds, under-ceiling configurations were accepted but every `hash()`
|
|
13
|
+
call raised a raw OpenSSL `ValueError` ("memory limit exceeded")
|
|
14
|
+
regardless of `maxmem` (reproduced for `n = 2^16 .. 2^22`; `r >= 2` works
|
|
15
|
+
throughout the documented range). Construction now fails fast with a
|
|
16
|
+
`ConfigurationError` naming the remedy; `r=1` below `2^16` and `r >= 2`
|
|
17
|
+
everywhere are unaffected, and the default profile is untouched. Regression
|
|
18
|
+
tests in `tests/test_hardening_regressions.py` (fail on the unfixed
|
|
19
|
+
behavior, pass on the fix). README and SECURITY.md now state the exception
|
|
20
|
+
precisely.
|
|
21
|
+
- **Constructing a `KeyManager` over a legacy (duck-typed) store now warns
|
|
22
|
+
loudly**: a store without `mark_verified`/`mark_rotated`/`mark_revoked`
|
|
23
|
+
used to accept the non-atomic read-modify-write fallback silently, and a
|
|
24
|
+
concurrent revocation could be lost (a revoked key verifying again). The
|
|
25
|
+
fallback itself is kept for backwards compatibility, but a one-time
|
|
26
|
+
`UserWarning` is emitted at construction, and accepting the documented
|
|
27
|
+
risk now requires explicitly setting
|
|
28
|
+
`bitting.manager.LEGACY_STORE_WARNING = False`. New module-level export
|
|
29
|
+
`LEGACY_STORE_WARNING`. SECURITY.md documents the behavior.
|
|
30
|
+
- **README limitations state metadata-size and scope-count caller
|
|
31
|
+
responsibilities**: `issue()` accepts any JSON-serializable metadata
|
|
32
|
+
and any number of valid scopes (a 10 MB metadata blob or a 100k-scope key is
|
|
33
|
+
stored whole), and `missing_scopes` is O(granted x required) — cap sizes and
|
|
34
|
+
counts at the application layer.
|
|
35
|
+
- **`rotate()` rejects already-expired keys** instead of minting a successor
|
|
36
|
+
with a grace window on a dead credential: rotation now raises `ValueError`
|
|
37
|
+
("key is expired; issue a new key instead") when the key's TTL has passed.
|
|
38
|
+
- **`ParsedKey.__repr__` redacts the secret** (only `prefix`/`env`/`scheme`
|
|
39
|
+
and the secret's length appear), so a debugger or an unlucky `%r` log line
|
|
40
|
+
can never print the live credential. Regression tests in
|
|
41
|
+
`tests/test_release_hardening.py`.
|
|
42
|
+
- CHANGELOG date for 1.2.0 corrected to 2026-11-17.
|
|
43
|
+
|
|
44
|
+
## [1.2.0] - 2026-11-17
|
|
45
|
+
|
|
46
|
+
Security-focused release. Every confirmed hardening item below is fixed with
|
|
47
|
+
a deterministic regression test; the suite grew from 180 to 396 tests, and
|
|
48
|
+
ruff, mypy --strict, and the sdist/wheel builds stay clean. New API is
|
|
49
|
+
additive only: `KeyStore.mark_revoked`, the public
|
|
50
|
+
`bitting.validate_scopes` helper, and `pytest-cov` in the `dev` extra.
|
|
51
|
+
|
|
52
|
+
### Lifecycle, hashing, and packaging hardening
|
|
53
|
+
|
|
54
|
+
#### Fixed
|
|
55
|
+
|
|
56
|
+
- **`ScryptHasher` no longer issues permanently-unverifiable keys**:
|
|
57
|
+
construction accepted parameters (`r > 64`, `p > 64`, `n > 2^22`) that the
|
|
58
|
+
stored-hash sanity bounds in `verify()` reject outright, so keys hashed
|
|
59
|
+
with such a hasher failed every verification with `hash_mismatch` forever
|
|
60
|
+
("bricked keys" — reproduced with `ScryptHasher(r=128)` and
|
|
61
|
+
`ScryptHasher(p=65)`, which constructed and hashed fine but never
|
|
62
|
+
self-verified). Construction now rejects parameters outside the
|
|
63
|
+
verification bounds with a clear error, and `verify()` accepts parameters
|
|
64
|
+
equal to the hasher's own configuration unconditionally (mirroring
|
|
65
|
+
`Argon2Hasher`), so every legitimately constructible hasher keeps verifying
|
|
66
|
+
its own keys — including in-bounds heavy configurations — and cost
|
|
67
|
+
upgrades/downgrades keep old keys working.
|
|
68
|
+
- **`revoke()` can no longer erase a concurrently claimed rotation**:
|
|
69
|
+
revocation performed a non-atomic read-modify-write full-record `save()`;
|
|
70
|
+
a revoke racing a rotate wrote a stale snapshot back and erased
|
|
71
|
+
`rotated_at`/`grace_until` (deterministically reproduced with a gated
|
|
72
|
+
store). Revocation now goes through the new
|
|
73
|
+
`KeyStore.mark_revoked(prefix, at=...)` — a targeted conditional
|
|
74
|
+
`UPDATE keys SET revoked_at=? WHERE prefix=? AND revoked_at IS NULL`
|
|
75
|
+
inside `BEGIN IMMEDIATE` for SQLite (atomic across threads and processes)
|
|
76
|
+
and a lock-guarded replacement for the in-memory store. As a consequence,
|
|
77
|
+
revocation is now **idempotent**: revoking an already-revoked key keeps the
|
|
78
|
+
first (authoritative) `revoked_at` timestamp and records the repeated
|
|
79
|
+
attempt in the audit trail with an `already_revoked` detail flag
|
|
80
|
+
(previously the timestamp was silently overwritten). Duck-typed stores
|
|
81
|
+
without `mark_revoked` fall back to the previous behavior, documented as
|
|
82
|
+
non-atomic.
|
|
83
|
+
- **`Argon2Hasher` no longer issues permanently-unverifiable keys** (the
|
|
84
|
+
same defect class as the scrypt one above): construction accepted
|
|
85
|
+
parameters whose stored form `verify()` rejects unconditionally
|
|
86
|
+
(`parallelism > 64`, `memory_cost > 2^20 KiB`, `time_cost > 2^16` — e.g.
|
|
87
|
+
`Argon2Hasher(parallelism=65)` hashed fine and never verified).
|
|
88
|
+
Construction now enforces the same sanity bounds, and the
|
|
89
|
+
own-configuration exemption in `verify()` covers all bounds (previously it
|
|
90
|
+
exempted only the strict total-work caps), mirroring `ScryptHasher`.
|
|
91
|
+
- **FastAPI `require()` rejects bare-string scopes**: a bare string silently
|
|
92
|
+
became a set of single characters (`"read:users"` -> `{'r','e','a',...}`),
|
|
93
|
+
matching nothing sensible while appearing configured. It now raises
|
|
94
|
+
`ValueError` at setup, consistent with `KeyManager`'s scope validation.
|
|
95
|
+
- **`revoke()` drops a redundant store read**: the `KeyNotFoundError`
|
|
96
|
+
contract is preserved by the post-transition re-read.
|
|
97
|
+
- **FastAPI `require()` validates scopes at setup time**: malformed scope
|
|
98
|
+
strings (empty, whitespace-containing, non-string) in a route's
|
|
99
|
+
`require(scopes=...)` raised `ValueError` inside the request handler — a
|
|
100
|
+
500 on every request. They now raise at dependency-construction time, so
|
|
101
|
+
the application fails fast at startup instead.
|
|
102
|
+
- **sdist ships a runnable test suite**: `tests/conftest.py` was missing from
|
|
103
|
+
the source distribution (setuptools' default sdist list includes only
|
|
104
|
+
`tests/test*.py`), so `pytest` on an unpacked sdist failed at collection.
|
|
105
|
+
A `MANIFEST.in` now includes `conftest.py` plus the operator-facing docs
|
|
106
|
+
(CHANGELOG, SECURITY, CONTRIBUTING, CONTRIBUTORS) and the examples.
|
|
107
|
+
- **README corrections**: the documented test count was stale; the
|
|
108
|
+
limitations section now states the custom-store fallback consequence
|
|
109
|
+
explicitly (a store without `mark_verified` can lose a concurrent
|
|
110
|
+
revocation — a revoked key may verify again) and records the `list_keys()`
|
|
111
|
+
scaling characteristics.
|
|
112
|
+
|
|
113
|
+
#### Added
|
|
114
|
+
|
|
115
|
+
- `KeyStore.mark_revoked(prefix, at=...)` protocol method (see above); both
|
|
116
|
+
built-in stores implement it atomically.
|
|
117
|
+
- `tests/test_hardening_regressions.py` — regression tests for every item
|
|
118
|
+
above, plus two suite-gap tests from mutation testing: a chi-square
|
|
119
|
+
statistical-uniformity test for the base62 generator (a modulo-bias
|
|
120
|
+
mutation previously survived the entire suite) and
|
|
121
|
+
constant-time-comparison wiring tests for both hashers (replacing
|
|
122
|
+
`hmac.compare_digest` with `==` previously survived).
|
|
123
|
+
- A test pinning the documented residual risk of the legacy five-method
|
|
124
|
+
store fallback: a verification touch racing a revocation on such a store
|
|
125
|
+
can resurrect the revoked key. This cannot be fixed generically without
|
|
126
|
+
store cooperation; the limitation is now stated explicitly in README and
|
|
127
|
+
SECURITY.md instead of being implied.
|
|
128
|
+
|
|
129
|
+
#### Security notes (no behavior change)
|
|
130
|
+
|
|
131
|
+
- Measured crafted-stored-hash envelope, now documented precisely in
|
|
132
|
+
SECURITY.md and README: with store-write access (outside the documented
|
|
133
|
+
threat model) an attacker can select in-bounds KDF parameters per record —
|
|
134
|
+
memory stays hard-capped by the configured `maxmem`, but scrypt CPU per
|
|
135
|
+
verification could reach ~100-150x the configured cost (via `p <= 64`) and
|
|
136
|
+
Argon2id ~60x (total-work cap). *(Superseded for scrypt by the total-work
|
|
137
|
+
budget below: scrypt CPU is now bounded at 4x.)*
|
|
138
|
+
|
|
139
|
+
#### Further hardening (follow-up fixes)
|
|
140
|
+
|
|
141
|
+
##### Fixed
|
|
142
|
+
|
|
143
|
+
- **A credential revoked, expired, rotated out of grace, deleted or
|
|
144
|
+
scope-narrowed while its verification's KDF was running no longer
|
|
145
|
+
authorizes**: the verdict previously came from the pre-hash snapshot, so
|
|
146
|
+
the in-flight request returned `ok` even though the revocation had already
|
|
147
|
+
committed. Verification now re-reads the record and the clock *after* the
|
|
148
|
+
KDF and re-checks lifecycle state before authorizing; the extra cost is
|
|
149
|
+
one indexed lookup on the success path only. This shrinks — but cannot
|
|
150
|
+
eliminate — the check-then-act window; applications needing a hard
|
|
151
|
+
guarantee must serialize revocation against authorization at a higher
|
|
152
|
+
layer.
|
|
153
|
+
- **Crafted scrypt stored hashes are now bounded by a total-work budget**:
|
|
154
|
+
`n x r x p` of a stored record may not exceed 4x the active profile's work
|
|
155
|
+
(with the documented default profile's work as the floor), so a record
|
|
156
|
+
like `n=131072,r=2,p=64` (~67x default, ~4 s per verify, measured) is
|
|
157
|
+
rejected before the KDF instead of burning CPU on every verification.
|
|
158
|
+
Parameters matching the hasher's own configuration are always accepted,
|
|
159
|
+
and the default-work floor keeps keys issued at the documented default
|
|
160
|
+
verifiable on cheaper deployments. Keys issued under a profile more than
|
|
161
|
+
4x heavier than the active one stop verifying after a drastic config
|
|
162
|
+
downgrade — the deliberate trade that closes the crafted-CPU envelope
|
|
163
|
+
noted above.
|
|
164
|
+
- **`SQLiteStore("~/keys.db")` works**: `~` was expanded for the parent
|
|
165
|
+
directory but not the connection path, so the store created directories
|
|
166
|
+
under `$HOME` and then failed to open the literal `~/keys.db`.
|
|
167
|
+
- **`bitting <command> --json` works**: `--json` was only accepted before
|
|
168
|
+
the subcommand; after it, argparse exited 2, contradicting the README.
|
|
169
|
+
The flag is now registered on every subparser too.
|
|
170
|
+
- **`InMemoryStore.mark_verified` deep-copies metadata**: nested containers
|
|
171
|
+
were previously re-aliased to the stored record (`dict()` copy).
|
|
172
|
+
- **`from_iso` accepts a trailing `Z`/`z` on every supported Python**:
|
|
173
|
+
`datetime.fromisoformat` only accepts `Z` from Python 3.11, so a row
|
|
174
|
+
written by an external tool with a `Z` suffix loaded on 3.11+ and raised
|
|
175
|
+
on 3.10.
|
|
176
|
+
- **Encoded-hash parameter parsing is canonical-only**: scrypt parameters
|
|
177
|
+
must be plain digits with the exact `n=`/`r=`/`p=` names (previously
|
|
178
|
+
`n=+256`, `n=1_024`, `n=256=999`, `n= 256` and renamed keys were all
|
|
179
|
+
parsed and honored), and Argon2id accepts exactly the three canonical
|
|
180
|
+
`m`/`t`/`p` parameters, each once (previously a later duplicate key
|
|
181
|
+
silently overrode an earlier value).
|
|
182
|
+
- **Duplicate credential headers fail closed**: the header lookup returned
|
|
183
|
+
the first occurrence, so a request carrying both a valid and an invalid
|
|
184
|
+
key authenticated when the valid one happened to be listed first. An
|
|
185
|
+
ambiguous credential is now refused outright (401).
|
|
186
|
+
- **`issue()` retries on a prefix collision instead of silently
|
|
187
|
+
overwriting**: `store.save()` is an upsert, so a colliding prefix would
|
|
188
|
+
have replaced an existing credential. The prefix is now checked before
|
|
189
|
+
saving and redrawn (astronomically unlikely, but the failure mode is
|
|
190
|
+
credential replacement).
|
|
191
|
+
- **Hasher constructors require integral parameter types**: a float `n`
|
|
192
|
+
previously raised a raw `TypeError` from the power-of-two check, a float
|
|
193
|
+
`dklen` or Argon2id `time_cost` constructed fine and failed at hash time,
|
|
194
|
+
and a bool was silently accepted (`True == 1`). All parameters now fail
|
|
195
|
+
fast with `ConfigurationError` at construction.
|
|
196
|
+
- **Metadata must be JSON-serializable, and SQLite no longer stringifies
|
|
197
|
+
what is not**: `issue()` previously accepted any metadata; the SQLite
|
|
198
|
+
layer serialized it with `json.dumps(default=str)`, silently turning
|
|
199
|
+
non-JSON values into strings while `InMemoryStore` kept the live object —
|
|
200
|
+
the same key round-tripped differently per store. `issue()` now rejects
|
|
201
|
+
non-JSON metadata with a clear `ValueError`, and the SQLite serialization
|
|
202
|
+
no longer coerces.
|
|
203
|
+
|
|
204
|
+
##### Added
|
|
205
|
+
|
|
206
|
+
- **`bitting.validate_scopes`** — the scope normalization/validation helper
|
|
207
|
+
used by `KeyManager` and the FastAPI integration is now public, so
|
|
208
|
+
applications can validate configured scopes the same way the library
|
|
209
|
+
does.
|
|
210
|
+
- **`pytest-cov` is declared in the `dev` extra**, so the documented
|
|
211
|
+
coverage workflow works for contributors out of the box.
|
|
212
|
+
|
|
213
|
+
##### Tests
|
|
214
|
+
|
|
215
|
+
- `tests/test_concurrency_regressions.py` — 64 concurrency tests
|
|
216
|
+
(including a real two-OS-process revoke/rotate interleaving against a
|
|
217
|
+
WAL-mode SQLite file), adapted to the idempotent `mark_revoked(at=)`
|
|
218
|
+
semantics.
|
|
219
|
+
- `tests/test_storage_regressions.py` — 20 storage tests plus a
|
|
220
|
+
both-stores metadata round-trip equivalence test.
|
|
221
|
+
|
|
222
|
+
### Security hardening
|
|
223
|
+
|
|
224
|
+
#### Fixed
|
|
225
|
+
|
|
226
|
+
- **Concurrent first-open of a fresh SQLite store no longer crashes** (found
|
|
227
|
+
by the CI matrix on 3.10/3.11/3.13): `PRAGMA journal_mode=WAL` requires an
|
|
228
|
+
exclusive lock and SQLite returns `SQLITE_BUSY` for that statement
|
|
229
|
+
*without* invoking the busy handler — so several processes opening the
|
|
230
|
+
same fresh database file simultaneously (multi-worker service boot, the
|
|
231
|
+
multiprocess contention test) crashed with `StorageError: database is
|
|
232
|
+
locked`. The open path now retries the journal-mode switch for a bounded
|
|
233
|
+
~2 s before failing; once any opener completes the switch, WAL is
|
|
234
|
+
persistent and every other opener converges. Regression:
|
|
235
|
+
`test_concurrent_first_open_sqlite` (12 barrier-synchronized processes x 3
|
|
236
|
+
fresh files).
|
|
237
|
+
- **Concurrent verification can no longer resurrect revoked or rotated
|
|
238
|
+
keys**: the throttled `last_verified_at` touch was persisted with a
|
|
239
|
+
full-record `save()` of a snapshot read *before* the expensive hash
|
|
240
|
+
check. A verification in flight while an operator revoked (or rotated) the
|
|
241
|
+
same key wrote the stale snapshot back, permanently erasing
|
|
242
|
+
`revoked_at`/`rotated_at`/`grace_until` — the "revoked" key kept
|
|
243
|
+
authenticating indefinitely, and a rotated key became permanently active
|
|
244
|
+
alongside its successor. Touches now go through the new
|
|
245
|
+
`KeyStore.mark_verified()` (a targeted single-`last_verified_at`-column
|
|
246
|
+
update in SQLite, atomic under the store lock in memory; single-column
|
|
247
|
+
`UPDATE ... WHERE prefix=?`). Duck-typed stores without `mark_verified`
|
|
248
|
+
fall back to a re-read that alters only the timestamp (documented
|
|
249
|
+
non-atomic, matching the `mark_rotated` precedent).
|
|
250
|
+
- **Hashers no longer raise on non-string stored hashes**:
|
|
251
|
+
`ScryptHasher.verify(raw, None)` (or any non-string `encoded`) raised
|
|
252
|
+
`AttributeError`/`TypeError` instead of returning `False`, crashing the
|
|
253
|
+
request path when a store returned a corrupt record. Both hashers now fail
|
|
254
|
+
closed. `KeyManager` additionally catches a raising hasher (corrupted
|
|
255
|
+
record or broken custom hasher) and returns `hash_mismatch`, recording
|
|
256
|
+
the exception class in the audit detail.
|
|
257
|
+
- **Crafted Argon2id stored hashes can no longer force multi-minute KDF
|
|
258
|
+
runs**: the per-parameter sanity bounds (t <= 2^16, m <= 1 GiB) admitted
|
|
259
|
+
combinations like t=1024 x m=256 MiB, measured at ~170 s CPU and 256 MiB
|
|
260
|
+
per verification — a denial-of-service vector for anyone able to write a
|
|
261
|
+
store record, contradicting the 1.1.0 hardening goal. Verification now
|
|
262
|
+
also enforces a total-work bound (t x m <= 2^23 KiB-passes and t <= 4096)
|
|
263
|
+
for stored parameters, while always accepting parameters equal to the
|
|
264
|
+
hasher's own configuration so deliberately heavy deployments keep
|
|
265
|
+
verifying their own keys.
|
|
266
|
+
- **Salt/digest lengths from stored hashes are capped**: both hashers now
|
|
267
|
+
reject stored salts or digests longer than 512 bytes before any allocation
|
|
268
|
+
or KDF work (construction validates the same range for
|
|
269
|
+
`salt_length`/`dklen`/`hash_length`, so self-produced hashes always
|
|
270
|
+
verify). Closes the oversized-base64 allocation vector.
|
|
271
|
+
- **`issue(scopes="read:users")` is rejected**: a bare string was silently
|
|
272
|
+
exploded into single-character scopes (`{'r','e','a',...}`), producing a
|
|
273
|
+
key that granted nothing and failed every scope check. Both
|
|
274
|
+
`issue()`/`rotate()` (granted) and `verify()` (required) now reject
|
|
275
|
+
strings/bytes and non-string, empty, or whitespace-containing scope
|
|
276
|
+
entries with `ValueError`.
|
|
277
|
+
|
|
278
|
+
#### Changed
|
|
279
|
+
|
|
280
|
+
- **`verify()` strips surrounding whitespace before hashing**: the key
|
|
281
|
+
parser already tolerated (and stripped) padding, but the hash was
|
|
282
|
+
computed over the unstripped string, so a padded key failed with
|
|
283
|
+
`hash_mismatch` through the library while the FastAPI integration (which
|
|
284
|
+
strips header values) accepted it. Both layers now behave identically:
|
|
285
|
+
whitespace-padded keys verify.
|
|
286
|
+
- **`verify()` validates `required_scopes`**: malformed required scopes
|
|
287
|
+
(empty/whitespace/non-string) raise `ValueError` — caller error, distinct
|
|
288
|
+
from a bad key — instead of silently 403-ing forever.
|
|
289
|
+
- **CLI `issue` uses the library's default scrypt cost**: the CLI previously
|
|
290
|
+
hashed with a light scrypt profile (n=1024, 16x weaker than the library
|
|
291
|
+
default n=16384), silently reducing the offline-cracking cost of every
|
|
292
|
+
CLI-issued key. Issuing one key performs a single hash, so interactivity
|
|
293
|
+
is unaffected; the cost profile is still printed at issue time. README and
|
|
294
|
+
SECURITY.md updated to match.
|
|
295
|
+
|
|
296
|
+
#### Added
|
|
297
|
+
|
|
298
|
+
- `KeyStore.mark_verified(prefix, at=...)` protocol method (see above);
|
|
299
|
+
both built-in stores implement it atomically.
|
|
300
|
+
- Deterministic regression tests for the verify-vs-revoke/rotate race
|
|
301
|
+
(gated hasher parks a verification between the store read and the touch
|
|
302
|
+
write), multithreaded and true multiprocess SQLite contention storms,
|
|
303
|
+
Hypothesis property tests (round-trip, no-escalation, fail-closed
|
|
304
|
+
fuzzing), and a fixed-seed fuzz corpus.
|
|
305
|
+
- `hypothesis` is now a declared `dev` extra so a fresh CI install works.
|
|
306
|
+
- `tests/test_cli.py::test_issue_uses_default_scrypt_cost` — end-to-end
|
|
307
|
+
regression asserting that CLI-issued keys are persisted with the
|
|
308
|
+
library-default scrypt parameters.
|
|
309
|
+
## [1.1.0] - 2026-11-17
|
|
310
|
+
|
|
311
|
+
Follow-up security and correctness release. Two high-severity logic bugs were
|
|
312
|
+
confirmed by reproduction and fixed with deterministic regression tests,
|
|
313
|
+
alongside hasher-dispatch support, verification write throttling, and a broad
|
|
314
|
+
hardening pass.
|
|
315
|
+
|
|
316
|
+
### Fixed
|
|
317
|
+
|
|
318
|
+
- **Rotation grace no longer bypasses key expiry** (HIGH): the rotated-key
|
|
319
|
+
branch of `verify()` never checked `expires_at`, so a rotated key kept
|
|
320
|
+
authenticating through its grace window even after its TTL had passed.
|
|
321
|
+
Expiry is now a hard cap on grace; a rotated, expired key is rejected with
|
|
322
|
+
reason `expired`.
|
|
323
|
+
- **Concurrent double-rotation is now atomic** (HIGH): `rotate()` performed a
|
|
324
|
+
non-atomic read-check-write, so two concurrent rotations of the same key
|
|
325
|
+
could both succeed and mint two valid successors. Rotation now claims the
|
|
326
|
+
active→rotated transition through the new `KeyStore.mark_rotated()` — a
|
|
327
|
+
single conditional `UPDATE ... WHERE rotated_at IS NULL AND revoked_at IS
|
|
328
|
+
NULL` inside `BEGIN IMMEDIATE` for SQLite (atomic across threads and
|
|
329
|
+
processes) and a lock-guarded check-and-set for the in-memory store. Losers
|
|
330
|
+
of the race get the normal "already rotated" error. This also closes a
|
|
331
|
+
rotate-vs-revoke race. The base `KeyStore` ships a non-atomic default and
|
|
332
|
+
`rotate()` falls back to the 1.0 behavior for duck-typed stores.
|
|
333
|
+
- **scrypt `maxmem` is derived from parameters** instead of being hard-coded
|
|
334
|
+
to 256 MiB: `ScryptHasher(n=2**18, r=8)` (≈268 MiB) previously passed
|
|
335
|
+
construction but failed on every `hash()`. Consistent configurations up to
|
|
336
|
+
a 1 GiB ceiling now work; anything larger is rejected at construction with
|
|
337
|
+
a clear error. An explicit `maxmem=` argument is still honored (and
|
|
338
|
+
validated).
|
|
339
|
+
- **FastAPI `auto_error=False` no longer collapses 403 into 401**: scope
|
|
340
|
+
failures now raise the new `ScopeDeniedError` (a `PermissionError`
|
|
341
|
+
subclass carrying `missing_scopes`), and `register_error_handlers` maps it
|
|
342
|
+
to `403` with the missing scopes listed while authentication failures stay
|
|
343
|
+
`401`. `register_error_handlers` is now exported.
|
|
344
|
+
- `InMemoryStore` returns copies on read and copies on write, so mutating a
|
|
345
|
+
fetched record (or an object after `save()`) can no longer change stored
|
|
346
|
+
state — matching `SQLiteStore` semantics.
|
|
347
|
+
- `list_events(limit=...)` rejects limits < 1 in both stores (previously
|
|
348
|
+
`limit=-1` returned everything on SQLite and a wrong slice in memory).
|
|
349
|
+
- `rotate()` rejects negative grace periods (previously they silently killed
|
|
350
|
+
the old key immediately).
|
|
351
|
+
- `revoke()` rejects timezone-naive `now` values, consistent with `issue()`.
|
|
352
|
+
- `parse_duration()` raises `ValueError` (as documented) instead of
|
|
353
|
+
`OverflowError` for out-of-range values like `"999999999999999w"`.
|
|
354
|
+
- `KeyRecord.__repr__` redacts the stored hash, mirroring `IssuedKey` —
|
|
355
|
+
hashes can no longer leak into logs via repr.
|
|
356
|
+
- `Argon2Hasher` rejects `memory_cost < 8 * parallelism` at construction
|
|
357
|
+
instead of failing on the first `hash()`.
|
|
358
|
+
- Verification rejects stored hashes whose parameters fall outside sane
|
|
359
|
+
bounds (scrypt `n/r/p`, Argon2id `t/m/p`) or whose digest is shorter than
|
|
360
|
+
16 bytes — before running the KDF — so a crafted store record cannot
|
|
361
|
+
force absurd verification cost or exploit truncated digests. `ScryptHasher`
|
|
362
|
+
likewise requires `dklen >= 16` at construction.
|
|
363
|
+
|
|
364
|
+
### Added
|
|
365
|
+
|
|
366
|
+
- **Hasher dispatch by stored algorithm**: `KeyManager(..., hashers={...})`
|
|
367
|
+
registers additional hashers keyed by algorithm name; verification picks
|
|
368
|
+
the hasher recorded with each key, so switching algorithms (e.g. scrypt →
|
|
369
|
+
Argon2id) no longer invalidates existing keys. Keys with an unregistered
|
|
370
|
+
algorithm fail closed with `hash_mismatch`.
|
|
371
|
+
- **Verification write throttling**: `last_verified_at` persistence is
|
|
372
|
+
throttled to once per `verify_touch_interval` (default 60 s; `timedelta(0)`
|
|
373
|
+
restores write-on-every-verify).
|
|
374
|
+
- **Optional verify-time audit**: `audit_verifications=False` skips
|
|
375
|
+
`verified`/`verify_failed` events while lifecycle events (issued/rotated/
|
|
376
|
+
revoked) are always kept.
|
|
377
|
+
- **Audit pruning**: `KeyManager.prune_events(before=...)` plus
|
|
378
|
+
`KeyStore.delete_events_before(cutoff)` in both built-in stores bound
|
|
379
|
+
audit-log growth.
|
|
380
|
+
- **CLI**: `bitting verify` accepts the key via `--stdin` or `-` so it never
|
|
381
|
+
lands in shell history or process listings.
|
|
382
|
+
|
|
383
|
+
### Docs & hygiene
|
|
384
|
+
|
|
385
|
+
- Scope strings are validated at issue/rotate time (non-empty, no
|
|
386
|
+
whitespace); the successor-TTL behavior of `rotate()` is now documented in
|
|
387
|
+
its docstring.
|
|
388
|
+
- README: contributor team named directly (was only linked); rotation table
|
|
389
|
+
and limitations updated for the capped grace window and atomic rotation;
|
|
390
|
+
CLI section documents `--stdin` and the CLI's lighter scrypt cost; test
|
|
391
|
+
count corrected (now 180).
|
|
392
|
+
- CHANGELOG: corrected the 1.0.1 release date (its commits and tag are from
|
|
393
|
+
2026-11-16).
|
|
394
|
+
- `.gitignore` now excludes SQLite databases (`*.db`, `*.sqlite`,
|
|
395
|
+
`*.sqlite3`) so key stores cannot be committed accidentally.
|
|
396
|
+
- The FastAPI example's install hint now includes the `argon2` extra it
|
|
397
|
+
actually uses.
|
|
398
|
+
- CI: workflow runs with `permissions: contents: read` and actions are
|
|
399
|
+
pinned to commit SHAs (supply-chain hardening).
|
|
400
|
+
|
|
401
|
+
## [1.0.1] - 2026-11-16
|
|
402
|
+
|
|
403
|
+
### Fixed
|
|
404
|
+
|
|
405
|
+
- **CI**: the test suite failed under a bare `pytest` invocation (`ModuleNotFoundError: No module named 'tests'`) because the repo root was only importable when running `python -m pytest`. Added `pythonpath = ["."]` to the pytest configuration, so the suite now passes however pytest is invoked. This is what caused the first CI run to fail.
|
|
406
|
+
- **CI**: `pip-audit` and `build` are now installed before the steps that use them.
|
|
407
|
+
- **Key format**: `parse_api_key` now accepts the full range of prefix (8–64) and secret (16–128) component lengths that `generate_api_key` can produce; previously only the default lengths (16/40) parsed, making custom-length keys unverifiable. Regression tests added.
|
|
408
|
+
- **Argon2id**: `Argon2Hasher.verify` now also catches argon2-cffi's own `HashingError` (raised for invalid stored-hash parameters), so verification returns `False` instead of raising.
|
|
409
|
+
- **Docs**: installation instructions for optional extras now use working direct-reference syntax (`pip install 'bitting[fastapi] @ git+...'`) since the package is not yet on PyPI; removed a duplicated example block from the FastAPI integration docstring.
|
|
410
|
+
|
|
411
|
+
## [1.0.0] - 2026-11-16
|
|
412
|
+
|
|
413
|
+
### Added
|
|
414
|
+
|
|
415
|
+
- **Key format**: `btg_<env>_<prefix>_<secret>_<checksum>` keys with rejection-sampled base62 entropy (~95-bit public prefix, ~238-bit secret), environment labels, and a CRC32-based transcription-error checksum.
|
|
416
|
+
- **Hashing**: `Hasher` protocol; `ScryptHasher` (standard library, memory-hard, default ~16 MiB cost) and `Argon2Hasher` (optional `bitting[argon2]` extra). Self-describing encoded hashes with per-hash salts; constant-time verification.
|
|
417
|
+
- **Storage**: `KeyStore` protocol; `InMemoryStore` and `SQLiteStore` (WAL mode, `BEGIN IMMEDIATE` transactions, thread-safe writes, schema-version guard, parent-directory creation).
|
|
418
|
+
- **Lifecycle**: `KeyManager` with `issue`, `verify`, `rotate` (grace windows for zero-downtime rotation), `revoke`, `list_keys`, and injectable clock.
|
|
419
|
+
- **Verification semantics**: `VerifyResult`/`VerifyReason` distinguishing `invalid_format`, `not_found`, `hash_mismatch`, `expired`, `revoked`, `rotated`, `rotated_grace`, and `scope_missing` — enabling correct 401 vs 403 responses.
|
|
420
|
+
- **Scopes**: exact matching plus `read:*` prefix wildcards and the global `*`; precise `missing_scopes` reporting.
|
|
421
|
+
- **Audit**: every lifecycle action emits an `AuditEvent` (persisted by stores, plus an optional synchronous callback); audit persistence and observer failures never break verification.
|
|
422
|
+
- **CLI**: `bitting issue|verify|rotate|revoke|list|events` with `--db`, `--json`, duration TTLs, and meaningful exit codes.
|
|
423
|
+
- **FastAPI integration** (optional `bitting[fastapi]` extra): `APIKeyAuth` dependency builder with `X-API-Key` and `Authorization: Bearer` styles and precise 401/403 semantics.
|
|
424
|
+
- **Documentation**: README with architecture diagram, security model, and deployment notes; SECURITY.md; CONTRIBUTING.md; runnable examples.
|
|
425
|
+
- **Quality**: 117 automated tests (unit + integration), ruff lint/format clean, mypy `--strict` clean, pip-audit clean, wheel/sdist build verified.
|
|
426
|
+
|
|
427
|
+
[1.2.0]: https://github.com/muhammadanasmahmood/bitting/releases/tag/v1.2.0
|
|
428
|
+
[1.1.0]: https://github.com/muhammadanasmahmood/bitting/releases/tag/v1.1.0
|
|
429
|
+
[1.0.1]: https://github.com/muhammadanasmahmood/bitting/releases/tag/v1.0.1
|
|
430
|
+
[1.0.0]: https://github.com/muhammadanasmahmood/bitting/releases/tag/v1.0.0
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# Contributing to bitting
|
|
2
|
+
|
|
3
|
+
Thanks for considering a contribution. This document explains the expectations for changes so the library stays small, correct, and trustworthy.
|
|
4
|
+
|
|
5
|
+
## Ground rules
|
|
6
|
+
|
|
7
|
+
- **Security first.** Anything touching key generation, hashing, verification, or storage must include tests that demonstrate the security property you rely on (tamper detection, constant-time behavior, thread safety, ...).
|
|
8
|
+
- **No new required dependencies.** The zero-dependency core is a feature. Optional functionality belongs behind an extra (`bitting[...]`).
|
|
9
|
+
- **Keep the surface small.** Prefer saying no to features that belong in applications or companion packages. A focused library is more auditable than a framework.
|
|
10
|
+
- **Documentation is part of the feature.** Public APIs need docstrings, and user-visible changes need README updates.
|
|
11
|
+
|
|
12
|
+
## Development setup
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
git clone https://github.com/muhammadanasmahmood/bitting.git
|
|
16
|
+
cd bitting
|
|
17
|
+
python3 -m venv .venv && source .venv/bin/activate
|
|
18
|
+
pip install -e '.[dev,fastapi,argon2]'
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Workflow
|
|
22
|
+
|
|
23
|
+
1. **Discuss first** (for anything beyond a bugfix): open an issue describing the problem and your proposed approach.
|
|
24
|
+
2. **Fork & branch**: `git switch -c my-change`.
|
|
25
|
+
3. **Make the change** with tests. Bug fixes need a regression test that fails without the fix.
|
|
26
|
+
4. **Run the full quality gate locally**:
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pytest # full suite must pass
|
|
30
|
+
ruff check src tests examples
|
|
31
|
+
ruff format --check src tests examples
|
|
32
|
+
mypy # strict; must report no issues
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
CI runs exactly these on every push and pull request for Python 3.10–3.13. A PR that fails any of them will not be merged.
|
|
36
|
+
|
|
37
|
+
5. **Commit** with an imperative subject line (`Add grace-period overflow guard to rotate()`), and a body explaining *why* when the change is not obvious.
|
|
38
|
+
6. **Open a pull request** referencing the issue it resolves.
|
|
39
|
+
|
|
40
|
+
## Commit style
|
|
41
|
+
|
|
42
|
+
- Imperative, capitalized, ≤ 72 characters in the subject: `Add`, `Fix`, `Refactor`, `Document`.
|
|
43
|
+
- One logical change per commit.
|
|
44
|
+
- No secrets, tokens, or credentials in any commit — the repository has push protection enabled and a pre-push scan habit is a good one to keep.
|
|
45
|
+
|
|
46
|
+
## Testing guidelines
|
|
47
|
+
|
|
48
|
+
- Unit tests for pure logic (`keys`, `hashing`, `timeutil`).
|
|
49
|
+
- Integration tests for stateful paths (`storage`, `manager` lifecycle).
|
|
50
|
+
- Use the shared fixtures in `tests/conftest.py` (`fast_hasher`, `clock`, `manager`) — tests must not depend on wall-clock time or run at production hashing cost (one deliberate default-cost test exists in `test_hashing.py`; keep it that way).
|
|
51
|
+
- New stores must cover: save/find round-trip, update, delete, list, concurrency (see `test_storage_sqlite.py` for the checklist).
|
|
52
|
+
|
|
53
|
+
## Reporting security issues
|
|
54
|
+
|
|
55
|
+
Do **not** open a public issue for security problems — see [SECURITY.md](SECURITY.md).
|
|
56
|
+
|
|
57
|
+
## Code of conduct
|
|
58
|
+
|
|
59
|
+
Be precise, be kind, assume competence and good intent. Tough technical critique is welcome; personal remarks are not.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Contributors
|
|
2
|
+
|
|
3
|
+
## Maintainers
|
|
4
|
+
|
|
5
|
+
| Contributor | Role |
|
|
6
|
+
|---|---|
|
|
7
|
+
| [@muhammadanasmahmood](https://github.com/muhammadanasmahmood) | Project Owner & Maintainer — architecture, releases, and repository stewardship |
|
|
8
|
+
|
|
9
|
+
## Contributing
|
|
10
|
+
|
|
11
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for the development workflow. Contributions of any kind — code, tests, documentation, security review, issue triage — are credited here.
|
bitting-1.2.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Muhammad Anas Mahmood
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Ship the full test suite in the sdist. setuptools' default sdist file
|
|
2
|
+
# list includes only tests/test*.py — without this, conftest.py is omitted
|
|
3
|
+
# and `pytest` on an unpacked sdist fails at collection.
|
|
4
|
+
include tests/conftest.py
|
|
5
|
+
|
|
6
|
+
# Operator-relevant documentation beyond the README (README itself and
|
|
7
|
+
# LICENSE are included automatically).
|
|
8
|
+
include CHANGELOG.md
|
|
9
|
+
include SECURITY.md
|
|
10
|
+
include CONTRIBUTING.md
|
|
11
|
+
include CONTRIBUTORS.md
|
|
12
|
+
|
|
13
|
+
# Ship the runnable examples too, so the documented quality gate
|
|
14
|
+
# (ruff check src tests examples) works from an unpacked sdist.
|
|
15
|
+
include examples/*.py
|