forked from LAION-AI/Open-Assistant
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.py
178 lines (128 loc) · 6.34 KB
/
auth.py
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
168
169
170
171
172
173
174
175
176
177
178
import hashlib
import json
from datetime import datetime, timedelta
import sqlmodel
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from fastapi import HTTPException, Security
from fastapi.security import APIKeyHeader
from jose import jwe
from jose.exceptions import JWEError
from loguru import logger
from oasst_inference_server import deps, models
from oasst_inference_server.schemas import auth
from oasst_inference_server.settings import settings
from starlette.status import HTTP_400_BAD_REQUEST, HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN
authorization_scheme = APIKeyHeader(name="Authorization", auto_error=False, scheme_name="Authorization")
refresh_scheme = APIKeyHeader(name="Refresh", auto_error=False, scheme_name="Refresh")
trusted_client_scheme = APIKeyHeader(name="TrustedClient", auto_error=False, scheme_name="TrustedClient")
def get_current_user_id(
token: str = Security(authorization_scheme), trusted_client_token: str = Security(trusted_client_scheme)
) -> str:
"""Get the current user ID by decoding the JWT token."""
if trusted_client_token is not None:
info: auth.TrustedClient = auth.TrustedClientToken(content=trusted_client_token).content
if info.api_key not in settings.trusted_api_keys_list:
raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="Unauthorized client")
return info.user_id
if token is None or not token.startswith("Bearer "):
logger.warning(f"Invalid token: {token}")
raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Not authenticated")
token = token[len("Bearer ") :]
if not token:
logger.warning(f"Invalid token: {token}")
raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Not authenticated")
key: bytes = derive_key()
try:
token: bytes = jwe.decrypt(token, key)
except JWEError:
raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="Invalid token")
payload: dict = json.loads(token.decode())
validate_access_token(payload)
user_id = payload.get("user_id")
return user_id
def create_access_token(user_id: str) -> str:
"""Create encoded JSON Web Token (JWT) for the given user ID."""
payload: bytes = build_payload(user_id, "access", settings.auth_access_token_expire_minutes)
key = derive_key()
token: bytes = jwe.encrypt(payload, key)
return token.decode()
async def create_refresh_token(user_id: str) -> str:
"""Create encoded refresh token for the given user ID."""
payload: bytes = build_payload(user_id, "refresh", settings.auth_refresh_token_expire_minutes)
key = derive_key()
token: bytes = jwe.encrypt(payload, key)
await store_refresh_token(token, user_id)
return token.decode()
async def refresh_access_token(refresh_token: str) -> str:
"""Refresh the access token using the given refresh token."""
key: bytes = derive_key()
try:
token: bytes = jwe.decrypt(refresh_token, key)
except JWEError:
raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="Invalid token")
token_model = await query_refresh_token(token)
if not token_model or not token_model.enabled:
raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="Invalid token")
payload: dict = json.loads(token.decode())
validate_refresh_token(payload, token_model.user_id)
user_id = payload.get("user_id")
access_token: str = create_access_token(user_id)
return access_token
def derive_key() -> bytes:
"""Derive a key from the auth secret."""
hkdf = HKDF(
algorithm=hashes.SHA256(),
length=settings.auth_length,
salt=settings.auth_salt,
info=settings.auth_info,
)
key = hkdf.derive(settings.auth_secret)
return key
def build_payload(user_id: str, token_type: str, expire_minutes: int) -> bytes:
"""Build a token payload as `bytes` encoded from a JSON string."""
expires_delta = timedelta(minutes=expire_minutes)
expire = datetime.utcnow() + expires_delta
payload_dict = {
"user_id": user_id,
"exp": expire.timestamp(),
"type": token_type,
}
payload: bytes = json.dumps(payload_dict).encode()
return payload
async def store_refresh_token(token: bytes, user_id: str) -> None:
"""Store a refresh token in the backend DB."""
token_hash: bytes = hashlib.sha256(token).hexdigest()
async with deps.manual_create_session() as session:
token_model: models.DbRefreshToken = models.DbRefreshToken(token_hash=token_hash, user_id=user_id)
session.add(token_model)
await session.commit()
async def query_refresh_token(token: bytes) -> models.DbRefreshToken | None:
"""Query a refresh token in the backend DB."""
token_hash: bytes = hashlib.sha256(token).hexdigest()
async with deps.manual_create_session() as session:
query = sqlmodel.select(models.DbRefreshToken).where(models.DbRefreshToken.token_hash == token_hash)
token_model: models.DbRefreshToken = (await session.exec(query)).one_or_none()
return token_model
def validate_access_token(payload: dict) -> None:
"""Validate an access token payload."""
user_id = payload.get("user_id")
exp = payload.get("exp")
token_type = payload.get("type")
if not user_id or not exp:
raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="Invalid token")
if not token_type or token_type != "access":
raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail="Invalid token type")
if datetime.utcnow() >= datetime.fromtimestamp(exp):
raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="Token expired")
def validate_refresh_token(payload: dict, compare_user_id: str) -> None:
"""Validate a refresh token payload and confirm it corresponds to the correct user."""
user_id = payload.get("user_id")
exp = payload.get("exp")
token_type = payload.get("type")
if not exp or not user_id or user_id != compare_user_id:
raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="Invalid token")
if not token_type or token_type != "refresh":
raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail="Invalid token type")
if datetime.utcnow() >= datetime.fromtimestamp(exp):
raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail="Token expired")