-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauth.py
More file actions
442 lines (383 loc) · 15 KB
/
Copy pathauth.py
File metadata and controls
442 lines (383 loc) · 15 KB
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
from __future__ import annotations
import secrets
import time
from logging import getLogger
from uuid import uuid4
import aiohttp
import requests
from fastapi import APIRouter, Depends, HTTPException, Request, status
from fastapi.security import (
APIKeyCookie,
OAuth2PasswordBearer,
OAuth2PasswordRequestForm,
)
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel
from sqlmodel import Session, create_engine, select
from typing_extensions import Annotated, Any
from murfey.server.murfey_db import murfey_db, url
from murfey.util.api import url_path_for
from murfey.util.config import get_security_config
from murfey.util.db import MurfeyUser as User, Session as MurfeySession
# Set up logger
logger = getLogger("murfey.server.api.auth")
# Set up router
router = APIRouter(
prefix="/auth",
tags=["Authentication"],
)
# Set up variables used for authentication
security_config = get_security_config()
auth_url = security_config.auth_url
ALGORITHM = security_config.auth_algorithm or "HS256"
SECRET_KEY = security_config.auth_key or secrets.token_hex(32)
oauth2_scheme = (
OAuth2PasswordBearer(tokenUrl="auth/token")
if security_config.auth_type == "password"
else APIKeyCookie(name=security_config.cookie_key)
)
instrument_oauth2_scheme = (
OAuth2PasswordBearer(tokenUrl="auth/token")
if security_config.instrument_auth_type == "token"
else lambda *args, **kwargs: None
)
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
instrument_server_tokens: dict[float, dict] = {}
# Set up database engine
try:
_url = url(security_config)
engine = create_engine(_url)
except Exception:
engine = None
def hash_password(password: str) -> str:
return pwd_context.hash(password)
"""
=======================================================================================
VALIDATION FUNCTIONS
=======================================================================================
Functions and helpers used to validate incoming requests from both the client and
the frontend.
'validate_token()' and 'validate_instrument_token()' are imported in the other FastAPI
modules and attached as dependencies to the routers. They validate the tokens passed
around internally by Murfey to ensure that the request is valid.
'validate_instrument_server_session_access()' and 'validate_frontend_session_access()'
are used to verify the IDs of sessions ot be accessed, and are attached as dependencies
to them.
'validate_user_instrument_access()' is used to verify the instrument server name being
accessed by the frontend, and is attached as a dependency as well.
"""
# Essential headers used for authentication to forward along if present
AUTH_HEADERS = (
"authorization",
"x-auth-request-access-token",
)
def check_user(username: str) -> bool:
try:
with Session(engine) as murfey_db:
users = murfey_db.exec(select(User)).all()
except Exception:
return False
return username in [u.username for u in users]
async def submit_to_auth_endpoint(
url_subpath: str,
request: Request,
token: str,
) -> dict[str, Any]:
"""
Helper function to forward incoming requests to an authentication server
to verify that they are allowed to inspect the
"""
# Forward only essentials auth-related headers
headers = {
key: value
for key, value in dict(request.headers).items()
if key.lower() in AUTH_HEADERS
}
if security_config.auth_type == "password":
headers["authorization"] = f"Bearer {token}"
cookies = (
{security_config.cookie_key: token}
if security_config.auth_type == "cookie"
else {}
)
async with aiohttp.ClientSession(cookies=cookies) as session:
async with session.get(
f"{auth_url}/{url_subpath}",
headers=headers,
) as response:
success = response.status == 200
validation_outcome: dict[str, Any] = await response.json()
return validation_outcome if success and validation_outcome else {"valid": False}
async def validate_token(
token: Annotated[str, Depends(oauth2_scheme)],
request: Request,
):
"""
Used by the backend routers to validate requests coming in from frontend.
"""
try:
# Validate using auth URL if provided; will error if invalid
if auth_url:
if not (
await submit_to_auth_endpoint("validate_token", request, token)
).get("valid"):
raise JWTError
# If authenticating using cookies; an auth URL MUST be provided
else:
if security_config.auth_type == "cookie":
raise JWTError
# Validate using password
if security_config.auth_type == "password":
decoded_data = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
# Check that the user is present and is valid
if decoded_data.get("user"):
if not check_user(decoded_data["user"]):
raise JWTError
else:
raise JWTError
except JWTError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials from frontend",
headers={"WWW-Authenticate": "Bearer"},
)
return None
def validate_session_against_visit(session_id: int, visit: str):
"""
Checks that the session ID is associated with the claimed visit.
"""
with Session(engine) as murfey_db:
session_data = murfey_db.exec(
select(MurfeySession).where(MurfeySession.id == session_id)
).all()
if len(session_data) != 1:
return False
return visit == session_data[0].visit
async def validate_instrument_token(
token: Annotated[str, Depends(instrument_oauth2_scheme)],
):
"""
Used by the backend routers to check the incoming instrument server token.
"""
try:
# Validate using auth URL if provided
if security_config.instrument_auth_url:
async with aiohttp.ClientSession() as session:
headers = (
{}
if not security_config.instrument_auth_type
else {"Authorization": f"Bearer {token}"}
)
async with session.get(
f"{security_config.instrument_auth_url}/validate_token",
headers=headers,
) as response:
success = response.status == 200
validation_outcome = await response.json()
if not (success and validation_outcome.get("valid")):
raise JWTError
else:
# First, check if the token has expired
decoded_data = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
if expiry_time := decoded_data.get("expiry_time"):
if expiry_time < time.time():
raise JWTError
# Check that the decoded session corresponds to the visit
elif decoded_data.get("session") is not None:
if not validate_session_against_visit(
decoded_data["session"], decoded_data["visit"]
):
raise JWTError
# Verify 'user' token if enabled
elif security_config.allow_user_token:
if not decoded_data.get("user"):
raise JWTError
else:
raise JWTError
except JWTError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials from instrument",
headers={"WWW-Authenticate": "Bearer"},
)
return None
def get_visit_name(session_id: int) -> str:
with Session(engine) as murfey_db:
return (
murfey_db.exec(select(MurfeySession).where(MurfeySession.id == session_id))
.one()
.visit
)
async def validate_instrument_server_session_access(
session_id: int,
token: Annotated[str, Depends(instrument_oauth2_scheme)],
) -> int:
"""
Validates whether an instrument request can access information about this session
"""
visit_name = get_visit_name(session_id)
if security_config.instrument_auth_url:
async with aiohttp.ClientSession() as session:
headers = (
{}
if not security_config.instrument_auth_type
else {"Authorization": f"Bearer {token}"}
)
async with session.get(
f"{security_config.instrument_auth_url}/validate_visit_access/{visit_name}",
headers=headers,
) as response:
success = response.status == 200
validation_outcome = await response.json()
if not (success and validation_outcome.get("valid")):
logger.warning("Unauthorised visit access request from instrument")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="You do not have access to this visit",
headers={"WWW-Authenticate": "Bearer"},
)
return session_id
async def validate_frontend_session_access(
session_id: int,
request: Request,
token: Annotated[str, Depends(oauth2_scheme)],
) -> int:
"""
Validates whether a frontend request can access information about this session
"""
visit_name = get_visit_name(session_id)
if auth_url:
if not (
await submit_to_auth_endpoint(
f"validate_visit_access/{visit_name}",
request,
token,
)
).get("valid"):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="You do not have access to this visit",
headers={"WWW-Authenticate": "Bearer"},
)
return session_id
async def validate_user_instrument_access(
instrument_name: str,
request: Request,
token: Annotated[str, Depends(oauth2_scheme)],
) -> str:
"""
Validates whether a frontend request can access information about this instrument
"""
if auth_url:
if not (
await submit_to_auth_endpoint(
f"validate_instrument_access/{instrument_name}",
request,
token,
)
).get("valid"):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="You do not have access to this instrument",
headers={"WWW-Authenticate": "Bearer"},
)
return instrument_name
# Create annotated session ID and instrument name for endpoints that need to verify them
MurfeySessionIDInstrument = Annotated[
int, Depends(validate_instrument_server_session_access)
]
MurfeySessionIDFrontend = Annotated[int, Depends(validate_frontend_session_access)]
MurfeyInstrumentNameFrontend = Annotated[str, Depends(validate_user_instrument_access)]
"""
=======================================================================================
API ENDPOINTS AND HELPER FUNCTIONS/CLASSES
=======================================================================================
"""
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def validate_user(username: str, password: str) -> bool:
try:
with Session(engine) as murfey_db:
user = murfey_db.exec(select(User).where(User.username == username)).one()
except Exception:
return False
return verify_password(password, user.hashed_password)
def create_access_token(data: dict, token: str = "") -> str:
# If authenticating with password, auth URL needs a 'mint_session_token' endpoint
if security_config.auth_type == "password":
if auth_url and data.get("session"):
session_id = data["session"]
if not isinstance(session_id, int) and session_id > 0:
# Check the session ID is alphanumeric for security
raise ValueError("Session ID was invalid (not alphanumeric)")
minted_token_response = requests.get(
f"{auth_url}{url_path_for('auth.router', 'mint_session_token', session_id=session_id)}",
headers={"Authorization": f"Bearer {token}"},
)
if minted_token_response.status_code != 200:
raise RuntimeError(
f"Request received status code {minted_token_response.status_code} when trying to create session token"
)
return minted_token_response.json()["access_token"]
to_encode = data.copy()
# Make token for instrument
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
class Token(BaseModel):
access_token: str
token_type: str
@router.post("/token")
async def generate_token(
form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
) -> Token:
# Only generate a token if it's a password
if security_config.auth_type == "password":
if auth_url:
data = aiohttp.FormData()
data.add_field("username", form_data.username)
data.add_field("password", form_data.password)
async with aiohttp.ClientSession() as session:
async with session.post(
f"{auth_url}{url_path_for('auth.router', 'generate_token')}",
data=data,
) as response:
validated = response.status == 200
token = await response.json()
access_token = token.get("access_token")
else:
validated = validate_user(form_data.username, form_data.password)
access_token = create_access_token(
data={"user": form_data.username},
)
if not validated:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
return Token(access_token=access_token, token_type="bearer")
# Return empty token otherwise
return Token(access_token="", token_type="bearer")
@router.get("/sessions/{session_id}/token")
async def mint_session_token(session_id: MurfeySessionIDFrontend, db=murfey_db):
visit = (
db.exec(select(MurfeySession).where(MurfeySession.id == session_id)).one().visit
)
expiry_time = None
if security_config.session_token_timeout:
expiry_time = time.time() + security_config.session_token_timeout
token = create_access_token(
{
"session": session_id,
"visit": visit,
"uuid": str(uuid4()),
"expiry_time": expiry_time,
}
)
return Token(access_token=token, token_type="bearer")
@router.get("/validate_token")
async def simple_token_validation(
token: Annotated[str, Depends(validate_instrument_token)],
):
return {"valid": True}