auth.py 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753
  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. # GHSA-r2qv-8222-hqg3 (CVSS 9.9) — API key permission enforcement is allowlist-based.
  23. #
  24. # Until 0.2.4.x, ``_check_apikey_permissions`` only consulted the admin denylist
  25. # below. The three documented scope flags on ``APIKey``
  26. # (``can_read_status`` / ``can_queue`` / ``can_control_printer`` / ``can_manage_library``)
  27. # were enforced only by ``check_permission()`` inside ``routes/webhook.py``;
  28. # every other route used ``require_permission_if_auth_enabled`` which fell
  29. # through to the denylist-only path, so an API key with all flags unchecked
  30. # could still stop prints, edit queue items, and read every endpoint not in
  31. # this set. ``require_any_permission_if_auth_enabled`` and
  32. # ``require_ownership_permission`` did not call this helper at all, so admin
  33. # "any-of" routes and ownership-modify routes were entirely ungated for API keys.
  34. #
  35. # Fix: ``_check_apikey_permissions`` now requires every requested permission to
  36. # be present in ``_APIKEY_SCOPE_BY_PERMISSION`` (allowlist), and gates on the
  37. # corresponding scope flag on the API key. Unmapped permissions = 403. This
  38. # means a Permission added to ``core/permissions.py`` without a matching entry
  39. # in ``_APIKEY_SCOPE_BY_PERMISSION`` is automatically denied for API keys —
  40. # the previous denylist shape allowed every new Permission to silently widen
  41. # the API-key surface.
  42. #
  43. # The denylist is retained for documentation / drift-detection only — its
  44. # entries also satisfy "not in the allowlist", so they fail closed regardless.
  45. #
  46. # Mapping rationale (see wiki/features/api-keys.md):
  47. # can_read_status → every ``*_READ`` + camera + stats + system + websocket
  48. # can_queue → queue write ops + archive reprint
  49. # can_control_printer → physical printer + smart-plug control
  50. # can_manage_library → library upload/own + MakerWorld import (separate
  51. # trust level from queue management, hence its own flag)
  52. # admin-only → unmapped (default-deny); covers all create/update/
  53. # delete of admin resources, settings writes, user/
  54. # group/api-key/backup admin ops, discovery scan,
  55. # cloud auth, library ALL-ownership perms, purges
  56. _APIKEY_SCOPE_BY_PERMISSION: dict[Permission, str] = {
  57. # can_read_status — read-only access to status, history, and configuration
  58. Permission.PRINTERS_READ: "can_read_status",
  59. # Legacy flat permissions retained for back-compat with custom API keys —
  60. # the role bootstraps no longer use these, but custom keys may still
  61. # carry can_read_status scope mapping. New endpoints gate on the
  62. # ARCHIVES_READ_OWN / _ALL split (maziggy/bambuddy-security #2).
  63. Permission.ARCHIVES_READ: "can_read_status",
  64. Permission.ARCHIVES_READ_OWN: "can_read_status",
  65. Permission.ARCHIVES_READ_ALL: "can_read_status",
  66. Permission.QUEUE_READ: "can_read_status",
  67. Permission.QUEUE_READ_OWN: "can_read_status",
  68. Permission.QUEUE_READ_ALL: "can_read_status",
  69. Permission.LIBRARY_READ: "can_read_status",
  70. Permission.LIBRARY_READ_OWN: "can_read_status",
  71. Permission.LIBRARY_READ_ALL: "can_read_status",
  72. Permission.PROJECTS_READ: "can_read_status",
  73. Permission.FILAMENTS_READ: "can_read_status",
  74. Permission.INVENTORY_READ: "can_read_status",
  75. Permission.INVENTORY_VIEW_ASSIGNMENTS: "can_read_status",
  76. Permission.INVENTORY_FORECAST_READ: "can_read_status",
  77. Permission.SMART_PLUGS_READ: "can_read_status",
  78. Permission.CAMERA_VIEW: "can_read_status",
  79. Permission.MAINTENANCE_READ: "can_read_status",
  80. Permission.KPROFILES_READ: "can_read_status",
  81. Permission.NOTIFICATIONS_READ: "can_read_status",
  82. Permission.NOTIFICATION_TEMPLATES_READ: "can_read_status",
  83. Permission.EXTERNAL_LINKS_READ: "can_read_status",
  84. Permission.FIRMWARE_READ: "can_read_status",
  85. Permission.AMS_HISTORY_READ: "can_read_status",
  86. Permission.PRINTER_SENSOR_HISTORY_READ: "can_read_status",
  87. Permission.STATS_READ: "can_read_status",
  88. Permission.STATS_FILTER_BY_USER: "can_read_status",
  89. Permission.SYSTEM_READ: "can_read_status",
  90. # SETTINGS_READ stays allowed via read-status so SpoolBuddy kiosks keep
  91. # working (they need the UI-language setting via API key).
  92. Permission.SETTINGS_READ: "can_read_status",
  93. Permission.MAKERWORLD_VIEW: "can_read_status",
  94. Permission.WEBSOCKET_CONNECT: "can_read_status",
  95. # can_queue — queue write ops + reprint (which enqueues an existing archive)
  96. Permission.QUEUE_CREATE: "can_queue",
  97. Permission.QUEUE_UPDATE_OWN: "can_queue",
  98. Permission.QUEUE_UPDATE_ALL: "can_queue",
  99. Permission.QUEUE_DELETE_OWN: "can_queue",
  100. Permission.QUEUE_DELETE_ALL: "can_queue",
  101. Permission.QUEUE_REORDER: "can_queue",
  102. Permission.ARCHIVES_REPRINT_OWN: "can_queue",
  103. Permission.ARCHIVES_REPRINT_ALL: "can_queue",
  104. # can_control_printer — physical-world side effects on hardware
  105. Permission.PRINTERS_CONTROL: "can_control_printer",
  106. Permission.PRINTERS_FILES: "can_control_printer",
  107. Permission.PRINTERS_AMS_RFID: "can_control_printer",
  108. Permission.PRINTERS_CLEAR_PLATE: "can_control_printer",
  109. Permission.SMART_PLUGS_CONTROL: "can_control_printer",
  110. # can_manage_library — file-manager scope (upload/rename/delete library
  111. # entries + MakerWorld import which downloads files into the library).
  112. # OWN and ALL ownership variants map to the same scope so the
  113. # `require_ownership_permission` checker (which gates on `all_perm`)
  114. # passes the API key through. This matches `can_queue` and the
  115. # archives/inventory scopes — API keys have no per-row ownership identity
  116. # (line 1663), so splitting OWN/ALL across allowlist/denylist made the
  117. # whole library curation surface unreachable for API keys (#1832).
  118. # LIBRARY_PURGE stays admin-only as a genuinely destructive op that
  119. # bypasses the soft-delete window.
  120. Permission.LIBRARY_UPLOAD: "can_manage_library",
  121. Permission.LIBRARY_UPDATE_OWN: "can_manage_library",
  122. Permission.LIBRARY_UPDATE_ALL: "can_manage_library",
  123. Permission.LIBRARY_DELETE_OWN: "can_manage_library",
  124. Permission.LIBRARY_DELETE_ALL: "can_manage_library",
  125. Permission.MAKERWORLD_IMPORT: "can_manage_library",
  126. # can_manage_inventory — inventory write scope. Covers the documented
  127. # spool/catalog/forecast write surface AND the SpoolBuddy kiosk endpoints
  128. # (NFC scan, scale reading, system command/update) which used
  129. # INVENTORY_UPDATE as a stand-in for "kiosk write" under the prior
  130. # denylist model. Read-only inventory (INVENTORY_READ etc.) stays under
  131. # can_read_status.
  132. Permission.INVENTORY_CREATE: "can_manage_inventory",
  133. Permission.INVENTORY_UPDATE: "can_manage_inventory",
  134. Permission.INVENTORY_DELETE: "can_manage_inventory",
  135. Permission.INVENTORY_FORECAST_WRITE: "can_manage_inventory",
  136. # can_access_cloud — narrow opt-in scope, gated by the router-level
  137. # ``_cloud_api_key_gate`` and additionally enforced here so the route-
  138. # level ``cloud_caller(Permission.CLOUD_AUTH)`` dep also fails closed
  139. # when the flag is off (defence-in-depth).
  140. Permission.CLOUD_AUTH: "can_access_cloud",
  141. # ORCA_CLOUD_AUTH folds into the same ``can_access_cloud`` scope: same
  142. # trust dimension (third-party cloud access for profile sync), so an
  143. # operator who already accepted "this key can talk to clouds for the
  144. # owner" doesn't need a second toggle for Orca. Splitting later requires
  145. # a new column + migration — easy to add if the trust dimensions diverge.
  146. Permission.ORCA_CLOUD_AUTH: "can_access_cloud",
  147. }
  148. # Retained for documentation, drift-detection, and the prior "administrative
  149. # operations" error string. Entries here are also absent from
  150. # ``_APIKEY_SCOPE_BY_PERMISSION``, so they fail closed via the allowlist; the
  151. # denylist is a redundant explicit "these are admin" marker, not the load-
  152. # bearing security check.
  153. _APIKEY_DENIED_PERMISSIONS: frozenset[Permission] = frozenset(
  154. {
  155. # Settings administration (cred storage; rewriting these reaches SMTP/LDAP/MQTT).
  156. Permission.SETTINGS_UPDATE,
  157. Permission.SETTINGS_BACKUP,
  158. Permission.SETTINGS_RESTORE,
  159. # User / group / API-key administration.
  160. Permission.USERS_READ,
  161. Permission.USERS_CREATE,
  162. Permission.USERS_UPDATE,
  163. Permission.USERS_DELETE,
  164. Permission.GROUPS_READ,
  165. Permission.GROUPS_CREATE,
  166. Permission.GROUPS_UPDATE,
  167. Permission.GROUPS_DELETE,
  168. Permission.API_KEYS_CREATE,
  169. Permission.API_KEYS_UPDATE,
  170. Permission.API_KEYS_DELETE,
  171. Permission.API_KEYS_READ,
  172. # GitHub backup admin + firmware OTA.
  173. Permission.GITHUB_BACKUP,
  174. Permission.GITHUB_RESTORE,
  175. Permission.FIRMWARE_UPDATE,
  176. # Resource administration (printer/project/filament/maintenance/k-profile/etc CRUD).
  177. # API keys with the operational scopes can read these resources via
  178. # *_READ permissions but cannot mutate the catalog/registry itself.
  179. Permission.PRINTERS_CREATE,
  180. Permission.PRINTERS_UPDATE,
  181. Permission.PRINTERS_DELETE,
  182. Permission.ARCHIVES_CREATE,
  183. Permission.ARCHIVES_UPDATE_OWN,
  184. Permission.ARCHIVES_UPDATE_ALL,
  185. Permission.ARCHIVES_DELETE_OWN,
  186. Permission.ARCHIVES_DELETE_ALL,
  187. Permission.ARCHIVES_PURGE,
  188. # LIBRARY_UPDATE_ALL / LIBRARY_DELETE_ALL moved to the allowlist
  189. # under `can_manage_library` (#1832) — split between allow/deny made
  190. # the whole library curation surface unreachable for API keys via
  191. # `require_ownership_permission`. Purge stays denied as a genuinely
  192. # destructive op.
  193. Permission.LIBRARY_PURGE,
  194. Permission.PROJECTS_CREATE,
  195. Permission.PROJECTS_UPDATE,
  196. Permission.PROJECTS_DELETE,
  197. Permission.FILAMENTS_CREATE,
  198. Permission.FILAMENTS_UPDATE,
  199. Permission.FILAMENTS_DELETE,
  200. Permission.MAINTENANCE_CREATE,
  201. Permission.MAINTENANCE_UPDATE,
  202. Permission.MAINTENANCE_DELETE,
  203. Permission.KPROFILES_CREATE,
  204. Permission.KPROFILES_UPDATE,
  205. Permission.KPROFILES_DELETE,
  206. Permission.NOTIFICATIONS_CREATE,
  207. Permission.NOTIFICATIONS_UPDATE,
  208. Permission.NOTIFICATIONS_DELETE,
  209. Permission.NOTIFICATIONS_USER_EMAIL,
  210. Permission.NOTIFICATION_TEMPLATES_UPDATE,
  211. Permission.EXTERNAL_LINKS_CREATE,
  212. Permission.EXTERNAL_LINKS_UPDATE,
  213. Permission.EXTERNAL_LINKS_DELETE,
  214. Permission.SMART_PLUGS_CREATE,
  215. Permission.SMART_PLUGS_UPDATE,
  216. Permission.SMART_PLUGS_DELETE,
  217. # Network scanning — operator only (no API-key scope for this).
  218. Permission.DISCOVERY_SCAN,
  219. }
  220. )
  221. def _resolve_apikey_scope(perm_string: str) -> str | None:
  222. """Return the scope-flag attribute name gating ``perm_string`` for API keys.
  223. None when the permission is unmapped (= admin-only / not API-key-usable).
  224. """
  225. try:
  226. perm = Permission(perm_string)
  227. except ValueError:
  228. return None
  229. return _APIKEY_SCOPE_BY_PERMISSION.get(perm)
  230. def _check_apikey_permissions(api_key: APIKey, perm_strings: list[str], *, require_any: bool = False) -> None:
  231. """Raise 403 unless ``api_key`` is allowed to use ``perm_strings``.
  232. Allowlist semantics: every requested permission MUST be present in
  233. ``_APIKEY_SCOPE_BY_PERMISSION`` AND its scope flag must be True on
  234. ``api_key``. Unmapped permissions = administrative = 403.
  235. By default ALL requested permissions must pass (mirrors
  236. ``require_permission`` / ``require_permission_if_auth_enabled``).
  237. When ``require_any=True``, only one needs to pass (mirrors
  238. ``require_any_permission_if_auth_enabled``).
  239. """
  240. if not perm_strings:
  241. # Defensive: empty perm list means the dep is auth-only, not perm-gated.
  242. # Routes never call us with [] today, but if they did, returning here
  243. # would silently allow — instead, fail closed.
  244. raise HTTPException(
  245. status_code=status.HTTP_403_FORBIDDEN,
  246. detail="API keys cannot be used for unspecified permissions",
  247. )
  248. last_failure: HTTPException | None = None
  249. for perm_str in perm_strings:
  250. scope_attr = _resolve_apikey_scope(perm_str)
  251. if scope_attr is None:
  252. failure = HTTPException(
  253. status_code=status.HTTP_403_FORBIDDEN,
  254. detail="API keys cannot be used for administrative operations",
  255. )
  256. elif not getattr(api_key, scope_attr, False):
  257. failure = HTTPException(
  258. status_code=status.HTTP_403_FORBIDDEN,
  259. detail=f"API key does not have '{scope_attr}' permission",
  260. )
  261. else:
  262. failure = None
  263. if failure is None and require_any:
  264. return # at least one passed
  265. if failure is not None and not require_any:
  266. raise failure
  267. last_failure = failure
  268. if require_any and last_failure is not None:
  269. raise last_failure
  270. def require_energy_cost_update():
  271. """Dependency for ``POST /settings/electricity-price`` (#1356).
  272. Bypasses the ``_APIKEY_DENIED_PERMISSIONS`` ``SETTINGS_UPDATE`` block for
  273. API keys that explicitly opt into ``can_update_energy_cost``. Full
  274. ``SETTINGS_UPDATE`` for API keys stays denied — this is a narrowly-scoped
  275. door for the Home Assistant dynamic-tariff use case documented in
  276. ``wiki/features/energy.md``, not a general settings-write capability.
  277. Accepts:
  278. * Auth disabled → always allowed (matches other settings routes)
  279. * JWT user with ``SETTINGS_UPDATE`` permission
  280. * API key with ``can_update_energy_cost = True``
  281. """
  282. async def permission_checker(
  283. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  284. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  285. ) -> User | None:
  286. async with async_session() as db:
  287. if not await is_auth_enabled(db):
  288. return None
  289. credentials_exception = HTTPException(
  290. status_code=status.HTTP_401_UNAUTHORIZED,
  291. detail="Could not validate credentials",
  292. headers={"WWW-Authenticate": "Bearer"},
  293. )
  294. # API key path — X-API-Key header or Bearer bb_xxx
  295. api_key_value: str | None = None
  296. if x_api_key:
  297. api_key_value = x_api_key
  298. elif credentials is not None and credentials.credentials.startswith("bb_"):
  299. api_key_value = credentials.credentials
  300. if api_key_value is not None:
  301. api_key = await _validate_api_key(db, api_key_value)
  302. if api_key is None:
  303. raise HTTPException(
  304. status_code=status.HTTP_401_UNAUTHORIZED,
  305. detail="Invalid API key",
  306. headers={"WWW-Authenticate": "Bearer"},
  307. )
  308. if not api_key.can_update_energy_cost:
  309. raise HTTPException(
  310. status_code=status.HTTP_403_FORBIDDEN,
  311. detail="API key does not have 'update_energy_cost' permission",
  312. )
  313. return None
  314. # JWT path
  315. if credentials is None:
  316. raise credentials_exception
  317. try:
  318. payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM])
  319. username: str = payload.get("sub")
  320. if username is None:
  321. raise credentials_exception
  322. jti: str | None = payload.get("jti")
  323. if not jti or await is_jti_revoked(jti):
  324. raise credentials_exception
  325. iat: int | float | None = payload.get("iat")
  326. except JWTError:
  327. raise credentials_exception
  328. user = await get_user_by_username(db, username)
  329. if user is None or not user.is_active:
  330. raise credentials_exception
  331. if not _is_token_fresh(iat, user):
  332. raise credentials_exception
  333. if not user.has_all_permissions(Permission.SETTINGS_UPDATE.value):
  334. raise HTTPException(
  335. status_code=status.HTTP_403_FORBIDDEN,
  336. detail=f"Missing required permissions: {Permission.SETTINGS_UPDATE.value}",
  337. )
  338. return user
  339. return permission_checker
  340. # Password hashing
  341. # Use pbkdf2_sha256 instead of bcrypt to avoid 72-byte limit and passlib initialization issues
  342. # pbkdf2_sha256 is a secure password hashing algorithm without bcrypt's limitations
  343. pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto")
  344. def _get_jwt_secret() -> str:
  345. """Get the JWT secret key from environment, file, or generate a new one.
  346. Priority:
  347. 1. JWT_SECRET_KEY environment variable
  348. 2. .jwt_secret file in data directory
  349. 3. Generate new random secret and save to file
  350. Returns:
  351. The JWT secret key
  352. """
  353. # 1. Check environment variable first
  354. env_secret = os.environ.get("JWT_SECRET_KEY")
  355. if env_secret:
  356. logger.info("Using JWT secret from JWT_SECRET_KEY environment variable")
  357. return env_secret
  358. # 2. Check for secret file in data directory
  359. from backend.app.core.paths import resolve_data_dir
  360. data_dir = resolve_data_dir()
  361. secret_file = data_dir / ".jwt_secret"
  362. if secret_file.exists():
  363. try:
  364. secret = secret_file.read_text().strip()
  365. if secret and len(secret) >= 32:
  366. logger.info("Using JWT secret from %s", secret_file)
  367. return secret
  368. except OSError as e:
  369. logger.warning("Failed to read JWT secret file: %s", e)
  370. # 3. Generate new random secret
  371. new_secret = secrets.token_urlsafe(64)
  372. # Try to save it
  373. try:
  374. data_dir.mkdir(parents=True, exist_ok=True)
  375. # Note: CodeQL flags this as "clear-text storage of sensitive information" but this is
  376. # intentional and secure - JWT secrets must be readable by the app, we set 0600 permissions,
  377. # and this is standard practice for self-hosted applications (same as .env files).
  378. secret_file.write_text(new_secret) # nosec B105
  379. # Restrict permissions (owner read/write only)
  380. secret_file.chmod(0o600)
  381. logger.info("Generated new JWT secret and saved to %s", secret_file)
  382. except OSError as e:
  383. logger.warning(
  384. "Could not save JWT secret to file (%s). "
  385. "Secret will be regenerated on restart, invalidating existing tokens. "
  386. "Set JWT_SECRET_KEY environment variable for persistence.",
  387. e,
  388. )
  389. return new_secret
  390. # JWT settings
  391. SECRET_KEY = _get_jwt_secret()
  392. ALGORITHM = "HS256"
  393. ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 # 24 hours (M-2: reduced from 7 days)
  394. # Hard ceiling for the admin-configurable session policy (#1706). 30 days
  395. # matches the Pydantic le=720 on AppSettings.session_max_hours; defense in
  396. # depth so a tampered settings row can't request an absurd lifetime.
  397. SESSION_MAX_HOURS_HARD_CEILING = 720
  398. # HTTP Bearer token
  399. security = HTTPBearer(auto_error=False)
  400. async def resolve_session_max_minutes(db: AsyncSession) -> int:
  401. """Return the session-lifetime ceiling (minutes) honoured by login routes.
  402. Reads ``session_max_hours`` from the settings table (#1706), clamps to
  403. [1h, 720h], and falls back to the audit-default 24h if the row is
  404. missing, blank, or unparseable.
  405. DB errors are NOT caught here — login is already in a DB transaction and
  406. a broken DB must abort the login rather than silently extend or shrink
  407. the session lifetime.
  408. """
  409. default_minutes = ACCESS_TOKEN_EXPIRE_MINUTES
  410. result = await db.execute(select(Settings).where(Settings.key == "session_max_hours"))
  411. row = result.scalar_one_or_none()
  412. if row is None or not row.value:
  413. return default_minutes
  414. try:
  415. hours = int(row.value)
  416. except (TypeError, ValueError):
  417. return default_minutes
  418. if hours < 1:
  419. return default_minutes
  420. if hours > SESSION_MAX_HOURS_HARD_CEILING:
  421. hours = SESSION_MAX_HOURS_HARD_CEILING
  422. return hours * 60
  423. # --- Slicer download tokens ---
  424. # Short-lived, single-use tokens for slicer protocol handlers that can't send
  425. # auth headers. Stored in AuthEphemeralToken (token_type=TokenType.SLICER_DOWNLOAD)
  426. # so they survive server restarts and work in multi-worker deployments (M-3).
  427. SLICER_TOKEN_EXPIRE_MINUTES = 5
  428. async def create_slicer_download_token(resource_type: str, resource_id: int) -> str:
  429. """Create a short-lived, single-use download token for slicer protocol handlers."""
  430. now = datetime.now(timezone.utc)
  431. expires_at = now + timedelta(minutes=SLICER_TOKEN_EXPIRE_MINUTES)
  432. token = secrets.token_urlsafe(24)
  433. resource_key = f"{resource_type}:{resource_id}"
  434. async with async_session() as db:
  435. # Prune expired tokens opportunistically
  436. await db.execute(
  437. delete(AuthEphemeralToken).where(
  438. AuthEphemeralToken.token_type == TokenType.SLICER_DOWNLOAD,
  439. AuthEphemeralToken.expires_at < now,
  440. )
  441. )
  442. db.add(
  443. AuthEphemeralToken(
  444. token=token,
  445. token_type=TokenType.SLICER_DOWNLOAD,
  446. nonce=resource_key,
  447. expires_at=expires_at,
  448. )
  449. )
  450. await db.commit()
  451. return token
  452. async def verify_slicer_download_token(token: str, resource_type: str, resource_id: int) -> bool:
  453. """Verify and atomically consume a slicer download token.
  454. Returns True only if the token is valid, unexpired, and bound to the given resource.
  455. DELETE...RETURNING ensures the token is single-use even under concurrent requests.
  456. M-NEW-1 fix: nonce (resource key) is included in the WHERE clause so the DELETE
  457. only succeeds when the token is presented to the *correct* resource endpoint.
  458. Previously the token was consumed (committed) even when stored_key != expected_key,
  459. permanently invalidating it while returning False to the caller.
  460. """
  461. expected_key = f"{resource_type}:{resource_id}"
  462. now = datetime.now(timezone.utc)
  463. async with async_session() as db:
  464. result = await db.execute(
  465. delete(AuthEphemeralToken)
  466. .where(
  467. AuthEphemeralToken.token == token,
  468. AuthEphemeralToken.token_type == TokenType.SLICER_DOWNLOAD,
  469. AuthEphemeralToken.nonce == expected_key,
  470. AuthEphemeralToken.expires_at > now,
  471. )
  472. .returning(AuthEphemeralToken.id)
  473. )
  474. if result.one_or_none() is None:
  475. return False
  476. await db.commit()
  477. return True
  478. # --- Camera stream tokens ---
  479. # Reusable tokens for camera stream/snapshot endpoints loaded via <img>/<video>
  480. # tags (these cannot send Authorization headers). Unlike slicer tokens they are
  481. # NOT single-use — streams reconnect on errors. Stored in AuthEphemeralToken
  482. # (token_type="camera_stream") for multi-worker compatibility (M-3).
  483. CAMERA_STREAM_TOKEN_EXPIRE_MINUTES = 60
  484. async def create_camera_stream_token() -> str:
  485. """Create a reusable token for camera stream/snapshot access."""
  486. now = datetime.now(timezone.utc)
  487. expires_at = now + timedelta(minutes=CAMERA_STREAM_TOKEN_EXPIRE_MINUTES)
  488. token = secrets.token_urlsafe(24)
  489. async with async_session() as db:
  490. # Prune expired tokens opportunistically
  491. await db.execute(
  492. delete(AuthEphemeralToken).where(
  493. AuthEphemeralToken.token_type == "camera_stream",
  494. AuthEphemeralToken.expires_at < now,
  495. )
  496. )
  497. db.add(
  498. AuthEphemeralToken(
  499. token=token,
  500. token_type="camera_stream",
  501. expires_at=expires_at,
  502. )
  503. )
  504. await db.commit()
  505. return token
  506. WEBSOCKET_TOKEN_EXPIRE_MINUTES = 60
  507. async def create_websocket_token(username: str | None) -> str:
  508. """Create a short-lived token for ``/api/v1/ws`` connections.
  509. Mirrors the camera-stream-token pattern: opaque random string stored
  510. in ``auth_ephemeral_tokens`` with type ``"websocket"`` so the WS
  511. endpoint can verify it *before* calling ``websocket.accept()``.
  512. Records the issuing principal in the ``username`` field — for JWT
  513. callers this is the actual username, for API-keyed callers this is
  514. the empty string (handled in the route layer; we accept None at this
  515. interface so the auth-disabled path doesn't have to fabricate one).
  516. The 60-minute expiry matches camera tokens: long enough to survive
  517. page reloads / brief disconnects, short enough that a leaked token
  518. is not a credential.
  519. """
  520. now = datetime.now(timezone.utc)
  521. expires_at = now + timedelta(minutes=WEBSOCKET_TOKEN_EXPIRE_MINUTES)
  522. token = secrets.token_urlsafe(24)
  523. async with async_session() as db:
  524. # Prune expired tokens opportunistically (same shape as camera).
  525. await db.execute(
  526. delete(AuthEphemeralToken).where(
  527. AuthEphemeralToken.token_type == "websocket",
  528. AuthEphemeralToken.expires_at < now,
  529. )
  530. )
  531. db.add(
  532. AuthEphemeralToken(
  533. token=token,
  534. token_type="websocket",
  535. username=username or "",
  536. expires_at=expires_at,
  537. )
  538. )
  539. await db.commit()
  540. return token
  541. async def verify_websocket_token(token: str) -> str | None:
  542. """Verify a WebSocket connect token.
  543. Returns the recorded ``username`` (possibly ``""`` for API-key
  544. callers, never ``None`` on success) when the token is valid, or
  545. ``None`` when it is missing / expired / unknown. The token is
  546. NOT consumed — a single page reload should not need a new round
  547. trip to mint a replacement.
  548. """
  549. now = datetime.now(timezone.utc)
  550. async with async_session() as db:
  551. result = await db.execute(
  552. select(AuthEphemeralToken).where(
  553. AuthEphemeralToken.token == token,
  554. AuthEphemeralToken.token_type == "websocket",
  555. AuthEphemeralToken.expires_at > now,
  556. )
  557. )
  558. row = result.scalar_one_or_none()
  559. if row is None:
  560. return None
  561. return row.username or ""
  562. async def verify_camera_stream_token(token: str) -> bool:
  563. """Verify a camera stream token is valid (reusable — does not consume it).
  564. Tries the ephemeral 60-minute token first (the common, browser-bound case)
  565. and falls through to long-lived tokens (#1108) for HA / kiosk integrations
  566. that paste a token once and expect it to keep working for days.
  567. """
  568. now = datetime.now(timezone.utc)
  569. async with async_session() as db:
  570. result = await db.execute(
  571. select(AuthEphemeralToken).where(
  572. AuthEphemeralToken.token == token,
  573. AuthEphemeralToken.token_type == "camera_stream",
  574. AuthEphemeralToken.expires_at > now,
  575. )
  576. )
  577. if result.scalar_one_or_none() is not None:
  578. return True
  579. # Long-lived path. Imported lazily so the auth module stays importable
  580. # at startup before the long_lived_tokens model is registered.
  581. from backend.app.services.long_lived_tokens import verify_token as verify_long_lived
  582. record = await verify_long_lived(db, token, scope="camera_stream")
  583. return record is not None
  584. def verify_password(plain_password: str, hashed_password: str) -> bool:
  585. """Verify a password against a hash.
  586. Uses pbkdf2_sha256 which handles long passwords automatically.
  587. """
  588. return pwd_context.verify(plain_password, hashed_password)
  589. def get_password_hash(password: str) -> str:
  590. """Hash a password.
  591. Uses pbkdf2_sha256 which is secure and has no password length limit.
  592. """
  593. return pwd_context.hash(password)
  594. def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
  595. """Create a JWT access token with jti (revocation) and iat (freshness) claims."""
  596. to_encode = data.copy()
  597. now = datetime.now(timezone.utc)
  598. if expires_delta:
  599. expire = now + expires_delta
  600. else:
  601. expire = now + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  602. jti = secrets.token_hex(16)
  603. to_encode.update({"exp": expire, "jti": jti, "iat": now})
  604. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  605. return encoded_jwt
  606. def _is_token_fresh(iat: int | float | None, user: User) -> bool:
  607. """Return False if the token was issued before the user's last password change.
  608. Used to invalidate all sessions after a password reset/change (M-R7-B).
  609. All tokens without an iat claim are unconditionally rejected — every token
  610. issued by this server carries iat, so absence means the token is forged or
  611. from a pre-iat code path whose max TTL at the time (24 h) has long since
  612. expired. The post-#1706 admin-set ceiling does not relax this — an iat-less
  613. token still cannot have been issued by current code.
  614. """
  615. if iat is None:
  616. return False
  617. if not hasattr(user, "password_changed_at") or user.password_changed_at is None:
  618. return True # No password change recorded yet (I2 migration handles this)
  619. token_issued_at = datetime.fromtimestamp(iat, tz=timezone.utc)
  620. pca = user.password_changed_at
  621. if pca.tzinfo is None:
  622. pca = pca.replace(tzinfo=timezone.utc)
  623. # JWT iat is whole seconds; truncate pca so tokens issued in the same second pass.
  624. pca = pca.replace(microsecond=0)
  625. return token_issued_at >= pca
  626. async def revoke_jti(jti: str, expires_at: datetime, username: str | None = None) -> None:
  627. """Store a revoked JWT jti so it is rejected on future requests.
  628. Silently ignores duplicate inserts (e.g. double-logout with the same token).
  629. """
  630. from sqlalchemy.exc import IntegrityError
  631. async with async_session() as db:
  632. revoked = AuthEphemeralToken(
  633. token=jti,
  634. token_type="revoked_jti",
  635. username=username,
  636. expires_at=expires_at,
  637. )
  638. db.add(revoked)
  639. try:
  640. await db.commit()
  641. except IntegrityError:
  642. await db.rollback() # jti already revoked — desired state, ignore
  643. async def is_jti_revoked(jti: str) -> bool:
  644. """Return True if the given jti has been revoked."""
  645. async with async_session() as db:
  646. result = await db.execute(
  647. select(AuthEphemeralToken).where(
  648. AuthEphemeralToken.token == jti,
  649. AuthEphemeralToken.token_type == "revoked_jti",
  650. )
  651. )
  652. return result.scalar_one_or_none() is not None
  653. async def get_user_by_username(db: AsyncSession, username: str) -> User | None:
  654. """Get a user by username (case-insensitive) with groups loaded for permission checks."""
  655. result = await db.execute(
  656. select(User).where(func.lower(User.username) == func.lower(username)).options(selectinload(User.groups))
  657. )
  658. return result.scalar_one_or_none()
  659. async def get_user_by_email(db: AsyncSession, email: str) -> User | None:
  660. """Get a user by email (case-insensitive) with groups loaded for permission checks."""
  661. result = await db.execute(
  662. select(User).where(func.lower(User.email) == func.lower(email)).options(selectinload(User.groups))
  663. )
  664. return result.scalar_one_or_none()
  665. async def authenticate_user(db: AsyncSession, username: str, password: str) -> User | None:
  666. """Authenticate a user by username and password.
  667. Username lookup is case-insensitive. Password is case-sensitive.
  668. LDAP and OIDC users must authenticate via their respective providers.
  669. """
  670. user = await get_user_by_username(db, username)
  671. if not user:
  672. return None
  673. if getattr(user, "auth_source", "local") in ("ldap", "oidc"):
  674. return None # LDAP/OIDC users must authenticate via their provider
  675. if not user.password_hash or not verify_password(password, user.password_hash):
  676. return None
  677. if not user.is_active:
  678. return None
  679. return user
  680. async def authenticate_user_by_email(db: AsyncSession, email: str, password: str) -> User | None:
  681. """Authenticate a user by email and password.
  682. Email lookup is case-insensitive. Password is case-sensitive.
  683. LDAP and OIDC users must authenticate via their respective providers.
  684. """
  685. user = await get_user_by_email(db, email)
  686. if not user:
  687. return None
  688. if getattr(user, "auth_source", "local") in ("ldap", "oidc"):
  689. return None # LDAP/OIDC users must authenticate via their provider
  690. if not user.password_hash or not verify_password(password, user.password_hash):
  691. return None
  692. if not user.is_active:
  693. return None
  694. return user
  695. async def is_auth_enabled(db: AsyncSession) -> bool:
  696. """Check if authentication is enabled.
  697. Fails CLOSED on database errors. A previous version of this function
  698. caught every exception and returned False — silently treating an
  699. unavailable database as "auth is disabled" and granting unauthenticated
  700. access to every endpoint that called it (GHSA-6mf4-q26m-47pv, CVSS 9.8).
  701. An attacker could trigger that fail-open by flooding /api/v1/auth/login
  702. to exhaust the process's file-descriptor budget, then hit a protected
  703. endpoint during the window where the next DB op raised.
  704. Legitimate "auth was never configured" still returns False — the
  705. settings row is simply absent, ``scalar_one_or_none`` returns None,
  706. no exception. Any OTHER failure (connection error, fd exhaustion,
  707. schema mismatch, …) propagates so the caller can deny the request
  708. (503 / 500). Fail-closed is the only safe default for an auth probe.
  709. """
  710. result = await db.execute(select(Settings).where(Settings.key == "auth_enabled"))
  711. setting = result.scalar_one_or_none()
  712. if setting is None:
  713. return False
  714. return setting.value.lower() == "true"
  715. async def _user_from_api_key(db: AsyncSession, api_key: APIKey) -> User | None:
  716. """Resolve the owner of a validated API key, or None for legacy ownerless keys.
  717. Cloud routes (and any route that needs caller identity) read the returned
  718. User to look up per-user state like ``cloud_token``. Legacy keys created
  719. before #1182 have ``user_id IS NULL`` and stay anonymous — they keep working
  720. against non-cloud routes for backward compatibility, but cloud routes will
  721. surface a "recreate this key" error rather than 200 with empty results.
  722. """
  723. if api_key.user_id is None:
  724. return None
  725. result = await db.execute(select(User).where(User.id == api_key.user_id))
  726. user = result.scalar_one_or_none()
  727. if user is None or not user.is_active:
  728. # CASCADE on user delete should prevent a dangling user_id, but if
  729. # someone manually deactivates the owner the key shouldn't suddenly
  730. # gain an "anonymous" identity — drop the request to None so cloud
  731. # access fails closed.
  732. return None
  733. return user
  734. async def _validate_api_key(db: AsyncSession, api_key_value: str) -> APIKey | None:
  735. """Validate an API key and return the APIKey object if valid, None otherwise.
  736. L-1: Pre-filter by key_prefix (first 8 chars) before running pbkdf2 so only
  737. O(1) candidate rows are hashed instead of the full key table. The prefix is
  738. not secret (it is shown in the admin UI), so this does not reduce security.
  739. """
  740. try:
  741. # key_prefix is stored as "<first-8-chars>..." (e.g. "bb_Abc12...").
  742. # Matching on the first 8 chars of the submitted key reduces the scan to
  743. # at most one row in practice (2^40 collision space for 5 base64 chars).
  744. key_lookup = api_key_value[:8] if len(api_key_value) >= 8 else api_key_value
  745. result = await db.execute(
  746. select(APIKey).where(
  747. APIKey.enabled.is_(True),
  748. APIKey.key_prefix.like(
  749. key_lookup.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%", escape="\\"
  750. ),
  751. )
  752. )
  753. api_keys = result.scalars().all()
  754. for api_key in api_keys:
  755. if verify_password(api_key_value, api_key.key_hash):
  756. # Check expiration
  757. if api_key.expires_at:
  758. expires = api_key.expires_at
  759. if expires.tzinfo is None:
  760. expires = expires.replace(tzinfo=timezone.utc)
  761. if expires < datetime.now(timezone.utc):
  762. return None # Expired
  763. # Update last_used timestamp
  764. api_key.last_used = datetime.now(timezone.utc)
  765. await db.commit()
  766. return api_key
  767. except Exception as e: # SEC-AUTH-EXC: validation failure returns None; every caller treats None as "invalid key" → 401 (fail-closed)
  768. logger.warning("API key validation error: %s", e)
  769. return None
  770. async def get_current_user_optional(
  771. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  772. ) -> User | None:
  773. """Get the current authenticated user from JWT token, or None if not authenticated.
  774. Returns None only when NO credentials are supplied. If a token is supplied
  775. but invalid/revoked, raises 401 — a revoked token must not grant anonymous
  776. access (I6).
  777. """
  778. if credentials is None:
  779. return None
  780. _unauthorized = HTTPException(
  781. status_code=status.HTTP_401_UNAUTHORIZED,
  782. detail="Could not validate credentials",
  783. headers={"WWW-Authenticate": "Bearer"},
  784. )
  785. try:
  786. token = credentials.credentials
  787. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  788. username: str = payload.get("sub")
  789. if username is None:
  790. raise _unauthorized
  791. jti: str | None = payload.get("jti")
  792. if not jti or await is_jti_revoked(jti):
  793. raise _unauthorized # I6: revoked token → 401, not anonymous
  794. iat: int | float | None = payload.get("iat")
  795. except JWTError:
  796. raise _unauthorized
  797. async with async_session() as db:
  798. user = await get_user_by_username(db, username)
  799. if user is None or not user.is_active:
  800. raise _unauthorized
  801. if not _is_token_fresh(iat, user):
  802. raise _unauthorized
  803. return user
  804. async def get_current_user(
  805. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  806. ) -> User:
  807. """Get the current authenticated user from JWT token."""
  808. credentials_exception = HTTPException(
  809. status_code=status.HTTP_401_UNAUTHORIZED,
  810. detail="Could not validate credentials",
  811. headers={"WWW-Authenticate": "Bearer"},
  812. )
  813. if credentials is None:
  814. raise credentials_exception
  815. try:
  816. token = credentials.credentials
  817. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  818. username: str = payload.get("sub")
  819. if username is None:
  820. raise credentials_exception
  821. jti: str | None = payload.get("jti")
  822. if not jti or await is_jti_revoked(jti):
  823. raise credentials_exception
  824. iat: int | float | None = payload.get("iat")
  825. except JWTError:
  826. raise credentials_exception
  827. async with async_session() as db:
  828. user = await get_user_by_username(db, username)
  829. if user is None:
  830. raise credentials_exception
  831. if not user.is_active:
  832. raise HTTPException(
  833. status_code=status.HTTP_403_FORBIDDEN,
  834. detail="User account is disabled",
  835. )
  836. if not _is_token_fresh(iat, user):
  837. raise credentials_exception
  838. return user
  839. async def get_current_active_user(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  840. """Get the current active user (alias for clarity)."""
  841. return current_user
  842. async def require_auth_if_enabled(
  843. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  844. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  845. ) -> User | None:
  846. """Require authentication if auth is enabled, otherwise return None.
  847. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  848. (via X-API-Key header or Authorization: Bearer bb_xxx). API keys return
  849. None for backward compatibility — routes that need the API-key owner (i.e.
  850. cloud routes for #1182) resolve it via their own router-level dependency
  851. that stashes ``request.state.api_key_owner``. Returning the owner here
  852. instead would silently grant API-keyed callers access to every route that
  853. fences via ``if current_user is None``, which is a wider surface than
  854. #1182 was designed to expose.
  855. """
  856. async with async_session() as db:
  857. auth_enabled = await is_auth_enabled(db)
  858. if not auth_enabled:
  859. return None
  860. # Check for API key first (X-API-Key header)
  861. if x_api_key:
  862. api_key = await _validate_api_key(db, x_api_key)
  863. if api_key:
  864. return None # API key valid, allow access
  865. # Check for Bearer token (could be JWT or API key)
  866. if credentials is not None:
  867. token = credentials.credentials
  868. # Check if it's an API key (starts with bb_)
  869. if token.startswith("bb_"):
  870. api_key = await _validate_api_key(db, token)
  871. if api_key:
  872. return None # API key valid, allow access
  873. raise HTTPException(
  874. status_code=status.HTTP_401_UNAUTHORIZED,
  875. detail="Invalid API key",
  876. headers={"WWW-Authenticate": "Bearer"},
  877. )
  878. # Otherwise treat as JWT
  879. try:
  880. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  881. username: str = payload.get("sub")
  882. if username is None:
  883. raise HTTPException(
  884. status_code=status.HTTP_401_UNAUTHORIZED,
  885. detail="Could not validate credentials",
  886. headers={"WWW-Authenticate": "Bearer"},
  887. )
  888. jti: str | None = payload.get("jti")
  889. if not jti or await is_jti_revoked(jti):
  890. raise HTTPException(
  891. status_code=status.HTTP_401_UNAUTHORIZED,
  892. detail="Could not validate credentials",
  893. headers={"WWW-Authenticate": "Bearer"},
  894. )
  895. iat: int | float | None = payload.get("iat")
  896. except JWTError:
  897. raise HTTPException(
  898. status_code=status.HTTP_401_UNAUTHORIZED,
  899. detail="Could not validate credentials",
  900. headers={"WWW-Authenticate": "Bearer"},
  901. )
  902. user = await get_user_by_username(db, username)
  903. if user is None or not user.is_active:
  904. raise HTTPException(
  905. status_code=status.HTTP_401_UNAUTHORIZED,
  906. detail="Could not validate credentials",
  907. headers={"WWW-Authenticate": "Bearer"},
  908. )
  909. if not _is_token_fresh(iat, user):
  910. raise HTTPException(
  911. status_code=status.HTTP_401_UNAUTHORIZED,
  912. detail="Could not validate credentials",
  913. headers={"WWW-Authenticate": "Bearer"},
  914. )
  915. return user
  916. # No credentials provided
  917. raise HTTPException(
  918. status_code=status.HTTP_401_UNAUTHORIZED,
  919. detail="Authentication required",
  920. headers={"WWW-Authenticate": "Bearer"},
  921. )
  922. def require_role(required_role: str):
  923. """Dependency factory for role-based access control."""
  924. async def role_checker(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  925. if current_user.role != required_role:
  926. raise HTTPException(
  927. status_code=status.HTTP_403_FORBIDDEN,
  928. detail=f"Requires {required_role} role",
  929. )
  930. return current_user
  931. return role_checker
  932. def require_admin_if_auth_enabled():
  933. """Dependency factory that requires admin role if auth is enabled.
  934. GHSA-r2qv follow-up (audit pattern P3): explicitly fail-closed for API
  935. keys. The previous implementation chained on ``require_auth_if_enabled``
  936. which returns ``None`` for *both* "auth disabled" *and* "valid API
  937. key" — the inner ``admin_checker`` then treated ``None`` as auth-
  938. disabled and admitted the caller. If any route had ever adopted this
  939. dep, any API key with no scope flags set would have satisfied an
  940. admin requirement. The dep distinguishes the two cases by consulting
  941. ``is_auth_enabled`` directly and rejecting API-keyed requests with
  942. 403. "Admin" requires a user-identity role, which API keys do not
  943. carry.
  944. Admin semantics: uses ``User.is_admin`` (``role == "admin"`` OR
  945. Administrators-group membership) so a default-install operator who
  946. was made admin by being added to Administrators rather than by
  947. flipping the legacy role column passes. Earlier this check looked
  948. only at ``role`` and would have locked group-only admins out of the
  949. user-management routes once those routes started requiring it.
  950. """
  951. async def admin_checker(
  952. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  953. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  954. ) -> User | None:
  955. async with async_session() as db:
  956. if not await is_auth_enabled(db):
  957. return None # Auth disabled — no role to check.
  958. # Reject API-keyed requests up front: admin is a user-role
  959. # concept, not a key-scope concept. The right path for
  960. # admin-equivalent API-key access is a specific Permission
  961. # (e.g. SETTINGS_UPDATE) gated by the allowlist, not the
  962. # admin role.
  963. if x_api_key or (credentials and credentials.credentials.startswith("bb_")):
  964. raise HTTPException(
  965. status_code=status.HTTP_403_FORBIDDEN,
  966. detail="Admin operations require a user role; API keys cannot be admins",
  967. )
  968. # Standard JWT path: validate and require admin role.
  969. if credentials is None:
  970. raise HTTPException(
  971. status_code=status.HTTP_401_UNAUTHORIZED,
  972. detail="Authentication required",
  973. headers={"WWW-Authenticate": "Bearer"},
  974. )
  975. try:
  976. payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM])
  977. username: str = payload.get("sub")
  978. if username is None:
  979. raise HTTPException(
  980. status_code=status.HTTP_401_UNAUTHORIZED,
  981. detail="Could not validate credentials",
  982. headers={"WWW-Authenticate": "Bearer"},
  983. )
  984. jti: str | None = payload.get("jti")
  985. if not jti or await is_jti_revoked(jti):
  986. raise HTTPException(
  987. status_code=status.HTTP_401_UNAUTHORIZED,
  988. detail="Could not validate credentials",
  989. headers={"WWW-Authenticate": "Bearer"},
  990. )
  991. iat: int | float | None = payload.get("iat")
  992. except JWTError:
  993. raise HTTPException(
  994. status_code=status.HTTP_401_UNAUTHORIZED,
  995. detail="Could not validate credentials",
  996. headers={"WWW-Authenticate": "Bearer"},
  997. )
  998. user = await get_user_by_username(db, username)
  999. if user is None or not user.is_active:
  1000. raise HTTPException(
  1001. status_code=status.HTTP_401_UNAUTHORIZED,
  1002. detail="Could not validate credentials",
  1003. headers={"WWW-Authenticate": "Bearer"},
  1004. )
  1005. if not _is_token_fresh(iat, user):
  1006. raise HTTPException(
  1007. status_code=status.HTTP_401_UNAUTHORIZED,
  1008. detail="Could not validate credentials",
  1009. headers={"WWW-Authenticate": "Bearer"},
  1010. )
  1011. if not user.is_admin:
  1012. raise HTTPException(
  1013. status_code=status.HTTP_403_FORBIDDEN,
  1014. detail="Requires admin role",
  1015. )
  1016. return user
  1017. return admin_checker
  1018. def generate_api_key() -> tuple[str, str, str]:
  1019. """Generate a new API key.
  1020. Returns:
  1021. tuple: (full_key, key_hash, key_prefix)
  1022. - full_key: The complete API key (only shown once on creation)
  1023. - key_hash: Hashed version for storage and verification
  1024. - key_prefix: First 8 characters for display purposes
  1025. """
  1026. # Generate a secure random API key (32 bytes = 64 hex characters)
  1027. full_key = f"bb_{secrets.token_urlsafe(32)}"
  1028. key_hash = get_password_hash(full_key)
  1029. key_prefix = full_key[:8] + "..." if len(full_key) > 8 else full_key
  1030. return full_key, key_hash, key_prefix
  1031. async def get_api_key(
  1032. authorization: Annotated[str | None, Header(alias="Authorization")] = None,
  1033. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1034. db: AsyncSession = Depends(get_db),
  1035. ) -> APIKey:
  1036. """Get and validate API key from request headers.
  1037. Checks both 'Authorization: Bearer <key>' and 'X-API-Key: <key>' headers.
  1038. """
  1039. api_key_value = None
  1040. if x_api_key:
  1041. api_key_value = x_api_key
  1042. elif authorization and authorization.startswith("Bearer "):
  1043. api_key_value = authorization.replace("Bearer ", "")
  1044. if not api_key_value:
  1045. raise HTTPException(
  1046. status_code=status.HTTP_401_UNAUTHORIZED,
  1047. detail="API key required. Provide 'X-API-Key' header or 'Authorization: Bearer <key>'",
  1048. )
  1049. # Pre-filter by key_prefix to avoid O(n) pbkdf2 hashes across all enabled keys.
  1050. key_lookup = api_key_value[:8] if len(api_key_value) >= 8 else api_key_value
  1051. result = await db.execute(
  1052. select(APIKey).where(
  1053. APIKey.enabled.is_(True),
  1054. APIKey.key_prefix.like(
  1055. key_lookup.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%",
  1056. escape="\\",
  1057. ),
  1058. )
  1059. )
  1060. api_keys = result.scalars().all()
  1061. for api_key in api_keys:
  1062. # Check if key matches (verify against hash)
  1063. if verify_password(api_key_value, api_key.key_hash):
  1064. # Check expiration
  1065. if api_key.expires_at:
  1066. expires = api_key.expires_at
  1067. if expires.tzinfo is None:
  1068. expires = expires.replace(tzinfo=timezone.utc)
  1069. if expires < datetime.now(timezone.utc):
  1070. raise HTTPException(
  1071. status_code=status.HTTP_401_UNAUTHORIZED,
  1072. detail="API key has expired",
  1073. )
  1074. # Update last_used timestamp
  1075. api_key.last_used = datetime.now(timezone.utc)
  1076. await db.commit()
  1077. return api_key
  1078. raise HTTPException(
  1079. status_code=status.HTTP_401_UNAUTHORIZED,
  1080. detail="Invalid API key",
  1081. )
  1082. async def caller_is_api_key(
  1083. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1084. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1085. ) -> bool:
  1086. """Return True when the request is authenticated via API key (X-API-Key or Bearer bb_xxx)."""
  1087. if x_api_key:
  1088. return True
  1089. return credentials is not None and credentials.credentials.startswith("bb_")
  1090. def check_permission(api_key: APIKey, permission: str) -> None:
  1091. """Check if API key has the required permission.
  1092. Args:
  1093. api_key: The API key object
  1094. permission: One of 'queue', 'control_printer', 'read_status'
  1095. Raises:
  1096. HTTPException: If permission is not granted
  1097. """
  1098. permission_map = {
  1099. "queue": "can_queue",
  1100. "control_printer": "can_control_printer",
  1101. "read_status": "can_read_status",
  1102. }
  1103. if permission not in permission_map:
  1104. raise HTTPException(
  1105. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  1106. detail=f"Unknown permission: {permission}",
  1107. )
  1108. attr_name = permission_map[permission]
  1109. if not getattr(api_key, attr_name, False):
  1110. raise HTTPException(
  1111. status_code=status.HTTP_403_FORBIDDEN,
  1112. detail=f"API key does not have '{permission}' permission",
  1113. )
  1114. def check_printer_access(api_key: APIKey, printer_id: int) -> None:
  1115. """Check if API key has access to the specified printer.
  1116. Args:
  1117. api_key: The API key object
  1118. printer_id: The printer ID to check access for
  1119. Raises:
  1120. HTTPException: If access is denied
  1121. """
  1122. # None = global key, access to all printers
  1123. if api_key.printer_ids is None:
  1124. return
  1125. # Empty list or printer not in allowed list = no access
  1126. if printer_id not in api_key.printer_ids:
  1127. raise HTTPException(
  1128. status_code=status.HTTP_403_FORBIDDEN,
  1129. detail=f"API key does not have access to printer {printer_id}",
  1130. )
  1131. # Convenience dependencies - these are functions that return Depends objects
  1132. def RequireAdmin():
  1133. """Dependency that requires admin role."""
  1134. return Depends(require_role("admin"))
  1135. def RequireAdminIfAuthEnabled():
  1136. """Dependency that requires admin role if auth is enabled."""
  1137. return Depends(require_admin_if_auth_enabled())
  1138. def require_permission(*permissions: str | Permission):
  1139. """Dependency factory that requires user to have ALL specified permissions.
  1140. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  1141. (via X-API-Key header or Authorization: Bearer bb_xxx).
  1142. Args:
  1143. *permissions: Permission strings or Permission enum values to require
  1144. Returns:
  1145. A dependency function that validates permissions
  1146. """
  1147. # Convert Permission enums to strings
  1148. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  1149. async def permission_checker(
  1150. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1151. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1152. ) -> User | None:
  1153. async with async_session() as db:
  1154. # Check for API key first (X-API-Key header)
  1155. if x_api_key:
  1156. api_key = await _validate_api_key(db, x_api_key)
  1157. if api_key:
  1158. _check_apikey_permissions(api_key, perm_strings)
  1159. return None # API key valid, allow access
  1160. credentials_exception = HTTPException(
  1161. status_code=status.HTTP_401_UNAUTHORIZED,
  1162. detail="Could not validate credentials",
  1163. headers={"WWW-Authenticate": "Bearer"},
  1164. )
  1165. if credentials is None:
  1166. raise credentials_exception
  1167. token = credentials.credentials
  1168. # Check if it's an API key (starts with bb_)
  1169. if token.startswith("bb_"):
  1170. api_key = await _validate_api_key(db, token)
  1171. if api_key:
  1172. _check_apikey_permissions(api_key, perm_strings)
  1173. return None # API key valid, allow access
  1174. raise HTTPException(
  1175. status_code=status.HTTP_401_UNAUTHORIZED,
  1176. detail="Invalid API key",
  1177. headers={"WWW-Authenticate": "Bearer"},
  1178. )
  1179. # Otherwise treat as JWT
  1180. try:
  1181. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  1182. username: str = payload.get("sub")
  1183. if username is None:
  1184. raise credentials_exception
  1185. jti: str | None = payload.get("jti")
  1186. if not jti or await is_jti_revoked(jti):
  1187. raise credentials_exception
  1188. iat: int | float | None = payload.get("iat")
  1189. except JWTError:
  1190. raise credentials_exception
  1191. user = await get_user_by_username(db, username)
  1192. if user is None or not user.is_active:
  1193. raise credentials_exception
  1194. if not _is_token_fresh(iat, user):
  1195. raise credentials_exception
  1196. if not user.has_all_permissions(*perm_strings):
  1197. raise HTTPException(
  1198. status_code=status.HTTP_403_FORBIDDEN,
  1199. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  1200. )
  1201. return user
  1202. return permission_checker
  1203. def require_permission_if_auth_enabled(*permissions: str | Permission):
  1204. """Dependency factory that checks permissions only if auth is enabled.
  1205. This provides backward compatibility - when auth is disabled, all access is allowed.
  1206. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  1207. (via X-API-Key header or Authorization: Bearer bb_xxx).
  1208. Args:
  1209. *permissions: Permission strings or Permission enum values to require
  1210. Returns:
  1211. A dependency function that validates permissions if auth is enabled
  1212. """
  1213. # Convert Permission enums to strings
  1214. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  1215. async def permission_checker(
  1216. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1217. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1218. ) -> User | None:
  1219. async with async_session() as db:
  1220. auth_enabled = await is_auth_enabled(db)
  1221. if not auth_enabled:
  1222. return None # Auth disabled, allow access
  1223. # Check for API key first (X-API-Key header). API-keyed requests
  1224. # bypass the JWT permission check entirely — their scopes live on
  1225. # the APIKey row (can_queue / can_control_printer / can_read_status
  1226. # / can_access_cloud / printer_ids), and the dep returns None so
  1227. # routes don't gain a synthetic User identity that would grant
  1228. # access to fenced surfaces like long-lived-token management.
  1229. # Cloud routes (#1182) resolve the API-key owner separately via
  1230. # their own router-level dependency; see ``cloud.py``.
  1231. if x_api_key:
  1232. api_key = await _validate_api_key(db, x_api_key)
  1233. if api_key:
  1234. _check_apikey_permissions(api_key, perm_strings)
  1235. return None # API key valid, allow access
  1236. # Check for Bearer token (could be JWT or API key)
  1237. if credentials is not None:
  1238. token = credentials.credentials
  1239. # Check if it's an API key (starts with bb_)
  1240. if token.startswith("bb_"):
  1241. api_key = await _validate_api_key(db, token)
  1242. if api_key:
  1243. _check_apikey_permissions(api_key, perm_strings)
  1244. return None # API key valid, allow access
  1245. raise HTTPException(
  1246. status_code=status.HTTP_401_UNAUTHORIZED,
  1247. detail="Invalid API key",
  1248. headers={"WWW-Authenticate": "Bearer"},
  1249. )
  1250. # Otherwise treat as JWT
  1251. try:
  1252. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  1253. username: str = payload.get("sub")
  1254. if username is None:
  1255. raise HTTPException(
  1256. status_code=status.HTTP_401_UNAUTHORIZED,
  1257. detail="Could not validate credentials",
  1258. headers={"WWW-Authenticate": "Bearer"},
  1259. )
  1260. jti: str | None = payload.get("jti")
  1261. if not jti or await is_jti_revoked(jti):
  1262. raise HTTPException(
  1263. status_code=status.HTTP_401_UNAUTHORIZED,
  1264. detail="Could not validate credentials",
  1265. headers={"WWW-Authenticate": "Bearer"},
  1266. )
  1267. iat: int | float | None = payload.get("iat")
  1268. except JWTError:
  1269. raise HTTPException(
  1270. status_code=status.HTTP_401_UNAUTHORIZED,
  1271. detail="Could not validate credentials",
  1272. headers={"WWW-Authenticate": "Bearer"},
  1273. )
  1274. user = await get_user_by_username(db, username)
  1275. if user is None or not user.is_active:
  1276. raise HTTPException(
  1277. status_code=status.HTTP_401_UNAUTHORIZED,
  1278. detail="Could not validate credentials",
  1279. headers={"WWW-Authenticate": "Bearer"},
  1280. )
  1281. if not _is_token_fresh(iat, user):
  1282. raise HTTPException(
  1283. status_code=status.HTTP_401_UNAUTHORIZED,
  1284. detail="Could not validate credentials",
  1285. headers={"WWW-Authenticate": "Bearer"},
  1286. )
  1287. if not user.has_all_permissions(*perm_strings):
  1288. raise HTTPException(
  1289. status_code=status.HTTP_403_FORBIDDEN,
  1290. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  1291. )
  1292. return user
  1293. # No credentials provided
  1294. raise HTTPException(
  1295. status_code=status.HTTP_401_UNAUTHORIZED,
  1296. detail="Authentication required",
  1297. headers={"WWW-Authenticate": "Bearer"},
  1298. )
  1299. return permission_checker
  1300. def RequirePermission(*permissions: str | Permission):
  1301. """Convenience dependency that requires ALL specified permissions."""
  1302. return Depends(require_permission(*permissions))
  1303. def RequirePermissionIfAuthEnabled(*permissions: str | Permission):
  1304. """Convenience dependency that requires permissions if auth is enabled."""
  1305. return Depends(require_permission_if_auth_enabled(*permissions))
  1306. def require_any_permission_if_auth_enabled(*permissions: str | Permission):
  1307. """Dependency factory that requires AT LEAST ONE of the given permissions when auth is enabled."""
  1308. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  1309. async def checker(
  1310. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1311. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1312. ) -> User | None:
  1313. async with async_session() as db:
  1314. auth_enabled = await is_auth_enabled(db)
  1315. if not auth_enabled:
  1316. return None
  1317. if x_api_key:
  1318. api_key = await _validate_api_key(db, x_api_key)
  1319. if api_key:
  1320. # GHSA-r2qv-8222-hqg3: previously returned None unconditionally,
  1321. # letting any valid API key satisfy admin "any-of" route
  1322. # dependencies. require_any → at-least-one must pass the scope check.
  1323. _check_apikey_permissions(api_key, perm_strings, require_any=True)
  1324. return None
  1325. if credentials is not None:
  1326. token = credentials.credentials
  1327. if token.startswith("bb_"):
  1328. api_key = await _validate_api_key(db, token)
  1329. if api_key:
  1330. _check_apikey_permissions(api_key, perm_strings, require_any=True)
  1331. return None
  1332. raise HTTPException(
  1333. status_code=status.HTTP_401_UNAUTHORIZED,
  1334. detail="Invalid API key",
  1335. headers={"WWW-Authenticate": "Bearer"},
  1336. )
  1337. try:
  1338. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  1339. username: str = payload.get("sub")
  1340. if username is None:
  1341. raise HTTPException(
  1342. status_code=status.HTTP_401_UNAUTHORIZED,
  1343. detail="Could not validate credentials",
  1344. headers={"WWW-Authenticate": "Bearer"},
  1345. )
  1346. jti: str | None = payload.get("jti")
  1347. if not jti or await is_jti_revoked(jti):
  1348. raise HTTPException(
  1349. status_code=status.HTTP_401_UNAUTHORIZED,
  1350. detail="Could not validate credentials",
  1351. headers={"WWW-Authenticate": "Bearer"},
  1352. )
  1353. iat: int | float | None = payload.get("iat")
  1354. except JWTError:
  1355. raise HTTPException(
  1356. status_code=status.HTTP_401_UNAUTHORIZED,
  1357. detail="Could not validate credentials",
  1358. headers={"WWW-Authenticate": "Bearer"},
  1359. )
  1360. user = await get_user_by_username(db, username)
  1361. if user is None or not user.is_active:
  1362. raise HTTPException(
  1363. status_code=status.HTTP_401_UNAUTHORIZED,
  1364. detail="Could not validate credentials",
  1365. headers={"WWW-Authenticate": "Bearer"},
  1366. )
  1367. if not _is_token_fresh(iat, user):
  1368. raise HTTPException(
  1369. status_code=status.HTTP_401_UNAUTHORIZED,
  1370. detail="Could not validate credentials",
  1371. headers={"WWW-Authenticate": "Bearer"},
  1372. )
  1373. if not user.has_any_permission(*perm_strings):
  1374. raise HTTPException(
  1375. status_code=status.HTTP_403_FORBIDDEN,
  1376. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  1377. )
  1378. return user
  1379. raise HTTPException(
  1380. status_code=status.HTTP_401_UNAUTHORIZED,
  1381. detail="Authentication required",
  1382. headers={"WWW-Authenticate": "Bearer"},
  1383. )
  1384. return checker
  1385. def RequireAnyPermissionIfAuthEnabled(*permissions: str | Permission):
  1386. """Convenience dependency that requires AT LEAST ONE of the given permissions when auth is enabled."""
  1387. return Depends(require_any_permission_if_auth_enabled(*permissions))
  1388. def require_camera_stream_token_if_auth_enabled():
  1389. """Dependency that validates a camera stream token query param when auth is enabled.
  1390. Used for camera stream/snapshot endpoints that are loaded via <img> tags
  1391. which cannot send Authorization headers. The frontend obtains a token from
  1392. POST /printers/camera/stream-token and appends it as ?token=xxx.
  1393. """
  1394. async def checker(token: str | None = None) -> None:
  1395. async with async_session() as db:
  1396. if not await is_auth_enabled(db):
  1397. return # Auth disabled, allow access
  1398. if not token or not await verify_camera_stream_token(token):
  1399. raise HTTPException(
  1400. status_code=status.HTTP_401_UNAUTHORIZED,
  1401. detail="Valid camera stream token required. Obtain one from POST /api/v1/printers/camera/stream-token",
  1402. )
  1403. return checker
  1404. RequireCameraStreamTokenIfAuthEnabled = Depends(require_camera_stream_token_if_auth_enabled())
  1405. def require_ownership_permission(
  1406. all_permission: str | Permission,
  1407. own_permission: str | Permission,
  1408. ):
  1409. """Dependency factory for ownership-based permission checks.
  1410. - User with ``all_permission`` can modify any item
  1411. - User with ``own_permission`` can only modify items where created_by_id == user.id
  1412. - Ownerless items (created_by_id = null) require ``all_permission``
  1413. - API keys (via X-API-Key header or Bearer bb_xxx) must satisfy the
  1414. ``all_permission``'s API-key scope flag (e.g. ``can_queue`` for
  1415. ``QUEUE_UPDATE_ALL``) and then receive ``can_modify_all=True``.
  1416. OWN/ALL ownership pairs map to the same scope flag in
  1417. ``_APIKEY_SCOPE_BY_PERMISSION`` so checking ``all_permission`` is the
  1418. correct gate; API keys have no per-row ownership identity. Pre-
  1419. GHSA-r2qv-8222-hqg3 fix this returned ``(None, True)`` for any valid
  1420. key with no scope check — see ``core/auth.py`` allowlist commentary.
  1421. Returns:
  1422. A dependency function that returns (user, can_modify_all).
  1423. - can_modify_all=True: user can modify any item
  1424. - can_modify_all=False: user can only modify their own items
  1425. """
  1426. all_perm = all_permission.value if isinstance(all_permission, Permission) else all_permission
  1427. own_perm = own_permission.value if isinstance(own_permission, Permission) else own_permission
  1428. async def checker(
  1429. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1430. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1431. ) -> tuple[User | None, bool]:
  1432. """Returns (user, can_modify_all).
  1433. - can_modify_all=True: user can modify any item
  1434. - can_modify_all=False: user can only modify their own items
  1435. """
  1436. async with async_session() as db:
  1437. auth_enabled = await is_auth_enabled(db)
  1438. if not auth_enabled:
  1439. return None, True # Auth disabled, allow all
  1440. # GHSA-r2qv-8222-hqg3: previously API keys received (None, True)
  1441. # unconditionally on ownership-modify routes — a "queue-only" key
  1442. # could delete any user's archives, library files, queue items.
  1443. # OWN and ALL ownership perms both map to the same scope flag
  1444. # (e.g. both QUEUE_UPDATE_OWN and QUEUE_UPDATE_ALL → can_queue),
  1445. # so checking ``all_perm`` against the api_key's scope is the
  1446. # correct gate. API keys don't have per-row ownership identity, so
  1447. # on pass we keep can_modify_all=True (preserves prior intent,
  1448. # narrows access to keys with the right scope flag).
  1449. if x_api_key:
  1450. api_key = await _validate_api_key(db, x_api_key)
  1451. if api_key:
  1452. _check_apikey_permissions(api_key, [all_perm])
  1453. return None, True
  1454. # Check for Bearer token (could be JWT or API key)
  1455. if credentials is not None:
  1456. token = credentials.credentials
  1457. # Check if it's an API key (starts with bb_)
  1458. if token.startswith("bb_"):
  1459. api_key = await _validate_api_key(db, token)
  1460. if api_key:
  1461. _check_apikey_permissions(api_key, [all_perm])
  1462. return None, True
  1463. raise HTTPException(
  1464. status_code=status.HTTP_401_UNAUTHORIZED,
  1465. detail="Invalid API key",
  1466. headers={"WWW-Authenticate": "Bearer"},
  1467. )
  1468. # Otherwise treat as JWT
  1469. try:
  1470. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  1471. username: str = payload.get("sub")
  1472. if username is None:
  1473. raise HTTPException(
  1474. status_code=status.HTTP_401_UNAUTHORIZED,
  1475. detail="Could not validate credentials",
  1476. headers={"WWW-Authenticate": "Bearer"},
  1477. )
  1478. jti: str | None = payload.get("jti")
  1479. if not jti or await is_jti_revoked(jti):
  1480. raise HTTPException(
  1481. status_code=status.HTTP_401_UNAUTHORIZED,
  1482. detail="Could not validate credentials",
  1483. headers={"WWW-Authenticate": "Bearer"},
  1484. )
  1485. iat: int | float | None = payload.get("iat")
  1486. except JWTError:
  1487. raise HTTPException(
  1488. status_code=status.HTTP_401_UNAUTHORIZED,
  1489. detail="Could not validate credentials",
  1490. headers={"WWW-Authenticate": "Bearer"},
  1491. )
  1492. user = await get_user_by_username(db, username)
  1493. if user is None or not user.is_active:
  1494. raise HTTPException(
  1495. status_code=status.HTTP_401_UNAUTHORIZED,
  1496. detail="Could not validate credentials",
  1497. headers={"WWW-Authenticate": "Bearer"},
  1498. )
  1499. if not _is_token_fresh(iat, user):
  1500. raise HTTPException(
  1501. status_code=status.HTTP_401_UNAUTHORIZED,
  1502. detail="Could not validate credentials",
  1503. headers={"WWW-Authenticate": "Bearer"},
  1504. )
  1505. if user.has_permission(all_perm):
  1506. return user, True
  1507. if user.has_permission(own_perm):
  1508. return user, False
  1509. raise HTTPException(
  1510. status_code=status.HTTP_403_FORBIDDEN,
  1511. detail=f"Missing permission: {own_perm} or {all_perm}",
  1512. )
  1513. # No credentials provided
  1514. raise HTTPException(
  1515. status_code=status.HTTP_401_UNAUTHORIZED,
  1516. detail="Authentication required",
  1517. headers={"WWW-Authenticate": "Bearer"},
  1518. )
  1519. return checker