auth.py 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802
  1. from __future__ import annotations
  2. import logging
  3. import os
  4. import secrets
  5. from datetime import datetime, timedelta, timezone
  6. from typing import Annotated
  7. import jwt
  8. from fastapi import Depends, Header, HTTPException, status
  9. from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
  10. from jwt.exceptions import PyJWTError as JWTError
  11. from passlib.context import CryptContext
  12. from sqlalchemy import delete, func, select
  13. from sqlalchemy.ext.asyncio import AsyncSession
  14. from sqlalchemy.orm import selectinload
  15. from backend.app.core.database import async_session, get_db
  16. from backend.app.core.permissions import Permission
  17. from backend.app.models.api_key import APIKey
  18. from backend.app.models.auth_ephemeral import AuthEphemeralToken, TokenType
  19. from backend.app.models.settings import Settings
  20. from backend.app.models.user import User
  21. logger = logging.getLogger(__name__)
  22. # GHSA-r2qv-8222-hqg3 (CVSS 9.9) — API key permission enforcement is allowlist-based.
  23. #
  24. # Until 0.2.4.x, ``_check_apikey_permissions`` only consulted the admin denylist
  25. # below. The three documented scope flags on ``APIKey``
  26. # (``can_read_status`` / ``can_queue`` / ``can_control_printer`` / ``can_manage_library``)
  27. # were enforced only by ``check_permission()`` inside ``routes/webhook.py``;
  28. # every other route used ``require_permission_if_auth_enabled`` which fell
  29. # through to the denylist-only path, so an API key with all flags unchecked
  30. # could still stop prints, edit queue items, and read every endpoint not in
  31. # this set. ``require_any_permission_if_auth_enabled`` and
  32. # ``require_ownership_permission`` did not call this helper at all, so admin
  33. # "any-of" routes and ownership-modify routes were entirely ungated for API keys.
  34. #
  35. # Fix: ``_check_apikey_permissions`` now requires every requested permission to
  36. # be present in ``_APIKEY_SCOPE_BY_PERMISSION`` (allowlist), and gates on the
  37. # corresponding scope flag on the API key. Unmapped permissions = 403. This
  38. # means a Permission added to ``core/permissions.py`` without a matching entry
  39. # in ``_APIKEY_SCOPE_BY_PERMISSION`` is automatically denied for API keys —
  40. # the previous denylist shape allowed every new Permission to silently widen
  41. # the API-key surface.
  42. #
  43. # The denylist is retained for documentation / drift-detection only — its
  44. # entries also satisfy "not in the allowlist", so they fail closed regardless.
  45. #
  46. # Mapping rationale (see wiki/features/api-keys.md):
  47. # can_read_status → every ``*_READ`` + camera + stats + system + websocket
  48. # can_queue → queue write ops + archive reprint
  49. # can_control_printer → physical printer + smart-plug control
  50. # can_manage_library → library upload/own + MakerWorld import (separate
  51. # trust level from queue management, hence its own flag)
  52. # can_manage_inventory → spool/catalog/forecast writes + SpoolBuddy kiosk writes
  53. # can_manage_maintenance→ per-printer maintenance log/reset + type-catalog CRUD
  54. # admin-only → unmapped (default-deny); covers all create/update/
  55. # delete of admin resources, settings writes, user/
  56. # group/api-key/backup admin ops, discovery scan,
  57. # cloud auth, library ALL-ownership perms, purges
  58. _APIKEY_SCOPE_BY_PERMISSION: dict[Permission, str] = {
  59. # can_read_status — read-only access to status, history, and configuration
  60. Permission.PRINTERS_READ: "can_read_status",
  61. # Legacy flat permissions retained for back-compat with custom API keys —
  62. # the role bootstraps no longer use these, but custom keys may still
  63. # carry can_read_status scope mapping. New endpoints gate on the
  64. # ARCHIVES_READ_OWN / _ALL split (maziggy/bambuddy-security #2).
  65. Permission.ARCHIVES_READ: "can_read_status",
  66. Permission.ARCHIVES_READ_OWN: "can_read_status",
  67. Permission.ARCHIVES_READ_ALL: "can_read_status",
  68. Permission.QUEUE_READ: "can_read_status",
  69. Permission.QUEUE_READ_OWN: "can_read_status",
  70. Permission.QUEUE_READ_ALL: "can_read_status",
  71. Permission.LIBRARY_READ: "can_read_status",
  72. Permission.LIBRARY_READ_OWN: "can_read_status",
  73. Permission.LIBRARY_READ_ALL: "can_read_status",
  74. Permission.PROJECTS_READ: "can_read_status",
  75. Permission.FILAMENTS_READ: "can_read_status",
  76. Permission.INVENTORY_READ: "can_read_status",
  77. Permission.INVENTORY_VIEW_ASSIGNMENTS: "can_read_status",
  78. Permission.INVENTORY_FORECAST_READ: "can_read_status",
  79. Permission.SMART_PLUGS_READ: "can_read_status",
  80. Permission.CAMERA_VIEW: "can_read_status",
  81. Permission.MAINTENANCE_READ: "can_read_status",
  82. Permission.KPROFILES_READ: "can_read_status",
  83. Permission.NOTIFICATIONS_READ: "can_read_status",
  84. Permission.NOTIFICATION_TEMPLATES_READ: "can_read_status",
  85. Permission.EXTERNAL_LINKS_READ: "can_read_status",
  86. Permission.FIRMWARE_READ: "can_read_status",
  87. Permission.AMS_HISTORY_READ: "can_read_status",
  88. Permission.PRINTER_SENSOR_HISTORY_READ: "can_read_status",
  89. Permission.STATS_READ: "can_read_status",
  90. Permission.STATS_FILTER_BY_USER: "can_read_status",
  91. Permission.SYSTEM_READ: "can_read_status",
  92. # SETTINGS_READ stays allowed via read-status so SpoolBuddy kiosks keep
  93. # working (they need the UI-language setting via API key).
  94. Permission.SETTINGS_READ: "can_read_status",
  95. Permission.MAKERWORLD_VIEW: "can_read_status",
  96. Permission.WEBSOCKET_CONNECT: "can_read_status",
  97. # can_queue — queue write ops + reprint (which enqueues an existing archive)
  98. Permission.QUEUE_CREATE: "can_queue",
  99. Permission.QUEUE_UPDATE_OWN: "can_queue",
  100. Permission.QUEUE_UPDATE_ALL: "can_queue",
  101. Permission.QUEUE_DELETE_OWN: "can_queue",
  102. Permission.QUEUE_DELETE_ALL: "can_queue",
  103. Permission.QUEUE_REORDER: "can_queue",
  104. Permission.ARCHIVES_REPRINT_OWN: "can_queue",
  105. Permission.ARCHIVES_REPRINT_ALL: "can_queue",
  106. # can_control_printer — physical-world side effects on hardware
  107. Permission.PRINTERS_CONTROL: "can_control_printer",
  108. Permission.PRINTERS_FILES: "can_control_printer",
  109. Permission.PRINTERS_AMS_RFID: "can_control_printer",
  110. Permission.PRINTERS_CLEAR_PLATE: "can_control_printer",
  111. Permission.SMART_PLUGS_CONTROL: "can_control_printer",
  112. # can_manage_library — file-manager scope (upload/rename/delete library
  113. # entries + MakerWorld import which downloads files into the library).
  114. # OWN and ALL ownership variants map to the same scope so the
  115. # `require_ownership_permission` checker (which gates on `all_perm`)
  116. # passes the API key through. This matches `can_queue` and the
  117. # archives/inventory scopes — API keys have no per-row ownership identity
  118. # (line 1663), so splitting OWN/ALL across allowlist/denylist made the
  119. # whole library curation surface unreachable for API keys (#1832).
  120. # LIBRARY_PURGE stays admin-only as a genuinely destructive op that
  121. # bypasses the soft-delete window.
  122. Permission.LIBRARY_UPLOAD: "can_manage_library",
  123. Permission.LIBRARY_UPDATE_OWN: "can_manage_library",
  124. Permission.LIBRARY_UPDATE_ALL: "can_manage_library",
  125. Permission.LIBRARY_DELETE_OWN: "can_manage_library",
  126. Permission.LIBRARY_DELETE_ALL: "can_manage_library",
  127. Permission.MAKERWORLD_IMPORT: "can_manage_library",
  128. # can_manage_inventory — inventory write scope. Covers the documented
  129. # spool/catalog/forecast write surface AND the SpoolBuddy kiosk endpoints
  130. # (NFC scan, scale reading, system command/update) which used
  131. # INVENTORY_UPDATE as a stand-in for "kiosk write" under the prior
  132. # denylist model. Read-only inventory (INVENTORY_READ etc.) stays under
  133. # can_read_status.
  134. Permission.INVENTORY_CREATE: "can_manage_inventory",
  135. Permission.INVENTORY_UPDATE: "can_manage_inventory",
  136. Permission.INVENTORY_DELETE: "can_manage_inventory",
  137. Permission.INVENTORY_FORECAST_WRITE: "can_manage_inventory",
  138. # can_manage_maintenance — carved out of the admin denylist so HA-style
  139. # automations can log "cleaned nozzle" / reset a maintenance counter via
  140. # `POST /maintenance/items/{item_id}/perform` without granting broader
  141. # printer control or settings write (#1832 follow-up). Also covers the
  142. # per-printer maintenance CRUD (assign/remove items, edit intervals) and
  143. # the type-catalog CRUD — the type catalog is a config surface (system
  144. # types are auto-seeded, custom types are user-defined), so grouping it
  145. # with the item writes matches the operator mental model of "keys that
  146. # log maintenance can also manage what gets tracked." MAINTENANCE_READ
  147. # stays under can_read_status.
  148. Permission.MAINTENANCE_CREATE: "can_manage_maintenance",
  149. Permission.MAINTENANCE_UPDATE: "can_manage_maintenance",
  150. Permission.MAINTENANCE_DELETE: "can_manage_maintenance",
  151. # can_manage_archives — print-history curation. Carved out of the admin
  152. # denylist so automations can prune old prints via API key (#1888): the
  153. # archive delete/update routes gate on
  154. # ``require_ownership_permission(ARCHIVES_*_ALL, ARCHIVES_*_OWN)``, which
  155. # resolves the ALL permission for API keys (no per-row ownership identity,
  156. # same as can_queue / can_manage_library), so OWN and ALL map to the same
  157. # scope. ARCHIVES_PURGE stays admin-only (see denylist) as a genuinely
  158. # destructive op that drops the stats contribution, mirroring LIBRARY_PURGE.
  159. # ARCHIVES_REPRINT_* stays under can_queue (it enqueues a print).
  160. Permission.ARCHIVES_CREATE: "can_manage_archives",
  161. Permission.ARCHIVES_UPDATE_OWN: "can_manage_archives",
  162. Permission.ARCHIVES_UPDATE_ALL: "can_manage_archives",
  163. Permission.ARCHIVES_DELETE_OWN: "can_manage_archives",
  164. Permission.ARCHIVES_DELETE_ALL: "can_manage_archives",
  165. # can_manage_projects — project curation. Carved out of the admin denylist
  166. # so automations can create projects and batch-add archives via API key
  167. # (#1893). The project mutation routes gate on plain
  168. # ``RequirePermissionIfAuthEnabled(Permission.PROJECTS_*)`` (no OWN/ALL
  169. # ownership split — projects have no per-row ownership permission), so the
  170. # three CRUD permissions map directly to the one scope. Membership edits
  171. # (e.g. add-archives-to-project) gate on PROJECTS_UPDATE, so they're covered.
  172. # PROJECTS_READ stays under can_read_status (unchanged).
  173. Permission.PROJECTS_CREATE: "can_manage_projects",
  174. Permission.PROJECTS_UPDATE: "can_manage_projects",
  175. Permission.PROJECTS_DELETE: "can_manage_projects",
  176. # can_access_cloud — narrow opt-in scope, gated by the router-level
  177. # ``_cloud_api_key_gate`` and additionally enforced here so the route-
  178. # level ``cloud_caller(Permission.CLOUD_AUTH)`` dep also fails closed
  179. # when the flag is off (defence-in-depth).
  180. Permission.CLOUD_AUTH: "can_access_cloud",
  181. # ORCA_CLOUD_AUTH folds into the same ``can_access_cloud`` scope: same
  182. # trust dimension (third-party cloud access for profile sync), so an
  183. # operator who already accepted "this key can talk to clouds for the
  184. # owner" doesn't need a second toggle for Orca. Splitting later requires
  185. # a new column + migration — easy to add if the trust dimensions diverge.
  186. Permission.ORCA_CLOUD_AUTH: "can_access_cloud",
  187. }
  188. # Retained for documentation, drift-detection, and the prior "administrative
  189. # operations" error string. Entries here are also absent from
  190. # ``_APIKEY_SCOPE_BY_PERMISSION``, so they fail closed via the allowlist; the
  191. # denylist is a redundant explicit "these are admin" marker, not the load-
  192. # bearing security check.
  193. _APIKEY_DENIED_PERMISSIONS: frozenset[Permission] = frozenset(
  194. {
  195. # Settings administration (cred storage; rewriting these reaches SMTP/LDAP/MQTT).
  196. Permission.SETTINGS_UPDATE,
  197. Permission.SETTINGS_BACKUP,
  198. Permission.SETTINGS_RESTORE,
  199. # User / group / API-key administration.
  200. Permission.USERS_READ,
  201. Permission.USERS_CREATE,
  202. Permission.USERS_UPDATE,
  203. Permission.USERS_DELETE,
  204. Permission.GROUPS_READ,
  205. Permission.GROUPS_CREATE,
  206. Permission.GROUPS_UPDATE,
  207. Permission.GROUPS_DELETE,
  208. Permission.API_KEYS_CREATE,
  209. Permission.API_KEYS_UPDATE,
  210. Permission.API_KEYS_DELETE,
  211. Permission.API_KEYS_READ,
  212. # GitHub backup admin + firmware OTA.
  213. Permission.GITHUB_BACKUP,
  214. Permission.GITHUB_RESTORE,
  215. Permission.FIRMWARE_UPDATE,
  216. # Resource administration (printer/project/filament/maintenance/k-profile/etc CRUD).
  217. # API keys with the operational scopes can read these resources via
  218. # *_READ permissions but cannot mutate the catalog/registry itself.
  219. Permission.PRINTERS_CREATE,
  220. Permission.PRINTERS_UPDATE,
  221. Permission.PRINTERS_DELETE,
  222. # ARCHIVES_CREATE / _UPDATE_OWN / _UPDATE_ALL / _DELETE_OWN /
  223. # _DELETE_ALL moved to the allowlist under `can_manage_archives`
  224. # (#1888) — split between allow/deny made the whole archive-management
  225. # surface unreachable for API keys via `require_ownership_permission`
  226. # (same regression class as the library/maintenance carve-outs in
  227. # #1832). ARCHIVES_PURGE stays denied as a genuinely destructive op
  228. # that drops the print's stats contribution.
  229. Permission.ARCHIVES_PURGE,
  230. # LIBRARY_UPDATE_ALL / LIBRARY_DELETE_ALL moved to the allowlist
  231. # under `can_manage_library` (#1832) — split between allow/deny made
  232. # the whole library curation surface unreachable for API keys via
  233. # `require_ownership_permission`. Purge stays denied as a genuinely
  234. # destructive op.
  235. Permission.LIBRARY_PURGE,
  236. # PROJECTS_CREATE / _UPDATE / _DELETE moved to the allowlist under
  237. # `can_manage_projects` (#1893) — they were denied for every API key,
  238. # making the project-management surface (create, add-archives, delete)
  239. # unreachable, same regression class as the archives/library carve-outs.
  240. Permission.FILAMENTS_CREATE,
  241. Permission.FILAMENTS_UPDATE,
  242. Permission.FILAMENTS_DELETE,
  243. # MAINTENANCE_CREATE / MAINTENANCE_UPDATE / MAINTENANCE_DELETE moved
  244. # to the allowlist under `can_manage_maintenance` (#1832 follow-up).
  245. Permission.KPROFILES_CREATE,
  246. Permission.KPROFILES_UPDATE,
  247. Permission.KPROFILES_DELETE,
  248. Permission.NOTIFICATIONS_CREATE,
  249. Permission.NOTIFICATIONS_UPDATE,
  250. Permission.NOTIFICATIONS_DELETE,
  251. Permission.NOTIFICATIONS_USER_EMAIL,
  252. Permission.NOTIFICATION_TEMPLATES_UPDATE,
  253. Permission.EXTERNAL_LINKS_CREATE,
  254. Permission.EXTERNAL_LINKS_UPDATE,
  255. Permission.EXTERNAL_LINKS_DELETE,
  256. Permission.SMART_PLUGS_CREATE,
  257. Permission.SMART_PLUGS_UPDATE,
  258. Permission.SMART_PLUGS_DELETE,
  259. # Network scanning — operator only (no API-key scope for this).
  260. Permission.DISCOVERY_SCAN,
  261. # Slicer Pipelines (#1425) — admin authoring + the print-spending Run
  262. # action. PR A only ships CRUD; PR B / PR C may move PIPELINES_RUN onto
  263. # `can_queue` (it queues prints) once the run dispatch lands. PR A keeps
  264. # all three denied so they fail closed for any API-key surface.
  265. Permission.PIPELINES_READ,
  266. Permission.PIPELINES_WRITE,
  267. Permission.PIPELINES_RUN,
  268. }
  269. )
  270. def _resolve_apikey_scope(perm_string: str) -> str | None:
  271. """Return the scope-flag attribute name gating ``perm_string`` for API keys.
  272. None when the permission is unmapped (= admin-only / not API-key-usable).
  273. """
  274. try:
  275. perm = Permission(perm_string)
  276. except ValueError:
  277. return None
  278. return _APIKEY_SCOPE_BY_PERMISSION.get(perm)
  279. def _check_apikey_permissions(api_key: APIKey, perm_strings: list[str], *, require_any: bool = False) -> None:
  280. """Raise 403 unless ``api_key`` is allowed to use ``perm_strings``.
  281. Allowlist semantics: every requested permission MUST be present in
  282. ``_APIKEY_SCOPE_BY_PERMISSION`` AND its scope flag must be True on
  283. ``api_key``. Unmapped permissions = administrative = 403.
  284. By default ALL requested permissions must pass (mirrors
  285. ``require_permission`` / ``require_permission_if_auth_enabled``).
  286. When ``require_any=True``, only one needs to pass (mirrors
  287. ``require_any_permission_if_auth_enabled``).
  288. """
  289. if not perm_strings:
  290. # Defensive: empty perm list means the dep is auth-only, not perm-gated.
  291. # Routes never call us with [] today, but if they did, returning here
  292. # would silently allow — instead, fail closed.
  293. raise HTTPException(
  294. status_code=status.HTTP_403_FORBIDDEN,
  295. detail="API keys cannot be used for unspecified permissions",
  296. )
  297. last_failure: HTTPException | None = None
  298. for perm_str in perm_strings:
  299. scope_attr = _resolve_apikey_scope(perm_str)
  300. if scope_attr is None:
  301. failure = HTTPException(
  302. status_code=status.HTTP_403_FORBIDDEN,
  303. detail="API keys cannot be used for administrative operations",
  304. )
  305. elif not getattr(api_key, scope_attr, False):
  306. failure = HTTPException(
  307. status_code=status.HTTP_403_FORBIDDEN,
  308. detail=f"API key does not have '{scope_attr}' permission",
  309. )
  310. else:
  311. failure = None
  312. if failure is None and require_any:
  313. return # at least one passed
  314. if failure is not None and not require_any:
  315. raise failure
  316. last_failure = failure
  317. if require_any and last_failure is not None:
  318. raise last_failure
  319. def require_energy_cost_update():
  320. """Dependency for ``POST /settings/electricity-price`` (#1356).
  321. Bypasses the ``_APIKEY_DENIED_PERMISSIONS`` ``SETTINGS_UPDATE`` block for
  322. API keys that explicitly opt into ``can_update_energy_cost``. Full
  323. ``SETTINGS_UPDATE`` for API keys stays denied — this is a narrowly-scoped
  324. door for the Home Assistant dynamic-tariff use case documented in
  325. ``wiki/features/energy.md``, not a general settings-write capability.
  326. Accepts:
  327. * Auth disabled → always allowed (matches other settings routes)
  328. * JWT user with ``SETTINGS_UPDATE`` permission
  329. * API key with ``can_update_energy_cost = True``
  330. """
  331. async def permission_checker(
  332. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  333. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  334. ) -> User | None:
  335. async with async_session() as db:
  336. if not await is_auth_enabled(db):
  337. return None
  338. credentials_exception = HTTPException(
  339. status_code=status.HTTP_401_UNAUTHORIZED,
  340. detail="Could not validate credentials",
  341. headers={"WWW-Authenticate": "Bearer"},
  342. )
  343. # API key path — X-API-Key header or Bearer bb_xxx
  344. api_key_value: str | None = None
  345. if x_api_key:
  346. api_key_value = x_api_key
  347. elif credentials is not None and credentials.credentials.startswith("bb_"):
  348. api_key_value = credentials.credentials
  349. if api_key_value is not None:
  350. api_key = await _validate_api_key(db, api_key_value)
  351. if api_key is None:
  352. raise HTTPException(
  353. status_code=status.HTTP_401_UNAUTHORIZED,
  354. detail="Invalid API key",
  355. headers={"WWW-Authenticate": "Bearer"},
  356. )
  357. if not api_key.can_update_energy_cost:
  358. raise HTTPException(
  359. status_code=status.HTTP_403_FORBIDDEN,
  360. detail="API key does not have 'update_energy_cost' permission",
  361. )
  362. return None
  363. # JWT path
  364. if credentials is None:
  365. raise credentials_exception
  366. try:
  367. payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM])
  368. username: str = payload.get("sub")
  369. if username is None:
  370. raise credentials_exception
  371. jti: str | None = payload.get("jti")
  372. if not jti or await is_jti_revoked(jti):
  373. raise credentials_exception
  374. iat: int | float | None = payload.get("iat")
  375. except JWTError:
  376. raise credentials_exception
  377. user = await get_user_by_username(db, username)
  378. if user is None or not user.is_active:
  379. raise credentials_exception
  380. if not _is_token_fresh(iat, user):
  381. raise credentials_exception
  382. if not user.has_all_permissions(Permission.SETTINGS_UPDATE.value):
  383. raise HTTPException(
  384. status_code=status.HTTP_403_FORBIDDEN,
  385. detail=f"Missing required permissions: {Permission.SETTINGS_UPDATE.value}",
  386. )
  387. return user
  388. return permission_checker
  389. # Password hashing
  390. # Use pbkdf2_sha256 instead of bcrypt to avoid 72-byte limit and passlib initialization issues
  391. # pbkdf2_sha256 is a secure password hashing algorithm without bcrypt's limitations
  392. pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto")
  393. def _get_jwt_secret() -> str:
  394. """Get the JWT secret key from environment, file, or generate a new one.
  395. Priority:
  396. 1. JWT_SECRET_KEY environment variable
  397. 2. .jwt_secret file in data directory
  398. 3. Generate new random secret and save to file
  399. Returns:
  400. The JWT secret key
  401. """
  402. # 1. Check environment variable first
  403. env_secret = os.environ.get("JWT_SECRET_KEY")
  404. if env_secret:
  405. logger.info("Using JWT secret from JWT_SECRET_KEY environment variable")
  406. return env_secret
  407. # 2. Check for secret file in data directory
  408. from backend.app.core.paths import resolve_data_dir
  409. data_dir = resolve_data_dir()
  410. secret_file = data_dir / ".jwt_secret"
  411. if secret_file.exists():
  412. try:
  413. secret = secret_file.read_text().strip()
  414. if secret and len(secret) >= 32:
  415. logger.info("Using JWT secret from %s", secret_file)
  416. return secret
  417. except OSError as e:
  418. logger.warning("Failed to read JWT secret file: %s", e)
  419. # 3. Generate new random secret
  420. new_secret = secrets.token_urlsafe(64)
  421. # Try to save it
  422. try:
  423. data_dir.mkdir(parents=True, exist_ok=True)
  424. # Note: CodeQL flags this as "clear-text storage of sensitive information" but this is
  425. # intentional and secure - JWT secrets must be readable by the app, we set 0600 permissions,
  426. # and this is standard practice for self-hosted applications (same as .env files).
  427. secret_file.write_text(new_secret) # nosec B105
  428. # Restrict permissions (owner read/write only)
  429. secret_file.chmod(0o600)
  430. logger.info("Generated new JWT secret and saved to %s", secret_file)
  431. except OSError as e:
  432. logger.warning(
  433. "Could not save JWT secret to file (%s). "
  434. "Secret will be regenerated on restart, invalidating existing tokens. "
  435. "Set JWT_SECRET_KEY environment variable for persistence.",
  436. e,
  437. )
  438. return new_secret
  439. # JWT settings
  440. SECRET_KEY = _get_jwt_secret()
  441. ALGORITHM = "HS256"
  442. ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 # 24 hours (M-2: reduced from 7 days)
  443. # Hard ceiling for the admin-configurable session policy (#1706). 30 days
  444. # matches the Pydantic le=720 on AppSettings.session_max_hours; defense in
  445. # depth so a tampered settings row can't request an absurd lifetime.
  446. SESSION_MAX_HOURS_HARD_CEILING = 720
  447. # HTTP Bearer token
  448. security = HTTPBearer(auto_error=False)
  449. async def resolve_session_max_minutes(db: AsyncSession) -> int:
  450. """Return the session-lifetime ceiling (minutes) honoured by login routes.
  451. Reads ``session_max_hours`` from the settings table (#1706), clamps to
  452. [1h, 720h], and falls back to the audit-default 24h if the row is
  453. missing, blank, or unparseable.
  454. DB errors are NOT caught here — login is already in a DB transaction and
  455. a broken DB must abort the login rather than silently extend or shrink
  456. the session lifetime.
  457. """
  458. default_minutes = ACCESS_TOKEN_EXPIRE_MINUTES
  459. result = await db.execute(select(Settings).where(Settings.key == "session_max_hours"))
  460. row = result.scalar_one_or_none()
  461. if row is None or not row.value:
  462. return default_minutes
  463. try:
  464. hours = int(row.value)
  465. except (TypeError, ValueError):
  466. return default_minutes
  467. if hours < 1:
  468. return default_minutes
  469. if hours > SESSION_MAX_HOURS_HARD_CEILING:
  470. hours = SESSION_MAX_HOURS_HARD_CEILING
  471. return hours * 60
  472. # --- Slicer download tokens ---
  473. # Short-lived, single-use tokens for slicer protocol handlers that can't send
  474. # auth headers. Stored in AuthEphemeralToken (token_type=TokenType.SLICER_DOWNLOAD)
  475. # so they survive server restarts and work in multi-worker deployments (M-3).
  476. SLICER_TOKEN_EXPIRE_MINUTES = 5
  477. async def create_slicer_download_token(resource_type: str, resource_id: int) -> str:
  478. """Create a short-lived, single-use download token for slicer protocol handlers."""
  479. now = datetime.now(timezone.utc)
  480. expires_at = now + timedelta(minutes=SLICER_TOKEN_EXPIRE_MINUTES)
  481. token = secrets.token_urlsafe(24)
  482. resource_key = f"{resource_type}:{resource_id}"
  483. async with async_session() as db:
  484. # Prune expired tokens opportunistically
  485. await db.execute(
  486. delete(AuthEphemeralToken).where(
  487. AuthEphemeralToken.token_type == TokenType.SLICER_DOWNLOAD,
  488. AuthEphemeralToken.expires_at < now,
  489. )
  490. )
  491. db.add(
  492. AuthEphemeralToken(
  493. token=token,
  494. token_type=TokenType.SLICER_DOWNLOAD,
  495. nonce=resource_key,
  496. expires_at=expires_at,
  497. )
  498. )
  499. await db.commit()
  500. return token
  501. async def verify_slicer_download_token(token: str, resource_type: str, resource_id: int) -> bool:
  502. """Verify and atomically consume a slicer download token.
  503. Returns True only if the token is valid, unexpired, and bound to the given resource.
  504. DELETE...RETURNING ensures the token is single-use even under concurrent requests.
  505. M-NEW-1 fix: nonce (resource key) is included in the WHERE clause so the DELETE
  506. only succeeds when the token is presented to the *correct* resource endpoint.
  507. Previously the token was consumed (committed) even when stored_key != expected_key,
  508. permanently invalidating it while returning False to the caller.
  509. """
  510. expected_key = f"{resource_type}:{resource_id}"
  511. now = datetime.now(timezone.utc)
  512. async with async_session() as db:
  513. result = await db.execute(
  514. delete(AuthEphemeralToken)
  515. .where(
  516. AuthEphemeralToken.token == token,
  517. AuthEphemeralToken.token_type == TokenType.SLICER_DOWNLOAD,
  518. AuthEphemeralToken.nonce == expected_key,
  519. AuthEphemeralToken.expires_at > now,
  520. )
  521. .returning(AuthEphemeralToken.id)
  522. )
  523. if result.one_or_none() is None:
  524. return False
  525. await db.commit()
  526. return True
  527. # --- Camera stream tokens ---
  528. # Reusable tokens for camera stream/snapshot endpoints loaded via <img>/<video>
  529. # tags (these cannot send Authorization headers). Unlike slicer tokens they are
  530. # NOT single-use — streams reconnect on errors. Stored in AuthEphemeralToken
  531. # (token_type="camera_stream") for multi-worker compatibility (M-3).
  532. CAMERA_STREAM_TOKEN_EXPIRE_MINUTES = 60
  533. async def create_camera_stream_token() -> str:
  534. """Create a reusable token for camera stream/snapshot access."""
  535. now = datetime.now(timezone.utc)
  536. expires_at = now + timedelta(minutes=CAMERA_STREAM_TOKEN_EXPIRE_MINUTES)
  537. token = secrets.token_urlsafe(24)
  538. async with async_session() as db:
  539. # Prune expired tokens opportunistically
  540. await db.execute(
  541. delete(AuthEphemeralToken).where(
  542. AuthEphemeralToken.token_type == "camera_stream",
  543. AuthEphemeralToken.expires_at < now,
  544. )
  545. )
  546. db.add(
  547. AuthEphemeralToken(
  548. token=token,
  549. token_type="camera_stream",
  550. expires_at=expires_at,
  551. )
  552. )
  553. await db.commit()
  554. return token
  555. WEBSOCKET_TOKEN_EXPIRE_MINUTES = 60
  556. async def create_websocket_token(username: str | None) -> str:
  557. """Create a short-lived token for ``/api/v1/ws`` connections.
  558. Mirrors the camera-stream-token pattern: opaque random string stored
  559. in ``auth_ephemeral_tokens`` with type ``"websocket"`` so the WS
  560. endpoint can verify it *before* calling ``websocket.accept()``.
  561. Records the issuing principal in the ``username`` field — for JWT
  562. callers this is the actual username, for API-keyed callers this is
  563. the empty string (handled in the route layer; we accept None at this
  564. interface so the auth-disabled path doesn't have to fabricate one).
  565. The 60-minute expiry matches camera tokens: long enough to survive
  566. page reloads / brief disconnects, short enough that a leaked token
  567. is not a credential.
  568. """
  569. now = datetime.now(timezone.utc)
  570. expires_at = now + timedelta(minutes=WEBSOCKET_TOKEN_EXPIRE_MINUTES)
  571. token = secrets.token_urlsafe(24)
  572. async with async_session() as db:
  573. # Prune expired tokens opportunistically (same shape as camera).
  574. await db.execute(
  575. delete(AuthEphemeralToken).where(
  576. AuthEphemeralToken.token_type == "websocket",
  577. AuthEphemeralToken.expires_at < now,
  578. )
  579. )
  580. db.add(
  581. AuthEphemeralToken(
  582. token=token,
  583. token_type="websocket",
  584. username=username or "",
  585. expires_at=expires_at,
  586. )
  587. )
  588. await db.commit()
  589. return token
  590. async def verify_websocket_token(token: str) -> str | None:
  591. """Verify a WebSocket connect token.
  592. Returns the recorded ``username`` (possibly ``""`` for API-key
  593. callers, never ``None`` on success) when the token is valid, or
  594. ``None`` when it is missing / expired / unknown. The token is
  595. NOT consumed — a single page reload should not need a new round
  596. trip to mint a replacement.
  597. """
  598. now = datetime.now(timezone.utc)
  599. async with async_session() as db:
  600. result = await db.execute(
  601. select(AuthEphemeralToken).where(
  602. AuthEphemeralToken.token == token,
  603. AuthEphemeralToken.token_type == "websocket",
  604. AuthEphemeralToken.expires_at > now,
  605. )
  606. )
  607. row = result.scalar_one_or_none()
  608. if row is None:
  609. return None
  610. return row.username or ""
  611. async def verify_camera_stream_token(token: str) -> bool:
  612. """Verify a camera stream token is valid (reusable — does not consume it).
  613. Tries the ephemeral 60-minute token first (the common, browser-bound case)
  614. and falls through to long-lived tokens (#1108) for HA / kiosk integrations
  615. that paste a token once and expect it to keep working for days.
  616. """
  617. now = datetime.now(timezone.utc)
  618. async with async_session() as db:
  619. result = await db.execute(
  620. select(AuthEphemeralToken).where(
  621. AuthEphemeralToken.token == token,
  622. AuthEphemeralToken.token_type == "camera_stream",
  623. AuthEphemeralToken.expires_at > now,
  624. )
  625. )
  626. if result.scalar_one_or_none() is not None:
  627. return True
  628. # Long-lived path. Imported lazily so the auth module stays importable
  629. # at startup before the long_lived_tokens model is registered.
  630. from backend.app.services.long_lived_tokens import verify_token as verify_long_lived
  631. record = await verify_long_lived(db, token, scope="camera_stream")
  632. return record is not None
  633. def verify_password(plain_password: str, hashed_password: str) -> bool:
  634. """Verify a password against a hash.
  635. Uses pbkdf2_sha256 which handles long passwords automatically.
  636. """
  637. return pwd_context.verify(plain_password, hashed_password)
  638. def get_password_hash(password: str) -> str:
  639. """Hash a password.
  640. Uses pbkdf2_sha256 which is secure and has no password length limit.
  641. """
  642. return pwd_context.hash(password)
  643. def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
  644. """Create a JWT access token with jti (revocation) and iat (freshness) claims."""
  645. to_encode = data.copy()
  646. now = datetime.now(timezone.utc)
  647. if expires_delta:
  648. expire = now + expires_delta
  649. else:
  650. expire = now + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  651. jti = secrets.token_hex(16)
  652. to_encode.update({"exp": expire, "jti": jti, "iat": now})
  653. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  654. return encoded_jwt
  655. def _is_token_fresh(iat: int | float | None, user: User) -> bool:
  656. """Return False if the token was issued before the user's last password change.
  657. Used to invalidate all sessions after a password reset/change (M-R7-B).
  658. All tokens without an iat claim are unconditionally rejected — every token
  659. issued by this server carries iat, so absence means the token is forged or
  660. from a pre-iat code path whose max TTL at the time (24 h) has long since
  661. expired. The post-#1706 admin-set ceiling does not relax this — an iat-less
  662. token still cannot have been issued by current code.
  663. """
  664. if iat is None:
  665. return False
  666. if not hasattr(user, "password_changed_at") or user.password_changed_at is None:
  667. return True # No password change recorded yet (I2 migration handles this)
  668. token_issued_at = datetime.fromtimestamp(iat, tz=timezone.utc)
  669. pca = user.password_changed_at
  670. if pca.tzinfo is None:
  671. pca = pca.replace(tzinfo=timezone.utc)
  672. # JWT iat is whole seconds; truncate pca so tokens issued in the same second pass.
  673. pca = pca.replace(microsecond=0)
  674. return token_issued_at >= pca
  675. async def revoke_jti(jti: str, expires_at: datetime, username: str | None = None) -> None:
  676. """Store a revoked JWT jti so it is rejected on future requests.
  677. Silently ignores duplicate inserts (e.g. double-logout with the same token).
  678. """
  679. from sqlalchemy.exc import IntegrityError
  680. async with async_session() as db:
  681. revoked = AuthEphemeralToken(
  682. token=jti,
  683. token_type="revoked_jti",
  684. username=username,
  685. expires_at=expires_at,
  686. )
  687. db.add(revoked)
  688. try:
  689. await db.commit()
  690. except IntegrityError:
  691. await db.rollback() # jti already revoked — desired state, ignore
  692. async def is_jti_revoked(jti: str) -> bool:
  693. """Return True if the given jti has been revoked."""
  694. async with async_session() as db:
  695. result = await db.execute(
  696. select(AuthEphemeralToken).where(
  697. AuthEphemeralToken.token == jti,
  698. AuthEphemeralToken.token_type == "revoked_jti",
  699. )
  700. )
  701. return result.scalar_one_or_none() is not None
  702. async def get_user_by_username(db: AsyncSession, username: str) -> User | None:
  703. """Get a user by username (case-insensitive) with groups loaded for permission checks."""
  704. result = await db.execute(
  705. select(User).where(func.lower(User.username) == func.lower(username)).options(selectinload(User.groups))
  706. )
  707. return result.scalar_one_or_none()
  708. async def get_user_by_email(db: AsyncSession, email: str) -> User | None:
  709. """Get a user by email (case-insensitive) with groups loaded for permission checks."""
  710. result = await db.execute(
  711. select(User).where(func.lower(User.email) == func.lower(email)).options(selectinload(User.groups))
  712. )
  713. return result.scalar_one_or_none()
  714. async def authenticate_user(db: AsyncSession, username: str, password: str) -> User | None:
  715. """Authenticate a user by username and password.
  716. Username lookup is case-insensitive. Password is case-sensitive.
  717. LDAP and OIDC users must authenticate via their respective providers.
  718. """
  719. user = await get_user_by_username(db, username)
  720. if not user:
  721. return None
  722. if getattr(user, "auth_source", "local") in ("ldap", "oidc"):
  723. return None # LDAP/OIDC users must authenticate via their provider
  724. if not user.password_hash or not verify_password(password, user.password_hash):
  725. return None
  726. if not user.is_active:
  727. return None
  728. return user
  729. async def authenticate_user_by_email(db: AsyncSession, email: str, password: str) -> User | None:
  730. """Authenticate a user by email and password.
  731. Email lookup is case-insensitive. Password is case-sensitive.
  732. LDAP and OIDC users must authenticate via their respective providers.
  733. """
  734. user = await get_user_by_email(db, email)
  735. if not user:
  736. return None
  737. if getattr(user, "auth_source", "local") in ("ldap", "oidc"):
  738. return None # LDAP/OIDC users must authenticate via their provider
  739. if not user.password_hash or not verify_password(password, user.password_hash):
  740. return None
  741. if not user.is_active:
  742. return None
  743. return user
  744. async def is_auth_enabled(db: AsyncSession) -> bool:
  745. """Check if authentication is enabled.
  746. Fails CLOSED on database errors. A previous version of this function
  747. caught every exception and returned False — silently treating an
  748. unavailable database as "auth is disabled" and granting unauthenticated
  749. access to every endpoint that called it (GHSA-6mf4-q26m-47pv, CVSS 9.8).
  750. An attacker could trigger that fail-open by flooding /api/v1/auth/login
  751. to exhaust the process's file-descriptor budget, then hit a protected
  752. endpoint during the window where the next DB op raised.
  753. Legitimate "auth was never configured" still returns False — the
  754. settings row is simply absent, ``scalar_one_or_none`` returns None,
  755. no exception. Any OTHER failure (connection error, fd exhaustion,
  756. schema mismatch, …) propagates so the caller can deny the request
  757. (503 / 500). Fail-closed is the only safe default for an auth probe.
  758. """
  759. result = await db.execute(select(Settings).where(Settings.key == "auth_enabled"))
  760. setting = result.scalar_one_or_none()
  761. if setting is None:
  762. return False
  763. return setting.value.lower() == "true"
  764. async def _user_from_api_key(db: AsyncSession, api_key: APIKey) -> User | None:
  765. """Resolve the owner of a validated API key, or None for legacy ownerless keys.
  766. Cloud routes (and any route that needs caller identity) read the returned
  767. User to look up per-user state like ``cloud_token``. Legacy keys created
  768. before #1182 have ``user_id IS NULL`` and stay anonymous — they keep working
  769. against non-cloud routes for backward compatibility, but cloud routes will
  770. surface a "recreate this key" error rather than 200 with empty results.
  771. """
  772. if api_key.user_id is None:
  773. return None
  774. result = await db.execute(select(User).where(User.id == api_key.user_id))
  775. user = result.scalar_one_or_none()
  776. if user is None or not user.is_active:
  777. # CASCADE on user delete should prevent a dangling user_id, but if
  778. # someone manually deactivates the owner the key shouldn't suddenly
  779. # gain an "anonymous" identity — drop the request to None so cloud
  780. # access fails closed.
  781. return None
  782. return user
  783. async def _validate_api_key(db: AsyncSession, api_key_value: str) -> APIKey | None:
  784. """Validate an API key and return the APIKey object if valid, None otherwise.
  785. L-1: Pre-filter by key_prefix (first 8 chars) before running pbkdf2 so only
  786. O(1) candidate rows are hashed instead of the full key table. The prefix is
  787. not secret (it is shown in the admin UI), so this does not reduce security.
  788. """
  789. try:
  790. # key_prefix is stored as "<first-8-chars>..." (e.g. "bb_Abc12...").
  791. # Matching on the first 8 chars of the submitted key reduces the scan to
  792. # at most one row in practice (2^40 collision space for 5 base64 chars).
  793. key_lookup = api_key_value[:8] if len(api_key_value) >= 8 else api_key_value
  794. result = await db.execute(
  795. select(APIKey).where(
  796. APIKey.enabled.is_(True),
  797. APIKey.key_prefix.like(
  798. key_lookup.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%", escape="\\"
  799. ),
  800. )
  801. )
  802. api_keys = result.scalars().all()
  803. for api_key in api_keys:
  804. if verify_password(api_key_value, api_key.key_hash):
  805. # Check expiration
  806. if api_key.expires_at:
  807. expires = api_key.expires_at
  808. if expires.tzinfo is None:
  809. expires = expires.replace(tzinfo=timezone.utc)
  810. if expires < datetime.now(timezone.utc):
  811. return None # Expired
  812. # Update last_used timestamp
  813. api_key.last_used = datetime.now(timezone.utc)
  814. await db.commit()
  815. return api_key
  816. except Exception as e: # SEC-AUTH-EXC: validation failure returns None; every caller treats None as "invalid key" → 401 (fail-closed)
  817. logger.warning("API key validation error: %s", e)
  818. return None
  819. async def get_current_user_optional(
  820. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  821. ) -> User | None:
  822. """Get the current authenticated user from JWT token, or None if not authenticated.
  823. Returns None only when NO credentials are supplied. If a token is supplied
  824. but invalid/revoked, raises 401 — a revoked token must not grant anonymous
  825. access (I6).
  826. """
  827. if credentials is None:
  828. return None
  829. _unauthorized = HTTPException(
  830. status_code=status.HTTP_401_UNAUTHORIZED,
  831. detail="Could not validate credentials",
  832. headers={"WWW-Authenticate": "Bearer"},
  833. )
  834. try:
  835. token = credentials.credentials
  836. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  837. username: str = payload.get("sub")
  838. if username is None:
  839. raise _unauthorized
  840. jti: str | None = payload.get("jti")
  841. if not jti or await is_jti_revoked(jti):
  842. raise _unauthorized # I6: revoked token → 401, not anonymous
  843. iat: int | float | None = payload.get("iat")
  844. except JWTError:
  845. raise _unauthorized
  846. async with async_session() as db:
  847. user = await get_user_by_username(db, username)
  848. if user is None or not user.is_active:
  849. raise _unauthorized
  850. if not _is_token_fresh(iat, user):
  851. raise _unauthorized
  852. return user
  853. async def get_current_user(
  854. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  855. ) -> User:
  856. """Get the current authenticated user from JWT token."""
  857. credentials_exception = HTTPException(
  858. status_code=status.HTTP_401_UNAUTHORIZED,
  859. detail="Could not validate credentials",
  860. headers={"WWW-Authenticate": "Bearer"},
  861. )
  862. if credentials is None:
  863. raise credentials_exception
  864. try:
  865. token = credentials.credentials
  866. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  867. username: str = payload.get("sub")
  868. if username is None:
  869. raise credentials_exception
  870. jti: str | None = payload.get("jti")
  871. if not jti or await is_jti_revoked(jti):
  872. raise credentials_exception
  873. iat: int | float | None = payload.get("iat")
  874. except JWTError:
  875. raise credentials_exception
  876. async with async_session() as db:
  877. user = await get_user_by_username(db, username)
  878. if user is None:
  879. raise credentials_exception
  880. if not user.is_active:
  881. raise HTTPException(
  882. status_code=status.HTTP_403_FORBIDDEN,
  883. detail="User account is disabled",
  884. )
  885. if not _is_token_fresh(iat, user):
  886. raise credentials_exception
  887. return user
  888. async def get_current_active_user(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  889. """Get the current active user (alias for clarity)."""
  890. return current_user
  891. async def require_auth_if_enabled(
  892. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  893. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  894. ) -> User | None:
  895. """Require authentication if auth is enabled, otherwise return None.
  896. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  897. (via X-API-Key header or Authorization: Bearer bb_xxx). API keys return
  898. None for backward compatibility — routes that need the API-key owner (i.e.
  899. cloud routes for #1182) resolve it via their own router-level dependency
  900. that stashes ``request.state.api_key_owner``. Returning the owner here
  901. instead would silently grant API-keyed callers access to every route that
  902. fences via ``if current_user is None``, which is a wider surface than
  903. #1182 was designed to expose.
  904. """
  905. async with async_session() as db:
  906. auth_enabled = await is_auth_enabled(db)
  907. if not auth_enabled:
  908. return None
  909. # Check for API key first (X-API-Key header)
  910. if x_api_key:
  911. api_key = await _validate_api_key(db, x_api_key)
  912. if api_key:
  913. return None # API key valid, allow access
  914. # Check for Bearer token (could be JWT or API key)
  915. if credentials is not None:
  916. token = credentials.credentials
  917. # Check if it's an API key (starts with bb_)
  918. if token.startswith("bb_"):
  919. api_key = await _validate_api_key(db, token)
  920. if api_key:
  921. return None # API key valid, allow access
  922. raise HTTPException(
  923. status_code=status.HTTP_401_UNAUTHORIZED,
  924. detail="Invalid API key",
  925. headers={"WWW-Authenticate": "Bearer"},
  926. )
  927. # Otherwise treat as JWT
  928. try:
  929. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  930. username: str = payload.get("sub")
  931. if username is None:
  932. raise HTTPException(
  933. status_code=status.HTTP_401_UNAUTHORIZED,
  934. detail="Could not validate credentials",
  935. headers={"WWW-Authenticate": "Bearer"},
  936. )
  937. jti: str | None = payload.get("jti")
  938. if not jti or await is_jti_revoked(jti):
  939. raise HTTPException(
  940. status_code=status.HTTP_401_UNAUTHORIZED,
  941. detail="Could not validate credentials",
  942. headers={"WWW-Authenticate": "Bearer"},
  943. )
  944. iat: int | float | None = payload.get("iat")
  945. except JWTError:
  946. raise HTTPException(
  947. status_code=status.HTTP_401_UNAUTHORIZED,
  948. detail="Could not validate credentials",
  949. headers={"WWW-Authenticate": "Bearer"},
  950. )
  951. user = await get_user_by_username(db, username)
  952. if user is None or not user.is_active:
  953. raise HTTPException(
  954. status_code=status.HTTP_401_UNAUTHORIZED,
  955. detail="Could not validate credentials",
  956. headers={"WWW-Authenticate": "Bearer"},
  957. )
  958. if not _is_token_fresh(iat, user):
  959. raise HTTPException(
  960. status_code=status.HTTP_401_UNAUTHORIZED,
  961. detail="Could not validate credentials",
  962. headers={"WWW-Authenticate": "Bearer"},
  963. )
  964. return user
  965. # No credentials provided
  966. raise HTTPException(
  967. status_code=status.HTTP_401_UNAUTHORIZED,
  968. detail="Authentication required",
  969. headers={"WWW-Authenticate": "Bearer"},
  970. )
  971. def require_role(required_role: str):
  972. """Dependency factory for role-based access control."""
  973. async def role_checker(current_user: Annotated[User, Depends(get_current_user)]) -> User:
  974. if current_user.role != required_role:
  975. raise HTTPException(
  976. status_code=status.HTTP_403_FORBIDDEN,
  977. detail=f"Requires {required_role} role",
  978. )
  979. return current_user
  980. return role_checker
  981. def require_admin_if_auth_enabled():
  982. """Dependency factory that requires admin role if auth is enabled.
  983. GHSA-r2qv follow-up (audit pattern P3): explicitly fail-closed for API
  984. keys. The previous implementation chained on ``require_auth_if_enabled``
  985. which returns ``None`` for *both* "auth disabled" *and* "valid API
  986. key" — the inner ``admin_checker`` then treated ``None`` as auth-
  987. disabled and admitted the caller. If any route had ever adopted this
  988. dep, any API key with no scope flags set would have satisfied an
  989. admin requirement. The dep distinguishes the two cases by consulting
  990. ``is_auth_enabled`` directly and rejecting API-keyed requests with
  991. 403. "Admin" requires a user-identity role, which API keys do not
  992. carry.
  993. Admin semantics: uses ``User.is_admin`` (``role == "admin"`` OR
  994. Administrators-group membership) so a default-install operator who
  995. was made admin by being added to Administrators rather than by
  996. flipping the legacy role column passes. Earlier this check looked
  997. only at ``role`` and would have locked group-only admins out of the
  998. user-management routes once those routes started requiring it.
  999. """
  1000. async def admin_checker(
  1001. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1002. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1003. ) -> User | None:
  1004. async with async_session() as db:
  1005. if not await is_auth_enabled(db):
  1006. return None # Auth disabled — no role to check.
  1007. # Reject API-keyed requests up front: admin is a user-role
  1008. # concept, not a key-scope concept. The right path for
  1009. # admin-equivalent API-key access is a specific Permission
  1010. # (e.g. SETTINGS_UPDATE) gated by the allowlist, not the
  1011. # admin role.
  1012. if x_api_key or (credentials and credentials.credentials.startswith("bb_")):
  1013. raise HTTPException(
  1014. status_code=status.HTTP_403_FORBIDDEN,
  1015. detail="Admin operations require a user role; API keys cannot be admins",
  1016. )
  1017. # Standard JWT path: validate and require admin role.
  1018. if credentials is None:
  1019. raise HTTPException(
  1020. status_code=status.HTTP_401_UNAUTHORIZED,
  1021. detail="Authentication required",
  1022. headers={"WWW-Authenticate": "Bearer"},
  1023. )
  1024. try:
  1025. payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM])
  1026. username: str = payload.get("sub")
  1027. if username is None:
  1028. raise HTTPException(
  1029. status_code=status.HTTP_401_UNAUTHORIZED,
  1030. detail="Could not validate credentials",
  1031. headers={"WWW-Authenticate": "Bearer"},
  1032. )
  1033. jti: str | None = payload.get("jti")
  1034. if not jti or await is_jti_revoked(jti):
  1035. raise HTTPException(
  1036. status_code=status.HTTP_401_UNAUTHORIZED,
  1037. detail="Could not validate credentials",
  1038. headers={"WWW-Authenticate": "Bearer"},
  1039. )
  1040. iat: int | float | None = payload.get("iat")
  1041. except JWTError:
  1042. raise HTTPException(
  1043. status_code=status.HTTP_401_UNAUTHORIZED,
  1044. detail="Could not validate credentials",
  1045. headers={"WWW-Authenticate": "Bearer"},
  1046. )
  1047. user = await get_user_by_username(db, username)
  1048. if user is None or not user.is_active:
  1049. raise HTTPException(
  1050. status_code=status.HTTP_401_UNAUTHORIZED,
  1051. detail="Could not validate credentials",
  1052. headers={"WWW-Authenticate": "Bearer"},
  1053. )
  1054. if not _is_token_fresh(iat, user):
  1055. raise HTTPException(
  1056. status_code=status.HTTP_401_UNAUTHORIZED,
  1057. detail="Could not validate credentials",
  1058. headers={"WWW-Authenticate": "Bearer"},
  1059. )
  1060. if not user.is_admin:
  1061. raise HTTPException(
  1062. status_code=status.HTTP_403_FORBIDDEN,
  1063. detail="Requires admin role",
  1064. )
  1065. return user
  1066. return admin_checker
  1067. def generate_api_key() -> tuple[str, str, str]:
  1068. """Generate a new API key.
  1069. Returns:
  1070. tuple: (full_key, key_hash, key_prefix)
  1071. - full_key: The complete API key (only shown once on creation)
  1072. - key_hash: Hashed version for storage and verification
  1073. - key_prefix: First 8 characters for display purposes
  1074. """
  1075. # Generate a secure random API key (32 bytes = 64 hex characters)
  1076. full_key = f"bb_{secrets.token_urlsafe(32)}"
  1077. key_hash = get_password_hash(full_key)
  1078. key_prefix = full_key[:8] + "..." if len(full_key) > 8 else full_key
  1079. return full_key, key_hash, key_prefix
  1080. async def get_api_key(
  1081. authorization: Annotated[str | None, Header(alias="Authorization")] = None,
  1082. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1083. db: AsyncSession = Depends(get_db),
  1084. ) -> APIKey:
  1085. """Get and validate API key from request headers.
  1086. Checks both 'Authorization: Bearer <key>' and 'X-API-Key: <key>' headers.
  1087. """
  1088. api_key_value = None
  1089. if x_api_key:
  1090. api_key_value = x_api_key
  1091. elif authorization and authorization.startswith("Bearer "):
  1092. api_key_value = authorization.replace("Bearer ", "")
  1093. if not api_key_value:
  1094. raise HTTPException(
  1095. status_code=status.HTTP_401_UNAUTHORIZED,
  1096. detail="API key required. Provide 'X-API-Key' header or 'Authorization: Bearer <key>'",
  1097. )
  1098. # Pre-filter by key_prefix to avoid O(n) pbkdf2 hashes across all enabled keys.
  1099. key_lookup = api_key_value[:8] if len(api_key_value) >= 8 else api_key_value
  1100. result = await db.execute(
  1101. select(APIKey).where(
  1102. APIKey.enabled.is_(True),
  1103. APIKey.key_prefix.like(
  1104. key_lookup.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%",
  1105. escape="\\",
  1106. ),
  1107. )
  1108. )
  1109. api_keys = result.scalars().all()
  1110. for api_key in api_keys:
  1111. # Check if key matches (verify against hash)
  1112. if verify_password(api_key_value, api_key.key_hash):
  1113. # Check expiration
  1114. if api_key.expires_at:
  1115. expires = api_key.expires_at
  1116. if expires.tzinfo is None:
  1117. expires = expires.replace(tzinfo=timezone.utc)
  1118. if expires < datetime.now(timezone.utc):
  1119. raise HTTPException(
  1120. status_code=status.HTTP_401_UNAUTHORIZED,
  1121. detail="API key has expired",
  1122. )
  1123. # Update last_used timestamp
  1124. api_key.last_used = datetime.now(timezone.utc)
  1125. await db.commit()
  1126. return api_key
  1127. raise HTTPException(
  1128. status_code=status.HTTP_401_UNAUTHORIZED,
  1129. detail="Invalid API key",
  1130. )
  1131. async def caller_is_api_key(
  1132. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1133. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1134. ) -> bool:
  1135. """Return True when the request is authenticated via API key (X-API-Key or Bearer bb_xxx)."""
  1136. if x_api_key:
  1137. return True
  1138. return credentials is not None and credentials.credentials.startswith("bb_")
  1139. def check_permission(api_key: APIKey, permission: str) -> None:
  1140. """Check if API key has the required permission.
  1141. Args:
  1142. api_key: The API key object
  1143. permission: One of 'queue', 'control_printer', 'read_status'
  1144. Raises:
  1145. HTTPException: If permission is not granted
  1146. """
  1147. permission_map = {
  1148. "queue": "can_queue",
  1149. "control_printer": "can_control_printer",
  1150. "read_status": "can_read_status",
  1151. }
  1152. if permission not in permission_map:
  1153. raise HTTPException(
  1154. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  1155. detail=f"Unknown permission: {permission}",
  1156. )
  1157. attr_name = permission_map[permission]
  1158. if not getattr(api_key, attr_name, False):
  1159. raise HTTPException(
  1160. status_code=status.HTTP_403_FORBIDDEN,
  1161. detail=f"API key does not have '{permission}' permission",
  1162. )
  1163. def check_printer_access(api_key: APIKey, printer_id: int) -> None:
  1164. """Check if API key has access to the specified printer.
  1165. Args:
  1166. api_key: The API key object
  1167. printer_id: The printer ID to check access for
  1168. Raises:
  1169. HTTPException: If access is denied
  1170. """
  1171. # None = global key, access to all printers
  1172. if api_key.printer_ids is None:
  1173. return
  1174. # Empty list or printer not in allowed list = no access
  1175. if printer_id not in api_key.printer_ids:
  1176. raise HTTPException(
  1177. status_code=status.HTTP_403_FORBIDDEN,
  1178. detail=f"API key does not have access to printer {printer_id}",
  1179. )
  1180. # Convenience dependencies - these are functions that return Depends objects
  1181. def RequireAdmin():
  1182. """Dependency that requires admin role."""
  1183. return Depends(require_role("admin"))
  1184. def RequireAdminIfAuthEnabled():
  1185. """Dependency that requires admin role if auth is enabled."""
  1186. return Depends(require_admin_if_auth_enabled())
  1187. def require_permission(*permissions: str | Permission):
  1188. """Dependency factory that requires user to have ALL specified permissions.
  1189. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  1190. (via X-API-Key header or Authorization: Bearer bb_xxx).
  1191. Args:
  1192. *permissions: Permission strings or Permission enum values to require
  1193. Returns:
  1194. A dependency function that validates permissions
  1195. """
  1196. # Convert Permission enums to strings
  1197. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  1198. async def permission_checker(
  1199. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1200. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1201. ) -> User | None:
  1202. async with async_session() as db:
  1203. # Check for API key first (X-API-Key header)
  1204. if x_api_key:
  1205. api_key = await _validate_api_key(db, x_api_key)
  1206. if api_key:
  1207. _check_apikey_permissions(api_key, perm_strings)
  1208. return None # API key valid, allow access
  1209. credentials_exception = HTTPException(
  1210. status_code=status.HTTP_401_UNAUTHORIZED,
  1211. detail="Could not validate credentials",
  1212. headers={"WWW-Authenticate": "Bearer"},
  1213. )
  1214. if credentials is None:
  1215. raise credentials_exception
  1216. token = credentials.credentials
  1217. # Check if it's an API key (starts with bb_)
  1218. if token.startswith("bb_"):
  1219. api_key = await _validate_api_key(db, token)
  1220. if api_key:
  1221. _check_apikey_permissions(api_key, perm_strings)
  1222. return None # API key valid, allow access
  1223. raise HTTPException(
  1224. status_code=status.HTTP_401_UNAUTHORIZED,
  1225. detail="Invalid API key",
  1226. headers={"WWW-Authenticate": "Bearer"},
  1227. )
  1228. # Otherwise treat as JWT
  1229. try:
  1230. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  1231. username: str = payload.get("sub")
  1232. if username is None:
  1233. raise credentials_exception
  1234. jti: str | None = payload.get("jti")
  1235. if not jti or await is_jti_revoked(jti):
  1236. raise credentials_exception
  1237. iat: int | float | None = payload.get("iat")
  1238. except JWTError:
  1239. raise credentials_exception
  1240. user = await get_user_by_username(db, username)
  1241. if user is None or not user.is_active:
  1242. raise credentials_exception
  1243. if not _is_token_fresh(iat, user):
  1244. raise credentials_exception
  1245. if not user.has_all_permissions(*perm_strings):
  1246. raise HTTPException(
  1247. status_code=status.HTTP_403_FORBIDDEN,
  1248. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  1249. )
  1250. return user
  1251. return permission_checker
  1252. def require_permission_if_auth_enabled(*permissions: str | Permission):
  1253. """Dependency factory that checks permissions only if auth is enabled.
  1254. This provides backward compatibility - when auth is disabled, all access is allowed.
  1255. Accepts both JWT tokens (via Authorization: Bearer header) and API keys
  1256. (via X-API-Key header or Authorization: Bearer bb_xxx).
  1257. Args:
  1258. *permissions: Permission strings or Permission enum values to require
  1259. Returns:
  1260. A dependency function that validates permissions if auth is enabled
  1261. """
  1262. # Convert Permission enums to strings
  1263. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  1264. async def permission_checker(
  1265. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1266. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1267. ) -> User | None:
  1268. async with async_session() as db:
  1269. auth_enabled = await is_auth_enabled(db)
  1270. if not auth_enabled:
  1271. return None # Auth disabled, allow access
  1272. # Check for API key first (X-API-Key header). API-keyed requests
  1273. # bypass the JWT permission check entirely — their scopes live on
  1274. # the APIKey row (can_queue / can_control_printer / can_read_status
  1275. # / can_access_cloud / printer_ids), and the dep returns None so
  1276. # routes don't gain a synthetic User identity that would grant
  1277. # access to fenced surfaces like long-lived-token management.
  1278. # Cloud routes (#1182) resolve the API-key owner separately via
  1279. # their own router-level dependency; see ``cloud.py``.
  1280. if x_api_key:
  1281. api_key = await _validate_api_key(db, x_api_key)
  1282. if api_key:
  1283. _check_apikey_permissions(api_key, perm_strings)
  1284. return None # API key valid, allow access
  1285. # Check for Bearer token (could be JWT or API key)
  1286. if credentials is not None:
  1287. token = credentials.credentials
  1288. # Check if it's an API key (starts with bb_)
  1289. if token.startswith("bb_"):
  1290. api_key = await _validate_api_key(db, token)
  1291. if api_key:
  1292. _check_apikey_permissions(api_key, perm_strings)
  1293. return None # API key valid, allow access
  1294. raise HTTPException(
  1295. status_code=status.HTTP_401_UNAUTHORIZED,
  1296. detail="Invalid API key",
  1297. headers={"WWW-Authenticate": "Bearer"},
  1298. )
  1299. # Otherwise treat as JWT
  1300. try:
  1301. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  1302. username: str = payload.get("sub")
  1303. if username is None:
  1304. raise HTTPException(
  1305. status_code=status.HTTP_401_UNAUTHORIZED,
  1306. detail="Could not validate credentials",
  1307. headers={"WWW-Authenticate": "Bearer"},
  1308. )
  1309. jti: str | None = payload.get("jti")
  1310. if not jti or await is_jti_revoked(jti):
  1311. raise HTTPException(
  1312. status_code=status.HTTP_401_UNAUTHORIZED,
  1313. detail="Could not validate credentials",
  1314. headers={"WWW-Authenticate": "Bearer"},
  1315. )
  1316. iat: int | float | None = payload.get("iat")
  1317. except JWTError:
  1318. raise HTTPException(
  1319. status_code=status.HTTP_401_UNAUTHORIZED,
  1320. detail="Could not validate credentials",
  1321. headers={"WWW-Authenticate": "Bearer"},
  1322. )
  1323. user = await get_user_by_username(db, username)
  1324. if user is None or not user.is_active:
  1325. raise HTTPException(
  1326. status_code=status.HTTP_401_UNAUTHORIZED,
  1327. detail="Could not validate credentials",
  1328. headers={"WWW-Authenticate": "Bearer"},
  1329. )
  1330. if not _is_token_fresh(iat, user):
  1331. raise HTTPException(
  1332. status_code=status.HTTP_401_UNAUTHORIZED,
  1333. detail="Could not validate credentials",
  1334. headers={"WWW-Authenticate": "Bearer"},
  1335. )
  1336. if not user.has_all_permissions(*perm_strings):
  1337. raise HTTPException(
  1338. status_code=status.HTTP_403_FORBIDDEN,
  1339. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  1340. )
  1341. return user
  1342. # No credentials provided
  1343. raise HTTPException(
  1344. status_code=status.HTTP_401_UNAUTHORIZED,
  1345. detail="Authentication required",
  1346. headers={"WWW-Authenticate": "Bearer"},
  1347. )
  1348. return permission_checker
  1349. def RequirePermission(*permissions: str | Permission):
  1350. """Convenience dependency that requires ALL specified permissions."""
  1351. return Depends(require_permission(*permissions))
  1352. def RequirePermissionIfAuthEnabled(*permissions: str | Permission):
  1353. """Convenience dependency that requires permissions if auth is enabled."""
  1354. return Depends(require_permission_if_auth_enabled(*permissions))
  1355. def require_any_permission_if_auth_enabled(*permissions: str | Permission):
  1356. """Dependency factory that requires AT LEAST ONE of the given permissions when auth is enabled."""
  1357. perm_strings = [p.value if isinstance(p, Permission) else p for p in permissions]
  1358. async def checker(
  1359. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1360. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1361. ) -> User | None:
  1362. async with async_session() as db:
  1363. auth_enabled = await is_auth_enabled(db)
  1364. if not auth_enabled:
  1365. return None
  1366. if x_api_key:
  1367. api_key = await _validate_api_key(db, x_api_key)
  1368. if api_key:
  1369. # GHSA-r2qv-8222-hqg3: previously returned None unconditionally,
  1370. # letting any valid API key satisfy admin "any-of" route
  1371. # dependencies. require_any → at-least-one must pass the scope check.
  1372. _check_apikey_permissions(api_key, perm_strings, require_any=True)
  1373. return None
  1374. if credentials is not None:
  1375. token = credentials.credentials
  1376. if token.startswith("bb_"):
  1377. api_key = await _validate_api_key(db, token)
  1378. if api_key:
  1379. _check_apikey_permissions(api_key, perm_strings, require_any=True)
  1380. return None
  1381. raise HTTPException(
  1382. status_code=status.HTTP_401_UNAUTHORIZED,
  1383. detail="Invalid API key",
  1384. headers={"WWW-Authenticate": "Bearer"},
  1385. )
  1386. try:
  1387. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  1388. username: str = payload.get("sub")
  1389. if username is None:
  1390. raise HTTPException(
  1391. status_code=status.HTTP_401_UNAUTHORIZED,
  1392. detail="Could not validate credentials",
  1393. headers={"WWW-Authenticate": "Bearer"},
  1394. )
  1395. jti: str | None = payload.get("jti")
  1396. if not jti or await is_jti_revoked(jti):
  1397. raise HTTPException(
  1398. status_code=status.HTTP_401_UNAUTHORIZED,
  1399. detail="Could not validate credentials",
  1400. headers={"WWW-Authenticate": "Bearer"},
  1401. )
  1402. iat: int | float | None = payload.get("iat")
  1403. except JWTError:
  1404. raise HTTPException(
  1405. status_code=status.HTTP_401_UNAUTHORIZED,
  1406. detail="Could not validate credentials",
  1407. headers={"WWW-Authenticate": "Bearer"},
  1408. )
  1409. user = await get_user_by_username(db, username)
  1410. if user is None or not user.is_active:
  1411. raise HTTPException(
  1412. status_code=status.HTTP_401_UNAUTHORIZED,
  1413. detail="Could not validate credentials",
  1414. headers={"WWW-Authenticate": "Bearer"},
  1415. )
  1416. if not _is_token_fresh(iat, user):
  1417. raise HTTPException(
  1418. status_code=status.HTTP_401_UNAUTHORIZED,
  1419. detail="Could not validate credentials",
  1420. headers={"WWW-Authenticate": "Bearer"},
  1421. )
  1422. if not user.has_any_permission(*perm_strings):
  1423. raise HTTPException(
  1424. status_code=status.HTTP_403_FORBIDDEN,
  1425. detail=f"Missing required permissions: {', '.join(perm_strings)}",
  1426. )
  1427. return user
  1428. raise HTTPException(
  1429. status_code=status.HTTP_401_UNAUTHORIZED,
  1430. detail="Authentication required",
  1431. headers={"WWW-Authenticate": "Bearer"},
  1432. )
  1433. return checker
  1434. def RequireAnyPermissionIfAuthEnabled(*permissions: str | Permission):
  1435. """Convenience dependency that requires AT LEAST ONE of the given permissions when auth is enabled."""
  1436. return Depends(require_any_permission_if_auth_enabled(*permissions))
  1437. def require_camera_stream_token_if_auth_enabled():
  1438. """Dependency that validates a camera stream token query param when auth is enabled.
  1439. Used for camera stream/snapshot endpoints that are loaded via <img> tags
  1440. which cannot send Authorization headers. The frontend obtains a token from
  1441. POST /printers/camera/stream-token and appends it as ?token=xxx.
  1442. """
  1443. async def checker(token: str | None = None) -> None:
  1444. async with async_session() as db:
  1445. if not await is_auth_enabled(db):
  1446. return # Auth disabled, allow access
  1447. if not token or not await verify_camera_stream_token(token):
  1448. raise HTTPException(
  1449. status_code=status.HTTP_401_UNAUTHORIZED,
  1450. detail="Valid camera stream token required. Obtain one from POST /api/v1/printers/camera/stream-token",
  1451. )
  1452. return checker
  1453. RequireCameraStreamTokenIfAuthEnabled = Depends(require_camera_stream_token_if_auth_enabled())
  1454. def require_ownership_permission(
  1455. all_permission: str | Permission,
  1456. own_permission: str | Permission,
  1457. ):
  1458. """Dependency factory for ownership-based permission checks.
  1459. - User with ``all_permission`` can modify any item
  1460. - User with ``own_permission`` can only modify items where created_by_id == user.id
  1461. - Ownerless items (created_by_id = null) require ``all_permission``
  1462. - API keys (via X-API-Key header or Bearer bb_xxx) must satisfy the
  1463. ``all_permission``'s API-key scope flag (e.g. ``can_queue`` for
  1464. ``QUEUE_UPDATE_ALL``) and then receive ``can_modify_all=True``.
  1465. OWN/ALL ownership pairs map to the same scope flag in
  1466. ``_APIKEY_SCOPE_BY_PERMISSION`` so checking ``all_permission`` is the
  1467. correct gate; API keys have no per-row ownership identity. Pre-
  1468. GHSA-r2qv-8222-hqg3 fix this returned ``(None, True)`` for any valid
  1469. key with no scope check — see ``core/auth.py`` allowlist commentary.
  1470. Returns:
  1471. A dependency function that returns (user, can_modify_all).
  1472. - can_modify_all=True: user can modify any item
  1473. - can_modify_all=False: user can only modify their own items
  1474. """
  1475. all_perm = all_permission.value if isinstance(all_permission, Permission) else all_permission
  1476. own_perm = own_permission.value if isinstance(own_permission, Permission) else own_permission
  1477. async def checker(
  1478. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  1479. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  1480. ) -> tuple[User | None, bool]:
  1481. """Returns (user, can_modify_all).
  1482. - can_modify_all=True: user can modify any item
  1483. - can_modify_all=False: user can only modify their own items
  1484. """
  1485. async with async_session() as db:
  1486. auth_enabled = await is_auth_enabled(db)
  1487. if not auth_enabled:
  1488. return None, True # Auth disabled, allow all
  1489. # GHSA-r2qv-8222-hqg3: previously API keys received (None, True)
  1490. # unconditionally on ownership-modify routes — a "queue-only" key
  1491. # could delete any user's archives, library files, queue items.
  1492. # OWN and ALL ownership perms both map to the same scope flag
  1493. # (e.g. both QUEUE_UPDATE_OWN and QUEUE_UPDATE_ALL → can_queue),
  1494. # so checking ``all_perm`` against the api_key's scope is the
  1495. # correct gate. API keys don't have per-row ownership identity, so
  1496. # on pass we keep can_modify_all=True (preserves prior intent,
  1497. # narrows access to keys with the right scope flag).
  1498. if x_api_key:
  1499. api_key = await _validate_api_key(db, x_api_key)
  1500. if api_key:
  1501. _check_apikey_permissions(api_key, [all_perm])
  1502. return None, True
  1503. # Check for Bearer token (could be JWT or API key)
  1504. if credentials is not None:
  1505. token = credentials.credentials
  1506. # Check if it's an API key (starts with bb_)
  1507. if token.startswith("bb_"):
  1508. api_key = await _validate_api_key(db, token)
  1509. if api_key:
  1510. _check_apikey_permissions(api_key, [all_perm])
  1511. return None, True
  1512. raise HTTPException(
  1513. status_code=status.HTTP_401_UNAUTHORIZED,
  1514. detail="Invalid API key",
  1515. headers={"WWW-Authenticate": "Bearer"},
  1516. )
  1517. # Otherwise treat as JWT
  1518. try:
  1519. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  1520. username: str = payload.get("sub")
  1521. if username is None:
  1522. raise HTTPException(
  1523. status_code=status.HTTP_401_UNAUTHORIZED,
  1524. detail="Could not validate credentials",
  1525. headers={"WWW-Authenticate": "Bearer"},
  1526. )
  1527. jti: str | None = payload.get("jti")
  1528. if not jti or await is_jti_revoked(jti):
  1529. raise HTTPException(
  1530. status_code=status.HTTP_401_UNAUTHORIZED,
  1531. detail="Could not validate credentials",
  1532. headers={"WWW-Authenticate": "Bearer"},
  1533. )
  1534. iat: int | float | None = payload.get("iat")
  1535. except JWTError:
  1536. raise HTTPException(
  1537. status_code=status.HTTP_401_UNAUTHORIZED,
  1538. detail="Could not validate credentials",
  1539. headers={"WWW-Authenticate": "Bearer"},
  1540. )
  1541. user = await get_user_by_username(db, username)
  1542. if user is None or not user.is_active:
  1543. raise HTTPException(
  1544. status_code=status.HTTP_401_UNAUTHORIZED,
  1545. detail="Could not validate credentials",
  1546. headers={"WWW-Authenticate": "Bearer"},
  1547. )
  1548. if not _is_token_fresh(iat, user):
  1549. raise HTTPException(
  1550. status_code=status.HTTP_401_UNAUTHORIZED,
  1551. detail="Could not validate credentials",
  1552. headers={"WWW-Authenticate": "Bearer"},
  1553. )
  1554. if user.has_permission(all_perm):
  1555. return user, True
  1556. if user.has_permission(own_perm):
  1557. return user, False
  1558. raise HTTPException(
  1559. status_code=status.HTTP_403_FORBIDDEN,
  1560. detail=f"Missing permission: {own_perm} or {all_perm}",
  1561. )
  1562. # No credentials provided
  1563. raise HTTPException(
  1564. status_code=status.HTTP_401_UNAUTHORIZED,
  1565. detail="Authentication required",
  1566. headers={"WWW-Authenticate": "Bearer"},
  1567. )
  1568. return checker