auth.py 127 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886
  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. # --- Camera stream tokens ---
  757. # Reusable tokens for camera stream/snapshot endpoints loaded via <img>/<video>
  758. # tags (these cannot send Authorization headers). Unlike slicer tokens they are
  759. # NOT single-use — streams reconnect on errors. Stored in AuthEphemeralToken
  760. # (token_type="camera_stream") for multi-worker compatibility (M-3).
  761. #
  762. # Anonymous by design: the row records no username, so a route guarded by this
  763. # token knows only "some camera viewer", never which one. That is fine for a
  764. # live stream, which is per-printer and not per-user, and is precisely why
  765. # non-camera media moved to the identified media token in #3025.
  766. CAMERA_STREAM_TOKEN_EXPIRE_MINUTES = 60
  767. async def create_camera_stream_token(username: str | None = None, api_key_id: int | None = None) -> str:
  768. """Create a reusable token for camera stream/snapshot access.
  769. Records who minted it -- ``username`` for a user, ``api_key_id`` for an
  770. API key -- so the streams it opens stay within that caller's printer scope
  771. (#1727). Neither is set when auth is off.
  772. """
  773. now = datetime.now(timezone.utc)
  774. expires_at = now + timedelta(minutes=CAMERA_STREAM_TOKEN_EXPIRE_MINUTES)
  775. token = secrets.token_urlsafe(24)
  776. async with async_session() as db:
  777. # Prune expired tokens opportunistically
  778. await db.execute(
  779. delete(AuthEphemeralToken).where(
  780. AuthEphemeralToken.token_type == "camera_stream",
  781. AuthEphemeralToken.expires_at < now,
  782. )
  783. )
  784. db.add(
  785. AuthEphemeralToken(
  786. token=token,
  787. token_type="camera_stream",
  788. username=username or "",
  789. api_key_id=api_key_id,
  790. expires_at=expires_at,
  791. )
  792. )
  793. await db.commit()
  794. return token
  795. WEBSOCKET_TOKEN_EXPIRE_MINUTES = 60
  796. async def create_websocket_token(username: str | None, api_key_id: int | None = None) -> str:
  797. """Create a short-lived token for ``/api/v1/ws`` connections.
  798. Mirrors the camera-stream-token pattern: opaque random string stored
  799. in ``auth_ephemeral_tokens`` with type ``"websocket"`` so the WS
  800. endpoint can verify it *before* calling ``websocket.accept()``.
  801. Records the issuing principal in the ``username`` field — for JWT
  802. callers this is the actual username, for API-keyed callers this is
  803. the empty string (handled in the route layer; we accept None at this
  804. interface so the auth-disabled path doesn't have to fabricate one).
  805. The 60-minute expiry matches camera tokens: long enough to survive
  806. page reloads / brief disconnects, short enough that a leaked token
  807. is not a credential.
  808. """
  809. now = datetime.now(timezone.utc)
  810. expires_at = now + timedelta(minutes=WEBSOCKET_TOKEN_EXPIRE_MINUTES)
  811. token = secrets.token_urlsafe(24)
  812. async with async_session() as db:
  813. # Prune expired tokens opportunistically (same shape as camera).
  814. await db.execute(
  815. delete(AuthEphemeralToken).where(
  816. AuthEphemeralToken.token_type == "websocket",
  817. AuthEphemeralToken.expires_at < now,
  818. )
  819. )
  820. db.add(
  821. AuthEphemeralToken(
  822. token=token,
  823. token_type="websocket",
  824. username=username or "",
  825. api_key_id=api_key_id,
  826. expires_at=expires_at,
  827. )
  828. )
  829. await db.commit()
  830. return token
  831. async def verify_websocket_token_principal(token: str) -> tuple[str, int | None] | None:
  832. """Verify a WebSocket connect token and return who minted it.
  833. ``(username, api_key_id)``: the username is ``""`` for API-key callers
  834. and with auth off; ``api_key_id`` is set only for API keys. ``None`` when
  835. the token is missing / expired / unknown. The token is NOT consumed -- a
  836. single page reload should not need a new round trip to mint a
  837. replacement.
  838. """
  839. now = datetime.now(timezone.utc)
  840. async with async_session() as db:
  841. result = await db.execute(
  842. select(AuthEphemeralToken).where(
  843. AuthEphemeralToken.token == token,
  844. AuthEphemeralToken.token_type == "websocket",
  845. AuthEphemeralToken.expires_at > now,
  846. )
  847. )
  848. row = result.scalar_one_or_none()
  849. if row is None:
  850. return None
  851. return row.username or "", row.api_key_id
  852. async def verify_websocket_token(token: str) -> str | None:
  853. """Verify a WebSocket connect token.
  854. Returns the recorded ``username`` (possibly ``""`` for API-key
  855. callers, never ``None`` on success) when the token is valid, or
  856. ``None`` when it is missing / expired / unknown.
  857. """
  858. principal = await verify_websocket_token_principal(token)
  859. return None if principal is None else principal[0]
  860. _NO_PRINTERS = PrinterScope(frozenset())
  861. async def usable_api_key_prefix(db: AsyncSession, api_key_id: int) -> str | None:
  862. """The prefix of an API key that may still be used, else None.
  863. None for a key that is gone, disabled or expired. The prefix tells a key
  864. from a later one given its id (SQLite reuses ids), so an open WebSocket can
  865. tell whether its key is still the one it connected with.
  866. """
  867. api_key = (await db.execute(select(APIKey).where(APIKey.id == api_key_id))).scalar_one_or_none()
  868. if api_key is None or not api_key.enabled:
  869. return None
  870. if api_key.expires_at is not None:
  871. expires = api_key.expires_at
  872. if expires.tzinfo is None:
  873. expires = expires.replace(tzinfo=timezone.utc)
  874. if expires < datetime.now(timezone.utc):
  875. return None
  876. return api_key.key_prefix
  877. async def principal_printer_scope(db: AsyncSession, username: str | None, api_key_id: int | None) -> PrinterScope:
  878. """Printer scope of the principal a token was minted for (#1727).
  879. Fail-closed: a key that is gone, disabled, expired or whose owner was
  880. deactivated, a user who is gone or deactivated, and a token naming no
  881. principal all get no printers. Callers skip this when auth is off.
  882. """
  883. if api_key_id is not None:
  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 _NO_PRINTERS
  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 _NO_PRINTERS
  893. try:
  894. return await api_key_printer_scope(db, api_key)
  895. except HTTPException:
  896. return _NO_PRINTERS
  897. if username:
  898. user = await get_user_by_username(db, username)
  899. if user is None or not user.is_active:
  900. return _NO_PRINTERS
  901. return await resolve_user_printer_scope(db, user)
  902. return _NO_PRINTERS
  903. @dataclass(frozen=True)
  904. class StreamOpener:
  905. """Who opened a camera stream, and on what authority; re-checked while it runs.
  906. A live view runs for hours on a token checked once. Its opener is a user
  907. (a 60-minute token minted with their session), an API key, a long-lived
  908. token (Cam Wall, overlay, Home Assistant), or nobody while auth was off.
  909. ``started_at`` is when the user's token was minted, not when the stream
  910. opened: a session that ended in between (its token checked just before)
  911. must still end the stream.
  912. """
  913. auth_on: bool
  914. username: str | None = None
  915. api_key_id: int | None = None
  916. api_key_prefix: str | None = None
  917. long_lived_id: int | None = None
  918. long_lived_user_id: int | None = None
  919. long_lived_prefix: str | None = None
  920. started_at: datetime = field(default_factory=utcnow_naive)
  921. async def camera_stream_access(token: str) -> tuple[PrinterScope, StreamOpener] | None:
  922. """Verify a camera stream token: the minter's printer scope and who it is.
  923. Tries the ephemeral 60-minute token first (the common, browser-bound case)
  924. and falls through to long-lived tokens (#1108) for HA / kiosk integrations
  925. that paste a token once and expect it to keep working for days; those
  926. carry their owner's scope. None when the token is invalid.
  927. """
  928. now = datetime.now(timezone.utc)
  929. async with async_session() as db:
  930. result = await db.execute(
  931. select(AuthEphemeralToken).where(
  932. AuthEphemeralToken.token == token,
  933. AuthEphemeralToken.token_type == "camera_stream",
  934. AuthEphemeralToken.expires_at > now,
  935. )
  936. )
  937. row = result.scalar_one_or_none()
  938. if row is not None:
  939. scope = await principal_printer_scope(db, row.username, row.api_key_id)
  940. prefix = await usable_api_key_prefix(db, row.api_key_id) if row.api_key_id is not None else None
  941. minted = row.expires_at.replace(tzinfo=None) - timedelta(minutes=CAMERA_STREAM_TOKEN_EXPIRE_MINUTES)
  942. return scope, StreamOpener(
  943. auth_on=True,
  944. username=row.username or None,
  945. api_key_id=row.api_key_id,
  946. api_key_prefix=prefix,
  947. started_at=minted,
  948. )
  949. # Long-lived path. Imported lazily so the auth module stays importable
  950. # at startup before the long_lived_tokens model is registered.
  951. from backend.app.services.long_lived_tokens import STREAM_SCOPES, verify_token as verify_long_lived
  952. record = await verify_long_lived(db, token, scope=STREAM_SCOPES)
  953. if record is None:
  954. return None
  955. scope = await resolve_user_id_printer_scope(db, record.user_id)
  956. return scope, StreamOpener(
  957. auth_on=True,
  958. long_lived_id=record.id,
  959. long_lived_user_id=record.user_id,
  960. long_lived_prefix=record.lookup_prefix,
  961. )
  962. async def verify_camera_stream_token(token: str) -> PrinterScope | None:
  963. """Verify a camera stream token (reusable -- does not consume it).
  964. Returns the printer scope of whoever minted it (#1727), or None when the
  965. token is invalid. See camera_stream_access.
  966. """
  967. access = await camera_stream_access(token)
  968. return access[0] if access is not None else None
  969. async def stream_opener_still_allowed(opener: StreamOpener, printer_id: int) -> bool:
  970. """Whether a stream's opener may still watch this printer (False also when
  971. it can't be read).
  972. A user's sessions must not have ended since the stream started (password
  973. change or reset, 2FA removal, restore), and they must still exist and be
  974. active; a key must still be usable and the same key; a long-lived token
  975. must not be revoked or expired; a stream opened while auth was off ends
  976. once it is on. In every case the printer must still be in scope.
  977. """
  978. from backend.app.models.long_lived_token import LongLivedToken
  979. from backend.app.services.long_lived_tokens import _is_expired
  980. try:
  981. async with async_session() as db:
  982. auth_on = await is_auth_enabled(db)
  983. if not opener.auth_on:
  984. return not auth_on
  985. if not auth_on:
  986. return True
  987. if opener.long_lived_id is not None:
  988. record = await db.get(LongLivedToken, opener.long_lived_id)
  989. if (
  990. record is None
  991. or record.revoked_at is not None
  992. or record.user_id != opener.long_lived_user_id
  993. or record.lookup_prefix != opener.long_lived_prefix
  994. or _is_expired(record, datetime.now(timezone.utc))
  995. ):
  996. return False
  997. scope = await resolve_user_id_printer_scope(db, record.user_id)
  998. elif opener.api_key_id is not None:
  999. if await usable_api_key_prefix(db, opener.api_key_id) != opener.api_key_prefix:
  1000. return False
  1001. scope = await principal_printer_scope(db, None, opener.api_key_id)
  1002. elif opener.username:
  1003. user = await get_user_by_username(db, opener.username)
  1004. if user is None or not user.is_active:
  1005. return False
  1006. changed = user.password_changed_at
  1007. if changed is not None and changed.replace(tzinfo=None) > opener.started_at:
  1008. return False
  1009. scope = await principal_printer_scope(db, opener.username, None)
  1010. else:
  1011. return False
  1012. return scope.allows(printer_id)
  1013. except Exception: # SEC-AUTH-EXC: a failed re-check ends the stream (fail-closed)
  1014. logger.warning("Camera stream re-check failed", exc_info=True)
  1015. return False
  1016. async def verify_camwall_token(token: str) -> PrinterScope | None:
  1017. """Verify a Cam Wall token (#2531). Reusable -- does not consume it.
  1018. Returns the token owner's printer scope (#1727), or None when invalid.
  1019. Deliberately narrower than :func:`verify_camera_stream_token`: only the
  1020. long-lived ``camwall`` scope passes. The 60-minute ephemeral token belongs
  1021. to a logged-in browser, which already reaches the wall's metadata through
  1022. the ordinary printers API and has no need of this endpoint; and a
  1023. ``camera_stream`` token was handed out for video alone, so it must not
  1024. acquire the ability to enumerate printers by name just because a new
  1025. feature shipped.
  1026. """
  1027. async with async_session() as db:
  1028. from backend.app.services.long_lived_tokens import verify_token as verify_long_lived
  1029. record = await verify_long_lived(db, token, scope="camwall")
  1030. if record is None:
  1031. return None
  1032. return await resolve_user_id_printer_scope(db, record.user_id)
  1033. async def verify_overlay_token(token: str) -> PrinterScope | None:
  1034. """Verify a streaming-overlay token (#2613). Reusable -- does not consume it.
  1035. Returns the token owner's printer scope (#1727), or None when invalid.
  1036. Like :func:`verify_camwall_token`, only the matching long-lived scope passes:
  1037. the overlay status feed names the file being printed, so it must not be
  1038. reachable by a ``camwall`` token (which is trusted to hide the part name) or
  1039. a bare ``camera_stream`` token (handed out for video alone). The 60-minute
  1040. ephemeral token belongs to a logged-in browser, which reaches the same data
  1041. through the ordinary printers API and has no need of this endpoint.
  1042. """
  1043. async with async_session() as db:
  1044. from backend.app.services.long_lived_tokens import verify_token as verify_long_lived
  1045. record = await verify_long_lived(db, token, scope="overlay")
  1046. if record is None:
  1047. return None
  1048. return await resolve_user_id_printer_scope(db, record.user_id)
  1049. # --- Media tokens (#3025) ---
  1050. # Browsers cannot attach ``Authorization`` headers to ``<img src>`` / ``<video
  1051. # src>``, so image routes need a credential that fits in a query parameter.
  1052. # Until #3025 they borrowed the *camera stream* token for that, which had two
  1053. # costs: minting one requires ``camera:view``, so a user could not see a
  1054. # library thumbnail without also being handed the live camera pointed at the
  1055. # operator's room; and a camera-stream token records no principal at all, so
  1056. # the thirteen non-camera routes had no identity to check ownership against
  1057. # and returned any row to any holder.
  1058. #
  1059. # A media token fixes both by following the *websocket* token instead: it
  1060. # stores the username, so ``require_media_token_*`` can resolve the real user
  1061. # and apply the same per-row visibility gate the header-authenticated sibling
  1062. # routes already use. Like the websocket token it is not consumed (a page of
  1063. # thumbnails is many requests) and it outlives a password change by up to its
  1064. # TTL -- acceptable for read-only media at 60 minutes, and identical to the
  1065. # guarantee ``/api/v1/ws`` has made since GHSA-r2qv.
  1066. MEDIA_TOKEN_EXPIRE_MINUTES = 60
  1067. async def create_media_token(username: str | None) -> str:
  1068. """Create a reusable token for media (thumbnail / preview / icon) routes.
  1069. Records the issuing principal in ``username`` exactly as
  1070. :func:`create_websocket_token` does. API-keyed callers reach this with
  1071. ``None`` and get the empty string, which :func:`verify_media_token`
  1072. reports back and the dependencies then reject while auth is enabled --
  1073. an API key has no per-row ownership identity, and it does not need one
  1074. here because the media routes accept ``X-API-Key`` directly.
  1075. """
  1076. now = datetime.now(timezone.utc)
  1077. expires_at = now + timedelta(minutes=MEDIA_TOKEN_EXPIRE_MINUTES)
  1078. token = secrets.token_urlsafe(24)
  1079. async with async_session() as db:
  1080. # Prune expired tokens opportunistically (same shape as camera/websocket).
  1081. await db.execute(
  1082. delete(AuthEphemeralToken).where(
  1083. AuthEphemeralToken.token_type == "media",
  1084. AuthEphemeralToken.expires_at < now,
  1085. )
  1086. )
  1087. db.add(
  1088. AuthEphemeralToken(
  1089. token=token,
  1090. token_type="media",
  1091. username=username or "",
  1092. expires_at=expires_at,
  1093. )
  1094. )
  1095. await db.commit()
  1096. return token
  1097. async def verify_media_token(token: str) -> str | None:
  1098. """Verify a media token, returning the username it was minted for.
  1099. Returns ``""`` for a token minted by an API key (no per-row identity) and
  1100. ``None`` when the token is missing / expired / unknown. Not consumed --
  1101. one token serves every image on a page.
  1102. Deliberately narrower than :func:`verify_camera_stream_token`: no
  1103. long-lived scope passes here. ``camera_stream`` / ``camwall`` / ``overlay``
  1104. tokens are handed to kiosks, walls and Home Assistant to display *video*,
  1105. and are anonymous by construction, so accepting one would reinstate the
  1106. unowned read this token type exists to close (#3025). The inverse also
  1107. holds -- see :func:`verify_camwall_token`, which refuses a camera-stream
  1108. token for the same reason in the other direction.
  1109. """
  1110. now = datetime.now(timezone.utc)
  1111. async with async_session() as db:
  1112. result = await db.execute(
  1113. select(AuthEphemeralToken).where(
  1114. AuthEphemeralToken.token == token,
  1115. AuthEphemeralToken.token_type == "media",
  1116. AuthEphemeralToken.expires_at > now,
  1117. )
  1118. )
  1119. row = result.scalar_one_or_none()
  1120. if row is None:
  1121. return None
  1122. return row.username or ""
  1123. def verify_password(plain_password: str, hashed_password: str) -> bool:
  1124. """Verify a password against a hash.
  1125. Uses pbkdf2_sha256 which handles long passwords automatically.
  1126. """
  1127. return pwd_context.verify(plain_password, hashed_password)
  1128. def get_password_hash(password: str) -> str:
  1129. """Hash a password.
  1130. Uses pbkdf2_sha256 which is secure and has no password length limit.
  1131. """
  1132. return pwd_context.hash(password)
  1133. def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
  1134. """Create a JWT access token with jti (revocation) and iat (freshness) claims."""
  1135. to_encode = data.copy()
  1136. now = datetime.now(timezone.utc)
  1137. if expires_delta:
  1138. expire = now + expires_delta
  1139. else:
  1140. expire = now + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  1141. jti = secrets.token_hex(16)
  1142. to_encode.update({"exp": expire, "jti": jti, "iat": now})
  1143. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  1144. return encoded_jwt
  1145. def _is_token_fresh(iat: int | float | None, user: User) -> bool:
  1146. """Return False if the token was issued before the user's last password change.
  1147. Used to invalidate all sessions after a password reset/change (M-R7-B).
  1148. All tokens without an iat claim are unconditionally rejected — every token
  1149. issued by this server carries iat, so absence means the token is forged or
  1150. from a pre-iat code path whose max TTL at the time (24 h) has long since
  1151. expired. The post-#1706 admin-set ceiling does not relax this — an iat-less
  1152. token still cannot have been issued by current code.
  1153. """
  1154. if iat is None:
  1155. return False
  1156. if not hasattr(user, "password_changed_at") or user.password_changed_at is None:
  1157. return True # No password change recorded yet (I2 migration handles this)
  1158. token_issued_at = datetime.fromtimestamp(iat, tz=timezone.utc)
  1159. pca = user.password_changed_at
  1160. if pca.tzinfo is None:
  1161. pca = pca.replace(tzinfo=timezone.utc)
  1162. # JWT iat is whole seconds; truncate pca so tokens issued in the same second pass.
  1163. pca = pca.replace(microsecond=0)
  1164. return token_issued_at >= pca
  1165. async def revoke_jti(jti: str, expires_at: datetime, username: str | None = None) -> None:
  1166. """Store a revoked JWT jti so it is rejected on future requests.
  1167. Silently ignores duplicate inserts (e.g. double-logout with the same token).
  1168. """
  1169. from sqlalchemy.exc import IntegrityError
  1170. async with async_session() as db:
  1171. revoked = AuthEphemeralToken(
  1172. token=jti,
  1173. token_type="revoked_jti",
  1174. username=username,
  1175. expires_at=expires_at,
  1176. )
  1177. db.add(revoked)
  1178. try:
  1179. await db.commit()
  1180. except IntegrityError:
  1181. await db.rollback() # jti already revoked — desired state, ignore
  1182. async def is_jti_revoked(jti: str, db: AsyncSession | None = None) -> bool:
  1183. """Return True if the given jti has been revoked.
  1184. Pass ``db`` to reuse the caller's session instead of opening a new one
  1185. (issue #2572): the permission dependencies already hold a session, and a
  1186. second checkout per request doubled pool pressure — a login burst then
  1187. exhausted the pool. With ``db`` omitted a short session is opened as before,
  1188. for callers that check the jti before they have a session open.
  1189. """
  1190. async def _query(session: AsyncSession) -> bool:
  1191. result = await session.execute(
  1192. select(AuthEphemeralToken).where(
  1193. AuthEphemeralToken.token == jti,
  1194. AuthEphemeralToken.token_type == "revoked_jti",
  1195. )
  1196. )
  1197. return result.scalar_one_or_none() is not None
  1198. if db is not None:
  1199. return await _query(db)
  1200. async with async_session() as own_db:
  1201. return await _query(own_db)
  1202. async def get_user_by_username(db: AsyncSession, username: str) -> User | None:
  1203. """Get a user by username (case-insensitive) with groups loaded for permission checks."""
  1204. result = await db.execute(
  1205. select(User).where(func.lower(User.username) == func.lower(username)).options(selectinload(User.groups))
  1206. )
  1207. return result.scalar_one_or_none()
  1208. async def get_user_by_email(db: AsyncSession, email: str) -> User | None:
  1209. """Get a user by email (case-insensitive) with groups loaded for permission checks."""
  1210. result = await db.execute(
  1211. select(User).where(func.lower(User.email) == func.lower(email)).options(selectinload(User.groups))
  1212. )
  1213. return result.scalar_one_or_none()
  1214. async def authenticate_user(db: AsyncSession, username: str, password: str) -> User | None:
  1215. """Authenticate a user by username and password.
  1216. Username lookup is case-insensitive. Password is case-sensitive.
  1217. LDAP and OIDC users must authenticate via their respective providers.
  1218. """
  1219. user = await get_user_by_username(db, username)
  1220. if not user:
  1221. return None
  1222. if getattr(user, "auth_source", "local") in ("ldap", "oidc"):
  1223. return None # LDAP/OIDC users must authenticate via their provider
  1224. if not user.password_hash or not verify_password(password, user.password_hash):
  1225. return None
  1226. if not user.is_active:
  1227. return None
  1228. return user
  1229. async def authenticate_user_by_email(db: AsyncSession, email: str, password: str) -> User | None:
  1230. """Authenticate a user by email and password.
  1231. Email lookup is case-insensitive. Password is case-sensitive.
  1232. LDAP and OIDC users must authenticate via their respective providers.
  1233. """
  1234. user = await get_user_by_email(db, email)
  1235. if not user:
  1236. return None
  1237. if getattr(user, "auth_source", "local") in ("ldap", "oidc"):
  1238. return None # LDAP/OIDC users must authenticate via their provider
  1239. if not user.password_hash or not verify_password(password, user.password_hash):
  1240. return None
  1241. if not user.is_active:
  1242. return None
  1243. return user
  1244. # Short-lived cache for the auth-enabled flag (issue #2572). The middleware
  1245. # and every ownership/permission dependency probe this once (or more) per
  1246. # request; on a large farm that DB round-trip is pure overhead because the
  1247. # value changes only when an admin toggles auth.
  1248. #
  1249. # SECURITY: only a ``True`` (auth-enabled) result is EVER cached. A disabled /
  1250. # unconfigured result is never cached, so a stale cache can only ever cause a
  1251. # request to REQUIRE auth that a moment ago wasn't required — it can never skip
  1252. # an auth check that is now required. Staleness fails CLOSED, never open (cf.
  1253. # GHSA-6mf4-q26m-47pv). ``set_auth_enabled`` invalidates explicitly on any
  1254. # toggle; the TTL is only a backstop for out-of-band changes (a direct DB edit,
  1255. # or another worker process in a multi-worker deployment).
  1256. _AUTH_ENABLED_CACHE_TTL_SECONDS = 30.0
  1257. _auth_enabled_cached_value: bool = False
  1258. _auth_enabled_cached_until: float = 0.0
  1259. def invalidate_auth_enabled_cache() -> None:
  1260. """Drop the cached auth-enabled flag so the next probe re-reads the DB.
  1261. Call after any write that toggles the ``auth_enabled`` setting.
  1262. """
  1263. global _auth_enabled_cached_value, _auth_enabled_cached_until
  1264. _auth_enabled_cached_value = False
  1265. _auth_enabled_cached_until = 0.0
  1266. async def is_auth_enabled(db: AsyncSession) -> bool:
  1267. """Check if authentication is enabled.
  1268. Fails CLOSED on database errors. A previous version of this function
  1269. caught every exception and returned False — silently treating an
  1270. unavailable database as "auth is disabled" and granting unauthenticated
  1271. access to every endpoint that called it (GHSA-6mf4-q26m-47pv, CVSS 9.8).
  1272. An attacker could trigger that fail-open by flooding /api/v1/auth/login
  1273. to exhaust the process's file-descriptor budget, then hit a protected
  1274. endpoint during the window where the next DB op raised.
  1275. Legitimate "auth was never configured" still returns False — the
  1276. settings row is simply absent, ``scalar_one_or_none`` returns None,
  1277. no exception. Any OTHER failure (connection error, fd exhaustion,
  1278. schema mismatch, …) propagates so the caller can deny the request
  1279. (503 / 500). Fail-closed is the only safe default for an auth probe.
  1280. Result is cached briefly to cut per-request DB load on large farms; only
  1281. the enabled=True result is cached, so a stale read can only fail closed.
  1282. See the module-level cache comment above.
  1283. """
  1284. global _auth_enabled_cached_value, _auth_enabled_cached_until
  1285. if _auth_enabled_cached_value and time.monotonic() < _auth_enabled_cached_until:
  1286. return True
  1287. result = await db.execute(select(Settings).where(Settings.key == "auth_enabled"))
  1288. setting = result.scalar_one_or_none()
  1289. enabled = setting is not None and setting.value.lower() == "true"
  1290. if enabled:
  1291. _auth_enabled_cached_value = True
  1292. _auth_enabled_cached_until = time.monotonic() + _AUTH_ENABLED_CACHE_TTL_SECONDS
  1293. else:
  1294. # Never cache "disabled" — keep failing closed on any future staleness.
  1295. _auth_enabled_cached_value = False
  1296. return enabled
  1297. async def _user_from_api_key(db: AsyncSession, api_key: APIKey) -> User | None:
  1298. """Resolve the owner of a validated API key, or None for legacy ownerless keys.
  1299. Cloud routes (and any route that needs caller identity) read the returned
  1300. User to look up per-user state like ``cloud_token``. Legacy keys created
  1301. before #1182 have ``user_id IS NULL`` and stay anonymous — they keep working
  1302. against non-cloud routes for backward compatibility, but cloud routes will
  1303. surface a "recreate this key" error rather than 200 with empty results.
  1304. """
  1305. if api_key.user_id is None:
  1306. return None
  1307. result = await db.execute(select(User).where(User.id == api_key.user_id))
  1308. user = result.scalar_one_or_none()
  1309. if user is None or not user.is_active:
  1310. # CASCADE on user delete should prevent a dangling user_id, but if
  1311. # someone manually deactivates the owner the key shouldn't suddenly
  1312. # gain an "anonymous" identity — drop the request to None so cloud
  1313. # access fails closed.
  1314. return None
  1315. return user
  1316. # The row a successful validation produced for the request in flight. Printer-
  1317. # scoped routes validate the same credential twice -- once in the permission
  1318. # gate, once for the key's printer allowlist -- and a validation is a pbkdf2
  1319. # verify plus a ``last_used`` write, so the second one is pure cost. Keyed by
  1320. # the raw credential so a request carrying two of them can never cross their
  1321. # rows, and held in a ContextVar so it cannot outlive the task that set it.
  1322. _validated_api_key: ContextVar[tuple[str, APIKey] | None] = ContextVar("_validated_api_key", default=None)
  1323. # Same idea for a JWT: the user the permission gate resolved, so the printer
  1324. # scope lookup (#1727) needn't decode, revocation-check and load it again.
  1325. # Keyed by the raw token for the same reason as above.
  1326. _authenticated_user: ContextVar[tuple[str, User] | None] = ContextVar("_authenticated_user", default=None)
  1327. def _api_key_check_unavailable(error: Exception) -> HTTPException:
  1328. """The 503 for a key that couldn't be checked (database, pool), logged.
  1329. Not 401: the key may well be valid, and clients treat 401 "Invalid API key"
  1330. as final (the web interface clears its sign-in on it). Still fail-closed:
  1331. the request is refused either way.
  1332. """
  1333. logger.error("API key check failed: %s", error, exc_info=error)
  1334. return HTTPException(
  1335. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  1336. detail="Authentication service temporarily unavailable",
  1337. )
  1338. async def _validate_api_key(db: AsyncSession, api_key_value: str) -> APIKey | None:
  1339. """Validate an API key and return the APIKey object if valid, None otherwise.
  1340. Raises a 503 HTTPException when the key can't be checked at all (database
  1341. or pool error): that is not an invalid key, and must not read as one.
  1342. L-1: Pre-filter by key_prefix (first 8 chars) before running pbkdf2 so only
  1343. O(1) candidate rows are hashed instead of the full key table. The prefix is
  1344. not secret (it is shown in the admin UI), so this does not reduce security.
  1345. """
  1346. # key_prefix is stored as "<first-8-chars>..." (e.g. "bb_Abc12...").
  1347. # Matching on the first 8 chars of the submitted key reduces the scan to
  1348. # at most one row in practice (2^40 collision space for 5 base64 chars).
  1349. key_lookup = api_key_value[:8] if len(api_key_value) >= 8 else api_key_value
  1350. try:
  1351. result = await db.execute(
  1352. select(APIKey).where(
  1353. APIKey.enabled.is_(True),
  1354. APIKey.key_prefix.like(
  1355. key_lookup.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%", escape="\\"
  1356. ),
  1357. )
  1358. )
  1359. api_keys = result.scalars().all()
  1360. except Exception as e: # SEC-AUTH-EXC: key lookup failed -> raises 503, request refused (no key returned)
  1361. raise _api_key_check_unavailable(e) from e
  1362. for api_key in api_keys:
  1363. try:
  1364. matches = verify_password(api_key_value, api_key.key_hash)
  1365. except PasswordSizeError:
  1366. # The submitted value is too long to hash (passlib's limit): the
  1367. # client's input, not this row, and certainly not a match.
  1368. continue
  1369. except Exception as e: # SEC-AUTH-EXC: unverifiable hash counts as no match -> None -> 401
  1370. # An unreadable stored hash can't vouch for anything: not a match.
  1371. logger.warning("API key %s has an unreadable hash: %s", api_key.id, e)
  1372. continue
  1373. if not matches:
  1374. continue
  1375. # Check expiration
  1376. if api_key.expires_at:
  1377. expires = api_key.expires_at
  1378. if expires.tzinfo is None:
  1379. expires = expires.replace(tzinfo=timezone.utc)
  1380. if expires < datetime.now(timezone.utc):
  1381. return None # Expired
  1382. # Update last_used timestamp
  1383. api_key.last_used = datetime.now(timezone.utc)
  1384. try:
  1385. await db.commit()
  1386. except Exception as e: # SEC-AUTH-EXC: last_used write failed -> rollback + raise 503, key not returned
  1387. await db.rollback()
  1388. raise _api_key_check_unavailable(e) from e
  1389. _validated_api_key.set((api_key_value, api_key))
  1390. return api_key
  1391. return None
  1392. async def get_current_user_optional(
  1393. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1394. ) -> User | None:
  1395. """Get the current authenticated user from JWT token, or None if not authenticated.
  1396. Returns None only when NO credentials are supplied. If a token is supplied
  1397. but invalid/revoked, raises 401 — a revoked token must not grant anonymous
  1398. access (I6).
  1399. """
  1400. if credentials is None:
  1401. return None
  1402. _unauthorized = HTTPException(
  1403. status_code=status.HTTP_401_UNAUTHORIZED,
  1404. detail="Could not validate credentials",
  1405. headers={"WWW-Authenticate": "Bearer"},
  1406. )
  1407. try:
  1408. token = credentials.credentials
  1409. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  1410. username: str = payload.get("sub")
  1411. if username is None:
  1412. raise _unauthorized
  1413. jti: str | None = payload.get("jti")
  1414. iat: int | float | None = payload.get("iat")
  1415. except JWTError:
  1416. raise _unauthorized
  1417. if not jti:
  1418. raise _unauthorized # I6: revoked token → 401, not anonymous
  1419. async with async_session() as db:
  1420. if await is_jti_revoked(jti, db):
  1421. raise _unauthorized # I6: revoked token → 401, not anonymous
  1422. user = await get_user_by_username(db, username)
  1423. if user is None or not user.is_active:
  1424. raise _unauthorized
  1425. if not _is_token_fresh(iat, user):
  1426. raise _unauthorized
  1427. return user
  1428. async def get_current_user(
  1429. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1430. ) -> User:
  1431. """Get the current authenticated user from JWT token."""
  1432. credentials_exception = HTTPException(
  1433. status_code=status.HTTP_401_UNAUTHORIZED,
  1434. detail="Could not validate credentials",
  1435. headers={"WWW-Authenticate": "Bearer"},
  1436. )
  1437. if credentials is None:
  1438. raise credentials_exception
  1439. try:
  1440. token = credentials.credentials
  1441. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  1442. username: str = payload.get("sub")
  1443. if username is None:
  1444. raise credentials_exception
  1445. jti: str | None = payload.get("jti")
  1446. iat: int | float | None = payload.get("iat")
  1447. except JWTError:
  1448. raise credentials_exception
  1449. if not jti:
  1450. raise credentials_exception
  1451. async with async_session() as db:
  1452. if await is_jti_revoked(jti, db):
  1453. raise credentials_exception
  1454. user = await get_user_by_username(db, username)
  1455. if user is None:
  1456. raise credentials_exception
  1457. if not user.is_active:
  1458. raise HTTPException(
  1459. status_code=status.HTTP_403_FORBIDDEN,
  1460. detail="User account is disabled",
  1461. )
  1462. if not _is_token_fresh(iat, user):
  1463. raise credentials_exception
  1464. return user
  1465. async def get_current_active_user(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  1466. """Get the current active user (alias for clarity)."""
  1467. return current_user
  1468. async def require_auth_if_enabled(
  1469. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1470. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1471. ) -> User | None:
  1472. """Require authentication if auth is enabled, otherwise return None.
  1473. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  1474. (via X-API-Key header or Authorization: Bearer bb_xxx). API keys return
  1475. None for backward compatibility — routes that need the API-key owner (i.e.
  1476. cloud routes for #1182) resolve it via their own router-level dependency
  1477. that stashes ``request.state.api_key_owner``. Returning the owner here
  1478. instead would silently grant API-keyed callers access to every route that
  1479. fences via ``if current_user is None``, which is a wider surface than
  1480. #1182 was designed to expose.
  1481. """
  1482. async with async_session() as db:
  1483. auth_enabled = await is_auth_enabled(db)
  1484. if not auth_enabled:
  1485. return None
  1486. # Check for API key first (X-API-Key header). The owner is resolved
  1487. # purely for its side effect: a key whose owner has been deactivated
  1488. # must be dead everywhere, not just on the permission-gated routes.
  1489. # There is no permission to check here -- this dep is auth-only.
  1490. if x_api_key:
  1491. api_key = await _validate_api_key(db, x_api_key)
  1492. if api_key:
  1493. await resolve_apikey_owner(db, api_key)
  1494. return None # API key valid, allow access
  1495. # Check for Bearer token (could be JWT or API key)
  1496. if credentials is not None:
  1497. token = credentials.credentials
  1498. # Check if it's an API key (starts with bb_)
  1499. if token.startswith("bb_"):
  1500. api_key = await _validate_api_key(db, token)
  1501. if api_key:
  1502. await resolve_apikey_owner(db, api_key)
  1503. return None # API key valid, allow access
  1504. raise HTTPException(
  1505. status_code=status.HTTP_401_UNAUTHORIZED,
  1506. detail="Invalid API key",
  1507. headers={"WWW-Authenticate": "Bearer"},
  1508. )
  1509. # Otherwise treat as JWT
  1510. try:
  1511. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  1512. username: str = payload.get("sub")
  1513. if username is None:
  1514. raise HTTPException(
  1515. status_code=status.HTTP_401_UNAUTHORIZED,
  1516. detail="Could not validate credentials",
  1517. headers={"WWW-Authenticate": "Bearer"},
  1518. )
  1519. jti: str | None = payload.get("jti")
  1520. if not jti or await is_jti_revoked(jti, db):
  1521. raise HTTPException(
  1522. status_code=status.HTTP_401_UNAUTHORIZED,
  1523. detail="Could not validate credentials",
  1524. headers={"WWW-Authenticate": "Bearer"},
  1525. )
  1526. iat: int | float | None = payload.get("iat")
  1527. except JWTError:
  1528. raise HTTPException(
  1529. status_code=status.HTTP_401_UNAUTHORIZED,
  1530. detail="Could not validate credentials",
  1531. headers={"WWW-Authenticate": "Bearer"},
  1532. )
  1533. user = await get_user_by_username(db, username)
  1534. if user is None or not user.is_active:
  1535. raise HTTPException(
  1536. status_code=status.HTTP_401_UNAUTHORIZED,
  1537. detail="Could not validate credentials",
  1538. headers={"WWW-Authenticate": "Bearer"},
  1539. )
  1540. if not _is_token_fresh(iat, user):
  1541. raise HTTPException(
  1542. status_code=status.HTTP_401_UNAUTHORIZED,
  1543. detail="Could not validate credentials",
  1544. headers={"WWW-Authenticate": "Bearer"},
  1545. )
  1546. return user
  1547. # No credentials provided
  1548. raise HTTPException(
  1549. status_code=status.HTTP_401_UNAUTHORIZED,
  1550. detail="Authentication required",
  1551. headers={"WWW-Authenticate": "Bearer"},
  1552. )
  1553. def require_admin_if_auth_enabled():
  1554. """Dependency factory that requires admin role if auth is enabled.
  1555. GHSA-r2qv follow-up (audit pattern P3): explicitly fail-closed for API
  1556. keys. The previous implementation chained on ``require_auth_if_enabled``
  1557. which returns ``None`` for *both* "auth disabled" *and* "valid API
  1558. key" — the inner ``admin_checker`` then treated ``None`` as auth-
  1559. disabled and admitted the caller. If any route had ever adopted this
  1560. dep, any API key with no scope flags set would have satisfied an
  1561. admin requirement. The dep distinguishes the two cases by consulting
  1562. ``is_auth_enabled`` directly and rejecting API-keyed requests with
  1563. 403. "Admin" requires a user-identity role, which API keys do not
  1564. carry.
  1565. Admin semantics: uses ``User.is_admin`` (``role == "admin"`` OR
  1566. Administrators-group membership) so a default-install operator who
  1567. was made admin by being added to Administrators rather than by
  1568. flipping the legacy role column passes. Earlier this check looked
  1569. only at ``role`` and would have locked group-only admins out of the
  1570. user-management routes once those routes started requiring it.
  1571. """
  1572. async def admin_checker(
  1573. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1574. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1575. ) -> User | None:
  1576. async with async_session() as db:
  1577. if not await is_auth_enabled(db):
  1578. return None # Auth disabled — no role to check.
  1579. # Reject API-keyed requests up front: admin is a user-role
  1580. # concept, not a key-scope concept. The right path for
  1581. # admin-equivalent API-key access is a specific Permission
  1582. # (e.g. SETTINGS_UPDATE) gated by the allowlist, not the
  1583. # admin role.
  1584. if x_api_key or (credentials and credentials.credentials.startswith("bb_")):
  1585. raise HTTPException(
  1586. status_code=status.HTTP_403_FORBIDDEN,
  1587. detail="Admin operations require a user role; API keys cannot be admins",
  1588. )
  1589. # Standard JWT path: validate and require admin role.
  1590. if credentials is None:
  1591. raise HTTPException(
  1592. status_code=status.HTTP_401_UNAUTHORIZED,
  1593. detail="Authentication required",
  1594. headers={"WWW-Authenticate": "Bearer"},
  1595. )
  1596. try:
  1597. payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM])
  1598. username: str = payload.get("sub")
  1599. if username is None:
  1600. raise HTTPException(
  1601. status_code=status.HTTP_401_UNAUTHORIZED,
  1602. detail="Could not validate credentials",
  1603. headers={"WWW-Authenticate": "Bearer"},
  1604. )
  1605. jti: str | None = payload.get("jti")
  1606. if not jti or await is_jti_revoked(jti, db):
  1607. raise HTTPException(
  1608. status_code=status.HTTP_401_UNAUTHORIZED,
  1609. detail="Could not validate credentials",
  1610. headers={"WWW-Authenticate": "Bearer"},
  1611. )
  1612. iat: int | float | None = payload.get("iat")
  1613. except JWTError:
  1614. raise HTTPException(
  1615. status_code=status.HTTP_401_UNAUTHORIZED,
  1616. detail="Could not validate credentials",
  1617. headers={"WWW-Authenticate": "Bearer"},
  1618. )
  1619. user = await get_user_by_username(db, username)
  1620. if user is None or not user.is_active:
  1621. raise HTTPException(
  1622. status_code=status.HTTP_401_UNAUTHORIZED,
  1623. detail="Could not validate credentials",
  1624. headers={"WWW-Authenticate": "Bearer"},
  1625. )
  1626. if not _is_token_fresh(iat, user):
  1627. raise HTTPException(
  1628. status_code=status.HTTP_401_UNAUTHORIZED,
  1629. detail="Could not validate credentials",
  1630. headers={"WWW-Authenticate": "Bearer"},
  1631. )
  1632. if not user.is_admin:
  1633. raise HTTPException(
  1634. status_code=status.HTTP_403_FORBIDDEN,
  1635. detail="Requires admin role",
  1636. )
  1637. return user
  1638. return admin_checker
  1639. def generate_api_key() -> tuple[str, str, str]:
  1640. """Generate a new API key.
  1641. Returns:
  1642. tuple: (full_key, key_hash, key_prefix)
  1643. - full_key: The complete API key (only shown once on creation)
  1644. - key_hash: Hashed version for storage and verification
  1645. - key_prefix: First 8 characters for display purposes
  1646. """
  1647. # Generate a secure random API key (32 bytes = 64 hex characters)
  1648. full_key = f"bb_{secrets.token_urlsafe(32)}"
  1649. key_hash = get_password_hash(full_key)
  1650. key_prefix = full_key[:8] + "..." if len(full_key) > 8 else full_key
  1651. return full_key, key_hash, key_prefix
  1652. async def get_api_key(
  1653. authorization: Annotated[str | None, Header(alias="Authorization")] = None,
  1654. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1655. db: AsyncSession = Depends(get_db),
  1656. ) -> APIKey:
  1657. """Get and validate API key from request headers (the webhook routes).
  1658. Checks both 'Authorization: Bearer <key>' and 'X-API-Key: <key>' headers;
  1659. the key itself is checked by _validate_api_key. An expired key is an
  1660. invalid key, as on every other route.
  1661. """
  1662. api_key_value = None
  1663. if x_api_key:
  1664. api_key_value = x_api_key
  1665. elif authorization and authorization.startswith("Bearer "):
  1666. api_key_value = authorization.replace("Bearer ", "")
  1667. if not api_key_value:
  1668. raise HTTPException(
  1669. status_code=status.HTTP_401_UNAUTHORIZED,
  1670. detail="API key required. Provide 'X-API-Key' header or 'Authorization: Bearer <key>'",
  1671. )
  1672. # The same check as every other API-key route: a key that can't be checked
  1673. # (database error) is a 503 raised in there, not an invalid key.
  1674. api_key = await _validate_api_key(db, api_key_value)
  1675. if api_key is None:
  1676. raise HTTPException(
  1677. status_code=status.HTTP_401_UNAUTHORIZED,
  1678. detail="Invalid API key",
  1679. )
  1680. return api_key
  1681. async def caller_is_api_key(
  1682. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1683. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1684. ) -> bool:
  1685. """Return True when the request is authenticated via API key (X-API-Key or Bearer bb_xxx)."""
  1686. if x_api_key:
  1687. return True
  1688. return credentials is not None and credentials.credentials.startswith("bb_")
  1689. def check_permission(api_key: APIKey, permission: str) -> None:
  1690. """Check if API key has the required permission.
  1691. Args:
  1692. api_key: The API key object
  1693. permission: One of 'queue', 'control_printer', 'read_status'
  1694. Raises:
  1695. HTTPException: If permission is not granted
  1696. """
  1697. permission_map = {
  1698. "queue": "can_queue",
  1699. "control_printer": "can_control_printer",
  1700. "read_status": "can_read_status",
  1701. }
  1702. if permission not in permission_map:
  1703. raise HTTPException(
  1704. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  1705. detail=f"Unknown permission: {permission}",
  1706. )
  1707. attr_name = permission_map[permission]
  1708. if not getattr(api_key, attr_name, False):
  1709. raise HTTPException(
  1710. status_code=status.HTTP_403_FORBIDDEN,
  1711. detail=f"API key does not have '{permission}' permission",
  1712. )
  1713. # The coarse webhook permission names predate the Permission enum. Each maps to
  1714. # the enum member that best represents it, so the owner can be held to the same
  1715. # standard here as on the modern routes.
  1716. _WEBHOOK_PERMISSION_EQUIVALENT: dict[str, Permission] = {
  1717. "queue": Permission.QUEUE_CREATE,
  1718. "control_printer": Permission.PRINTERS_CONTROL,
  1719. "read_status": Permission.PRINTERS_READ,
  1720. }
  1721. async def check_webhook_permission(db: AsyncSession, api_key: APIKey, permission: str) -> None:
  1722. """``check_permission`` plus the owner checks the modern routes apply.
  1723. ``/webhook/*`` reaches its scope flags through ``check_permission`` rather
  1724. than ``_check_apikey_permissions``, so it does not pick up the owner
  1725. narrowing automatically. Without this it would be the way around the gate:
  1726. the same key that is refused printer control on ``/printers/{id}/print/stop``
  1727. could stop the print through ``/webhook/printer/{id}/stop``.
  1728. """
  1729. check_permission(api_key, permission)
  1730. owner = await resolve_apikey_owner(db, api_key)
  1731. equivalent = _WEBHOOK_PERMISSION_EQUIVALENT.get(permission)
  1732. if owner is not None and equivalent is not None and not owner.has_permission(equivalent.value):
  1733. raise HTTPException(
  1734. status_code=status.HTTP_403_FORBIDDEN,
  1735. detail=f"API key owner does not have '{equivalent.value}' permission",
  1736. )
  1737. async def api_key_printer_scope(db: AsyncSession, api_key: APIKey) -> PrinterScope:
  1738. """The printers ``api_key`` may reach: its own allowlist within its owner's scope.
  1739. Raises 403 when the owner was deactivated or deleted, like every other
  1740. owner check (see ``resolve_apikey_owner``).
  1741. """
  1742. scope = api_key_own_scope(api_key)
  1743. owner = await resolve_apikey_owner(db, api_key)
  1744. if owner is not None:
  1745. scope = scope.intersect(await resolve_user_printer_scope(db, owner))
  1746. return scope
  1747. async def ensure_api_key_printer_access(db: AsyncSession, api_key: APIKey, printer_id: int) -> None:
  1748. """Raise 404 unless ``api_key`` may reach ``printer_id`` (see ``api_key_printer_scope``)."""
  1749. (await api_key_printer_scope(db, api_key)).ensure(printer_id)
  1750. async def validated_api_key_from_request(
  1751. credentials: HTTPAuthorizationCredentials | None,
  1752. x_api_key: str | None,
  1753. ) -> APIKey | None:
  1754. """Return the validated API key carried by a request, if any.
  1755. Permission dependencies intentionally return ``None`` for API-key callers so
  1756. routes do not mistake a key for a user identity. Printer-bound routes still
  1757. need the key row to enforce ``printer_ids`` after the normal scope/owner
  1758. permission gate has run. This helper recognizes both supported transports.
  1759. """
  1760. candidate = x_api_key
  1761. if candidate is None and credentials is not None and credentials.credentials.startswith("bb_"):
  1762. candidate = credentials.credentials
  1763. if candidate is None:
  1764. return None
  1765. cached = _validated_api_key.get()
  1766. if cached is not None and cached[0] == candidate:
  1767. return cached[1]
  1768. async with async_session() as db:
  1769. api_key = await _validate_api_key(db, candidate)
  1770. if api_key is None:
  1771. raise HTTPException(
  1772. status_code=status.HTTP_401_UNAUTHORIZED,
  1773. detail="Invalid API key",
  1774. headers={"WWW-Authenticate": "Bearer"},
  1775. )
  1776. # Touch the JSON-backed value before detaching the row from the session.
  1777. _ = api_key.printer_ids
  1778. return api_key
  1779. async def current_api_key_if_present(
  1780. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1781. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1782. ) -> APIKey | None:
  1783. """FastAPI dependency exposing only an authenticated API-key principal."""
  1784. return await validated_api_key_from_request(credentials, x_api_key)
  1785. async def resolve_request_printer_scope(
  1786. credentials: HTTPAuthorizationCredentials | None,
  1787. x_api_key: str | None,
  1788. ) -> PrinterScope:
  1789. """The printer scope of whoever sent this request (#1727).
  1790. Meant to run after the route's permission gate, which has already turned
  1791. away bad credentials; it reuses what that gate resolved where it can. With
  1792. auth on and no usable principal it returns an empty scope, never every
  1793. printer.
  1794. """
  1795. async with async_session() as db:
  1796. if not await is_auth_enabled(db):
  1797. return ALL_PRINTERS
  1798. api_key = await validated_api_key_from_request(credentials, x_api_key)
  1799. if api_key is not None:
  1800. return await api_key_printer_scope(db, api_key)
  1801. if credentials is None:
  1802. return PrinterScope(frozenset())
  1803. cached = _authenticated_user.get()
  1804. if cached is not None and cached[0] == credentials.credentials:
  1805. user = cached[1]
  1806. else:
  1807. user = await get_current_user_optional(credentials)
  1808. if user is None:
  1809. return PrinterScope(frozenset())
  1810. return await resolve_user_printer_scope(db, user)
  1811. async def get_printer_scope_if_auth_enabled(
  1812. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1813. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1814. ) -> PrinterScope:
  1815. """FastAPI dependency for ``resolve_request_printer_scope``.
  1816. Declare it after the permission dependency so the gate runs first.
  1817. """
  1818. return await resolve_request_printer_scope(credentials, x_api_key)
  1819. RequestPrinterScope = Depends(get_printer_scope_if_auth_enabled)
  1820. def queue_review_required_for(user: User | None) -> bool:
  1821. """Whether jobs ``user`` queues must wait for someone to start them (#1620).
  1822. None is auth-off or a legacy ownerless API key, neither of which has a
  1823. reviewer above it. Whoever may start every job (queue:update_all) is the
  1824. reviewer, so their own jobs don't wait either.
  1825. """
  1826. return (
  1827. user is not None
  1828. and not user.has_permission(Permission.QUEUE_START_UNREVIEWED.value)
  1829. and not user.has_permission(Permission.QUEUE_UPDATE_ALL.value)
  1830. )
  1831. def may_start_queue_item(user: User | None, can_modify_all: bool, created_by_id: int | None) -> bool:
  1832. """Whether the caller may start a waiting queue item (#1620).
  1833. ``can_modify_all`` is what ``require_ownership_permission`` answered for
  1834. queue:update_all; an API key only gets it when its owner holds that. Anyone
  1835. else needs to be allowed to print without review, and the item must be
  1836. theirs or have no owner yet (a virtual-printer upload, claimed by starting
  1837. it, #1670).
  1838. """
  1839. if can_modify_all or user is None:
  1840. return True
  1841. if queue_review_required_for(user):
  1842. return False
  1843. return created_by_id is None or created_by_id == user.id
  1844. async def get_queue_review_required(
  1845. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1846. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1847. ) -> bool:
  1848. """FastAPI dependency: must the caller's new queue items wait for review (#1620)?
  1849. Permission dependencies answer API-key requests with no user, so the key's
  1850. owner decides here. Declare it after the permission dependency. With auth
  1851. on and no usable principal it answers True.
  1852. """
  1853. async with async_session() as db:
  1854. if not await is_auth_enabled(db):
  1855. return False
  1856. api_key = await validated_api_key_from_request(credentials, x_api_key)
  1857. if api_key is not None:
  1858. return queue_review_required_for(await resolve_apikey_owner(db, api_key))
  1859. if credentials is None:
  1860. return True
  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 True
  1868. return queue_review_required_for(user)
  1869. QueueReviewRequired = Depends(get_queue_review_required)
  1870. async def get_request_actor(
  1871. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1872. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1873. ) -> User | ApiKeyActor | None:
  1874. """FastAPI dependency: who a route's own ownership checks run against.
  1875. The signed-in user, or for an API key an ``ApiKeyActor`` for its owner.
  1876. None only when auth is off. Declare it after the permission dependency,
  1877. which has already turned away bad credentials.
  1878. """
  1879. async with async_session() as db:
  1880. if not await is_auth_enabled(db):
  1881. return None
  1882. api_key = await validated_api_key_from_request(credentials, x_api_key)
  1883. if api_key is not None:
  1884. return ApiKeyActor(api_key, await resolve_apikey_owner(db, api_key))
  1885. user = None
  1886. if credentials is not None:
  1887. cached = _authenticated_user.get()
  1888. if cached is not None and cached[0] == credentials.credentials:
  1889. user = cached[1]
  1890. else:
  1891. user = await get_current_user_optional(credentials)
  1892. if user is None:
  1893. raise HTTPException(
  1894. status_code=status.HTTP_401_UNAUTHORIZED,
  1895. detail="Authentication required",
  1896. headers={"WWW-Authenticate": "Bearer"},
  1897. )
  1898. return user
  1899. RequestActor = Depends(get_request_actor)
  1900. async def actor_still_exists(db: AsyncSession, actor: User | ApiKeyActor | None) -> bool:
  1901. """Whether the user a request started as still exists.
  1902. A request that downloads or extracts for seconds to minutes writes the id
  1903. it started with. A user deleted meanwhile leaves it pointing at nobody, or
  1904. on SQLite, which gives a freed id to the next user created, at someone
  1905. else; the name tells them apart. No actor (auth off) or a key without an
  1906. owner has no user to lose.
  1907. """
  1908. if actor is None or actor.id is None:
  1909. return True
  1910. found = await db.scalar(select(User.id).where(User.id == actor.id, User.username == actor.username))
  1911. return found is not None
  1912. async def require_actor_still_exists(db: AsyncSession, actor: User | ApiKeyActor | None) -> None:
  1913. """Stop a request whose user was deleted while it ran, before it saves anything as theirs."""
  1914. if not await actor_still_exists(db, actor):
  1915. raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="This account was deleted")
  1916. async def get_media_or_request_printer_scope(
  1917. token: str | None = None,
  1918. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1919. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1920. ) -> PrinterScope:
  1921. """``RequestPrinterScope`` for routes an ``<img>`` may load with ``?token=``.
  1922. Such a request carries a media token and no headers, so the header-based
  1923. lookup would find nobody and answer with no printers. With headers present
  1924. they win, exactly as in ``require_media_token_*``.
  1925. """
  1926. if token and credentials is None and x_api_key is None:
  1927. async with async_session() as db:
  1928. if not await is_auth_enabled(db):
  1929. return ALL_PRINTERS
  1930. username = await verify_media_token(token)
  1931. if not username:
  1932. return _NO_PRINTERS
  1933. user = await get_user_by_username(db, username)
  1934. if user is None or not user.is_active:
  1935. return _NO_PRINTERS
  1936. return await resolve_user_printer_scope(db, user)
  1937. return await resolve_request_printer_scope(credentials, x_api_key)
  1938. MediaOrRequestPrinterScope = Depends(get_media_or_request_printer_scope)
  1939. def require_printer_permission_if_auth_enabled(*permissions: str | Permission):
  1940. """Require permissions and that the path's ``printer_id`` is in the caller's scope.
  1941. For routes with ``{printer_id}`` in the path. A printer outside the scope
  1942. gets 404, the same as one that doesn't exist.
  1943. """
  1944. permission_checker = require_permission_if_auth_enabled(*permissions)
  1945. async def checker(
  1946. printer_id: int,
  1947. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1948. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1949. ) -> User | None:
  1950. user = await permission_checker(credentials=credentials, x_api_key=x_api_key)
  1951. scope = await resolve_request_printer_scope(credentials, x_api_key)
  1952. scope.ensure(printer_id)
  1953. return user
  1954. return checker
  1955. # Convenience dependencies - these are functions that return Depends objects
  1956. def RequireAdminIfAuthEnabled():
  1957. """Dependency that requires admin role if auth is enabled."""
  1958. return Depends(require_admin_if_auth_enabled())
  1959. def require_permission_if_auth_enabled(*permissions: str | Permission):
  1960. """Dependency factory that checks permissions only if auth is enabled.
  1961. This provides backward compatibility - when auth is disabled, all access is allowed.
  1962. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  1963. (via X-API-Key header or Authorization: Bearer bb_xxx).
  1964. Args:
  1965. *permissions: Permission strings or Permission enum values to require
  1966. Returns:
  1967. A dependency function that validates permissions if auth is enabled
  1968. """
  1969. # Convert Permission enums to strings
  1970. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  1971. async def permission_checker(
  1972. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1973. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1974. ) -> User | None:
  1975. async with async_session() as db:
  1976. auth_enabled = await is_auth_enabled(db)
  1977. if not auth_enabled:
  1978. return None # Auth disabled, allow access
  1979. # Check for API key first (X-API-Key header). API-keyed requests
  1980. # bypass the JWT permission check entirely — their scopes live on
  1981. # the APIKey row (can_queue / can_control_printer / can_read_status
  1982. # / can_access_cloud / printer_ids), and the dep returns None so
  1983. # routes don't gain a synthetic User identity that would grant
  1984. # access to fenced surfaces like long-lived-token management.
  1985. # Cloud routes (#1182) resolve the API-key owner separately via
  1986. # their own router-level dependency; see ``cloud.py``.
  1987. if x_api_key:
  1988. api_key = await _validate_api_key(db, x_api_key)
  1989. if api_key:
  1990. await authorize_api_key(db, api_key, perm_strings)
  1991. return None # API key valid, allow access
  1992. # Check for Bearer token (could be JWT or API key)
  1993. if credentials is not None:
  1994. token = credentials.credentials
  1995. # Check if it's an API key (starts with bb_)
  1996. if token.startswith("bb_"):
  1997. api_key = await _validate_api_key(db, token)
  1998. if api_key:
  1999. await authorize_api_key(db, api_key, perm_strings)
  2000. return None # API key valid, allow access
  2001. raise HTTPException(
  2002. status_code=status.HTTP_401_UNAUTHORIZED,
  2003. detail="Invalid API key",
  2004. headers={"WWW-Authenticate": "Bearer"},
  2005. )
  2006. # Otherwise treat as JWT
  2007. try:
  2008. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  2009. username: str = payload.get("sub")
  2010. if username is None:
  2011. raise HTTPException(
  2012. status_code=status.HTTP_401_UNAUTHORIZED,
  2013. detail="Could not validate credentials",
  2014. headers={"WWW-Authenticate": "Bearer"},
  2015. )
  2016. jti: str | None = payload.get("jti")
  2017. if not jti or await is_jti_revoked(jti, db):
  2018. raise HTTPException(
  2019. status_code=status.HTTP_401_UNAUTHORIZED,
  2020. detail="Could not validate credentials",
  2021. headers={"WWW-Authenticate": "Bearer"},
  2022. )
  2023. iat: int | float | None = payload.get("iat")
  2024. except JWTError:
  2025. raise HTTPException(
  2026. status_code=status.HTTP_401_UNAUTHORIZED,
  2027. detail="Could not validate credentials",
  2028. headers={"WWW-Authenticate": "Bearer"},
  2029. )
  2030. user = await get_user_by_username(db, username)
  2031. if user is None or not user.is_active:
  2032. raise HTTPException(
  2033. status_code=status.HTTP_401_UNAUTHORIZED,
  2034. detail="Could not validate credentials",
  2035. headers={"WWW-Authenticate": "Bearer"},
  2036. )
  2037. if not _is_token_fresh(iat, user):
  2038. raise HTTPException(
  2039. status_code=status.HTTP_401_UNAUTHORIZED,
  2040. detail="Could not validate credentials",
  2041. headers={"WWW-Authenticate": "Bearer"},
  2042. )
  2043. if not user.has_all_permissions(*perm_strings):
  2044. raise HTTPException(
  2045. status_code=status.HTTP_403_FORBIDDEN,
  2046. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  2047. )
  2048. _authenticated_user.set((token, user))
  2049. return user
  2050. # No credentials provided
  2051. raise HTTPException(
  2052. status_code=status.HTTP_401_UNAUTHORIZED,
  2053. detail="Authentication required",
  2054. headers={"WWW-Authenticate": "Bearer"},
  2055. )
  2056. return permission_checker
  2057. def RequirePermissionIfAuthEnabled(*permissions: str | Permission):
  2058. """Convenience dependency that requires permissions if auth is enabled."""
  2059. return Depends(require_permission_if_auth_enabled(*permissions))
  2060. def RequirePrinterPermissionIfAuthEnabled(*permissions: str | Permission):
  2061. """Require permissions plus the caller's printer scope for the path's ``printer_id``."""
  2062. return Depends(require_printer_permission_if_auth_enabled(*permissions))
  2063. def probe_permissions_if_auth_enabled(*permissions: str | Permission):
  2064. """Return permission availability while preserving authentication errors.
  2065. This is for endpoints that can return a useful permission-independent
  2066. subset. Missing permissions become ``False``; invalid or absent credentials
  2067. still retain the normal 401 response from the shared permission checker.
  2068. """
  2069. permission_checker = require_permission_if_auth_enabled(*permissions)
  2070. async def checker(
  2071. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  2072. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  2073. ) -> bool:
  2074. try:
  2075. await permission_checker(credentials, x_api_key)
  2076. except HTTPException as exc:
  2077. if exc.status_code == status.HTTP_403_FORBIDDEN:
  2078. return False
  2079. raise
  2080. return True
  2081. return checker
  2082. def require_any_permission_if_auth_enabled(*permissions: str | Permission):
  2083. """Dependency factory that requires AT LEAST ONE of the given permissions when auth is enabled."""
  2084. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  2085. async def checker(
  2086. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  2087. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  2088. ) -> User | None:
  2089. async with async_session() as db:
  2090. auth_enabled = await is_auth_enabled(db)
  2091. if not auth_enabled:
  2092. return None
  2093. if x_api_key:
  2094. api_key = await _validate_api_key(db, x_api_key)
  2095. if api_key:
  2096. # GHSA-r2qv-8222-hqg3: previously returned None unconditionally,
  2097. # letting any valid API key satisfy admin "any-of" route
  2098. # dependencies. require_any → at-least-one must pass the scope check.
  2099. await authorize_api_key(db, api_key, perm_strings, require_any=True)
  2100. return None
  2101. if credentials is not None:
  2102. token = credentials.credentials
  2103. if token.startswith("bb_"):
  2104. api_key = await _validate_api_key(db, token)
  2105. if api_key:
  2106. await authorize_api_key(db, api_key, perm_strings, require_any=True)
  2107. return None
  2108. raise HTTPException(
  2109. status_code=status.HTTP_401_UNAUTHORIZED,
  2110. detail="Invalid API key",
  2111. headers={"WWW-Authenticate": "Bearer"},
  2112. )
  2113. try:
  2114. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  2115. username: str = payload.get("sub")
  2116. if username is None:
  2117. raise HTTPException(
  2118. status_code=status.HTTP_401_UNAUTHORIZED,
  2119. detail="Could not validate credentials",
  2120. headers={"WWW-Authenticate": "Bearer"},
  2121. )
  2122. jti: str | None = payload.get("jti")
  2123. if not jti or await is_jti_revoked(jti, db):
  2124. raise HTTPException(
  2125. status_code=status.HTTP_401_UNAUTHORIZED,
  2126. detail="Could not validate credentials",
  2127. headers={"WWW-Authenticate": "Bearer"},
  2128. )
  2129. iat: int | float | None = payload.get("iat")
  2130. except JWTError:
  2131. raise HTTPException(
  2132. status_code=status.HTTP_401_UNAUTHORIZED,
  2133. detail="Could not validate credentials",
  2134. headers={"WWW-Authenticate": "Bearer"},
  2135. )
  2136. user = await get_user_by_username(db, username)
  2137. if user is None or not user.is_active:
  2138. raise HTTPException(
  2139. status_code=status.HTTP_401_UNAUTHORIZED,
  2140. detail="Could not validate credentials",
  2141. headers={"WWW-Authenticate": "Bearer"},
  2142. )
  2143. if not _is_token_fresh(iat, user):
  2144. raise HTTPException(
  2145. status_code=status.HTTP_401_UNAUTHORIZED,
  2146. detail="Could not validate credentials",
  2147. headers={"WWW-Authenticate": "Bearer"},
  2148. )
  2149. if not user.has_any_permission(*perm_strings):
  2150. raise HTTPException(
  2151. status_code=status.HTTP_403_FORBIDDEN,
  2152. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  2153. )
  2154. _authenticated_user.set((token, user))
  2155. return user
  2156. raise HTTPException(
  2157. status_code=status.HTTP_401_UNAUTHORIZED,
  2158. detail="Authentication required",
  2159. headers={"WWW-Authenticate": "Bearer"},
  2160. )
  2161. return checker
  2162. def RequireAnyPermissionIfAuthEnabled(*permissions: str | Permission):
  2163. """Convenience dependency that requires AT LEAST ONE of the given permissions when auth is enabled."""
  2164. return Depends(require_any_permission_if_auth_enabled(*permissions))
  2165. def require_camera_stream_token_if_auth_enabled():
  2166. """Dependency that validates a camera stream token query param when auth is enabled.
  2167. Used for camera stream/snapshot endpoints that are loaded via <img> tags
  2168. which cannot send Authorization headers. The frontend obtains a token from
  2169. POST /printers/camera/stream-token and appends it as ?token=xxx.
  2170. Camera routes only. Non-camera media (thumbnails, plate previews,
  2171. timelapses, cover images, icons) takes ``require_media_token_*``: minting a
  2172. camera-stream token costs ``camera:view``, which no thumbnail should
  2173. require, and the token names no principal, so a route guarded by it cannot
  2174. tell one user's rows from another's (#3025).
  2175. """
  2176. async def checker(printer_id: int, token: str | None = None) -> StreamOpener:
  2177. async with async_session() as db:
  2178. if not await is_auth_enabled(db):
  2179. return StreamOpener(auth_on=False) # Auth disabled, allow access
  2180. access = await camera_stream_access(token) if token else None
  2181. if access is None:
  2182. raise HTTPException(
  2183. status_code=status.HTTP_401_UNAUTHORIZED,
  2184. detail="Valid camera stream token required. Obtain one from POST /api/v1/printers/camera/stream-token",
  2185. )
  2186. scope, opener = access
  2187. # The token's minter may not see this printer (#1727)
  2188. scope.ensure(printer_id)
  2189. return opener
  2190. return checker
  2191. RequireCameraStreamTokenIfAuthEnabled = Depends(require_camera_stream_token_if_auth_enabled())
  2192. def require_camwall_token_if_auth_enabled():
  2193. """Dependency that validates a Cam Wall token query param when auth is enabled.
  2194. Used by the read-only Cam Wall feed (#2531), which a kiosk browser loads
  2195. with the token in the URL because it has no login session to carry a JWT.
  2196. Returns the token owner's printer scope, which the feed filters by (#1727).
  2197. """
  2198. async def checker(token: str | None = None) -> PrinterScope:
  2199. async with async_session() as db:
  2200. if not await is_auth_enabled(db):
  2201. return ALL_PRINTERS # Auth disabled, allow access
  2202. scope = await verify_camwall_token(token) if token else None
  2203. if scope is None:
  2204. raise HTTPException(
  2205. status_code=status.HTTP_401_UNAUTHORIZED,
  2206. detail="Valid Cam Wall token required. Create one under Settings > API Keys with the 'Cam Wall' scope.",
  2207. )
  2208. return scope
  2209. return checker
  2210. RequireCamWallTokenIfAuthEnabled = Depends(require_camwall_token_if_auth_enabled())
  2211. def require_overlay_token_if_auth_enabled():
  2212. """Dependency that validates a streaming-overlay token query param when auth
  2213. is enabled.
  2214. Used by the read-only overlay status feed (#2613), which OBS (or any
  2215. embed with no login session) loads with the token in the URL because it
  2216. has no JWT to carry.
  2217. """
  2218. async def checker(printer_id: int, token: str | None = None) -> None:
  2219. async with async_session() as db:
  2220. if not await is_auth_enabled(db):
  2221. return # Auth disabled, allow access
  2222. scope = await verify_overlay_token(token) if token else None
  2223. if scope is None:
  2224. raise HTTPException(
  2225. status_code=status.HTTP_401_UNAUTHORIZED,
  2226. detail="Valid overlay token required. Create one under Settings > API Keys with the 'Streaming Overlay' scope.",
  2227. )
  2228. # The token owner may not see this printer (#1727)
  2229. scope.ensure(printer_id)
  2230. return checker
  2231. RequireOverlayTokenIfAuthEnabled = Depends(require_overlay_token_if_auth_enabled())
  2232. def require_overlay_token_any_printer_if_auth_enabled():
  2233. """The overlay-token check for overlay assets that belong to no printer.
  2234. The overlay logo (#3104) is one per installation, so there is no printer
  2235. for the token owner's scope (#1727) to be checked against; a valid overlay
  2236. token is all it takes, as before.
  2237. """
  2238. async def checker(token: str | None = None) -> None:
  2239. async with async_session() as db:
  2240. if not await is_auth_enabled(db):
  2241. return # Auth disabled, allow access
  2242. if token is None or await verify_overlay_token(token) is None:
  2243. raise HTTPException(
  2244. status_code=status.HTTP_401_UNAUTHORIZED,
  2245. detail="Valid overlay token required. Create one under Settings > API Keys with the 'Streaming Overlay' scope.",
  2246. )
  2247. return checker
  2248. RequireOverlayTokenAnyPrinterIfAuthEnabled = Depends(require_overlay_token_any_printer_if_auth_enabled())
  2249. def require_ownership_permission(
  2250. all_permission: str | Permission,
  2251. own_permission: str | Permission,
  2252. ):
  2253. """Dependency factory for ownership-based permission checks.
  2254. - User with ``all_permission`` can modify any item
  2255. - User with ``own_permission`` can only modify items where created_by_id == user.id
  2256. - Ownerless items (created_by_id = null) require ``all_permission``
  2257. - API keys (via X-API-Key header or Bearer bb_xxx) must satisfy the
  2258. ``all_permission``'s API-key scope flag (e.g. ``can_queue`` for
  2259. ``QUEUE_UPDATE_ALL``) and then receive ``can_modify_all=True``.
  2260. OWN/ALL ownership pairs map to the same scope flag in
  2261. ``_APIKEY_SCOPE_BY_PERMISSION`` so checking ``all_permission`` is the
  2262. correct gate; API keys have no per-row ownership identity. Pre-
  2263. GHSA-r2qv-8222-hqg3 fix this returned ``(None, True)`` for any valid
  2264. key with no scope check — see ``core/auth.py`` allowlist commentary.
  2265. Returns:
  2266. A dependency function that returns (user, can_modify_all).
  2267. - can_modify_all=True: user can modify any item
  2268. - can_modify_all=False: user can only modify their own items
  2269. """
  2270. all_perm = all_permission.value if isinstance(all_permission, Permission) else all_permission
  2271. own_perm = own_permission.value if isinstance(own_permission, Permission) else own_permission
  2272. async def checker(
  2273. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  2274. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  2275. ) -> tuple[User | None, bool]:
  2276. """Returns (user, can_modify_all).
  2277. - can_modify_all=True: user can modify any item
  2278. - can_modify_all=False: user can only modify their own items
  2279. """
  2280. async with async_session() as db:
  2281. auth_enabled = await is_auth_enabled(db)
  2282. if not auth_enabled:
  2283. return None, True # Auth disabled, allow all
  2284. # GHSA-r2qv-8222-hqg3: previously API keys received (None, True)
  2285. # unconditionally on ownership-modify routes — a "queue-only" key
  2286. # could delete any user's archives, library files, queue items.
  2287. # OWN and ALL ownership perms both map to the same scope flag
  2288. # (e.g. both QUEUE_UPDATE_OWN and QUEUE_UPDATE_ALL → can_queue),
  2289. # so checking ``all_perm`` against the api_key's scope is the
  2290. # correct gate. API keys don't have per-row ownership identity, so
  2291. # on pass we keep can_modify_all=True (preserves prior intent,
  2292. # narrows access to keys with the right scope flag).
  2293. if x_api_key:
  2294. api_key = await _validate_api_key(db, x_api_key)
  2295. if api_key:
  2296. await authorize_api_key(db, api_key, [all_perm])
  2297. return None, True
  2298. # Check for Bearer token (could be JWT or API key)
  2299. if credentials is not None:
  2300. token = credentials.credentials
  2301. # Check if it's an API key (starts with bb_)
  2302. if token.startswith("bb_"):
  2303. api_key = await _validate_api_key(db, token)
  2304. if api_key:
  2305. await authorize_api_key(db, api_key, [all_perm])
  2306. return None, True
  2307. raise HTTPException(
  2308. status_code=status.HTTP_401_UNAUTHORIZED,
  2309. detail="Invalid API key",
  2310. headers={"WWW-Authenticate": "Bearer"},
  2311. )
  2312. # Otherwise treat as JWT
  2313. try:
  2314. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  2315. username: str = payload.get("sub")
  2316. if username is None:
  2317. raise HTTPException(
  2318. status_code=status.HTTP_401_UNAUTHORIZED,
  2319. detail="Could not validate credentials",
  2320. headers={"WWW-Authenticate": "Bearer"},
  2321. )
  2322. jti: str | None = payload.get("jti")
  2323. if not jti or await is_jti_revoked(jti, db):
  2324. raise HTTPException(
  2325. status_code=status.HTTP_401_UNAUTHORIZED,
  2326. detail="Could not validate credentials",
  2327. headers={"WWW-Authenticate": "Bearer"},
  2328. )
  2329. iat: int | float | None = payload.get("iat")
  2330. except JWTError:
  2331. raise HTTPException(
  2332. status_code=status.HTTP_401_UNAUTHORIZED,
  2333. detail="Could not validate credentials",
  2334. headers={"WWW-Authenticate": "Bearer"},
  2335. )
  2336. user = await get_user_by_username(db, username)
  2337. if user is None or not user.is_active:
  2338. raise HTTPException(
  2339. status_code=status.HTTP_401_UNAUTHORIZED,
  2340. detail="Could not validate credentials",
  2341. headers={"WWW-Authenticate": "Bearer"},
  2342. )
  2343. if not _is_token_fresh(iat, user):
  2344. raise HTTPException(
  2345. status_code=status.HTTP_401_UNAUTHORIZED,
  2346. detail="Could not validate credentials",
  2347. headers={"WWW-Authenticate": "Bearer"},
  2348. )
  2349. if user.has_permission(all_perm):
  2350. return user, True
  2351. if user.has_permission(own_perm):
  2352. return user, False
  2353. raise HTTPException(
  2354. status_code=status.HTTP_403_FORBIDDEN,
  2355. detail=f"Missing permission: {own_perm} or {all_perm}",
  2356. )
  2357. # No credentials provided
  2358. raise HTTPException(
  2359. status_code=status.HTTP_401_UNAUTHORIZED,
  2360. detail="Authentication required",
  2361. headers={"WWW-Authenticate": "Bearer"},
  2362. )
  2363. return checker
  2364. async def _user_from_media_token(token: str) -> User:
  2365. """Resolve the ``User`` a media token was minted for, or raise 401 (#3025).
  2366. Fail-closed on every miss: an unknown/expired token, a token minted by an
  2367. API key (empty username -- see :func:`create_media_token`), a username no
  2368. longer in the table, and a deactivated account all raise rather than fall
  2369. through to an anonymous read. The 401 detail names the mint endpoint so a
  2370. stale tab knows how to recover, and the frontend's error handler refreshes
  2371. the token on the first failed <img> load.
  2372. """
  2373. unauthorized = HTTPException(
  2374. status_code=status.HTTP_401_UNAUTHORIZED,
  2375. detail="Valid media token required. Obtain one from POST /api/v1/auth/media-token",
  2376. )
  2377. username = await verify_media_token(token)
  2378. if not username:
  2379. raise unauthorized
  2380. async with async_session() as db:
  2381. user = await get_user_by_username(db, username)
  2382. if user is None or not user.is_active:
  2383. raise unauthorized
  2384. return user
  2385. def require_media_token_permission(*permissions: str | Permission):
  2386. """Media-route dependency for resources with no per-row ownership (#3025).
  2387. Accepts either a ``?token=`` media token (the ``<img>`` case) or the
  2388. ordinary ``Authorization`` / ``X-API-Key`` headers, so a ``fetch()`` or an
  2389. API-keyed integration authenticates here exactly as it does on the
  2390. resource's sibling routes. Requires ALL of ``permissions``, matching
  2391. :func:`require_permission_if_auth_enabled`.
  2392. Returns the resolved ``User``, or ``None`` when auth is disabled or the
  2393. caller is an API key -- the same ``User | None`` contract the header-only
  2394. dependency has, so handlers need no new branch.
  2395. """
  2396. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  2397. header_checker = require_permission_if_auth_enabled(*permissions)
  2398. async def checker(
  2399. token: str | None = None,
  2400. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  2401. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  2402. ) -> User | None:
  2403. async with async_session() as db:
  2404. if not await is_auth_enabled(db):
  2405. return None # Auth disabled, allow access
  2406. if token:
  2407. user = await _user_from_media_token(token)
  2408. missing = [p for p in perm_strings if not user.has_permission(p)]
  2409. if missing:
  2410. raise HTTPException(
  2411. status_code=status.HTTP_403_FORBIDDEN,
  2412. detail=f"Missing required permissions: {', '.join(missing)}",
  2413. )
  2414. return user
  2415. return await header_checker(credentials=credentials, x_api_key=x_api_key)
  2416. return checker
  2417. def require_media_token_ownership(
  2418. all_permission: str | Permission,
  2419. own_permission: str | Permission,
  2420. ):
  2421. """Media-route dependency for ownership-scoped resources (#3025).
  2422. The ownership counterpart of :func:`require_media_token_permission`, and
  2423. the reason media tokens carry a principal at all: it returns the same
  2424. ``(user, can_read_all)`` pair as :func:`require_ownership_permission`, so a
  2425. thumbnail route can hand it straight to the ``_ensure_*_visible`` gate its
  2426. header-authenticated siblings already use instead of serving any row to any
  2427. token holder.
  2428. Header callers are delegated to :func:`require_ownership_permission`
  2429. unchanged -- including its API-key rule, where a key satisfying the ALL
  2430. permission's scope flag gets ``can_read_all=True`` because keys have no
  2431. per-row identity.
  2432. """
  2433. all_perm = all_permission.value if isinstance(all_permission, Permission) else all_permission
  2434. own_perm = own_permission.value if isinstance(own_permission, Permission) else own_permission
  2435. header_checker = require_ownership_permission(all_permission, own_permission)
  2436. async def checker(
  2437. token: str | None = None,
  2438. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  2439. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  2440. ) -> tuple[User | None, bool]:
  2441. async with async_session() as db:
  2442. if not await is_auth_enabled(db):
  2443. return None, True # Auth disabled, allow all
  2444. if token:
  2445. user = await _user_from_media_token(token)
  2446. if user.has_permission(all_perm):
  2447. return user, True
  2448. if user.has_permission(own_perm):
  2449. return user, False
  2450. raise HTTPException(
  2451. status_code=status.HTTP_403_FORBIDDEN,
  2452. detail=f"Missing permission: {own_perm} or {all_perm}",
  2453. )
  2454. return await header_checker(credentials=credentials, x_api_key=x_api_key)
  2455. return checker
  2456. def require_media_token_printer_permission(permission: str | Permission):
  2457. """Media-route dependency for per-printer resources (#3025).
  2458. :func:`require_media_token_permission` plus the caller's printer scope for
  2459. the path's ``printer_id``, mirroring
  2460. :func:`require_printer_permission_if_auth_enabled`. A media token names a
  2461. user, so their scope applies; a header caller gets the request's scope.
  2462. """
  2463. media_checker = require_media_token_permission(permission)
  2464. async def checker(
  2465. printer_id: int,
  2466. token: str | None = None,
  2467. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  2468. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  2469. ) -> User | None:
  2470. user = await media_checker(token=token, credentials=credentials, x_api_key=x_api_key)
  2471. if token and user is not None:
  2472. async with async_session() as db:
  2473. scope = await resolve_user_printer_scope(db, user)
  2474. else:
  2475. scope = await resolve_request_printer_scope(credentials, x_api_key)
  2476. scope.ensure(printer_id)
  2477. return user
  2478. return checker