auth.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  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 _validate_api_key(db: AsyncSession, api_key_value: str) -> APIKey | None:
  310. """Validate an API key and return the APIKey object if valid, None otherwise.
  311. L-1: Pre-filter by key_prefix (first 8 chars) before running pbkdf2 so only
  312. O(1) candidate rows are hashed instead of the full key table. The prefix is
  313. not secret (it is shown in the admin UI), so this does not reduce security.
  314. """
  315. try:
  316. # key_prefix is stored as "<first-8-chars>..." (e.g. "bb_Abc12...").
  317. # Matching on the first 8 chars of the submitted key reduces the scan to
  318. # at most one row in practice (2^40 collision space for 5 base64 chars).
  319. key_lookup = api_key_value[:8] if len(api_key_value) >= 8 else api_key_value
  320. result = await db.execute(
  321. select(APIKey).where(
  322. APIKey.enabled.is_(True),
  323. APIKey.key_prefix.like(
  324. key_lookup.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%", escape="\\"
  325. ),
  326. )
  327. )
  328. api_keys = result.scalars().all()
  329. for api_key in api_keys:
  330. if verify_password(api_key_value, api_key.key_hash):
  331. # Check expiration
  332. if api_key.expires_at:
  333. expires = api_key.expires_at
  334. if expires.tzinfo is None:
  335. expires = expires.replace(tzinfo=timezone.utc)
  336. if expires < datetime.now(timezone.utc):
  337. return None # Expired
  338. # Update last_used timestamp
  339. api_key.last_used = datetime.now(timezone.utc)
  340. await db.commit()
  341. return api_key
  342. except Exception as e:
  343. logger.warning("API key validation error: %s", e)
  344. return None
  345. async def get_current_user_optional(
  346. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  347. ) -> User | None:
  348. """Get the current authenticated user from JWT token, or None if not authenticated.
  349. Returns None only when NO credentials are supplied. If a token is supplied
  350. but invalid/revoked, raises 401 — a revoked token must not grant anonymous
  351. access (I6).
  352. """
  353. if credentials is None:
  354. return None
  355. _unauthorized = HTTPException(
  356. status_code=status.HTTP_401_UNAUTHORIZED,
  357. detail="Could not validate credentials",
  358. headers={"WWW-Authenticate": "Bearer"},
  359. )
  360. try:
  361. token = credentials.credentials
  362. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  363. username: str = payload.get("sub")
  364. if username is None:
  365. raise _unauthorized
  366. jti: str | None = payload.get("jti")
  367. if not jti or await is_jti_revoked(jti):
  368. raise _unauthorized # I6: revoked token → 401, not anonymous
  369. iat: int | float | None = payload.get("iat")
  370. except JWTError:
  371. raise _unauthorized
  372. async with async_session() as db:
  373. user = await get_user_by_username(db, username)
  374. if user is None or not user.is_active:
  375. raise _unauthorized
  376. if not _is_token_fresh(iat, user):
  377. raise _unauthorized
  378. return user
  379. async def get_current_user(
  380. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  381. ) -> User:
  382. """Get the current authenticated user from JWT token."""
  383. credentials_exception = HTTPException(
  384. status_code=status.HTTP_401_UNAUTHORIZED,
  385. detail="Could not validate credentials",
  386. headers={"WWW-Authenticate": "Bearer"},
  387. )
  388. if credentials is None:
  389. raise credentials_exception
  390. try:
  391. token = credentials.credentials
  392. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  393. username: str = payload.get("sub")
  394. if username is None:
  395. raise credentials_exception
  396. jti: str | None = payload.get("jti")
  397. if not jti or await is_jti_revoked(jti):
  398. raise credentials_exception
  399. iat: int | float | None = payload.get("iat")
  400. except JWTError:
  401. raise credentials_exception
  402. async with async_session() as db:
  403. user = await get_user_by_username(db, username)
  404. if user is None:
  405. raise credentials_exception
  406. if not user.is_active:
  407. raise HTTPException(
  408. status_code=status.HTTP_403_FORBIDDEN,
  409. detail="User account is disabled",
  410. )
  411. if not _is_token_fresh(iat, user):
  412. raise credentials_exception
  413. return user
  414. async def get_current_active_user(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  415. """Get the current active user (alias for clarity)."""
  416. return current_user
  417. async def require_auth_if_enabled(
  418. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  419. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  420. ) -> User | None:
  421. """Require authentication if auth is enabled, otherwise return None.
  422. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  423. (via X-API-Key header or Authorization: Bearer bb_xxx).
  424. """
  425. async with async_session() as db:
  426. auth_enabled = await is_auth_enabled(db)
  427. if not auth_enabled:
  428. return None
  429. # Check for API key first (X-API-Key header)
  430. if x_api_key:
  431. api_key = await _validate_api_key(db, x_api_key)
  432. if api_key:
  433. return None # API key valid, allow access
  434. # Check for Bearer token (could be JWT or API key)
  435. if credentials is not None:
  436. token = credentials.credentials
  437. # Check if it's an API key (starts with bb_)
  438. if token.startswith("bb_"):
  439. api_key = await _validate_api_key(db, token)
  440. if api_key:
  441. return None # API key valid, allow access
  442. raise HTTPException(
  443. status_code=status.HTTP_401_UNAUTHORIZED,
  444. detail="Invalid API key",
  445. headers={"WWW-Authenticate": "Bearer"},
  446. )
  447. # Otherwise treat as JWT
  448. try:
  449. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  450. username: str = payload.get("sub")
  451. if username is None:
  452. raise HTTPException(
  453. status_code=status.HTTP_401_UNAUTHORIZED,
  454. detail="Could not validate credentials",
  455. headers={"WWW-Authenticate": "Bearer"},
  456. )
  457. jti: str | None = payload.get("jti")
  458. if not jti or await is_jti_revoked(jti):
  459. raise HTTPException(
  460. status_code=status.HTTP_401_UNAUTHORIZED,
  461. detail="Could not validate credentials",
  462. headers={"WWW-Authenticate": "Bearer"},
  463. )
  464. iat: int | float | None = payload.get("iat")
  465. except JWTError:
  466. raise HTTPException(
  467. status_code=status.HTTP_401_UNAUTHORIZED,
  468. detail="Could not validate credentials",
  469. headers={"WWW-Authenticate": "Bearer"},
  470. )
  471. user = await get_user_by_username(db, username)
  472. if user is None or not user.is_active:
  473. raise HTTPException(
  474. status_code=status.HTTP_401_UNAUTHORIZED,
  475. detail="Could not validate credentials",
  476. headers={"WWW-Authenticate": "Bearer"},
  477. )
  478. if not _is_token_fresh(iat, user):
  479. raise HTTPException(
  480. status_code=status.HTTP_401_UNAUTHORIZED,
  481. detail="Could not validate credentials",
  482. headers={"WWW-Authenticate": "Bearer"},
  483. )
  484. return user
  485. # No credentials provided
  486. raise HTTPException(
  487. status_code=status.HTTP_401_UNAUTHORIZED,
  488. detail="Authentication required",
  489. headers={"WWW-Authenticate": "Bearer"},
  490. )
  491. def require_role(required_role: str):
  492. """Dependency factory for role-based access control."""
  493. async def role_checker(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  494. if current_user.role != required_role:
  495. raise HTTPException(
  496. status_code=status.HTTP_403_FORBIDDEN,
  497. detail=f"Requires {required_role} role",
  498. )
  499. return current_user
  500. return role_checker
  501. def require_admin_if_auth_enabled():
  502. """Dependency factory that requires admin role if auth is enabled."""
  503. async def admin_checker(
  504. current_user: Annotated[User | None, Depends(require_auth_if_enabled)] = None,
  505. ) -> User | None:
  506. if current_user is None:
  507. return None # Auth not enabled, allow access
  508. if current_user.role != "admin":
  509. raise HTTPException(
  510. status_code=status.HTTP_403_FORBIDDEN,
  511. detail="Requires admin role",
  512. )
  513. return current_user
  514. return admin_checker
  515. def generate_api_key() -> tuple[str, str, str]:
  516. """Generate a new API key.
  517. Returns:
  518. tuple: (full_key, key_hash, key_prefix)
  519. - full_key: The complete API key (only shown once on creation)
  520. - key_hash: Hashed version for storage and verification
  521. - key_prefix: First 8 characters for display purposes
  522. """
  523. # Generate a secure random API key (32 bytes = 64 hex characters)
  524. full_key = f"bb_{secrets.token_urlsafe(32)}"
  525. key_hash = get_password_hash(full_key)
  526. key_prefix = full_key[:8] + "..." if len(full_key) > 8 else full_key
  527. return full_key, key_hash, key_prefix
  528. async def get_api_key(
  529. authorization: Annotated[str | None, Header(alias="Authorization")] = None,
  530. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  531. db: AsyncSession = Depends(get_db),
  532. ) -> APIKey:
  533. """Get and validate API key from request headers.
  534. Checks both 'Authorization: Bearer <key>' and 'X-API-Key: <key>' headers.
  535. """
  536. api_key_value = None
  537. if x_api_key:
  538. api_key_value = x_api_key
  539. elif authorization and authorization.startswith("Bearer "):
  540. api_key_value = authorization.replace("Bearer ", "")
  541. if not api_key_value:
  542. raise HTTPException(
  543. status_code=status.HTTP_401_UNAUTHORIZED,
  544. detail="API key required. Provide 'X-API-Key' header or 'Authorization: Bearer <key>'",
  545. )
  546. # M-NEW-2: Pre-filter by key_prefix (first 8 chars) to avoid O(n) pbkdf2 over all
  547. # enabled keys — same fix as in _validate_api_key (L-1 from previous review).
  548. key_lookup = api_key_value[:8] if len(api_key_value) >= 8 else api_key_value
  549. result = await db.execute(
  550. select(APIKey).where(
  551. APIKey.enabled.is_(True),
  552. APIKey.key_prefix.like(
  553. key_lookup.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%",
  554. escape="\\",
  555. ),
  556. )
  557. )
  558. api_keys = result.scalars().all()
  559. for api_key in api_keys:
  560. # Check if key matches (verify against hash)
  561. if verify_password(api_key_value, api_key.key_hash):
  562. # Check expiration
  563. if api_key.expires_at:
  564. expires = api_key.expires_at
  565. if expires.tzinfo is None:
  566. expires = expires.replace(tzinfo=timezone.utc)
  567. if expires < datetime.now(timezone.utc):
  568. raise HTTPException(
  569. status_code=status.HTTP_401_UNAUTHORIZED,
  570. detail="API key has expired",
  571. )
  572. # Update last_used timestamp
  573. api_key.last_used = datetime.now(timezone.utc)
  574. await db.commit()
  575. return api_key
  576. raise HTTPException(
  577. status_code=status.HTTP_401_UNAUTHORIZED,
  578. detail="Invalid API key",
  579. )
  580. def check_permission(api_key: APIKey, permission: str) -> None:
  581. """Check if API key has the required permission.
  582. Args:
  583. api_key: The API key object
  584. permission: One of 'queue', 'control_printer', 'read_status'
  585. Raises:
  586. HTTPException: If permission is not granted
  587. """
  588. permission_map = {
  589. "queue": "can_queue",
  590. "control_printer": "can_control_printer",
  591. "read_status": "can_read_status",
  592. }
  593. if permission not in permission_map:
  594. raise HTTPException(
  595. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  596. detail=f"Unknown permission: {permission}",
  597. )
  598. attr_name = permission_map[permission]
  599. if not getattr(api_key, attr_name, False):
  600. raise HTTPException(
  601. status_code=status.HTTP_403_FORBIDDEN,
  602. detail=f"API key does not have '{permission}' permission",
  603. )
  604. def check_printer_access(api_key: APIKey, printer_id: int) -> None:
  605. """Check if API key has access to the specified printer.
  606. Args:
  607. api_key: The API key object
  608. printer_id: The printer ID to check access for
  609. Raises:
  610. HTTPException: If access is denied
  611. """
  612. # None = global key, access to all printers
  613. if api_key.printer_ids is None:
  614. return
  615. # Empty list or printer not in allowed list = no access
  616. if printer_id not in api_key.printer_ids:
  617. raise HTTPException(
  618. status_code=status.HTTP_403_FORBIDDEN,
  619. detail=f"API key does not have access to printer {printer_id}",
  620. )
  621. # Convenience dependencies - these are functions that return Depends objects
  622. def RequireAdmin():
  623. """Dependency that requires admin role."""
  624. return Depends(require_role("admin"))
  625. def RequireAdminIfAuthEnabled():
  626. """Dependency that requires admin role if auth is enabled."""
  627. return Depends(require_admin_if_auth_enabled())
  628. def require_permission(*permissions: str | Permission):
  629. """Dependency factory that requires user to have ALL specified permissions.
  630. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  631. (via X-API-Key header or Authorization: Bearer bb_xxx).
  632. Args:
  633. *permissions: Permission strings or Permission enum values to require
  634. Returns:
  635. A dependency function that validates permissions
  636. """
  637. # Convert Permission enums to strings
  638. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  639. async def permission_checker(
  640. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  641. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  642. ) -> User | None:
  643. async with async_session() as db:
  644. # Check for API key first (X-API-Key header)
  645. if x_api_key:
  646. api_key = await _validate_api_key(db, x_api_key)
  647. if api_key:
  648. return None # API key valid, allow access
  649. credentials_exception = HTTPException(
  650. status_code=status.HTTP_401_UNAUTHORIZED,
  651. detail="Could not validate credentials",
  652. headers={"WWW-Authenticate": "Bearer"},
  653. )
  654. if credentials is None:
  655. raise credentials_exception
  656. token = credentials.credentials
  657. # Check if it's an API key (starts with bb_)
  658. if token.startswith("bb_"):
  659. api_key = await _validate_api_key(db, token)
  660. if api_key:
  661. return None # API key valid, allow access
  662. raise HTTPException(
  663. status_code=status.HTTP_401_UNAUTHORIZED,
  664. detail="Invalid API key",
  665. headers={"WWW-Authenticate": "Bearer"},
  666. )
  667. # Otherwise treat as JWT
  668. try:
  669. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  670. username: str = payload.get("sub")
  671. if username is None:
  672. raise credentials_exception
  673. jti: str | None = payload.get("jti")
  674. if not jti or await is_jti_revoked(jti):
  675. raise credentials_exception
  676. iat: int | float | None = payload.get("iat")
  677. except JWTError:
  678. raise credentials_exception
  679. user = await get_user_by_username(db, username)
  680. if user is None or not user.is_active:
  681. raise credentials_exception
  682. if not _is_token_fresh(iat, user):
  683. raise credentials_exception
  684. if not user.has_all_permissions(*perm_strings):
  685. raise HTTPException(
  686. status_code=status.HTTP_403_FORBIDDEN,
  687. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  688. )
  689. return user
  690. return permission_checker
  691. def require_permission_if_auth_enabled(*permissions: str | Permission):
  692. """Dependency factory that checks permissions only if auth is enabled.
  693. This provides backward compatibility - when auth is disabled, all access is allowed.
  694. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  695. (via X-API-Key header or Authorization: Bearer bb_xxx).
  696. Args:
  697. *permissions: Permission strings or Permission enum values to require
  698. Returns:
  699. A dependency function that validates permissions if auth is enabled
  700. """
  701. # Convert Permission enums to strings
  702. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  703. async def permission_checker(
  704. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  705. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  706. ) -> User | None:
  707. async with async_session() as db:
  708. auth_enabled = await is_auth_enabled(db)
  709. if not auth_enabled:
  710. return None # Auth disabled, allow access
  711. # Check for API key first (X-API-Key header)
  712. if x_api_key:
  713. api_key = await _validate_api_key(db, x_api_key)
  714. if api_key:
  715. return None # API key valid, allow access
  716. # Check for Bearer token (could be JWT or API key)
  717. if credentials is not None:
  718. token = credentials.credentials
  719. # Check if it's an API key (starts with bb_)
  720. if token.startswith("bb_"):
  721. api_key = await _validate_api_key(db, token)
  722. if api_key:
  723. return None # API key valid, allow access
  724. raise HTTPException(
  725. status_code=status.HTTP_401_UNAUTHORIZED,
  726. detail="Invalid API key",
  727. headers={"WWW-Authenticate": "Bearer"},
  728. )
  729. # Otherwise treat as JWT
  730. try:
  731. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  732. username: str = payload.get("sub")
  733. if username is None:
  734. raise HTTPException(
  735. status_code=status.HTTP_401_UNAUTHORIZED,
  736. detail="Could not validate credentials",
  737. headers={"WWW-Authenticate": "Bearer"},
  738. )
  739. jti: str | None = payload.get("jti")
  740. if not jti or await is_jti_revoked(jti):
  741. raise HTTPException(
  742. status_code=status.HTTP_401_UNAUTHORIZED,
  743. detail="Could not validate credentials",
  744. headers={"WWW-Authenticate": "Bearer"},
  745. )
  746. iat: int | float | None = payload.get("iat")
  747. except JWTError:
  748. raise HTTPException(
  749. status_code=status.HTTP_401_UNAUTHORIZED,
  750. detail="Could not validate credentials",
  751. headers={"WWW-Authenticate": "Bearer"},
  752. )
  753. user = await get_user_by_username(db, username)
  754. if user is None or not user.is_active:
  755. raise HTTPException(
  756. status_code=status.HTTP_401_UNAUTHORIZED,
  757. detail="Could not validate credentials",
  758. headers={"WWW-Authenticate": "Bearer"},
  759. )
  760. if not _is_token_fresh(iat, user):
  761. raise HTTPException(
  762. status_code=status.HTTP_401_UNAUTHORIZED,
  763. detail="Could not validate credentials",
  764. headers={"WWW-Authenticate": "Bearer"},
  765. )
  766. if not user.has_all_permissions(*perm_strings):
  767. raise HTTPException(
  768. status_code=status.HTTP_403_FORBIDDEN,
  769. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  770. )
  771. return user
  772. # No credentials provided
  773. raise HTTPException(
  774. status_code=status.HTTP_401_UNAUTHORIZED,
  775. detail="Authentication required",
  776. headers={"WWW-Authenticate": "Bearer"},
  777. )
  778. return permission_checker
  779. def RequirePermission(*permissions: str | Permission):
  780. """Convenience dependency that requires ALL specified permissions."""
  781. return Depends(require_permission(*permissions))
  782. def RequirePermissionIfAuthEnabled(*permissions: str | Permission):
  783. """Convenience dependency that requires permissions if auth is enabled."""
  784. return Depends(require_permission_if_auth_enabled(*permissions))
  785. def require_camera_stream_token_if_auth_enabled():
  786. """Dependency that validates a camera stream token query param when auth is enabled.
  787. Used for camera stream/snapshot endpoints that are loaded via <img> tags
  788. which cannot send Authorization headers. The frontend obtains a token from
  789. POST /printers/camera/stream-token and appends it as ?token=xxx.
  790. """
  791. async def checker(token: str | None = None) -> None:
  792. async with async_session() as db:
  793. if not await is_auth_enabled(db):
  794. return # Auth disabled, allow access
  795. if not token or not await verify_camera_stream_token(token):
  796. raise HTTPException(
  797. status_code=status.HTTP_401_UNAUTHORIZED,
  798. detail="Valid camera stream token required. Obtain one from POST /api/v1/printers/camera/stream-token",
  799. )
  800. return checker
  801. RequireCameraStreamTokenIfAuthEnabled = Depends(require_camera_stream_token_if_auth_enabled())
  802. def require_ownership_permission(
  803. all_permission: str | Permission,
  804. own_permission: str | Permission,
  805. ):
  806. """Dependency factory for ownership-based permission checks.
  807. - User with `all_permission` can modify any item
  808. - User with `own_permission` can only modify items where created_by_id == user.id
  809. - Ownerless items (created_by_id = null) require `all_permission`
  810. - API keys (via X-API-Key header or Bearer bb_xxx) get full access (can_modify_all=True)
  811. Returns:
  812. A dependency function that 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. all_perm = all_permission.value if isinstance(all_permission, Permission) else all_permission
  817. own_perm = own_permission.value if isinstance(own_permission, Permission) else own_permission
  818. async def checker(
  819. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  820. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  821. ) -> tuple[User | None, bool]:
  822. """Returns (user, can_modify_all).
  823. - can_modify_all=True: user can modify any item
  824. - can_modify_all=False: user can only modify their own items
  825. """
  826. async with async_session() as db:
  827. auth_enabled = await is_auth_enabled(db)
  828. if not auth_enabled:
  829. return None, True # Auth disabled, allow all
  830. # Check for API key first (X-API-Key header)
  831. if x_api_key:
  832. api_key = await _validate_api_key(db, x_api_key)
  833. if api_key:
  834. return None, True # API key valid, allow all
  835. # Check for Bearer token (could be JWT or API key)
  836. if credentials is not None:
  837. token = credentials.credentials
  838. # Check if it's an API key (starts with bb_)
  839. if token.startswith("bb_"):
  840. api_key = await _validate_api_key(db, token)
  841. if api_key:
  842. return None, True # API key valid, allow all
  843. raise HTTPException(
  844. status_code=status.HTTP_401_UNAUTHORIZED,
  845. detail="Invalid API key",
  846. headers={"WWW-Authenticate": "Bearer"},
  847. )
  848. # Otherwise treat as JWT
  849. try:
  850. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  851. username: str = payload.get("sub")
  852. if username is None:
  853. raise HTTPException(
  854. status_code=status.HTTP_401_UNAUTHORIZED,
  855. detail="Could not validate credentials",
  856. headers={"WWW-Authenticate": "Bearer"},
  857. )
  858. jti: str | None = payload.get("jti")
  859. if not jti or await is_jti_revoked(jti):
  860. raise HTTPException(
  861. status_code=status.HTTP_401_UNAUTHORIZED,
  862. detail="Could not validate credentials",
  863. headers={"WWW-Authenticate": "Bearer"},
  864. )
  865. iat: int | float | None = payload.get("iat")
  866. except JWTError:
  867. raise HTTPException(
  868. status_code=status.HTTP_401_UNAUTHORIZED,
  869. detail="Could not validate credentials",
  870. headers={"WWW-Authenticate": "Bearer"},
  871. )
  872. user = await get_user_by_username(db, username)
  873. if user is None or not user.is_active:
  874. raise HTTPException(
  875. status_code=status.HTTP_401_UNAUTHORIZED,
  876. detail="Could not validate credentials",
  877. headers={"WWW-Authenticate": "Bearer"},
  878. )
  879. if not _is_token_fresh(iat, user):
  880. raise HTTPException(
  881. status_code=status.HTTP_401_UNAUTHORIZED,
  882. detail="Could not validate credentials",
  883. headers={"WWW-Authenticate": "Bearer"},
  884. )
  885. if user.has_permission(all_perm):
  886. return user, True
  887. if user.has_permission(own_perm):
  888. return user, False
  889. raise HTTPException(
  890. status_code=status.HTTP_403_FORBIDDEN,
  891. detail=f"Missing permission: {own_perm} or {all_perm}",
  892. )
  893. # No credentials provided
  894. raise HTTPException(
  895. status_code=status.HTTP_401_UNAUTHORIZED,
  896. detail="Authentication required",
  897. headers={"WWW-Authenticate": "Bearer"},
  898. )
  899. return checker