auth.py 118 KB

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