auth.py 41 KB

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