auth.py 64 KB

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