auth.py 97 KB

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