auth.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  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.ext.asyncio import AsyncSession
  12. from sqlalchemy.orm import selectinload
  13. from backend.app.api.routes.settings import get_external_login_url
  14. from backend.app.core.auth import (
  15. ACCESS_TOKEN_EXPIRE_MINUTES,
  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. get_current_active_user,
  26. get_password_hash,
  27. get_user_by_email,
  28. get_user_by_username,
  29. is_jti_revoked,
  30. revoke_jti,
  31. security,
  32. )
  33. from backend.app.core.database import async_session, get_db
  34. from backend.app.core.permissions import ALL_PERMISSIONS
  35. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent, EventType, TokenType
  36. from backend.app.models.group import Group
  37. from backend.app.models.settings import Settings
  38. from backend.app.models.user import User
  39. from backend.app.schemas.auth import (
  40. ForgotPasswordConfirmRequest,
  41. ForgotPasswordRequest,
  42. ForgotPasswordResponse,
  43. GroupBrief,
  44. LoginRequest,
  45. LoginResponse,
  46. ResetPasswordRequest,
  47. ResetPasswordResponse,
  48. SetupRequest,
  49. SetupResponse,
  50. SMTPSettings,
  51. TestSMTPRequest,
  52. TestSMTPResponse,
  53. UserResponse,
  54. _validate_password_complexity,
  55. )
  56. from backend.app.services.email_service import (
  57. create_password_reset_link_email_from_template,
  58. get_smtp_settings,
  59. save_smtp_settings,
  60. send_email,
  61. )
  62. _logger = logging.getLogger(__name__)
  63. def _user_to_response(user: User) -> UserResponse:
  64. """Convert a User model to UserResponse schema."""
  65. return UserResponse(
  66. id=user.id,
  67. username=user.username,
  68. email=user.email,
  69. role=user.role,
  70. is_active=user.is_active,
  71. is_admin=user.is_admin,
  72. auth_source=getattr(user, "auth_source", "local"),
  73. groups=[GroupBrief(id=g.id, name=g.name) for g in user.groups],
  74. permissions=sorted(user.get_permissions()),
  75. created_at=user.created_at.isoformat(),
  76. )
  77. def _api_key_to_user_response(api_key) -> UserResponse:
  78. """Create a synthetic admin UserResponse for a valid API key."""
  79. return UserResponse(
  80. id=0,
  81. username=f"api-key:{api_key.key_prefix}",
  82. email=None,
  83. role="admin",
  84. is_active=True,
  85. is_admin=True,
  86. groups=[],
  87. permissions=sorted(ALL_PERMISSIONS),
  88. created_at=api_key.created_at.isoformat(),
  89. )
  90. # ---------------------------------------------------------------------------
  91. # M-R9-A: Real client IP resolution for rate limiting behind reverse proxies.
  92. # Set TRUSTED_PROXY_IPS (comma-separated) to enable X-Forwarded-For trust.
  93. # Without this env var client.host is used directly (safe default).
  94. # ---------------------------------------------------------------------------
  95. _TRUSTED_PROXY_IPS: frozenset[str] = frozenset(
  96. ip.strip() for ip in os.environ.get("TRUSTED_PROXY_IPS", "").split(",") if ip.strip()
  97. )
  98. def _get_client_ip(request: Request) -> str:
  99. """Return the real client IP for rate-limiting purposes.
  100. When TRUSTED_PROXY_IPS is configured and the direct TCP peer is a trusted
  101. proxy, X-Forwarded-For is evaluated right-to-left: the rightmost IP that is
  102. NOT itself a trusted proxy is the true client address (M-R10-A fix).
  103. Standard nginx with proxy_add_x_forwarded_for *appends* the client IP, so
  104. the rightmost entry is always the one added by the last trusted proxy —
  105. i.e. the real client. Walking right-to-left and skipping known proxies is
  106. safe for multi-hop chains as well.
  107. Falls back to request.client.host when TRUSTED_PROXY_IPS is unset (direct
  108. deployment without a reverse proxy).
  109. """
  110. # I5: Use a per-request unique token instead of "unknown" when the transport
  111. # layer provides no client address. This prevents all such requests from
  112. # sharing one rate-limit bucket, and avoids collision with a literal username
  113. # "unknown". The token is not stable across requests, which is intentional:
  114. # we cannot track the IP so we also cannot rate-limit by it meaningfully.
  115. direct_ip = request.client.host if request.client else f"__no_ip_{secrets.token_hex(8)}__"
  116. if _TRUSTED_PROXY_IPS and direct_ip in _TRUSTED_PROXY_IPS:
  117. forwarded_for = request.headers.get("X-Forwarded-For", "")
  118. ips = [ip.strip() for ip in forwarded_for.split(",") if ip.strip()]
  119. # Walk right-to-left; skip IPs that belong to trusted proxies.
  120. for ip in reversed(ips):
  121. if ip not in _TRUSTED_PROXY_IPS:
  122. return ip
  123. # Edge case: every entry is a trusted proxy — fall back to leftmost.
  124. if ips:
  125. return ips[0]
  126. return direct_ip
  127. router = APIRouter(prefix="/auth", tags=["authentication"])
  128. async def is_auth_enabled(db: AsyncSession) -> bool:
  129. """Check if authentication is enabled."""
  130. result = await db.execute(select(Settings).where(Settings.key == "auth_enabled"))
  131. setting = result.scalar_one_or_none()
  132. if setting is None:
  133. return False
  134. return setting.value.lower() == "true"
  135. async def is_advanced_auth_enabled(db: AsyncSession) -> bool:
  136. """Check if advanced authentication is enabled."""
  137. result = await db.execute(select(Settings).where(Settings.key == "advanced_auth_enabled"))
  138. setting = result.scalar_one_or_none()
  139. if setting is None:
  140. return False
  141. return setting.value.lower() == "true"
  142. async def set_advanced_auth_enabled(db: AsyncSession, enabled: bool) -> None:
  143. """Set advanced authentication enabled status."""
  144. from backend.app.core.db_dialect import upsert_setting
  145. await upsert_setting(db, Settings, "advanced_auth_enabled", "true" if enabled else "false")
  146. async def set_auth_enabled(db: AsyncSession, enabled: bool) -> None:
  147. """Set authentication enabled status."""
  148. from backend.app.core.db_dialect import upsert_setting
  149. await upsert_setting(db, Settings, "auth_enabled", "true" if enabled else "false")
  150. # Note: Don't commit here - let get_db handle it or commit explicitly in the route
  151. async def is_setup_completed(db: AsyncSession) -> bool:
  152. """Check if setup has been completed."""
  153. result = await db.execute(select(Settings).where(Settings.key == "setup_completed"))
  154. setting = result.scalar_one_or_none()
  155. return setting and setting.value.lower() == "true"
  156. async def set_setup_completed(db: AsyncSession, completed: bool) -> None:
  157. """Set setup completed status."""
  158. from backend.app.core.db_dialect import upsert_setting
  159. await upsert_setting(db, Settings, "setup_completed", "true" if completed else "false")
  160. # Note: Don't commit here - let get_db handle it or commit explicitly in the route
  161. @router.post("/setup", response_model=SetupResponse)
  162. async def setup_auth(request: SetupRequest, db: AsyncSession = Depends(get_db)):
  163. """First-time setup: enable/disable authentication and create admin user."""
  164. import logging
  165. logger = logging.getLogger(__name__)
  166. try:
  167. # If auth is currently enabled, block unauthenticated setup changes.
  168. # Use the admin panel (/disable endpoint) to modify auth when it's already on.
  169. if await is_auth_enabled(db):
  170. raise HTTPException(
  171. status_code=status.HTTP_403_FORBIDDEN,
  172. detail="Authentication is already configured. Use the admin panel to modify auth settings.",
  173. )
  174. admin_created = False
  175. if request.auth_enabled:
  176. # Check if admin users already exist
  177. admin_users_result = await db.execute(select(User).where(User.role == "admin"))
  178. existing_admin_users = list(admin_users_result.scalars().all())
  179. has_admin_users = len(existing_admin_users) > 0
  180. if has_admin_users:
  181. # Admin users already exist, just enable auth (don't create new admin)
  182. logger.info(
  183. f"Admin users already exist ({len(existing_admin_users)} found), enabling authentication without creating new admin"
  184. )
  185. admin_created = False
  186. else:
  187. # No admin users exist, require admin credentials to create first admin
  188. if not request.admin_username or not request.admin_password:
  189. raise HTTPException(
  190. status_code=status.HTTP_400_BAD_REQUEST,
  191. detail="Admin username and password are required when enabling authentication (no admin users exist)",
  192. )
  193. # Enforce password complexity only when actually creating a new admin.
  194. # Schema-level validation was removed so that re-enabling auth with an
  195. # existing admin (or LDAP) doesn't reject whatever placeholder the form sends.
  196. try:
  197. _validate_password_complexity(request.admin_password)
  198. except ValueError as exc:
  199. raise HTTPException(
  200. status_code=status.HTTP_400_BAD_REQUEST,
  201. detail=str(exc),
  202. )
  203. # Check if username already exists (shouldn't happen if no admin users exist, but check anyway)
  204. existing_user = await get_user_by_username(db, request.admin_username)
  205. if existing_user:
  206. raise HTTPException(
  207. status_code=status.HTTP_400_BAD_REQUEST,
  208. detail="User with this username already exists",
  209. )
  210. # Create admin user FIRST (before enabling auth)
  211. try:
  212. logger.info("Creating admin user: %s", request.admin_username)
  213. admin_user = User(
  214. username=request.admin_username,
  215. password_hash=get_password_hash(request.admin_password),
  216. role="admin",
  217. is_active=True,
  218. )
  219. # Try to add user to Administrators group if it exists
  220. admin_group_result = await db.execute(select(Group).where(Group.name == "Administrators"))
  221. admin_group = admin_group_result.scalar_one_or_none()
  222. if admin_group:
  223. admin_user.groups.append(admin_group)
  224. logger.info("Added new admin user to Administrators group")
  225. db.add(admin_user)
  226. logger.info("Admin user added to session: %s", request.admin_username)
  227. admin_created = True
  228. except Exception as e:
  229. await db.rollback()
  230. logger.error("Failed to create admin user: %s", e, exc_info=True)
  231. raise HTTPException(
  232. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  233. detail="Failed to create admin user",
  234. )
  235. # Set auth enabled and mark setup as completed
  236. await set_auth_enabled(db, request.auth_enabled)
  237. await set_setup_completed(db, True)
  238. await db.commit()
  239. if admin_created:
  240. await db.refresh(admin_user)
  241. logger.info("Admin user created successfully: %s", admin_user.id)
  242. logger.info("Setup completed: auth_enabled=%s, admin_created=%s", request.auth_enabled, admin_created)
  243. return SetupResponse(auth_enabled=request.auth_enabled, admin_created=admin_created)
  244. except HTTPException:
  245. raise
  246. except Exception as e:
  247. logger.error("Setup error: %s", e, exc_info=True)
  248. await db.rollback()
  249. raise HTTPException(
  250. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  251. detail="Setup failed",
  252. )
  253. @router.get("/status")
  254. async def get_auth_status(db: AsyncSession = Depends(get_db)):
  255. """Get authentication status (public endpoint)."""
  256. auth_enabled = await is_auth_enabled(db)
  257. setup_completed = await is_setup_completed(db)
  258. # Only require setup if it hasn't been completed yet
  259. requires_setup = not setup_completed
  260. return {"auth_enabled": auth_enabled, "requires_setup": requires_setup}
  261. @router.post("/disable", response_model=dict)
  262. async def disable_auth(
  263. current_user: User = Depends(get_current_active_user),
  264. db: AsyncSession = Depends(get_db),
  265. ):
  266. """Disable authentication (admin only)."""
  267. import logging
  268. logger = logging.getLogger(__name__)
  269. # Reload user with groups for proper is_admin check
  270. result = await db.execute(select(User).where(User.id == current_user.id).options(selectinload(User.groups)))
  271. user = result.scalar_one()
  272. # Only admins can disable authentication
  273. if not user.is_admin:
  274. raise HTTPException(
  275. status_code=status.HTTP_403_FORBIDDEN,
  276. detail="Only admins can disable authentication",
  277. )
  278. try:
  279. await set_auth_enabled(db, False)
  280. await db.commit()
  281. logger.info("Authentication disabled by admin user: %s", user.username)
  282. return {"message": "Authentication disabled successfully", "auth_enabled": False}
  283. except Exception as e:
  284. await db.rollback()
  285. logger.error("Failed to disable authentication: %s", e, exc_info=True)
  286. raise HTTPException(
  287. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  288. detail="Failed to disable authentication",
  289. )
  290. @router.post("/login", response_model=LoginResponse)
  291. async def login(raw_request: Request, request: LoginRequest, response: Response, db: AsyncSession = Depends(get_db)):
  292. """Login and get access token.
  293. Supports username or email-based login. Username lookup is case-insensitive.
  294. When 2FA is enabled for the user the response contains ``requires_2fa=True``
  295. and a short-lived ``pre_auth_token`` instead of the final JWT. The client
  296. must then call ``POST /auth/2fa/verify`` (or first ``POST /auth/2fa/email/send``
  297. to trigger an email OTP) to obtain the real access token.
  298. """
  299. # Check if auth is enabled
  300. auth_enabled = await is_auth_enabled(db)
  301. if not auth_enabled:
  302. raise HTTPException(
  303. status_code=status.HTTP_400_BAD_REQUEST,
  304. detail="Authentication is not enabled",
  305. )
  306. # Rate-limit repeated login failures — two independent buckets (M-R5-B / M-R6-A):
  307. # 1. Per-username (10/15 min): prevents password brute-force on a known account.
  308. # 2. Per-IP (20/15 min): prevents an attacker from locking out arbitrary accounts
  309. # (DoS) by sending failures for many usernames from a single address.
  310. from backend.app.api.routes.mfa import MAX_LOGIN_ATTEMPTS, check_rate_limit, record_failed_attempt
  311. await check_rate_limit(db, request.username, event_type=EventType.LOGIN_ATTEMPT, max_attempts=MAX_LOGIN_ATTEMPTS)
  312. client_ip = _get_client_ip(raw_request)
  313. await check_rate_limit(db, client_ip, event_type=EventType.LOGIN_IP, max_attempts=20)
  314. # Check if LDAP is enabled
  315. ldap_user = None
  316. ldap_settings = await _get_ldap_settings(db)
  317. if ldap_settings:
  318. try:
  319. from backend.app.services.ldap_service import (
  320. authenticate_ldap_user,
  321. parse_ldap_config,
  322. )
  323. ldap_config = parse_ldap_config(ldap_settings)
  324. if ldap_config:
  325. ldap_user = authenticate_ldap_user(ldap_config, request.username, request.password)
  326. if ldap_user:
  327. # LDAP auth succeeded — find or create local user
  328. user = await get_user_by_username(db, ldap_user.username)
  329. if user and user.auth_source != "ldap":
  330. # Username exists as local user — don't override
  331. user = None
  332. ldap_user = None
  333. elif not user:
  334. if not ldap_config.auto_provision:
  335. # User doesn't exist and auto-provision is off
  336. ldap_user = None
  337. else:
  338. # Auto-provision LDAP user
  339. user = await _provision_ldap_user(db, ldap_user, ldap_config)
  340. if user and ldap_user:
  341. # Update email and group mappings on each login
  342. await _sync_ldap_user(db, user, ldap_user, ldap_config)
  343. except Exception as e:
  344. import logging
  345. logging.getLogger(__name__).warning("LDAP authentication error, falling back to local: %s", e)
  346. ldap_user = None
  347. # Try username-based authentication (skip if already authenticated via LDAP)
  348. if not ldap_user:
  349. user = await authenticate_user(db, request.username, request.password)
  350. # If username auth failed and advanced auth is enabled, try email-based authentication
  351. if not user and not ldap_user:
  352. advanced_auth = await is_advanced_auth_enabled(db)
  353. if advanced_auth:
  354. user = await authenticate_user_by_email(db, request.username, request.password)
  355. if not user:
  356. await record_failed_attempt(db, request.username, event_type=EventType.LOGIN_ATTEMPT)
  357. await record_failed_attempt(db, client_ip, event_type=EventType.LOGIN_IP)
  358. raise HTTPException(
  359. status_code=status.HTTP_401_UNAUTHORIZED,
  360. detail="Incorrect username or password",
  361. headers={"WWW-Authenticate": "Bearer"},
  362. )
  363. # Reload user with groups for proper permission calculation
  364. result = await db.execute(select(User).where(User.id == user.id).options(selectinload(User.groups)))
  365. user = result.scalar_one()
  366. # L-R6-A: Password was correct — reset login failure counters for both buckets
  367. from backend.app.api.routes.mfa import clear_failed_attempts
  368. await clear_failed_attempts(db, user.username, event_type=EventType.LOGIN_ATTEMPT)
  369. await clear_failed_attempts(db, client_ip, event_type=EventType.LOGIN_IP)
  370. # --- 2FA check ---
  371. # Determine which 2FA methods are active for this user.
  372. from backend.app.models.settings import Settings as _Settings
  373. from backend.app.models.user_totp import UserTOTP
  374. totp_result = await db.execute(select(UserTOTP).where(UserTOTP.user_id == user.id))
  375. user_totp = totp_result.scalar_one_or_none()
  376. totp_enabled = user_totp is not None and user_totp.is_enabled
  377. email_2fa_result = await db.execute(select(_Settings).where(_Settings.key == f"user_{user.id}_email_2fa_enabled"))
  378. email_2fa_setting = email_2fa_result.scalar_one_or_none()
  379. email_otp_enabled = (
  380. email_2fa_setting is not None and email_2fa_setting.value.lower() == "true" and user.email is not None
  381. )
  382. if totp_enabled or email_otp_enabled:
  383. # Import here to avoid circular imports
  384. from backend.app.api.routes.mfa import create_pre_auth_token
  385. # Bind the pre_auth_token to an HttpOnly cookie so XSS cannot steal the
  386. # token from JS memory and complete 2FA from a different client.
  387. challenge_id = secrets.token_urlsafe(32)
  388. pre_auth_token = await create_pre_auth_token(db, user.username, challenge_id=challenge_id)
  389. response.set_cookie(
  390. key="2fa_challenge",
  391. value=challenge_id,
  392. httponly=True,
  393. # H-1: only transmit over HTTPS so the binding cookie can't be intercepted
  394. # on mixed-content deployments. Falls back to False on plain HTTP so tests
  395. # and local development still work (the client wouldn't send it otherwise).
  396. secure=raw_request.url.scheme == "https",
  397. samesite="lax",
  398. max_age=300,
  399. path="/api/v1/auth/2fa",
  400. )
  401. methods: list[str] = []
  402. if totp_enabled:
  403. methods.append("totp")
  404. if email_otp_enabled:
  405. methods.append("email")
  406. # Backup codes are always available when TOTP is set up
  407. if totp_enabled:
  408. methods.append("backup")
  409. return LoginResponse(
  410. requires_2fa=True,
  411. pre_auth_token=pre_auth_token,
  412. two_fa_methods=methods,
  413. )
  414. # No 2FA — issue full token immediately
  415. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  416. access_token = create_access_token(data={"sub": user.username}, expires_delta=access_token_expires)
  417. return LoginResponse(
  418. access_token=access_token,
  419. token_type="bearer",
  420. user=_user_to_response(user),
  421. )
  422. @router.get("/me", response_model=UserResponse)
  423. async def get_current_user_info(
  424. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  425. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  426. db: AsyncSession = Depends(get_db),
  427. ):
  428. """Get current user information.
  429. Accepts JWT tokens (via Authorization: Bearer header) and API keys
  430. (via X-API-Key header or Authorization: Bearer bb_xxx).
  431. API keys return a synthetic admin user with all permissions.
  432. """
  433. import jwt
  434. from jwt.exceptions import PyJWTError as JWTError
  435. # Check for API key via X-API-Key header
  436. if x_api_key:
  437. api_key = await _validate_api_key(db, x_api_key)
  438. if api_key:
  439. return _api_key_to_user_response(api_key)
  440. # Check for Bearer token (could be JWT or API key)
  441. if credentials is not None:
  442. token = credentials.credentials
  443. # Check if it's an API key (starts with bb_)
  444. if token.startswith("bb_"):
  445. api_key = await _validate_api_key(db, token)
  446. if api_key:
  447. return _api_key_to_user_response(api_key)
  448. raise HTTPException(
  449. status_code=status.HTTP_401_UNAUTHORIZED,
  450. detail="Invalid API key",
  451. headers={"WWW-Authenticate": "Bearer"},
  452. )
  453. # Otherwise treat as JWT
  454. try:
  455. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  456. username: str = payload.get("sub")
  457. if username is None:
  458. raise HTTPException(
  459. status_code=status.HTTP_401_UNAUTHORIZED,
  460. detail="Could not validate credentials",
  461. headers={"WWW-Authenticate": "Bearer"},
  462. )
  463. jti: str | None = payload.get("jti")
  464. if not jti or await is_jti_revoked(jti): # B1: logout bypass fix
  465. raise HTTPException(
  466. status_code=status.HTTP_401_UNAUTHORIZED,
  467. detail="Could not validate credentials",
  468. headers={"WWW-Authenticate": "Bearer"},
  469. )
  470. iat: int | float | None = payload.get("iat")
  471. except JWTError:
  472. raise HTTPException(
  473. status_code=status.HTTP_401_UNAUTHORIZED,
  474. detail="Could not validate credentials",
  475. headers={"WWW-Authenticate": "Bearer"},
  476. )
  477. user = await get_user_by_username(db, username)
  478. if user is None or not user.is_active:
  479. raise HTTPException(
  480. status_code=status.HTTP_401_UNAUTHORIZED,
  481. detail="Could not validate credentials",
  482. headers={"WWW-Authenticate": "Bearer"},
  483. )
  484. # Reload with groups for proper permission calculation
  485. result = await db.execute(select(User).where(User.id == user.id).options(selectinload(User.groups)))
  486. user = result.scalar_one()
  487. # L-R8-A: reject tokens issued before the last password change
  488. if not _is_token_fresh(iat, user):
  489. raise HTTPException(
  490. status_code=status.HTTP_401_UNAUTHORIZED,
  491. detail="Could not validate credentials",
  492. headers={"WWW-Authenticate": "Bearer"},
  493. )
  494. return _user_to_response(user)
  495. # No credentials provided
  496. raise HTTPException(
  497. status_code=status.HTTP_401_UNAUTHORIZED,
  498. detail="Authentication required",
  499. headers={"WWW-Authenticate": "Bearer"},
  500. )
  501. @router.post("/logout")
  502. async def logout(
  503. raw_request: Request,
  504. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  505. ):
  506. """Logout — revokes the current JWT so it cannot be reused after logout."""
  507. if credentials is not None:
  508. raw_token = credentials.credentials
  509. # Nit2: Verify signature before revoking to prevent DoS-revoke attacks
  510. # (an attacker crafting a token with an arbitrary jti cannot force
  511. # revocation of a legitimate token because the signature check rejects it).
  512. # Expired tokens are still accepted — the user is logging out and their
  513. # token may have just expired; we still want to record the revocation.
  514. try:
  515. verified = _jwt.decode(
  516. raw_token,
  517. SECRET_KEY,
  518. algorithms=[ALGORITHM],
  519. options={"verify_exp": False}, # allow expired tokens at logout
  520. )
  521. jti: str | None = verified.get("jti")
  522. exp = verified.get("exp")
  523. username: str | None = verified.get("sub")
  524. if jti and exp:
  525. expires_at = datetime.fromtimestamp(exp, tz=timezone.utc)
  526. try:
  527. await revoke_jti(jti, expires_at, username)
  528. except Exception as exc:
  529. _logger.error("Failed to revoke JTI on logout for user %s: %s", username, exc)
  530. except PyJWTError:
  531. client_ip = _get_client_ip(raw_request)
  532. ua = raw_request.headers.get("user-agent", "<unknown>")
  533. _logger.error(
  534. "Logout received token that failed signature verification — skipping revocation "
  535. "(possible tamper attempt; ip=%s ua=%s)",
  536. client_ip,
  537. ua,
  538. )
  539. return {"message": "Logged out successfully"}
  540. # Advanced Authentication Endpoints
  541. @router.post("/smtp/test", response_model=TestSMTPResponse)
  542. async def test_smtp_connection(
  543. test_request: TestSMTPRequest,
  544. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  545. db: AsyncSession = Depends(get_db),
  546. ):
  547. """Test SMTP connection using saved settings (admin only when auth enabled)."""
  548. import logging
  549. logger = logging.getLogger(__name__)
  550. try:
  551. smtp_settings = await get_smtp_settings(db)
  552. if not smtp_settings:
  553. return TestSMTPResponse(success=False, message="SMTP settings not configured. Save SMTP settings first.")
  554. # Send test email
  555. send_email(
  556. smtp_settings=smtp_settings,
  557. to_email=test_request.test_recipient,
  558. subject="BamBuddy SMTP Test",
  559. body_text="This is a test email from BamBuddy. If you received this, your SMTP settings are working correctly!",
  560. 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>",
  561. )
  562. logger.info(f"Test email sent successfully to {test_request.test_recipient}")
  563. return TestSMTPResponse(success=True, message="Test email sent successfully")
  564. except Exception as e:
  565. logger.error("Failed to send test email: %s", e)
  566. return TestSMTPResponse(success=False, message="Failed to send test email")
  567. @router.get("/smtp", response_model=SMTPSettings | None)
  568. async def get_smtp_config(
  569. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  570. db: AsyncSession = Depends(get_db),
  571. ):
  572. """Get SMTP settings (admin only when auth enabled). Password is not returned."""
  573. smtp_settings = await get_smtp_settings(db)
  574. if smtp_settings:
  575. # Don't return password in response
  576. smtp_settings.smtp_password = None
  577. return smtp_settings
  578. @router.post("/smtp", response_model=dict)
  579. async def save_smtp_config(
  580. smtp_settings: SMTPSettings,
  581. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  582. db: AsyncSession = Depends(get_db),
  583. ):
  584. """Save SMTP settings (admin only when auth enabled)."""
  585. import logging
  586. logger = logging.getLogger(__name__)
  587. try:
  588. await save_smtp_settings(db, smtp_settings)
  589. await db.commit()
  590. logger.info(f"SMTP settings updated by admin user: {current_user.username if current_user else 'anonymous'}")
  591. return {"message": "SMTP settings saved successfully"}
  592. except Exception as e:
  593. await db.rollback()
  594. logger.error("Failed to save SMTP settings: %s", e)
  595. raise HTTPException(
  596. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  597. detail="Failed to save SMTP settings",
  598. )
  599. @router.post("/advanced-auth/enable", response_model=dict)
  600. async def enable_advanced_auth(
  601. current_user: User = Depends(get_current_active_user),
  602. db: AsyncSession = Depends(get_db),
  603. ):
  604. """Enable advanced authentication (admin only).
  605. Requires SMTP settings to be configured and tested first.
  606. """
  607. import logging
  608. logger = logging.getLogger(__name__)
  609. # Reload user with groups for proper is_admin check
  610. result = await db.execute(select(User).where(User.id == current_user.id).options(selectinload(User.groups)))
  611. user = result.scalar_one()
  612. if not user.is_admin:
  613. raise HTTPException(
  614. status_code=status.HTTP_403_FORBIDDEN,
  615. detail="Only admins can enable advanced authentication",
  616. )
  617. # Verify SMTP settings are configured
  618. smtp_settings = await get_smtp_settings(db)
  619. if not smtp_settings:
  620. raise HTTPException(
  621. status_code=status.HTTP_400_BAD_REQUEST,
  622. detail="SMTP settings must be configured before enabling advanced authentication",
  623. )
  624. try:
  625. await set_advanced_auth_enabled(db, True)
  626. await db.commit()
  627. logger.info(f"Advanced authentication enabled by admin user: {user.username}")
  628. return {"message": "Advanced authentication enabled successfully", "advanced_auth_enabled": True}
  629. except Exception as e:
  630. await db.rollback()
  631. logger.error("Failed to enable advanced authentication: %s", e)
  632. raise HTTPException(
  633. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  634. detail="Failed to enable advanced authentication",
  635. )
  636. @router.post("/advanced-auth/disable", response_model=dict)
  637. async def disable_advanced_auth(
  638. current_user: User = Depends(get_current_active_user),
  639. db: AsyncSession = Depends(get_db),
  640. ):
  641. """Disable advanced authentication (admin only)."""
  642. import logging
  643. logger = logging.getLogger(__name__)
  644. # Reload user with groups for proper is_admin check
  645. result = await db.execute(select(User).where(User.id == current_user.id).options(selectinload(User.groups)))
  646. user = result.scalar_one()
  647. if not user.is_admin:
  648. raise HTTPException(
  649. status_code=status.HTTP_403_FORBIDDEN,
  650. detail="Only admins can disable advanced authentication",
  651. )
  652. try:
  653. await set_advanced_auth_enabled(db, False)
  654. await db.commit()
  655. logger.info(f"Advanced authentication disabled by admin user: {user.username}")
  656. return {"message": "Advanced authentication disabled successfully", "advanced_auth_enabled": False}
  657. except Exception as e:
  658. await db.rollback()
  659. logger.error("Failed to disable advanced authentication: %s", e)
  660. raise HTTPException(
  661. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  662. detail="Failed to disable advanced authentication",
  663. )
  664. @router.get("/advanced-auth/status")
  665. async def get_advanced_auth_status(db: AsyncSession = Depends(get_db)):
  666. """Get advanced authentication status."""
  667. advanced_auth_enabled = await is_advanced_auth_enabled(db)
  668. smtp_configured = await get_smtp_settings(db) is not None
  669. return {
  670. "advanced_auth_enabled": advanced_auth_enabled,
  671. "smtp_configured": smtp_configured,
  672. }
  673. # TTL for password-reset tokens (H-6)
  674. _RESET_TOKEN_TTL = timedelta(hours=1)
  675. # Rate-limit for password-reset email sends per identifier (M-A)
  676. _MAX_PWD_RESET_SENDS = 3
  677. _PWD_RESET_SEND_WINDOW = timedelta(minutes=15)
  678. # L-NEW-6: per-IP cap to prevent mass-reset flooding across many addresses
  679. _MAX_PWD_RESET_SENDS_PER_IP = 10
  680. async def _send_reset_email_or_delete_token(
  681. reset_token: str,
  682. smtp_settings,
  683. to_email: str,
  684. subject: str,
  685. text_body: str,
  686. html_body: str,
  687. log_label: str,
  688. ) -> None:
  689. """Background task: send a password-reset email and delete the token on failure.
  690. C1: FastAPI silently swallows BackgroundTask exceptions. This wrapper
  691. catches send failures, deletes the single-use token so it cannot be used
  692. (user is not locked out forever — they can request a new link), and logs at
  693. ERROR so operators are alerted without leaking details to the caller.
  694. """
  695. try:
  696. send_email(smtp_settings, to_email, subject, text_body, html_body)
  697. _logger.info("Password reset email sent (%s) to %s", log_label, to_email)
  698. except Exception as exc:
  699. _logger.error(
  700. "Password reset email failed (%s) to %s — deleting token to unblock re-request: %s",
  701. log_label,
  702. to_email,
  703. exc,
  704. )
  705. try:
  706. async with async_session() as db:
  707. await db.execute(
  708. delete(AuthEphemeralToken).where(
  709. AuthEphemeralToken.token == reset_token,
  710. AuthEphemeralToken.token_type == TokenType.PASSWORD_RESET,
  711. )
  712. )
  713. await db.commit()
  714. except Exception as db_exc:
  715. _logger.error("Failed to delete reset token after send failure: %s", db_exc)
  716. @router.post("/forgot-password", response_model=ForgotPasswordResponse)
  717. async def forgot_password(
  718. request: ForgotPasswordRequest,
  719. background_tasks: BackgroundTasks,
  720. raw_request: Request,
  721. db: AsyncSession = Depends(get_db),
  722. ):
  723. """Request password reset via email (advanced auth only).
  724. H-6: Issues a short-lived single-use reset token and emails the user a
  725. secure link instead of a plaintext temporary password. The new password is
  726. set only when the user clicks the link and POSTs to /forgot-password/confirm.
  727. """
  728. # Check if advanced auth is enabled
  729. advanced_auth = await is_advanced_auth_enabled(db)
  730. if not advanced_auth:
  731. raise HTTPException(
  732. status_code=status.HTTP_400_BAD_REQUEST,
  733. detail="Advanced authentication is not enabled",
  734. )
  735. # M-A: Rate-limit by normalised email to prevent reset-email flooding.
  736. # Apply unconditionally (before the user lookup) so unknown emails are also
  737. # throttled — this prevents both flooding and timing-based enumeration.
  738. identifier = request.email.lower()
  739. cutoff = datetime.now(timezone.utc) - _PWD_RESET_SEND_WINDOW
  740. rate_result = await db.execute(
  741. select(AuthRateLimitEvent).where(
  742. AuthRateLimitEvent.username == identifier,
  743. AuthRateLimitEvent.event_type == EventType.PASSWORD_RESET_SEND,
  744. AuthRateLimitEvent.occurred_at > cutoff,
  745. )
  746. )
  747. if len(rate_result.scalars().all()) >= _MAX_PWD_RESET_SENDS:
  748. raise HTTPException(
  749. status_code=status.HTTP_429_TOO_MANY_REQUESTS,
  750. detail=f"Too many password reset requests. Please wait {_PWD_RESET_SEND_WINDOW.seconds // 60} minutes.",
  751. )
  752. # L-NEW-6: per-IP rate limit — prevents mass-reset flooding across many
  753. # different email addresses from a single source IP.
  754. client_ip = _get_client_ip(raw_request)
  755. ip_rate_result = await db.execute(
  756. select(AuthRateLimitEvent).where(
  757. AuthRateLimitEvent.username == client_ip,
  758. AuthRateLimitEvent.event_type == EventType.PASSWORD_RESET_IP,
  759. AuthRateLimitEvent.occurred_at > cutoff,
  760. )
  761. )
  762. if len(ip_rate_result.scalars().all()) >= _MAX_PWD_RESET_SENDS_PER_IP:
  763. raise HTTPException(
  764. status_code=status.HTTP_429_TOO_MANY_REQUESTS,
  765. detail=f"Too many password reset requests. Please wait {_PWD_RESET_SEND_WINDOW.seconds // 60} minutes.",
  766. )
  767. # Nit7: Always record the IP-level event (prevents spray attacks across many
  768. # different email addresses from one IP). The email-level event is only
  769. # recorded when we actually send an email to a local user — LDAP/OIDC users
  770. # do not consume a slot because this flow is a no-op for them.
  771. db.add(AuthRateLimitEvent(username=client_ip, event_type=EventType.PASSWORD_RESET_IP))
  772. await db.commit()
  773. # Get SMTP settings
  774. smtp_settings = await get_smtp_settings(db)
  775. if not smtp_settings:
  776. raise HTTPException(
  777. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  778. detail="Email service is not configured",
  779. )
  780. # Find user by email — always return success to prevent email enumeration.
  781. user = await get_user_by_email(db, request.email)
  782. # M-1: exclude LDAP and OIDC users — they must use their respective provider.
  783. if user and user.is_active and user.auth_source not in ("ldap", "oidc"):
  784. try:
  785. # Record email-level slot only for local users who will actually receive
  786. # the reset email (Nit7: don't waste the user's quota for LDAP/OIDC no-ops).
  787. db.add(AuthRateLimitEvent(username=identifier, event_type=EventType.PASSWORD_RESET_SEND))
  788. now = datetime.now(timezone.utc)
  789. # Prune any outstanding reset tokens for this user before issuing a new one.
  790. await db.execute(
  791. delete(AuthEphemeralToken).where(
  792. AuthEphemeralToken.token_type == TokenType.PASSWORD_RESET,
  793. AuthEphemeralToken.username == user.username,
  794. )
  795. )
  796. reset_token = secrets.token_urlsafe(32)
  797. db.add(
  798. AuthEphemeralToken(
  799. token=reset_token,
  800. token_type=TokenType.PASSWORD_RESET,
  801. username=user.username,
  802. expires_at=now + _RESET_TOKEN_TTL,
  803. )
  804. )
  805. await db.commit()
  806. login_url = await get_external_login_url(db)
  807. # M-B: Deliver token in the URL fragment so it never reaches the server
  808. # in access-logs or Referer headers (mirrors H-4 for the OIDC token).
  809. reset_url = f"{login_url}#reset_token={reset_token}"
  810. subject, text_body, html_body = await create_password_reset_link_email_from_template(
  811. db, user.username, reset_url
  812. )
  813. # L-R9-B: send asynchronously so response time is independent of
  814. # whether the user exists (prevents email-existence timing oracle).
  815. # C1: wrapper deletes the token if SMTP fails so the user can re-request.
  816. background_tasks.add_task(
  817. _send_reset_email_or_delete_token,
  818. reset_token,
  819. smtp_settings,
  820. user.email,
  821. subject,
  822. text_body,
  823. html_body,
  824. "forgot_password",
  825. )
  826. _logger.info("Password reset email queued for %s", user.email)
  827. except Exception as e:
  828. _logger.error("Failed to send password reset email: %s", e)
  829. # Don't reveal error to caller for security
  830. return ForgotPasswordResponse(
  831. message="If the email address is associated with an account, a password reset email has been sent."
  832. )
  833. @router.post("/forgot-password/confirm", response_model=ForgotPasswordResponse)
  834. async def forgot_password_confirm(request: ForgotPasswordConfirmRequest, db: AsyncSession = Depends(get_db)):
  835. """Complete a password reset by supplying the token from the reset email.
  836. H-6: Atomically consumes the single-use token (DELETE…RETURNING) and sets
  837. the new password. Expired or already-used tokens are silently rejected with
  838. the same response to prevent oracle attacks.
  839. """
  840. now = datetime.now(timezone.utc)
  841. result = await db.execute(
  842. delete(AuthEphemeralToken)
  843. .where(
  844. AuthEphemeralToken.token == request.token,
  845. AuthEphemeralToken.token_type == TokenType.PASSWORD_RESET,
  846. )
  847. .returning(AuthEphemeralToken.username, AuthEphemeralToken.expires_at)
  848. )
  849. row = result.one_or_none()
  850. await db.commit()
  851. if row is None:
  852. raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid or expired password reset token")
  853. username, expires_at = row
  854. # SQLite returns naive datetimes; treat them as UTC.
  855. if expires_at.tzinfo is None:
  856. expires_at = expires_at.replace(tzinfo=timezone.utc)
  857. if now > expires_at:
  858. raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid or expired password reset token")
  859. user = await get_user_by_username(db, username)
  860. # M-1: block LDAP/OIDC users — they authenticate via their provider, not local password.
  861. if not user or not user.is_active or user.auth_source in ("ldap", "oidc"):
  862. raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid or expired password reset token")
  863. user.password_hash = get_password_hash(request.new_password)
  864. user.password_changed_at = now # M-R7-B: invalidate all prior JWTs
  865. await db.commit()
  866. _logger.info("Password reset completed for user '%s'", username)
  867. return ForgotPasswordResponse(message="Password has been reset successfully.")
  868. @router.post("/reset-password", response_model=ResetPasswordResponse)
  869. async def reset_user_password(
  870. request: ResetPasswordRequest,
  871. background_tasks: BackgroundTasks,
  872. current_user: User = Depends(get_current_active_user),
  873. db: AsyncSession = Depends(get_db),
  874. ):
  875. """Reset a user's password and send them an email (admin only, advanced auth only)."""
  876. # Reload user with groups for proper is_admin check
  877. result = await db.execute(select(User).where(User.id == current_user.id).options(selectinload(User.groups)))
  878. admin_user = result.scalar_one()
  879. if not admin_user.is_admin:
  880. raise HTTPException(
  881. status_code=status.HTTP_403_FORBIDDEN,
  882. detail="Only admins can reset user passwords",
  883. )
  884. # Check if advanced auth is enabled
  885. advanced_auth = await is_advanced_auth_enabled(db)
  886. if not advanced_auth:
  887. raise HTTPException(
  888. status_code=status.HTTP_400_BAD_REQUEST,
  889. detail="Advanced authentication is not enabled",
  890. )
  891. # Get SMTP settings
  892. smtp_settings = await get_smtp_settings(db)
  893. if not smtp_settings:
  894. raise HTTPException(
  895. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  896. detail="Email service is not configured",
  897. )
  898. # Find user to reset
  899. result = await db.execute(select(User).where(User.id == request.user_id))
  900. user = result.scalar_one_or_none()
  901. if not user:
  902. raise HTTPException(
  903. status_code=status.HTTP_404_NOT_FOUND,
  904. detail="User not found",
  905. )
  906. # M-1: block LDAP/OIDC users — passwords are managed by their respective providers.
  907. if user.auth_source in ("ldap", "oidc"):
  908. raise HTTPException(
  909. status_code=status.HTTP_400_BAD_REQUEST,
  910. detail="Cannot reset password for LDAP/OIDC users — authentication is managed by their provider",
  911. )
  912. if not user.email:
  913. raise HTTPException(
  914. status_code=status.HTTP_400_BAD_REQUEST,
  915. detail="User does not have an email address configured",
  916. )
  917. try:
  918. # H-B: Issue a single-use reset link instead of generating a plaintext password.
  919. # The admin never sees the credential — the user sets their own password.
  920. now = datetime.now(timezone.utc)
  921. await db.execute(
  922. delete(AuthEphemeralToken).where(
  923. AuthEphemeralToken.token_type == TokenType.PASSWORD_RESET,
  924. AuthEphemeralToken.username == user.username,
  925. )
  926. )
  927. reset_token = secrets.token_urlsafe(32)
  928. db.add(
  929. AuthEphemeralToken(
  930. token=reset_token,
  931. token_type=TokenType.PASSWORD_RESET,
  932. username=user.username,
  933. expires_at=now + _RESET_TOKEN_TTL,
  934. )
  935. )
  936. await db.commit()
  937. login_url = await get_external_login_url(db)
  938. reset_url = f"{login_url}#reset_token={reset_token}"
  939. subject, text_body, html_body = await create_password_reset_link_email_from_template(
  940. db, user.username, reset_url
  941. )
  942. background_tasks.add_task(
  943. _send_reset_email_or_delete_token,
  944. reset_token,
  945. smtp_settings,
  946. user.email,
  947. subject,
  948. text_body,
  949. html_body,
  950. "admin_reset",
  951. )
  952. _logger.info("Admin password reset link queued for user '%s' by admin '%s'", user.username, admin_user.username)
  953. return ResetPasswordResponse(message=f"Password reset link sent to {user.email}")
  954. except Exception as e:
  955. await db.rollback()
  956. _logger.error("Failed to send admin password reset for user '%s': %s", user.username, e)
  957. raise HTTPException(
  958. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  959. detail="Failed to send password reset link. Check server logs.", # L-R7-B: no internal details
  960. )
  961. # LDAP Authentication Helpers
  962. async def _get_ldap_settings(db: AsyncSession) -> dict[str, str] | None:
  963. """Get LDAP settings from the database. Returns None if LDAP is not enabled."""
  964. ldap_keys = [
  965. "ldap_enabled",
  966. "ldap_server_url",
  967. "ldap_bind_dn",
  968. "ldap_bind_password",
  969. "ldap_search_base",
  970. "ldap_user_filter",
  971. "ldap_security",
  972. "ldap_group_mapping",
  973. "ldap_auto_provision",
  974. "ldap_ca_cert_path",
  975. "ldap_default_group",
  976. ]
  977. result = await db.execute(select(Settings).where(Settings.key.in_(ldap_keys)))
  978. settings = {s.key: s.value for s in result.scalars().all()}
  979. if settings.get("ldap_enabled", "false").lower() != "true":
  980. return None
  981. return settings
  982. async def _provision_ldap_user(db: AsyncSession, ldap_user, ldap_config) -> User:
  983. """Create a new local user from LDAP authentication."""
  984. import logging
  985. from backend.app.services.ldap_service import resolve_group_mapping
  986. logger = logging.getLogger(__name__)
  987. new_user = User(
  988. username=ldap_user.username,
  989. email=ldap_user.email,
  990. password_hash=None,
  991. role="user",
  992. auth_source="ldap",
  993. is_active=True,
  994. )
  995. # Map LDAP groups to BamBuddy groups, falling back to the configured default group
  996. # when the user is authenticated but has no matching group mapping (#921-follow-up).
  997. mapped_group_names = resolve_group_mapping(ldap_user.groups, ldap_config.group_mapping)
  998. if not mapped_group_names and ldap_config.default_group:
  999. mapped_group_names = [ldap_config.default_group]
  1000. logger.warning(
  1001. "LDAP user %s has no mapped groups — assigning configured default group '%s'",
  1002. ldap_user.username,
  1003. ldap_config.default_group,
  1004. )
  1005. if mapped_group_names:
  1006. groups_result = await db.execute(select(Group).where(Group.name.in_(mapped_group_names)))
  1007. new_user.groups = list(groups_result.scalars().all())
  1008. db.add(new_user)
  1009. await db.commit()
  1010. await db.refresh(new_user)
  1011. logger.info("Auto-provisioned LDAP user: %s (groups: %s)", new_user.username, mapped_group_names)
  1012. return new_user
  1013. async def _sync_ldap_user(db: AsyncSession, user: User, ldap_user, ldap_config) -> None:
  1014. """Sync LDAP user attributes (email, groups) on each login."""
  1015. import logging
  1016. from backend.app.services.ldap_service import resolve_group_mapping
  1017. logger = logging.getLogger(__name__)
  1018. changed = False
  1019. # Update email if changed
  1020. if ldap_user.email and ldap_user.email != user.email:
  1021. user.email = ldap_user.email
  1022. changed = True
  1023. # Sync group mappings — always update to match LDAP state (including revocation).
  1024. # Fall back to the configured default group when the user has no mapped groups,
  1025. # so authenticated LDAP users are never left permission-less.
  1026. mapped_group_names = resolve_group_mapping(ldap_user.groups, ldap_config.group_mapping)
  1027. if not mapped_group_names and ldap_config.default_group:
  1028. mapped_group_names = [ldap_config.default_group]
  1029. logger.warning(
  1030. "LDAP user %s has no mapped groups — assigning configured default group '%s'",
  1031. user.username,
  1032. ldap_config.default_group,
  1033. )
  1034. if mapped_group_names:
  1035. groups_result = await db.execute(select(Group).where(Group.name.in_(mapped_group_names)))
  1036. new_groups = list(groups_result.scalars().all())
  1037. else:
  1038. new_groups = []
  1039. current_group_ids = {g.id for g in user.groups}
  1040. new_group_ids = {g.id for g in new_groups}
  1041. if current_group_ids != new_group_ids:
  1042. user.groups = new_groups
  1043. changed = True
  1044. if changed:
  1045. await db.commit()
  1046. logger.info("Synced LDAP user attributes: %s", user.username)
  1047. @router.post("/ldap/test")
  1048. async def test_ldap(
  1049. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  1050. db: AsyncSession = Depends(get_db),
  1051. ):
  1052. """Test LDAP connection using saved settings (admin only when auth enabled)."""
  1053. import logging
  1054. from backend.app.services.ldap_service import parse_ldap_config, test_ldap_connection
  1055. logger = logging.getLogger(__name__)
  1056. ldap_settings = await _get_ldap_settings(db)
  1057. if not ldap_settings:
  1058. # LDAP might not be enabled yet but settings might still exist — read all keys
  1059. ldap_keys = [
  1060. "ldap_enabled",
  1061. "ldap_server_url",
  1062. "ldap_bind_dn",
  1063. "ldap_bind_password",
  1064. "ldap_search_base",
  1065. "ldap_user_filter",
  1066. "ldap_security",
  1067. "ldap_group_mapping",
  1068. "ldap_auto_provision",
  1069. ]
  1070. result = await db.execute(select(Settings).where(Settings.key.in_(ldap_keys)))
  1071. ldap_settings = {s.key: s.value for s in result.scalars().all()}
  1072. # Force enabled for test
  1073. ldap_settings["ldap_enabled"] = "true"
  1074. config = parse_ldap_config(ldap_settings)
  1075. if not config:
  1076. return {"success": False, "message": "LDAP server URL is not configured"}
  1077. success, message = test_ldap_connection(config)
  1078. if success:
  1079. logger.info("LDAP connection test successful")
  1080. else:
  1081. logger.warning("LDAP connection test failed: %s", message)
  1082. return {"success": success, "message": message}
  1083. @router.get("/ldap/status")
  1084. async def get_ldap_status(db: AsyncSession = Depends(get_db)):
  1085. """Get LDAP authentication status."""
  1086. # Only fetch the minimum keys needed — never load secrets
  1087. ldap_keys = ["ldap_enabled", "ldap_server_url"]
  1088. result = await db.execute(select(Settings).where(Settings.key.in_(ldap_keys)))
  1089. settings = {s.key: s.value for s in result.scalars().all()}
  1090. return {
  1091. "ldap_enabled": settings.get("ldap_enabled", "false").lower() == "true",
  1092. "ldap_configured": bool(settings.get("ldap_server_url")),
  1093. }