auth.py 81 KB

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