auth.py 111 KB

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