auth.py 120 KB

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