auth.py 84 KB

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