-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathauth_manager.py
More file actions
509 lines (363 loc) · 15.4 KB
/
auth_manager.py
File metadata and controls
509 lines (363 loc) · 15.4 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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
"""
Authentication Manager for Admin Panel
Multi-user JWT-based authentication with DB-backed users and role-based access.
Roles: guest, user, admin.
Session-based token management with in-memory cache and revocation support.
"""
import hashlib
import logging
import os
import secrets
from datetime import datetime, timedelta
from typing import Dict, Optional
from uuid import uuid4
import jwt
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from pydantic import BaseModel
from utils.password import verify_password as _verify_legacy_password
logger = logging.getLogger(__name__)
# Configuration
JWT_SECRET = os.getenv("ADMIN_JWT_SECRET", secrets.token_hex(32))
JWT_ALGORITHM = "HS256"
JWT_EXPIRATION_HOURS = int(os.getenv("ADMIN_JWT_EXPIRATION_HOURS", "24"))
# Legacy env-var credentials (fallback when users table is empty)
_LEGACY_USERNAME = os.getenv("ADMIN_USERNAME", "admin")
_LEGACY_PASSWORD_HASH: str = os.getenv("ADMIN_PASSWORD_HASH", "") or ""
if not _LEGACY_PASSWORD_HASH:
_LEGACY_PASSWORD_HASH = hashlib.sha256(b"admin").hexdigest()
# Deployment mode — hardware modules excluded in cloud mode
_DEPLOYMENT_MODE = os.getenv("DEPLOYMENT_MODE", "full").lower()
_CLOUD_EXCLUDED_MODULES = ("speech", "gsm")
# ============== Pydantic Models ==============
class LoginRequest(BaseModel):
username: str
password: str
class LoginResponse(BaseModel):
access_token: str
token_type: str = "bearer"
expires_in: int
class ChangePasswordRequest(BaseModel):
old_password: str
new_password: str
class UpdateProfileRequest(BaseModel):
display_name: Optional[str] = None
class TokenPayload(BaseModel):
sub: str # username
user_id: int # database user id
role: str
exp: int # expiration timestamp
iat: int # issued at timestamp
jti: str = "" # JWT ID for session tracking
workspace_id: int = 1 # backward compat: old tokens default to 1
class User(BaseModel):
id: int
username: str
role: str
workspace_id: int = 1
permissions: Dict[str, str] = {}
# ============== Security ==============
security = HTTPBearer(auto_error=False)
# ============== Session Cache ==============
class SessionCache:
"""In-memory cache mapping JTI → user_id for fast session validation."""
def __init__(self) -> None:
self._cache: Dict[str, int] = {} # jti → user_id
def get(self, jti: str) -> Optional[int]:
return self._cache.get(jti)
def put(self, jti: str, user_id: int) -> None:
self._cache[jti] = user_id
def remove(self, jti: str) -> None:
self._cache.pop(jti, None)
def remove_all_for_user(self, user_id: int) -> None:
to_remove = [jti for jti, uid in self._cache.items() if uid == user_id]
for jti in to_remove:
del self._cache[jti]
def size(self) -> int:
return len(self._cache)
_session_cache = SessionCache()
# ============== Permissions Cache ==============
class PermissionsCache:
"""In-memory cache mapping role_name → permissions dict."""
def __init__(self) -> None:
self._cache: Dict[str, Dict[str, str]] = {}
async def get(self, role_name: str) -> Dict[str, str]:
"""Get permissions for role, loading from DB on cache miss.
Returns a **copy** so callers can mutate (e.g. pop modules) without
corrupting the cached entry.
"""
if role_name not in self._cache:
from db.integration import async_role_manager
role = await async_role_manager.get_by_name(role_name)
self._cache[role_name] = role.get("permissions", {}) if role else {}
return dict(self._cache[role_name])
def invalidate(self, role_name: Optional[str] = None) -> None:
"""Clear cache. If role_name given, clear only that entry."""
if role_name:
self._cache.pop(role_name, None)
else:
self._cache.clear()
_permissions_cache = PermissionsCache()
# ============== Member Role Cache ==============
class MemberRoleCache:
"""In-memory cache: (user_id, workspace_id) → role_name."""
def __init__(self) -> None:
self._cache: Dict[tuple, str] = {}
def get(self, user_id: int, workspace_id: int) -> Optional[str]:
return self._cache.get((user_id, workspace_id))
def put(self, user_id: int, workspace_id: int, role_name: str) -> None:
self._cache[(user_id, workspace_id)] = role_name
def invalidate_user(self, user_id: int) -> None:
to_remove = [k for k in self._cache if k[0] == user_id]
for k in to_remove:
del self._cache[k]
def invalidate_workspace(self, workspace_id: int) -> None:
to_remove = [k for k in self._cache if k[1] == workspace_id]
for k in to_remove:
del self._cache[k]
_member_role_cache = MemberRoleCache()
# ============== Password Helpers ==============
# Centralized in utils/password.py. Legacy env-var fallback uses _verify_legacy_password.
# ============== Token Management ==============
def create_access_token(
username: str, role: str = "admin", user_id: int = 0, workspace_id: int = 1
) -> tuple[str, int, str]:
"""Create a JWT access token with a unique JTI.
Returns:
tuple: (token, expires_in_seconds, jti)
"""
now = datetime.utcnow()
expires = now + timedelta(hours=JWT_EXPIRATION_HOURS)
expires_in = int((expires - now).total_seconds())
jti = str(uuid4())
payload = {
"sub": username,
"user_id": user_id,
"role": role,
"workspace_id": workspace_id,
"exp": int(expires.timestamp()),
"iat": int(now.timestamp()),
"jti": jti,
}
token = jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
return token, expires_in, jti
def decode_token(token: str) -> Optional[TokenPayload]:
"""Decode and validate a JWT token."""
try:
payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
# Backward compat: old tokens may not have user_id
if "user_id" not in payload:
payload["user_id"] = 0
# Backward compat: old tokens may not have jti
if "jti" not in payload:
payload["jti"] = ""
# Backward compat: old tokens may not have workspace_id
if "workspace_id" not in payload:
payload["workspace_id"] = 1
return TokenPayload(**payload)
except jwt.ExpiredSignatureError:
logger.debug("Token expired")
return None
except jwt.InvalidTokenError as e:
logger.debug(f"Invalid token: {e}")
return None
# ============== Session Management ==============
async def create_session(
username: str,
role: str,
user_id: int,
ip: Optional[str],
user_agent: Optional[str],
workspace_id: int = 1,
) -> LoginResponse:
"""Create a new session: generate token, persist to DB, populate cache."""
from db.integration import async_session_manager
token, expires_in, jti = create_access_token(username, role, user_id, workspace_id)
expires_at = datetime.utcnow() + timedelta(seconds=expires_in)
await async_session_manager.create_session(
user_id=user_id,
jti=jti,
ip_address=ip,
user_agent=user_agent,
expires_at=expires_at,
workspace_id=workspace_id,
)
_session_cache.put(jti, user_id)
return LoginResponse(access_token=token, token_type="bearer", expires_in=expires_in)
async def revoke_session(jti: str) -> bool:
"""Revoke a single session by JTI."""
from db.integration import async_session_manager
_session_cache.remove(jti)
return await async_session_manager.revoke_by_jti(jti)
async def revoke_all_user_sessions(user_id: int) -> int:
"""Revoke all sessions for a user."""
from db.integration import async_session_manager
_session_cache.remove_all_for_user(user_id)
return await async_session_manager.revoke_all_for_user(user_id)
# ============== Authentication ==============
async def authenticate_user(username: str, password: str) -> Optional[User]:
"""Authenticate user against DB. Falls back to env-var admin if no DB users."""
try:
from db.integration import async_user_manager
user_data = await async_user_manager.authenticate(username, password)
if user_data:
return User(
id=user_data["id"],
username=user_data["username"],
role=user_data["role"],
)
# If DB auth failed, check if DB has any users at all
user_count = await async_user_manager.get_user_count()
if user_count > 0:
# DB has users, this is a real auth failure
return None
except Exception as e:
# DB error — do NOT fall through to legacy fallback (security: H3)
logger.error(f"DB auth error (not falling back to legacy): {e}")
return None
# Fallback: legacy env-var admin ONLY when no users in DB (first run)
if username == _LEGACY_USERNAME and _verify_legacy_password(password, _LEGACY_PASSWORD_HASH):
return User(id=0, username=username, role="admin")
return None
# ============== Session Validation Helpers ==============
async def _validate_session(token_payload: TokenPayload) -> Optional[User]:
"""Validate a decoded token against the session cache/DB.
Returns User if session is valid, None otherwise.
"""
jti = token_payload.jti
# Tokens without jti are pre-session-management tokens — reject
if not jti:
return None
user_id = token_payload.user_id
workspace_id = token_payload.workspace_id
# Check in-memory cache first
cached_uid = _session_cache.get(jti)
if cached_uid is not None:
if cached_uid != user_id:
return None
return User(
id=user_id,
username=token_payload.sub,
role=token_payload.role,
workspace_id=workspace_id,
)
# Cache miss — check DB
from db.integration import async_session_manager
db_session = await async_session_manager.get_by_jti(jti)
if db_session is None:
return None
if db_session.revoked_at is not None:
return None
# Internal bot tokens use user_id=0 which has no real User row — skip user check
if user_id != 0 and (db_session.user is None or not db_session.user.is_active):
return None
# Valid session — populate cache
_session_cache.put(jti, user_id)
return User(
id=user_id,
username=token_payload.sub,
role=token_payload.role,
workspace_id=workspace_id,
)
# ============== FastAPI Dependencies ==============
async def get_current_user(
credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
) -> User:
"""Dependency to get the current authenticated user."""
if credentials is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
token_payload = decode_token(credentials.credentials)
if token_payload is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired token",
headers={"WWW-Authenticate": "Bearer"},
)
user = await _validate_session(token_payload)
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Session revoked or user deactivated",
headers={"WWW-Authenticate": "Bearer"},
)
return user
async def get_optional_user(
credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
) -> Optional[User]:
"""Dependency to get the current user if authenticated, None otherwise."""
if credentials is None:
return None
token_payload = decode_token(credentials.credentials)
if token_payload is None:
return None
return await _validate_session(token_payload)
def require_permission(module: str, min_level: str):
"""FastAPI Depends factory: checks user has >= min_level for module."""
async def _dependency(user: User = Depends(get_current_user)) -> User:
perms = await get_user_permissions(user)
user.permissions = perms
user_level = perms.get(module, "")
if not level_gte(user_level, min_level):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Permission denied: requires {module}:{min_level}",
)
return user
return _dependency
# ============== RBAC Helpers ==============
_LEVEL_ORDER = {"view": 1, "edit": 2, "manage": 3}
def level_gte(user_level: str, required_level: str) -> bool:
"""Check if user_level is >= required_level in the permission hierarchy."""
return _LEVEL_ORDER.get(user_level, 0) >= _LEVEL_ORDER.get(required_level, 0)
def user_has_level(user: User, module: str, min_level: str) -> bool:
"""Check if user has >= min_level for module. Requires permissions pre-loaded."""
return level_gte(user.permissions.get(module, ""), min_level)
def workspace_context(user: User, module: str) -> tuple[Optional[int], int]:
"""Extract (owner_id, workspace_id) from user for repository calls.
Returns:
(owner_id, workspace_id) — owner_id is None for managers (manage-level),
workspace_id is always set from user's JWT.
Usage in routers::
owner_id, workspace_id = workspace_context(user, "chat")
result = await manager.list(..., owner_id=owner_id, workspace_id=workspace_id)
"""
owner_id = None if user_has_level(user, module, "manage") else user.id
return owner_id, user.workspace_id
async def get_user_permissions(user: User) -> Dict[str, str]:
"""Get permissions dict for user via workspace_members lookup. Uses cache.
In cloud deployment mode, hardware-only modules (speech, gsm) are removed
from the result. The ``system`` module is kept — it covers logs and
finetune endpoints that are available in cloud mode.
"""
# Internal bot users (user_id=0) with admin role get full manage access
if user.id == 0 and user.role == "admin":
return dict.fromkeys(("chat", "bots", "widgets", "llm", "tts", "system"), "manage")
role_name = _member_role_cache.get(user.id, user.workspace_id)
if role_name is None:
from db.integration import async_workspace_manager
role_name = await async_workspace_manager.get_member_role_name(user.id, user.workspace_id)
if role_name is None:
role_name = "viewer" # safe fallback
_member_role_cache.put(user.id, user.workspace_id, role_name)
perms = await _permissions_cache.get(role_name)
# Filter out hardware-only modules in cloud deployment mode
if _DEPLOYMENT_MODE == "cloud":
for module in _CLOUD_EXCLUDED_MODULES:
perms.pop(module, None)
return perms
def invalidate_permissions_cache(role_name: Optional[str] = None) -> None:
"""Clear permissions cache. Called when roles are modified."""
_permissions_cache.invalidate(role_name)
# ============== Status ==============
AUTH_ENABLED = os.getenv("ADMIN_AUTH_ENABLED", "true").lower() in ("true", "1", "yes")
def get_auth_status() -> Dict:
"""Get current auth configuration status."""
return {
"enabled": AUTH_ENABLED,
"jwt_expiration_hours": JWT_EXPIRATION_HOURS,
"active_sessions": _session_cache.size(),
}