auth.py 93 KB

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