1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
|
"""Authentication and authorization utilities for ai-search.
This module provides JWT token validation using JWKS from the auth server.
"""
import logging
from datetime import datetime
from functools import wraps
from typing import Optional
from urllib.parse import urljoin
import requests
from authlib.jose import JsonWebKey, JsonWebToken, KeySet
from authlib.jose.errors import BadSignatureError
from quart import request, jsonify, current_app
logger = logging.getLogger(__name__)
class TokenValidationError(Exception):
"""Raised when token validation fails."""
pass
def fetch_jwks(auth_server_url: str, timeout: int = 30) -> KeySet:
"""Fetch JSON Web Keys from the auth server."""
jwks_uri = urljoin(auth_server_url, "auth/public-jwks")
response = requests.get(jwks_uri, timeout=timeout)
response.raise_for_status()
jwks_data = response.json()
keys = [
JsonWebKey.import_key(key) for key in jwks_data.get("jwks", {}).get("keys", [])
]
if not keys:
raise TokenValidationError("No keys found in JWKS response")
return KeySet(keys)
def get_cached_jwks(auth_server_url: str) -> KeySet:
"""Get cached JWKS from Redis, fetching if necessary."""
cache = current_app.extensions["cache"]
cached = cache.get("auth_server_jwks")
if cached is not None:
return KeySet([JsonWebKey.import_key(key) for key in cached])
# Fetch and cache for 2 hours
jwks = fetch_jwks(auth_server_url)
key_data = [key.export() for key in jwks.keys]
cache.set("auth_server_jwks", key_data, timeout=7200)
return jwks
def validate_token(token: str, keys: KeySet) -> dict:
"""Validate a JWT token against the provided keys.
Args:
token: The JWT token string
keys: KeySet containing valid public keys
Returns:
Decoded JWT payload
Raises:
TokenValidationError: If token is invalid or cannot be verified
"""
for key in keys.keys:
try:
jwt = JsonWebToken(["RS256"])
payload = jwt.decode(token, key)
# Check expiration
if payload.get("exp") and datetime.now().timestamp() > payload["exp"]:
raise TokenValidationError("Token has expired")
logger.debug("Token validated successfully")
return payload
except BadSignatureError:
continue
raise TokenValidationError("Token signature could not be verified")
def require_token(func):
"""Decorator that requires a valid bearer token for the endpoint.
Expects the Authorization header with a Bearer token.
Adds `auth_token` kwarg to the decorated function with the decoded JWT payload.
Example:
@app.route("/api/v1/search")
@require_token
async def search(auth_token=None):
# auth_token contains the decoded JWT payload
user_id = auth_token.get("sub")
...
"""
@wraps(func)
async def wrapper(*args, **kwargs):
auth_server_url = current_app.config.get("AUTH_SERVER_URL")
if not auth_server_url:
logger.error("AUTH_SERVER_URL not configured")
return jsonify(
{
"error": "ConfigurationError",
"description": "Authentication not properly configured",
}
), 500
# Extract bearer token from Authorization header
bearer = request.headers.get("Authorization", "")
if not bearer.startswith("Bearer "):
logger.debug("No bearer token provided")
return jsonify(
{
"error": "AuthenticationError",
"description": "Expected 'Authorization: Bearer <token>' header",
}
), 401
try:
_, token = bearer.split(" ", 1)
token = token.strip()
# Get cached JWKS and validate token
jwks = get_cached_jwks(auth_server_url)
jwt_payload = validate_token(token, jwks)
# Add auth token info to kwargs
kwargs["auth_token"] = {"access_token": token, "jwt": jwt_payload}
return await func(*args, **kwargs)
except TokenValidationError as exc:
logger.debug("Token validation failed: %s", exc)
return jsonify(
{"error": "TokenValidationError", "description": str(exc)}
), 401
except Exception:
logger.error("Unexpected error during token validation", exc_info=True)
return jsonify(
{
"error": "InternalError",
"description": "Failed to validate authentication token",
}
), 500
return wrapper
def get_user_id(auth_token: Optional[dict] = None) -> Optional[str]:
"""Extract user ID from auth token.
Args:
auth_token: The auth token dict with 'jwt' key containing the payload
Returns:
User ID (subject claim) or None if not available
"""
if auth_token is None:
return None
jwt_payload = auth_token.get("jwt", {})
return jwt_payload.get("sub")
|