auth.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. from __future__ import annotations
  2. import logging
  3. import os
  4. import secrets
  5. from datetime import datetime, timedelta
  6. from pathlib import Path
  7. from typing import Annotated
  8. import jwt
  9. from fastapi import Depends, Header, HTTPException, status
  10. from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
  11. from jwt.exceptions import PyJWTError as JWTError
  12. from passlib.context import CryptContext
  13. from sqlalchemy import select
  14. from sqlalchemy.ext.asyncio import AsyncSession
  15. from sqlalchemy.orm import selectinload
  16. from backend.app.core.database import async_session, get_db
  17. from backend.app.core.permissions import Permission
  18. from backend.app.models.api_key import APIKey
  19. from backend.app.models.settings import Settings
  20. from backend.app.models.user import User
  21. logger = logging.getLogger(__name__)
  22. # Password hashing
  23. # Use pbkdf2_sha256 instead of bcrypt to avoid 72-byte limit and passlib initialization issues
  24. # pbkdf2_sha256 is a secure password hashing algorithm without bcrypt's limitations
  25. pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto")
  26. def _get_jwt_secret() -> str:
  27. """Get the JWT secret key from environment, file, or generate a new one.
  28. Priority:
  29. 1. JWT_SECRET_KEY environment variable
  30. 2. .jwt_secret file in data directory
  31. 3. Generate new random secret and save to file
  32. Returns:
  33. The JWT secret key
  34. """
  35. # 1. Check environment variable first
  36. env_secret = os.environ.get("JWT_SECRET_KEY")
  37. if env_secret:
  38. logger.info("Using JWT secret from JWT_SECRET_KEY environment variable")
  39. return env_secret
  40. # 2. Check for secret file in data directory
  41. # Use DATA_DIR env var (same as rest of app), fallback to data/ subdirectory
  42. data_dir_env = os.environ.get("DATA_DIR")
  43. if data_dir_env:
  44. data_dir = Path(data_dir_env)
  45. else:
  46. # Fallback to data/ subdirectory under project root (not project root itself!)
  47. data_dir = Path(__file__).parent.parent.parent.parent / "data"
  48. secret_file = data_dir / ".jwt_secret"
  49. if secret_file.exists():
  50. try:
  51. secret = secret_file.read_text().strip()
  52. if secret and len(secret) >= 32:
  53. logger.info("Using JWT secret from %s", secret_file)
  54. return secret
  55. except Exception as e:
  56. logger.warning("Failed to read JWT secret file: %s", e)
  57. # 3. Generate new random secret
  58. new_secret = secrets.token_urlsafe(64)
  59. # Try to save it
  60. try:
  61. data_dir.mkdir(parents=True, exist_ok=True)
  62. # Note: CodeQL flags this as "clear-text storage of sensitive information" but this is
  63. # intentional and secure - JWT secrets must be readable by the app, we set 0600 permissions,
  64. # and this is standard practice for self-hosted applications (same as .env files).
  65. secret_file.write_text(new_secret) # nosec B105 - intentional secure storage
  66. # Restrict permissions (owner read/write only)
  67. secret_file.chmod(0o600)
  68. logger.info("Generated new JWT secret and saved to %s", secret_file)
  69. except Exception as e:
  70. logger.warning(
  71. "Could not save JWT secret to file (%s). "
  72. "Secret will be regenerated on restart, invalidating existing tokens. "
  73. "Set JWT_SECRET_KEY environment variable for persistence.",
  74. e,
  75. )
  76. return new_secret
  77. # JWT settings
  78. SECRET_KEY = _get_jwt_secret()
  79. ALGORITHM = "HS256"
  80. ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # 7 days
  81. # HTTP Bearer token
  82. security = HTTPBearer(auto_error=False)
  83. def verify_password(plain_password: str, hashed_password: str) -> bool:
  84. """Verify a password against a hash.
  85. Uses pbkdf2_sha256 which handles long passwords automatically.
  86. """
  87. return pwd_context.verify(plain_password, hashed_password)
  88. def get_password_hash(password: str) -> str:
  89. """Hash a password.
  90. Uses pbkdf2_sha256 which is secure and has no password length limit.
  91. """
  92. return pwd_context.hash(password)
  93. def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
  94. """Create a JWT access token."""
  95. to_encode = data.copy()
  96. if expires_delta:
  97. expire = datetime.utcnow() + expires_delta
  98. else:
  99. expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  100. to_encode.update({"exp": expire})
  101. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  102. return encoded_jwt
  103. async def get_user_by_username(db: AsyncSession, username: str) -> User | None:
  104. """Get a user by username with groups loaded for permission checks."""
  105. result = await db.execute(select(User).where(User.username == username).options(selectinload(User.groups)))
  106. return result.scalar_one_or_none()
  107. async def authenticate_user(db: AsyncSession, username: str, password: str) -> User | None:
  108. """Authenticate a user by username and password."""
  109. user = await get_user_by_username(db, username)
  110. if not user:
  111. return None
  112. if not verify_password(password, user.password_hash):
  113. return None
  114. if not user.is_active:
  115. return None
  116. return user
  117. async def is_auth_enabled(db: AsyncSession) -> bool:
  118. """Check if authentication is enabled."""
  119. try:
  120. result = await db.execute(select(Settings).where(Settings.key == "auth_enabled"))
  121. setting = result.scalar_one_or_none()
  122. if setting is None:
  123. return False
  124. return setting.value.lower() == "true"
  125. except Exception:
  126. # If settings table doesn't exist or query fails, assume auth is disabled
  127. return False
  128. async def get_current_user_optional(
  129. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  130. ) -> User | None:
  131. """Get the current authenticated user from JWT token, or None if not authenticated."""
  132. if credentials is None:
  133. return None
  134. try:
  135. token = credentials.credentials
  136. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  137. username: str = payload.get("sub")
  138. if username is None:
  139. return None
  140. except JWTError:
  141. return None
  142. async with async_session() as db:
  143. user = await get_user_by_username(db, username)
  144. if user is None or not user.is_active:
  145. return None
  146. return user
  147. async def get_current_user(
  148. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  149. ) -> User:
  150. """Get the current authenticated user from JWT token."""
  151. credentials_exception = HTTPException(
  152. status_code=status.HTTP_401_UNAUTHORIZED,
  153. detail="Could not validate credentials",
  154. headers={"WWW-Authenticate": "Bearer"},
  155. )
  156. if credentials is None:
  157. raise credentials_exception
  158. try:
  159. token = credentials.credentials
  160. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  161. username: str = payload.get("sub")
  162. if username is None:
  163. raise credentials_exception
  164. except JWTError:
  165. raise credentials_exception
  166. async with async_session() as db:
  167. user = await get_user_by_username(db, username)
  168. if user is None:
  169. raise credentials_exception
  170. if not user.is_active:
  171. raise HTTPException(
  172. status_code=status.HTTP_403_FORBIDDEN,
  173. detail="User account is disabled",
  174. )
  175. return user
  176. async def get_current_active_user(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  177. """Get the current active user (alias for clarity)."""
  178. return current_user
  179. async def require_auth_if_enabled(
  180. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  181. ) -> User | None:
  182. """Require authentication if auth is enabled, otherwise return None."""
  183. async with async_session() as db:
  184. auth_enabled = await is_auth_enabled(db)
  185. if not auth_enabled:
  186. return None
  187. if credentials is None:
  188. raise HTTPException(
  189. status_code=status.HTTP_401_UNAUTHORIZED,
  190. detail="Authentication required",
  191. headers={"WWW-Authenticate": "Bearer"},
  192. )
  193. try:
  194. token = credentials.credentials
  195. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  196. username: str = payload.get("sub")
  197. if username is None:
  198. raise HTTPException(
  199. status_code=status.HTTP_401_UNAUTHORIZED,
  200. detail="Could not validate credentials",
  201. headers={"WWW-Authenticate": "Bearer"},
  202. )
  203. except JWTError:
  204. raise HTTPException(
  205. status_code=status.HTTP_401_UNAUTHORIZED,
  206. detail="Could not validate credentials",
  207. headers={"WWW-Authenticate": "Bearer"},
  208. )
  209. user = await get_user_by_username(db, username)
  210. if user is None or not user.is_active:
  211. raise HTTPException(
  212. status_code=status.HTTP_401_UNAUTHORIZED,
  213. detail="Could not validate credentials",
  214. headers={"WWW-Authenticate": "Bearer"},
  215. )
  216. return user
  217. def require_role(required_role: str):
  218. """Dependency factory for role-based access control."""
  219. async def role_checker(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  220. if current_user.role != required_role:
  221. raise HTTPException(
  222. status_code=status.HTTP_403_FORBIDDEN,
  223. detail=f"Requires {required_role} role",
  224. )
  225. return current_user
  226. return role_checker
  227. def require_admin_if_auth_enabled():
  228. """Dependency factory that requires admin role if auth is enabled."""
  229. async def admin_checker(
  230. current_user: Annotated[User | None, Depends(require_auth_if_enabled)] = None,
  231. ) -> User | None:
  232. if current_user is None:
  233. return None # Auth not enabled, allow access
  234. if current_user.role != "admin":
  235. raise HTTPException(
  236. status_code=status.HTTP_403_FORBIDDEN,
  237. detail="Requires admin role",
  238. )
  239. return current_user
  240. return admin_checker
  241. def generate_api_key() -> tuple[str, str, str]:
  242. """Generate a new API key.
  243. Returns:
  244. tuple: (full_key, key_hash, key_prefix)
  245. - full_key: The complete API key (only shown once on creation)
  246. - key_hash: Hashed version for storage and verification
  247. - key_prefix: First 8 characters for display purposes
  248. """
  249. # Generate a secure random API key (32 bytes = 64 hex characters)
  250. full_key = f"bb_{secrets.token_urlsafe(32)}"
  251. key_hash = get_password_hash(full_key)
  252. key_prefix = full_key[:8] + "..." if len(full_key) > 8 else full_key
  253. return full_key, key_hash, key_prefix
  254. async def get_api_key(
  255. authorization: Annotated[str | None, Header(alias="Authorization")] = None,
  256. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  257. db: AsyncSession = Depends(get_db),
  258. ) -> APIKey:
  259. """Get and validate API key from request headers.
  260. Checks both 'Authorization: Bearer <key>' and 'X-API-Key: <key>' headers.
  261. """
  262. api_key_value = None
  263. if x_api_key:
  264. api_key_value = x_api_key
  265. elif authorization and authorization.startswith("Bearer "):
  266. api_key_value = authorization.replace("Bearer ", "")
  267. if not api_key_value:
  268. raise HTTPException(
  269. status_code=status.HTTP_401_UNAUTHORIZED,
  270. detail="API key required. Provide 'X-API-Key' header or 'Authorization: Bearer <key>'",
  271. )
  272. # Get all API keys and check them
  273. result = await db.execute(select(APIKey).where(APIKey.enabled.is_(True)))
  274. api_keys = result.scalars().all()
  275. for api_key in api_keys:
  276. # Check if key matches (verify against hash)
  277. if verify_password(api_key_value, api_key.key_hash):
  278. # Check expiration
  279. if api_key.expires_at and api_key.expires_at < datetime.now():
  280. raise HTTPException(
  281. status_code=status.HTTP_401_UNAUTHORIZED,
  282. detail="API key has expired",
  283. )
  284. # Update last_used timestamp
  285. api_key.last_used = datetime.now()
  286. await db.commit()
  287. return api_key
  288. raise HTTPException(
  289. status_code=status.HTTP_401_UNAUTHORIZED,
  290. detail="Invalid API key",
  291. )
  292. def check_permission(api_key: APIKey, permission: str) -> None:
  293. """Check if API key has the required permission.
  294. Args:
  295. api_key: The API key object
  296. permission: One of 'queue', 'control_printer', 'read_status'
  297. Raises:
  298. HTTPException: If permission is not granted
  299. """
  300. permission_map = {
  301. "queue": "can_queue",
  302. "control_printer": "can_control_printer",
  303. "read_status": "can_read_status",
  304. }
  305. if permission not in permission_map:
  306. raise HTTPException(
  307. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  308. detail=f"Unknown permission: {permission}",
  309. )
  310. attr_name = permission_map[permission]
  311. if not getattr(api_key, attr_name, False):
  312. raise HTTPException(
  313. status_code=status.HTTP_403_FORBIDDEN,
  314. detail=f"API key does not have '{permission}' permission",
  315. )
  316. def check_printer_access(api_key: APIKey, printer_id: int) -> None:
  317. """Check if API key has access to the specified printer.
  318. Args:
  319. api_key: The API key object
  320. printer_id: The printer ID to check access for
  321. Raises:
  322. HTTPException: If access is denied
  323. """
  324. # If printer_ids is None or empty, access to all printers
  325. if api_key.printer_ids is None or len(api_key.printer_ids) == 0:
  326. return
  327. # Check if printer_id is in allowed list
  328. if printer_id not in api_key.printer_ids:
  329. raise HTTPException(
  330. status_code=status.HTTP_403_FORBIDDEN,
  331. detail=f"API key does not have access to printer {printer_id}",
  332. )
  333. # Convenience dependencies - these are functions that return Depends objects
  334. def RequireAdmin():
  335. """Dependency that requires admin role."""
  336. return Depends(require_role("admin"))
  337. def RequireAdminIfAuthEnabled():
  338. """Dependency that requires admin role if auth is enabled."""
  339. return Depends(require_admin_if_auth_enabled())
  340. def require_permission(*permissions: str | Permission):
  341. """Dependency factory that requires user to have ALL specified permissions.
  342. Args:
  343. *permissions: Permission strings or Permission enum values to require
  344. Returns:
  345. A dependency function that validates permissions
  346. """
  347. # Convert Permission enums to strings
  348. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  349. async def permission_checker(
  350. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  351. ) -> User:
  352. credentials_exception = HTTPException(
  353. status_code=status.HTTP_401_UNAUTHORIZED,
  354. detail="Could not validate credentials",
  355. headers={"WWW-Authenticate": "Bearer"},
  356. )
  357. if credentials is None:
  358. raise credentials_exception
  359. try:
  360. token = credentials.credentials
  361. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  362. username: str = payload.get("sub")
  363. if username is None:
  364. raise credentials_exception
  365. except JWTError:
  366. raise credentials_exception
  367. async with async_session() as db:
  368. user = await get_user_by_username(db, username)
  369. if user is None or not user.is_active:
  370. raise credentials_exception
  371. if not user.has_all_permissions(*perm_strings):
  372. raise HTTPException(
  373. status_code=status.HTTP_403_FORBIDDEN,
  374. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  375. )
  376. return user
  377. return permission_checker
  378. def require_permission_if_auth_enabled(*permissions: str | Permission):
  379. """Dependency factory that checks permissions only if auth is enabled.
  380. This provides backward compatibility - when auth is disabled, all access is allowed.
  381. Args:
  382. *permissions: Permission strings or Permission enum values to require
  383. Returns:
  384. A dependency function that validates permissions if auth is enabled
  385. """
  386. # Convert Permission enums to strings
  387. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  388. async def permission_checker(
  389. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  390. ) -> User | None:
  391. async with async_session() as db:
  392. auth_enabled = await is_auth_enabled(db)
  393. if not auth_enabled:
  394. return None # Auth disabled, allow access
  395. if credentials is None:
  396. raise HTTPException(
  397. status_code=status.HTTP_401_UNAUTHORIZED,
  398. detail="Authentication required",
  399. headers={"WWW-Authenticate": "Bearer"},
  400. )
  401. try:
  402. token = credentials.credentials
  403. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  404. username: str = payload.get("sub")
  405. if username is None:
  406. raise HTTPException(
  407. status_code=status.HTTP_401_UNAUTHORIZED,
  408. detail="Could not validate credentials",
  409. headers={"WWW-Authenticate": "Bearer"},
  410. )
  411. except JWTError:
  412. raise HTTPException(
  413. status_code=status.HTTP_401_UNAUTHORIZED,
  414. detail="Could not validate credentials",
  415. headers={"WWW-Authenticate": "Bearer"},
  416. )
  417. user = await get_user_by_username(db, username)
  418. if user is None or not user.is_active:
  419. raise HTTPException(
  420. status_code=status.HTTP_401_UNAUTHORIZED,
  421. detail="Could not validate credentials",
  422. headers={"WWW-Authenticate": "Bearer"},
  423. )
  424. if not user.has_all_permissions(*perm_strings):
  425. raise HTTPException(
  426. status_code=status.HTTP_403_FORBIDDEN,
  427. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  428. )
  429. return user
  430. return permission_checker
  431. def RequirePermission(*permissions: str | Permission):
  432. """Convenience dependency that requires ALL specified permissions."""
  433. return Depends(require_permission(*permissions))
  434. def RequirePermissionIfAuthEnabled(*permissions: str | Permission):
  435. """Convenience dependency that requires permissions if auth is enabled."""
  436. return Depends(require_permission_if_auth_enabled(*permissions))
  437. def require_ownership_permission(
  438. all_permission: str | Permission,
  439. own_permission: str | Permission,
  440. ):
  441. """Dependency factory for ownership-based permission checks.
  442. - User with `all_permission` can modify any item
  443. - User with `own_permission` can only modify items where created_by_id == user.id
  444. - Ownerless items (created_by_id = null) require `all_permission`
  445. Returns:
  446. A dependency function that returns (user, can_modify_all).
  447. - can_modify_all=True: user can modify any item
  448. - can_modify_all=False: user can only modify their own items
  449. """
  450. all_perm = all_permission.value if isinstance(all_permission, Permission) else all_permission
  451. own_perm = own_permission.value if isinstance(own_permission, Permission) else own_permission
  452. async def checker(
  453. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  454. ) -> tuple[User | None, bool]:
  455. """Returns (user, can_modify_all).
  456. - can_modify_all=True: user can modify any item
  457. - can_modify_all=False: user can only modify their own items
  458. """
  459. async with async_session() as db:
  460. auth_enabled = await is_auth_enabled(db)
  461. if not auth_enabled:
  462. return None, True # Auth disabled, allow all
  463. if credentials is None:
  464. raise HTTPException(
  465. status_code=status.HTTP_401_UNAUTHORIZED,
  466. detail="Authentication required",
  467. headers={"WWW-Authenticate": "Bearer"},
  468. )
  469. try:
  470. token = credentials.credentials
  471. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  472. username: str = payload.get("sub")
  473. if username is None:
  474. raise HTTPException(
  475. status_code=status.HTTP_401_UNAUTHORIZED,
  476. detail="Could not validate credentials",
  477. headers={"WWW-Authenticate": "Bearer"},
  478. )
  479. except JWTError:
  480. raise HTTPException(
  481. status_code=status.HTTP_401_UNAUTHORIZED,
  482. detail="Could not validate credentials",
  483. headers={"WWW-Authenticate": "Bearer"},
  484. )
  485. user = await get_user_by_username(db, username)
  486. if user is None or not user.is_active:
  487. raise HTTPException(
  488. status_code=status.HTTP_401_UNAUTHORIZED,
  489. detail="Could not validate credentials",
  490. headers={"WWW-Authenticate": "Bearer"},
  491. )
  492. if user.has_permission(all_perm):
  493. return user, True
  494. if user.has_permission(own_perm):
  495. return user, False
  496. raise HTTPException(
  497. status_code=status.HTTP_403_FORBIDDEN,
  498. detail=f"Missing permission: {own_perm} or {all_perm}",
  499. )
  500. return checker