auth.py 78 KB

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