auth.py 130 KB

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