auth.py 91 KB

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