auth.py 32 KB

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