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/__init__.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""bitting — API key lifecycle management for Python.
|
|
2
|
+
|
|
3
|
+
Generation, memory-hard hashing (scrypt / Argon2id), prefix-indexed
|
|
4
|
+
storage, rotation with grace periods, scopes with wildcards, TTL,
|
|
5
|
+
revocation, audit events, a CLI, and an optional FastAPI integration.
|
|
6
|
+
|
|
7
|
+
Quick start::
|
|
8
|
+
|
|
9
|
+
from bitting import InMemoryStore, KeyManager
|
|
10
|
+
|
|
11
|
+
manager = KeyManager(InMemoryStore())
|
|
12
|
+
issued = manager.issue(scopes={"read:users"}, description="ci-runner")
|
|
13
|
+
print(issued.raw_key) # shown exactly once
|
|
14
|
+
|
|
15
|
+
result = manager.verify(issued.raw_key, required_scopes={"read:users"})
|
|
16
|
+
assert result.ok
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from .errors import (
|
|
22
|
+
BittingError,
|
|
23
|
+
ConfigurationError,
|
|
24
|
+
DuplicateKeyError,
|
|
25
|
+
KeyFormatError,
|
|
26
|
+
KeyNotFoundError,
|
|
27
|
+
StorageError,
|
|
28
|
+
)
|
|
29
|
+
from .hashing import Argon2Hasher, Hasher, ScryptHasher
|
|
30
|
+
from .keys import generate_api_key, parse_api_key
|
|
31
|
+
from .manager import (
|
|
32
|
+
DEFAULT_ROTATION_GRACE,
|
|
33
|
+
KeyManager,
|
|
34
|
+
missing_scopes,
|
|
35
|
+
scope_matches,
|
|
36
|
+
validate_scopes,
|
|
37
|
+
)
|
|
38
|
+
from .models import (
|
|
39
|
+
AuditEvent,
|
|
40
|
+
AuditEventKind,
|
|
41
|
+
IssuedKey,
|
|
42
|
+
KeyRecord,
|
|
43
|
+
VerifyReason,
|
|
44
|
+
VerifyResult,
|
|
45
|
+
)
|
|
46
|
+
from .storage import InMemoryStore, KeyStore, SQLiteStore
|
|
47
|
+
from .timeutil import parse_duration
|
|
48
|
+
|
|
49
|
+
__version__ = "1.2.0"
|
|
50
|
+
|
|
51
|
+
__all__ = [
|
|
52
|
+
"DEFAULT_ROTATION_GRACE",
|
|
53
|
+
"Argon2Hasher",
|
|
54
|
+
"AuditEvent",
|
|
55
|
+
"AuditEventKind",
|
|
56
|
+
"BittingError",
|
|
57
|
+
"ConfigurationError",
|
|
58
|
+
"DuplicateKeyError",
|
|
59
|
+
"Hasher",
|
|
60
|
+
"InMemoryStore",
|
|
61
|
+
"IssuedKey",
|
|
62
|
+
"KeyFormatError",
|
|
63
|
+
"KeyManager",
|
|
64
|
+
"KeyNotFoundError",
|
|
65
|
+
"KeyRecord",
|
|
66
|
+
"KeyStore",
|
|
67
|
+
"SQLiteStore",
|
|
68
|
+
"ScryptHasher",
|
|
69
|
+
"StorageError",
|
|
70
|
+
"VerifyReason",
|
|
71
|
+
"VerifyResult",
|
|
72
|
+
"generate_api_key",
|
|
73
|
+
"missing_scopes",
|
|
74
|
+
"parse_api_key",
|
|
75
|
+
"parse_duration",
|
|
76
|
+
"scope_matches",
|
|
77
|
+
"validate_scopes",
|
|
78
|
+
]
|
bitting/__main__.py
ADDED
bitting/cli.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""Command-line interface: issue, verify, rotate, revoke, and list keys.
|
|
2
|
+
|
|
3
|
+
Every command accepts ``--db`` (a SQLite path, default ``bitting.db``)
|
|
4
|
+
and ``--json`` for machine-readable output. ``verify`` accepts the key
|
|
5
|
+
as an argument, as ``-``, or via ``--stdin`` (recommended, so the key
|
|
6
|
+
never lands in shell history or process listings). Exit codes: 0 on
|
|
7
|
+
success, 1 on operational failure (not found, bad key, ...), 2 on
|
|
8
|
+
usage errors.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import json
|
|
15
|
+
import sys
|
|
16
|
+
from datetime import timedelta
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from .errors import BittingError
|
|
20
|
+
from .hashing import ScryptHasher
|
|
21
|
+
from .manager import KeyManager
|
|
22
|
+
from .models import KeyRecord
|
|
23
|
+
from .storage import SQLiteStore
|
|
24
|
+
from .timeutil import parse_duration
|
|
25
|
+
|
|
26
|
+
__all__ = ["build_parser", "main"]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
30
|
+
parser = argparse.ArgumentParser(
|
|
31
|
+
prog="bitting",
|
|
32
|
+
description="API key lifecycle management: issue, verify, rotate, revoke, list.",
|
|
33
|
+
)
|
|
34
|
+
parser.add_argument(
|
|
35
|
+
"--db", default="bitting.db", help="SQLite database path (default: bitting.db)"
|
|
36
|
+
)
|
|
37
|
+
parser.add_argument(
|
|
38
|
+
"--json", action="store_true", dest="as_json", help="Emit machine-readable JSON"
|
|
39
|
+
)
|
|
40
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
41
|
+
|
|
42
|
+
# README documents "--json on every command". argparse does not
|
|
43
|
+
# inherit top-level optionals, so `bitting issue --json` used to exit 2.
|
|
44
|
+
# Register it on each subparser too; SUPPRESS keeps an absent flag from
|
|
45
|
+
# overwriting a --json given before the subcommand.
|
|
46
|
+
def _add_json_flag(p: argparse.ArgumentParser) -> None:
|
|
47
|
+
p.add_argument(
|
|
48
|
+
"--json",
|
|
49
|
+
action="store_true",
|
|
50
|
+
dest="as_json",
|
|
51
|
+
default=argparse.SUPPRESS,
|
|
52
|
+
help="Emit machine-readable JSON (also accepted before the command)",
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
p_issue = sub.add_parser("issue", help="Issue a new API key")
|
|
56
|
+
p_issue.add_argument(
|
|
57
|
+
"--scopes", default="", help="Comma-separated scopes, e.g. read:users,write:posts"
|
|
58
|
+
)
|
|
59
|
+
p_issue.add_argument("--description", default="", help="Free-form description")
|
|
60
|
+
p_issue.add_argument("--ttl", default=None, help="Lifetime, e.g. 30d, 12h, 90 (seconds)")
|
|
61
|
+
p_issue.add_argument("--env", default="live", help="Environment label (default: live)")
|
|
62
|
+
|
|
63
|
+
p_verify = sub.add_parser("verify", help="Verify a raw API key")
|
|
64
|
+
p_verify.add_argument(
|
|
65
|
+
"key",
|
|
66
|
+
nargs="?",
|
|
67
|
+
default=None,
|
|
68
|
+
help="The raw API key string, or '-' to read it from stdin",
|
|
69
|
+
)
|
|
70
|
+
p_verify.add_argument(
|
|
71
|
+
"--stdin",
|
|
72
|
+
action="store_true",
|
|
73
|
+
help="Read the raw key from stdin (avoids the key landing in shell "
|
|
74
|
+
"history or process listings)",
|
|
75
|
+
)
|
|
76
|
+
p_verify.add_argument(
|
|
77
|
+
"--require-scope",
|
|
78
|
+
action="append",
|
|
79
|
+
default=[],
|
|
80
|
+
dest="required_scopes",
|
|
81
|
+
help="Scope the key must have (repeatable)",
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
p_rotate = sub.add_parser(
|
|
85
|
+
"rotate", help="Rotate a key by prefix (old key stays valid during grace)"
|
|
86
|
+
)
|
|
87
|
+
p_rotate.add_argument("prefix", help="Prefix of the key to rotate")
|
|
88
|
+
p_rotate.add_argument(
|
|
89
|
+
"--grace", default="24h", help="Grace period for the old key (default: 24h)"
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
p_revoke = sub.add_parser("revoke", help="Revoke a key by prefix (immediate)")
|
|
93
|
+
p_revoke.add_argument("prefix", help="Prefix of the key to revoke")
|
|
94
|
+
|
|
95
|
+
p_list = sub.add_parser("list", help="List stored keys (prefixes and metadata, never secrets)")
|
|
96
|
+
p_events = sub.add_parser("events", help="Show recent audit events")
|
|
97
|
+
p_events.add_argument("--limit", type=int, default=20)
|
|
98
|
+
|
|
99
|
+
for subparser in (p_issue, p_verify, p_rotate, p_revoke, p_list, p_events):
|
|
100
|
+
_add_json_flag(subparser)
|
|
101
|
+
|
|
102
|
+
return parser
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _scopes(text: str) -> list[str]:
|
|
106
|
+
return [s.strip() for s in text.split(",") if s.strip()]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _print(payload: dict[str, Any], as_json: bool) -> None:
|
|
110
|
+
if as_json:
|
|
111
|
+
print(json.dumps(payload, indent=2))
|
|
112
|
+
else:
|
|
113
|
+
for key, value in payload.items():
|
|
114
|
+
print(f"{key:>15}: {value}")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def main(argv: list[str] | None = None) -> int:
|
|
118
|
+
args = build_parser().parse_args(argv)
|
|
119
|
+
try:
|
|
120
|
+
store = SQLiteStore(args.db)
|
|
121
|
+
except BittingError as exc:
|
|
122
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
123
|
+
return 1
|
|
124
|
+
except OSError as exc:
|
|
125
|
+
# Filesystem problems (parent path is a file, permission denied,
|
|
126
|
+
# unreadable directory, ...) must exit cleanly, not traceback.
|
|
127
|
+
print(f"error: cannot open database {args.db!r}: {exc}", file=sys.stderr)
|
|
128
|
+
return 1
|
|
129
|
+
|
|
130
|
+
# The CLI hashes at the library's default scrypt cost (n=2^14, ~16 MiB).
|
|
131
|
+
# Issuing a key performs a single hash, so interactive use stays
|
|
132
|
+
# snappy, and CLI-issued keys get the same offline-guessing resistance
|
|
133
|
+
# as library-issued ones. Verification cost is governed by the
|
|
134
|
+
# parameters stored with each key, not by this profile.
|
|
135
|
+
hasher = ScryptHasher()
|
|
136
|
+
manager = KeyManager(store, hasher=hasher, env=getattr(args, "env", "live"))
|
|
137
|
+
|
|
138
|
+
try:
|
|
139
|
+
if args.command == "issue":
|
|
140
|
+
ttl: timedelta | None = None
|
|
141
|
+
if args.ttl is not None:
|
|
142
|
+
ttl = parse_duration(args.ttl)
|
|
143
|
+
issued = manager.issue(
|
|
144
|
+
scopes=_scopes(args.scopes),
|
|
145
|
+
description=args.description,
|
|
146
|
+
ttl=ttl,
|
|
147
|
+
)
|
|
148
|
+
_print(
|
|
149
|
+
{
|
|
150
|
+
"raw_key": issued.raw_key,
|
|
151
|
+
"key_id": issued.key_id,
|
|
152
|
+
"prefix": issued.prefix,
|
|
153
|
+
"scopes": ",".join(sorted(issued.record.scopes)) or "(none)",
|
|
154
|
+
"expires_at": issued.record.expires_at.isoformat()
|
|
155
|
+
if issued.record.expires_at
|
|
156
|
+
else "never",
|
|
157
|
+
"hash": (
|
|
158
|
+
f"scrypt n={hasher.n} r={hasher.r} p={hasher.p} "
|
|
159
|
+
"(library default cost; see 'Tuning hash cost' in the README)"
|
|
160
|
+
),
|
|
161
|
+
"note": "Store the raw key now; it cannot be recovered later.",
|
|
162
|
+
},
|
|
163
|
+
args.as_json,
|
|
164
|
+
)
|
|
165
|
+
return 0
|
|
166
|
+
|
|
167
|
+
if args.command == "verify":
|
|
168
|
+
raw_key = args.key
|
|
169
|
+
if args.stdin or raw_key == "-":
|
|
170
|
+
raw_key = sys.stdin.read().strip()
|
|
171
|
+
if not raw_key:
|
|
172
|
+
print(
|
|
173
|
+
"error: no key provided (pass it as an argument or via --stdin)",
|
|
174
|
+
file=sys.stderr,
|
|
175
|
+
)
|
|
176
|
+
return 2
|
|
177
|
+
result = manager.verify(raw_key, required_scopes=args.required_scopes)
|
|
178
|
+
payload = {
|
|
179
|
+
"ok": result.ok,
|
|
180
|
+
"reason": result.reason.value,
|
|
181
|
+
"key_id": result.record.key_id if result.record else None,
|
|
182
|
+
"prefix": result.record.prefix if result.record else None,
|
|
183
|
+
}
|
|
184
|
+
if result.missing_scopes:
|
|
185
|
+
payload["missing_scopes"] = ",".join(sorted(result.missing_scopes))
|
|
186
|
+
if not args.as_json:
|
|
187
|
+
status = "VALID" if result.ok else f"INVALID ({result.reason.value})"
|
|
188
|
+
payload = {"status": status, **{k: v for k, v in payload.items() if k != "ok"}}
|
|
189
|
+
_print(payload, args.as_json)
|
|
190
|
+
return 0 if result.ok else 1
|
|
191
|
+
|
|
192
|
+
if args.command == "rotate":
|
|
193
|
+
issued = manager.rotate(args.prefix, grace=parse_duration(args.grace))
|
|
194
|
+
_print(
|
|
195
|
+
{
|
|
196
|
+
"raw_key": issued.raw_key,
|
|
197
|
+
"new_prefix": issued.prefix,
|
|
198
|
+
"rotated_prefix": args.prefix,
|
|
199
|
+
"key_id": issued.key_id,
|
|
200
|
+
"note": "The old key keeps working until the grace window closes.",
|
|
201
|
+
},
|
|
202
|
+
args.as_json,
|
|
203
|
+
)
|
|
204
|
+
return 0
|
|
205
|
+
|
|
206
|
+
if args.command == "revoke":
|
|
207
|
+
record = manager.revoke(args.prefix)
|
|
208
|
+
_print(
|
|
209
|
+
{
|
|
210
|
+
"revoked_prefix": record.prefix,
|
|
211
|
+
"key_id": record.key_id,
|
|
212
|
+
"revoked_at": record.revoked_at.isoformat() if record.revoked_at else None,
|
|
213
|
+
},
|
|
214
|
+
args.as_json,
|
|
215
|
+
)
|
|
216
|
+
return 0
|
|
217
|
+
|
|
218
|
+
if args.command == "list":
|
|
219
|
+
keys = manager.list_keys()
|
|
220
|
+
if args.as_json:
|
|
221
|
+
print(json.dumps([record.to_json() for record in keys], indent=2))
|
|
222
|
+
else:
|
|
223
|
+
if not keys:
|
|
224
|
+
print("No keys stored.")
|
|
225
|
+
for record in keys:
|
|
226
|
+
state = _describe_state(record)
|
|
227
|
+
scopes = ",".join(sorted(record.scopes)) or "-"
|
|
228
|
+
description = record.description or "-"
|
|
229
|
+
print(f"{record.prefix} {state:<22} scopes={scopes} desc={description}")
|
|
230
|
+
return 0
|
|
231
|
+
|
|
232
|
+
if args.command == "events":
|
|
233
|
+
events = manager.list_events(limit=args.limit)
|
|
234
|
+
if args.as_json:
|
|
235
|
+
print(json.dumps([event.to_json() for event in events], indent=2))
|
|
236
|
+
else:
|
|
237
|
+
if not events:
|
|
238
|
+
print("No events recorded.")
|
|
239
|
+
for event in events:
|
|
240
|
+
at = event.at.isoformat()
|
|
241
|
+
print(f"{at} {event.kind.value:<14} {event.prefix} {event.detail}")
|
|
242
|
+
return 0
|
|
243
|
+
|
|
244
|
+
raise BittingError(f"unknown command: {args.command}") # pragma: no cover
|
|
245
|
+
except BittingError as exc:
|
|
246
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
247
|
+
return 1
|
|
248
|
+
except ValueError as exc:
|
|
249
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
250
|
+
return 1
|
|
251
|
+
finally:
|
|
252
|
+
store.close()
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _describe_state(record: KeyRecord) -> str:
|
|
256
|
+
if record.revoked_at is not None:
|
|
257
|
+
return "revoked"
|
|
258
|
+
if record.rotated_at is not None:
|
|
259
|
+
return "rotated"
|
|
260
|
+
if record.is_expired():
|
|
261
|
+
return "expired"
|
|
262
|
+
return "active"
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
if __name__ == "__main__": # pragma: no cover
|
|
266
|
+
sys.exit(main())
|
bitting/errors.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Exception hierarchy for bitting.
|
|
2
|
+
|
|
3
|
+
All library errors derive from :class:`BittingError`, so applications can
|
|
4
|
+
catch a single base class while still distinguishing failure modes when
|
|
5
|
+
needed.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"BittingError",
|
|
12
|
+
"ConfigurationError",
|
|
13
|
+
"DuplicateKeyError",
|
|
14
|
+
"KeyFormatError",
|
|
15
|
+
"KeyNotFoundError",
|
|
16
|
+
"StorageError",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class BittingError(Exception):
|
|
21
|
+
"""Base class for all errors raised by bitting."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class KeyFormatError(BittingError):
|
|
25
|
+
"""A raw API key string is malformed (wrong scheme, bad checksum, ...)."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class KeyNotFoundError(BittingError):
|
|
29
|
+
"""No key record exists for the given prefix."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class DuplicateKeyError(BittingError):
|
|
33
|
+
"""A key with the same prefix already exists in the store."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class StorageError(BittingError):
|
|
37
|
+
"""The backing key store failed an operation."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ConfigurationError(BittingError):
|
|
41
|
+
"""The library was configured with invalid values."""
|