auth.py 134 KB

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