auth.py 85 KB

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