auth.py 74 KB

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