auth.py 78 KB

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