auth.py 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095
  1. import logging
  2. import os
  3. import secrets
  4. from datetime import datetime, timedelta, timezone
  5. from typing import Annotated
  6. import jwt as _jwt
  7. from fastapi import APIRouter, BackgroundTasks, Depends, Header, HTTPException, Request, Response, status
  8. from fastapi.security import HTTPAuthorizationCredentials
  9. from jwt.exceptions import PyJWTError
  10. from sqlalchemy import delete, or_, select
  11. from sqlalchemy.exc import SQLAlchemyError
  12. from sqlalchemy.ext.asyncio import AsyncSession
  13. from sqlalchemy.orm import selectinload
  14. from backend.app.api.routes.settings import get_external_login_url
  15. from backend.app.core.auth import (
  16. ALGORITHM,
  17. SECRET_KEY,
  18. Permission,
  19. RequireAdminIfAuthEnabled,
  20. RequirePermissionIfAuthEnabled,
  21. _is_token_fresh,
  22. _validate_api_key,
  23. apikey_effective_permissions,
  24. authenticate_user,
  25. authenticate_user_by_email,
  26. create_access_token,
  27. create_media_token,
  28. create_websocket_token,
  29. current_api_key_if_present,
  30. get_current_active_user,
  31. get_password_hash,
  32. get_user_by_email,
  33. get_user_by_username,
  34. is_jti_revoked,
  35. require_auth_if_enabled,
  36. resolve_apikey_owner,
  37. resolve_session_max_minutes,
  38. revoke_jti,
  39. security,
  40. token_outlived_its_session,
  41. )
  42. from backend.app.core.database import async_session, get_db
  43. from backend.app.core.filament_scope import filament_policies_for
  44. from backend.app.core.oidc_env import env_bool
  45. from backend.app.models.api_key import APIKey
  46. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent, EventType, TokenType
  47. from backend.app.models.group import Group
  48. from backend.app.models.settings import Settings
  49. from backend.app.models.user import User
  50. from backend.app.schemas.auth import (
  51. EncryptionRowCounts,
  52. EncryptionStatusResponse,
  53. ForgotPasswordConfirmRequest,
  54. ForgotPasswordRequest,
  55. ForgotPasswordResponse,
  56. GroupBrief,
  57. LDAPProvisionRequest,
  58. LDAPSearchResultResponse,
  59. LDAPTestRequest,
  60. LoginRequest,
  61. LoginResponse,
  62. ResetPasswordRequest,
  63. ResetPasswordResponse,
  64. SetupRequest,
  65. SetupResponse,
  66. SMTPSettings,
  67. TestSMTPRequest,
  68. TestSMTPResponse,
  69. UserResponse,
  70. _validate_password_complexity,
  71. )
  72. from backend.app.services.email_service import (
  73. create_password_reset_link_email_from_template,
  74. get_smtp_settings,
  75. save_smtp_settings,
  76. send_email,
  77. )
  78. from backend.app.services.finance_defaults import ensure_user_finance_defaults
  79. _logger = logging.getLogger(__name__)
  80. def _user_to_response(user: User) -> UserResponse:
  81. """Convert a User model to UserResponse schema."""
  82. return UserResponse(
  83. id=user.id,
  84. username=user.username,
  85. email=user.email,
  86. role=user.role,
  87. is_active=user.is_active,
  88. is_admin=user.is_admin,
  89. auth_source=getattr(user, "auth_source", "local"),
  90. groups=[GroupBrief(id=g.id, name=g.name) for g in user.groups],
  91. permissions=sorted(user.get_permissions()),
  92. filament_policies=filament_policies_for(user),
  93. created_at=user.created_at.isoformat(),
  94. )
  95. async def _api_key_to_user_response(db: AsyncSession, api_key) -> UserResponse:
  96. """Describe a valid API key as the identity it actually carries (#1894).
  97. Until 0.2.5 this returned a synthetic admin: ``id=0``, ``role="admin"``,
  98. ``is_admin=True`` and every permission in the enum. That was wrong in both
  99. directions. A key cannot perform administrative operations at all --
  100. ``_check_apikey_permissions`` denies every permission that is not in the
  101. scope allowlist -- so a client that builds its UI from this response (which
  102. is exactly what a native client does) rendered admin actions that 403 on
  103. use, and had no way to learn the id its own prints are filed under.
  104. Now: identity comes from the key's owner, and ``permissions`` is the set the
  105. key can genuinely exercise. ``is_admin`` is always False because no key can
  106. reach an administrative route regardless of who owns it.
  107. Legacy keys predating per-user ownership (``user_id IS NULL``) have no
  108. identity to report, so they keep ``id=0`` and the ``api-key:`` username --
  109. but they stop claiming admin. ``created_at`` describes the credential in
  110. both branches, unchanged.
  111. """
  112. # Same resolution the permission gate uses, so what is reported here and
  113. # what is enforced there cannot drift -- including the 403 when the owner
  114. # has been deactivated, which makes the key dead rather than anonymous.
  115. owner = await resolve_apikey_owner(db, api_key)
  116. return UserResponse(
  117. id=owner.id if owner else 0,
  118. username=owner.username if owner else f"api-key:{api_key.key_prefix}",
  119. # Withheld on purpose: the owner's email is not needed to resolve
  120. # identity, and this response is reachable by anyone holding the key.
  121. email=None,
  122. # Deprecated free-text field; "user" is the existing value meaning
  123. # "not an admin". Inventing an "api_key" role here would put a third
  124. # value into a field callers compare against string literals.
  125. role="user",
  126. is_active=True,
  127. is_admin=False,
  128. auth_source=getattr(owner, "auth_source", "local") if owner else "local",
  129. # The key is not a group member -- listing the owner's groups would
  130. # imply capabilities the key does not inherit.
  131. groups=[],
  132. permissions=apikey_effective_permissions(api_key, owner),
  133. # The owner's: the scheduler and the queue judge a key's jobs by the
  134. # owner's filament rules (#3522). A legacy ownerless key's jobs have no
  135. # creator, so they are unrestricted, as None says.
  136. filament_policies=filament_policies_for(owner) if owner else None,
  137. created_at=api_key.created_at.isoformat(),
  138. )
  139. # ---------------------------------------------------------------------------
  140. # M-R9-A: Real client IP resolution for rate limiting behind reverse proxies.
  141. # Set TRUSTED_PROXY_IPS (comma-separated) to enable X-Forwarded-For trust.
  142. # Without this env var client.host is used directly (safe default).
  143. # ---------------------------------------------------------------------------
  144. _TRUSTED_PROXY_IPS: frozenset[str] = frozenset(
  145. ip.strip() for ip in os.environ.get("TRUSTED_PROXY_IPS", "").split(",") if ip.strip()
  146. )
  147. # #1589: read at call time, not import time, so tests can monkeypatch os.environ
  148. # between cases without re-importing the module.
  149. def _local_login_env_bypass() -> bool:
  150. """Return True when ``BAMBUDDY_LOCAL_LOGIN`` env var is set truthy.
  151. Bypasses the ``local_login_enabled`` DB setting on the local-credentials
  152. code path AND the forgot-password endpoint so a server admin can recover
  153. an install whose SSO provider is unreachable. Accepted truthy values:
  154. ``true``, ``1``, ``yes`` (case-insensitive).
  155. """
  156. # strict=False: this runs on the login/forgot-password request path, not at
  157. # startup. An unrecognized value must fall back to "off" (the safe default),
  158. # never raise -- a 500 on the recovery endpoint is the opposite of what this
  159. # bypass is for.
  160. return env_bool("BAMBUDDY_LOCAL_LOGIN", False, strict=False)
  161. def _get_client_ip(request: Request) -> str:
  162. """Return the real client IP for rate-limiting purposes.
  163. When TRUSTED_PROXY_IPS is configured and the direct TCP peer is a trusted
  164. proxy, X-Forwarded-For is evaluated right-to-left: the rightmost IP that is
  165. NOT itself a trusted proxy is the true client address (M-R10-A fix).
  166. Standard nginx with proxy_add_x_forwarded_for *appends* the client IP, so
  167. the rightmost entry is always the one added by the last trusted proxy —
  168. i.e. the real client. Walking right-to-left and skipping known proxies is
  169. safe for multi-hop chains as well.
  170. Falls back to request.client.host when TRUSTED_PROXY_IPS is unset (direct
  171. deployment without a reverse proxy).
  172. """
  173. # I5: Use a per-request unique token instead of "unknown" when the transport
  174. # layer provides no client address. This prevents all such requests from
  175. # sharing one rate-limit bucket, and avoids collision with a literal username
  176. # "unknown". The token is not stable across requests, which is intentional:
  177. # we cannot track the IP so we also cannot rate-limit by it meaningfully.
  178. direct_ip = request.client.host if request.client else f"__no_ip_{secrets.token_hex(8)}__"
  179. if _TRUSTED_PROXY_IPS and direct_ip in _TRUSTED_PROXY_IPS:
  180. forwarded_for = request.headers.get("X-Forwarded-For", "")
  181. ips = [ip.strip() for ip in forwarded_for.split(",") if ip.strip()]
  182. # Walk right-to-left; skip IPs that belong to trusted proxies.
  183. for ip in reversed(ips):
  184. if ip not in _TRUSTED_PROXY_IPS:
  185. return ip
  186. # Edge case: every entry is a trusted proxy — fall back to leftmost.
  187. if ips:
  188. return ips[0]
  189. return direct_ip
  190. router = APIRouter(prefix="/auth", tags=["authentication"])
  191. async def is_auth_enabled(db: AsyncSession) -> bool:
  192. """Check if authentication is enabled."""
  193. result = await db.execute(select(Settings).where(Settings.key == "auth_enabled"))
  194. setting = result.scalar_one_or_none()
  195. if setting is None:
  196. return False
  197. return setting.value.lower() == "true"
  198. async def is_advanced_auth_enabled(db: AsyncSession) -> bool:
  199. """Check if advanced authentication is enabled."""
  200. result = await db.execute(select(Settings).where(Settings.key == "advanced_auth_enabled"))
  201. setting = result.scalar_one_or_none()
  202. if setting is None:
  203. return False
  204. return setting.value.lower() == "true"
  205. async def set_advanced_auth_enabled(db: AsyncSession, enabled: bool) -> None:
  206. """Set advanced authentication enabled status."""
  207. from backend.app.core.db_dialect import upsert_setting
  208. await upsert_setting(db, Settings, "advanced_auth_enabled", "true" if enabled else "false")
  209. async def set_auth_enabled(db: AsyncSession, enabled: bool) -> None:
  210. """Set authentication enabled status."""
  211. from backend.app.core.auth import invalidate_auth_enabled_cache
  212. from backend.app.core.db_dialect import upsert_setting
  213. await upsert_setting(db, Settings, "auth_enabled", "true" if enabled else "false")
  214. # Drop the cached auth-enabled flag so the change takes effect immediately
  215. # instead of after the TTL (issue #2572). Safe pre-commit: only enabled=True
  216. # is ever cached, and the newly-enabled True isn't visible to other sessions
  217. # until this transaction commits, so no stale value can be re-cached here.
  218. invalidate_auth_enabled_cache()
  219. # Note: Don't commit here - let get_db handle it or commit explicitly in the route
  220. async def is_setup_completed(db: AsyncSession) -> bool:
  221. """Check if setup has been completed."""
  222. result = await db.execute(select(Settings).where(Settings.key == "setup_completed"))
  223. setting = result.scalar_one_or_none()
  224. return setting and setting.value.lower() == "true"
  225. async def set_setup_completed(db: AsyncSession, completed: bool) -> None:
  226. """Set setup completed status."""
  227. from backend.app.core.db_dialect import upsert_setting
  228. await upsert_setting(db, Settings, "setup_completed", "true" if completed else "false")
  229. # Note: Don't commit here - let get_db handle it or commit explicitly in the route
  230. @router.post("/setup", response_model=SetupResponse)
  231. async def setup_auth(request: SetupRequest, db: AsyncSession = Depends(get_db, scope="function")):
  232. """First-time setup: enable/disable authentication and create admin user."""
  233. import logging
  234. logger = logging.getLogger(__name__)
  235. try:
  236. # If auth is currently enabled, block unauthenticated setup changes.
  237. # Use the admin panel (/disable endpoint) to modify auth when it's already on.
  238. if await is_auth_enabled(db):
  239. raise HTTPException(
  240. status_code=status.HTTP_403_FORBIDDEN,
  241. detail="Authentication is already configured. Use the admin panel to modify auth settings.",
  242. )
  243. admin_created = False
  244. if request.auth_enabled:
  245. # Check if admin users already exist
  246. admin_users_result = await db.execute(select(User).where(User.role == "admin"))
  247. existing_admin_users = list(admin_users_result.scalars().all())
  248. has_admin_users = len(existing_admin_users) > 0
  249. if has_admin_users:
  250. # Admin users already exist, just enable auth (don't create new admin)
  251. logger.info(
  252. f"Admin users already exist ({len(existing_admin_users)} found), enabling authentication without creating new admin"
  253. )
  254. admin_created = False
  255. else:
  256. # No admin users exist, require admin credentials to create first admin
  257. if not request.admin_username or not request.admin_password:
  258. raise HTTPException(
  259. status_code=status.HTTP_400_BAD_REQUEST,
  260. detail="Admin username and password are required when enabling authentication (no admin users exist)",
  261. )
  262. # Enforce password complexity only when actually creating a new admin.
  263. # Schema-level validation was removed so that re-enabling auth with an
  264. # existing admin (or LDAP) doesn't reject whatever placeholder the form sends.
  265. try:
  266. _validate_password_complexity(request.admin_password)
  267. except ValueError as exc:
  268. raise HTTPException(
  269. status_code=status.HTTP_400_BAD_REQUEST,
  270. detail=str(exc),
  271. )
  272. # Check if username already exists (shouldn't happen if no admin users exist, but check anyway)
  273. existing_user = await get_user_by_username(db, request.admin_username)
  274. if existing_user:
  275. raise HTTPException(
  276. status_code=status.HTTP_400_BAD_REQUEST,
  277. detail="User with this username already exists",
  278. )
  279. # Create admin user FIRST (before enabling auth)
  280. try:
  281. logger.info("Creating admin user: %s", request.admin_username)
  282. admin_user = User(
  283. username=request.admin_username,
  284. password_hash=get_password_hash(request.admin_password),
  285. role="admin",
  286. is_active=True,
  287. )
  288. # Try to add user to Administrators group if it exists
  289. admin_group_result = await db.execute(select(Group).where(Group.name == "Administrators"))
  290. admin_group = admin_group_result.scalar_one_or_none()
  291. if admin_group:
  292. admin_user.groups.append(admin_group)
  293. logger.info("Added new admin user to Administrators group")
  294. db.add(admin_user)
  295. logger.info("Admin user added to session: %s", request.admin_username)
  296. admin_created = True
  297. except Exception as e: # SEC-AUTH-EXC: rollback + raise 500 (fail-closed); no user is created on error
  298. await db.rollback()
  299. logger.error("Failed to create admin user: %s", e, exc_info=True)
  300. raise HTTPException(
  301. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  302. detail="Failed to create admin user",
  303. )
  304. if request.auth_enabled:
  305. # Enabling auth flips cloud-credential storage from the global
  306. # Settings rows to User.cloud_token. Carry any token linked while
  307. # auth was off across to the owning admin, or /cloud/* silently
  308. # degrades to local presets with no indication anything broke
  309. # (#2530). Only migrate when there is exactly one obvious owner:
  310. # handing another admin's session a Bambu credential is not a
  311. # guess worth making.
  312. from backend.app.api.routes.cloud import migrate_global_cloud_token_to_user
  313. from backend.app.services.bambu_cloud_credentials import get_stored_token
  314. if admin_created:
  315. cloud_owner = admin_user
  316. elif len(existing_admin_users) == 1:
  317. cloud_owner = existing_admin_users[0]
  318. else:
  319. cloud_owner = None
  320. if cloud_owner is not None:
  321. if await migrate_global_cloud_token_to_user(db, cloud_owner):
  322. logger.info("Migrated global Bambu Cloud credentials to admin '%s'", cloud_owner.username)
  323. else:
  324. global_token, _, _ = await get_stored_token(db, None)
  325. if global_token:
  326. logger.warning(
  327. "A Bambu Cloud account is linked globally but %s admins exist; "
  328. "leaving it unassigned. Re-link the account from Settings after login.",
  329. len(existing_admin_users),
  330. )
  331. # Set auth enabled and mark setup as completed
  332. await set_auth_enabled(db, request.auth_enabled)
  333. await set_setup_completed(db, True)
  334. if request.auth_enabled:
  335. # Tokens minted while it was off name nobody (every tab mints a
  336. # WebSocket one): they would reconnect the dashboards closed below.
  337. await db.execute(
  338. delete(AuthEphemeralToken).where(
  339. or_(AuthEphemeralToken.username.is_(None), AuthEphemeralToken.username == ""),
  340. AuthEphemeralToken.api_key_id.is_(None),
  341. AuthEphemeralToken.token_type != "revoked_jti",
  342. )
  343. )
  344. await db.commit()
  345. if request.auth_enabled:
  346. # Dashboards opened while it was off have every printer and would
  347. # keep them. Closed, such a tab re-checks auth and goes to the login.
  348. from backend.app.core.websocket import ws_manager
  349. await ws_manager.close_anonymous()
  350. if admin_created:
  351. await db.refresh(admin_user)
  352. logger.info("Admin user created successfully: %s", admin_user.id)
  353. logger.info("Setup completed: auth_enabled=%s, admin_created=%s", request.auth_enabled, admin_created)
  354. return SetupResponse(auth_enabled=request.auth_enabled, admin_created=admin_created)
  355. except HTTPException:
  356. raise
  357. except Exception as e: # SEC-AUTH-EXC: rollback + raise 500 (fail-closed); setup state stays unchanged
  358. logger.error("Setup error: %s", e, exc_info=True)
  359. await db.rollback()
  360. raise HTTPException(
  361. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  362. detail="Setup failed",
  363. )
  364. @router.get("/status")
  365. async def get_auth_status(db: AsyncSession = Depends(get_db, scope="function")):
  366. """Get authentication status (public endpoint)."""
  367. auth_enabled = await is_auth_enabled(db)
  368. setup_completed = await is_setup_completed(db)
  369. # Only require setup if it hasn't been completed yet
  370. requires_setup = not setup_completed
  371. return {"auth_enabled": auth_enabled, "requires_setup": requires_setup}
  372. @router.post("/disable", response_model=dict)
  373. async def disable_auth(
  374. current_user: User = Depends(get_current_active_user),
  375. db: AsyncSession = Depends(get_db, scope="function"),
  376. ):
  377. """Disable authentication (admin only)."""
  378. import logging
  379. logger = logging.getLogger(__name__)
  380. # Reload user with groups for proper is_admin check
  381. result = await db.execute(select(User).where(User.id == current_user.id).options(selectinload(User.groups)))
  382. user = result.scalar_one()
  383. # Only admins can disable authentication
  384. if not user.is_admin:
  385. raise HTTPException(
  386. status_code=status.HTTP_403_FORBIDDEN,
  387. detail="Only admins can disable authentication",
  388. )
  389. try:
  390. # Mirror of the migration in setup_auth: with auth off the cloud routes
  391. # read the global Settings rows and never look at User.cloud_token, so
  392. # hand this admin's credential over rather than stranding it (#2530).
  393. from backend.app.api.routes.cloud import migrate_user_cloud_token_to_global
  394. if await migrate_user_cloud_token_to_global(db, user):
  395. logger.info("Migrated Bambu Cloud credentials from admin '%s' to global storage", user.username)
  396. await set_auth_enabled(db, False)
  397. await db.commit()
  398. logger.info("Authentication disabled by admin user: %s", user.username)
  399. return {"message": "Authentication disabled successfully", "auth_enabled": False}
  400. except Exception as e: # SEC-AUTH-EXC: rollback + raise 500 (fail-closed); auth_enabled stays at its prior value
  401. await db.rollback()
  402. logger.error("Failed to disable authentication: %s", e, exc_info=True)
  403. raise HTTPException(
  404. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  405. detail="Failed to disable authentication",
  406. )
  407. @router.post("/login", response_model=LoginResponse)
  408. async def login(
  409. raw_request: Request,
  410. request: LoginRequest,
  411. response: Response,
  412. db: AsyncSession = Depends(get_db, scope="function"),
  413. ):
  414. """Login and get access token.
  415. Supports username or email-based login. Username lookup is case-insensitive.
  416. When 2FA is enabled for the user the response contains ``requires_2fa=True``
  417. and a short-lived ``pre_auth_token`` instead of the final JWT. The client
  418. must then call ``POST /auth/2fa/verify`` (or first ``POST /auth/2fa/email/send``
  419. to trigger an email OTP) to obtain the real access token.
  420. """
  421. # Check if auth is enabled
  422. auth_enabled = await is_auth_enabled(db)
  423. if not auth_enabled:
  424. raise HTTPException(
  425. status_code=status.HTTP_400_BAD_REQUEST,
  426. detail="Authentication is not enabled",
  427. )
  428. # Rate-limit repeated login failures — two independent buckets (M-R5-B / M-R6-A):
  429. # 1. Per-username (10/15 min): prevents password brute-force on a known account.
  430. # 2. Per-IP (20/15 min): prevents an attacker from locking out arbitrary accounts
  431. # (DoS) by sending failures for many usernames from a single address.
  432. from backend.app.api.routes.mfa import MAX_LOGIN_ATTEMPTS, check_rate_limit, record_failed_attempt
  433. await check_rate_limit(db, request.username, event_type=EventType.LOGIN_ATTEMPT, max_attempts=MAX_LOGIN_ATTEMPTS)
  434. client_ip = _get_client_ip(raw_request)
  435. await check_rate_limit(db, client_ip, event_type=EventType.LOGIN_IP, max_attempts=20)
  436. # Initialize `user` up front so every downstream branch can read/write
  437. # it without UnboundLocalError. The LDAP success path sets it inside its
  438. # own block; the local-credentials and email-credentials paths set it
  439. # below. The original code relied on the local-credentials path running
  440. # unconditionally to bind `user`; #1589 made that path skippable, so the
  441. # init has to live here.
  442. user = None
  443. # Check if LDAP is enabled
  444. ldap_user = None
  445. ldap_user_provisioned = False
  446. ldap_settings = await _get_ldap_settings(db)
  447. if ldap_settings:
  448. try:
  449. from backend.app.services.ldap_service import (
  450. authenticate_ldap_user,
  451. parse_ldap_config,
  452. )
  453. ldap_config = parse_ldap_config(ldap_settings)
  454. if ldap_config:
  455. ldap_user = authenticate_ldap_user(ldap_config, request.username, request.password)
  456. if ldap_user:
  457. # LDAP auth succeeded — find or create local user
  458. user = await get_user_by_username(db, ldap_user.username)
  459. if user and user.auth_source != "ldap":
  460. # Username exists as local user — don't override
  461. user = None
  462. ldap_user = None
  463. elif not user:
  464. if not ldap_config.auto_provision:
  465. # User doesn't exist and auto-provision is off
  466. ldap_user = None
  467. else:
  468. # Auto-provision LDAP user. Provisioning already sets the
  469. # email, groups and finance defaults the sync below would,
  470. # so a new user skips it (it also logged the default-group
  471. # warning a second time, #3197).
  472. user = await _provision_ldap_user(db, ldap_user, ldap_config)
  473. ldap_user_provisioned = True
  474. if user and ldap_user and not ldap_user_provisioned:
  475. # Update email and group mappings on each login
  476. await _sync_ldap_user(db, user, ldap_user, ldap_config)
  477. # Keep finance defaults idempotently in sync for LDAP users
  478. # (wallet + private cost center + self-membership).
  479. await ensure_user_finance_defaults(db, user)
  480. except Exception as e: # SEC-AUTH-EXC: LDAP failure sets ldap_user=None, downstream local-auth path runs with its own credential check (no implicit grant)
  481. import logging
  482. logging.getLogger(__name__).warning("LDAP authentication error, falling back to local: %s", e)
  483. ldap_user = None
  484. # #1589: local username/password gate. LDAP keeps its own switch
  485. # (ldap_enabled) and is not affected — a delegated directory has its
  486. # own policy and lockouts and is closer to SSO than to local creds.
  487. # The env-var BAMBUDDY_LOCAL_LOGIN=true bypasses this gate so a server
  488. # admin can recover an install whose SSO provider is unreachable
  489. # without editing the DB.
  490. from backend.app.models.settings import Settings as _Settings_for_local_login
  491. local_login_allowed = ldap_user is not None or _local_login_env_bypass()
  492. if not local_login_allowed:
  493. setting_row = await db.execute(
  494. select(_Settings_for_local_login).where(_Settings_for_local_login.key == "local_login_enabled")
  495. )
  496. row = setting_row.scalar_one_or_none()
  497. # Default True when the row is absent — matches AppSettings default
  498. # so fresh installs and tests behave like every release before #1589.
  499. local_login_allowed = row is None or row.value.lower() == "true"
  500. # Try username-based authentication (skip if already authenticated via LDAP)
  501. if not ldap_user and local_login_allowed:
  502. user = await authenticate_user(db, request.username, request.password)
  503. # If username auth failed and advanced auth is enabled, try email-based authentication
  504. if not user and not ldap_user and local_login_allowed:
  505. advanced_auth = await is_advanced_auth_enabled(db)
  506. if advanced_auth:
  507. user = await authenticate_user_by_email(db, request.username, request.password)
  508. if not user:
  509. await record_failed_attempt(db, request.username, event_type=EventType.LOGIN_ATTEMPT)
  510. await record_failed_attempt(db, client_ip, event_type=EventType.LOGIN_IP)
  511. # Same generic 401 either way — never tell the client whether the
  512. # username exists or whether local login was disabled. The Settings
  513. # UI and /auth/advanced-auth/status are the channels for that state;
  514. # leaking it here would help credential-stuffing distinguish "local
  515. # disabled" from "wrong password" across an install fleet.
  516. raise HTTPException(
  517. status_code=status.HTTP_401_UNAUTHORIZED,
  518. detail="Incorrect username or password",
  519. headers={"WWW-Authenticate": "Bearer"},
  520. )
  521. # Reload user with groups for proper permission calculation
  522. result = await db.execute(select(User).where(User.id == user.id).options(selectinload(User.groups)))
  523. user = result.scalar_one()
  524. # L-R6-A: Password was correct — reset login failure counters for both buckets
  525. from backend.app.api.routes.mfa import clear_failed_attempts
  526. await clear_failed_attempts(db, user.username, event_type=EventType.LOGIN_ATTEMPT)
  527. await clear_failed_attempts(db, client_ip, event_type=EventType.LOGIN_IP)
  528. # --- 2FA check ---
  529. # Determine which 2FA methods are active for this user.
  530. from backend.app.models.settings import Settings as _Settings
  531. from backend.app.models.user_totp import UserTOTP
  532. totp_result = await db.execute(select(UserTOTP).where(UserTOTP.user_id == user.id))
  533. user_totp = totp_result.scalar_one_or_none()
  534. totp_enabled = user_totp is not None and user_totp.is_enabled
  535. email_2fa_result = await db.execute(select(_Settings).where(_Settings.key == f"user_{user.id}_email_2fa_enabled"))
  536. email_2fa_setting = email_2fa_result.scalar_one_or_none()
  537. email_otp_enabled = (
  538. email_2fa_setting is not None and email_2fa_setting.value.lower() == "true" and user.email is not None
  539. )
  540. if totp_enabled or email_otp_enabled:
  541. # Import here to avoid circular imports
  542. from backend.app.api.routes.mfa import create_pre_auth_token
  543. # Bind the pre_auth_token to an HttpOnly cookie so XSS cannot steal the
  544. # token from JS memory and complete 2FA from a different client.
  545. challenge_id = secrets.token_urlsafe(32)
  546. pre_auth_token = await create_pre_auth_token(db, user.username, challenge_id=challenge_id)
  547. response.set_cookie(
  548. key="2fa_challenge",
  549. value=challenge_id,
  550. httponly=True,
  551. # H-1: only transmit over HTTPS so the binding cookie can't be intercepted
  552. # on mixed-content deployments. Falls back to False on plain HTTP so tests
  553. # and local development still work (the client wouldn't send it otherwise).
  554. secure=raw_request.url.scheme == "https",
  555. samesite="lax",
  556. max_age=300,
  557. path="/api/v1/auth/2fa",
  558. )
  559. methods: list[str] = []
  560. if totp_enabled:
  561. methods.append("totp")
  562. if email_otp_enabled:
  563. methods.append("email")
  564. # Backup codes are always available when TOTP is set up
  565. if totp_enabled:
  566. methods.append("backup")
  567. return LoginResponse(
  568. requires_2fa=True,
  569. pre_auth_token=pre_auth_token,
  570. two_fa_methods=methods,
  571. )
  572. # No 2FA — issue full token immediately. Session lifetime honours the
  573. # admin-configurable ceiling (#1706); resolver clamps to [1h, 720h].
  574. access_token_expires = timedelta(minutes=await resolve_session_max_minutes(db))
  575. access_token = create_access_token(data={"sub": user.username}, expires_delta=access_token_expires)
  576. return LoginResponse(
  577. access_token=access_token,
  578. token_type="bearer",
  579. user=_user_to_response(user),
  580. )
  581. @router.post("/ws-token")
  582. async def mint_websocket_token(
  583. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.WEBSOCKET_CONNECT),
  584. api_key: APIKey | None = Depends(current_api_key_if_present),
  585. ):
  586. """Mint a short-lived token for ``/api/v1/ws`` connections (GHSA-r2qv follow-up).
  587. The WebSocket endpoint cannot read ``Authorization`` headers from
  588. browsers (the WebSocket handshake does not let JS attach custom
  589. headers), so we use the same opaque-token-in-query-param pattern
  590. as ``/camera/stream`` — the token is minted here behind the standard
  591. permission gate, then appended as ``?token=<value>`` on the
  592. ``ws://...`` URL. The WebSocket endpoint validates it *before*
  593. calling ``websocket.accept()``.
  594. Returns ``{"token": <opaque string>}``. The token is valid for 60
  595. minutes; the SPA refreshes it on reconnect if expired. API keys can
  596. mint tokens too — their scope flags decide whether ``WEBSOCKET_CONNECT``
  597. passes via the standard allowlist (``can_read_status`` covers it).
  598. """
  599. username = current_user.username if current_user is not None else None
  600. # The socket only carries the printers its minter may see (#1727)
  601. api_key_id = api_key.id if api_key is not None else None
  602. # The key's prefix binds the token to this key (SQLite reuses a deleted key's id)
  603. api_key_prefix = api_key.key_prefix if api_key is not None else None
  604. return {"token": await create_websocket_token(username, api_key_id, api_key_prefix)}
  605. @router.post("/media-token")
  606. async def mint_media_token(
  607. current_user: User | None = Depends(require_auth_if_enabled),
  608. ):
  609. """Mint a short-lived token for ``<img>`` / ``<video>`` media routes (#3025).
  610. Thumbnails, plate previews, timelapses, cover images and sidebar icons are
  611. loaded by the browser as element ``src`` URLs, which cannot carry an
  612. ``Authorization`` header. Those routes used to accept the *camera stream*
  613. token instead, which made ``camera:view`` a prerequisite for seeing a
  614. library thumbnail -- on a home install, handing someone the live feed of
  615. the room the printer is in just so their own files render.
  616. So this mints behind plain authentication: any signed-in user may ask, and
  617. what the token can actually reach is decided per request by the same
  618. permission and ownership rules as the resource's other routes. It is not a
  619. camera credential and does not open the camera routes.
  620. Returns ``{"token": <opaque string>}``, valid for 60 minutes.
  621. """
  622. username = current_user.username if current_user is not None else None
  623. return {"token": await create_media_token(username)}
  624. @router.get("/me", response_model=UserResponse)
  625. async def get_current_user_info(
  626. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  627. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  628. db: AsyncSession = Depends(get_db, scope="function"),
  629. ):
  630. """Get current user information.
  631. Accepts JWT tokens (via Authorization: Bearer header) and API keys
  632. (via X-API-Key header or Authorization: Bearer bb_xxx). API keys report
  633. their owner's identity and the permissions the key can actually exercise
  634. -- see ``_api_key_to_user_response``.
  635. """
  636. import jwt
  637. from jwt.exceptions import PyJWTError as JWTError
  638. # Check for API key via X-API-Key header
  639. if x_api_key:
  640. api_key = await _validate_api_key(db, x_api_key)
  641. if api_key:
  642. return await _api_key_to_user_response(db, api_key)
  643. # Check for Bearer token (could be JWT or API key)
  644. if credentials is not None:
  645. token = credentials.credentials
  646. # Check if it's an API key (starts with bb_)
  647. if token.startswith("bb_"):
  648. api_key = await _validate_api_key(db, token)
  649. if api_key:
  650. return await _api_key_to_user_response(db, api_key)
  651. raise HTTPException(
  652. status_code=status.HTTP_401_UNAUTHORIZED,
  653. detail="Invalid API key",
  654. headers={"WWW-Authenticate": "Bearer"},
  655. )
  656. # Otherwise treat as JWT
  657. try:
  658. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  659. username: str = payload.get("sub")
  660. if username is None:
  661. raise HTTPException(
  662. status_code=status.HTTP_401_UNAUTHORIZED,
  663. detail="Could not validate credentials",
  664. headers={"WWW-Authenticate": "Bearer"},
  665. )
  666. jti: str | None = payload.get("jti")
  667. if not jti or await is_jti_revoked(jti, db): # B1: logout bypass fix
  668. raise HTTPException(
  669. status_code=status.HTTP_401_UNAUTHORIZED,
  670. detail="Could not validate credentials",
  671. headers={"WWW-Authenticate": "Bearer"},
  672. )
  673. iat: int | float | None = payload.get("iat")
  674. except JWTError:
  675. raise HTTPException(
  676. status_code=status.HTTP_401_UNAUTHORIZED,
  677. detail="Could not validate credentials",
  678. headers={"WWW-Authenticate": "Bearer"},
  679. )
  680. user = await get_user_by_username(db, username)
  681. if user is None or not user.is_active:
  682. raise HTTPException(
  683. status_code=status.HTTP_401_UNAUTHORIZED,
  684. detail="Could not validate credentials",
  685. headers={"WWW-Authenticate": "Bearer"},
  686. )
  687. # Reload with groups for proper permission calculation
  688. result = await db.execute(select(User).where(User.id == user.id).options(selectinload(User.groups)))
  689. user = result.scalar_one()
  690. # L-R8-A: reject tokens issued before the last password change
  691. if not _is_token_fresh(iat, user):
  692. raise HTTPException(
  693. status_code=status.HTTP_401_UNAUTHORIZED,
  694. detail="Could not validate credentials",
  695. headers={"WWW-Authenticate": "Bearer"},
  696. )
  697. return _user_to_response(user)
  698. # No credentials provided
  699. raise HTTPException(
  700. status_code=status.HTTP_401_UNAUTHORIZED,
  701. detail="Authentication required",
  702. headers={"WWW-Authenticate": "Bearer"},
  703. )
  704. @router.post("/logout")
  705. async def logout(
  706. raw_request: Request,
  707. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  708. ):
  709. """Logout — revokes the current JWT so it cannot be reused after logout."""
  710. if credentials is not None:
  711. raw_token = credentials.credentials
  712. # Nit2: Verify signature before revoking to prevent DoS-revoke attacks
  713. # (an attacker crafting a token with an arbitrary jti cannot force
  714. # revocation of a legitimate token because the signature check rejects it).
  715. # Expired tokens are still accepted — the user is logging out and their
  716. # token may have just expired; we still want to record the revocation.
  717. try:
  718. verified = _jwt.decode(
  719. raw_token,
  720. SECRET_KEY,
  721. algorithms=[ALGORITHM],
  722. options={"verify_exp": False}, # allow expired tokens at logout
  723. )
  724. jti: str | None = verified.get("jti")
  725. exp = verified.get("exp")
  726. username: str | None = verified.get("sub")
  727. if jti and exp:
  728. expires_at = datetime.fromtimestamp(exp, tz=timezone.utc)
  729. try:
  730. await revoke_jti(jti, expires_at, username)
  731. except Exception as exc: # SEC-AUTH-EXC: JTI-revoke failure on logout is logged only; logout removes access, never grants it (token stays valid until natural expiry — degraded but never escalation)
  732. _logger.error("Failed to revoke JTI on logout for user %s: %s", username, exc)
  733. except PyJWTError:
  734. client_ip = _get_client_ip(raw_request)
  735. ua = raw_request.headers.get("user-agent", "<unknown>")
  736. _logger.error(
  737. "Logout received token that failed signature verification — skipping revocation "
  738. "(possible tamper attempt; ip=%s ua=%s)",
  739. client_ip,
  740. ua,
  741. )
  742. return {"message": "Logged out successfully"}
  743. # Advanced Authentication Endpoints
  744. @router.post("/smtp/test", response_model=TestSMTPResponse)
  745. async def test_smtp_connection(
  746. test_request: TestSMTPRequest,
  747. _admin: User | None = RequireAdminIfAuthEnabled(),
  748. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  749. db: AsyncSession = Depends(get_db, scope="function"),
  750. ):
  751. """Test SMTP connection using the form's settings, else the saved ones (admin only when auth enabled).
  752. An empty password keeps the saved one, which only goes to the server it
  753. was entered for.
  754. """
  755. import logging
  756. from backend.app.services.secret_fields import SMTP_DESTINATIONS, same_value
  757. logger = logging.getLogger(__name__)
  758. try:
  759. stored = await get_smtp_settings(db)
  760. smtp_settings = test_request.smtp or stored
  761. if not smtp_settings:
  762. return TestSMTPResponse(success=False, message="SMTP settings not configured. Save SMTP settings first.")
  763. if test_request.smtp and smtp_settings.smtp_auth_enabled and not smtp_settings.smtp_password:
  764. if stored and stored.smtp_password:
  765. moved = [f for f in SMTP_DESTINATIONS if not same_value(getattr(smtp_settings, f), getattr(stored, f))]
  766. if moved:
  767. return TestSMTPResponse(
  768. success=False, message=f"Enter the SMTP password again: {', '.join(moved)} changed"
  769. )
  770. smtp_settings = smtp_settings.model_copy(update={"smtp_password": stored.smtp_password})
  771. # Send test email
  772. send_email(
  773. smtp_settings=smtp_settings,
  774. to_email=test_request.test_recipient,
  775. subject="BamBuddy SMTP Test",
  776. body_text="This is a test email from BamBuddy. If you received this, your SMTP settings are working correctly!",
  777. body_html="<p>This is a test email from <strong>BamBuddy</strong>.</p><p>If you received this, your SMTP settings are working correctly!</p>",
  778. )
  779. logger.info(f"Test email sent successfully to {test_request.test_recipient}")
  780. return TestSMTPResponse(success=True, message="Test email sent successfully")
  781. except Exception as e: # SEC-AUTH-EXC: SMTP test diagnostic returns success=False; no auth-relevant outcome (route is admin-gated by SETTINGS_UPDATE upstream)
  782. logger.error("Failed to send test email: %s", e)
  783. return TestSMTPResponse(success=False, message="Failed to send test email")
  784. @router.get("/smtp", response_model=SMTPSettings | None)
  785. async def get_smtp_config(
  786. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  787. db: AsyncSession = Depends(get_db, scope="function"),
  788. ):
  789. """Get SMTP settings (admin only when auth enabled). Password is not returned."""
  790. smtp_settings = await get_smtp_settings(db)
  791. if smtp_settings:
  792. # Don't return password in response
  793. smtp_settings.smtp_password = None
  794. return smtp_settings
  795. @router.post("/smtp", response_model=dict)
  796. async def save_smtp_config(
  797. smtp_settings: SMTPSettings,
  798. _admin: User | None = RequireAdminIfAuthEnabled(),
  799. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  800. db: AsyncSession = Depends(get_db, scope="function"),
  801. ):
  802. """Save SMTP settings (admin only when auth enabled).
  803. An empty password keeps the stored one, which only goes to the server it
  804. was entered for: a changed host, port or security needs it entered again
  805. (without authentication, the stored password is dropped instead).
  806. """
  807. import logging
  808. from backend.app.services.secret_fields import SMTP_DESTINATIONS, same_value
  809. logger = logging.getLogger(__name__)
  810. drop_password = False
  811. stored = await get_smtp_settings(db)
  812. if stored and stored.smtp_password and not smtp_settings.smtp_password:
  813. moved = [f for f in SMTP_DESTINATIONS if not same_value(getattr(smtp_settings, f), getattr(stored, f))]
  814. if moved and smtp_settings.smtp_auth_enabled:
  815. raise HTTPException(
  816. status_code=status.HTTP_400_BAD_REQUEST,
  817. detail=f"Enter the SMTP password again: {', '.join(moved)} changed",
  818. )
  819. drop_password = bool(moved)
  820. try:
  821. await save_smtp_settings(db, smtp_settings)
  822. if drop_password:
  823. from backend.app.core.db_dialect import upsert_setting
  824. from backend.app.models.settings import Settings
  825. await upsert_setting(db, Settings, "smtp_password", "")
  826. await db.commit()
  827. logger.info(f"SMTP settings updated by admin user: {current_user.username if current_user else 'anonymous'}")
  828. return {"message": "SMTP settings saved successfully"}
  829. except Exception as e: # SEC-AUTH-EXC: rollback + raise 500 (fail-closed); SMTP settings unchanged on error
  830. await db.rollback()
  831. logger.error("Failed to save SMTP settings: %s", e)
  832. raise HTTPException(
  833. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  834. detail="Failed to save SMTP settings",
  835. )
  836. @router.post("/advanced-auth/enable", response_model=dict)
  837. async def enable_advanced_auth(
  838. current_user: User = Depends(get_current_active_user),
  839. db: AsyncSession = Depends(get_db, scope="function"),
  840. ):
  841. """Enable advanced authentication (admin only).
  842. Requires SMTP settings to be configured and tested first.
  843. """
  844. import logging
  845. logger = logging.getLogger(__name__)
  846. # Reload user with groups for proper is_admin check
  847. result = await db.execute(select(User).where(User.id == current_user.id).options(selectinload(User.groups)))
  848. user = result.scalar_one()
  849. if not user.is_admin:
  850. raise HTTPException(
  851. status_code=status.HTTP_403_FORBIDDEN,
  852. detail="Only admins can enable advanced authentication",
  853. )
  854. # Verify SMTP settings are configured
  855. smtp_settings = await get_smtp_settings(db)
  856. if not smtp_settings:
  857. raise HTTPException(
  858. status_code=status.HTTP_400_BAD_REQUEST,
  859. detail="SMTP settings must be configured before enabling advanced authentication",
  860. )
  861. try:
  862. await set_advanced_auth_enabled(db, True)
  863. await db.commit()
  864. logger.info(f"Advanced authentication enabled by admin user: {user.username}")
  865. return {"message": "Advanced authentication enabled successfully", "advanced_auth_enabled": True}
  866. except Exception as e: # SEC-AUTH-EXC: rollback + raise 500 (fail-closed); advanced-auth setting unchanged on error
  867. await db.rollback()
  868. logger.error("Failed to enable advanced authentication: %s", e)
  869. raise HTTPException(
  870. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  871. detail="Failed to enable advanced authentication",
  872. )
  873. @router.post("/advanced-auth/disable", response_model=dict)
  874. async def disable_advanced_auth(
  875. current_user: User = Depends(get_current_active_user),
  876. db: AsyncSession = Depends(get_db, scope="function"),
  877. ):
  878. """Disable advanced authentication (admin only)."""
  879. import logging
  880. logger = logging.getLogger(__name__)
  881. # Reload user with groups for proper is_admin check
  882. result = await db.execute(select(User).where(User.id == current_user.id).options(selectinload(User.groups)))
  883. user = result.scalar_one()
  884. if not user.is_admin:
  885. raise HTTPException(
  886. status_code=status.HTTP_403_FORBIDDEN,
  887. detail="Only admins can disable advanced authentication",
  888. )
  889. try:
  890. await set_advanced_auth_enabled(db, False)
  891. await db.commit()
  892. logger.info(f"Advanced authentication disabled by admin user: {user.username}")
  893. return {"message": "Advanced authentication disabled successfully", "advanced_auth_enabled": False}
  894. except Exception as e: # SEC-AUTH-EXC: rollback + raise 500 (fail-closed); advanced-auth setting unchanged on error
  895. await db.rollback()
  896. logger.error("Failed to disable advanced authentication: %s", e)
  897. raise HTTPException(
  898. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  899. detail="Failed to disable advanced authentication",
  900. )
  901. @router.get("/advanced-auth/status")
  902. async def get_advanced_auth_status(db: AsyncSession = Depends(get_db, scope="function")):
  903. """Get advanced authentication status.
  904. Surfaces ``local_login_enabled`` and ``autologin_provider_id`` (#1589)
  905. so the LoginPage can decide whether to render the credentials form and
  906. whether to redirect unauthenticated visitors directly to an SSO
  907. provider, in a single query. ``BAMBUDDY_LOCAL_LOGIN=true`` flips the
  908. reported value back to True so the recovery path is visible.
  909. """
  910. from backend.app.models.oidc_provider import OIDCProvider
  911. from backend.app.models.settings import Settings as _Settings_for_local_login
  912. advanced_auth_enabled = await is_advanced_auth_enabled(db)
  913. smtp_configured = await get_smtp_settings(db) is not None
  914. setting_row = await db.execute(
  915. select(_Settings_for_local_login).where(_Settings_for_local_login.key == "local_login_enabled")
  916. )
  917. row = setting_row.scalar_one_or_none()
  918. db_local_enabled = row is None or row.value.lower() == "true"
  919. local_login_enabled = db_local_enabled or _local_login_env_bypass()
  920. # Autologin provider must be both flagged AND enabled — disabling a
  921. # provider should not silently keep redirecting visitors to it.
  922. autologin = await db.execute(
  923. select(OIDCProvider.id).where(OIDCProvider.is_autologin.is_(True), OIDCProvider.is_enabled.is_(True)).limit(1)
  924. )
  925. autologin_provider_id = autologin.scalar_one_or_none()
  926. return {
  927. "advanced_auth_enabled": advanced_auth_enabled,
  928. "smtp_configured": smtp_configured,
  929. "local_login_enabled": local_login_enabled,
  930. "autologin_provider_id": autologin_provider_id,
  931. }
  932. # TTL for password-reset tokens (H-6)
  933. _RESET_TOKEN_TTL = timedelta(hours=1)
  934. # Rate-limit for password-reset email sends per identifier (M-A)
  935. _MAX_PWD_RESET_SENDS = 3
  936. _PWD_RESET_SEND_WINDOW = timedelta(minutes=15)
  937. # L-NEW-6: per-IP cap to prevent mass-reset flooding across many addresses
  938. _MAX_PWD_RESET_SENDS_PER_IP = 10
  939. async def _send_reset_email_or_delete_token(
  940. reset_token: str,
  941. smtp_settings,
  942. to_email: str,
  943. subject: str,
  944. text_body: str,
  945. html_body: str,
  946. log_label: str,
  947. ) -> None:
  948. """Background task: send a password-reset email and delete the token on failure.
  949. C1: FastAPI silently swallows BackgroundTask exceptions. This wrapper
  950. catches send failures, deletes the single-use token so it cannot be used
  951. (user is not locked out forever — they can request a new link), and logs at
  952. ERROR so operators are alerted without leaking details to the caller.
  953. """
  954. try:
  955. send_email(smtp_settings, to_email, subject, text_body, html_body)
  956. _logger.info("Password reset email sent (%s) to %s", log_label, to_email)
  957. except Exception as exc: # SEC-AUTH-EXC: email-send failure → defensive token cleanup so a stuck token doesn't block re-request; no access granted, just frees future workflow
  958. _logger.error(
  959. "Password reset email failed (%s) to %s — deleting token to unblock re-request: %s",
  960. log_label,
  961. to_email,
  962. exc,
  963. )
  964. try:
  965. async with async_session() as db:
  966. await db.execute(
  967. delete(AuthEphemeralToken).where(
  968. AuthEphemeralToken.token == reset_token,
  969. AuthEphemeralToken.token_type == TokenType.PASSWORD_RESET,
  970. )
  971. )
  972. await db.commit()
  973. except Exception as db_exc: # SEC-AUTH-EXC: nested cleanup failure logged only; no access decision made in this branch (already handling a prior failure)
  974. _logger.error("Failed to delete reset token after send failure: %s", db_exc)
  975. @router.post("/forgot-password", response_model=ForgotPasswordResponse)
  976. async def forgot_password(
  977. request: ForgotPasswordRequest,
  978. background_tasks: BackgroundTasks,
  979. raw_request: Request,
  980. db: AsyncSession = Depends(get_db, scope="function"),
  981. ):
  982. """Request password reset via email (advanced auth only).
  983. H-6: Issues a short-lived single-use reset token and emails the user a
  984. secure link instead of a plaintext temporary password. The new password is
  985. set only when the user clicks the link and POSTs to /forgot-password/confirm.
  986. """
  987. # #1589: forgot-password is a local-credentials flow — useless when local
  988. # login is disabled (the reset wouldn't grant access anyway). Same gate as
  989. # /auth/login, with the same env-var bypass for SSO-broken recovery.
  990. if not _local_login_env_bypass():
  991. from backend.app.models.settings import Settings as _Settings_for_local_login
  992. setting_row = await db.execute(
  993. select(_Settings_for_local_login).where(_Settings_for_local_login.key == "local_login_enabled")
  994. )
  995. row = setting_row.scalar_one_or_none()
  996. if row is not None and row.value.lower() != "true":
  997. raise HTTPException(
  998. status_code=status.HTTP_403_FORBIDDEN,
  999. detail="Local login is disabled — use SSO instead.",
  1000. )
  1001. # Check if advanced auth is enabled
  1002. advanced_auth = await is_advanced_auth_enabled(db)
  1003. if not advanced_auth:
  1004. raise HTTPException(
  1005. status_code=status.HTTP_400_BAD_REQUEST,
  1006. detail="Advanced authentication is not enabled",
  1007. )
  1008. # M-A: Rate-limit by normalised email to prevent reset-email flooding.
  1009. # Apply unconditionally (before the user lookup) so unknown emails are also
  1010. # throttled — this prevents both flooding and timing-based enumeration.
  1011. identifier = request.email.lower()
  1012. cutoff = datetime.now(timezone.utc) - _PWD_RESET_SEND_WINDOW
  1013. rate_result = await db.execute(
  1014. select(AuthRateLimitEvent).where(
  1015. AuthRateLimitEvent.username == identifier,
  1016. AuthRateLimitEvent.event_type == EventType.PASSWORD_RESET_SEND,
  1017. AuthRateLimitEvent.occurred_at > cutoff,
  1018. )
  1019. )
  1020. if len(rate_result.scalars().all()) >= _MAX_PWD_RESET_SENDS:
  1021. raise HTTPException(
  1022. status_code=status.HTTP_429_TOO_MANY_REQUESTS,
  1023. detail=f"Too many password reset requests. Please wait {_PWD_RESET_SEND_WINDOW.seconds // 60} minutes.",
  1024. )
  1025. # L-NEW-6: per-IP rate limit — prevents mass-reset flooding across many
  1026. # different email addresses from a single source IP.
  1027. client_ip = _get_client_ip(raw_request)
  1028. ip_rate_result = await db.execute(
  1029. select(AuthRateLimitEvent).where(
  1030. AuthRateLimitEvent.username == client_ip,
  1031. AuthRateLimitEvent.event_type == EventType.PASSWORD_RESET_IP,
  1032. AuthRateLimitEvent.occurred_at > cutoff,
  1033. )
  1034. )
  1035. if len(ip_rate_result.scalars().all()) >= _MAX_PWD_RESET_SENDS_PER_IP:
  1036. raise HTTPException(
  1037. status_code=status.HTTP_429_TOO_MANY_REQUESTS,
  1038. detail=f"Too many password reset requests. Please wait {_PWD_RESET_SEND_WINDOW.seconds // 60} minutes.",
  1039. )
  1040. # Nit7: Always record the IP-level event (prevents spray attacks across many
  1041. # different email addresses from one IP). The email-level event is only
  1042. # recorded when we actually send an email to a local user — LDAP/OIDC users
  1043. # do not consume a slot because this flow is a no-op for them.
  1044. db.add(AuthRateLimitEvent(username=client_ip, event_type=EventType.PASSWORD_RESET_IP))
  1045. await db.commit()
  1046. # Get SMTP settings
  1047. smtp_settings = await get_smtp_settings(db)
  1048. if not smtp_settings:
  1049. raise HTTPException(
  1050. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  1051. detail="Email service is not configured",
  1052. )
  1053. # Find user by email — always return success to prevent email enumeration.
  1054. user = await get_user_by_email(db, request.email)
  1055. # M-1: exclude LDAP and OIDC users — they must use their respective provider.
  1056. if user and user.is_active and user.auth_source not in ("ldap", "oidc"):
  1057. try:
  1058. # Record email-level slot only for local users who will actually receive
  1059. # the reset email (Nit7: don't waste the user's quota for LDAP/OIDC no-ops).
  1060. db.add(AuthRateLimitEvent(username=identifier, event_type=EventType.PASSWORD_RESET_SEND))
  1061. now = datetime.now(timezone.utc)
  1062. # Prune any outstanding reset tokens for this user before issuing a new one.
  1063. await db.execute(
  1064. delete(AuthEphemeralToken).where(
  1065. AuthEphemeralToken.token_type == TokenType.PASSWORD_RESET,
  1066. AuthEphemeralToken.username == user.username,
  1067. )
  1068. )
  1069. reset_token = secrets.token_urlsafe(32)
  1070. db.add(
  1071. AuthEphemeralToken(
  1072. token=reset_token,
  1073. token_type=TokenType.PASSWORD_RESET,
  1074. username=user.username,
  1075. expires_at=now + _RESET_TOKEN_TTL,
  1076. )
  1077. )
  1078. await db.commit()
  1079. login_url = await get_external_login_url(db)
  1080. # M-B: Deliver token in the URL fragment so it never reaches the server
  1081. # in access-logs or Referer headers (mirrors H-4 for the OIDC token).
  1082. reset_url = f"{login_url}#reset_token={reset_token}"
  1083. subject, text_body, html_body = await create_password_reset_link_email_from_template(
  1084. db, user.username, reset_url
  1085. )
  1086. # L-R9-B: send asynchronously so response time is independent of
  1087. # whether the user exists (prevents email-existence timing oracle).
  1088. # C1: wrapper deletes the token if SMTP fails so the user can re-request.
  1089. background_tasks.add_task(
  1090. _send_reset_email_or_delete_token,
  1091. reset_token,
  1092. smtp_settings,
  1093. user.email,
  1094. subject,
  1095. text_body,
  1096. html_body,
  1097. "forgot_password",
  1098. )
  1099. _logger.info("Password reset email queued for %s", user.email)
  1100. except Exception as e: # SEC-AUTH-EXC: forgot-password response is intentionally generic regardless of outcome (user-enumeration defence); email failure does not grant access
  1101. _logger.error("Failed to send password reset email: %s", e)
  1102. # Don't reveal error to caller for security
  1103. return ForgotPasswordResponse(
  1104. message="If the email address is associated with an account, a password reset email has been sent."
  1105. )
  1106. @router.post("/forgot-password/confirm", response_model=ForgotPasswordResponse)
  1107. async def forgot_password_confirm(
  1108. request: ForgotPasswordConfirmRequest, db: AsyncSession = Depends(get_db, scope="function")
  1109. ):
  1110. """Complete a password reset by supplying the token from the reset email.
  1111. H-6: Atomically consumes the single-use token (DELETE…RETURNING) and sets
  1112. the new password. Expired or already-used tokens are silently rejected with
  1113. the same response to prevent oracle attacks.
  1114. """
  1115. now = datetime.now(timezone.utc)
  1116. result = await db.execute(
  1117. delete(AuthEphemeralToken)
  1118. .where(
  1119. AuthEphemeralToken.token == request.token,
  1120. AuthEphemeralToken.token_type == TokenType.PASSWORD_RESET,
  1121. )
  1122. .returning(AuthEphemeralToken.username, AuthEphemeralToken.expires_at, AuthEphemeralToken.created_at)
  1123. )
  1124. row = result.one_or_none()
  1125. await db.commit()
  1126. if row is None:
  1127. raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid or expired password reset token")
  1128. username, expires_at, minted_at = row
  1129. if await token_outlived_its_session(db, username, minted_at):
  1130. raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid or expired password reset token")
  1131. # Stored as naive UTC on both databases; treat it as UTC.
  1132. if expires_at.tzinfo is None:
  1133. expires_at = expires_at.replace(tzinfo=timezone.utc)
  1134. if now > expires_at:
  1135. raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid or expired password reset token")
  1136. user = await get_user_by_username(db, username)
  1137. # M-1: block LDAP/OIDC users — they authenticate via their provider, not local password.
  1138. if not user or not user.is_active or user.auth_source in ("ldap", "oidc"):
  1139. raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid or expired password reset token")
  1140. user.password_hash = get_password_hash(request.new_password)
  1141. user.password_changed_at = now # M-R7-B: invalidate all prior JWTs
  1142. # The WebSocket and camera tokens too: reusable for an hour, they would
  1143. # reconnect a closed dashboard straight away.
  1144. from backend.app.api.routes.users import drop_pending_tokens
  1145. await drop_pending_tokens(db, user.username)
  1146. await db.commit()
  1147. # Open dashboards are never signed in again: one someone else had open on
  1148. # the account would keep receiving its printers.
  1149. from backend.app.core.websocket import ws_manager
  1150. await ws_manager.close_user(user.id)
  1151. _logger.info("Password reset completed for user '%s'", username)
  1152. return ForgotPasswordResponse(message="Password has been reset successfully.")
  1153. @router.post("/reset-password", response_model=ResetPasswordResponse)
  1154. async def reset_user_password(
  1155. request: ResetPasswordRequest,
  1156. background_tasks: BackgroundTasks,
  1157. current_user: User = Depends(get_current_active_user),
  1158. db: AsyncSession = Depends(get_db, scope="function"),
  1159. ):
  1160. """Reset a user's password and send them an email (admin only, advanced auth only)."""
  1161. # Reload user with groups for proper is_admin check
  1162. result = await db.execute(select(User).where(User.id == current_user.id).options(selectinload(User.groups)))
  1163. admin_user = result.scalar_one()
  1164. if not admin_user.is_admin:
  1165. raise HTTPException(
  1166. status_code=status.HTTP_403_FORBIDDEN,
  1167. detail="Only admins can reset user passwords",
  1168. )
  1169. # Check if advanced auth is enabled
  1170. advanced_auth = await is_advanced_auth_enabled(db)
  1171. if not advanced_auth:
  1172. raise HTTPException(
  1173. status_code=status.HTTP_400_BAD_REQUEST,
  1174. detail="Advanced authentication is not enabled",
  1175. )
  1176. # Get SMTP settings
  1177. smtp_settings = await get_smtp_settings(db)
  1178. if not smtp_settings:
  1179. raise HTTPException(
  1180. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  1181. detail="Email service is not configured",
  1182. )
  1183. # Find user to reset
  1184. result = await db.execute(select(User).where(User.id == request.user_id))
  1185. user = result.scalar_one_or_none()
  1186. if not user:
  1187. raise HTTPException(
  1188. status_code=status.HTTP_404_NOT_FOUND,
  1189. detail="User not found",
  1190. )
  1191. # M-1: block LDAP/OIDC users — passwords are managed by their respective providers.
  1192. if user.auth_source in ("ldap", "oidc"):
  1193. raise HTTPException(
  1194. status_code=status.HTTP_400_BAD_REQUEST,
  1195. detail="Cannot reset password for LDAP/OIDC users — authentication is managed by their provider",
  1196. )
  1197. if not user.email:
  1198. raise HTTPException(
  1199. status_code=status.HTTP_400_BAD_REQUEST,
  1200. detail="User does not have an email address configured",
  1201. )
  1202. try:
  1203. # H-B: Issue a single-use reset link instead of generating a plaintext password.
  1204. # The admin never sees the credential — the user sets their own password.
  1205. now = datetime.now(timezone.utc)
  1206. await db.execute(
  1207. delete(AuthEphemeralToken).where(
  1208. AuthEphemeralToken.token_type == TokenType.PASSWORD_RESET,
  1209. AuthEphemeralToken.username == user.username,
  1210. )
  1211. )
  1212. reset_token = secrets.token_urlsafe(32)
  1213. db.add(
  1214. AuthEphemeralToken(
  1215. token=reset_token,
  1216. token_type=TokenType.PASSWORD_RESET,
  1217. username=user.username,
  1218. expires_at=now + _RESET_TOKEN_TTL,
  1219. )
  1220. )
  1221. await db.commit()
  1222. login_url = await get_external_login_url(db)
  1223. reset_url = f"{login_url}#reset_token={reset_token}"
  1224. subject, text_body, html_body = await create_password_reset_link_email_from_template(
  1225. db, user.username, reset_url
  1226. )
  1227. background_tasks.add_task(
  1228. _send_reset_email_or_delete_token,
  1229. reset_token,
  1230. smtp_settings,
  1231. user.email,
  1232. subject,
  1233. text_body,
  1234. html_body,
  1235. "admin_reset",
  1236. )
  1237. _logger.info("Admin password reset link queued for user '%s' by admin '%s'", user.username, admin_user.username)
  1238. return ResetPasswordResponse(message=f"Password reset link sent to {user.email}")
  1239. except Exception as e: # SEC-AUTH-EXC: rollback + raise 500 (fail-closed); reset token state unchanged on error
  1240. await db.rollback()
  1241. _logger.error("Failed to send admin password reset for user '%s': %s", user.username, e)
  1242. raise HTTPException(
  1243. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  1244. detail="Failed to send password reset link. Check server logs.", # L-R7-B: no internal details
  1245. )
  1246. # LDAP Authentication Helpers
  1247. LDAP_SETTING_KEYS = (
  1248. "ldap_enabled",
  1249. "ldap_server_url",
  1250. "ldap_bind_dn",
  1251. "ldap_bind_password",
  1252. "ldap_search_base",
  1253. "ldap_user_filter",
  1254. "ldap_security",
  1255. "ldap_group_mapping",
  1256. "ldap_auto_provision",
  1257. "ldap_ca_cert_path",
  1258. "ldap_default_group",
  1259. )
  1260. async def _get_ldap_settings(db: AsyncSession) -> dict[str, str] | None:
  1261. """Get LDAP settings from the database. Returns None if LDAP is not enabled."""
  1262. result = await db.execute(select(Settings).where(Settings.key.in_(LDAP_SETTING_KEYS)))
  1263. settings = {s.key: s.value for s in result.scalars().all()}
  1264. if settings.get("ldap_enabled", "false").lower() != "true":
  1265. return None
  1266. return settings
  1267. async def _provision_ldap_user(db: AsyncSession, ldap_user, ldap_config) -> User:
  1268. """Create a new local user from LDAP authentication."""
  1269. import logging
  1270. from backend.app.services.ldap_service import resolve_group_mapping
  1271. logger = logging.getLogger(__name__)
  1272. new_user = User(
  1273. username=ldap_user.username,
  1274. email=ldap_user.email,
  1275. password_hash=None,
  1276. role="user",
  1277. auth_source="ldap",
  1278. is_active=True,
  1279. )
  1280. # Map LDAP groups to BamBuddy groups, falling back to the configured default group
  1281. # when the user is authenticated but has no matching group mapping (#921-follow-up).
  1282. mapped_group_names = resolve_group_mapping(ldap_user.groups, ldap_config.group_mapping)
  1283. if not mapped_group_names and ldap_config.default_group:
  1284. mapped_group_names = [ldap_config.default_group]
  1285. logger.warning(
  1286. "LDAP user %s has no mapped groups — assigning configured default group '%s'",
  1287. ldap_user.username,
  1288. ldap_config.default_group,
  1289. )
  1290. if mapped_group_names:
  1291. groups_result = await db.execute(select(Group).where(Group.name.in_(mapped_group_names)))
  1292. new_user.groups = list(groups_result.scalars().all())
  1293. new_user.sync_role_to_groups()
  1294. db.add(new_user)
  1295. await db.flush()
  1296. await ensure_user_finance_defaults(db, new_user)
  1297. await db.commit()
  1298. await db.refresh(new_user)
  1299. logger.info("Auto-provisioned LDAP user: %s (groups: %s)", new_user.username, mapped_group_names)
  1300. return new_user
  1301. async def _sync_ldap_user(db: AsyncSession, user: User, ldap_user, ldap_config) -> None:
  1302. """Sync LDAP user attributes (email, groups) on each login.
  1303. Group sync only touches BamBuddy groups that LDAP is configured to manage —
  1304. that is, the values of `group_mapping` plus `default_group`. Any group
  1305. outside that set is assumed to be a manual admin assignment and is
  1306. preserved across logins (#1292). Manual assignments to a BamBuddy group
  1307. that IS LDAP-managed are still overridden by LDAP truth, because revoking
  1308. access in LDAP must propagate to BamBuddy on next login.
  1309. """
  1310. import logging
  1311. from backend.app.services.ldap_service import resolve_group_mapping
  1312. logger = logging.getLogger(__name__)
  1313. changed = False
  1314. # Update email if changed
  1315. if ldap_user.email and ldap_user.email != user.email:
  1316. user.email = ldap_user.email
  1317. changed = True
  1318. # Compute the set of BamBuddy groups LDAP is allowed to manage. Anything
  1319. # outside this set is left alone so manual admin assignments survive logins.
  1320. ldap_managed_names: set[str] = set(ldap_config.group_mapping.values())
  1321. if ldap_config.default_group:
  1322. ldap_managed_names.add(ldap_config.default_group)
  1323. # Resolve what LDAP says the user should currently be in.
  1324. mapped_group_names = resolve_group_mapping(ldap_user.groups, ldap_config.group_mapping)
  1325. if not mapped_group_names and ldap_config.default_group:
  1326. mapped_group_names = [ldap_config.default_group]
  1327. logger.warning(
  1328. "LDAP user %s has no mapped groups — assigning configured default group '%s'",
  1329. user.username,
  1330. ldap_config.default_group,
  1331. )
  1332. if mapped_group_names:
  1333. groups_result = await db.execute(select(Group).where(Group.name.in_(mapped_group_names)))
  1334. new_ldap_groups = list(groups_result.scalars().all())
  1335. else:
  1336. new_ldap_groups = []
  1337. # Preserve manual assignments to non-LDAP-managed groups; replace only
  1338. # the LDAP-managed slice with the resolved set.
  1339. preserved_manual_groups = [g for g in user.groups if g.name not in ldap_managed_names]
  1340. new_groups = preserved_manual_groups + new_ldap_groups
  1341. current_group_ids = {g.id for g in user.groups}
  1342. new_group_ids = {g.id for g in new_groups}
  1343. groups_changed = current_group_ids != new_group_ids
  1344. if groups_changed:
  1345. user.groups = new_groups
  1346. user.sync_role_to_groups()
  1347. changed = True
  1348. if changed:
  1349. await db.commit()
  1350. logger.info("Synced LDAP user attributes: %s", user.username)
  1351. if groups_changed:
  1352. # The user's open dashboards may now see other printers (#1727)
  1353. from backend.app.core.websocket import ws_manager
  1354. await ws_manager.refresh_printer_scopes()
  1355. @router.post("/ldap/test")
  1356. async def test_ldap(
  1357. body: LDAPTestRequest | None = None,
  1358. _admin: User | None = RequireAdminIfAuthEnabled(),
  1359. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  1360. db: AsyncSession = Depends(get_db, scope="function"),
  1361. ):
  1362. """Test the LDAP connection with the form's settings over the saved ones (admin only when auth enabled).
  1363. Works while LDAP is still off. An empty bind password keeps the saved one,
  1364. which only goes to the server it was entered for.
  1365. """
  1366. import logging
  1367. from backend.app.services.ldap_service import parse_ldap_config, test_ldap_connection
  1368. from backend.app.services.secret_fields import SETTINGS_SECRETS, SecretConfigError, merge_partial
  1369. logger = logging.getLogger(__name__)
  1370. result = await db.execute(select(Settings).where(Settings.key.in_(LDAP_SETTING_KEYS)))
  1371. # Unset security is StartTLS, as when saving.
  1372. stored = {"ldap_security": "starttls", **{s.key: s.value for s in result.scalars().all()}}
  1373. form = body.model_dump(exclude_none=True) if body else {}
  1374. if not form.get("ldap_bind_password"):
  1375. form.pop("ldap_bind_password", None)
  1376. try:
  1377. form = merge_partial(stored, form, {"ldap_bind_password": SETTINGS_SECRETS["ldap_bind_password"]})
  1378. except SecretConfigError as e:
  1379. return {"success": False, "message": str(e)}
  1380. config = parse_ldap_config({**stored, **form, "ldap_enabled": "true"})
  1381. if not config:
  1382. return {"success": False, "message": "LDAP server URL is not configured"}
  1383. success, message = test_ldap_connection(config)
  1384. if success:
  1385. logger.info("LDAP connection test successful")
  1386. else:
  1387. logger.warning("LDAP connection test failed: %s", message)
  1388. return {"success": success, "message": message}
  1389. @router.get("/ldap/status")
  1390. async def get_ldap_status(db: AsyncSession = Depends(get_db, scope="function")):
  1391. """Get LDAP authentication status."""
  1392. # Only fetch the minimum keys needed — never load secrets
  1393. ldap_keys = ["ldap_enabled", "ldap_server_url"]
  1394. result = await db.execute(select(Settings).where(Settings.key.in_(ldap_keys)))
  1395. settings = {s.key: s.value for s in result.scalars().all()}
  1396. return {
  1397. "ldap_enabled": settings.get("ldap_enabled", "false").lower() == "true",
  1398. "ldap_configured": bool(settings.get("ldap_server_url")),
  1399. }
  1400. # =============================================================================
  1401. # Manual LDAP user provisioning (#1298)
  1402. # =============================================================================
  1403. # Admins can search the directory and provision users directly from the UI
  1404. # without enabling auto-provision on login. The two endpoints below pair with
  1405. # the new "LDAP" tab in the user-create modal.
  1406. @router.get("/ldap/search", response_model=list[LDAPSearchResultResponse])
  1407. async def search_ldap_directory(
  1408. q: str,
  1409. _admin: User | None = RequireAdminIfAuthEnabled(),
  1410. _: User | None = RequirePermissionIfAuthEnabled(Permission.USERS_CREATE),
  1411. db: AsyncSession = Depends(get_db, scope="function"),
  1412. ):
  1413. """Search the LDAP directory for users matching `q`.
  1414. Returns up to 25 candidates. The query is matched (case-insensitively, with
  1415. wildcards on both sides) against sAMAccountName, uid, mail, displayName,
  1416. and cn — covering both AD and OpenLDAP layouts. Each result is annotated
  1417. with `already_provisioned` so the UI can grey out usernames that already
  1418. exist as BamBuddy users.
  1419. Requires USERS_CREATE permission. Minimum query length is 2 characters.
  1420. """
  1421. from sqlalchemy import func as sa_func
  1422. from backend.app.services.ldap_service import parse_ldap_config, search_ldap_users
  1423. query = q.strip()
  1424. if len(query) < 2:
  1425. raise HTTPException(
  1426. status_code=status.HTTP_400_BAD_REQUEST,
  1427. detail="Query must be at least 2 characters",
  1428. )
  1429. ldap_settings = await _get_ldap_settings(db)
  1430. if not ldap_settings:
  1431. raise HTTPException(
  1432. status_code=status.HTTP_400_BAD_REQUEST,
  1433. detail="LDAP is not enabled",
  1434. )
  1435. config = parse_ldap_config(ldap_settings)
  1436. if not config:
  1437. raise HTTPException(
  1438. status_code=status.HTTP_400_BAD_REQUEST,
  1439. detail="LDAP server URL is not configured",
  1440. )
  1441. try:
  1442. results = search_ldap_users(config, query, limit=25)
  1443. except Exception as e: # SEC-AUTH-EXC: raise 503 (fail-closed); route gated upstream by USERS_CREATE permission so detail leak is admin-only
  1444. _logger.exception("LDAP directory search failed")
  1445. # Admin-only endpoint — surface the underlying reason so the operator
  1446. # can fix it (auth_middleware already restricted access to USERS_CREATE).
  1447. raise HTTPException(
  1448. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  1449. detail=f"LDAP search failed: {type(e).__name__}: {e}",
  1450. )
  1451. if not results:
  1452. return []
  1453. # Annotate `already_provisioned` so the SPA can dim/disable rows that map
  1454. # to an existing local row. Case-insensitive lookup mirrors create_user.
  1455. usernames_lower = [r.username.lower() for r in results]
  1456. existing_query = await db.execute(select(User.username).where(sa_func.lower(User.username).in_(usernames_lower)))
  1457. existing_lower = {str(name).lower() for name in existing_query.scalars().all()}
  1458. return [
  1459. LDAPSearchResultResponse(
  1460. username=r.username,
  1461. email=r.email,
  1462. display_name=r.display_name,
  1463. dn=r.dn,
  1464. already_provisioned=r.username.lower() in existing_lower,
  1465. )
  1466. for r in results
  1467. ]
  1468. @router.post("/ldap/provision", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
  1469. async def provision_ldap_user(
  1470. payload: LDAPProvisionRequest,
  1471. _admin: User | None = RequireAdminIfAuthEnabled(),
  1472. _: User | None = RequirePermissionIfAuthEnabled(Permission.USERS_CREATE),
  1473. db: AsyncSession = Depends(get_db, scope="function"),
  1474. ):
  1475. """Provision a BamBuddy user from an existing LDAP directory entry.
  1476. Re-resolves the username via the service-account bind (rather than trusting
  1477. the request body) so group mappings and email come from a fresh LDAP read.
  1478. Applies the same group-mapping / default-group logic as the auto-provision
  1479. login path (`_provision_ldap_user`), so behavior stays identical regardless
  1480. of whether the user was created here or on first login.
  1481. Admin-only with USERS_CREATE, like users.create_user.
  1482. """
  1483. from sqlalchemy import func as sa_func
  1484. from backend.app.services.ldap_service import lookup_ldap_user, parse_ldap_config
  1485. username = payload.username.strip()
  1486. if not username:
  1487. raise HTTPException(
  1488. status_code=status.HTTP_400_BAD_REQUEST,
  1489. detail="Username is required",
  1490. )
  1491. ldap_settings = await _get_ldap_settings(db)
  1492. if not ldap_settings:
  1493. raise HTTPException(
  1494. status_code=status.HTTP_400_BAD_REQUEST,
  1495. detail="LDAP is not enabled",
  1496. )
  1497. config = parse_ldap_config(ldap_settings)
  1498. if not config:
  1499. raise HTTPException(
  1500. status_code=status.HTTP_400_BAD_REQUEST,
  1501. detail="LDAP server URL is not configured",
  1502. )
  1503. # Look up via service bind. Service-bind failures bubble up as 503; missing
  1504. # entries surface as 404 to distinguish "directory unreachable" from
  1505. # "username doesn't exist in the directory" in the UI.
  1506. try:
  1507. ldap_user = lookup_ldap_user(config, username)
  1508. except Exception as e: # SEC-AUTH-EXC: raise 503 (fail-closed); LDAP provision never succeeds on lookup failure
  1509. _logger.exception("LDAP lookup failed during provision")
  1510. raise HTTPException(
  1511. status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
  1512. detail=f"LDAP lookup failed: {type(e).__name__}: {e}",
  1513. )
  1514. if ldap_user is None:
  1515. raise HTTPException(
  1516. status_code=status.HTTP_404_NOT_FOUND,
  1517. detail=f"User '{username}' not found in LDAP directory",
  1518. )
  1519. # Reject duplicates — the canonical username from LDAP is what gets stored,
  1520. # so the conflict check uses that rather than the request payload.
  1521. existing = await db.execute(select(User).where(sa_func.lower(User.username) == sa_func.lower(ldap_user.username)))
  1522. existing_user = existing.scalar_one_or_none()
  1523. if existing_user is not None:
  1524. if existing_user.auth_source == "ldap":
  1525. detail = f"LDAP user '{ldap_user.username}' is already provisioned"
  1526. else:
  1527. detail = f"A local user with the username '{ldap_user.username}' already exists"
  1528. raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=detail)
  1529. new_user = await _provision_ldap_user(db, ldap_user, config)
  1530. # Reload with groups eagerly loaded so _user_to_response can serialize them
  1531. # without lazy-load warnings (matches create_user / list_users pattern).
  1532. result = await db.execute(select(User).where(User.id == new_user.id).options(selectinload(User.groups)))
  1533. new_user = result.scalar_one()
  1534. _logger.info("Manually provisioned LDAP user %s (id=%d)", new_user.username, new_user.id)
  1535. return _user_to_response(new_user)
  1536. # =============================================================================
  1537. # Long-lived camera-stream tokens (#1108)
  1538. # =============================================================================
  1539. # A token a user can paste into Home Assistant / Frigate / a kiosk and have it
  1540. # keep working for days/weeks rather than refreshing the 60-minute ephemeral
  1541. # token. Permission gate: CAMERA_VIEW (same blast radius as the existing 60-min
  1542. # token-mint endpoint).
  1543. #
  1544. # Two scopes, both minted here — see ALLOWED_SCOPES in services/long_lived_tokens
  1545. # for what each one reaches: "camera_stream" (video only) and "camwall" (video
  1546. # plus the Cam Wall's read-only tile metadata, #2531).
  1547. def _long_lived_token_to_response(record, *, plaintext: str | None = None) -> dict:
  1548. """Serialise a LongLivedToken row for the SPA. Plaintext is included
  1549. only at create time (and then never again), per the issue's "shown once"
  1550. contract.
  1551. """
  1552. return {
  1553. "id": record.id,
  1554. "user_id": record.user_id,
  1555. "name": record.name,
  1556. "scope": record.scope,
  1557. "lookup_prefix": record.lookup_prefix,
  1558. "created_at": record.created_at.isoformat() if record.created_at else None,
  1559. "expires_at": record.expires_at.isoformat() if record.expires_at else None,
  1560. "last_used_at": record.last_used_at.isoformat() if record.last_used_at else None,
  1561. # Plaintext is the ONLY field the user ever sees in full — copied once
  1562. # to a clipboard / kiosk config and then forgotten.
  1563. "token": plaintext,
  1564. }
  1565. @router.post("/tokens", response_model=dict, status_code=status.HTTP_201_CREATED)
  1566. async def create_long_lived_camera_token(
  1567. payload: dict,
  1568. response: Response,
  1569. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1570. db: AsyncSession = Depends(get_db, scope="function"),
  1571. ):
  1572. """Mint a long-lived camera-stream token (#1108).
  1573. Body: ``{"name": str, "expires_in_days": int, "scope": "camera_stream"}``.
  1574. The plaintext token is returned **exactly once** in the response. The DB
  1575. only ever stores a pbkdf2 hash, so a leaked DB dump cannot replay the
  1576. token. Hard cap of 365 days; the issue's ``expire_in: 0`` (never) is
  1577. explicitly rejected.
  1578. """
  1579. from backend.app.services.long_lived_tokens import (
  1580. ALLOWED_SCOPES,
  1581. MAX_TOKEN_LIFETIME_DAYS,
  1582. create_token,
  1583. )
  1584. # Auth-disabled path: tokens are user-owned, but if auth is off there is
  1585. # no user to own them. Refuse rather than silently picking a random user.
  1586. if current_user is None:
  1587. raise HTTPException(
  1588. status_code=status.HTTP_403_FORBIDDEN,
  1589. detail="Long-lived tokens require authentication to be enabled",
  1590. )
  1591. name = payload.get("name")
  1592. if not isinstance(name, str) or not name.strip():
  1593. raise HTTPException(status_code=400, detail="name is required")
  1594. expires_in_days = payload.get("expires_in_days")
  1595. if not isinstance(expires_in_days, int) or expires_in_days <= 0:
  1596. raise HTTPException(
  1597. status_code=400,
  1598. detail=(
  1599. f"expires_in_days must be a positive integer (max {MAX_TOKEN_LIFETIME_DAYS}; #1108: no infinite tokens)"
  1600. ),
  1601. )
  1602. scope = payload.get("scope", "camera_stream")
  1603. if scope not in ALLOWED_SCOPES:
  1604. raise HTTPException(status_code=400, detail=f"unsupported scope: {scope!r}")
  1605. try:
  1606. created = await create_token(
  1607. db,
  1608. user_id=current_user.id,
  1609. name=name,
  1610. expires_in_days=expires_in_days,
  1611. scope=scope,
  1612. )
  1613. except ValueError as e:
  1614. raise HTTPException(status_code=400, detail=str(e))
  1615. _logger.info(
  1616. "Long-lived camera token created: user=%s name=%r scope=%s expires=%s",
  1617. current_user.username,
  1618. name,
  1619. scope,
  1620. created.record.expires_at.isoformat(),
  1621. )
  1622. response.headers["Cache-Control"] = "no-store"
  1623. return _long_lived_token_to_response(created.record, plaintext=created.plaintext)
  1624. @router.get("/tokens", response_model=list[dict])
  1625. async def list_long_lived_tokens(
  1626. user_id: int | None = None,
  1627. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1628. db: AsyncSession = Depends(get_db, scope="function"),
  1629. ):
  1630. """List long-lived tokens.
  1631. Default: caller's own tokens.
  1632. Admins can pass ``?user_id=N`` to see another user's tokens, or omit it
  1633. to see everything (handy for leak triage).
  1634. """
  1635. from backend.app.services.long_lived_tokens import list_user_tokens
  1636. # Auth-disabled installs don't have a notion of "my tokens" — refuse so
  1637. # we don't leak a global list to whoever can hit the API.
  1638. if current_user is None:
  1639. raise HTTPException(
  1640. status_code=status.HTTP_403_FORBIDDEN,
  1641. detail="Long-lived tokens require authentication to be enabled",
  1642. )
  1643. # Reload with groups so is_admin reflects group membership reliably.
  1644. user_with_groups = (
  1645. await db.execute(select(User).where(User.id == current_user.id).options(selectinload(User.groups)))
  1646. ).scalar_one()
  1647. if user_id is None or user_id == current_user.id:
  1648. records = await list_user_tokens(db, current_user.id)
  1649. elif user_with_groups.is_admin:
  1650. records = await list_user_tokens(db, user_id)
  1651. else:
  1652. raise HTTPException(
  1653. status_code=status.HTTP_403_FORBIDDEN,
  1654. detail="Only admins can list other users' tokens",
  1655. )
  1656. return [_long_lived_token_to_response(r) for r in records]
  1657. @router.get("/tokens/all", response_model=list[dict])
  1658. async def list_all_long_lived_tokens(
  1659. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1660. db: AsyncSession = Depends(get_db, scope="function"),
  1661. ):
  1662. """Admin-only: every active long-lived token in the system, newest first.
  1663. Used by the leak-triage view in admin settings.
  1664. """
  1665. from backend.app.services.long_lived_tokens import list_all_tokens
  1666. if current_user is None:
  1667. raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Auth required")
  1668. user_with_groups = (
  1669. await db.execute(select(User).where(User.id == current_user.id).options(selectinload(User.groups)))
  1670. ).scalar_one()
  1671. if not user_with_groups.is_admin:
  1672. raise HTTPException(
  1673. status_code=status.HTTP_403_FORBIDDEN,
  1674. detail="Admin only",
  1675. )
  1676. records = await list_all_tokens(db)
  1677. return [_long_lived_token_to_response(r) for r in records]
  1678. @router.delete("/tokens/{token_id}", status_code=status.HTTP_204_NO_CONTENT)
  1679. async def revoke_long_lived_token(
  1680. token_id: int,
  1681. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1682. db: AsyncSession = Depends(get_db, scope="function"),
  1683. ):
  1684. """Revoke a long-lived token. Owners can revoke their own; admins any."""
  1685. from backend.app.models.long_lived_token import LongLivedToken
  1686. from backend.app.services.long_lived_tokens import revoke_token
  1687. if current_user is None:
  1688. raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Auth required")
  1689. record = (await db.execute(select(LongLivedToken).where(LongLivedToken.id == token_id))).scalar_one_or_none()
  1690. if record is None:
  1691. raise HTTPException(status_code=404, detail="Token not found")
  1692. if record.user_id != current_user.id:
  1693. # Reload for is_admin so admins can revoke any user's token (leak response).
  1694. user_with_groups = (
  1695. await db.execute(select(User).where(User.id == current_user.id).options(selectinload(User.groups)))
  1696. ).scalar_one()
  1697. if not user_with_groups.is_admin:
  1698. raise HTTPException(
  1699. status_code=status.HTTP_403_FORBIDDEN,
  1700. detail="You can only revoke your own tokens",
  1701. )
  1702. revoked = await revoke_token(db, token_id)
  1703. if not revoked:
  1704. # Already revoked is treated as 404 for idempotency from the UI side.
  1705. raise HTTPException(status_code=404, detail="Token not found or already revoked")
  1706. _logger.info(
  1707. "Long-lived camera token revoked: id=%d by user=%s",
  1708. token_id,
  1709. current_user.username,
  1710. )
  1711. return Response(status_code=status.HTTP_204_NO_CONTENT)
  1712. @router.get("/encryption-status", response_model=EncryptionStatusResponse)
  1713. async def get_encryption_status(
  1714. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  1715. db: AsyncSession = Depends(get_db, scope="function"),
  1716. ) -> EncryptionStatusResponse:
  1717. """Report at-rest encryption status for OIDC + TOTP secrets.
  1718. Surfaces:
  1719. (a) whether a key is configured and where it came from
  1720. (b) how many rows are still legacy plaintext
  1721. (c) whether decryption is broken (no key OR key cannot decrypt existing rows)
  1722. (d) the count of rows skipped during the last re-encryption migration
  1723. S2: gated on SETTINGS_UPDATE so Viewers (who only have SETTINGS_READ)
  1724. cannot read encryption-status — admin/operator only.
  1725. """
  1726. from sqlalchemy import case, func, not_, select
  1727. from backend.app.core.database import get_migration_error_count
  1728. from backend.app.core.encryption import get_key_source, is_encryption_active, mfa_decrypt
  1729. from backend.app.models.oidc_provider import OIDCProvider
  1730. from backend.app.models.user_totp import UserTOTP
  1731. key_configured = is_encryption_active()
  1732. key_source = get_key_source() or "none"
  1733. try:
  1734. oidc_row = await db.execute(
  1735. select(
  1736. func.sum(case((not_(OIDCProvider._client_secret_enc.like("fernet:%")), 1), else_=0)),
  1737. func.sum(case((OIDCProvider._client_secret_enc.like("fernet:%"), 1), else_=0)),
  1738. )
  1739. )
  1740. legacy_oidc, encrypted_oidc = oidc_row.one()
  1741. totp_row = await db.execute(
  1742. select(
  1743. func.sum(case((not_(UserTOTP._secret_enc.like("fernet:%")), 1), else_=0)),
  1744. func.sum(case((UserTOTP._secret_enc.like("fernet:%"), 1), else_=0)),
  1745. )
  1746. )
  1747. legacy_totp, encrypted_totp = totp_row.one()
  1748. except SQLAlchemyError:
  1749. _logger.exception("Failed to query encryption row counts")
  1750. raise HTTPException(status_code=500, detail="Failed to retrieve encryption status")
  1751. legacy_plaintext_rows = EncryptionRowCounts(
  1752. oidc_providers=int(legacy_oidc or 0),
  1753. user_totp=int(legacy_totp or 0),
  1754. )
  1755. encrypted_rows = EncryptionRowCounts(
  1756. oidc_providers=int(encrypted_oidc or 0),
  1757. user_totp=int(encrypted_totp or 0),
  1758. )
  1759. # B4: detect "wrong key" state — sample-decrypt one encrypted row to
  1760. # distinguish "no key" from "key configured but cannot decrypt these rows".
  1761. # The legacy computed-field check (key_configured=False AND encrypted>0)
  1762. # missed the case where an operator pasted a different valid Fernet key
  1763. # (rotation, cross-deployment restore, env override) — status would show
  1764. # green while every encrypted row was unrecoverable.
  1765. decryption_broken = False
  1766. total_encrypted = encrypted_rows.oidc_providers + encrypted_rows.user_totp
  1767. if not key_configured and total_encrypted > 0:
  1768. decryption_broken = True
  1769. elif key_configured and total_encrypted > 0:
  1770. sample_value: str | None = None
  1771. try:
  1772. if encrypted_rows.oidc_providers > 0:
  1773. r = await db.execute(
  1774. select(OIDCProvider._client_secret_enc)
  1775. .where(OIDCProvider._client_secret_enc.like("fernet:%"))
  1776. .limit(1)
  1777. )
  1778. sample_value = r.scalar_one_or_none()
  1779. if sample_value is None and encrypted_rows.user_totp > 0:
  1780. r = await db.execute(select(UserTOTP._secret_enc).where(UserTOTP._secret_enc.like("fernet:%")).limit(1))
  1781. sample_value = r.scalar_one_or_none()
  1782. except SQLAlchemyError:
  1783. _logger.exception("Failed to query sample encrypted row for decryption probe")
  1784. # Over-alert is safer than silent corruption — surface as broken.
  1785. decryption_broken = True
  1786. sample_value = None
  1787. if sample_value:
  1788. try:
  1789. mfa_decrypt(sample_value)
  1790. except RuntimeError:
  1791. decryption_broken = True
  1792. return EncryptionStatusResponse(
  1793. key_configured=key_configured,
  1794. key_source=key_source,
  1795. legacy_plaintext_rows=legacy_plaintext_rows,
  1796. encrypted_rows=encrypted_rows,
  1797. decryption_broken=decryption_broken,
  1798. migration_error_count=get_migration_error_count(),
  1799. )