auth.py 84 KB

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