auth.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  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 delete, 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.auth_ephemeral import AuthEphemeralToken, TokenType
  20. from backend.app.models.settings import Settings
  21. from backend.app.models.user import User
  22. logger = logging.getLogger(__name__)
  23. # Permissions that cannot be accessed via API key.
  24. # API keys are limited to device/inventory operations. The following capabilities
  25. # are restricted to fully-authenticated users: user/group/API-key management,
  26. # settings read/backup/restore, firmware updates, and GitHub-backed backup/restore.
  27. _APIKEY_DENIED_PERMISSIONS: frozenset[Permission] = frozenset(
  28. {
  29. Permission.SETTINGS_READ,
  30. Permission.SETTINGS_UPDATE,
  31. Permission.SETTINGS_BACKUP,
  32. Permission.SETTINGS_RESTORE,
  33. Permission.USERS_READ,
  34. Permission.USERS_CREATE,
  35. Permission.USERS_UPDATE,
  36. Permission.USERS_DELETE,
  37. Permission.GROUPS_READ,
  38. Permission.GROUPS_CREATE,
  39. Permission.GROUPS_UPDATE,
  40. Permission.GROUPS_DELETE,
  41. Permission.API_KEYS_CREATE,
  42. Permission.API_KEYS_UPDATE,
  43. Permission.API_KEYS_DELETE,
  44. Permission.API_KEYS_READ,
  45. Permission.GITHUB_BACKUP,
  46. Permission.GITHUB_RESTORE,
  47. Permission.FIRMWARE_UPDATE,
  48. }
  49. )
  50. def _check_apikey_permissions(perm_strings: list[str]) -> None:
  51. """Raise 403 if any required permission is admin-only (not accessible via API key)."""
  52. denied = _APIKEY_DENIED_PERMISSIONS.intersection(perm_strings)
  53. if denied:
  54. raise HTTPException(
  55. status_code=status.HTTP_403_FORBIDDEN,
  56. detail="API keys cannot be used for administrative operations",
  57. )
  58. # Password hashing
  59. # Use pbkdf2_sha256 instead of bcrypt to avoid 72-byte limit and passlib initialization issues
  60. # pbkdf2_sha256 is a secure password hashing algorithm without bcrypt's limitations
  61. pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto")
  62. def _get_jwt_secret() -> str:
  63. """Get the JWT secret key from environment, file, or generate a new one.
  64. Priority:
  65. 1. JWT_SECRET_KEY environment variable
  66. 2. .jwt_secret file in data directory
  67. 3. Generate new random secret and save to file
  68. Returns:
  69. The JWT secret key
  70. """
  71. # 1. Check environment variable first
  72. env_secret = os.environ.get("JWT_SECRET_KEY")
  73. if env_secret:
  74. logger.info("Using JWT secret from JWT_SECRET_KEY environment variable")
  75. return env_secret
  76. # 2. Check for secret file in data directory
  77. # Use DATA_DIR env var (same as rest of app), fallback to data/ subdirectory
  78. data_dir_env = os.environ.get("DATA_DIR")
  79. if data_dir_env:
  80. data_dir = Path(data_dir_env)
  81. else:
  82. # Fallback to data/ subdirectory under project root (not project root itself!)
  83. data_dir = Path(__file__).parent.parent.parent.parent / "data"
  84. secret_file = data_dir / ".jwt_secret"
  85. if secret_file.exists():
  86. try:
  87. secret = secret_file.read_text().strip()
  88. if secret and len(secret) >= 32:
  89. logger.info("Using JWT secret from %s", secret_file)
  90. return secret
  91. except OSError as e:
  92. logger.warning("Failed to read JWT secret file: %s", e)
  93. # 3. Generate new random secret
  94. new_secret = secrets.token_urlsafe(64)
  95. # Try to save it
  96. try:
  97. data_dir.mkdir(parents=True, exist_ok=True)
  98. # Note: CodeQL flags this as "clear-text storage of sensitive information" but this is
  99. # intentional and secure - JWT secrets must be readable by the app, we set 0600 permissions,
  100. # and this is standard practice for self-hosted applications (same as .env files).
  101. secret_file.write_text(new_secret) # nosec B105
  102. # Restrict permissions (owner read/write only)
  103. secret_file.chmod(0o600)
  104. logger.info("Generated new JWT secret and saved to %s", secret_file)
  105. except OSError as e:
  106. logger.warning(
  107. "Could not save JWT secret to file (%s). "
  108. "Secret will be regenerated on restart, invalidating existing tokens. "
  109. "Set JWT_SECRET_KEY environment variable for persistence.",
  110. e,
  111. )
  112. return new_secret
  113. # JWT settings
  114. SECRET_KEY = _get_jwt_secret()
  115. ALGORITHM = "HS256"
  116. ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 # 24 hours (M-2: reduced from 7 days)
  117. # HTTP Bearer token
  118. security = HTTPBearer(auto_error=False)
  119. # --- Slicer download tokens ---
  120. # Short-lived, single-use tokens for slicer protocol handlers that can't send
  121. # auth headers. Stored in AuthEphemeralToken (token_type=TokenType.SLICER_DOWNLOAD)
  122. # so they survive server restarts and work in multi-worker deployments (M-3).
  123. SLICER_TOKEN_EXPIRE_MINUTES = 5
  124. async def create_slicer_download_token(resource_type: str, resource_id: int) -> str:
  125. """Create a short-lived, single-use download token for slicer protocol handlers."""
  126. now = datetime.now(timezone.utc)
  127. expires_at = now + timedelta(minutes=SLICER_TOKEN_EXPIRE_MINUTES)
  128. token = secrets.token_urlsafe(24)
  129. resource_key = f"{resource_type}:{resource_id}"
  130. async with async_session() as db:
  131. # Prune expired tokens opportunistically
  132. await db.execute(
  133. delete(AuthEphemeralToken).where(
  134. AuthEphemeralToken.token_type == TokenType.SLICER_DOWNLOAD,
  135. AuthEphemeralToken.expires_at < now,
  136. )
  137. )
  138. db.add(
  139. AuthEphemeralToken(
  140. token=token,
  141. token_type=TokenType.SLICER_DOWNLOAD,
  142. nonce=resource_key,
  143. expires_at=expires_at,
  144. )
  145. )
  146. await db.commit()
  147. return token
  148. async def verify_slicer_download_token(token: str, resource_type: str, resource_id: int) -> bool:
  149. """Verify and atomically consume a slicer download token.
  150. Returns True only if the token is valid, unexpired, and bound to the given resource.
  151. DELETE...RETURNING ensures the token is single-use even under concurrent requests.
  152. M-NEW-1 fix: nonce (resource key) is included in the WHERE clause so the DELETE
  153. only succeeds when the token is presented to the *correct* resource endpoint.
  154. Previously the token was consumed (committed) even when stored_key != expected_key,
  155. permanently invalidating it while returning False to the caller.
  156. """
  157. expected_key = f"{resource_type}:{resource_id}"
  158. now = datetime.now(timezone.utc)
  159. async with async_session() as db:
  160. result = await db.execute(
  161. delete(AuthEphemeralToken)
  162. .where(
  163. AuthEphemeralToken.token == token,
  164. AuthEphemeralToken.token_type == TokenType.SLICER_DOWNLOAD,
  165. AuthEphemeralToken.nonce == expected_key,
  166. AuthEphemeralToken.expires_at > now,
  167. )
  168. .returning(AuthEphemeralToken.id)
  169. )
  170. if result.one_or_none() is None:
  171. return False
  172. await db.commit()
  173. return True
  174. # --- Camera stream tokens ---
  175. # Reusable tokens for camera stream/snapshot endpoints loaded via <img>/<video>
  176. # tags (these cannot send Authorization headers). Unlike slicer tokens they are
  177. # NOT single-use — streams reconnect on errors. Stored in AuthEphemeralToken
  178. # (token_type="camera_stream") for multi-worker compatibility (M-3).
  179. CAMERA_STREAM_TOKEN_EXPIRE_MINUTES = 60
  180. async def create_camera_stream_token() -> str:
  181. """Create a reusable token for camera stream/snapshot access."""
  182. now = datetime.now(timezone.utc)
  183. expires_at = now + timedelta(minutes=CAMERA_STREAM_TOKEN_EXPIRE_MINUTES)
  184. token = secrets.token_urlsafe(24)
  185. async with async_session() as db:
  186. # Prune expired tokens opportunistically
  187. await db.execute(
  188. delete(AuthEphemeralToken).where(
  189. AuthEphemeralToken.token_type == "camera_stream",
  190. AuthEphemeralToken.expires_at < now,
  191. )
  192. )
  193. db.add(
  194. AuthEphemeralToken(
  195. token=token,
  196. token_type="camera_stream",
  197. expires_at=expires_at,
  198. )
  199. )
  200. await db.commit()
  201. return token
  202. async def verify_camera_stream_token(token: str) -> bool:
  203. """Verify a camera stream token is valid (reusable — does not consume it)."""
  204. now = datetime.now(timezone.utc)
  205. async with async_session() as db:
  206. result = await db.execute(
  207. select(AuthEphemeralToken).where(
  208. AuthEphemeralToken.token == token,
  209. AuthEphemeralToken.token_type == "camera_stream",
  210. AuthEphemeralToken.expires_at > now,
  211. )
  212. )
  213. return result.scalar_one_or_none() is not None
  214. def verify_password(plain_password: str, hashed_password: str) -> bool:
  215. """Verify a password against a hash.
  216. Uses pbkdf2_sha256 which handles long passwords automatically.
  217. """
  218. return pwd_context.verify(plain_password, hashed_password)
  219. def get_password_hash(password: str) -> str:
  220. """Hash a password.
  221. Uses pbkdf2_sha256 which is secure and has no password length limit.
  222. """
  223. return pwd_context.hash(password)
  224. def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
  225. """Create a JWT access token with jti (revocation) and iat (freshness) claims."""
  226. to_encode = data.copy()
  227. now = datetime.now(timezone.utc)
  228. if expires_delta:
  229. expire = now + expires_delta
  230. else:
  231. expire = now + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  232. jti = secrets.token_hex(16)
  233. to_encode.update({"exp": expire, "jti": jti, "iat": now})
  234. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  235. return encoded_jwt
  236. def _is_token_fresh(iat: int | float | None, user: User) -> bool:
  237. """Return False if the token was issued before the user's last password change.
  238. Used to invalidate all sessions after a password reset/change (M-R7-B).
  239. All tokens without an iat claim are unconditionally rejected — every token
  240. issued by this server carries iat, so absence means the token is forged or
  241. from a pre-iat code path whose max TTL (24 h) has long since expired.
  242. """
  243. if iat is None:
  244. return False
  245. if not hasattr(user, "password_changed_at") or user.password_changed_at is None:
  246. return True # No password change recorded yet (I2 migration handles this)
  247. token_issued_at = datetime.fromtimestamp(iat, tz=timezone.utc)
  248. pca = user.password_changed_at
  249. if pca.tzinfo is None:
  250. pca = pca.replace(tzinfo=timezone.utc)
  251. # JWT iat is whole seconds; truncate pca so tokens issued in the same second pass.
  252. pca = pca.replace(microsecond=0)
  253. return token_issued_at >= pca
  254. async def revoke_jti(jti: str, expires_at: datetime, username: str | None = None) -> None:
  255. """Store a revoked JWT jti so it is rejected on future requests.
  256. Silently ignores duplicate inserts (e.g. double-logout with the same token).
  257. """
  258. from sqlalchemy.exc import IntegrityError
  259. async with async_session() as db:
  260. revoked = AuthEphemeralToken(
  261. token=jti,
  262. token_type="revoked_jti",
  263. username=username,
  264. expires_at=expires_at,
  265. )
  266. db.add(revoked)
  267. try:
  268. await db.commit()
  269. except IntegrityError:
  270. await db.rollback() # jti already revoked — desired state, ignore
  271. async def is_jti_revoked(jti: str) -> bool:
  272. """Return True if the given jti has been revoked."""
  273. async with async_session() as db:
  274. result = await db.execute(
  275. select(AuthEphemeralToken).where(
  276. AuthEphemeralToken.token == jti,
  277. AuthEphemeralToken.token_type == "revoked_jti",
  278. )
  279. )
  280. return result.scalar_one_or_none() is not None
  281. async def get_user_by_username(db: AsyncSession, username: str) -> User | None:
  282. """Get a user by username (case-insensitive) with groups loaded for permission checks."""
  283. result = await db.execute(
  284. select(User).where(func.lower(User.username) == func.lower(username)).options(selectinload(User.groups))
  285. )
  286. return result.scalar_one_or_none()
  287. async def get_user_by_email(db: AsyncSession, email: str) -> User | None:
  288. """Get a user by email (case-insensitive) with groups loaded for permission checks."""
  289. result = await db.execute(
  290. select(User).where(func.lower(User.email) == func.lower(email)).options(selectinload(User.groups))
  291. )
  292. return result.scalar_one_or_none()
  293. async def authenticate_user(db: AsyncSession, username: str, password: str) -> User | None:
  294. """Authenticate a user by username and password.
  295. Username lookup is case-insensitive. Password is case-sensitive.
  296. LDAP and OIDC users must authenticate via their respective providers.
  297. """
  298. user = await get_user_by_username(db, username)
  299. if not user:
  300. return None
  301. if getattr(user, "auth_source", "local") in ("ldap", "oidc"):
  302. return None # LDAP/OIDC users must authenticate via their provider
  303. if not user.password_hash or not verify_password(password, user.password_hash):
  304. return None
  305. if not user.is_active:
  306. return None
  307. return user
  308. async def authenticate_user_by_email(db: AsyncSession, email: str, password: str) -> User | None:
  309. """Authenticate a user by email and password.
  310. Email lookup is case-insensitive. Password is case-sensitive.
  311. LDAP and OIDC users must authenticate via their respective providers.
  312. """
  313. user = await get_user_by_email(db, email)
  314. if not user:
  315. return None
  316. if getattr(user, "auth_source", "local") in ("ldap", "oidc"):
  317. return None # LDAP/OIDC users must authenticate via their provider
  318. if not user.password_hash or not verify_password(password, user.password_hash):
  319. return None
  320. if not user.is_active:
  321. return None
  322. return user
  323. async def is_auth_enabled(db: AsyncSession) -> bool:
  324. """Check if authentication is enabled."""
  325. try:
  326. result = await db.execute(select(Settings).where(Settings.key == "auth_enabled"))
  327. setting = result.scalar_one_or_none()
  328. if setting is None:
  329. return False
  330. return setting.value.lower() == "true"
  331. except Exception:
  332. # If settings table doesn't exist or query fails, assume auth is disabled
  333. return False
  334. async def _validate_api_key(db: AsyncSession, api_key_value: str) -> APIKey | None:
  335. """Validate an API key and return the APIKey object if valid, None otherwise.
  336. L-1: Pre-filter by key_prefix (first 8 chars) before running pbkdf2 so only
  337. O(1) candidate rows are hashed instead of the full key table. The prefix is
  338. not secret (it is shown in the admin UI), so this does not reduce security.
  339. """
  340. try:
  341. # key_prefix is stored as "<first-8-chars>..." (e.g. "bb_Abc12...").
  342. # Matching on the first 8 chars of the submitted key reduces the scan to
  343. # at most one row in practice (2^40 collision space for 5 base64 chars).
  344. key_lookup = api_key_value[:8] if len(api_key_value) >= 8 else api_key_value
  345. result = await db.execute(
  346. select(APIKey).where(
  347. APIKey.enabled.is_(True),
  348. APIKey.key_prefix.like(
  349. key_lookup.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%", escape="\\"
  350. ),
  351. )
  352. )
  353. api_keys = result.scalars().all()
  354. for api_key in api_keys:
  355. if verify_password(api_key_value, api_key.key_hash):
  356. # Check expiration
  357. if api_key.expires_at:
  358. expires = api_key.expires_at
  359. if expires.tzinfo is None:
  360. expires = expires.replace(tzinfo=timezone.utc)
  361. if expires < datetime.now(timezone.utc):
  362. return None # Expired
  363. # Update last_used timestamp
  364. api_key.last_used = datetime.now(timezone.utc)
  365. await db.commit()
  366. return api_key
  367. except Exception as e:
  368. logger.warning("API key validation error: %s", e)
  369. return None
  370. async def get_current_user_optional(
  371. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  372. ) -> User | None:
  373. """Get the current authenticated user from JWT token, or None if not authenticated.
  374. Returns None only when NO credentials are supplied. If a token is supplied
  375. but invalid/revoked, raises 401 — a revoked token must not grant anonymous
  376. access (I6).
  377. """
  378. if credentials is None:
  379. return None
  380. _unauthorized = HTTPException(
  381. status_code=status.HTTP_401_UNAUTHORIZED,
  382. detail="Could not validate credentials",
  383. headers={"WWW-Authenticate": "Bearer"},
  384. )
  385. try:
  386. token = credentials.credentials
  387. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  388. username: str = payload.get("sub")
  389. if username is None:
  390. raise _unauthorized
  391. jti: str | None = payload.get("jti")
  392. if not jti or await is_jti_revoked(jti):
  393. raise _unauthorized # I6: revoked token → 401, not anonymous
  394. iat: int | float | None = payload.get("iat")
  395. except JWTError:
  396. raise _unauthorized
  397. async with async_session() as db:
  398. user = await get_user_by_username(db, username)
  399. if user is None or not user.is_active:
  400. raise _unauthorized
  401. if not _is_token_fresh(iat, user):
  402. raise _unauthorized
  403. return user
  404. async def get_current_user(
  405. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  406. ) -> User:
  407. """Get the current authenticated user from JWT token."""
  408. credentials_exception = HTTPException(
  409. status_code=status.HTTP_401_UNAUTHORIZED,
  410. detail="Could not validate credentials",
  411. headers={"WWW-Authenticate": "Bearer"},
  412. )
  413. if credentials is None:
  414. raise credentials_exception
  415. try:
  416. token = credentials.credentials
  417. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  418. username: str = payload.get("sub")
  419. if username is None:
  420. raise credentials_exception
  421. jti: str | None = payload.get("jti")
  422. if not jti or await is_jti_revoked(jti):
  423. raise credentials_exception
  424. iat: int | float | None = payload.get("iat")
  425. except JWTError:
  426. raise credentials_exception
  427. async with async_session() as db:
  428. user = await get_user_by_username(db, username)
  429. if user is None:
  430. raise credentials_exception
  431. if not user.is_active:
  432. raise HTTPException(
  433. status_code=status.HTTP_403_FORBIDDEN,
  434. detail="User account is disabled",
  435. )
  436. if not _is_token_fresh(iat, user):
  437. raise credentials_exception
  438. return user
  439. async def get_current_active_user(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  440. """Get the current active user (alias for clarity)."""
  441. return current_user
  442. async def require_auth_if_enabled(
  443. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  444. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  445. ) -> User | None:
  446. """Require authentication if auth is enabled, otherwise return None.
  447. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  448. (via X-API-Key header or Authorization: Bearer bb_xxx).
  449. """
  450. async with async_session() as db:
  451. auth_enabled = await is_auth_enabled(db)
  452. if not auth_enabled:
  453. return None
  454. # Check for API key first (X-API-Key header)
  455. if x_api_key:
  456. api_key = await _validate_api_key(db, x_api_key)
  457. if api_key:
  458. return None # API key valid, allow access
  459. # Check for Bearer token (could be JWT or API key)
  460. if credentials is not None:
  461. token = credentials.credentials
  462. # Check if it's an API key (starts with bb_)
  463. if token.startswith("bb_"):
  464. api_key = await _validate_api_key(db, token)
  465. if api_key:
  466. return None # API key valid, allow access
  467. raise HTTPException(
  468. status_code=status.HTTP_401_UNAUTHORIZED,
  469. detail="Invalid API key",
  470. headers={"WWW-Authenticate": "Bearer"},
  471. )
  472. # Otherwise treat as JWT
  473. try:
  474. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  475. username: str = payload.get("sub")
  476. if username is None:
  477. raise HTTPException(
  478. status_code=status.HTTP_401_UNAUTHORIZED,
  479. detail="Could not validate credentials",
  480. headers={"WWW-Authenticate": "Bearer"},
  481. )
  482. jti: str | None = payload.get("jti")
  483. if not jti or await is_jti_revoked(jti):
  484. raise HTTPException(
  485. status_code=status.HTTP_401_UNAUTHORIZED,
  486. detail="Could not validate credentials",
  487. headers={"WWW-Authenticate": "Bearer"},
  488. )
  489. iat: int | float | None = payload.get("iat")
  490. except JWTError:
  491. raise HTTPException(
  492. status_code=status.HTTP_401_UNAUTHORIZED,
  493. detail="Could not validate credentials",
  494. headers={"WWW-Authenticate": "Bearer"},
  495. )
  496. user = await get_user_by_username(db, username)
  497. if user is None or not user.is_active:
  498. raise HTTPException(
  499. status_code=status.HTTP_401_UNAUTHORIZED,
  500. detail="Could not validate credentials",
  501. headers={"WWW-Authenticate": "Bearer"},
  502. )
  503. if not _is_token_fresh(iat, user):
  504. raise HTTPException(
  505. status_code=status.HTTP_401_UNAUTHORIZED,
  506. detail="Could not validate credentials",
  507. headers={"WWW-Authenticate": "Bearer"},
  508. )
  509. return user
  510. # No credentials provided
  511. raise HTTPException(
  512. status_code=status.HTTP_401_UNAUTHORIZED,
  513. detail="Authentication required",
  514. headers={"WWW-Authenticate": "Bearer"},
  515. )
  516. def require_role(required_role: str):
  517. """Dependency factory for role-based access control."""
  518. async def role_checker(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  519. if current_user.role != required_role:
  520. raise HTTPException(
  521. status_code=status.HTTP_403_FORBIDDEN,
  522. detail=f"Requires {required_role} role",
  523. )
  524. return current_user
  525. return role_checker
  526. def require_admin_if_auth_enabled():
  527. """Dependency factory that requires admin role if auth is enabled."""
  528. async def admin_checker(
  529. current_user: Annotated[User | None, Depends(require_auth_if_enabled)] = None,
  530. ) -> User | None:
  531. if current_user is None:
  532. return None # Auth not enabled, allow access
  533. if current_user.role != "admin":
  534. raise HTTPException(
  535. status_code=status.HTTP_403_FORBIDDEN,
  536. detail="Requires admin role",
  537. )
  538. return current_user
  539. return admin_checker
  540. def generate_api_key() -> tuple[str, str, str]:
  541. """Generate a new API key.
  542. Returns:
  543. tuple: (full_key, key_hash, key_prefix)
  544. - full_key: The complete API key (only shown once on creation)
  545. - key_hash: Hashed version for storage and verification
  546. - key_prefix: First 8 characters for display purposes
  547. """
  548. # Generate a secure random API key (32 bytes = 64 hex characters)
  549. full_key = f"bb_{secrets.token_urlsafe(32)}"
  550. key_hash = get_password_hash(full_key)
  551. key_prefix = full_key[:8] + "..." if len(full_key) > 8 else full_key
  552. return full_key, key_hash, key_prefix
  553. async def get_api_key(
  554. authorization: Annotated[str | None, Header(alias="Authorization")] = None,
  555. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  556. db: AsyncSession = Depends(get_db),
  557. ) -> APIKey:
  558. """Get and validate API key from request headers.
  559. Checks both 'Authorization: Bearer <key>' and 'X-API-Key: <key>' headers.
  560. """
  561. api_key_value = None
  562. if x_api_key:
  563. api_key_value = x_api_key
  564. elif authorization and authorization.startswith("Bearer "):
  565. api_key_value = authorization.replace("Bearer ", "")
  566. if not api_key_value:
  567. raise HTTPException(
  568. status_code=status.HTTP_401_UNAUTHORIZED,
  569. detail="API key required. Provide 'X-API-Key' header or 'Authorization: Bearer <key>'",
  570. )
  571. # Pre-filter by key_prefix to avoid O(n) pbkdf2 hashes across all enabled keys.
  572. key_lookup = api_key_value[:8] if len(api_key_value) >= 8 else api_key_value
  573. result = await db.execute(
  574. select(APIKey).where(
  575. APIKey.enabled.is_(True),
  576. APIKey.key_prefix.like(
  577. key_lookup.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%",
  578. escape="\\",
  579. ),
  580. )
  581. )
  582. api_keys = result.scalars().all()
  583. for api_key in api_keys:
  584. # Check if key matches (verify against hash)
  585. if verify_password(api_key_value, api_key.key_hash):
  586. # Check expiration
  587. if api_key.expires_at:
  588. expires = api_key.expires_at
  589. if expires.tzinfo is None:
  590. expires = expires.replace(tzinfo=timezone.utc)
  591. if expires < datetime.now(timezone.utc):
  592. raise HTTPException(
  593. status_code=status.HTTP_401_UNAUTHORIZED,
  594. detail="API key has expired",
  595. )
  596. # Update last_used timestamp
  597. api_key.last_used = datetime.now(timezone.utc)
  598. await db.commit()
  599. return api_key
  600. raise HTTPException(
  601. status_code=status.HTTP_401_UNAUTHORIZED,
  602. detail="Invalid API key",
  603. )
  604. def check_permission(api_key: APIKey, permission: str) -> None:
  605. """Check if API key has the required permission.
  606. Args:
  607. api_key: The API key object
  608. permission: One of 'queue', 'control_printer', 'read_status'
  609. Raises:
  610. HTTPException: If permission is not granted
  611. """
  612. permission_map = {
  613. "queue": "can_queue",
  614. "control_printer": "can_control_printer",
  615. "read_status": "can_read_status",
  616. }
  617. if permission not in permission_map:
  618. raise HTTPException(
  619. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  620. detail=f"Unknown permission: {permission}",
  621. )
  622. attr_name = permission_map[permission]
  623. if not getattr(api_key, attr_name, False):
  624. raise HTTPException(
  625. status_code=status.HTTP_403_FORBIDDEN,
  626. detail=f"API key does not have '{permission}' permission",
  627. )
  628. def check_printer_access(api_key: APIKey, printer_id: int) -> None:
  629. """Check if API key has access to the specified printer.
  630. Args:
  631. api_key: The API key object
  632. printer_id: The printer ID to check access for
  633. Raises:
  634. HTTPException: If access is denied
  635. """
  636. # None = global key, access to all printers
  637. if api_key.printer_ids is None:
  638. return
  639. # Empty list or printer not in allowed list = no access
  640. if printer_id not in api_key.printer_ids:
  641. raise HTTPException(
  642. status_code=status.HTTP_403_FORBIDDEN,
  643. detail=f"API key does not have access to printer {printer_id}",
  644. )
  645. # Convenience dependencies - these are functions that return Depends objects
  646. def RequireAdmin():
  647. """Dependency that requires admin role."""
  648. return Depends(require_role("admin"))
  649. def RequireAdminIfAuthEnabled():
  650. """Dependency that requires admin role if auth is enabled."""
  651. return Depends(require_admin_if_auth_enabled())
  652. def require_permission(*permissions: str | Permission):
  653. """Dependency factory that requires user to have ALL specified permissions.
  654. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  655. (via X-API-Key header or Authorization: Bearer bb_xxx).
  656. Args:
  657. *permissions: Permission strings or Permission enum values to require
  658. Returns:
  659. A dependency function that validates permissions
  660. """
  661. # Convert Permission enums to strings
  662. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  663. async def permission_checker(
  664. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  665. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  666. ) -> User | None:
  667. async with async_session() as db:
  668. # Check for API key first (X-API-Key header)
  669. if x_api_key:
  670. api_key = await _validate_api_key(db, x_api_key)
  671. if api_key:
  672. _check_apikey_permissions(perm_strings)
  673. return None # API key valid, allow access
  674. credentials_exception = HTTPException(
  675. status_code=status.HTTP_401_UNAUTHORIZED,
  676. detail="Could not validate credentials",
  677. headers={"WWW-Authenticate": "Bearer"},
  678. )
  679. if credentials is None:
  680. raise credentials_exception
  681. token = credentials.credentials
  682. # Check if it's an API key (starts with bb_)
  683. if token.startswith("bb_"):
  684. api_key = await _validate_api_key(db, token)
  685. if api_key:
  686. _check_apikey_permissions(perm_strings)
  687. return None # API key valid, allow access
  688. raise HTTPException(
  689. status_code=status.HTTP_401_UNAUTHORIZED,
  690. detail="Invalid API key",
  691. headers={"WWW-Authenticate": "Bearer"},
  692. )
  693. # Otherwise treat as JWT
  694. try:
  695. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  696. username: str = payload.get("sub")
  697. if username is None:
  698. raise credentials_exception
  699. jti: str | None = payload.get("jti")
  700. if not jti or await is_jti_revoked(jti):
  701. raise credentials_exception
  702. iat: int | float | None = payload.get("iat")
  703. except JWTError:
  704. raise credentials_exception
  705. user = await get_user_by_username(db, username)
  706. if user is None or not user.is_active:
  707. raise credentials_exception
  708. if not _is_token_fresh(iat, user):
  709. raise credentials_exception
  710. if not user.has_all_permissions(*perm_strings):
  711. raise HTTPException(
  712. status_code=status.HTTP_403_FORBIDDEN,
  713. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  714. )
  715. return user
  716. return permission_checker
  717. def require_permission_if_auth_enabled(*permissions: str | Permission):
  718. """Dependency factory that checks permissions only if auth is enabled.
  719. This provides backward compatibility - when auth is disabled, all access is allowed.
  720. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  721. (via X-API-Key header or Authorization: Bearer bb_xxx).
  722. Args:
  723. *permissions: Permission strings or Permission enum values to require
  724. Returns:
  725. A dependency function that validates permissions if auth is enabled
  726. """
  727. # Convert Permission enums to strings
  728. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  729. async def permission_checker(
  730. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  731. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  732. ) -> User | None:
  733. async with async_session() as db:
  734. auth_enabled = await is_auth_enabled(db)
  735. if not auth_enabled:
  736. return None # Auth disabled, allow access
  737. # Check for API key first (X-API-Key header)
  738. if x_api_key:
  739. api_key = await _validate_api_key(db, x_api_key)
  740. if api_key:
  741. _check_apikey_permissions(perm_strings)
  742. return None # API key valid, allow access
  743. # Check for Bearer token (could be JWT or API key)
  744. if credentials is not None:
  745. token = credentials.credentials
  746. # Check if it's an API key (starts with bb_)
  747. if token.startswith("bb_"):
  748. api_key = await _validate_api_key(db, token)
  749. if api_key:
  750. _check_apikey_permissions(perm_strings)
  751. return None # API key valid, allow access
  752. raise HTTPException(
  753. status_code=status.HTTP_401_UNAUTHORIZED,
  754. detail="Invalid API key",
  755. headers={"WWW-Authenticate": "Bearer"},
  756. )
  757. # Otherwise treat as JWT
  758. try:
  759. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  760. username: str = payload.get("sub")
  761. if username is None:
  762. raise HTTPException(
  763. status_code=status.HTTP_401_UNAUTHORIZED,
  764. detail="Could not validate credentials",
  765. headers={"WWW-Authenticate": "Bearer"},
  766. )
  767. jti: str | None = payload.get("jti")
  768. if not jti or await is_jti_revoked(jti):
  769. raise HTTPException(
  770. status_code=status.HTTP_401_UNAUTHORIZED,
  771. detail="Could not validate credentials",
  772. headers={"WWW-Authenticate": "Bearer"},
  773. )
  774. iat: int | float | None = payload.get("iat")
  775. except JWTError:
  776. raise HTTPException(
  777. status_code=status.HTTP_401_UNAUTHORIZED,
  778. detail="Could not validate credentials",
  779. headers={"WWW-Authenticate": "Bearer"},
  780. )
  781. user = await get_user_by_username(db, username)
  782. if user is None or not user.is_active:
  783. raise HTTPException(
  784. status_code=status.HTTP_401_UNAUTHORIZED,
  785. detail="Could not validate credentials",
  786. headers={"WWW-Authenticate": "Bearer"},
  787. )
  788. if not _is_token_fresh(iat, user):
  789. raise HTTPException(
  790. status_code=status.HTTP_401_UNAUTHORIZED,
  791. detail="Could not validate credentials",
  792. headers={"WWW-Authenticate": "Bearer"},
  793. )
  794. if not user.has_all_permissions(*perm_strings):
  795. raise HTTPException(
  796. status_code=status.HTTP_403_FORBIDDEN,
  797. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  798. )
  799. return user
  800. # No credentials provided
  801. raise HTTPException(
  802. status_code=status.HTTP_401_UNAUTHORIZED,
  803. detail="Authentication required",
  804. headers={"WWW-Authenticate": "Bearer"},
  805. )
  806. return permission_checker
  807. def RequirePermission(*permissions: str | Permission):
  808. """Convenience dependency that requires ALL specified permissions."""
  809. return Depends(require_permission(*permissions))
  810. def RequirePermissionIfAuthEnabled(*permissions: str | Permission):
  811. """Convenience dependency that requires permissions if auth is enabled."""
  812. return Depends(require_permission_if_auth_enabled(*permissions))
  813. def require_camera_stream_token_if_auth_enabled():
  814. """Dependency that validates a camera stream token query param when auth is enabled.
  815. Used for camera stream/snapshot endpoints that are loaded via <img> tags
  816. which cannot send Authorization headers. The frontend obtains a token from
  817. POST /printers/camera/stream-token and appends it as ?token=xxx.
  818. """
  819. async def checker(token: str | None = None) -> None:
  820. async with async_session() as db:
  821. if not await is_auth_enabled(db):
  822. return # Auth disabled, allow access
  823. if not token or not await verify_camera_stream_token(token):
  824. raise HTTPException(
  825. status_code=status.HTTP_401_UNAUTHORIZED,
  826. detail="Valid camera stream token required. Obtain one from POST /api/v1/printers/camera/stream-token",
  827. )
  828. return checker
  829. RequireCameraStreamTokenIfAuthEnabled = Depends(require_camera_stream_token_if_auth_enabled())
  830. def require_ownership_permission(
  831. all_permission: str | Permission,
  832. own_permission: str | Permission,
  833. ):
  834. """Dependency factory for ownership-based permission checks.
  835. - User with `all_permission` can modify any item
  836. - User with `own_permission` can only modify items where created_by_id == user.id
  837. - Ownerless items (created_by_id = null) require `all_permission`
  838. - API keys (via X-API-Key header or Bearer bb_xxx) get full access (can_modify_all=True)
  839. Returns:
  840. A dependency function that returns (user, can_modify_all).
  841. - can_modify_all=True: user can modify any item
  842. - can_modify_all=False: user can only modify their own items
  843. """
  844. all_perm = all_permission.value if isinstance(all_permission, Permission) else all_permission
  845. own_perm = own_permission.value if isinstance(own_permission, Permission) else own_permission
  846. async def checker(
  847. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  848. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  849. ) -> tuple[User | None, bool]:
  850. """Returns (user, can_modify_all).
  851. - can_modify_all=True: user can modify any item
  852. - can_modify_all=False: user can only modify their own items
  853. """
  854. async with async_session() as db:
  855. auth_enabled = await is_auth_enabled(db)
  856. if not auth_enabled:
  857. return None, True # Auth disabled, allow all
  858. # Check for API key first (X-API-Key header)
  859. if x_api_key:
  860. api_key = await _validate_api_key(db, x_api_key)
  861. if api_key:
  862. return None, True # API key valid, allow all
  863. # Check for Bearer token (could be JWT or API key)
  864. if credentials is not None:
  865. token = credentials.credentials
  866. # Check if it's an API key (starts with bb_)
  867. if token.startswith("bb_"):
  868. api_key = await _validate_api_key(db, token)
  869. if api_key:
  870. return None, True # API key valid, allow all
  871. raise HTTPException(
  872. status_code=status.HTTP_401_UNAUTHORIZED,
  873. detail="Invalid API key",
  874. headers={"WWW-Authenticate": "Bearer"},
  875. )
  876. # Otherwise treat as JWT
  877. try:
  878. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  879. username: str = payload.get("sub")
  880. if username is None:
  881. raise HTTPException(
  882. status_code=status.HTTP_401_UNAUTHORIZED,
  883. detail="Could not validate credentials",
  884. headers={"WWW-Authenticate": "Bearer"},
  885. )
  886. jti: str | None = payload.get("jti")
  887. if not jti or await is_jti_revoked(jti):
  888. raise HTTPException(
  889. status_code=status.HTTP_401_UNAUTHORIZED,
  890. detail="Could not validate credentials",
  891. headers={"WWW-Authenticate": "Bearer"},
  892. )
  893. iat: int | float | None = payload.get("iat")
  894. except JWTError:
  895. raise HTTPException(
  896. status_code=status.HTTP_401_UNAUTHORIZED,
  897. detail="Could not validate credentials",
  898. headers={"WWW-Authenticate": "Bearer"},
  899. )
  900. user = await get_user_by_username(db, username)
  901. if user is None or not user.is_active:
  902. raise HTTPException(
  903. status_code=status.HTTP_401_UNAUTHORIZED,
  904. detail="Could not validate credentials",
  905. headers={"WWW-Authenticate": "Bearer"},
  906. )
  907. if not _is_token_fresh(iat, user):
  908. raise HTTPException(
  909. status_code=status.HTTP_401_UNAUTHORIZED,
  910. detail="Could not validate credentials",
  911. headers={"WWW-Authenticate": "Bearer"},
  912. )
  913. if user.has_permission(all_perm):
  914. return user, True
  915. if user.has_permission(own_perm):
  916. return user, False
  917. raise HTTPException(
  918. status_code=status.HTTP_403_FORBIDDEN,
  919. detail=f"Missing permission: {own_perm} or {all_perm}",
  920. )
  921. # No credentials provided
  922. raise HTTPException(
  923. status_code=status.HTTP_401_UNAUTHORIZED,
  924. detail="Authentication required",
  925. headers={"WWW-Authenticate": "Bearer"},
  926. )
  927. return checker