auth.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. from __future__ import annotations
  2. import logging
  3. import os
  4. import secrets
  5. from datetime import datetime, timedelta, timezone
  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 func, 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 OSError 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
  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 OSError 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. # --- Slicer download tokens ---
  84. # Short-lived tokens for slicer protocol handlers that can't send auth headers.
  85. # Maps token → (resource_key, expiry). resource_key = "archive:{id}" or "library:{id}".
  86. _slicer_tokens: dict[str, tuple[str, datetime]] = {}
  87. SLICER_TOKEN_EXPIRE_MINUTES = 5
  88. def create_slicer_download_token(resource_type: str, resource_id: int) -> str:
  89. """Create a short-lived download token for slicer protocol handlers."""
  90. # Cleanup expired tokens
  91. now = datetime.now(timezone.utc)
  92. expired = [k for k, (_, exp) in _slicer_tokens.items() if exp < now]
  93. for k in expired:
  94. del _slicer_tokens[k]
  95. token = secrets.token_urlsafe(24)
  96. resource_key = f"{resource_type}:{resource_id}"
  97. _slicer_tokens[token] = (resource_key, now + timedelta(minutes=SLICER_TOKEN_EXPIRE_MINUTES))
  98. return token
  99. def verify_slicer_download_token(token: str, resource_type: str, resource_id: int) -> bool:
  100. """Verify a slicer download token is valid for the given resource."""
  101. entry = _slicer_tokens.get(token)
  102. if not entry:
  103. return False
  104. resource_key, expiry = entry
  105. if datetime.now(timezone.utc) > expiry:
  106. del _slicer_tokens[token]
  107. return False
  108. expected_key = f"{resource_type}:{resource_id}"
  109. if resource_key != expected_key:
  110. return False
  111. # Token is single-use
  112. del _slicer_tokens[token]
  113. return True
  114. # --- Camera stream tokens ---
  115. # Reusable tokens for camera stream/snapshot endpoints loaded via <img> tags.
  116. # Unlike slicer tokens, these are NOT single-use (streams reconnect on errors)
  117. # and have a longer expiry. Maps token → expiry.
  118. _camera_stream_tokens: dict[str, datetime] = {}
  119. CAMERA_STREAM_TOKEN_EXPIRE_MINUTES = 60
  120. def create_camera_stream_token() -> str:
  121. """Create a reusable token for camera stream/snapshot access."""
  122. now = datetime.now(timezone.utc)
  123. # Cleanup expired tokens
  124. expired = [k for k, exp in _camera_stream_tokens.items() if exp < now]
  125. for k in expired:
  126. del _camera_stream_tokens[k]
  127. token = secrets.token_urlsafe(24)
  128. _camera_stream_tokens[token] = now + timedelta(minutes=CAMERA_STREAM_TOKEN_EXPIRE_MINUTES)
  129. return token
  130. def verify_camera_stream_token(token: str) -> bool:
  131. """Verify a camera stream token is valid."""
  132. expiry = _camera_stream_tokens.get(token)
  133. if not expiry:
  134. return False
  135. if datetime.now(timezone.utc) > expiry:
  136. del _camera_stream_tokens[token]
  137. return False
  138. return True
  139. def verify_password(plain_password: str, hashed_password: str) -> bool:
  140. """Verify a password against a hash.
  141. Uses pbkdf2_sha256 which handles long passwords automatically.
  142. """
  143. return pwd_context.verify(plain_password, hashed_password)
  144. def get_password_hash(password: str) -> str:
  145. """Hash a password.
  146. Uses pbkdf2_sha256 which is secure and has no password length limit.
  147. """
  148. return pwd_context.hash(password)
  149. def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
  150. """Create a JWT access token."""
  151. to_encode = data.copy()
  152. if expires_delta:
  153. expire = datetime.now(timezone.utc) + expires_delta
  154. else:
  155. expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  156. to_encode.update({"exp": expire})
  157. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  158. return encoded_jwt
  159. async def get_user_by_username(db: AsyncSession, username: str) -> User | None:
  160. """Get a user by username (case-insensitive) with groups loaded for permission checks."""
  161. result = await db.execute(
  162. select(User).where(func.lower(User.username) == func.lower(username)).options(selectinload(User.groups))
  163. )
  164. return result.scalar_one_or_none()
  165. async def get_user_by_email(db: AsyncSession, email: str) -> User | None:
  166. """Get a user by email (case-insensitive) with groups loaded for permission checks."""
  167. result = await db.execute(
  168. select(User).where(func.lower(User.email) == func.lower(email)).options(selectinload(User.groups))
  169. )
  170. return result.scalar_one_or_none()
  171. async def authenticate_user(db: AsyncSession, username: str, password: str) -> User | None:
  172. """Authenticate a user by username and password.
  173. Username lookup is case-insensitive. Password is case-sensitive.
  174. """
  175. user = await get_user_by_username(db, username)
  176. if not user:
  177. return None
  178. if not verify_password(password, user.password_hash):
  179. return None
  180. if not user.is_active:
  181. return None
  182. return user
  183. async def authenticate_user_by_email(db: AsyncSession, email: str, password: str) -> User | None:
  184. """Authenticate a user by email and password.
  185. Email lookup is case-insensitive. Password is case-sensitive.
  186. """
  187. user = await get_user_by_email(db, email)
  188. if not user:
  189. return None
  190. if not verify_password(password, user.password_hash):
  191. return None
  192. if not user.is_active:
  193. return None
  194. return user
  195. async def is_auth_enabled(db: AsyncSession) -> bool:
  196. """Check if authentication is enabled."""
  197. try:
  198. result = await db.execute(select(Settings).where(Settings.key == "auth_enabled"))
  199. setting = result.scalar_one_or_none()
  200. if setting is None:
  201. return False
  202. return setting.value.lower() == "true"
  203. except Exception:
  204. # If settings table doesn't exist or query fails, assume auth is disabled
  205. return False
  206. async def _validate_api_key(db: AsyncSession, api_key_value: str) -> APIKey | None:
  207. """Validate an API key and return the APIKey object if valid, None otherwise.
  208. This is an internal helper used by auth functions to check API keys.
  209. """
  210. try:
  211. result = await db.execute(select(APIKey).where(APIKey.enabled.is_(True)))
  212. api_keys = result.scalars().all()
  213. for api_key in api_keys:
  214. if verify_password(api_key_value, api_key.key_hash):
  215. # Check expiration
  216. if api_key.expires_at:
  217. expires = api_key.expires_at
  218. if expires.tzinfo is None:
  219. expires = expires.replace(tzinfo=timezone.utc)
  220. if expires < datetime.now(timezone.utc):
  221. return None # Expired
  222. # Update last_used timestamp
  223. api_key.last_used = datetime.now(timezone.utc)
  224. await db.commit()
  225. return api_key
  226. except Exception as e:
  227. logger.warning("API key validation error: %s", e)
  228. return None
  229. async def get_current_user_optional(
  230. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  231. ) -> User | None:
  232. """Get the current authenticated user from JWT token, or None if not authenticated."""
  233. if credentials is None:
  234. return None
  235. try:
  236. token = credentials.credentials
  237. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  238. username: str = payload.get("sub")
  239. if username is None:
  240. return None
  241. except JWTError:
  242. return None
  243. async with async_session() as db:
  244. user = await get_user_by_username(db, username)
  245. if user is None or not user.is_active:
  246. return None
  247. return user
  248. async def get_current_user(
  249. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  250. ) -> User:
  251. """Get the current authenticated user from JWT token."""
  252. credentials_exception = HTTPException(
  253. status_code=status.HTTP_401_UNAUTHORIZED,
  254. detail="Could not validate credentials",
  255. headers={"WWW-Authenticate": "Bearer"},
  256. )
  257. if credentials is None:
  258. raise credentials_exception
  259. try:
  260. token = credentials.credentials
  261. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  262. username: str = payload.get("sub")
  263. if username is None:
  264. raise credentials_exception
  265. except JWTError:
  266. raise credentials_exception
  267. async with async_session() as db:
  268. user = await get_user_by_username(db, username)
  269. if user is None:
  270. raise credentials_exception
  271. if not user.is_active:
  272. raise HTTPException(
  273. status_code=status.HTTP_403_FORBIDDEN,
  274. detail="User account is disabled",
  275. )
  276. return user
  277. async def get_current_active_user(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  278. """Get the current active user (alias for clarity)."""
  279. return current_user
  280. async def require_auth_if_enabled(
  281. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  282. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  283. ) -> User | None:
  284. """Require authentication if auth is enabled, otherwise return None.
  285. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  286. (via X-API-Key header or Authorization: Bearer bb_xxx).
  287. """
  288. async with async_session() as db:
  289. auth_enabled = await is_auth_enabled(db)
  290. if not auth_enabled:
  291. return None
  292. # Check for API key first (X-API-Key header)
  293. if x_api_key:
  294. api_key = await _validate_api_key(db, x_api_key)
  295. if api_key:
  296. return None # API key valid, allow access
  297. # Check for Bearer token (could be JWT or API key)
  298. if credentials is not None:
  299. token = credentials.credentials
  300. # Check if it's an API key (starts with bb_)
  301. if token.startswith("bb_"):
  302. api_key = await _validate_api_key(db, token)
  303. if api_key:
  304. return None # API key valid, allow access
  305. raise HTTPException(
  306. status_code=status.HTTP_401_UNAUTHORIZED,
  307. detail="Invalid API key",
  308. headers={"WWW-Authenticate": "Bearer"},
  309. )
  310. # Otherwise treat as JWT
  311. try:
  312. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  313. username: str = payload.get("sub")
  314. if username is None:
  315. raise HTTPException(
  316. status_code=status.HTTP_401_UNAUTHORIZED,
  317. detail="Could not validate credentials",
  318. headers={"WWW-Authenticate": "Bearer"},
  319. )
  320. except JWTError:
  321. raise HTTPException(
  322. status_code=status.HTTP_401_UNAUTHORIZED,
  323. detail="Could not validate credentials",
  324. headers={"WWW-Authenticate": "Bearer"},
  325. )
  326. user = await get_user_by_username(db, username)
  327. if user is None or not user.is_active:
  328. raise HTTPException(
  329. status_code=status.HTTP_401_UNAUTHORIZED,
  330. detail="Could not validate credentials",
  331. headers={"WWW-Authenticate": "Bearer"},
  332. )
  333. return user
  334. # No credentials provided
  335. raise HTTPException(
  336. status_code=status.HTTP_401_UNAUTHORIZED,
  337. detail="Authentication required",
  338. headers={"WWW-Authenticate": "Bearer"},
  339. )
  340. def require_role(required_role: str):
  341. """Dependency factory for role-based access control."""
  342. async def role_checker(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  343. if current_user.role != required_role:
  344. raise HTTPException(
  345. status_code=status.HTTP_403_FORBIDDEN,
  346. detail=f"Requires {required_role} role",
  347. )
  348. return current_user
  349. return role_checker
  350. def require_admin_if_auth_enabled():
  351. """Dependency factory that requires admin role if auth is enabled."""
  352. async def admin_checker(
  353. current_user: Annotated[User | None, Depends(require_auth_if_enabled)] = None,
  354. ) -> User | None:
  355. if current_user is None:
  356. return None # Auth not enabled, allow access
  357. if current_user.role != "admin":
  358. raise HTTPException(
  359. status_code=status.HTTP_403_FORBIDDEN,
  360. detail="Requires admin role",
  361. )
  362. return current_user
  363. return admin_checker
  364. def generate_api_key() -> tuple[str, str, str]:
  365. """Generate a new API key.
  366. Returns:
  367. tuple: (full_key, key_hash, key_prefix)
  368. - full_key: The complete API key (only shown once on creation)
  369. - key_hash: Hashed version for storage and verification
  370. - key_prefix: First 8 characters for display purposes
  371. """
  372. # Generate a secure random API key (32 bytes = 64 hex characters)
  373. full_key = f"bb_{secrets.token_urlsafe(32)}"
  374. key_hash = get_password_hash(full_key)
  375. key_prefix = full_key[:8] + "..." if len(full_key) > 8 else full_key
  376. return full_key, key_hash, key_prefix
  377. async def get_api_key(
  378. authorization: Annotated[str | None, Header(alias="Authorization")] = None,
  379. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  380. db: AsyncSession = Depends(get_db),
  381. ) -> APIKey:
  382. """Get and validate API key from request headers.
  383. Checks both 'Authorization: Bearer <key>' and 'X-API-Key: <key>' headers.
  384. """
  385. api_key_value = None
  386. if x_api_key:
  387. api_key_value = x_api_key
  388. elif authorization and authorization.startswith("Bearer "):
  389. api_key_value = authorization.replace("Bearer ", "")
  390. if not api_key_value:
  391. raise HTTPException(
  392. status_code=status.HTTP_401_UNAUTHORIZED,
  393. detail="API key required. Provide 'X-API-Key' header or 'Authorization: Bearer <key>'",
  394. )
  395. # Get all API keys and check them
  396. result = await db.execute(select(APIKey).where(APIKey.enabled.is_(True)))
  397. api_keys = result.scalars().all()
  398. for api_key in api_keys:
  399. # Check if key matches (verify against hash)
  400. if verify_password(api_key_value, api_key.key_hash):
  401. # Check expiration
  402. if api_key.expires_at:
  403. expires = api_key.expires_at
  404. if expires.tzinfo is None:
  405. expires = expires.replace(tzinfo=timezone.utc)
  406. if expires < datetime.now(timezone.utc):
  407. raise HTTPException(
  408. status_code=status.HTTP_401_UNAUTHORIZED,
  409. detail="API key has expired",
  410. )
  411. # Update last_used timestamp
  412. api_key.last_used = datetime.now(timezone.utc)
  413. await db.commit()
  414. return api_key
  415. raise HTTPException(
  416. status_code=status.HTTP_401_UNAUTHORIZED,
  417. detail="Invalid API key",
  418. )
  419. def check_permission(api_key: APIKey, permission: str) -> None:
  420. """Check if API key has the required permission.
  421. Args:
  422. api_key: The API key object
  423. permission: One of 'queue', 'control_printer', 'read_status'
  424. Raises:
  425. HTTPException: If permission is not granted
  426. """
  427. permission_map = {
  428. "queue": "can_queue",
  429. "control_printer": "can_control_printer",
  430. "read_status": "can_read_status",
  431. }
  432. if permission not in permission_map:
  433. raise HTTPException(
  434. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  435. detail=f"Unknown permission: {permission}",
  436. )
  437. attr_name = permission_map[permission]
  438. if not getattr(api_key, attr_name, False):
  439. raise HTTPException(
  440. status_code=status.HTTP_403_FORBIDDEN,
  441. detail=f"API key does not have '{permission}' permission",
  442. )
  443. def check_printer_access(api_key: APIKey, printer_id: int) -> None:
  444. """Check if API key has access to the specified printer.
  445. Args:
  446. api_key: The API key object
  447. printer_id: The printer ID to check access for
  448. Raises:
  449. HTTPException: If access is denied
  450. """
  451. # None = global key, access to all printers
  452. if api_key.printer_ids is None:
  453. return
  454. # Empty list or printer not in allowed list = no access
  455. if printer_id not in api_key.printer_ids:
  456. raise HTTPException(
  457. status_code=status.HTTP_403_FORBIDDEN,
  458. detail=f"API key does not have access to printer {printer_id}",
  459. )
  460. # Convenience dependencies - these are functions that return Depends objects
  461. def RequireAdmin():
  462. """Dependency that requires admin role."""
  463. return Depends(require_role("admin"))
  464. def RequireAdminIfAuthEnabled():
  465. """Dependency that requires admin role if auth is enabled."""
  466. return Depends(require_admin_if_auth_enabled())
  467. def require_permission(*permissions: str | Permission):
  468. """Dependency factory that requires user to have ALL specified permissions.
  469. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  470. (via X-API-Key header or Authorization: Bearer bb_xxx).
  471. Args:
  472. *permissions: Permission strings or Permission enum values to require
  473. Returns:
  474. A dependency function that validates permissions
  475. """
  476. # Convert Permission enums to strings
  477. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  478. async def permission_checker(
  479. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  480. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  481. ) -> User | None:
  482. async with async_session() as db:
  483. # Check for API key first (X-API-Key header)
  484. if x_api_key:
  485. api_key = await _validate_api_key(db, x_api_key)
  486. if api_key:
  487. return None # API key valid, allow access
  488. credentials_exception = HTTPException(
  489. status_code=status.HTTP_401_UNAUTHORIZED,
  490. detail="Could not validate credentials",
  491. headers={"WWW-Authenticate": "Bearer"},
  492. )
  493. if credentials is None:
  494. raise credentials_exception
  495. token = credentials.credentials
  496. # Check if it's an API key (starts with bb_)
  497. if token.startswith("bb_"):
  498. api_key = await _validate_api_key(db, token)
  499. if api_key:
  500. return None # API key valid, allow access
  501. raise HTTPException(
  502. status_code=status.HTTP_401_UNAUTHORIZED,
  503. detail="Invalid API key",
  504. headers={"WWW-Authenticate": "Bearer"},
  505. )
  506. # Otherwise treat as JWT
  507. try:
  508. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  509. username: str = payload.get("sub")
  510. if username is None:
  511. raise credentials_exception
  512. except JWTError:
  513. raise credentials_exception
  514. user = await get_user_by_username(db, username)
  515. if user is None or not user.is_active:
  516. raise credentials_exception
  517. if not user.has_all_permissions(*perm_strings):
  518. raise HTTPException(
  519. status_code=status.HTTP_403_FORBIDDEN,
  520. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  521. )
  522. return user
  523. return permission_checker
  524. def require_permission_if_auth_enabled(*permissions: str | Permission):
  525. """Dependency factory that checks permissions only if auth is enabled.
  526. This provides backward compatibility - when auth is disabled, all access is allowed.
  527. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  528. (via X-API-Key header or Authorization: Bearer bb_xxx).
  529. Args:
  530. *permissions: Permission strings or Permission enum values to require
  531. Returns:
  532. A dependency function that validates permissions if auth is enabled
  533. """
  534. # Convert Permission enums to strings
  535. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  536. async def permission_checker(
  537. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  538. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  539. ) -> User | None:
  540. async with async_session() as db:
  541. auth_enabled = await is_auth_enabled(db)
  542. if not auth_enabled:
  543. return None # Auth disabled, allow access
  544. # Check for API key first (X-API-Key header)
  545. if x_api_key:
  546. api_key = await _validate_api_key(db, x_api_key)
  547. if api_key:
  548. return None # API key valid, allow access
  549. # Check for Bearer token (could be JWT or API key)
  550. if credentials is not None:
  551. token = credentials.credentials
  552. # Check if it's an API key (starts with bb_)
  553. if token.startswith("bb_"):
  554. api_key = await _validate_api_key(db, token)
  555. if api_key:
  556. return None # API key valid, allow access
  557. raise HTTPException(
  558. status_code=status.HTTP_401_UNAUTHORIZED,
  559. detail="Invalid API key",
  560. headers={"WWW-Authenticate": "Bearer"},
  561. )
  562. # Otherwise treat as JWT
  563. try:
  564. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  565. username: str = payload.get("sub")
  566. if username is None:
  567. raise HTTPException(
  568. status_code=status.HTTP_401_UNAUTHORIZED,
  569. detail="Could not validate credentials",
  570. headers={"WWW-Authenticate": "Bearer"},
  571. )
  572. except JWTError:
  573. raise HTTPException(
  574. status_code=status.HTTP_401_UNAUTHORIZED,
  575. detail="Could not validate credentials",
  576. headers={"WWW-Authenticate": "Bearer"},
  577. )
  578. user = await get_user_by_username(db, username)
  579. if user is None or not user.is_active:
  580. raise HTTPException(
  581. status_code=status.HTTP_401_UNAUTHORIZED,
  582. detail="Could not validate credentials",
  583. headers={"WWW-Authenticate": "Bearer"},
  584. )
  585. if not user.has_all_permissions(*perm_strings):
  586. raise HTTPException(
  587. status_code=status.HTTP_403_FORBIDDEN,
  588. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  589. )
  590. return user
  591. # No credentials provided
  592. raise HTTPException(
  593. status_code=status.HTTP_401_UNAUTHORIZED,
  594. detail="Authentication required",
  595. headers={"WWW-Authenticate": "Bearer"},
  596. )
  597. return permission_checker
  598. def RequirePermission(*permissions: str | Permission):
  599. """Convenience dependency that requires ALL specified permissions."""
  600. return Depends(require_permission(*permissions))
  601. def RequirePermissionIfAuthEnabled(*permissions: str | Permission):
  602. """Convenience dependency that requires permissions if auth is enabled."""
  603. return Depends(require_permission_if_auth_enabled(*permissions))
  604. def require_camera_stream_token_if_auth_enabled():
  605. """Dependency that validates a camera stream token query param when auth is enabled.
  606. Used for camera stream/snapshot endpoints that are loaded via <img> tags
  607. which cannot send Authorization headers. The frontend obtains a token from
  608. POST /printers/camera/stream-token and appends it as ?token=xxx.
  609. """
  610. async def checker(token: str | None = None) -> None:
  611. async with async_session() as db:
  612. if not await is_auth_enabled(db):
  613. return # Auth disabled, allow access
  614. if not token or not verify_camera_stream_token(token):
  615. raise HTTPException(
  616. status_code=status.HTTP_401_UNAUTHORIZED,
  617. detail="Valid camera stream token required. Obtain one from POST /api/v1/printers/camera/stream-token",
  618. )
  619. return checker
  620. RequireCameraStreamTokenIfAuthEnabled = Depends(require_camera_stream_token_if_auth_enabled())
  621. def require_ownership_permission(
  622. all_permission: str | Permission,
  623. own_permission: str | Permission,
  624. ):
  625. """Dependency factory for ownership-based permission checks.
  626. - User with `all_permission` can modify any item
  627. - User with `own_permission` can only modify items where created_by_id == user.id
  628. - Ownerless items (created_by_id = null) require `all_permission`
  629. - API keys (via X-API-Key header or Bearer bb_xxx) get full access (can_modify_all=True)
  630. Returns:
  631. A dependency function that returns (user, can_modify_all).
  632. - can_modify_all=True: user can modify any item
  633. - can_modify_all=False: user can only modify their own items
  634. """
  635. all_perm = all_permission.value if isinstance(all_permission, Permission) else all_permission
  636. own_perm = own_permission.value if isinstance(own_permission, Permission) else own_permission
  637. async def checker(
  638. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  639. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  640. ) -> tuple[User | None, bool]:
  641. """Returns (user, can_modify_all).
  642. - can_modify_all=True: user can modify any item
  643. - can_modify_all=False: user can only modify their own items
  644. """
  645. async with async_session() as db:
  646. auth_enabled = await is_auth_enabled(db)
  647. if not auth_enabled:
  648. return None, True # Auth disabled, allow all
  649. # Check for API key first (X-API-Key header)
  650. if x_api_key:
  651. api_key = await _validate_api_key(db, x_api_key)
  652. if api_key:
  653. return None, True # API key valid, allow all
  654. # Check for Bearer token (could be JWT or API key)
  655. if credentials is not None:
  656. token = credentials.credentials
  657. # Check if it's an API key (starts with bb_)
  658. if token.startswith("bb_"):
  659. api_key = await _validate_api_key(db, token)
  660. if api_key:
  661. return None, True # API key valid, allow all
  662. raise HTTPException(
  663. status_code=status.HTTP_401_UNAUTHORIZED,
  664. detail="Invalid API key",
  665. headers={"WWW-Authenticate": "Bearer"},
  666. )
  667. # Otherwise treat as JWT
  668. try:
  669. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  670. username: str = payload.get("sub")
  671. if username is None:
  672. raise HTTPException(
  673. status_code=status.HTTP_401_UNAUTHORIZED,
  674. detail="Could not validate credentials",
  675. headers={"WWW-Authenticate": "Bearer"},
  676. )
  677. except JWTError:
  678. raise HTTPException(
  679. status_code=status.HTTP_401_UNAUTHORIZED,
  680. detail="Could not validate credentials",
  681. headers={"WWW-Authenticate": "Bearer"},
  682. )
  683. user = await get_user_by_username(db, username)
  684. if user is None or not user.is_active:
  685. raise HTTPException(
  686. status_code=status.HTTP_401_UNAUTHORIZED,
  687. detail="Could not validate credentials",
  688. headers={"WWW-Authenticate": "Bearer"},
  689. )
  690. if user.has_permission(all_perm):
  691. return user, True
  692. if user.has_permission(own_perm):
  693. return user, False
  694. raise HTTPException(
  695. status_code=status.HTTP_403_FORBIDDEN,
  696. detail=f"Missing permission: {own_perm} or {all_perm}",
  697. )
  698. # No credentials provided
  699. raise HTTPException(
  700. status_code=status.HTTP_401_UNAUTHORIZED,
  701. detail="Authentication required",
  702. headers={"WWW-Authenticate": "Bearer"},
  703. )
  704. return checker