auth.py 64 KB

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