auth.py 124 KB

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