wiltech-labs-auth 1.0.1__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,63 @@
1
+ """
2
+ wiltech-labs-auth: who is calling a Wiltech FastAPI app, and may they?
3
+
4
+ Clerk JWT verification, the Caller with the roles saved in the app's
5
+ database, require_admin / require_owner, service API keys for app-to-app
6
+ calls, and Clerk (Svix) webhook verification.
7
+
8
+ This module is the entire public surface — import from `wiltech_labs_auth`,
9
+ not from its sub-packages.
10
+ """
11
+ from wiltech_labs_auth.api_keys import (
12
+ API_KEY_HEADER,
13
+ API_KEYS_TABLE_SQL,
14
+ ApiKeyModel,
15
+ ApiKeyRepository,
16
+ ServiceCaller,
17
+ generate_api_key,
18
+ get_api_key_repository,
19
+ hash_api_key,
20
+ require_api_key,
21
+ )
22
+ from wiltech_labs_auth.authorization import (
23
+ Caller,
24
+ CallerLookup,
25
+ SavedUser,
26
+ UserDetailViewLookup,
27
+ get_caller,
28
+ get_caller_lookup,
29
+ require_admin,
30
+ require_owner,
31
+ )
32
+ from wiltech_labs_auth.clerk import AuthenticatedUser, get_authenticated_user
33
+ from wiltech_labs_auth.roles import ROLE_LABELS, UserRole, parse_role_ids, role_options
34
+ from wiltech_labs_auth.webhooks import WebhookVerificationError, clerk_webhook_event, verify_svix_signature
35
+
36
+ __all__ = [
37
+ "API_KEYS_TABLE_SQL",
38
+ "API_KEY_HEADER",
39
+ "ApiKeyModel",
40
+ "ApiKeyRepository",
41
+ "AuthenticatedUser",
42
+ "Caller",
43
+ "CallerLookup",
44
+ "ROLE_LABELS",
45
+ "SavedUser",
46
+ "ServiceCaller",
47
+ "UserDetailViewLookup",
48
+ "UserRole",
49
+ "WebhookVerificationError",
50
+ "clerk_webhook_event",
51
+ "generate_api_key",
52
+ "get_api_key_repository",
53
+ "get_authenticated_user",
54
+ "get_caller",
55
+ "get_caller_lookup",
56
+ "hash_api_key",
57
+ "parse_role_ids",
58
+ "require_admin",
59
+ "require_api_key",
60
+ "require_owner",
61
+ "role_options",
62
+ "verify_svix_signature",
63
+ ]
@@ -0,0 +1,23 @@
1
+ from wiltech_labs_auth.api_keys.api_keys import (
2
+ API_KEY_HEADER,
3
+ API_KEYS_TABLE_SQL,
4
+ ApiKeyModel,
5
+ ApiKeyRepository,
6
+ ServiceCaller,
7
+ generate_api_key,
8
+ get_api_key_repository,
9
+ hash_api_key,
10
+ require_api_key,
11
+ )
12
+
13
+ __all__ = [
14
+ "API_KEY_HEADER",
15
+ "API_KEYS_TABLE_SQL",
16
+ "ApiKeyModel",
17
+ "ApiKeyRepository",
18
+ "ServiceCaller",
19
+ "generate_api_key",
20
+ "get_api_key_repository",
21
+ "hash_api_key",
22
+ "require_api_key",
23
+ ]
@@ -0,0 +1,169 @@
1
+ import hashlib
2
+ import secrets
3
+ import uuid
4
+ from dataclasses import dataclass
5
+ from datetime import datetime, timedelta, timezone
6
+ from typing import Callable, Optional
7
+
8
+ from fastapi import Depends, HTTPException, Request, status
9
+ from fastapi.security import APIKeyHeader
10
+
11
+ from wiltech_labs_core import Database, get_database
12
+
13
+ API_KEY_HEADER = "X-Api-Key"
14
+ KEY_PREFIX = "wtk_"
15
+
16
+ # How stale last_used_date may get before a request updates it. Writing on
17
+ # every call would spend D1's free write allowance on bookkeeping.
18
+ LAST_USED_RESOLUTION = timedelta(hours=1)
19
+
20
+ # Migration for apps that accept service API keys (copy into migrations/ and schema.sql).
21
+ API_KEYS_TABLE_SQL = """
22
+ CREATE TABLE IF NOT EXISTS api_keys (
23
+ id TEXT PRIMARY KEY,
24
+ name TEXT NOT NULL,
25
+ key_hash TEXT NOT NULL UNIQUE,
26
+ key_prefix TEXT NOT NULL,
27
+ scopes TEXT NOT NULL,
28
+ created_date TEXT NOT NULL,
29
+ last_used_date TEXT,
30
+ revoked_date TEXT
31
+ );
32
+ """.strip()
33
+
34
+ _api_key_header = APIKeyHeader(name=API_KEY_HEADER, auto_error=False)
35
+
36
+
37
+ def generate_api_key() -> str:
38
+ """A new random key, e.g. `wtk_3q2...`. Shown to the person once; only its hash is stored."""
39
+ return KEY_PREFIX + secrets.token_urlsafe(32)
40
+
41
+
42
+ def hash_api_key(key: str) -> str:
43
+ """
44
+ SHA-256 hex digest. A plain hash, not bcrypt: the key is 256 random bits,
45
+ so there is nothing to brute-force, and lookups must be one indexed query.
46
+ """
47
+ return hashlib.sha256(key.encode()).hexdigest()
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class ApiKeyModel:
52
+ id: str
53
+ name: str
54
+ key_prefix: str
55
+ scopes: list[str]
56
+ created_date: str
57
+ last_used_date: Optional[str] = None
58
+ revoked_date: Optional[str] = None
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class ServiceCaller:
63
+ """An app (not a person) calling with an API key."""
64
+
65
+ key_id: str
66
+ name: str
67
+ scopes: list[str]
68
+
69
+
70
+ def _now() -> datetime:
71
+ return datetime.now(timezone.utc)
72
+
73
+
74
+ def _to_model(row: dict) -> ApiKeyModel:
75
+ return ApiKeyModel(
76
+ id=row["id"],
77
+ name=row["name"],
78
+ key_prefix=row["key_prefix"],
79
+ scopes=[scope for scope in (row["scopes"] or "").split(",") if scope],
80
+ created_date=row["created_date"],
81
+ last_used_date=row.get("last_used_date"),
82
+ revoked_date=row.get("revoked_date"),
83
+ )
84
+
85
+
86
+ class ApiKeyRepository:
87
+ """SQL for the `api_keys` table (API_KEYS_TABLE_SQL)."""
88
+
89
+ def __init__(self, db: Database) -> None:
90
+ self.db = db
91
+
92
+ async def create(self, name: str, scopes: list[str]) -> tuple[ApiKeyModel, str]:
93
+ """Returns the saved key and the plain key. The plain key can't be recovered later."""
94
+ plain = generate_api_key()
95
+ key_id = str(uuid.uuid4())
96
+ created = _now().isoformat()
97
+ await self.db.execute(
98
+ "INSERT INTO api_keys (id, name, key_hash, key_prefix, scopes, created_date) VALUES (?, ?, ?, ?, ?, ?)",
99
+ (key_id, name, hash_api_key(plain), plain[: len(KEY_PREFIX) + 6], ",".join(sorted(set(scopes))), created),
100
+ )
101
+ model = await self.find(key_id)
102
+ assert model is not None
103
+ return model, plain
104
+
105
+ async def find(self, key_id: str) -> Optional[ApiKeyModel]:
106
+ row = await self.db.fetch_one("SELECT * FROM api_keys WHERE id = ?", (key_id,))
107
+ return _to_model(row) if row else None
108
+
109
+ async def find_active_by_key(self, plain: str) -> Optional[ApiKeyModel]:
110
+ row = await self.db.fetch_one(
111
+ "SELECT * FROM api_keys WHERE key_hash = ? AND revoked_date IS NULL",
112
+ (hash_api_key(plain),),
113
+ )
114
+ return _to_model(row) if row else None
115
+
116
+ async def list_all(self) -> list[ApiKeyModel]:
117
+ rows = await self.db.fetch_all("SELECT * FROM api_keys ORDER BY created_date DESC")
118
+ return [_to_model(row) for row in rows]
119
+
120
+ async def revoke(self, key_id: str) -> None:
121
+ await self.db.execute(
122
+ "UPDATE api_keys SET revoked_date = ? WHERE id = ? AND revoked_date IS NULL",
123
+ (_now().isoformat(), key_id),
124
+ )
125
+
126
+ async def mark_used(self, key: ApiKeyModel) -> None:
127
+ if key.last_used_date and _now() - datetime.fromisoformat(key.last_used_date) < LAST_USED_RESOLUTION:
128
+ return
129
+ await self.db.execute("UPDATE api_keys SET last_used_date = ? WHERE id = ?", (_now().isoformat(), key.id))
130
+
131
+
132
+ def get_api_key_repository(request: Request) -> ApiKeyRepository:
133
+ """Overridable like get_caller_lookup, e.g. to keep keys in another database."""
134
+ return ApiKeyRepository(get_database(request))
135
+
136
+
137
+ def require_api_key(*scopes: str) -> Callable:
138
+ """
139
+ Route dependency factory for service-to-service calls:
140
+
141
+ @router.post("/parse", dependencies=[Depends(require_api_key("docs:parse"))])
142
+
143
+ 401 without a valid, unrevoked key in X-Api-Key; 403 if the key lacks one
144
+ of `scopes`. Returns the ServiceCaller.
145
+ """
146
+ required = set(scopes)
147
+
148
+ async def dependency(
149
+ key: Optional[str] = Depends(_api_key_header),
150
+ repository: ApiKeyRepository = Depends(get_api_key_repository),
151
+ ) -> ServiceCaller:
152
+ if not key or not key.startswith(KEY_PREFIX):
153
+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="API key required")
154
+
155
+ saved = await repository.find_active_by_key(key)
156
+ if saved is None:
157
+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid API key")
158
+
159
+ missing = required - set(saved.scopes)
160
+ if missing:
161
+ raise HTTPException(
162
+ status_code=status.HTTP_403_FORBIDDEN,
163
+ detail=f"API key lacks scope: {', '.join(sorted(missing))}",
164
+ )
165
+
166
+ await repository.mark_used(saved)
167
+ return ServiceCaller(key_id=saved.id, name=saved.name, scopes=saved.scopes)
168
+
169
+ return dependency
@@ -0,0 +1,21 @@
1
+ from wiltech_labs_auth.authorization.authorization import (
2
+ Caller,
3
+ CallerLookup,
4
+ SavedUser,
5
+ UserDetailViewLookup,
6
+ get_caller,
7
+ get_caller_lookup,
8
+ require_admin,
9
+ require_owner,
10
+ )
11
+
12
+ __all__ = [
13
+ "Caller",
14
+ "CallerLookup",
15
+ "SavedUser",
16
+ "UserDetailViewLookup",
17
+ "get_caller",
18
+ "get_caller_lookup",
19
+ "require_admin",
20
+ "require_owner",
21
+ ]
@@ -0,0 +1,111 @@
1
+ from dataclasses import dataclass
2
+ from typing import Optional, Protocol
3
+
4
+ from fastapi import Depends, HTTPException, Request, status
5
+
6
+ from wiltech_labs_auth.clerk import AuthenticatedUser, get_authenticated_user
7
+ from wiltech_labs_auth.roles import UserRole, parse_role_ids
8
+ from wiltech_labs_core import Database, get_database
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class SavedUser:
13
+ """What the app's database knows about a Clerk user: their `users.id` and saved roles."""
14
+
15
+ id: str
16
+ role_ids: list[str]
17
+
18
+
19
+ class CallerLookup(Protocol):
20
+ async def find(self, external_id: str) -> Optional[SavedUser]: ...
21
+
22
+
23
+ class UserDetailViewLookup:
24
+ """
25
+ The default lookup: reads `user_detail_view` (id, external_user_id,
26
+ role_ids as 'ADMIN,STANDARD') rather than a users repository, so this
27
+ package never imports an app's users domain. Apps whose schema differs
28
+ override `get_caller_lookup` instead.
29
+ """
30
+
31
+ def __init__(self, db: Database) -> None:
32
+ self.db = db
33
+
34
+ async def find(self, external_id: str) -> Optional[SavedUser]:
35
+ row = await self.db.fetch_one(
36
+ "SELECT id, role_ids FROM user_detail_view WHERE external_user_id = ?",
37
+ (external_id,),
38
+ )
39
+ if not row:
40
+ return None
41
+ return SavedUser(id=row["id"], role_ids=parse_role_ids(row["role_ids"]))
42
+
43
+
44
+ def get_caller_lookup(request: Request) -> CallerLookup:
45
+ """
46
+ Where `get_caller` finds the saved user. Swap it per app:
47
+
48
+ app.dependency_overrides[get_caller_lookup] = lambda request: MyLookup(...)
49
+ """
50
+ return UserDetailViewLookup(get_database(request))
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class Caller:
55
+ """
56
+ The signed-in caller as our database sees them.
57
+
58
+ `user_id` is their `users.id`, or None if they have never called `/me`
59
+ and so have no saved user yet. `role_ids` are their saved roles — the
60
+ source of truth for permissions, not the Clerk token.
61
+ """
62
+ external_id: str
63
+ user_id: Optional[str]
64
+ role_ids: list[str]
65
+
66
+ @property
67
+ def is_admin(self) -> bool:
68
+ return UserRole.ADMIN.value in self.role_ids
69
+
70
+
71
+ async def get_caller(
72
+ current_user: AuthenticatedUser = Depends(get_authenticated_user),
73
+ lookup: CallerLookup = Depends(get_caller_lookup),
74
+ ) -> Caller:
75
+ """Route dependency: who is calling, with their saved roles."""
76
+ saved = await lookup.find(current_user.id)
77
+
78
+ if saved is None:
79
+ return Caller(external_id=current_user.id, user_id=None, role_ids=[])
80
+
81
+ return Caller(external_id=current_user.id, user_id=saved.id, role_ids=saved.role_ids)
82
+
83
+
84
+ async def require_admin(caller: Caller = Depends(get_caller)) -> Caller:
85
+ """
86
+ Route dependency: only callers whose saved roles include ADMIN get through.
87
+
88
+ An admin granted through the API stays an admin even if Clerk stops
89
+ sending the role. 401 if not signed in (raised by get_authenticated_user);
90
+ 403 if signed in but not an admin, including a caller with no saved user.
91
+ """
92
+ if not caller.is_admin:
93
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin role required")
94
+
95
+ return caller
96
+
97
+
98
+ async def require_owner(user_id: str, caller: Caller = Depends(get_caller)) -> str:
99
+ """
100
+ Route dependency for personal resources under `/users/{user_id}/...`:
101
+ only that user may use them — not even an admin. Returns the path's
102
+ `user_id`; 403 for anyone else, whether or not that user exists, so the
103
+ API doesn't reveal which ids exist.
104
+ """
105
+ if caller.user_id is None or caller.user_id != user_id:
106
+ raise HTTPException(
107
+ status_code=status.HTTP_403_FORBIDDEN,
108
+ detail="Not allowed to access this user's resources",
109
+ )
110
+
111
+ return user_id
@@ -0,0 +1,3 @@
1
+ from wiltech_labs_auth.clerk.clerk_auth import AuthenticatedUser, get_authenticated_user
2
+
3
+ __all__ = ["AuthenticatedUser", "get_authenticated_user"]
@@ -0,0 +1,152 @@
1
+ import asyncio
2
+ import logging
3
+ from dataclasses import dataclass
4
+ from time import monotonic
5
+ from typing import Any
6
+
7
+ import httpx
8
+ import jwt
9
+ from fastapi import Depends, HTTPException, Request, status
10
+ from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
11
+ from jwt import InvalidTokenError, PyJWK
12
+
13
+ from wiltech_labs_core import get_config
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ _bearer = HTTPBearer(auto_error=False)
18
+ _jwks_cache: dict[str, tuple[float, dict[str, Any]]] = {}
19
+ _jwks_lock = asyncio.Lock()
20
+ _JWKS_CACHE_SECONDS = 3600
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class AuthenticatedUser:
25
+ id: str
26
+ name: str
27
+ email: str | None
28
+ role_ids: list[str]
29
+ claims: dict[str, Any]
30
+
31
+
32
+ def _unauthorized(detail: str = "Invalid or expired authentication token") -> HTTPException:
33
+ return HTTPException(
34
+ status_code=status.HTTP_401_UNAUTHORIZED,
35
+ detail=detail,
36
+ headers={"WWW-Authenticate": "Bearer"},
37
+ )
38
+
39
+
40
+ async def _get_jwks(jwks_url: str, force_refresh: bool = False) -> dict[str, Any]:
41
+ cached = _jwks_cache.get(jwks_url)
42
+ if not force_refresh and cached and cached[0] > monotonic():
43
+ return cached[1]
44
+
45
+ async with _jwks_lock:
46
+ cached = _jwks_cache.get(jwks_url)
47
+ if not force_refresh and cached and cached[0] > monotonic():
48
+ return cached[1]
49
+
50
+ async with httpx.AsyncClient(timeout=10) as client:
51
+ response = await client.get(jwks_url)
52
+ response.raise_for_status()
53
+
54
+ jwks = response.json()
55
+ if not isinstance(jwks.get("keys"), list):
56
+ raise RuntimeError("Clerk JWKS response does not contain a keys list")
57
+
58
+ _jwks_cache[jwks_url] = (monotonic() + _JWKS_CACHE_SECONDS, jwks)
59
+ return jwks
60
+
61
+
62
+ def _find_signing_key(jwks: dict[str, Any], key_id: str) -> Any | None:
63
+ for key in jwks["keys"]:
64
+ if key.get("kid") == key_id and key.get("use") == "sig":
65
+ return PyJWK.from_dict(key).key
66
+
67
+ return None
68
+
69
+
70
+ def _normalise_role_ids(claims: dict[str, Any]) -> list[str]:
71
+ value = claims.get("roleIds", claims.get("roles"))
72
+ if not isinstance(value, list):
73
+ return ["STANDARD"]
74
+
75
+ roles = [str(role) for role in value if role]
76
+ return list(dict.fromkeys(roles)) or ["STANDARD"]
77
+
78
+
79
+ async def get_authenticated_user(
80
+ request: Request,
81
+ credentials: HTTPAuthorizationCredentials | None = Depends(_bearer),
82
+ ) -> AuthenticatedUser:
83
+ """
84
+ Route dependency: the Clerk user behind the `Authorization: Bearer` token.
85
+
86
+ 401 for a missing, malformed, expired or wrongly signed token; 503 if
87
+ Clerk's JWKS can't be fetched. Needs CLERK_JWKS_URL and CLERK_AUDIENCE;
88
+ CLERK_AUTHORIZED_PARTIES (comma-separated `azp` values) is optional.
89
+ """
90
+ if credentials is None or credentials.scheme.lower() != "bearer":
91
+ raise _unauthorized("Bearer token required")
92
+
93
+ jwks_url = get_config(request, "CLERK_JWKS_URL")
94
+ audience = get_config(request, "CLERK_AUDIENCE", "wiltech-dev-api")
95
+ if not jwks_url or not audience:
96
+ raise RuntimeError("CLERK_JWKS_URL and CLERK_AUDIENCE must be configured")
97
+
98
+ issuer = jwks_url.removesuffix("/.well-known/jwks.json")
99
+
100
+ try:
101
+ header = jwt.get_unverified_header(credentials.credentials)
102
+ key_id = header.get("kid")
103
+ if not key_id or header.get("alg") != "RS256":
104
+ raise _unauthorized()
105
+
106
+ jwks = await _get_jwks(jwks_url)
107
+ signing_key = _find_signing_key(jwks, key_id)
108
+ if signing_key is None:
109
+ jwks = await _get_jwks(jwks_url, force_refresh=True)
110
+ signing_key = _find_signing_key(jwks, key_id)
111
+ if signing_key is None:
112
+ raise _unauthorized()
113
+
114
+ claims = jwt.decode(
115
+ credentials.credentials,
116
+ signing_key,
117
+ algorithms=["RS256"],
118
+ audience=audience,
119
+ issuer=issuer,
120
+ options={"require": ["exp", "iat", "iss", "sub"]},
121
+ )
122
+ except HTTPException:
123
+ raise
124
+ except (InvalidTokenError, ValueError, TypeError) as exc:
125
+ raise _unauthorized() from exc
126
+ except httpx.HTTPError as exc:
127
+ logger.warning("could not reach Clerk JWKS at %r: %r", jwks_url, exc)
128
+ raise HTTPException(
129
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
130
+ detail="Authentication service unavailable",
131
+ ) from exc
132
+
133
+ authorized_parties = get_config(request, "CLERK_AUTHORIZED_PARTIES")
134
+ if authorized_parties:
135
+ allowed = {
136
+ party.strip()
137
+ for party in authorized_parties.split(",")
138
+ if party.strip()
139
+ }
140
+ if claims.get("azp") not in allowed:
141
+ raise _unauthorized()
142
+
143
+ name = claims.get("name") or claims.get("fullName") or claims["sub"]
144
+ email = claims.get("email") or claims.get("emailAddress")
145
+
146
+ return AuthenticatedUser(
147
+ id=claims["sub"],
148
+ name=str(name),
149
+ email=str(email) if email else None,
150
+ role_ids=_normalise_role_ids(claims),
151
+ claims=claims,
152
+ )
File without changes
@@ -0,0 +1,3 @@
1
+ from wiltech_labs_auth.roles.roles import ROLE_LABELS, UserRole, parse_role_ids, role_options
2
+
3
+ __all__ = ["ROLE_LABELS", "UserRole", "parse_role_ids", "role_options"]
@@ -0,0 +1,33 @@
1
+ from enum import Enum
2
+
3
+ from wiltech_labs_rest import EmbeddedRef
4
+
5
+
6
+ # Enum for user role
7
+ class UserRole(str, Enum):
8
+ STANDARD = "STANDARD"
9
+ ADMIN = "ADMIN"
10
+
11
+
12
+ # Display labels for metadata option lists.
13
+ ROLE_LABELS: dict[UserRole, str] = {
14
+ UserRole.STANDARD: "Standard user",
15
+ UserRole.ADMIN: "System Administrator",
16
+ }
17
+
18
+
19
+ def role_options() -> list[EmbeddedRef]:
20
+ """The `values` list for any `roleIds` field in `_metadata`."""
21
+ return [EmbeddedRef(id=role.value, value=label) for role, label in ROLE_LABELS.items()]
22
+
23
+
24
+ def parse_role_ids(value: str | None) -> list[str]:
25
+ """
26
+ Split `user_detail_view.role_ids` ('ADMIN,STANDARD', or NULL) into a
27
+ sorted list. GROUP_CONCAT does not guarantee order, so sort for stable
28
+ responses.
29
+ """
30
+ if not value:
31
+ return []
32
+
33
+ return sorted(role for role in value.split(",") if role)
@@ -0,0 +1,3 @@
1
+ from wiltech_labs_auth.webhooks.svix import WebhookVerificationError, clerk_webhook_event, verify_svix_signature
2
+
3
+ __all__ = ["WebhookVerificationError", "clerk_webhook_event", "verify_svix_signature"]
@@ -0,0 +1,80 @@
1
+ import base64
2
+ import hashlib
3
+ import hmac
4
+ import json
5
+ import time
6
+ from typing import Any, Mapping, Optional
7
+
8
+ from fastapi import HTTPException, Request, status
9
+
10
+ from wiltech_labs_core import get_config
11
+
12
+ # Reject deliveries whose timestamp is further than this from now (replay protection).
13
+ TOLERANCE_SECONDS = 5 * 60
14
+
15
+
16
+ class WebhookVerificationError(Exception):
17
+ pass
18
+
19
+
20
+ def verify_svix_signature(
21
+ secret: str,
22
+ headers: Mapping[str, str],
23
+ body: bytes,
24
+ now: Optional[float] = None,
25
+ tolerance: int = TOLERANCE_SECONDS,
26
+ ) -> None:
27
+ """
28
+ Check a Svix-signed webhook (what Clerk sends). Raises
29
+ WebhookVerificationError unless one of the `svix-signature` values is the
30
+ HMAC-SHA256 of "{svix-id}.{svix-timestamp}.{body}" under the endpoint's
31
+ `whsec_...` secret, and the timestamp is recent.
32
+
33
+ `body` must be the raw bytes as received: re-serialised JSON won't match.
34
+ """
35
+ msg_id = headers.get("svix-id")
36
+ timestamp = headers.get("svix-timestamp")
37
+ signatures = headers.get("svix-signature")
38
+ if not msg_id or not timestamp or not signatures:
39
+ raise WebhookVerificationError("missing svix headers")
40
+
41
+ try:
42
+ sent_at = int(timestamp)
43
+ except ValueError as exc:
44
+ raise WebhookVerificationError("invalid svix-timestamp") from exc
45
+ if abs((now if now is not None else time.time()) - sent_at) > tolerance:
46
+ raise WebhookVerificationError("timestamp outside the allowed window")
47
+
48
+ key = base64.b64decode(secret.removeprefix("whsec_"))
49
+ signed = f"{msg_id}.{timestamp}.".encode() + body
50
+ expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
51
+
52
+ # Space-separated "v1,<base64>" entries: several while a secret is being rotated.
53
+ for entry in signatures.split():
54
+ version, _, signature = entry.partition(",")
55
+ if version == "v1" and hmac.compare_digest(signature, expected):
56
+ return
57
+
58
+ raise WebhookVerificationError("no matching signature")
59
+
60
+
61
+ async def clerk_webhook_event(request: Request) -> dict[str, Any]:
62
+ """
63
+ Route dependency for a Clerk webhook endpoint: the verified event
64
+ (`{"type": "user.deleted", "data": {...}}`). 400 if the signature is bad,
65
+ 503 if CLERK_WEBHOOK_SECRET isn't set.
66
+
67
+ @router.post("/webhooks/clerk")
68
+ async def clerk(event: dict = Depends(clerk_webhook_event)): ...
69
+ """
70
+ secret = get_config(request, "CLERK_WEBHOOK_SECRET")
71
+ if not secret:
72
+ raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="CLERK_WEBHOOK_SECRET isn't set")
73
+
74
+ body = await request.body()
75
+ try:
76
+ verify_svix_signature(secret, request.headers, body)
77
+ except WebhookVerificationError as exc:
78
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid webhook signature") from exc
79
+
80
+ return json.loads(body)
@@ -0,0 +1,185 @@
1
+ Metadata-Version: 2.5
2
+ Name: wiltech-labs-auth
3
+ Version: 1.0.1
4
+ Summary: Authentication and authorization for Wiltech FastAPI apps: Clerk JWT verification, the Caller with saved roles, require_admin / require_owner, service API keys and Clerk webhook verification.
5
+ Project-URL: Homepage, https://github.com/wilferraciolli/py-libraries/tree/main/packages/auth
6
+ Project-URL: Repository, https://github.com/wilferraciolli/py-libraries
7
+ Project-URL: Conventions, https://github.com/wilferraciolli/py-libraries/blob/main/docs/PYTHON_APP_CONVENTIONS.md
8
+ Author: Wiliam Ferraciolli
9
+ License-Expression: Apache-2.0
10
+ Keywords: api-keys,authorization,clerk,cloudflare-workers,fastapi,jwt
11
+ Classifier: Framework :: FastAPI
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Typing :: Typed
14
+ Requires-Python: >=3.13
15
+ Requires-Dist: fastapi>=0.110
16
+ Requires-Dist: httpx>=0.27
17
+ Requires-Dist: pyjwt[crypto]>=2.8
18
+ Requires-Dist: wiltech-labs-core>=0.1.0
19
+ Requires-Dist: wiltech-labs-rest>=1.0.0
20
+ Description-Content-Type: text/markdown
21
+
22
+ # wiltech-labs-auth
23
+
24
+ Who is calling a Wiltech FastAPI app, and may they? Clerk JWT verification, the `Caller`
25
+ with the roles **saved in the app's database**, `require_admin` / `require_owner`,
26
+ **service API keys** for app-to-app calls, and **Clerk webhook** (Svix) verification.
27
+
28
+ Builds on [`wiltech-labs-core`](../core) (config, `Database`) and
29
+ [`wiltech-labs-rest`](../rest) (`EmbeddedRef` for role options). Pure Python
30
+ (`pyjwt[crypto]`, `httpx`), so it runs in Cloudflare Workers.
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ uv add wiltech-labs-auth
36
+ ```
37
+
38
+ ## Usage
39
+
40
+ ### Signed-in users (Clerk)
41
+
42
+ ```python
43
+ # main.py
44
+ from fastapi import Depends
45
+ from wiltech_labs_auth import get_authenticated_user, require_admin
46
+
47
+ app.include_router(todo_router.router, prefix="/api", dependencies=[Depends(get_authenticated_user)])
48
+ app.include_router(system_settings_router.router, prefix="/api", dependencies=[Depends(require_admin)])
49
+ ```
50
+
51
+ ```python
52
+ # todos/todo_router.py — personal resources: only the user in the path, not even an admin
53
+ from wiltech_labs_auth import Caller, get_caller, require_owner
54
+
55
+ router = APIRouter(prefix="/users/{user_id}/todos")
56
+
57
+
58
+ @router.get("")
59
+ async def list_todos(user_id: str = Depends(require_owner), service: TodoService = Depends(get_todo_service)):
60
+ ...
61
+ ```
62
+
63
+ `get_caller` finds the saved user through `get_caller_lookup`, which by default reads
64
+ `user_detail_view (id, external_user_id, role_ids)`, the view every app built from
65
+ `fastapi-template` has. An app with a different schema overrides it:
66
+
67
+ ```python
68
+ from wiltech_labs_auth import SavedUser, get_caller_lookup
69
+
70
+
71
+ class MembersLookup:
72
+ def __init__(self, db): self.db = db
73
+
74
+ async def find(self, external_id: str) -> SavedUser | None:
75
+ row = await self.db.fetch_one("SELECT id, roles FROM members WHERE clerk_id = ?", (external_id,))
76
+ return SavedUser(row["id"], row["roles"].split(",")) if row else None
77
+
78
+
79
+ app.dependency_overrides[get_caller_lookup] = lambda request: MembersLookup(get_database(request))
80
+ ```
81
+
82
+ ### Service API keys (app → app)
83
+
84
+ For a Worker calling a shared service at home (a PDF parser, a transcriber) where there is
85
+ no signed-in person.
86
+
87
+ 1. Add the table: copy `API_KEYS_TABLE_SQL` into a migration (and `schema.sql` for D1).
88
+ 2. Issue a key from an admin route or a one-off script. The plain key is returned **once**;
89
+ only its SHA-256 is stored.
90
+
91
+ ```python
92
+ saved, plain_key = await ApiKeyRepository(db).create("docs-worker", ["docs:parse"])
93
+ ```
94
+
95
+ 3. Protect routes:
96
+
97
+ ```python
98
+ from wiltech_labs_auth import ServiceCaller, require_api_key
99
+
100
+ @router.post("/documents/parse")
101
+ async def parse(service: ServiceCaller = Depends(require_api_key("docs:parse"))): ...
102
+ ```
103
+
104
+ 4. The caller sends `X-Api-Key: wtk_...`. A missing or revoked key gets 401, a missing
105
+ scope gets 403. `last_used_date` updates at most once an hour per key, to save D1 writes.
106
+
107
+ Rotate a key by creating a new one, deploying it, then calling `revoke(old_id)`.
108
+
109
+ ### Clerk webhooks
110
+
111
+ Keep the local `users` table in step with Clerk (for example, delete a user's data on
112
+ `user.deleted`). In Clerk: *Webhooks → Add endpoint* → `https://api.example.com/api/webhooks/clerk`,
113
+ then put its signing secret in `CLERK_WEBHOOK_SECRET`.
114
+
115
+ ```python
116
+ from wiltech_labs_auth import clerk_webhook_event
117
+
118
+ @router.post("/webhooks/clerk") # NOT behind get_authenticated_user
119
+ async def clerk(event: dict = Depends(clerk_webhook_event)):
120
+ if event["type"] == "user.deleted":
121
+ await users.delete_by_external_id(event["data"]["id"])
122
+ return {"received": True}
123
+ ```
124
+
125
+ `verify_svix_signature(secret, headers, raw_body)` is also exported for non-FastAPI use.
126
+
127
+ ## Configuration
128
+
129
+ | Variable | Used by | Notes |
130
+ |---|---|---|
131
+ | `CLERK_JWKS_URL` | `get_authenticated_user` | The issuer is this URL minus `/.well-known/jwks.json` |
132
+ | `CLERK_AUDIENCE` | `get_authenticated_user` | Default `wiltech-dev-api` (as in the template) |
133
+ | `CLERK_AUTHORIZED_PARTIES` | `get_authenticated_user` | Optional, comma-separated allowed `azp` |
134
+ | `CLERK_WEBHOOK_SECRET` | `clerk_webhook_event` | `whsec_...` |
135
+
136
+ ## Public API
137
+
138
+ | Name | What it is |
139
+ |---|---|
140
+ | `get_authenticated_user`, `AuthenticatedUser` | Verify the Clerk bearer token (JWKS cached for 1 h, refreshed on an unknown `kid`) |
141
+ | `get_caller`, `Caller` | The caller with **saved** roles (`user_id` is `None` before their first `/me`) |
142
+ | `get_caller_lookup`, `CallerLookup`, `SavedUser`, `UserDetailViewLookup` | Where `get_caller` looks users up; override per app |
143
+ | `require_admin` | 403 unless the saved roles include `ADMIN` |
144
+ | `require_owner` | For `/users/{user_id}/...`: 403 unless the caller *is* `user_id` |
145
+ | `UserRole`, `ROLE_LABELS`, `role_options()`, `parse_role_ids()` | Roles and their metadata option list |
146
+ | `require_api_key(*scopes)`, `ServiceCaller` | Service-to-service dependency (`X-Api-Key`) |
147
+ | `ApiKeyRepository`, `ApiKeyModel`, `API_KEYS_TABLE_SQL`, `get_api_key_repository` | Key storage |
148
+ | `generate_api_key()`, `hash_api_key()`, `API_KEY_HEADER` | Key helpers |
149
+ | `clerk_webhook_event`, `verify_svix_signature`, `WebhookVerificationError` | Webhook verification |
150
+
151
+ ## Development
152
+
153
+ ```bash
154
+ uv run --package wiltech-labs-auth pytest packages/auth
155
+ ```
156
+
157
+ ## Publishing
158
+
159
+ Publish `wiltech-labs-core` first; this package depends on it.
160
+
161
+ ```bash
162
+ cd packages/auth
163
+
164
+ # 1. Test, bump, build
165
+ uv run pytest
166
+ uv version --bump patch # or minor / major; skip for the first 0.1.0
167
+ rm -rf ../../dist && uv build # -> ../../dist/
168
+
169
+ # 2. TestPyPI (optional rehearsal), using a token from test.pypi.org
170
+ read -rsp "TestPyPI token: " UV_PUBLISH_TOKEN && export UV_PUBLISH_TOKEN && echo
171
+ uv publish --index testpypi ../../dist/*
172
+ unset UV_PUBLISH_TOKEN
173
+
174
+ # 3. PyPI (the real thing), using a token from pypi.org
175
+ read -rsp "PyPI token: " UV_PUBLISH_TOKEN && export UV_PUBLISH_TOKEN && echo
176
+ uv publish ../../dist/*
177
+ unset UV_PUBLISH_TOKEN
178
+
179
+ # 4. Commit and tag
180
+ git commit -am "wiltech-labs-auth <version>"
181
+ git tag auth-v<version> && git push && git push --tags
182
+ ```
183
+
184
+ A version number can only be uploaded once to each site. To retry after a fix, bump the
185
+ version and rebuild.
@@ -0,0 +1,15 @@
1
+ wiltech_labs_auth/__init__.py,sha256=25u8RT8iypkjkuT1xxx9O2oC7Gz2LP4cCGkZI9HHuqY,1686
2
+ wiltech_labs_auth/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ wiltech_labs_auth/api_keys/__init__.py,sha256=iA1s4pxaPevT5gMgpN6zex-n43E6rv2m2wdO0lFTUMo,467
4
+ wiltech_labs_auth/api_keys/api_keys.py,sha256=Empnlp4FcSeaTtDvhJyOXx41j5nsZ9TxQZmY3t4J7GQ,5780
5
+ wiltech_labs_auth/authorization/__init__.py,sha256=Ot-b-Px6VuWwjqBNXG4-0apmo-eEtwxjdB3EdIsNVAo,389
6
+ wiltech_labs_auth/authorization/authorization.py,sha256=YOv9fEwfsEcRMKL2mder5nG1KuAIpn_YRseA-J8ta4g,3718
7
+ wiltech_labs_auth/clerk/__init__.py,sha256=hLCFo77rKaGsJEGzU1zApyODlJxikqnSx22lq3b80fY,148
8
+ wiltech_labs_auth/clerk/clerk_auth.py,sha256=KJaxOjR1Vs6oIZfTgsMIq_st1zOpWv58j2ByMJFc2A0,5011
9
+ wiltech_labs_auth/roles/__init__.py,sha256=F8L03cezCU0VVwePqWID6hMC5fkvvEUtWGB1qPvP_bQ,167
10
+ wiltech_labs_auth/roles/roles.py,sha256=wLCEXJ5si7s115dho3lRXaHvQIZ0MuL8rWW44nOYee8,864
11
+ wiltech_labs_auth/webhooks/__init__.py,sha256=-Naf_DX6UpLoisJTwgjgyQ4p6UYvT6SecVscbVq5p54,201
12
+ wiltech_labs_auth/webhooks/svix.py,sha256=wWyfI8LzITeKkOyq4nlhkeyDzhdF0Sm8qbXmHAC3HkM,2865
13
+ wiltech_labs_auth-1.0.1.dist-info/METADATA,sha256=dWmjl0jUv2ZQD6AxWhJY04XlWeHZPQiIUld3DMeXgKM,7141
14
+ wiltech_labs_auth-1.0.1.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
15
+ wiltech_labs_auth-1.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any