auth.py 121 KB

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