auth.py 134 KB

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