auth.py 82 KB

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