auth.py 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945
  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. async def verify_overlay_token(token: str) -> bool:
  649. """Verify a streaming-overlay token (#2613). Reusable — does not consume it.
  650. Like :func:`verify_camwall_token`, only the matching long-lived scope passes:
  651. the overlay status feed names the file being printed, so it must not be
  652. reachable by a ``camwall`` token (which is trusted to hide the part name) or
  653. a bare ``camera_stream`` token (handed out for video alone). The 60-minute
  654. ephemeral token belongs to a logged-in browser, which reaches the same data
  655. through the ordinary printers API and has no need of this endpoint.
  656. """
  657. async with async_session() as db:
  658. from backend.app.services.long_lived_tokens import verify_token as verify_long_lived
  659. record = await verify_long_lived(db, token, scope="overlay")
  660. return record is not None
  661. def verify_password(plain_password: str, hashed_password: str) -> bool:
  662. """Verify a password against a hash.
  663. Uses pbkdf2_sha256 which handles long passwords automatically.
  664. """
  665. return pwd_context.verify(plain_password, hashed_password)
  666. def get_password_hash(password: str) -> str:
  667. """Hash a password.
  668. Uses pbkdf2_sha256 which is secure and has no password length limit.
  669. """
  670. return pwd_context.hash(password)
  671. def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
  672. """Create a JWT access token with jti (revocation) and iat (freshness) claims."""
  673. to_encode = data.copy()
  674. now = datetime.now(timezone.utc)
  675. if expires_delta:
  676. expire = now + expires_delta
  677. else:
  678. expire = now + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  679. jti = secrets.token_hex(16)
  680. to_encode.update({"exp": expire, "jti": jti, "iat": now})
  681. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  682. return encoded_jwt
  683. def _is_token_fresh(iat: int | float | None, user: User) -> bool:
  684. """Return False if the token was issued before the user's last password change.
  685. Used to invalidate all sessions after a password reset/change (M-R7-B).
  686. All tokens without an iat claim are unconditionally rejected — every token
  687. issued by this server carries iat, so absence means the token is forged or
  688. from a pre-iat code path whose max TTL at the time (24 h) has long since
  689. expired. The post-#1706 admin-set ceiling does not relax this — an iat-less
  690. token still cannot have been issued by current code.
  691. """
  692. if iat is None:
  693. return False
  694. if not hasattr(user, "password_changed_at") or user.password_changed_at is None:
  695. return True # No password change recorded yet (I2 migration handles this)
  696. token_issued_at = datetime.fromtimestamp(iat, tz=timezone.utc)
  697. pca = user.password_changed_at
  698. if pca.tzinfo is None:
  699. pca = pca.replace(tzinfo=timezone.utc)
  700. # JWT iat is whole seconds; truncate pca so tokens issued in the same second pass.
  701. pca = pca.replace(microsecond=0)
  702. return token_issued_at >= pca
  703. async def revoke_jti(jti: str, expires_at: datetime, username: str | None = None) -> None:
  704. """Store a revoked JWT jti so it is rejected on future requests.
  705. Silently ignores duplicate inserts (e.g. double-logout with the same token).
  706. """
  707. from sqlalchemy.exc import IntegrityError
  708. async with async_session() as db:
  709. revoked = AuthEphemeralToken(
  710. token=jti,
  711. token_type="revoked_jti",
  712. username=username,
  713. expires_at=expires_at,
  714. )
  715. db.add(revoked)
  716. try:
  717. await db.commit()
  718. except IntegrityError:
  719. await db.rollback() # jti already revoked — desired state, ignore
  720. async def is_jti_revoked(jti: str, db: AsyncSession | None = None) -> bool:
  721. """Return True if the given jti has been revoked.
  722. Pass ``db`` to reuse the caller's session instead of opening a new one
  723. (issue #2572): the permission dependencies already hold a session, and a
  724. second checkout per request doubled pool pressure — a login burst then
  725. exhausted the pool. With ``db`` omitted a short session is opened as before,
  726. for callers that check the jti before they have a session open.
  727. """
  728. async def _query(session: AsyncSession) -> bool:
  729. result = await session.execute(
  730. select(AuthEphemeralToken).where(
  731. AuthEphemeralToken.token == jti,
  732. AuthEphemeralToken.token_type == "revoked_jti",
  733. )
  734. )
  735. return result.scalar_one_or_none() is not None
  736. if db is not None:
  737. return await _query(db)
  738. async with async_session() as own_db:
  739. return await _query(own_db)
  740. async def get_user_by_username(db: AsyncSession, username: str) -> User | None:
  741. """Get a user by username (case-insensitive) with groups loaded for permission checks."""
  742. result = await db.execute(
  743. select(User).where(func.lower(User.username) == func.lower(username)).options(selectinload(User.groups))
  744. )
  745. return result.scalar_one_or_none()
  746. async def get_user_by_email(db: AsyncSession, email: str) -> User | None:
  747. """Get a user by email (case-insensitive) with groups loaded for permission checks."""
  748. result = await db.execute(
  749. select(User).where(func.lower(User.email) == func.lower(email)).options(selectinload(User.groups))
  750. )
  751. return result.scalar_one_or_none()
  752. async def authenticate_user(db: AsyncSession, username: str, password: str) -> User | None:
  753. """Authenticate a user by username and password.
  754. Username lookup is case-insensitive. Password is case-sensitive.
  755. LDAP and OIDC users must authenticate via their respective providers.
  756. """
  757. user = await get_user_by_username(db, username)
  758. if not user:
  759. return None
  760. if getattr(user, "auth_source", "local") in ("ldap", "oidc"):
  761. return None # LDAP/OIDC users must authenticate via their provider
  762. if not user.password_hash or not verify_password(password, user.password_hash):
  763. return None
  764. if not user.is_active:
  765. return None
  766. return user
  767. async def authenticate_user_by_email(db: AsyncSession, email: str, password: str) -> User | None:
  768. """Authenticate a user by email and password.
  769. Email lookup is case-insensitive. Password is case-sensitive.
  770. LDAP and OIDC users must authenticate via their respective providers.
  771. """
  772. user = await get_user_by_email(db, email)
  773. if not user:
  774. return None
  775. if getattr(user, "auth_source", "local") in ("ldap", "oidc"):
  776. return None # LDAP/OIDC users must authenticate via their provider
  777. if not user.password_hash or not verify_password(password, user.password_hash):
  778. return None
  779. if not user.is_active:
  780. return None
  781. return user
  782. # Short-lived cache for the auth-enabled flag (issue #2572). The middleware
  783. # and every ownership/permission dependency probe this once (or more) per
  784. # request; on a large farm that DB round-trip is pure overhead because the
  785. # value changes only when an admin toggles auth.
  786. #
  787. # SECURITY: only a ``True`` (auth-enabled) result is EVER cached. A disabled /
  788. # unconfigured result is never cached, so a stale cache can only ever cause a
  789. # request to REQUIRE auth that a moment ago wasn't required — it can never skip
  790. # an auth check that is now required. Staleness fails CLOSED, never open (cf.
  791. # GHSA-6mf4-q26m-47pv). ``set_auth_enabled`` invalidates explicitly on any
  792. # toggle; the TTL is only a backstop for out-of-band changes (a direct DB edit,
  793. # or another worker process in a multi-worker deployment).
  794. _AUTH_ENABLED_CACHE_TTL_SECONDS = 30.0
  795. _auth_enabled_cached_value: bool = False
  796. _auth_enabled_cached_until: float = 0.0
  797. def invalidate_auth_enabled_cache() -> None:
  798. """Drop the cached auth-enabled flag so the next probe re-reads the DB.
  799. Call after any write that toggles the ``auth_enabled`` setting.
  800. """
  801. global _auth_enabled_cached_value, _auth_enabled_cached_until
  802. _auth_enabled_cached_value = False
  803. _auth_enabled_cached_until = 0.0
  804. async def is_auth_enabled(db: AsyncSession) -> bool:
  805. """Check if authentication is enabled.
  806. Fails CLOSED on database errors. A previous version of this function
  807. caught every exception and returned False — silently treating an
  808. unavailable database as "auth is disabled" and granting unauthenticated
  809. access to every endpoint that called it (GHSA-6mf4-q26m-47pv, CVSS 9.8).
  810. An attacker could trigger that fail-open by flooding /api/v1/auth/login
  811. to exhaust the process's file-descriptor budget, then hit a protected
  812. endpoint during the window where the next DB op raised.
  813. Legitimate "auth was never configured" still returns False — the
  814. settings row is simply absent, ``scalar_one_or_none`` returns None,
  815. no exception. Any OTHER failure (connection error, fd exhaustion,
  816. schema mismatch, …) propagates so the caller can deny the request
  817. (503 / 500). Fail-closed is the only safe default for an auth probe.
  818. Result is cached briefly to cut per-request DB load on large farms; only
  819. the enabled=True result is cached, so a stale read can only fail closed.
  820. See the module-level cache comment above.
  821. """
  822. global _auth_enabled_cached_value, _auth_enabled_cached_until
  823. if _auth_enabled_cached_value and time.monotonic() < _auth_enabled_cached_until:
  824. return True
  825. result = await db.execute(select(Settings).where(Settings.key == "auth_enabled"))
  826. setting = result.scalar_one_or_none()
  827. enabled = setting is not None and setting.value.lower() == "true"
  828. if enabled:
  829. _auth_enabled_cached_value = True
  830. _auth_enabled_cached_until = time.monotonic() + _AUTH_ENABLED_CACHE_TTL_SECONDS
  831. else:
  832. # Never cache "disabled" — keep failing closed on any future staleness.
  833. _auth_enabled_cached_value = False
  834. return enabled
  835. async def _user_from_api_key(db: AsyncSession, api_key: APIKey) -> User | None:
  836. """Resolve the owner of a validated API key, or None for legacy ownerless keys.
  837. Cloud routes (and any route that needs caller identity) read the returned
  838. User to look up per-user state like ``cloud_token``. Legacy keys created
  839. before #1182 have ``user_id IS NULL`` and stay anonymous — they keep working
  840. against non-cloud routes for backward compatibility, but cloud routes will
  841. surface a "recreate this key" error rather than 200 with empty results.
  842. """
  843. if api_key.user_id is None:
  844. return None
  845. result = await db.execute(select(User).where(User.id == api_key.user_id))
  846. user = result.scalar_one_or_none()
  847. if user is None or not user.is_active:
  848. # CASCADE on user delete should prevent a dangling user_id, but if
  849. # someone manually deactivates the owner the key shouldn't suddenly
  850. # gain an "anonymous" identity — drop the request to None so cloud
  851. # access fails closed.
  852. return None
  853. return user
  854. async def _validate_api_key(db: AsyncSession, api_key_value: str) -> APIKey | None:
  855. """Validate an API key and return the APIKey object if valid, None otherwise.
  856. L-1: Pre-filter by key_prefix (first 8 chars) before running pbkdf2 so only
  857. O(1) candidate rows are hashed instead of the full key table. The prefix is
  858. not secret (it is shown in the admin UI), so this does not reduce security.
  859. """
  860. try:
  861. # key_prefix is stored as "<first-8-chars>..." (e.g. "bb_Abc12...").
  862. # Matching on the first 8 chars of the submitted key reduces the scan to
  863. # at most one row in practice (2^40 collision space for 5 base64 chars).
  864. key_lookup = api_key_value[:8] if len(api_key_value) >= 8 else api_key_value
  865. result = await db.execute(
  866. select(APIKey).where(
  867. APIKey.enabled.is_(True),
  868. APIKey.key_prefix.like(
  869. key_lookup.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%", escape="\\"
  870. ),
  871. )
  872. )
  873. api_keys = result.scalars().all()
  874. for api_key in api_keys:
  875. if verify_password(api_key_value, api_key.key_hash):
  876. # Check expiration
  877. if api_key.expires_at:
  878. expires = api_key.expires_at
  879. if expires.tzinfo is None:
  880. expires = expires.replace(tzinfo=timezone.utc)
  881. if expires < datetime.now(timezone.utc):
  882. return None # Expired
  883. # Update last_used timestamp
  884. api_key.last_used = datetime.now(timezone.utc)
  885. await db.commit()
  886. return api_key
  887. except Exception as e: # SEC-AUTH-EXC: validation failure returns None; every caller treats None as "invalid key" → 401 (fail-closed)
  888. logger.warning("API key validation error: %s", e)
  889. return None
  890. async def get_current_user_optional(
  891. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  892. ) -> User | None:
  893. """Get the current authenticated user from JWT token, or None if not authenticated.
  894. Returns None only when NO credentials are supplied. If a token is supplied
  895. but invalid/revoked, raises 401 — a revoked token must not grant anonymous
  896. access (I6).
  897. """
  898. if credentials is None:
  899. return None
  900. _unauthorized = HTTPException(
  901. status_code=status.HTTP_401_UNAUTHORIZED,
  902. detail="Could not validate credentials",
  903. headers={"WWW-Authenticate": "Bearer"},
  904. )
  905. try:
  906. token = credentials.credentials
  907. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  908. username: str = payload.get("sub")
  909. if username is None:
  910. raise _unauthorized
  911. jti: str | None = payload.get("jti")
  912. iat: int | float | None = payload.get("iat")
  913. except JWTError:
  914. raise _unauthorized
  915. if not jti:
  916. raise _unauthorized # I6: revoked token → 401, not anonymous
  917. async with async_session() as db:
  918. if await is_jti_revoked(jti, db):
  919. raise _unauthorized # I6: revoked token → 401, not anonymous
  920. user = await get_user_by_username(db, username)
  921. if user is None or not user.is_active:
  922. raise _unauthorized
  923. if not _is_token_fresh(iat, user):
  924. raise _unauthorized
  925. return user
  926. async def get_current_user(
  927. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  928. ) -> User:
  929. """Get the current authenticated user from JWT token."""
  930. credentials_exception = HTTPException(
  931. status_code=status.HTTP_401_UNAUTHORIZED,
  932. detail="Could not validate credentials",
  933. headers={"WWW-Authenticate": "Bearer"},
  934. )
  935. if credentials is None:
  936. raise credentials_exception
  937. try:
  938. token = credentials.credentials
  939. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  940. username: str = payload.get("sub")
  941. if username is None:
  942. raise credentials_exception
  943. jti: str | None = payload.get("jti")
  944. iat: int | float | None = payload.get("iat")
  945. except JWTError:
  946. raise credentials_exception
  947. if not jti:
  948. raise credentials_exception
  949. async with async_session() as db:
  950. if await is_jti_revoked(jti, db):
  951. raise credentials_exception
  952. user = await get_user_by_username(db, username)
  953. if user is None:
  954. raise credentials_exception
  955. if not user.is_active:
  956. raise HTTPException(
  957. status_code=status.HTTP_403_FORBIDDEN,
  958. detail="User account is disabled",
  959. )
  960. if not _is_token_fresh(iat, user):
  961. raise credentials_exception
  962. return user
  963. async def get_current_active_user(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  964. """Get the current active user (alias for clarity)."""
  965. return current_user
  966. async def require_auth_if_enabled(
  967. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  968. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  969. ) -> User | None:
  970. """Require authentication if auth is enabled, otherwise return None.
  971. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  972. (via X-API-Key header or Authorization: Bearer bb_xxx). API keys return
  973. None for backward compatibility — routes that need the API-key owner (i.e.
  974. cloud routes for #1182) resolve it via their own router-level dependency
  975. that stashes ``request.state.api_key_owner``. Returning the owner here
  976. instead would silently grant API-keyed callers access to every route that
  977. fences via ``if current_user is None``, which is a wider surface than
  978. #1182 was designed to expose.
  979. """
  980. async with async_session() as db:
  981. auth_enabled = await is_auth_enabled(db)
  982. if not auth_enabled:
  983. return None
  984. # Check for API key first (X-API-Key header)
  985. if x_api_key:
  986. api_key = await _validate_api_key(db, x_api_key)
  987. if api_key:
  988. return None # API key valid, allow access
  989. # Check for Bearer token (could be JWT or API key)
  990. if credentials is not None:
  991. token = credentials.credentials
  992. # Check if it's an API key (starts with bb_)
  993. if token.startswith("bb_"):
  994. api_key = await _validate_api_key(db, token)
  995. if api_key:
  996. return None # API key valid, allow access
  997. raise HTTPException(
  998. status_code=status.HTTP_401_UNAUTHORIZED,
  999. detail="Invalid API key",
  1000. headers={"WWW-Authenticate": "Bearer"},
  1001. )
  1002. # Otherwise treat as JWT
  1003. try:
  1004. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  1005. username: str = payload.get("sub")
  1006. if username is None:
  1007. raise HTTPException(
  1008. status_code=status.HTTP_401_UNAUTHORIZED,
  1009. detail="Could not validate credentials",
  1010. headers={"WWW-Authenticate": "Bearer"},
  1011. )
  1012. jti: str | None = payload.get("jti")
  1013. if not jti or await is_jti_revoked(jti, db):
  1014. raise HTTPException(
  1015. status_code=status.HTTP_401_UNAUTHORIZED,
  1016. detail="Could not validate credentials",
  1017. headers={"WWW-Authenticate": "Bearer"},
  1018. )
  1019. iat: int | float | None = payload.get("iat")
  1020. except JWTError:
  1021. raise HTTPException(
  1022. status_code=status.HTTP_401_UNAUTHORIZED,
  1023. detail="Could not validate credentials",
  1024. headers={"WWW-Authenticate": "Bearer"},
  1025. )
  1026. user = await get_user_by_username(db, username)
  1027. if user is None or not user.is_active:
  1028. raise HTTPException(
  1029. status_code=status.HTTP_401_UNAUTHORIZED,
  1030. detail="Could not validate credentials",
  1031. headers={"WWW-Authenticate": "Bearer"},
  1032. )
  1033. if not _is_token_fresh(iat, user):
  1034. raise HTTPException(
  1035. status_code=status.HTTP_401_UNAUTHORIZED,
  1036. detail="Could not validate credentials",
  1037. headers={"WWW-Authenticate": "Bearer"},
  1038. )
  1039. return user
  1040. # No credentials provided
  1041. raise HTTPException(
  1042. status_code=status.HTTP_401_UNAUTHORIZED,
  1043. detail="Authentication required",
  1044. headers={"WWW-Authenticate": "Bearer"},
  1045. )
  1046. def require_role(required_role: str):
  1047. """Dependency factory for role-based access control."""
  1048. async def role_checker(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  1049. if current_user.role != required_role:
  1050. raise HTTPException(
  1051. status_code=status.HTTP_403_FORBIDDEN,
  1052. detail=f"Requires {required_role} role",
  1053. )
  1054. return current_user
  1055. return role_checker
  1056. def require_admin_if_auth_enabled():
  1057. """Dependency factory that requires admin role if auth is enabled.
  1058. GHSA-r2qv follow-up (audit pattern P3): explicitly fail-closed for API
  1059. keys. The previous implementation chained on ``require_auth_if_enabled``
  1060. which returns ``None`` for *both* "auth disabled" *and* "valid API
  1061. key" — the inner ``admin_checker`` then treated ``None`` as auth-
  1062. disabled and admitted the caller. If any route had ever adopted this
  1063. dep, any API key with no scope flags set would have satisfied an
  1064. admin requirement. The dep distinguishes the two cases by consulting
  1065. ``is_auth_enabled`` directly and rejecting API-keyed requests with
  1066. 403. "Admin" requires a user-identity role, which API keys do not
  1067. carry.
  1068. Admin semantics: uses ``User.is_admin`` (``role == "admin"`` OR
  1069. Administrators-group membership) so a default-install operator who
  1070. was made admin by being added to Administrators rather than by
  1071. flipping the legacy role column passes. Earlier this check looked
  1072. only at ``role`` and would have locked group-only admins out of the
  1073. user-management routes once those routes started requiring it.
  1074. """
  1075. async def admin_checker(
  1076. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1077. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1078. ) -> User | None:
  1079. async with async_session() as db:
  1080. if not await is_auth_enabled(db):
  1081. return None # Auth disabled — no role to check.
  1082. # Reject API-keyed requests up front: admin is a user-role
  1083. # concept, not a key-scope concept. The right path for
  1084. # admin-equivalent API-key access is a specific Permission
  1085. # (e.g. SETTINGS_UPDATE) gated by the allowlist, not the
  1086. # admin role.
  1087. if x_api_key or (credentials and credentials.credentials.startswith("bb_")):
  1088. raise HTTPException(
  1089. status_code=status.HTTP_403_FORBIDDEN,
  1090. detail="Admin operations require a user role; API keys cannot be admins",
  1091. )
  1092. # Standard JWT path: validate and require admin role.
  1093. if credentials is None:
  1094. raise HTTPException(
  1095. status_code=status.HTTP_401_UNAUTHORIZED,
  1096. detail="Authentication required",
  1097. headers={"WWW-Authenticate": "Bearer"},
  1098. )
  1099. try:
  1100. payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM])
  1101. username: str = payload.get("sub")
  1102. if username is None:
  1103. raise HTTPException(
  1104. status_code=status.HTTP_401_UNAUTHORIZED,
  1105. detail="Could not validate credentials",
  1106. headers={"WWW-Authenticate": "Bearer"},
  1107. )
  1108. jti: str | None = payload.get("jti")
  1109. if not jti or await is_jti_revoked(jti, db):
  1110. raise HTTPException(
  1111. status_code=status.HTTP_401_UNAUTHORIZED,
  1112. detail="Could not validate credentials",
  1113. headers={"WWW-Authenticate": "Bearer"},
  1114. )
  1115. iat: int | float | None = payload.get("iat")
  1116. except JWTError:
  1117. raise HTTPException(
  1118. status_code=status.HTTP_401_UNAUTHORIZED,
  1119. detail="Could not validate credentials",
  1120. headers={"WWW-Authenticate": "Bearer"},
  1121. )
  1122. user = await get_user_by_username(db, username)
  1123. if user is None or not user.is_active:
  1124. raise HTTPException(
  1125. status_code=status.HTTP_401_UNAUTHORIZED,
  1126. detail="Could not validate credentials",
  1127. headers={"WWW-Authenticate": "Bearer"},
  1128. )
  1129. if not _is_token_fresh(iat, user):
  1130. raise HTTPException(
  1131. status_code=status.HTTP_401_UNAUTHORIZED,
  1132. detail="Could not validate credentials",
  1133. headers={"WWW-Authenticate": "Bearer"},
  1134. )
  1135. if not user.is_admin:
  1136. raise HTTPException(
  1137. status_code=status.HTTP_403_FORBIDDEN,
  1138. detail="Requires admin role",
  1139. )
  1140. return user
  1141. return admin_checker
  1142. def generate_api_key() -> tuple[str, str, str]:
  1143. """Generate a new API key.
  1144. Returns:
  1145. tuple: (full_key, key_hash, key_prefix)
  1146. - full_key: The complete API key (only shown once on creation)
  1147. - key_hash: Hashed version for storage and verification
  1148. - key_prefix: First 8 characters for display purposes
  1149. """
  1150. # Generate a secure random API key (32 bytes = 64 hex characters)
  1151. full_key = f"bb_{secrets.token_urlsafe(32)}"
  1152. key_hash = get_password_hash(full_key)
  1153. key_prefix = full_key[:8] + "..." if len(full_key) > 8 else full_key
  1154. return full_key, key_hash, key_prefix
  1155. async def get_api_key(
  1156. authorization: Annotated[str | None, Header(alias="Authorization")] = None,
  1157. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1158. db: AsyncSession = Depends(get_db),
  1159. ) -> APIKey:
  1160. """Get and validate API key from request headers.
  1161. Checks both 'Authorization: Bearer <key>' and 'X-API-Key: <key>' headers.
  1162. """
  1163. api_key_value = None
  1164. if x_api_key:
  1165. api_key_value = x_api_key
  1166. elif authorization and authorization.startswith("Bearer "):
  1167. api_key_value = authorization.replace("Bearer ", "")
  1168. if not api_key_value:
  1169. raise HTTPException(
  1170. status_code=status.HTTP_401_UNAUTHORIZED,
  1171. detail="API key required. Provide 'X-API-Key' header or 'Authorization: Bearer <key>'",
  1172. )
  1173. # Pre-filter by key_prefix to avoid O(n) pbkdf2 hashes across all enabled keys.
  1174. key_lookup = api_key_value[:8] if len(api_key_value) >= 8 else api_key_value
  1175. result = await db.execute(
  1176. select(APIKey).where(
  1177. APIKey.enabled.is_(True),
  1178. APIKey.key_prefix.like(
  1179. key_lookup.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%",
  1180. escape="\\",
  1181. ),
  1182. )
  1183. )
  1184. api_keys = result.scalars().all()
  1185. for api_key in api_keys:
  1186. # Check if key matches (verify against hash)
  1187. if verify_password(api_key_value, api_key.key_hash):
  1188. # Check expiration
  1189. if api_key.expires_at:
  1190. expires = api_key.expires_at
  1191. if expires.tzinfo is None:
  1192. expires = expires.replace(tzinfo=timezone.utc)
  1193. if expires < datetime.now(timezone.utc):
  1194. raise HTTPException(
  1195. status_code=status.HTTP_401_UNAUTHORIZED,
  1196. detail="API key has expired",
  1197. )
  1198. # Update last_used timestamp
  1199. api_key.last_used = datetime.now(timezone.utc)
  1200. await db.commit()
  1201. return api_key
  1202. raise HTTPException(
  1203. status_code=status.HTTP_401_UNAUTHORIZED,
  1204. detail="Invalid API key",
  1205. )
  1206. async def caller_is_api_key(
  1207. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1208. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1209. ) -> bool:
  1210. """Return True when the request is authenticated via API key (X-API-Key or Bearer bb_xxx)."""
  1211. if x_api_key:
  1212. return True
  1213. return credentials is not None and credentials.credentials.startswith("bb_")
  1214. def check_permission(api_key: APIKey, permission: str) -> None:
  1215. """Check if API key has the required permission.
  1216. Args:
  1217. api_key: The API key object
  1218. permission: One of 'queue', 'control_printer', 'read_status'
  1219. Raises:
  1220. HTTPException: If permission is not granted
  1221. """
  1222. permission_map = {
  1223. "queue": "can_queue",
  1224. "control_printer": "can_control_printer",
  1225. "read_status": "can_read_status",
  1226. }
  1227. if permission not in permission_map:
  1228. raise HTTPException(
  1229. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  1230. detail=f"Unknown permission: {permission}",
  1231. )
  1232. attr_name = permission_map[permission]
  1233. if not getattr(api_key, attr_name, False):
  1234. raise HTTPException(
  1235. status_code=status.HTTP_403_FORBIDDEN,
  1236. detail=f"API key does not have '{permission}' permission",
  1237. )
  1238. def check_printer_access(api_key: APIKey, printer_id: int) -> None:
  1239. """Check if API key has access to the specified printer.
  1240. Args:
  1241. api_key: The API key object
  1242. printer_id: The printer ID to check access for
  1243. Raises:
  1244. HTTPException: If access is denied
  1245. """
  1246. # None = global key, access to all printers
  1247. if api_key.printer_ids is None:
  1248. return
  1249. # Empty list or printer not in allowed list = no access
  1250. if printer_id not in api_key.printer_ids:
  1251. raise HTTPException(
  1252. status_code=status.HTTP_403_FORBIDDEN,
  1253. detail=f"API key does not have access to printer {printer_id}",
  1254. )
  1255. # Convenience dependencies - these are functions that return Depends objects
  1256. def RequireAdmin():
  1257. """Dependency that requires admin role."""
  1258. return Depends(require_role("admin"))
  1259. def RequireAdminIfAuthEnabled():
  1260. """Dependency that requires admin role if auth is enabled."""
  1261. return Depends(require_admin_if_auth_enabled())
  1262. def require_permission(*permissions: str | Permission):
  1263. """Dependency factory that requires user to have ALL specified permissions.
  1264. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  1265. (via X-API-Key header or Authorization: Bearer bb_xxx).
  1266. Args:
  1267. *permissions: Permission strings or Permission enum values to require
  1268. Returns:
  1269. A dependency function that validates permissions
  1270. """
  1271. # Convert Permission enums to strings
  1272. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  1273. async def permission_checker(
  1274. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1275. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1276. ) -> User | None:
  1277. async with async_session() as db:
  1278. # Check for API key first (X-API-Key header)
  1279. if x_api_key:
  1280. api_key = await _validate_api_key(db, x_api_key)
  1281. if api_key:
  1282. _check_apikey_permissions(api_key, perm_strings)
  1283. return None # API key valid, allow access
  1284. credentials_exception = HTTPException(
  1285. status_code=status.HTTP_401_UNAUTHORIZED,
  1286. detail="Could not validate credentials",
  1287. headers={"WWW-Authenticate": "Bearer"},
  1288. )
  1289. if credentials is None:
  1290. raise credentials_exception
  1291. token = credentials.credentials
  1292. # Check if it's an API key (starts with bb_)
  1293. if token.startswith("bb_"):
  1294. api_key = await _validate_api_key(db, token)
  1295. if api_key:
  1296. _check_apikey_permissions(api_key, perm_strings)
  1297. return None # API key valid, allow access
  1298. raise HTTPException(
  1299. status_code=status.HTTP_401_UNAUTHORIZED,
  1300. detail="Invalid API key",
  1301. headers={"WWW-Authenticate": "Bearer"},
  1302. )
  1303. # Otherwise treat as JWT
  1304. try:
  1305. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  1306. username: str = payload.get("sub")
  1307. if username is None:
  1308. raise credentials_exception
  1309. jti: str | None = payload.get("jti")
  1310. if not jti or await is_jti_revoked(jti, db):
  1311. raise credentials_exception
  1312. iat: int | float | None = payload.get("iat")
  1313. except JWTError:
  1314. raise credentials_exception
  1315. user = await get_user_by_username(db, username)
  1316. if user is None or not user.is_active:
  1317. raise credentials_exception
  1318. if not _is_token_fresh(iat, user):
  1319. raise credentials_exception
  1320. if not user.has_all_permissions(*perm_strings):
  1321. raise HTTPException(
  1322. status_code=status.HTTP_403_FORBIDDEN,
  1323. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  1324. )
  1325. return user
  1326. return permission_checker
  1327. def require_permission_if_auth_enabled(*permissions: str | Permission):
  1328. """Dependency factory that checks permissions only if auth is enabled.
  1329. This provides backward compatibility - when auth is disabled, all access is allowed.
  1330. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  1331. (via X-API-Key header or Authorization: Bearer bb_xxx).
  1332. Args:
  1333. *permissions: Permission strings or Permission enum values to require
  1334. Returns:
  1335. A dependency function that validates permissions if auth is enabled
  1336. """
  1337. # Convert Permission enums to strings
  1338. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  1339. async def permission_checker(
  1340. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1341. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1342. ) -> User | None:
  1343. async with async_session() as db:
  1344. auth_enabled = await is_auth_enabled(db)
  1345. if not auth_enabled:
  1346. return None # Auth disabled, allow access
  1347. # Check for API key first (X-API-Key header). API-keyed requests
  1348. # bypass the JWT permission check entirely — their scopes live on
  1349. # the APIKey row (can_queue / can_control_printer / can_read_status
  1350. # / can_access_cloud / printer_ids), and the dep returns None so
  1351. # routes don't gain a synthetic User identity that would grant
  1352. # access to fenced surfaces like long-lived-token management.
  1353. # Cloud routes (#1182) resolve the API-key owner separately via
  1354. # their own router-level dependency; see ``cloud.py``.
  1355. if x_api_key:
  1356. api_key = await _validate_api_key(db, x_api_key)
  1357. if api_key:
  1358. _check_apikey_permissions(api_key, perm_strings)
  1359. return None # API key valid, allow access
  1360. # Check for Bearer token (could be JWT or API key)
  1361. if credentials is not None:
  1362. token = credentials.credentials
  1363. # Check if it's an API key (starts with bb_)
  1364. if token.startswith("bb_"):
  1365. api_key = await _validate_api_key(db, token)
  1366. if api_key:
  1367. _check_apikey_permissions(api_key, perm_strings)
  1368. return None # API key valid, allow access
  1369. raise HTTPException(
  1370. status_code=status.HTTP_401_UNAUTHORIZED,
  1371. detail="Invalid API key",
  1372. headers={"WWW-Authenticate": "Bearer"},
  1373. )
  1374. # Otherwise treat as JWT
  1375. try:
  1376. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  1377. username: str = payload.get("sub")
  1378. if username is None:
  1379. raise HTTPException(
  1380. status_code=status.HTTP_401_UNAUTHORIZED,
  1381. detail="Could not validate credentials",
  1382. headers={"WWW-Authenticate": "Bearer"},
  1383. )
  1384. jti: str | None = payload.get("jti")
  1385. if not jti or await is_jti_revoked(jti, db):
  1386. raise HTTPException(
  1387. status_code=status.HTTP_401_UNAUTHORIZED,
  1388. detail="Could not validate credentials",
  1389. headers={"WWW-Authenticate": "Bearer"},
  1390. )
  1391. iat: int | float | None = payload.get("iat")
  1392. except JWTError:
  1393. raise HTTPException(
  1394. status_code=status.HTTP_401_UNAUTHORIZED,
  1395. detail="Could not validate credentials",
  1396. headers={"WWW-Authenticate": "Bearer"},
  1397. )
  1398. user = await get_user_by_username(db, username)
  1399. if user is None or not user.is_active:
  1400. raise HTTPException(
  1401. status_code=status.HTTP_401_UNAUTHORIZED,
  1402. detail="Could not validate credentials",
  1403. headers={"WWW-Authenticate": "Bearer"},
  1404. )
  1405. if not _is_token_fresh(iat, user):
  1406. raise HTTPException(
  1407. status_code=status.HTTP_401_UNAUTHORIZED,
  1408. detail="Could not validate credentials",
  1409. headers={"WWW-Authenticate": "Bearer"},
  1410. )
  1411. if not user.has_all_permissions(*perm_strings):
  1412. raise HTTPException(
  1413. status_code=status.HTTP_403_FORBIDDEN,
  1414. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  1415. )
  1416. return user
  1417. # No credentials provided
  1418. raise HTTPException(
  1419. status_code=status.HTTP_401_UNAUTHORIZED,
  1420. detail="Authentication required",
  1421. headers={"WWW-Authenticate": "Bearer"},
  1422. )
  1423. return permission_checker
  1424. def RequirePermission(*permissions: str | Permission):
  1425. """Convenience dependency that requires ALL specified permissions."""
  1426. return Depends(require_permission(*permissions))
  1427. def RequirePermissionIfAuthEnabled(*permissions: str | Permission):
  1428. """Convenience dependency that requires permissions if auth is enabled."""
  1429. return Depends(require_permission_if_auth_enabled(*permissions))
  1430. def require_any_permission_if_auth_enabled(*permissions: str | Permission):
  1431. """Dependency factory that requires AT LEAST ONE of the given permissions when auth is enabled."""
  1432. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  1433. async def checker(
  1434. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1435. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1436. ) -> User | None:
  1437. async with async_session() as db:
  1438. auth_enabled = await is_auth_enabled(db)
  1439. if not auth_enabled:
  1440. return None
  1441. if x_api_key:
  1442. api_key = await _validate_api_key(db, x_api_key)
  1443. if api_key:
  1444. # GHSA-r2qv-8222-hqg3: previously returned None unconditionally,
  1445. # letting any valid API key satisfy admin "any-of" route
  1446. # dependencies. require_any → at-least-one must pass the scope check.
  1447. _check_apikey_permissions(api_key, perm_strings, require_any=True)
  1448. return None
  1449. if credentials is not None:
  1450. token = credentials.credentials
  1451. if token.startswith("bb_"):
  1452. api_key = await _validate_api_key(db, token)
  1453. if api_key:
  1454. _check_apikey_permissions(api_key, perm_strings, require_any=True)
  1455. return None
  1456. raise HTTPException(
  1457. status_code=status.HTTP_401_UNAUTHORIZED,
  1458. detail="Invalid API key",
  1459. headers={"WWW-Authenticate": "Bearer"},
  1460. )
  1461. try:
  1462. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  1463. username: str = payload.get("sub")
  1464. if username is None:
  1465. raise HTTPException(
  1466. status_code=status.HTTP_401_UNAUTHORIZED,
  1467. detail="Could not validate credentials",
  1468. headers={"WWW-Authenticate": "Bearer"},
  1469. )
  1470. jti: str | None = payload.get("jti")
  1471. if not jti or await is_jti_revoked(jti, db):
  1472. raise HTTPException(
  1473. status_code=status.HTTP_401_UNAUTHORIZED,
  1474. detail="Could not validate credentials",
  1475. headers={"WWW-Authenticate": "Bearer"},
  1476. )
  1477. iat: int | float | None = payload.get("iat")
  1478. except JWTError:
  1479. raise HTTPException(
  1480. status_code=status.HTTP_401_UNAUTHORIZED,
  1481. detail="Could not validate credentials",
  1482. headers={"WWW-Authenticate": "Bearer"},
  1483. )
  1484. user = await get_user_by_username(db, username)
  1485. if user is None or not user.is_active:
  1486. raise HTTPException(
  1487. status_code=status.HTTP_401_UNAUTHORIZED,
  1488. detail="Could not validate credentials",
  1489. headers={"WWW-Authenticate": "Bearer"},
  1490. )
  1491. if not _is_token_fresh(iat, user):
  1492. raise HTTPException(
  1493. status_code=status.HTTP_401_UNAUTHORIZED,
  1494. detail="Could not validate credentials",
  1495. headers={"WWW-Authenticate": "Bearer"},
  1496. )
  1497. if not user.has_any_permission(*perm_strings):
  1498. raise HTTPException(
  1499. status_code=status.HTTP_403_FORBIDDEN,
  1500. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  1501. )
  1502. return user
  1503. raise HTTPException(
  1504. status_code=status.HTTP_401_UNAUTHORIZED,
  1505. detail="Authentication required",
  1506. headers={"WWW-Authenticate": "Bearer"},
  1507. )
  1508. return checker
  1509. def RequireAnyPermissionIfAuthEnabled(*permissions: str | Permission):
  1510. """Convenience dependency that requires AT LEAST ONE of the given permissions when auth is enabled."""
  1511. return Depends(require_any_permission_if_auth_enabled(*permissions))
  1512. def require_camera_stream_token_if_auth_enabled():
  1513. """Dependency that validates a camera stream token query param when auth is enabled.
  1514. Used for camera stream/snapshot endpoints that are loaded via <img> tags
  1515. which cannot send Authorization headers. The frontend obtains a token from
  1516. POST /printers/camera/stream-token and appends it as ?token=xxx.
  1517. """
  1518. async def checker(token: str | None = None) -> None:
  1519. async with async_session() as db:
  1520. if not await is_auth_enabled(db):
  1521. return # Auth disabled, allow access
  1522. if not token or not await verify_camera_stream_token(token):
  1523. raise HTTPException(
  1524. status_code=status.HTTP_401_UNAUTHORIZED,
  1525. detail="Valid camera stream token required. Obtain one from POST /api/v1/printers/camera/stream-token",
  1526. )
  1527. return checker
  1528. RequireCameraStreamTokenIfAuthEnabled = Depends(require_camera_stream_token_if_auth_enabled())
  1529. def require_camwall_token_if_auth_enabled():
  1530. """Dependency that validates a Cam Wall token query param when auth is enabled.
  1531. Used by the read-only Cam Wall feed (#2531), which a kiosk browser loads
  1532. with the token in the URL because it has no login session to carry a JWT.
  1533. """
  1534. async def checker(token: str | None = None) -> None:
  1535. async with async_session() as db:
  1536. if not await is_auth_enabled(db):
  1537. return # Auth disabled, allow access
  1538. if not token or not await verify_camwall_token(token):
  1539. raise HTTPException(
  1540. status_code=status.HTTP_401_UNAUTHORIZED,
  1541. detail="Valid Cam Wall token required. Create one under Settings > API Keys with the 'Cam Wall' scope.",
  1542. )
  1543. return checker
  1544. RequireCamWallTokenIfAuthEnabled = Depends(require_camwall_token_if_auth_enabled())
  1545. def require_overlay_token_if_auth_enabled():
  1546. """Dependency that validates a streaming-overlay token query param when auth
  1547. is enabled.
  1548. Used by the read-only overlay status feed (#2613), which OBS (or any
  1549. embed with no login session) loads with the token in the URL because it
  1550. has no JWT to carry.
  1551. """
  1552. async def checker(token: str | None = None) -> None:
  1553. async with async_session() as db:
  1554. if not await is_auth_enabled(db):
  1555. return # Auth disabled, allow access
  1556. if not token or not await verify_overlay_token(token):
  1557. raise HTTPException(
  1558. status_code=status.HTTP_401_UNAUTHORIZED,
  1559. detail="Valid overlay token required. Create one under Settings > API Keys with the 'Streaming Overlay' scope.",
  1560. )
  1561. return checker
  1562. RequireOverlayTokenIfAuthEnabled = Depends(require_overlay_token_if_auth_enabled())
  1563. def require_ownership_permission(
  1564. all_permission: str | Permission,
  1565. own_permission: str | Permission,
  1566. ):
  1567. """Dependency factory for ownership-based permission checks.
  1568. - User with ``all_permission`` can modify any item
  1569. - User with ``own_permission`` can only modify items where created_by_id == user.id
  1570. - Ownerless items (created_by_id = null) require ``all_permission``
  1571. - API keys (via X-API-Key header or Bearer bb_xxx) must satisfy the
  1572. ``all_permission``'s API-key scope flag (e.g. ``can_queue`` for
  1573. ``QUEUE_UPDATE_ALL``) and then receive ``can_modify_all=True``.
  1574. OWN/ALL ownership pairs map to the same scope flag in
  1575. ``_APIKEY_SCOPE_BY_PERMISSION`` so checking ``all_permission`` is the
  1576. correct gate; API keys have no per-row ownership identity. Pre-
  1577. GHSA-r2qv-8222-hqg3 fix this returned ``(None, True)`` for any valid
  1578. key with no scope check — see ``core/auth.py`` allowlist commentary.
  1579. Returns:
  1580. A dependency function that returns (user, can_modify_all).
  1581. - can_modify_all=True: user can modify any item
  1582. - can_modify_all=False: user can only modify their own items
  1583. """
  1584. all_perm = all_permission.value if isinstance(all_permission, Permission) else all_permission
  1585. own_perm = own_permission.value if isinstance(own_permission, Permission) else own_permission
  1586. async def checker(
  1587. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1588. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1589. ) -> tuple[User | None, bool]:
  1590. """Returns (user, can_modify_all).
  1591. - can_modify_all=True: user can modify any item
  1592. - can_modify_all=False: user can only modify their own items
  1593. """
  1594. async with async_session() as db:
  1595. auth_enabled = await is_auth_enabled(db)
  1596. if not auth_enabled:
  1597. return None, True # Auth disabled, allow all
  1598. # GHSA-r2qv-8222-hqg3: previously API keys received (None, True)
  1599. # unconditionally on ownership-modify routes — a "queue-only" key
  1600. # could delete any user's archives, library files, queue items.
  1601. # OWN and ALL ownership perms both map to the same scope flag
  1602. # (e.g. both QUEUE_UPDATE_OWN and QUEUE_UPDATE_ALL → can_queue),
  1603. # so checking ``all_perm`` against the api_key's scope is the
  1604. # correct gate. API keys don't have per-row ownership identity, so
  1605. # on pass we keep can_modify_all=True (preserves prior intent,
  1606. # narrows access to keys with the right scope flag).
  1607. if x_api_key:
  1608. api_key = await _validate_api_key(db, x_api_key)
  1609. if api_key:
  1610. _check_apikey_permissions(api_key, [all_perm])
  1611. return None, True
  1612. # Check for Bearer token (could be JWT or API key)
  1613. if credentials is not None:
  1614. token = credentials.credentials
  1615. # Check if it's an API key (starts with bb_)
  1616. if token.startswith("bb_"):
  1617. api_key = await _validate_api_key(db, token)
  1618. if api_key:
  1619. _check_apikey_permissions(api_key, [all_perm])
  1620. return None, True
  1621. raise HTTPException(
  1622. status_code=status.HTTP_401_UNAUTHORIZED,
  1623. detail="Invalid API key",
  1624. headers={"WWW-Authenticate": "Bearer"},
  1625. )
  1626. # Otherwise treat as JWT
  1627. try:
  1628. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  1629. username: str = payload.get("sub")
  1630. if username is None:
  1631. raise HTTPException(
  1632. status_code=status.HTTP_401_UNAUTHORIZED,
  1633. detail="Could not validate credentials",
  1634. headers={"WWW-Authenticate": "Bearer"},
  1635. )
  1636. jti: str | None = payload.get("jti")
  1637. if not jti or await is_jti_revoked(jti, db):
  1638. raise HTTPException(
  1639. status_code=status.HTTP_401_UNAUTHORIZED,
  1640. detail="Could not validate credentials",
  1641. headers={"WWW-Authenticate": "Bearer"},
  1642. )
  1643. iat: int | float | None = payload.get("iat")
  1644. except JWTError:
  1645. raise HTTPException(
  1646. status_code=status.HTTP_401_UNAUTHORIZED,
  1647. detail="Could not validate credentials",
  1648. headers={"WWW-Authenticate": "Bearer"},
  1649. )
  1650. user = await get_user_by_username(db, username)
  1651. if user is None or not user.is_active:
  1652. raise HTTPException(
  1653. status_code=status.HTTP_401_UNAUTHORIZED,
  1654. detail="Could not validate credentials",
  1655. headers={"WWW-Authenticate": "Bearer"},
  1656. )
  1657. if not _is_token_fresh(iat, user):
  1658. raise HTTPException(
  1659. status_code=status.HTTP_401_UNAUTHORIZED,
  1660. detail="Could not validate credentials",
  1661. headers={"WWW-Authenticate": "Bearer"},
  1662. )
  1663. if user.has_permission(all_perm):
  1664. return user, True
  1665. if user.has_permission(own_perm):
  1666. return user, False
  1667. raise HTTPException(
  1668. status_code=status.HTTP_403_FORBIDDEN,
  1669. detail=f"Missing permission: {own_perm} or {all_perm}",
  1670. )
  1671. # No credentials provided
  1672. raise HTTPException(
  1673. status_code=status.HTTP_401_UNAUTHORIZED,
  1674. detail="Authentication required",
  1675. headers={"WWW-Authenticate": "Bearer"},
  1676. )
  1677. return checker