auth.py 83 KB

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