auth.py 81 KB

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