auth.py 52 KB

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