auth.py 109 KB

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