auth.py 21 KB

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