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.
@@ -0,0 +1,256 @@
1
+ """FastAPI integration: a ready-made API key dependency.
2
+
3
+ Requires the optional ``fastapi`` extra (see README, Installation).
4
+
5
+ The dependency returns the authenticated :class:`bitting.KeyRecord` and
6
+ raises precise HTTP errors:
7
+
8
+ * 401 for authentication failures (bad format, unknown key, wrong hash,
9
+ expired, revoked, fully rotated),
10
+ * 403 for authorization failures (missing scopes), with the missing
11
+ scopes listed in the response detail.
12
+
13
+ Both header styles are supported: ``X-API-Key: <key>`` (default) or
14
+ ``Authorization: Bearer <key>``.
15
+
16
+ Example::
17
+
18
+ from fastapi import Depends, FastAPI
19
+
20
+ from bitting import KeyManager, SQLiteStore
21
+ from bitting.integrations.fastapi import APIKeyAuth
22
+
23
+ app = FastAPI()
24
+ auth = APIKeyAuth(KeyManager(SQLiteStore("keys.db")))
25
+
26
+ @app.get("/users", dependencies=[Depends(auth.require(scopes={"read:users"}))])
27
+ async def list_users():
28
+ return [...]
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ from collections.abc import Callable, Iterable
34
+
35
+ from fastapi import FastAPI, HTTPException, Request, Response, status
36
+ from fastapi.responses import JSONResponse
37
+
38
+ from ..manager import KeyManager
39
+ from ..models import KeyRecord, VerifyReason, VerifyResult
40
+
41
+ __all__ = [
42
+ "WWW_AUTHENTICATE",
43
+ "APIKeyAuth",
44
+ "AuthenticationError",
45
+ "ScopeDeniedError",
46
+ "register_error_handlers",
47
+ ]
48
+
49
+ WWW_AUTHENTICATE = "ApiKey"
50
+
51
+ # Every verify reason except SCOPE_MISSING is an authentication failure (401);
52
+ # SCOPE_MISSING is authorization (403). ROTATED_GRACE never reaches _deny()
53
+ # because it means the key verified successfully during its grace window.
54
+ _AUTHN_FAILURE_REASONS = frozenset(
55
+ {
56
+ VerifyReason.INVALID_FORMAT,
57
+ VerifyReason.NOT_FOUND,
58
+ VerifyReason.HASH_MISMATCH,
59
+ VerifyReason.EXPIRED,
60
+ VerifyReason.REVOKED,
61
+ VerifyReason.ROTATED,
62
+ }
63
+ )
64
+
65
+
66
+ class AuthenticationError(PermissionError):
67
+ r"""A key failed authentication (bad format, unknown, expired, ...).
68
+
69
+ Subclasses :class:`PermissionError` for backwards compatibility with
70
+ code that caught the pre-1.2 exception type, but is raised *only* by
71
+ the API-key dependency — so :func:`register_error_handlers` can map
72
+ exactly these failures to 401 without relabelling unrelated
73
+ application ``PermissionError``\ s (filesystem errors, third-party
74
+ libraries, ...) as API-key problems.
75
+ """
76
+
77
+
78
+ class ScopeDeniedError(PermissionError):
79
+ """A valid key lacked the required scopes (an authorization failure).
80
+
81
+ Raised instead of :class:`PermissionError` when ``auto_error=False``
82
+ so applications (and :func:`register_error_handlers`) can map it to
83
+ ``403`` while authentication failures stay ``401``.
84
+ """
85
+
86
+ def __init__(self, missing_scopes: Iterable[str]) -> None:
87
+ self.missing_scopes = frozenset(missing_scopes)
88
+ super().__init__("missing required scopes: " + ", ".join(sorted(self.missing_scopes)))
89
+
90
+
91
+ class APIKeyAuth:
92
+ """Build FastAPI dependencies backed by a :class:`KeyManager`.
93
+
94
+ Args:
95
+ manager: The key manager to verify against.
96
+ header: Where the client sends the key — ``"X-API-Key"`` (default)
97
+ or ``"Authorization"`` (then ``Bearer <key>`` is expected).
98
+ auto_error: Return 401/403 responses (True, default) or raise
99
+ without a response (:class:`AuthenticationError` for
100
+ authentication failures, :class:`ScopeDeniedError` for missing
101
+ scopes) so custom handlers can take over.
102
+ """
103
+
104
+ def __init__(
105
+ self,
106
+ manager: KeyManager,
107
+ *,
108
+ header: str = "X-API-Key",
109
+ auto_error: bool = True,
110
+ ) -> None:
111
+ if header.lower() not in {"x-api-key", "authorization"}:
112
+ raise ValueError("header must be 'X-API-Key' or 'Authorization'")
113
+ self._manager = manager
114
+ self._header = header
115
+ self._auto_error = auto_error
116
+
117
+ def _www_authenticate(self) -> str:
118
+ """The RFC 7235 challenge scheme matching the configured header.
119
+
120
+ ``Bearer`` when keys arrive as ``Authorization: Bearer <key>``;
121
+ ``ApiKey`` for the ``X-API-Key`` header.
122
+ """
123
+ return "Bearer" if self._header.lower() == "authorization" else WWW_AUTHENTICATE
124
+
125
+ def _extract(self, request: Request) -> str | None:
126
+ # An ambiguous credential is not a credential. Starlette's
127
+ # headers.get() returns the *first* occurrence, so a request
128
+ # carrying both a valid and an invalid key would authenticate on
129
+ # whichever the client happened to list first. Refuse duplicates
130
+ # outright instead of guessing.
131
+ values = request.headers.getlist(self._header)
132
+ if len(values) > 1:
133
+ return None
134
+ value = values[0] if values else None
135
+ if value is None:
136
+ return None
137
+ if self._header.lower() == "authorization":
138
+ scheme, _, token = value.partition(" ")
139
+ if scheme.lower() != "bearer" or not token:
140
+ return None
141
+ return token.strip()
142
+ return value.strip()
143
+
144
+ def _deny(self, result: VerifyResult) -> HTTPException:
145
+ if result.reason is VerifyReason.SCOPE_MISSING:
146
+ missing = ", ".join(sorted(result.missing_scopes))
147
+ return HTTPException(
148
+ status_code=status.HTTP_403_FORBIDDEN,
149
+ detail=f"missing required scopes: {missing}",
150
+ )
151
+ return HTTPException(
152
+ status_code=status.HTTP_401_UNAUTHORIZED,
153
+ detail=f"invalid API key: {result.reason.value}",
154
+ headers={"WWW-Authenticate": self._www_authenticate()},
155
+ )
156
+
157
+ def _authenticate(self, request: Request, required_scopes: Iterable[str]) -> KeyRecord:
158
+ raw = self._extract(request)
159
+ if raw is None:
160
+ result = VerifyResult(ok=False, reason=VerifyReason.INVALID_FORMAT)
161
+ else:
162
+ result = self._manager.verify(raw, required_scopes=required_scopes)
163
+ if not result.ok:
164
+ if self._auto_error:
165
+ raise self._deny(result)
166
+ if result.reason is VerifyReason.SCOPE_MISSING:
167
+ raise ScopeDeniedError(result.missing_scopes)
168
+ raise AuthenticationError(result.reason.value)
169
+ if result.record is None: # pragma: no cover - invariant
170
+ # Fail closed: an ``ok`` result always carries its record, but
171
+ # an ``assert`` here would be stripped under ``python -O``.
172
+ raise AuthenticationError(VerifyReason.INVALID_FORMAT.value)
173
+ return result.record
174
+
175
+ def require(self, *, scopes: Iterable[str] = ()) -> Callable[[Request], KeyRecord]:
176
+ """Return a FastAPI dependency that enforces these scopes.
177
+
178
+ Always use it through :func:`fastapi.Depends`, both in route
179
+ ``dependencies=[...]`` lists and for parameter injection::
180
+
181
+ @app.get("/users", dependencies=[Depends(auth.require(scopes={"read:users"}))])
182
+ ...
183
+
184
+ @app.get("/users")
185
+ async def list_users(
186
+ record: KeyRecord = Depends(auth.require(scopes={"read:users"})),
187
+ ):
188
+ ...
189
+
190
+ Scopes are validated eagerly, at dependency-construction time
191
+ (route setup / application startup): a malformed scope — a bare
192
+ string, empty, whitespace-containing, or not a string — raises
193
+ ``ValueError`` immediately instead of failing every request with
194
+ a 500.
195
+ """
196
+ if isinstance(scopes, (str, bytes)):
197
+ # A bare string would silently become a set of single characters
198
+ # ("read:users" -> {'r','e','a',...}), matching nothing sensible.
199
+ raise ValueError(
200
+ f"require(scopes=...) needs an iterable of scope strings, not a "
201
+ f"single string (got {scopes!r}); pass e.g. scopes={{'read:users'}}"
202
+ )
203
+ scope_set = frozenset(scopes)
204
+ for scope in scope_set:
205
+ if not isinstance(scope, str) or not scope or any(ch.isspace() for ch in scope):
206
+ raise ValueError(
207
+ f"require(scopes=...) needs non-empty scope strings without "
208
+ f"whitespace (got {scope!r}); this is a route-configuration error"
209
+ )
210
+
211
+ def dependency(request: Request) -> KeyRecord:
212
+ return self._authenticate(request, scope_set)
213
+
214
+ return dependency
215
+
216
+ def login_route(self, *, prefix: str = "/api-keys") -> None:
217
+ """No-op: issuing keys over HTTP is intentionally unsupported.
218
+
219
+ Key issuance is an operator action; exposing it via a public
220
+ route would let any authenticated client mint keys. Use the CLI
221
+ or library from trusted code paths instead.
222
+ """
223
+ raise NotImplementedError(
224
+ "issuing API keys over HTTP is intentionally unsupported; "
225
+ "use the bitting CLI or library from trusted code"
226
+ )
227
+
228
+
229
+ def register_error_handlers(app: FastAPI, auth: APIKeyAuth | None = None) -> None:
230
+ r"""Attach uniform 401/403 JSON responses for the auto_error=False flow.
231
+
232
+ :class:`ScopeDeniedError` maps to 403 with the missing scopes listed;
233
+ :class:`AuthenticationError` maps to 401 with a ``WWW-Authenticate``
234
+ header matching ``auth``'s header mode (``Bearer`` for Authorization
235
+ mode, ``ApiKey`` otherwise; ``ApiKey`` when ``auth`` is omitted).
236
+ Only the dedicated exception classes are registered: unrelated
237
+ application ``PermissionError``\ s keep their own meaning instead of
238
+ being relabelled as API-key failures. Pass ``auth`` so the challenge
239
+ scheme matches your deployment.
240
+ """
241
+ challenge = auth._www_authenticate() if auth is not None else WWW_AUTHENTICATE
242
+
243
+ @app.exception_handler(ScopeDeniedError)
244
+ async def _scope_denied(_: Request, exc: ScopeDeniedError) -> Response:
245
+ return JSONResponse(
246
+ status_code=status.HTTP_403_FORBIDDEN,
247
+ content={"detail": str(exc), "missing_scopes": sorted(exc.missing_scopes)},
248
+ )
249
+
250
+ @app.exception_handler(AuthenticationError)
251
+ async def _authentication_error(_: Request, exc: AuthenticationError) -> Response:
252
+ return JSONResponse(
253
+ status_code=status.HTTP_401_UNAUTHORIZED,
254
+ content={"detail": f"invalid API key: {exc}"},
255
+ headers={"WWW-Authenticate": challenge},
256
+ )
bitting/keys.py ADDED
@@ -0,0 +1,228 @@
1
+ """API key format: generation, parsing, and checksum validation.
2
+
3
+ Key anatomy
4
+ ===========
5
+ A bitting key looks like::
6
+
7
+ btg_live_9kQ2VxNmLpR7zT4w_8fJk2LmNpQrStUvWxYz3Aa5Bb7CcDdEe9fGh_5K3m
8
+
9
+ It has five parts, joined by underscores:
10
+
11
+ ``btg``
12
+ Scheme marker that identifies the key format.
13
+ ``live``
14
+ Environment label (``live``, ``test``, ... — configurable, validated).
15
+ ``9kQ2VxNmLpR7zT4w``
16
+ A 16-character base62 *prefix* (~95 bits; 8-64 configurable). It is
17
+ stored in plaintext and used as the lookup index so verification
18
+ never scans the table.
19
+ ``8fJk...9fGh``
20
+ A 40-character base62 *secret* (~238 bits; 16-128 configurable). It
21
+ is never stored; only its memory-hard hash is persisted.
22
+ ``5K3m``
23
+ A 4-character base62 *checksum* over the preceding characters. It
24
+ catches transcription errors (typos) before the store is touched.
25
+ This is a data-integrity aid, **not** a security control.
26
+
27
+ Design notes
28
+ ------------
29
+ * Prefix lookup is the same trade-off made by Stripe-style API keys:
30
+ an attacker who steals the database learns which prefixes exist but
31
+ cannot reconstruct any secret (they only ever see hashes).
32
+ * Malformed keys are rejected before a store lookup, so junk traffic
33
+ cannot be used to force database work.
34
+ * ``secrets`` from the standard library provides the entropy; no
35
+ dependency is required.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import binascii
41
+ import re
42
+ import secrets
43
+ from dataclasses import dataclass
44
+
45
+ from .errors import ConfigurationError, KeyFormatError
46
+
47
+ __all__ = [
48
+ "ALPHABET",
49
+ "CHECKSUM_LENGTH",
50
+ "DEFAULT_ENV",
51
+ "PREFIX_LENGTH",
52
+ "SCHEME",
53
+ "SECRET_LENGTH",
54
+ "ParsedKey",
55
+ "compute_checksum",
56
+ "generate_api_key",
57
+ "parse_api_key",
58
+ "validate_env_label",
59
+ ]
60
+
61
+ #: Scheme marker that starts every bitting key.
62
+ SCHEME = "btg"
63
+
64
+ #: base62 alphabet used for all random components.
65
+ ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
66
+
67
+ #: Length of the plaintext prefix (the lookup index).
68
+ PREFIX_LENGTH = 16
69
+
70
+ #: Length of the secret component.
71
+ SECRET_LENGTH = 40
72
+
73
+ #: Length of the trailing checksum.
74
+ CHECKSUM_LENGTH = 4
75
+
76
+ #: Default environment label embedded in generated keys.
77
+ DEFAULT_ENV = "live"
78
+
79
+ _ENV_RE = re.compile(r"^[a-z][a-z0-9]{1,15}$")
80
+
81
+ # btg_live_<8-64 chars>_<16-128 chars>_<4 chars>
82
+ # The component-length ranges mirror exactly what generate_api_key()
83
+ # validates, so every key the generator can produce is parseable.
84
+ _KEY_RE = re.compile(
85
+ r"^(?P<scheme>btg)"
86
+ r"_(?P<env>[a-z][a-z0-9]{1,15})"
87
+ r"_(?P<prefix>[0-9A-Za-z]{8,64})"
88
+ r"_(?P<secret>[0-9A-Za-z]{16,128})"
89
+ r"_(?P<checksum>[0-9A-Za-z]{4})$"
90
+ )
91
+
92
+
93
+ @dataclass(frozen=True, slots=True)
94
+ class ParsedKey:
95
+ """The decoded components of a raw API key string.
96
+
97
+ The secret is redacted in ``repr()`` so a debugger or an unlucky
98
+ ``%r`` log line can never print the live credential.
99
+ """
100
+
101
+ scheme: str
102
+ env: str
103
+ prefix: str
104
+ secret: str
105
+
106
+ def __repr__(self) -> str:
107
+ return (
108
+ f"{type(self).__name__}(scheme={self.scheme!r}, env={self.env!r}, "
109
+ f"prefix={self.prefix!r}, secret=<redacted:{len(self.secret)} chars>)"
110
+ )
111
+
112
+ @property
113
+ def canonical(self) -> str:
114
+ """The key string without the trailing checksum."""
115
+ return f"{self.scheme}_{self.env}_{self.prefix}_{self.secret}"
116
+
117
+
118
+ def validate_env_label(env: str) -> str:
119
+ """Validate an environment label such as ``live`` or ``test``.
120
+
121
+ Labels must be 2-16 characters of lowercase letters and digits,
122
+ starting with a letter. This keeps keys unambiguous when parsed.
123
+
124
+ Raises:
125
+ ConfigurationError: If the label is invalid.
126
+ """
127
+ if not isinstance(env, str) or not _ENV_RE.fullmatch(env):
128
+ raise ConfigurationError(
129
+ "environment label must be 2-16 chars of lowercase letters/digits, "
130
+ f"starting with a letter (got {env!r})"
131
+ )
132
+ return env
133
+
134
+
135
+ def _random_token(length: int) -> str:
136
+ # System randomness with rejection sampling to avoid modulo bias:
137
+ # draw fresh indices until one is uniform over the 62-symbol alphabet.
138
+ alphabet_length = len(ALPHABET)
139
+ out: list[str] = []
140
+ while len(out) < length:
141
+ byte = secrets.token_bytes(1)[0]
142
+ if byte < 248: # 248 = 62 * 4, the largest exact multiple of 62 <= 256
143
+ out.append(ALPHABET[byte % alphabet_length])
144
+ return "".join(out)
145
+
146
+
147
+ def compute_checksum(canonical: str) -> str:
148
+ """Compute the 4-char base62 checksum for a canonical key string.
149
+
150
+ The checksum is ``CRC32(canonical) mod 62**4``, base62-encoded and
151
+ zero-padded. It detects common transcription errors (single-character
152
+ substitutions, most transpositions). It is *not* cryptographic and
153
+ must never be treated as an integrity guarantee against an attacker.
154
+ """
155
+ value = binascii.crc32(canonical.encode("utf-8")) % (62**CHECKSUM_LENGTH)
156
+ digits: list[str] = []
157
+ for _ in range(CHECKSUM_LENGTH):
158
+ value, remainder = divmod(value, 62)
159
+ digits.append(ALPHABET[remainder])
160
+ return "".join(reversed(digits))
161
+
162
+
163
+ def generate_api_key(
164
+ env: str = DEFAULT_ENV,
165
+ *,
166
+ prefix_length: int = PREFIX_LENGTH,
167
+ secret_length: int = SECRET_LENGTH,
168
+ ) -> str:
169
+ """Generate a new raw API key string.
170
+
171
+ Args:
172
+ env: Environment label embedded in the key (``live``, ``test``, ...).
173
+ prefix_length: Length of the random prefix (default 16).
174
+ secret_length: Length of the random secret (default 40).
175
+
176
+ Returns:
177
+ A key of the form ``btg_<env>_<prefix>_<secret>_<checksum>``.
178
+
179
+ Raises:
180
+ ConfigurationError: If ``env`` or the component lengths are invalid.
181
+ """
182
+ validate_env_label(env)
183
+ if isinstance(prefix_length, bool) or not isinstance(prefix_length, int):
184
+ raise ConfigurationError(
185
+ f"prefix_length must be an int (got {type(prefix_length).__name__})"
186
+ )
187
+ if isinstance(secret_length, bool) or not isinstance(secret_length, int):
188
+ raise ConfigurationError(
189
+ f"secret_length must be an int (got {type(secret_length).__name__})"
190
+ )
191
+ if prefix_length < 8 or prefix_length > 64:
192
+ raise ConfigurationError("prefix_length must be between 8 and 64")
193
+ if secret_length < 16 or secret_length > 128:
194
+ raise ConfigurationError("secret_length must be between 16 and 128")
195
+ prefix = _random_token(prefix_length)
196
+ secret = _random_token(secret_length)
197
+ canonical = f"{SCHEME}_{env}_{prefix}_{secret}"
198
+ return f"{canonical}_{compute_checksum(canonical)}"
199
+
200
+
201
+ def parse_api_key(raw: str) -> ParsedKey:
202
+ """Parse and checksum-validate a raw API key string.
203
+
204
+ Leading/trailing whitespace is tolerated and stripped.
205
+
206
+ Returns:
207
+ The decoded :class:`ParsedKey`.
208
+
209
+ Raises:
210
+ KeyFormatError: If the key does not match the format, the checksum
211
+ is wrong, or the scheme is not ``btg``.
212
+ """
213
+ if not isinstance(raw, str):
214
+ raise KeyFormatError(f"API key must be a string, got {type(raw).__name__}")
215
+ candidate = raw.strip()
216
+ match = _KEY_RE.fullmatch(candidate)
217
+ if match is None:
218
+ raise KeyFormatError("malformed API key: expected btg_<env>_<prefix>_<secret>_<checksum>")
219
+ parts = match.groupdict()
220
+ parsed = ParsedKey(
221
+ scheme=parts["scheme"],
222
+ env=parts["env"],
223
+ prefix=parts["prefix"],
224
+ secret=parts["secret"],
225
+ )
226
+ if compute_checksum(parsed.canonical) != parts["checksum"]:
227
+ raise KeyFormatError("API key checksum mismatch (transcription error?)")
228
+ return parsed