auth.py 75 KB

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