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/__init__.py +78 -0
- bitting/__main__.py +10 -0
- bitting/cli.py +266 -0
- bitting/errors.py +41 -0
- bitting/hashing.py +502 -0
- bitting/integrations/__init__.py +5 -0
- bitting/integrations/fastapi.py +256 -0
- bitting/keys.py +228 -0
- bitting/manager.py +783 -0
- bitting/models.py +194 -0
- bitting/py.typed +0 -0
- bitting/storage.py +608 -0
- bitting/timeutil.py +109 -0
- bitting-1.2.0.dist-info/METADATA +309 -0
- bitting-1.2.0.dist-info/RECORD +19 -0
- bitting-1.2.0.dist-info/WHEEL +5 -0
- bitting-1.2.0.dist-info/entry_points.txt +2 -0
- bitting-1.2.0.dist-info/licenses/LICENSE +21 -0
- bitting-1.2.0.dist-info/top_level.txt +1 -0
bitting/timeutil.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Time helpers: aware-UTC clock access and human-friendly duration parsing.
|
|
2
|
+
|
|
3
|
+
The library never uses naive datetimes. All timestamps are timezone-aware
|
|
4
|
+
UTC values, serialized to ISO 8601 in storage.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from datetime import datetime, timedelta, timezone
|
|
11
|
+
|
|
12
|
+
__all__ = ["from_iso", "parse_duration", "to_iso", "utcnow"]
|
|
13
|
+
|
|
14
|
+
_DURATION_RE = re.compile(
|
|
15
|
+
r"^\s*(?P<value>\d+(?:\.\d+)?)\s*(?P<unit>s|sec|secs|second|seconds|"
|
|
16
|
+
r"m|min|mins|minute|minutes|h|hr|hrs|hour|hours|d|day|days|w|week|weeks)\s*$",
|
|
17
|
+
re.IGNORECASE,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
_UNIT_TO_SECONDS: dict[str, float] = {
|
|
21
|
+
"s": 1,
|
|
22
|
+
"sec": 1,
|
|
23
|
+
"secs": 1,
|
|
24
|
+
"second": 1,
|
|
25
|
+
"seconds": 1,
|
|
26
|
+
"m": 60,
|
|
27
|
+
"min": 60,
|
|
28
|
+
"mins": 60,
|
|
29
|
+
"minute": 60,
|
|
30
|
+
"minutes": 60,
|
|
31
|
+
"h": 3600,
|
|
32
|
+
"hr": 3600,
|
|
33
|
+
"hrs": 3600,
|
|
34
|
+
"hour": 3600,
|
|
35
|
+
"hours": 3600,
|
|
36
|
+
"d": 86400,
|
|
37
|
+
"day": 86400,
|
|
38
|
+
"days": 86400,
|
|
39
|
+
"w": 604800,
|
|
40
|
+
"week": 604800,
|
|
41
|
+
"weeks": 604800,
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def utcnow() -> datetime:
|
|
46
|
+
"""Return the current moment as a timezone-aware UTC datetime."""
|
|
47
|
+
return datetime.now(timezone.utc)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def parse_duration(text: str) -> timedelta:
|
|
51
|
+
"""Parse a human-friendly duration string into a :class:`timedelta`.
|
|
52
|
+
|
|
53
|
+
Supported units (case-insensitive): ``s``, ``m``, ``h``, ``d``, ``w``
|
|
54
|
+
and their long forms (``seconds``, ``minutes``, ``hours``, ``days``,
|
|
55
|
+
``weeks``). A bare number is interpreted as seconds.
|
|
56
|
+
|
|
57
|
+
Examples:
|
|
58
|
+
>>> parse_duration("30d")
|
|
59
|
+
datetime.timedelta(days=30)
|
|
60
|
+
>>> parse_duration("12h")
|
|
61
|
+
datetime.timedelta(seconds=43200)
|
|
62
|
+
>>> parse_duration("90")
|
|
63
|
+
datetime.timedelta(seconds=90)
|
|
64
|
+
|
|
65
|
+
Raises:
|
|
66
|
+
ValueError: If the text is not a valid duration.
|
|
67
|
+
"""
|
|
68
|
+
if not isinstance(text, str):
|
|
69
|
+
raise ValueError(f"duration must be a string, got {type(text).__name__}")
|
|
70
|
+
match = _DURATION_RE.match(text)
|
|
71
|
+
if match is None:
|
|
72
|
+
stripped = text.strip()
|
|
73
|
+
if re.fullmatch(r"\d+(?:\.\d+)?", stripped):
|
|
74
|
+
seconds = float(stripped)
|
|
75
|
+
else:
|
|
76
|
+
raise ValueError(f"invalid duration: {text!r}")
|
|
77
|
+
else:
|
|
78
|
+
value = float(match.group("value"))
|
|
79
|
+
unit = match.group("unit").lower()
|
|
80
|
+
seconds = value * _UNIT_TO_SECONDS[unit]
|
|
81
|
+
if seconds < 0:
|
|
82
|
+
raise ValueError(f"duration must be non-negative, got {text!r}")
|
|
83
|
+
try:
|
|
84
|
+
return timedelta(seconds=seconds)
|
|
85
|
+
except OverflowError as exc:
|
|
86
|
+
# Values like "999999999999999w" overflow timedelta; surface the
|
|
87
|
+
# documented ValueError instead of leaking OverflowError.
|
|
88
|
+
raise ValueError(f"duration out of range: {text!r}") from exc
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def to_iso(moment: datetime) -> str:
|
|
92
|
+
"""Serialize a datetime to an ISO 8601 UTC string."""
|
|
93
|
+
return moment.astimezone(timezone.utc).isoformat()
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def from_iso(text: str) -> datetime:
|
|
97
|
+
"""Parse an ISO 8601 string into a timezone-aware UTC datetime.
|
|
98
|
+
|
|
99
|
+
A trailing ``Z`` is normalized to ``+00:00`` explicitly: Python 3.11+
|
|
100
|
+
accepts it natively but 3.10 does not, so a row written by an external
|
|
101
|
+
tool would load on 3.11 and raise StorageError on 3.10. ``to_iso``
|
|
102
|
+
always emits ``+00:00``, so library-written rows are unaffected.
|
|
103
|
+
"""
|
|
104
|
+
if text.endswith(("Z", "z")):
|
|
105
|
+
text = text[:-1] + "+00:00"
|
|
106
|
+
parsed = datetime.fromisoformat(text)
|
|
107
|
+
if parsed.tzinfo is None:
|
|
108
|
+
parsed = parsed.replace(tzinfo=timezone.utc)
|
|
109
|
+
return parsed.astimezone(timezone.utc)
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bitting
|
|
3
|
+
Version: 1.2.0
|
|
4
|
+
Summary: API key lifecycle management for Python: generation, memory-hard hashing, prefix-indexed storage, rotation with grace periods, scopes, TTL, and audit events.
|
|
5
|
+
Author: Muhammad Anas Mahmood
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/muhammadanasmahmood/bitting
|
|
8
|
+
Project-URL: Repository, https://github.com/muhammadanasmahmood/bitting
|
|
9
|
+
Project-URL: Issues, https://github.com/muhammadanasmahmood/bitting/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/muhammadanasmahmood/bitting/blob/main/CHANGELOG.md
|
|
11
|
+
Keywords: api-key,api-keys,authentication,security,hashing,scrypt,argon2,rotation,scopes,fastapi
|
|
12
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Security
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
Provides-Extra: argon2
|
|
27
|
+
Requires-Dist: argon2-cffi>=23.1; extra == "argon2"
|
|
28
|
+
Provides-Extra: fastapi
|
|
29
|
+
Requires-Dist: fastapi>=0.110; extra == "fastapi"
|
|
30
|
+
Provides-Extra: dev
|
|
31
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
32
|
+
Requires-Dist: pytest-cov>=5.0; extra == "dev"
|
|
33
|
+
Requires-Dist: ruff>=0.6; extra == "dev"
|
|
34
|
+
Requires-Dist: mypy>=1.10; extra == "dev"
|
|
35
|
+
Requires-Dist: httpx>=0.27; extra == "dev"
|
|
36
|
+
Requires-Dist: hypothesis>=6.100; extra == "dev"
|
|
37
|
+
Dynamic: license-file
|
|
38
|
+
|
|
39
|
+
# bitting
|
|
40
|
+
|
|
41
|
+
**API key lifecycle management for Python — generation, memory-hard hashing, prefix-indexed storage, rotation with grace periods, scopes, TTL, revocation, audit events, a CLI, and an optional FastAPI integration. Zero required dependencies.**
|
|
42
|
+
|
|
43
|
+
> *Bitting* is the locksmithing term for the unique pattern of cuts that makes one key fit exactly one lock.
|
|
44
|
+
|
|
45
|
+
[](https://github.com/muhammadanasmahmood/bitting/actions/workflows/ci.yml)
|
|
46
|
+
[](https://github.com/muhammadanasmahmood/bitting)
|
|
47
|
+
[](LICENSE)
|
|
48
|
+
[](https://github.com/astral-sh/ruff)
|
|
49
|
+
|
|
50
|
+
---
|
|
51
|
+
|
|
52
|
+
## The problem
|
|
53
|
+
|
|
54
|
+
Almost every service with machine-to-machine access needs API keys, and almost every team hand-rolls the same system — usually badly:
|
|
55
|
+
|
|
56
|
+
- keys stored **in plaintext** in the database (a single SQL dump leaks every credential),
|
|
57
|
+
- verification by **full-table scans** (`SELECT * FROM keys` then compare in Python),
|
|
58
|
+
- fast hashes (SHA-256, or worse, none) that let an attacker with the database test **billions** of key guesses per second on a GPU,
|
|
59
|
+
- **no rotation story**, so keys live forever and get shared between services,
|
|
60
|
+
- no scopes, no expiry, no audit trail.
|
|
61
|
+
|
|
62
|
+
The existing options tend to be either trivial header-checkers that compare against keys sitting in environment variables, or heavyweight vendor platforms that require external services. The middle ground — a focused, self-contained, well-engineered library — is what bitting provides.
|
|
63
|
+
|
|
64
|
+
## What bitting does differently
|
|
65
|
+
|
|
66
|
+
| Concern | Common hand-rolled approach | bitting |
|
|
67
|
+
|---|---|---|
|
|
68
|
+
| Storage | Plaintext key in a column | Only a **memory-hard hash** is stored (scrypt default, Argon2id optional) |
|
|
69
|
+
| Lookup | Full table scan | **Prefix-indexed**: a 16-char public prefix is the lookup key |
|
|
70
|
+
| Format | `uuid4()` — no typo detection, no environment label | `btg_live_<prefix>_<secret>_<checksum>` with a transcription-error checksum |
|
|
71
|
+
| Rotation | None (or "delete and hope") | New key issued; old key keeps working through a **grace window** (capped by the key's original expiry), then is rejected |
|
|
72
|
+
| Scopes | Boolean "is admin" | String scopes with `read:*` wildcards and precise `missing_scopes` reporting |
|
|
73
|
+
| Expiry | Never | TTL or absolute expiry, verified per request |
|
|
74
|
+
| Revocation | DELETE the row (loses history) | `revoked_at` timestamp; history and audit trail retained |
|
|
75
|
+
| Observability | None | Every lifecycle action emits an **audit event** (stored + optional callback) |
|
|
76
|
+
| Failure detail | `401 unauthorized` | `VerifyReason` enum: `invalid_format`, `not_found`, `hash_mismatch`, `expired`, `revoked`, `rotated`, `rotated_grace`, `scope_missing` |
|
|
77
|
+
|
|
78
|
+
### Design decisions worth knowing
|
|
79
|
+
|
|
80
|
+
- **scrypt from the standard library is the default hasher.** No compiled dependencies, yet memory-hard (default cost: 16 MiB per hash). If the database leaks, offline guessing is expensive instead of trivial. Argon2id is available via the optional `argon2` extra (see below).
|
|
81
|
+
- **The prefix is public by design** (the same trade-off as Stripe-style keys): an attacker who steals the store learns *which prefixes exist* but cannot reconstruct any key. Verification cost is one indexed lookup plus one hash — constant as your key count grows. (`last_verified_at` persistence is throttled to once per interval; see Configuration.)
|
|
82
|
+
- **Malformed keys are rejected before touching the store**, so junk traffic cannot be turned into database load.
|
|
83
|
+
- **The checksum is not a security feature.** It catches typos when a human copies a key; it is documented as such and never trusted as an integrity control.
|
|
84
|
+
- **Raw keys exist exactly once** — at issue time. `IssuedKey.__repr__` is redacted so secrets cannot leak into logs by accident.
|
|
85
|
+
|
|
86
|
+
## Installation
|
|
87
|
+
|
|
88
|
+
bitting is not yet on PyPI (publication is on the roadmap). Install directly from GitHub:
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
pip install git+https://github.com/muhammadanasmahmood/bitting.git
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Optional extras, using direct-reference syntax (works with pip 21.3+):
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
pip install 'bitting[fastapi] @ git+https://github.com/muhammadanasmahmood/bitting.git' # FastAPI integration
|
|
98
|
+
pip install 'bitting[argon2] @ git+https://github.com/muhammadanasmahmood/bitting.git' # Argon2id hasher
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Or from a local clone of this repository, where the short forms apply:
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
pip install '.[fastapi]' # FastAPI integration
|
|
105
|
+
pip install '.[argon2]' # Argon2id hasher
|
|
106
|
+
pip install '.[dev]' # pytest, ruff, mypy (for contributors)
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Quick start
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
from datetime import timedelta
|
|
113
|
+
|
|
114
|
+
from bitting import KeyManager, SQLiteStore
|
|
115
|
+
|
|
116
|
+
manager = KeyManager(SQLiteStore("api-keys.db"))
|
|
117
|
+
|
|
118
|
+
# Issue a key (the raw key is shown exactly once — ever)
|
|
119
|
+
issued = manager.issue(
|
|
120
|
+
scopes={"read:users", "write:posts"},
|
|
121
|
+
description="ci-runner",
|
|
122
|
+
ttl=timedelta(days=30),
|
|
123
|
+
)
|
|
124
|
+
print(issued.raw_key) # btg_live_9kQ2VxNmLpR7zT4w_...
|
|
125
|
+
print(issued.prefix) # safe to display and store
|
|
126
|
+
|
|
127
|
+
# Verify on every request
|
|
128
|
+
result = manager.verify(raw_key, required_scopes={"read:users"})
|
|
129
|
+
if result.ok:
|
|
130
|
+
...
|
|
131
|
+
elif result.reason.value == "scope_missing":
|
|
132
|
+
... # 403, with result.missing_scopes
|
|
133
|
+
else:
|
|
134
|
+
... # 401
|
|
135
|
+
|
|
136
|
+
# Rotate without downtime: old key works for 24h, then dies
|
|
137
|
+
new = manager.rotate(issued.prefix, grace=timedelta(hours=24))
|
|
138
|
+
|
|
139
|
+
# Revoke immediately
|
|
140
|
+
manager.revoke(new.prefix)
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## Architecture
|
|
144
|
+
|
|
145
|
+
```
|
|
146
|
+
┌────────────────────────────────────────────────────────────────┐
|
|
147
|
+
│ Your application │
|
|
148
|
+
│ (FastAPI dependency · CLI · plain library calls) │
|
|
149
|
+
└───────────────┬────────────────────────────────────────────────┘
|
|
150
|
+
│
|
|
151
|
+
┌───────▼────────┐ issue / verify / rotate / revoke
|
|
152
|
+
│ KeyManager │──────────────┐
|
|
153
|
+
└───┬───────┬────┘ │ audit events
|
|
154
|
+
keys.py │ │ hashing.py ▼
|
|
155
|
+
(generate, │ │ (scrypt / ┌─────────────┐
|
|
156
|
+
parse, │ │ Argon2id) │ AuditEvent │──▶ optional callback
|
|
157
|
+
checksum) │ └──────────────└─────────────┘
|
|
158
|
+
▼
|
|
159
|
+
┌──────────────┐ KeyStore protocol
|
|
160
|
+
│ KeyStore │◀──── InMemoryStore (tests, prototypes)
|
|
161
|
+
│ (SQLite WAL) │◀──── SQLiteStore (durable, thread-safe)
|
|
162
|
+
└──────────────┘◀──── your adapter (Postgres, Redis, ...)
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
Layers and responsibilities:
|
|
166
|
+
|
|
167
|
+
- **`keys.py`** — key format: generation with rejection-sampled base62 entropy, parsing, and the CRC32-based transcription checksum.
|
|
168
|
+
- **`hashing.py`** — the `Hasher` protocol, `ScryptHasher` (stdlib, default), `Argon2Hasher` (optional). Self-describing encoded hashes (`$scrypt$n=16384$r=8$p=1$…`) mean parameters can be tuned per deployment without invalidating existing keys: parameters matching the active configuration are always accepted, and stored work is bounded to 4× the active profile's work (with the documented default profile as the floor) — keys issued at the default cost keep verifying on any cheaper deployment, while a drastic downgrade beyond 4× of the active profile retires old heavier keys.
|
|
169
|
+
- **`storage.py`** — the `KeyStore` protocol plus `InMemoryStore` and `SQLiteStore` (WAL mode, `BEGIN IMMEDIATE` transactions, a process-wide lock for thread safety, and a schema-version guard).
|
|
170
|
+
- **`manager.py`** — the lifecycle orchestrator: issue, verify (with the full reason state machine), rotate with grace, revoke, and audit dispatch.
|
|
171
|
+
- **`models.py`** — `KeyRecord`, `IssuedKey` (redacted repr), `VerifyResult`/`VerifyReason`, `AuditEvent`.
|
|
172
|
+
- **`integrations/fastapi.py`** — optional dependency builder with precise 401/403 semantics.
|
|
173
|
+
|
|
174
|
+
## Technology stack
|
|
175
|
+
|
|
176
|
+
- **Python 3.10+**, standard library only for the core (`secrets`, `hashlib.scrypt`, `sqlite3`, `argparse`, `dataclasses`).
|
|
177
|
+
- **Optional**: `argon2-cffi` (Argon2id), `fastapi` (integration).
|
|
178
|
+
- **Toolchain**: pytest, ruff (lint + format), mypy `--strict`, pip-audit, GitHub Actions CI.
|
|
179
|
+
|
|
180
|
+
## Configuration
|
|
181
|
+
|
|
182
|
+
```python
|
|
183
|
+
KeyManager(
|
|
184
|
+
store=SQLiteStore("api-keys.db"), # or InMemoryStore(), or your own
|
|
185
|
+
hasher=ScryptHasher(n=2**14), # default; raise for more resistance
|
|
186
|
+
env="live", # label embedded in keys ("test", ...)
|
|
187
|
+
now_fn=my_clock, # injectable clock (testing)
|
|
188
|
+
on_event=send_to_audit_log, # synchronous callback per action
|
|
189
|
+
hashers={"argon2id": Argon2Hasher()}, # verify keys hashed with other algorithms
|
|
190
|
+
verify_touch_interval=timedelta(seconds=60), # throttle last_verified_at writes
|
|
191
|
+
audit_verifications=True, # set False to skip verify-time audit events
|
|
192
|
+
)
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
**Switching hashers.** Verification dispatches on the algorithm stored with each key (scrypt/Argon2id hashes are self-describing), so tuning cost parameters never invalidates existing keys. When you switch *algorithms* — e.g. scrypt → Argon2id — pass the old hasher in `hashers={...}` and existing keys keep verifying while new keys are hashed with the primary hasher. Keys whose algorithm has no registered hasher fail closed with `hash_mismatch`.
|
|
196
|
+
|
|
197
|
+
**Verification write load.** Successful verifications update `last_verified_at` in the returned record, but persist it at most once per `verify_touch_interval` (default 60 s; `timedelta(0)` restores write-on-every-verify). The persisted touch is a single-field update (`KeyStore.mark_verified`) and never rewrites lifecycle columns, so it cannot race with a concurrent revoke or rotate. Verify-time audit events (`verified` / `verify_failed`) can be disabled with `audit_verifications=False`; lifecycle events (issued/rotated/revoked) are always recorded. Audit history can be bounded with `manager.prune_events(before=...)`.
|
|
198
|
+
|
|
199
|
+
Tuning hash cost: the default scrypt parameters (n=2^14, r=8, p=1 ≈ 16 MiB) verify in roughly 50–100 ms on typical server hardware. That is the right ballpark for human-issued keys; it makes online brute-force through your API impractical and offline attacks on a stolen database expensive. If you issue thousands of keys per second in batch tooling, lower the cost deliberately — and document that you did. The scrypt memory limit is derived from your parameters (any consistent configuration up to 1 GiB works — except `r=1` with `n ≥ 2^16`, which OpenSSL rejects at hash time regardless of `maxmem`, so construction fails fast with a clear error; beyond the ceiling, construction is likewise refused).
|
|
200
|
+
|
|
201
|
+
## CLI
|
|
202
|
+
|
|
203
|
+
```console
|
|
204
|
+
$ bitting --db api-keys.db issue --scopes "read:users,write:posts" --ttl 30d
|
|
205
|
+
raw_key: btg_live_9kQ2VxNmLpR7zT4w_8fJk2LmNpQrStUvWxYz3Aa5Bb7CcDdEe9fGh_5K3m
|
|
206
|
+
key_id: 6a1f...
|
|
207
|
+
prefix: 9kQ2VxNmLpR7zT4w
|
|
208
|
+
scopes: read:users,write:posts
|
|
209
|
+
expires_at: 2026-12-16T17:49:27+00:00
|
|
210
|
+
note: Store the raw key now; it cannot be recovered later.
|
|
211
|
+
|
|
212
|
+
$ echo "$KEY" | bitting --db api-keys.db verify --stdin --require-scope read:users
|
|
213
|
+
status: VALID
|
|
214
|
+
|
|
215
|
+
$ bitting --db api-keys.db rotate 9kQ2VxNmLpR7zT4w --grace 24h
|
|
216
|
+
$ bitting --db api-keys.db revoke 9kQ2VxNmLpR7zT4w
|
|
217
|
+
$ bitting --db api-keys.db list
|
|
218
|
+
$ bitting --db api-keys.db events
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
All commands support `--json` for scripting. Exit codes: `0` success, `1` operational failure, `2` usage error. `verify` accepts the key as an argument, as `-`, or via `--stdin` (recommended — it keeps the key out of shell history and process listings). The CLI hashes at the library's default scrypt cost (`n=2^14`), so CLI-issued keys have the same offline-guessing resistance as library-issued ones; the cost profile is printed at issue time, and verification cost is always governed by the parameters stored with each key.
|
|
222
|
+
|
|
223
|
+
## FastAPI integration
|
|
224
|
+
|
|
225
|
+
```python
|
|
226
|
+
from fastapi import Depends, FastAPI
|
|
227
|
+
|
|
228
|
+
from bitting import KeyManager, SQLiteStore
|
|
229
|
+
from bitting.integrations.fastapi import APIKeyAuth
|
|
230
|
+
from bitting.models import KeyRecord
|
|
231
|
+
|
|
232
|
+
app = FastAPI()
|
|
233
|
+
auth = APIKeyAuth(KeyManager(SQLiteStore("api-keys.db")))
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
@app.get("/users", dependencies=[Depends(auth.require(scopes={"read:users"}))])
|
|
237
|
+
async def list_users():
|
|
238
|
+
return {"users": ["alice", "bob"]}
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
@app.get("/me")
|
|
242
|
+
async def me(record: KeyRecord = Depends(auth.require())):
|
|
243
|
+
return {"prefix": record.prefix, "scopes": sorted(record.scopes)}
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
Authentication failures return `401` (with `WWW-Authenticate: ApiKey`); missing scopes return `403` naming the missing scopes. Both `X-API-Key: <key>` and `Authorization: Bearer <key>` styles are supported. Key issuance is deliberately **not** exposed as an HTTP route — minting keys belongs to trusted operator tooling, not to request handlers.
|
|
247
|
+
|
|
248
|
+
## Testing
|
|
249
|
+
|
|
250
|
+
```bash
|
|
251
|
+
pip install -e '.[dev,fastapi,argon2]'
|
|
252
|
+
pytest # 396 tests
|
|
253
|
+
ruff check src tests examples
|
|
254
|
+
ruff format --check src tests examples
|
|
255
|
+
mypy # strict mode
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
The suite covers: key format and checksum properties (including single-character tamper detection), both hashers (including one test at full production scrypt cost and one above the old 256 MiB memory cap), parameter-bound hardening against crafted stored hashes, both stores (including persistence, WAL mode, 40 concurrent saves across 8 threads, record isolation, and atomic rotation claims), the full manager lifecycle state machine (including the expiry-capped grace window and deterministic concurrent-rotation races), the audit trail (including throttling controls and pruning), the CLI (issue → verify → rotate → revoke → list → events, JSON output, and stdin key input), and the FastAPI integration (401/403 semantics in both auto_error modes, bearer mode, record injection).
|
|
259
|
+
|
|
260
|
+
## Deployment
|
|
261
|
+
|
|
262
|
+
- **Single process**: `SQLiteStore` is the intended default — WAL mode, thread-safe, zero infrastructure.
|
|
263
|
+
- **Multiple processes on one host**: point every process at the same SQLite file; SQLite's file locking coordinates writers. Put the database on local disk (not NFS), and expect write serialization — fine for key operations, which are rare compared to verifications. Cache verification results if request volume is high.
|
|
264
|
+
- **Distributed**: implement the five-method `KeyStore` protocol against your database of choice (Postgres is a natural fit — a prefix-indexed table with the same columns). The protocol is deliberately small so adapters stay thin.
|
|
265
|
+
- **Key rotation drill**: rotate on a schedule, keep the grace window shorter than your monitoring window for "old key still in use" alerts, and treat `rotated_grace` verifications as a signal to chase lingering clients.
|
|
266
|
+
|
|
267
|
+
## Security considerations
|
|
268
|
+
|
|
269
|
+
- **Threat model**: bitting protects keys *at rest* (memory-hard hashes, no plaintext anywhere after issue) and *in verification* (constant-time digest comparison, prefix-indexed lookups, parse-before-lookup). It does not protect a compromised application process — an attacker inside your process can hijack verification regardless of storage format.
|
|
270
|
+
- **Stored-hash parameters are bounds-checked and work-budgeted.** A crafted store record (requires write access to the database, which is outside bitting's threat model) can only select in-bounds parameters: memory is hard-capped by the hasher's configured `maxmem`, scrypt *CPU* per verification is bounded by a total-work budget (`n×r×p` ≤ 4× the active profile, default profile as the floor), and Argon2id carries a total-work cap (`t×m ≤ 2²³`, ~60× — a tighter argon2 budget is a deployment decision). Parameters matching the hasher's own configuration are always accepted.
|
|
271
|
+
- **Store the raw key where you store passwords**: a secrets manager at issue time. It cannot be recovered from bitting.
|
|
272
|
+
- **Transit is your responsibility**: keys must only travel over TLS.
|
|
273
|
+
- **The checksum catches typos, not attackers.** A tampered secret with a recomputed checksum parses fine — and is then rejected by hash verification.
|
|
274
|
+
- **Environment labels (`live`, `test`) are not a security boundary** — they are an operational aid. A `btg_test_...` key verifies if its prefix is in the store; use separate stores for separate environments.
|
|
275
|
+
- See [SECURITY.md](SECURITY.md) for how to report vulnerabilities.
|
|
276
|
+
|
|
277
|
+
## Roadmap
|
|
278
|
+
|
|
279
|
+
- [ ] Async store variants (`AsyncKeyStore`) for fully-async verification paths
|
|
280
|
+
- [ ] Optional pepper support in both hashers
|
|
281
|
+
- [ ] SQLAlchemy/PostgreSQL adapter in a companion package
|
|
282
|
+
- [ ] Verification-result caching helper (TTL-bounded, with revocation hooks)
|
|
283
|
+
- [ ] PyPI publication
|
|
284
|
+
|
|
285
|
+
## Limitations
|
|
286
|
+
|
|
287
|
+
- The core API is synchronous. (FastAPI runs sync dependencies in a thread pool, so the integration works fine; a native async path is on the roadmap.)
|
|
288
|
+
- `SQLiteStore` serializes writes in-process by design; very high write concurrency needs a database server behind a custom `KeyStore`.
|
|
289
|
+
- No built-in rate limiting of verification attempts — pair with your normal API rate limiting (the memory-hard default cost already makes online guessing expensive).
|
|
290
|
+
- Key records hold one hash; concurrent rotation of the same key from two threads or processes is safe with the built-in stores (the active→rotated transition is an atomic conditional update — `KeyStore.mark_rotated`). Custom stores should implement `mark_rotated` atomically to keep that guarantee; the base-class fallback is non-atomic.
|
|
291
|
+
- Revocation is equally atomic and idempotent (`KeyStore.mark_revoked`): concurrent revoke-vs-rotate cannot erase lifecycle state, and revoking twice keeps the first (authoritative) `revoked_at` while logging the repeat. Custom stores should implement `mark_revoked` the same targeted way.
|
|
292
|
+
- **Custom stores must implement `mark_verified` (and `mark_rotated` / `mark_revoked`) as targeted, atomic updates.** The built-in stores do; the *fallback* used when a store lacks them is a non-atomic read-modify-write, and under a concurrent lifecycle change it can lose a revocation — **a revoked key can then verify again** until the next lifecycle write. Stores that only implement the original five-method protocol are supported for compatibility, not for production use.
|
|
293
|
+
- `list_keys()` loads every record: ~0.09 ms per key (~11 s and ~0.4 GB of process memory at one million keys on the benchmark hardware). For large stores, prefer `find_by_prefix` lookups in tooling.
|
|
294
|
+
|
|
295
|
+
## Contributing
|
|
296
|
+
|
|
297
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md). Every PR must keep `pytest`, `ruff`, and `mypy --strict` green.
|
|
298
|
+
|
|
299
|
+
## Contributors
|
|
300
|
+
|
|
301
|
+
- **[Muhammad Anas Mahmood](https://github.com/muhammadanasmahmood)** — Project Owner & Maintainer · architecture, releases, and repository stewardship
|
|
302
|
+
|
|
303
|
+
See [CONTRIBUTORS.md](CONTRIBUTORS.md) for roles and how contributions are credited.
|
|
304
|
+
|
|
305
|
+
## License
|
|
306
|
+
|
|
307
|
+
[MIT](LICENSE) © Muhammad Anas Mahmood
|
|
308
|
+
|
|
309
|
+
- **Bound what you store in metadata and how many scopes you grant.** `issue()` accepts any JSON-serializable metadata and any number of valid scopes; a 10 MB metadata blob or a 100k-scope key is accepted today and stored whole, and `verify()` cost grows with the product of granted×required scopes (`missing_scopes` is O(granted × required) — 100k×100 ≈ 1 s). Cap sizes and counts at the application layer before they reach the library.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
bitting/__init__.py,sha256=sE_U8dr_vjSu9dUlnBF6SC8eTEjKpUX9oauKpH1wX7U,1833
|
|
2
|
+
bitting/__main__.py,sha256=u2mo7O9JWqROB-KDRnMUdsFRXbslBBBI6szKKFAeg8E,173
|
|
3
|
+
bitting/cli.py,sha256=Vl-o-sV21QWKfUrk9DLw3fMjnlHWUmFeUTHZySc_Ezo,10031
|
|
4
|
+
bitting/errors.py,sha256=Qxq_cysN9jmA2dY-KdfnImKKXXSUuX0OcyupOApCADY,977
|
|
5
|
+
bitting/hashing.py,sha256=D7aHUfZBguA3FwrNiOHoawfZKlTUPjhARBC7ClpYrh0,21297
|
|
6
|
+
bitting/keys.py,sha256=WLrbEj0ULwDEj14FztCaLnFX4daocHgOZakH8cOKAzM,7585
|
|
7
|
+
bitting/manager.py,sha256=YfrpLupz5nxpl2u0Wlwux_ffcIKhapBygSEOBU0bYgI,33214
|
|
8
|
+
bitting/models.py,sha256=loe5G_DS1s4739SzXHqdrkCjQcxx3Q_IPr0-yHLQRF0,5900
|
|
9
|
+
bitting/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
10
|
+
bitting/storage.py,sha256=m6_OzCQjTBBt1fXsI1njUJA6p2kT45A2aTVG14kDzDM,25358
|
|
11
|
+
bitting/timeutil.py,sha256=cB-Y0rexkFW36ezfv_pJ_U-ovzuTmmhevXyx8BVKIF0,3434
|
|
12
|
+
bitting/integrations/__init__.py,sha256=mp_eWMNN6307vfUr90F_uaTe858Mf_5Ch0yOo0QDJgY,101
|
|
13
|
+
bitting/integrations/fastapi.py,sha256=fFVQTPTuEhdAEGTrNjLaZ_bH8ZiSNLY-F4WumyhY4Ao,10349
|
|
14
|
+
bitting-1.2.0.dist-info/licenses/LICENSE,sha256=w3jaXrc4uFKZkrbEboJTGUds_r9cwRiXI7ZOQ-Xf_cc,1078
|
|
15
|
+
bitting-1.2.0.dist-info/METADATA,sha256=aKZacmWS9s1bdnHNOeVVhogS9O6w9l0J5Lyg_N7Xrkk,21502
|
|
16
|
+
bitting-1.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
17
|
+
bitting-1.2.0.dist-info/entry_points.txt,sha256=gA0PgGgouie5-3SSq-rDVoaUfsGt5l__Axd-_Vav4I0,45
|
|
18
|
+
bitting-1.2.0.dist-info/top_level.txt,sha256=kLqICagDGKqbxPZEYWW2XDH-5fpt12iNb160Q-VgG3U,8
|
|
19
|
+
bitting-1.2.0.dist-info/RECORD,,
|
|
@@ -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 @@
|
|
|
1
|
+
bitting
|