auth.py 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  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. Tries the ephemeral 60-minute token first (the common, browser-bound case)
  170. and falls through to long-lived tokens (#1108) for HA / kiosk integrations
  171. that paste a token once and expect it to keep working for days.
  172. """
  173. now = datetime.now(timezone.utc)
  174. async with async_session() as db:
  175. result = await db.execute(
  176. select(AuthEphemeralToken).where(
  177. AuthEphemeralToken.token == token,
  178. AuthEphemeralToken.token_type == "camera_stream",
  179. AuthEphemeralToken.expires_at > now,
  180. )
  181. )
  182. if result.scalar_one_or_none() is not None:
  183. return True
  184. # Long-lived path. Imported lazily so the auth module stays importable
  185. # at startup before the long_lived_tokens model is registered.
  186. from backend.app.services.long_lived_tokens import verify_token as verify_long_lived
  187. record = await verify_long_lived(db, token, scope="camera_stream")
  188. return record is not None
  189. def verify_password(plain_password: str, hashed_password: str) -> bool:
  190. """Verify a password against a hash.
  191. Uses pbkdf2_sha256 which handles long passwords automatically.
  192. """
  193. return pwd_context.verify(plain_password, hashed_password)
  194. def get_password_hash(password: str) -> str:
  195. """Hash a password.
  196. Uses pbkdf2_sha256 which is secure and has no password length limit.
  197. """
  198. return pwd_context.hash(password)
  199. def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
  200. """Create a JWT access token with jti (revocation) and iat (freshness) claims."""
  201. to_encode = data.copy()
  202. now = datetime.now(timezone.utc)
  203. if expires_delta:
  204. expire = now + expires_delta
  205. else:
  206. expire = now + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  207. jti = secrets.token_hex(16)
  208. to_encode.update({"exp": expire, "jti": jti, "iat": now})
  209. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  210. return encoded_jwt
  211. def _is_token_fresh(iat: int | float | None, user: User) -> bool:
  212. """Return False if the token was issued before the user's last password change.
  213. Used to invalidate all sessions after a password reset/change (M-R7-B).
  214. All tokens without an iat claim are unconditionally rejected — every token
  215. issued by this server carries iat, so absence means the token is forged or
  216. from a pre-iat code path whose max TTL (24 h) has long since expired.
  217. """
  218. if iat is None:
  219. return False
  220. if not hasattr(user, "password_changed_at") or user.password_changed_at is None:
  221. return True # No password change recorded yet (I2 migration handles this)
  222. token_issued_at = datetime.fromtimestamp(iat, tz=timezone.utc)
  223. pca = user.password_changed_at
  224. if pca.tzinfo is None:
  225. pca = pca.replace(tzinfo=timezone.utc)
  226. # JWT iat is whole seconds; truncate pca so tokens issued in the same second pass.
  227. pca = pca.replace(microsecond=0)
  228. return token_issued_at >= pca
  229. async def revoke_jti(jti: str, expires_at: datetime, username: str | None = None) -> None:
  230. """Store a revoked JWT jti so it is rejected on future requests.
  231. Silently ignores duplicate inserts (e.g. double-logout with the same token).
  232. """
  233. from sqlalchemy.exc import IntegrityError
  234. async with async_session() as db:
  235. revoked = AuthEphemeralToken(
  236. token=jti,
  237. token_type="revoked_jti",
  238. username=username,
  239. expires_at=expires_at,
  240. )
  241. db.add(revoked)
  242. try:
  243. await db.commit()
  244. except IntegrityError:
  245. await db.rollback() # jti already revoked — desired state, ignore
  246. async def is_jti_revoked(jti: str) -> bool:
  247. """Return True if the given jti has been revoked."""
  248. async with async_session() as db:
  249. result = await db.execute(
  250. select(AuthEphemeralToken).where(
  251. AuthEphemeralToken.token == jti,
  252. AuthEphemeralToken.token_type == "revoked_jti",
  253. )
  254. )
  255. return result.scalar_one_or_none() is not None
  256. async def get_user_by_username(db: AsyncSession, username: str) -> User | None:
  257. """Get a user by username (case-insensitive) with groups loaded for permission checks."""
  258. result = await db.execute(
  259. select(User).where(func.lower(User.username) == func.lower(username)).options(selectinload(User.groups))
  260. )
  261. return result.scalar_one_or_none()
  262. async def get_user_by_email(db: AsyncSession, email: str) -> User | None:
  263. """Get a user by email (case-insensitive) with groups loaded for permission checks."""
  264. result = await db.execute(
  265. select(User).where(func.lower(User.email) == func.lower(email)).options(selectinload(User.groups))
  266. )
  267. return result.scalar_one_or_none()
  268. async def authenticate_user(db: AsyncSession, username: str, password: str) -> User | None:
  269. """Authenticate a user by username and password.
  270. Username lookup is case-insensitive. Password is case-sensitive.
  271. LDAP and OIDC users must authenticate via their respective providers.
  272. """
  273. user = await get_user_by_username(db, username)
  274. if not user:
  275. return None
  276. if getattr(user, "auth_source", "local") in ("ldap", "oidc"):
  277. return None # LDAP/OIDC users must authenticate via their provider
  278. if not user.password_hash or not verify_password(password, user.password_hash):
  279. return None
  280. if not user.is_active:
  281. return None
  282. return user
  283. async def authenticate_user_by_email(db: AsyncSession, email: str, password: str) -> User | None:
  284. """Authenticate a user by email and password.
  285. Email lookup is case-insensitive. Password is case-sensitive.
  286. LDAP and OIDC users must authenticate via their respective providers.
  287. """
  288. user = await get_user_by_email(db, email)
  289. if not user:
  290. return None
  291. if getattr(user, "auth_source", "local") in ("ldap", "oidc"):
  292. return None # LDAP/OIDC users must authenticate via their provider
  293. if not user.password_hash or not verify_password(password, user.password_hash):
  294. return None
  295. if not user.is_active:
  296. return None
  297. return user
  298. async def is_auth_enabled(db: AsyncSession) -> bool:
  299. """Check if authentication is enabled."""
  300. try:
  301. result = await db.execute(select(Settings).where(Settings.key == "auth_enabled"))
  302. setting = result.scalar_one_or_none()
  303. if setting is None:
  304. return False
  305. return setting.value.lower() == "true"
  306. except Exception:
  307. # If settings table doesn't exist or query fails, assume auth is disabled
  308. return False
  309. async def _user_from_api_key(db: AsyncSession, api_key: APIKey) -> User | None:
  310. """Resolve the owner of a validated API key, or None for legacy ownerless keys.
  311. Cloud routes (and any route that needs caller identity) read the returned
  312. User to look up per-user state like ``cloud_token``. Legacy keys created
  313. before #1182 have ``user_id IS NULL`` and stay anonymous — they keep working
  314. against non-cloud routes for backward compatibility, but cloud routes will
  315. surface a "recreate this key" error rather than 200 with empty results.
  316. """
  317. if api_key.user_id is None:
  318. return None
  319. result = await db.execute(select(User).where(User.id == api_key.user_id))
  320. user = result.scalar_one_or_none()
  321. if user is None or not user.is_active:
  322. # CASCADE on user delete should prevent a dangling user_id, but if
  323. # someone manually deactivates the owner the key shouldn't suddenly
  324. # gain an "anonymous" identity — drop the request to None so cloud
  325. # access fails closed.
  326. return None
  327. return user
  328. async def _validate_api_key(db: AsyncSession, api_key_value: str) -> APIKey | None:
  329. """Validate an API key and return the APIKey object if valid, None otherwise.
  330. L-1: Pre-filter by key_prefix (first 8 chars) before running pbkdf2 so only
  331. O(1) candidate rows are hashed instead of the full key table. The prefix is
  332. not secret (it is shown in the admin UI), so this does not reduce security.
  333. """
  334. try:
  335. # key_prefix is stored as "<first-8-chars>..." (e.g. "bb_Abc12...").
  336. # Matching on the first 8 chars of the submitted key reduces the scan to
  337. # at most one row in practice (2^40 collision space for 5 base64 chars).
  338. key_lookup = api_key_value[:8] if len(api_key_value) >= 8 else api_key_value
  339. result = await db.execute(
  340. select(APIKey).where(
  341. APIKey.enabled.is_(True),
  342. APIKey.key_prefix.like(
  343. key_lookup.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%", escape="\\"
  344. ),
  345. )
  346. )
  347. api_keys = result.scalars().all()
  348. for api_key in api_keys:
  349. if verify_password(api_key_value, api_key.key_hash):
  350. # Check expiration
  351. if api_key.expires_at:
  352. expires = api_key.expires_at
  353. if expires.tzinfo is None:
  354. expires = expires.replace(tzinfo=timezone.utc)
  355. if expires < datetime.now(timezone.utc):
  356. return None # Expired
  357. # Update last_used timestamp
  358. api_key.last_used = datetime.now(timezone.utc)
  359. await db.commit()
  360. return api_key
  361. except Exception as e:
  362. logger.warning("API key validation error: %s", e)
  363. return None
  364. async def get_current_user_optional(
  365. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  366. ) -> User | None:
  367. """Get the current authenticated user from JWT token, or None if not authenticated.
  368. Returns None only when NO credentials are supplied. If a token is supplied
  369. but invalid/revoked, raises 401 — a revoked token must not grant anonymous
  370. access (I6).
  371. """
  372. if credentials is None:
  373. return None
  374. _unauthorized = HTTPException(
  375. status_code=status.HTTP_401_UNAUTHORIZED,
  376. detail="Could not validate credentials",
  377. headers={"WWW-Authenticate": "Bearer"},
  378. )
  379. try:
  380. token = credentials.credentials
  381. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  382. username: str = payload.get("sub")
  383. if username is None:
  384. raise _unauthorized
  385. jti: str | None = payload.get("jti")
  386. if not jti or await is_jti_revoked(jti):
  387. raise _unauthorized # I6: revoked token → 401, not anonymous
  388. iat: int | float | None = payload.get("iat")
  389. except JWTError:
  390. raise _unauthorized
  391. async with async_session() as db:
  392. user = await get_user_by_username(db, username)
  393. if user is None or not user.is_active:
  394. raise _unauthorized
  395. if not _is_token_fresh(iat, user):
  396. raise _unauthorized
  397. return user
  398. async def get_current_user(
  399. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  400. ) -> User:
  401. """Get the current authenticated user from JWT token."""
  402. credentials_exception = HTTPException(
  403. status_code=status.HTTP_401_UNAUTHORIZED,
  404. detail="Could not validate credentials",
  405. headers={"WWW-Authenticate": "Bearer"},
  406. )
  407. if credentials is None:
  408. raise credentials_exception
  409. try:
  410. token = credentials.credentials
  411. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  412. username: str = payload.get("sub")
  413. if username is None:
  414. raise credentials_exception
  415. jti: str | None = payload.get("jti")
  416. if not jti or await is_jti_revoked(jti):
  417. raise credentials_exception
  418. iat: int | float | None = payload.get("iat")
  419. except JWTError:
  420. raise credentials_exception
  421. async with async_session() as db:
  422. user = await get_user_by_username(db, username)
  423. if user is None:
  424. raise credentials_exception
  425. if not user.is_active:
  426. raise HTTPException(
  427. status_code=status.HTTP_403_FORBIDDEN,
  428. detail="User account is disabled",
  429. )
  430. if not _is_token_fresh(iat, user):
  431. raise credentials_exception
  432. return user
  433. async def get_current_active_user(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  434. """Get the current active user (alias for clarity)."""
  435. return current_user
  436. async def require_auth_if_enabled(
  437. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  438. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  439. ) -> User | None:
  440. """Require authentication if auth is enabled, otherwise return None.
  441. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  442. (via X-API-Key header or Authorization: Bearer bb_xxx). API keys return
  443. None for backward compatibility — routes that need the API-key owner (i.e.
  444. cloud routes for #1182) resolve it via their own router-level dependency
  445. that stashes ``request.state.api_key_owner``. Returning the owner here
  446. instead would silently grant API-keyed callers access to every route that
  447. fences via ``if current_user is None``, which is a wider surface than
  448. #1182 was designed to expose.
  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. # M-NEW-2: Pre-filter by key_prefix (first 8 chars) to avoid O(n) pbkdf2 over all
  572. # enabled keys — same fix as in _validate_api_key (L-1 from previous review).
  573. key_lookup = api_key_value[:8] if len(api_key_value) >= 8 else api_key_value
  574. result = await db.execute(
  575. select(APIKey).where(
  576. APIKey.enabled.is_(True),
  577. APIKey.key_prefix.like(
  578. key_lookup.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%",
  579. escape="\\",
  580. ),
  581. )
  582. )
  583. api_keys = result.scalars().all()
  584. for api_key in api_keys:
  585. # Check if key matches (verify against hash)
  586. if verify_password(api_key_value, api_key.key_hash):
  587. # Check expiration
  588. if api_key.expires_at:
  589. expires = api_key.expires_at
  590. if expires.tzinfo is None:
  591. expires = expires.replace(tzinfo=timezone.utc)
  592. if expires < datetime.now(timezone.utc):
  593. raise HTTPException(
  594. status_code=status.HTTP_401_UNAUTHORIZED,
  595. detail="API key has expired",
  596. )
  597. # Update last_used timestamp
  598. api_key.last_used = datetime.now(timezone.utc)
  599. await db.commit()
  600. return api_key
  601. raise HTTPException(
  602. status_code=status.HTTP_401_UNAUTHORIZED,
  603. detail="Invalid API key",
  604. )
  605. def check_permission(api_key: APIKey, permission: str) -> None:
  606. """Check if API key has the required permission.
  607. Args:
  608. api_key: The API key object
  609. permission: One of 'queue', 'control_printer', 'read_status'
  610. Raises:
  611. HTTPException: If permission is not granted
  612. """
  613. permission_map = {
  614. "queue": "can_queue",
  615. "control_printer": "can_control_printer",
  616. "read_status": "can_read_status",
  617. }
  618. if permission not in permission_map:
  619. raise HTTPException(
  620. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  621. detail=f"Unknown permission: {permission}",
  622. )
  623. attr_name = permission_map[permission]
  624. if not getattr(api_key, attr_name, False):
  625. raise HTTPException(
  626. status_code=status.HTTP_403_FORBIDDEN,
  627. detail=f"API key does not have '{permission}' permission",
  628. )
  629. def check_printer_access(api_key: APIKey, printer_id: int) -> None:
  630. """Check if API key has access to the specified printer.
  631. Args:
  632. api_key: The API key object
  633. printer_id: The printer ID to check access for
  634. Raises:
  635. HTTPException: If access is denied
  636. """
  637. # None = global key, access to all printers
  638. if api_key.printer_ids is None:
  639. return
  640. # Empty list or printer not in allowed list = no access
  641. if printer_id not in api_key.printer_ids:
  642. raise HTTPException(
  643. status_code=status.HTTP_403_FORBIDDEN,
  644. detail=f"API key does not have access to printer {printer_id}",
  645. )
  646. # Convenience dependencies - these are functions that return Depends objects
  647. def RequireAdmin():
  648. """Dependency that requires admin role."""
  649. return Depends(require_role("admin"))
  650. def RequireAdminIfAuthEnabled():
  651. """Dependency that requires admin role if auth is enabled."""
  652. return Depends(require_admin_if_auth_enabled())
  653. def require_permission(*permissions: str | Permission):
  654. """Dependency factory that requires user to have ALL specified permissions.
  655. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  656. (via X-API-Key header or Authorization: Bearer bb_xxx).
  657. Args:
  658. *permissions: Permission strings or Permission enum values to require
  659. Returns:
  660. A dependency function that validates permissions
  661. """
  662. # Convert Permission enums to strings
  663. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  664. async def permission_checker(
  665. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  666. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  667. ) -> User | None:
  668. async with async_session() as db:
  669. # Check for API key first (X-API-Key header)
  670. if x_api_key:
  671. api_key = await _validate_api_key(db, x_api_key)
  672. if api_key:
  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. return None # API key valid, allow access
  687. raise HTTPException(
  688. status_code=status.HTTP_401_UNAUTHORIZED,
  689. detail="Invalid API key",
  690. headers={"WWW-Authenticate": "Bearer"},
  691. )
  692. # Otherwise treat as JWT
  693. try:
  694. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  695. username: str = payload.get("sub")
  696. if username is None:
  697. raise credentials_exception
  698. jti: str | None = payload.get("jti")
  699. if not jti or await is_jti_revoked(jti):
  700. raise credentials_exception
  701. iat: int | float | None = payload.get("iat")
  702. except JWTError:
  703. raise credentials_exception
  704. user = await get_user_by_username(db, username)
  705. if user is None or not user.is_active:
  706. raise credentials_exception
  707. if not _is_token_fresh(iat, user):
  708. raise credentials_exception
  709. if not user.has_all_permissions(*perm_strings):
  710. raise HTTPException(
  711. status_code=status.HTTP_403_FORBIDDEN,
  712. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  713. )
  714. return user
  715. return permission_checker
  716. def require_permission_if_auth_enabled(*permissions: str | Permission):
  717. """Dependency factory that checks permissions only if auth is enabled.
  718. This provides backward compatibility - when auth is disabled, all access is allowed.
  719. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  720. (via X-API-Key header or Authorization: Bearer bb_xxx).
  721. Args:
  722. *permissions: Permission strings or Permission enum values to require
  723. Returns:
  724. A dependency function that validates permissions if auth is enabled
  725. """
  726. # Convert Permission enums to strings
  727. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  728. async def permission_checker(
  729. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  730. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  731. ) -> User | None:
  732. async with async_session() as db:
  733. auth_enabled = await is_auth_enabled(db)
  734. if not auth_enabled:
  735. return None # Auth disabled, allow access
  736. # Check for API key first (X-API-Key header). API-keyed requests
  737. # bypass the JWT permission check entirely — their scopes live on
  738. # the APIKey row (can_queue / can_control_printer / can_read_status
  739. # / can_access_cloud / printer_ids), and the dep returns None so
  740. # routes don't gain a synthetic User identity that would grant
  741. # access to fenced surfaces like long-lived-token management.
  742. # Cloud routes (#1182) resolve the API-key owner separately via
  743. # their own router-level dependency; see ``cloud.py``.
  744. if x_api_key:
  745. api_key = await _validate_api_key(db, x_api_key)
  746. if api_key:
  747. return None # API key valid, allow access
  748. # Check for Bearer token (could be JWT or API key)
  749. if credentials is not None:
  750. token = credentials.credentials
  751. # Check if it's an API key (starts with bb_)
  752. if token.startswith("bb_"):
  753. api_key = await _validate_api_key(db, token)
  754. if api_key:
  755. return None # API key valid, allow access
  756. raise HTTPException(
  757. status_code=status.HTTP_401_UNAUTHORIZED,
  758. detail="Invalid API key",
  759. headers={"WWW-Authenticate": "Bearer"},
  760. )
  761. # Otherwise treat as JWT
  762. try:
  763. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  764. username: str = payload.get("sub")
  765. if username is None:
  766. raise HTTPException(
  767. status_code=status.HTTP_401_UNAUTHORIZED,
  768. detail="Could not validate credentials",
  769. headers={"WWW-Authenticate": "Bearer"},
  770. )
  771. jti: str | None = payload.get("jti")
  772. if not jti or await is_jti_revoked(jti):
  773. raise HTTPException(
  774. status_code=status.HTTP_401_UNAUTHORIZED,
  775. detail="Could not validate credentials",
  776. headers={"WWW-Authenticate": "Bearer"},
  777. )
  778. iat: int | float | None = payload.get("iat")
  779. except JWTError:
  780. raise HTTPException(
  781. status_code=status.HTTP_401_UNAUTHORIZED,
  782. detail="Could not validate credentials",
  783. headers={"WWW-Authenticate": "Bearer"},
  784. )
  785. user = await get_user_by_username(db, username)
  786. if user is None or not user.is_active:
  787. raise HTTPException(
  788. status_code=status.HTTP_401_UNAUTHORIZED,
  789. detail="Could not validate credentials",
  790. headers={"WWW-Authenticate": "Bearer"},
  791. )
  792. if not _is_token_fresh(iat, user):
  793. raise HTTPException(
  794. status_code=status.HTTP_401_UNAUTHORIZED,
  795. detail="Could not validate credentials",
  796. headers={"WWW-Authenticate": "Bearer"},
  797. )
  798. if not user.has_all_permissions(*perm_strings):
  799. raise HTTPException(
  800. status_code=status.HTTP_403_FORBIDDEN,
  801. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  802. )
  803. return user
  804. # No credentials provided
  805. raise HTTPException(
  806. status_code=status.HTTP_401_UNAUTHORIZED,
  807. detail="Authentication required",
  808. headers={"WWW-Authenticate": "Bearer"},
  809. )
  810. return permission_checker
  811. def RequirePermission(*permissions: str | Permission):
  812. """Convenience dependency that requires ALL specified permissions."""
  813. return Depends(require_permission(*permissions))
  814. def RequirePermissionIfAuthEnabled(*permissions: str | Permission):
  815. """Convenience dependency that requires permissions if auth is enabled."""
  816. return Depends(require_permission_if_auth_enabled(*permissions))
  817. def require_camera_stream_token_if_auth_enabled():
  818. """Dependency that validates a camera stream token query param when auth is enabled.
  819. Used for camera stream/snapshot endpoints that are loaded via <img> tags
  820. which cannot send Authorization headers. The frontend obtains a token from
  821. POST /printers/camera/stream-token and appends it as ?token=xxx.
  822. """
  823. async def checker(token: str | None = None) -> None:
  824. async with async_session() as db:
  825. if not await is_auth_enabled(db):
  826. return # Auth disabled, allow access
  827. if not token or not await verify_camera_stream_token(token):
  828. raise HTTPException(
  829. status_code=status.HTTP_401_UNAUTHORIZED,
  830. detail="Valid camera stream token required. Obtain one from POST /api/v1/printers/camera/stream-token",
  831. )
  832. return checker
  833. RequireCameraStreamTokenIfAuthEnabled = Depends(require_camera_stream_token_if_auth_enabled())
  834. def require_ownership_permission(
  835. all_permission: str | Permission,
  836. own_permission: str | Permission,
  837. ):
  838. """Dependency factory for ownership-based permission checks.
  839. - User with `all_permission` can modify any item
  840. - User with `own_permission` can only modify items where created_by_id == user.id
  841. - Ownerless items (created_by_id = null) require `all_permission`
  842. - API keys (via X-API-Key header or Bearer bb_xxx) get full access (can_modify_all=True)
  843. Returns:
  844. A dependency function that returns (user, can_modify_all).
  845. - can_modify_all=True: user can modify any item
  846. - can_modify_all=False: user can only modify their own items
  847. """
  848. all_perm = all_permission.value if isinstance(all_permission, Permission) else all_permission
  849. own_perm = own_permission.value if isinstance(own_permission, Permission) else own_permission
  850. async def checker(
  851. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  852. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  853. ) -> tuple[User | None, bool]:
  854. """Returns (user, can_modify_all).
  855. - can_modify_all=True: user can modify any item
  856. - can_modify_all=False: user can only modify their own items
  857. """
  858. async with async_session() as db:
  859. auth_enabled = await is_auth_enabled(db)
  860. if not auth_enabled:
  861. return None, True # Auth disabled, allow all
  862. # Check for API key first (X-API-Key header)
  863. if x_api_key:
  864. api_key = await _validate_api_key(db, x_api_key)
  865. if api_key:
  866. return None, True # API key valid, allow all
  867. # Check for Bearer token (could be JWT or API key)
  868. if credentials is not None:
  869. token = credentials.credentials
  870. # Check if it's an API key (starts with bb_)
  871. if token.startswith("bb_"):
  872. api_key = await _validate_api_key(db, token)
  873. if api_key:
  874. return None, True # API key valid, allow all
  875. raise HTTPException(
  876. status_code=status.HTTP_401_UNAUTHORIZED,
  877. detail="Invalid API key",
  878. headers={"WWW-Authenticate": "Bearer"},
  879. )
  880. # Otherwise treat as JWT
  881. try:
  882. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  883. username: str = payload.get("sub")
  884. if username is None:
  885. raise HTTPException(
  886. status_code=status.HTTP_401_UNAUTHORIZED,
  887. detail="Could not validate credentials",
  888. headers={"WWW-Authenticate": "Bearer"},
  889. )
  890. jti: str | None = payload.get("jti")
  891. if not jti or await is_jti_revoked(jti):
  892. raise HTTPException(
  893. status_code=status.HTTP_401_UNAUTHORIZED,
  894. detail="Could not validate credentials",
  895. headers={"WWW-Authenticate": "Bearer"},
  896. )
  897. iat: int | float | None = payload.get("iat")
  898. except JWTError:
  899. raise HTTPException(
  900. status_code=status.HTTP_401_UNAUTHORIZED,
  901. detail="Could not validate credentials",
  902. headers={"WWW-Authenticate": "Bearer"},
  903. )
  904. user = await get_user_by_username(db, username)
  905. if user is None or not user.is_active:
  906. raise HTTPException(
  907. status_code=status.HTTP_401_UNAUTHORIZED,
  908. detail="Could not validate credentials",
  909. headers={"WWW-Authenticate": "Bearer"},
  910. )
  911. if not _is_token_fresh(iat, user):
  912. raise HTTPException(
  913. status_code=status.HTTP_401_UNAUTHORIZED,
  914. detail="Could not validate credentials",
  915. headers={"WWW-Authenticate": "Bearer"},
  916. )
  917. if user.has_permission(all_perm):
  918. return user, True
  919. if user.has_permission(own_perm):
  920. return user, False
  921. raise HTTPException(
  922. status_code=status.HTTP_403_FORBIDDEN,
  923. detail=f"Missing permission: {own_perm} or {all_perm}",
  924. )
  925. # No credentials provided
  926. raise HTTPException(
  927. status_code=status.HTTP_401_UNAUTHORIZED,
  928. detail="Authentication required",
  929. headers={"WWW-Authenticate": "Bearer"},
  930. )
  931. return checker