auth.py 21 KB

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