auth.py 72 KB

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