test_mfa_api.py 205 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206
  1. """Integration tests for 2FA and OIDC API endpoints.
  2. Tests the full request/response cycle for:
  3. - GET /api/v1/auth/2fa/status
  4. - POST /api/v1/auth/2fa/totp/setup
  5. - POST /api/v1/auth/2fa/totp/enable
  6. - POST /api/v1/auth/2fa/totp/disable
  7. - POST /api/v1/auth/2fa/email/enable
  8. - POST /api/v1/auth/2fa/email/disable
  9. - POST /api/v1/auth/2fa/verify (TOTP, email, backup paths)
  10. - DELETE /api/v1/auth/2fa/admin/{user_id}
  11. - GET /api/v1/auth/oidc/providers
  12. - POST /api/v1/auth/oidc/providers
  13. - PATCH /api/v1/auth/oidc/providers/{id}
  14. - DELETE /api/v1/auth/oidc/providers/{id}
  15. """
  16. from __future__ import annotations
  17. import secrets
  18. import time
  19. from datetime import datetime, timedelta, timezone
  20. from unittest.mock import patch
  21. import jwt as pyjwt
  22. import pyotp
  23. import pytest
  24. from httpx import AsyncClient
  25. from passlib.context import CryptContext
  26. from sqlalchemy.ext.asyncio import AsyncSession
  27. from backend.app.models.auth_ephemeral import AuthEphemeralToken
  28. from backend.app.models.user import User
  29. _pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto")
  30. # ---------------------------------------------------------------------------
  31. # Fixtures / helpers
  32. # ---------------------------------------------------------------------------
  33. AUTH_SETUP_URL = "/api/v1/auth/setup"
  34. LOGIN_URL = "/api/v1/auth/login"
  35. def _norm_pw(password: str) -> str:
  36. """Ensure password meets complexity requirements (I4: SetupRequest now validates)."""
  37. if not any(c.isupper() for c in password):
  38. password = password[0].upper() + password[1:]
  39. if not any(c not in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" for c in password):
  40. password = password + "!"
  41. return password
  42. async def _setup_and_login(client: AsyncClient, username: str, password: str) -> str:
  43. """Enable auth, create an admin user, login, and return the bearer token."""
  44. password = _norm_pw(password)
  45. await client.post(
  46. AUTH_SETUP_URL,
  47. json={
  48. "auth_enabled": True,
  49. "admin_username": username,
  50. "admin_password": password,
  51. },
  52. )
  53. resp = await client.post(LOGIN_URL, json={"username": username, "password": password})
  54. assert resp.status_code == 200
  55. return resp.json()["access_token"]
  56. async def _login_get_pre_auth_token(client: AsyncClient, username: str, password: str) -> str:
  57. """Login a user who has 2FA enabled; return the pre_auth_token from the response."""
  58. password = _norm_pw(password)
  59. resp = await client.post(LOGIN_URL, json={"username": username, "password": password})
  60. assert resp.status_code == 200
  61. data = resp.json()
  62. assert data["requires_2fa"] is True, f"Expected requires_2fa=True, got {data}"
  63. assert data["pre_auth_token"] is not None
  64. return data["pre_auth_token"]
  65. def _auth_header(token: str) -> dict[str, str]:
  66. return {"Authorization": f"Bearer {token}"}
  67. # ===========================================================================
  68. # 2FA Status
  69. # ===========================================================================
  70. class TestTwoFAStatus:
  71. """Tests for GET /api/v1/auth/2fa/status."""
  72. @pytest.mark.asyncio
  73. @pytest.mark.integration
  74. async def test_status_requires_auth(self, async_client: AsyncClient):
  75. response = await async_client.get("/api/v1/auth/2fa/status")
  76. assert response.status_code == 401
  77. @pytest.mark.asyncio
  78. @pytest.mark.integration
  79. async def test_status_default_disabled(self, async_client: AsyncClient):
  80. token = await _setup_and_login(async_client, "statususer", "statuspass123")
  81. response = await async_client.get("/api/v1/auth/2fa/status", headers=_auth_header(token))
  82. assert response.status_code == 200
  83. data = response.json()
  84. assert data["totp_enabled"] is False
  85. assert data["email_otp_enabled"] is False
  86. assert data["backup_codes_remaining"] == 0
  87. # ===========================================================================
  88. # TOTP Setup
  89. # ===========================================================================
  90. class TestTOTPSetup:
  91. """Tests for POST /api/v1/auth/2fa/totp/setup."""
  92. @pytest.mark.asyncio
  93. @pytest.mark.integration
  94. async def test_setup_requires_auth(self, async_client: AsyncClient):
  95. response = await async_client.post("/api/v1/auth/2fa/totp/setup")
  96. assert response.status_code == 401
  97. @pytest.mark.asyncio
  98. @pytest.mark.integration
  99. async def test_setup_returns_secret_and_qr(self, async_client: AsyncClient):
  100. token = await _setup_and_login(async_client, "totpsetup", "totpsetup123")
  101. response = await async_client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token))
  102. assert response.status_code == 200
  103. data = response.json()
  104. assert "secret" in data
  105. assert len(data["secret"]) > 0
  106. assert "qr_code_b64" in data
  107. assert data["issuer"] == "Bambuddy"
  108. @pytest.mark.asyncio
  109. @pytest.mark.integration
  110. async def test_setup_secret_is_valid_base32(self, async_client: AsyncClient):
  111. token = await _setup_and_login(async_client, "totpbase32", "totpbase32pw")
  112. response = await async_client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token))
  113. assert response.status_code == 200
  114. secret = response.json()["secret"]
  115. # pyotp will raise on invalid base32
  116. totp = pyotp.TOTP(secret)
  117. assert len(totp.now()) == 6
  118. # ===========================================================================
  119. # TOTP Enable
  120. # ===========================================================================
  121. class TestTOTPEnable:
  122. """Tests for POST /api/v1/auth/2fa/totp/enable."""
  123. @pytest.mark.asyncio
  124. @pytest.mark.integration
  125. async def test_enable_without_setup_returns_400(self, async_client: AsyncClient):
  126. token = await _setup_and_login(async_client, "nosetupenable", "nosetupenable1")
  127. response = await async_client.post(
  128. "/api/v1/auth/2fa/totp/enable",
  129. json={"code": "123456"},
  130. headers=_auth_header(token),
  131. )
  132. assert response.status_code == 400
  133. @pytest.mark.asyncio
  134. @pytest.mark.integration
  135. async def test_enable_with_invalid_code_returns_400(self, async_client: AsyncClient):
  136. token = await _setup_and_login(async_client, "badcodeuser", "badcodeuser1")
  137. await async_client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token))
  138. response = await async_client.post(
  139. "/api/v1/auth/2fa/totp/enable",
  140. json={"code": "000000"},
  141. headers=_auth_header(token),
  142. )
  143. assert response.status_code == 400
  144. @pytest.mark.asyncio
  145. @pytest.mark.integration
  146. async def test_enable_with_valid_code_returns_backup_codes(self, async_client: AsyncClient):
  147. token = await _setup_and_login(async_client, "enableok", "enableok123")
  148. setup_resp = await async_client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token))
  149. secret = setup_resp.json()["secret"]
  150. valid_code = pyotp.TOTP(secret).now()
  151. response = await async_client.post(
  152. "/api/v1/auth/2fa/totp/enable",
  153. json={"code": valid_code},
  154. headers=_auth_header(token),
  155. )
  156. assert response.status_code == 200
  157. data = response.json()
  158. assert "backup_codes" in data
  159. assert len(data["backup_codes"]) == 10
  160. for code in data["backup_codes"]:
  161. assert len(code) == 8
  162. @pytest.mark.asyncio
  163. @pytest.mark.integration
  164. async def test_status_reflects_enabled_totp(self, async_client: AsyncClient):
  165. token = await _setup_and_login(async_client, "statustotp", "statustotp1")
  166. setup_resp = await async_client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token))
  167. secret = setup_resp.json()["secret"]
  168. valid_code = pyotp.TOTP(secret).now()
  169. await async_client.post(
  170. "/api/v1/auth/2fa/totp/enable",
  171. json={"code": valid_code},
  172. headers=_auth_header(token),
  173. )
  174. status_resp = await async_client.get("/api/v1/auth/2fa/status", headers=_auth_header(token))
  175. data = status_resp.json()
  176. assert data["totp_enabled"] is True
  177. assert data["backup_codes_remaining"] == 10
  178. # ===========================================================================
  179. # TOTP Disable
  180. # ===========================================================================
  181. class TestTOTPDisable:
  182. """Tests for POST /api/v1/auth/2fa/totp/disable."""
  183. @pytest.mark.asyncio
  184. @pytest.mark.integration
  185. async def test_disable_when_not_enabled_returns_400(self, async_client: AsyncClient):
  186. token = await _setup_and_login(async_client, "disablenoenab", "disablenoenab1")
  187. response = await async_client.post(
  188. "/api/v1/auth/2fa/totp/disable",
  189. json={"code": "123456"},
  190. headers=_auth_header(token),
  191. )
  192. assert response.status_code == 400
  193. @pytest.mark.asyncio
  194. @pytest.mark.integration
  195. async def test_disable_with_valid_code(self, async_client: AsyncClient):
  196. token = await _setup_and_login(async_client, "disableok", "disableok123")
  197. setup_resp = await async_client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token))
  198. secret = setup_resp.json()["secret"]
  199. valid_code = pyotp.TOTP(secret).now()
  200. await async_client.post(
  201. "/api/v1/auth/2fa/totp/enable",
  202. json={"code": valid_code},
  203. headers=_auth_header(token),
  204. )
  205. # Disable with a fresh valid code
  206. disable_code = pyotp.TOTP(secret).now()
  207. response = await async_client.post(
  208. "/api/v1/auth/2fa/totp/disable",
  209. json={"code": disable_code},
  210. headers=_auth_header(token),
  211. )
  212. assert response.status_code == 200
  213. assert "disabled" in response.json()["message"].lower()
  214. # Status should now show disabled
  215. status_resp = await async_client.get("/api/v1/auth/2fa/status", headers=_auth_header(token))
  216. assert status_resp.json()["totp_enabled"] is False
  217. # ===========================================================================
  218. # Email OTP Enable/Disable
  219. # ===========================================================================
  220. class TestEmailOTP:
  221. """Tests for POST /api/v1/auth/2fa/email/enable, /enable/confirm and /disable."""
  222. @pytest.mark.asyncio
  223. @pytest.mark.integration
  224. async def test_enable_email_otp_without_email_returns_400(self, async_client: AsyncClient):
  225. """Users without an email address cannot enable email OTP."""
  226. token = await _setup_and_login(async_client, "noemailuser", "noemailuser1")
  227. response = await async_client.post("/api/v1/auth/2fa/email/enable", headers=_auth_header(token))
  228. assert response.status_code == 400
  229. assert "email" in response.json()["detail"].lower()
  230. @pytest.mark.asyncio
  231. @pytest.mark.integration
  232. async def test_confirm_enable_email_otp_happy_path(self, async_client: AsyncClient, db_session: AsyncSession):
  233. """Confirm step activates email OTP when setup_token + code are valid (C5)."""
  234. token = await _setup_and_login(async_client, "confirmenable", "confirmenable1")
  235. # Give user an email address directly (SMTP not available in tests)
  236. from sqlalchemy import select as sa_select
  237. result = await db_session.execute(sa_select(User).where(User.username == "confirmenable"))
  238. user = result.scalar_one()
  239. user.email = "confirmenable@example.com"
  240. await db_session.commit()
  241. # Inject a known setup token directly into the DB (bypasses SMTP)
  242. code = "123456"
  243. code_hash = _pwd_context.hash(code)
  244. setup_token = secrets.token_urlsafe(32)
  245. db_session.add(
  246. AuthEphemeralToken(
  247. token=setup_token,
  248. token_type="email_otp_setup",
  249. username="confirmenable",
  250. nonce=code_hash,
  251. expires_at=datetime.now(timezone.utc) + timedelta(minutes=10),
  252. )
  253. )
  254. await db_session.commit()
  255. resp = await async_client.post(
  256. "/api/v1/auth/2fa/email/enable/confirm",
  257. json={"setup_token": setup_token, "code": code},
  258. headers=_auth_header(token),
  259. )
  260. assert resp.status_code == 200
  261. status_resp = await async_client.get("/api/v1/auth/2fa/status", headers=_auth_header(token))
  262. assert status_resp.json()["email_otp_enabled"] is True
  263. @pytest.mark.asyncio
  264. @pytest.mark.integration
  265. async def test_confirm_enable_email_otp_wrong_code(self, async_client: AsyncClient, db_session: AsyncSession):
  266. """Wrong code on confirm step returns 400 and does not enable email OTP."""
  267. token = await _setup_and_login(async_client, "confirmwrong", "confirmwrong1")
  268. code_hash = _pwd_context.hash("654321")
  269. setup_token = secrets.token_urlsafe(32)
  270. db_session.add(
  271. AuthEphemeralToken(
  272. token=setup_token,
  273. token_type="email_otp_setup",
  274. username="confirmwrong",
  275. nonce=code_hash,
  276. expires_at=datetime.now(timezone.utc) + timedelta(minutes=10),
  277. )
  278. )
  279. await db_session.commit()
  280. resp = await async_client.post(
  281. "/api/v1/auth/2fa/email/enable/confirm",
  282. json={"setup_token": setup_token, "code": "000000"},
  283. headers=_auth_header(token),
  284. )
  285. assert resp.status_code == 400
  286. @pytest.mark.asyncio
  287. @pytest.mark.integration
  288. async def test_confirm_enable_email_otp_setup_token_is_single_use(
  289. self, async_client: AsyncClient, db_session: AsyncSession
  290. ):
  291. """Setup token is consumed on first use; replay returns 400."""
  292. token = await _setup_and_login(async_client, "confirmonce", "confirmonce1")
  293. code = "111111"
  294. code_hash = _pwd_context.hash(code)
  295. setup_token = secrets.token_urlsafe(32)
  296. db_session.add(
  297. AuthEphemeralToken(
  298. token=setup_token,
  299. token_type="email_otp_setup",
  300. username="confirmonce",
  301. nonce=code_hash,
  302. expires_at=datetime.now(timezone.utc) + timedelta(minutes=10),
  303. )
  304. )
  305. await db_session.commit()
  306. first = await async_client.post(
  307. "/api/v1/auth/2fa/email/enable/confirm",
  308. json={"setup_token": setup_token, "code": code},
  309. headers=_auth_header(token),
  310. )
  311. assert first.status_code == 200
  312. second = await async_client.post(
  313. "/api/v1/auth/2fa/email/enable/confirm",
  314. json={"setup_token": setup_token, "code": code},
  315. headers=_auth_header(token),
  316. )
  317. assert second.status_code == 400
  318. @pytest.mark.asyncio
  319. @pytest.mark.integration
  320. async def test_disable_email_otp_requires_password(self, async_client: AsyncClient):
  321. """Disabling email OTP requires the account password (C6: re-auth)."""
  322. token = await _setup_and_login(async_client, "disemailotp", "disemailotp1")
  323. # Wrong password → 401
  324. response = await async_client.post(
  325. "/api/v1/auth/2fa/email/disable",
  326. json={"password": "wrongpassword"},
  327. headers=_auth_header(token),
  328. )
  329. assert response.status_code == 401
  330. @pytest.mark.asyncio
  331. @pytest.mark.integration
  332. async def test_disable_email_otp_when_enabled(self, async_client: AsyncClient, db_session: AsyncSession):
  333. """Disabling email OTP when enabled turns it off and status reflects that."""
  334. token = await _setup_and_login(async_client, "disemailpw", "disemailpw1")
  335. # Enable email OTP via direct DB injection (no SMTP)
  336. code = "222222"
  337. setup_token = secrets.token_urlsafe(32)
  338. db_session.add(
  339. AuthEphemeralToken(
  340. token=setup_token,
  341. token_type="email_otp_setup",
  342. username="disemailpw",
  343. nonce=_pwd_context.hash(code),
  344. expires_at=datetime.now(timezone.utc) + timedelta(minutes=10),
  345. )
  346. )
  347. await db_session.commit()
  348. await async_client.post(
  349. "/api/v1/auth/2fa/email/enable/confirm",
  350. json={"setup_token": setup_token, "code": code},
  351. headers=_auth_header(token),
  352. )
  353. # Now disable
  354. response = await async_client.post(
  355. "/api/v1/auth/2fa/email/disable",
  356. json={"password": _norm_pw("disemailpw1")},
  357. headers=_auth_header(token),
  358. )
  359. assert response.status_code == 200
  360. status_resp = await async_client.get("/api/v1/auth/2fa/status", headers=_auth_header(token))
  361. assert status_resp.json()["email_otp_enabled"] is False
  362. # ===========================================================================
  363. # 2FA Verify — TOTP path
  364. # ===========================================================================
  365. class TestTwoFAVerifyTOTP:
  366. """Tests for POST /api/v1/auth/2fa/verify using the TOTP method."""
  367. @pytest.mark.asyncio
  368. @pytest.mark.integration
  369. async def test_verify_with_invalid_pre_auth_token(self, async_client: AsyncClient):
  370. response = await async_client.post(
  371. "/api/v1/auth/2fa/verify",
  372. json={"pre_auth_token": "bogus", "method": "totp", "code": "123456"},
  373. )
  374. assert response.status_code == 401
  375. @pytest.mark.asyncio
  376. @pytest.mark.integration
  377. async def test_verify_totp_issues_jwt(self, async_client: AsyncClient):
  378. """Full flow: setup → enable TOTP → login → pre_auth_token → verify → JWT."""
  379. token = await _setup_and_login(async_client, "verifytotpok", "verifytotpok1")
  380. setup_resp = await async_client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token))
  381. secret = setup_resp.json()["secret"]
  382. valid_code = pyotp.TOTP(secret).now()
  383. await async_client.post(
  384. "/api/v1/auth/2fa/totp/enable",
  385. json={"code": valid_code},
  386. headers=_auth_header(token),
  387. )
  388. # Login now returns requires_2fa=True + pre_auth_token
  389. pre_auth_token = await _login_get_pre_auth_token(async_client, "verifytotpok", "verifytotpok1")
  390. verify_resp = await async_client.post(
  391. "/api/v1/auth/2fa/verify",
  392. json={
  393. "pre_auth_token": pre_auth_token,
  394. "method": "totp",
  395. "code": pyotp.TOTP(secret).now(),
  396. },
  397. )
  398. assert verify_resp.status_code == 200
  399. data = verify_resp.json()
  400. assert "access_token" in data
  401. assert data["token_type"] == "bearer"
  402. assert data["user"]["username"] == "verifytotpok"
  403. @pytest.mark.asyncio
  404. @pytest.mark.integration
  405. async def test_verify_totp_invalid_code(self, async_client: AsyncClient):
  406. token = await _setup_and_login(async_client, "verifybadcode", "verifybadcode1")
  407. setup_resp = await async_client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token))
  408. secret = setup_resp.json()["secret"]
  409. valid_code = pyotp.TOTP(secret).now()
  410. await async_client.post(
  411. "/api/v1/auth/2fa/totp/enable",
  412. json={"code": valid_code},
  413. headers=_auth_header(token),
  414. )
  415. pre_auth_token = await _login_get_pre_auth_token(async_client, "verifybadcode", "verifybadcode1")
  416. verify_resp = await async_client.post(
  417. "/api/v1/auth/2fa/verify",
  418. json={"pre_auth_token": pre_auth_token, "method": "totp", "code": "000000"},
  419. )
  420. assert verify_resp.status_code == 401
  421. @pytest.mark.asyncio
  422. @pytest.mark.integration
  423. async def test_verify_invalid_method(self, async_client: AsyncClient):
  424. """An invalid 2FA method should return 400 even with a valid pre_auth_token."""
  425. token = await _setup_and_login(async_client, "invalidmethod", "invalidmethod1")
  426. setup_resp = await async_client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token))
  427. secret = setup_resp.json()["secret"]
  428. valid_code = pyotp.TOTP(secret).now()
  429. await async_client.post(
  430. "/api/v1/auth/2fa/totp/enable",
  431. json={"code": valid_code},
  432. headers=_auth_header(token),
  433. )
  434. pre_auth_token = await _login_get_pre_auth_token(async_client, "invalidmethod", "invalidmethod1")
  435. response = await async_client.post(
  436. "/api/v1/auth/2fa/verify",
  437. json={"pre_auth_token": pre_auth_token, "method": "sms", "code": "123456"},
  438. )
  439. assert response.status_code == 422 # Pydantic Literal validation
  440. # ===========================================================================
  441. # 2FA Verify — Backup code path
  442. # ===========================================================================
  443. class TestTwoFAVerifyBackup:
  444. """Tests for POST /api/v1/auth/2fa/verify using the backup method."""
  445. @pytest.mark.asyncio
  446. @pytest.mark.integration
  447. async def test_verify_with_backup_code(self, async_client: AsyncClient):
  448. token = await _setup_and_login(async_client, "backupcodeok", "backupcodeok1")
  449. setup_resp = await async_client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token))
  450. secret = setup_resp.json()["secret"]
  451. valid_code = pyotp.TOTP(secret).now()
  452. enable_resp = await async_client.post(
  453. "/api/v1/auth/2fa/totp/enable",
  454. json={"code": valid_code},
  455. headers=_auth_header(token),
  456. )
  457. backup_code = enable_resp.json()["backup_codes"][0]
  458. pre_auth_token = await _login_get_pre_auth_token(async_client, "backupcodeok", "backupcodeok1")
  459. verify_resp = await async_client.post(
  460. "/api/v1/auth/2fa/verify",
  461. json={"pre_auth_token": pre_auth_token, "method": "backup", "code": backup_code},
  462. )
  463. assert verify_resp.status_code == 200
  464. assert "access_token" in verify_resp.json()
  465. @pytest.mark.asyncio
  466. @pytest.mark.integration
  467. async def test_backup_code_is_single_use(self, async_client: AsyncClient):
  468. token = await _setup_and_login(async_client, "backupsingle", "backupsingle1")
  469. setup_resp = await async_client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token))
  470. secret = setup_resp.json()["secret"]
  471. valid_code = pyotp.TOTP(secret).now()
  472. enable_resp = await async_client.post(
  473. "/api/v1/auth/2fa/totp/enable",
  474. json={"code": valid_code},
  475. headers=_auth_header(token),
  476. )
  477. backup_code = enable_resp.json()["backup_codes"][0]
  478. # First use — should succeed
  479. pre_auth_token = await _login_get_pre_auth_token(async_client, "backupsingle", "backupsingle1")
  480. first_resp = await async_client.post(
  481. "/api/v1/auth/2fa/verify",
  482. json={"pre_auth_token": pre_auth_token, "method": "backup", "code": backup_code},
  483. )
  484. assert first_resp.status_code == 200
  485. # Second use of the same code — must fail (need new pre_auth_token + same backup code)
  486. pre_auth_token2 = await _login_get_pre_auth_token(async_client, "backupsingle", "backupsingle1")
  487. second_resp = await async_client.post(
  488. "/api/v1/auth/2fa/verify",
  489. json={"pre_auth_token": pre_auth_token2, "method": "backup", "code": backup_code},
  490. )
  491. assert second_resp.status_code == 401
  492. @pytest.mark.asyncio
  493. @pytest.mark.integration
  494. async def test_backup_code_count_decrements(self, async_client: AsyncClient):
  495. token = await _setup_and_login(async_client, "backupcount", "backupcount1")
  496. setup_resp = await async_client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token))
  497. secret = setup_resp.json()["secret"]
  498. valid_code = pyotp.TOTP(secret).now()
  499. enable_resp = await async_client.post(
  500. "/api/v1/auth/2fa/totp/enable",
  501. json={"code": valid_code},
  502. headers=_auth_header(token),
  503. )
  504. backup_code = enable_resp.json()["backup_codes"][0]
  505. pre_auth_token = await _login_get_pre_auth_token(async_client, "backupcount", "backupcount1")
  506. await async_client.post(
  507. "/api/v1/auth/2fa/verify",
  508. json={"pre_auth_token": pre_auth_token, "method": "backup", "code": backup_code},
  509. )
  510. # Status is readable with the original full token (still valid)
  511. status_resp = await async_client.get("/api/v1/auth/2fa/status", headers=_auth_header(token))
  512. assert status_resp.json()["backup_codes_remaining"] == 9
  513. # ===========================================================================
  514. # Rate Limiting
  515. # ===========================================================================
  516. class TestRateLimiting:
  517. """Ensure 429 is returned after 5 failed 2FA attempts."""
  518. @pytest.mark.asyncio
  519. @pytest.mark.integration
  520. async def test_rate_limit_lockout(self, async_client: AsyncClient):
  521. """After 5 failed TOTP attempts the 6th must return 429."""
  522. token = await _setup_and_login(async_client, "ratelimituser", "ratelimituser1")
  523. setup_resp = await async_client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token))
  524. secret = setup_resp.json()["secret"]
  525. valid_code = pyotp.TOTP(secret).now()
  526. await async_client.post(
  527. "/api/v1/auth/2fa/totp/enable",
  528. json={"code": valid_code},
  529. headers=_auth_header(token),
  530. )
  531. # 5 failed attempts via the login → pre_auth_token → verify flow
  532. for _ in range(5):
  533. pre_auth_token = await _login_get_pre_auth_token(async_client, "ratelimituser", "ratelimituser1")
  534. await async_client.post(
  535. "/api/v1/auth/2fa/verify",
  536. json={"pre_auth_token": pre_auth_token, "method": "totp", "code": "000000"},
  537. )
  538. # 6th attempt should hit the rate limit
  539. pre_auth_token = await _login_get_pre_auth_token(async_client, "ratelimituser", "ratelimituser1")
  540. response = await async_client.post(
  541. "/api/v1/auth/2fa/verify",
  542. json={"pre_auth_token": pre_auth_token, "method": "totp", "code": "000000"},
  543. )
  544. assert response.status_code == 429
  545. # ===========================================================================
  546. # Admin 2FA Disable
  547. # ===========================================================================
  548. class TestAdminDisable2FA:
  549. """Tests for DELETE /api/v1/auth/2fa/admin/{user_id}."""
  550. @pytest.mark.asyncio
  551. @pytest.mark.integration
  552. async def test_admin_disable_unknown_user_is_404(self, async_client: AsyncClient):
  553. token = await _setup_and_login(async_client, "admincheck", "admincheck123")
  554. response = await async_client.request(
  555. "DELETE",
  556. "/api/v1/auth/2fa/admin/99999",
  557. json={"admin_password": _norm_pw("admincheck123")},
  558. headers=_auth_header(token),
  559. )
  560. assert response.status_code == 404
  561. @pytest.mark.asyncio
  562. @pytest.mark.integration
  563. async def test_admin_disable_clears_totp(self, async_client: AsyncClient):
  564. from sqlalchemy import select
  565. from backend.app.models.user import User
  566. token = await _setup_and_login(async_client, "admintotp", "admintotp123")
  567. setup_resp = await async_client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token))
  568. secret = setup_resp.json()["secret"]
  569. valid_code = pyotp.TOTP(secret).now()
  570. await async_client.post(
  571. "/api/v1/auth/2fa/totp/enable",
  572. json={"code": valid_code},
  573. headers=_auth_header(token),
  574. )
  575. # Find the user's id by querying status (which works with the token)
  576. me_resp = await async_client.get("/api/v1/auth/me", headers=_auth_header(token))
  577. user_id = me_resp.json()["id"]
  578. response = await async_client.request(
  579. "DELETE",
  580. f"/api/v1/auth/2fa/admin/{user_id}",
  581. json={"admin_password": _norm_pw("admintotp123")},
  582. headers=_auth_header(token),
  583. )
  584. assert response.status_code == 200
  585. # I2: admin_disable_2fa bumps password_changed_at, invalidating the old token.
  586. # Re-login to get a fresh token before checking status.
  587. new_login = await async_client.post(
  588. LOGIN_URL, json={"username": "admintotp", "password": _norm_pw("admintotp123")}
  589. )
  590. assert new_login.status_code == 200, f"re-login failed: {new_login.json()}"
  591. assert new_login.json().get("requires_2fa") is False, f"still requires 2FA: {new_login.json()}"
  592. new_token = new_login.json()["access_token"]
  593. assert new_token is not None, f"no access_token in: {new_login.json()}"
  594. # Status should now show TOTP disabled
  595. status_resp = await async_client.get("/api/v1/auth/2fa/status", headers=_auth_header(new_token))
  596. assert status_resp.status_code == 200, f"status check failed: {status_resp.json()}"
  597. assert status_resp.json()["totp_enabled"] is False
  598. # ===========================================================================
  599. # OIDC Provider CRUD
  600. # ===========================================================================
  601. class TestOIDCProviders:
  602. """Tests for OIDC provider management endpoints."""
  603. @pytest.mark.asyncio
  604. @pytest.mark.integration
  605. async def test_list_public_providers_empty(self, async_client: AsyncClient):
  606. response = await async_client.get("/api/v1/auth/oidc/providers")
  607. assert response.status_code == 200
  608. assert isinstance(response.json(), list)
  609. @pytest.mark.asyncio
  610. @pytest.mark.integration
  611. async def test_create_provider_requires_admin(self, async_client: AsyncClient):
  612. token = await _setup_and_login(async_client, "oidcadmincreate", "oidcadmincreate1")
  613. response = await async_client.post(
  614. "/api/v1/auth/oidc/providers",
  615. json={
  616. "name": "PocketID",
  617. "issuer_url": "https://auth.example.com",
  618. "client_id": "bambuddy",
  619. "client_secret": "supersecret",
  620. "scopes": "openid email profile",
  621. "is_enabled": True,
  622. "auto_create_users": False,
  623. },
  624. headers=_auth_header(token),
  625. )
  626. assert response.status_code == 201
  627. data = response.json()
  628. assert data["name"] == "PocketID"
  629. assert data["issuer_url"] == "https://auth.example.com"
  630. assert "client_secret" not in data # Secret must not be returned
  631. @pytest.mark.asyncio
  632. @pytest.mark.integration
  633. async def test_created_provider_appears_in_all_list(self, async_client: AsyncClient):
  634. token = await _setup_and_login(async_client, "oidclistall", "oidclistall123")
  635. await async_client.post(
  636. "/api/v1/auth/oidc/providers",
  637. json={
  638. "name": "TestProvider",
  639. "issuer_url": "https://test.example.com",
  640. "client_id": "testclient",
  641. "client_secret": "testsecret",
  642. "scopes": "openid",
  643. "is_enabled": True,
  644. "auto_create_users": False,
  645. },
  646. headers=_auth_header(token),
  647. )
  648. response = await async_client.get("/api/v1/auth/oidc/providers/all", headers=_auth_header(token))
  649. assert response.status_code == 200
  650. names = [p["name"] for p in response.json()]
  651. assert "TestProvider" in names
  652. @pytest.mark.asyncio
  653. @pytest.mark.integration
  654. async def test_disabled_provider_not_in_public_list(self, async_client: AsyncClient):
  655. token = await _setup_and_login(async_client, "oidcdisabled", "oidcdisabled1")
  656. await async_client.post(
  657. "/api/v1/auth/oidc/providers",
  658. json={
  659. "name": "DisabledProvider",
  660. "issuer_url": "https://disabled.example.com",
  661. "client_id": "dc",
  662. "client_secret": "ds",
  663. "scopes": "openid",
  664. "is_enabled": False,
  665. "auto_create_users": False,
  666. },
  667. headers=_auth_header(token),
  668. )
  669. response = await async_client.get("/api/v1/auth/oidc/providers")
  670. names = [p["name"] for p in response.json()]
  671. assert "DisabledProvider" not in names
  672. @pytest.mark.asyncio
  673. @pytest.mark.integration
  674. async def test_update_provider(self, async_client: AsyncClient):
  675. token = await _setup_and_login(async_client, "oidcupdate", "oidcupdate123")
  676. create_resp = await async_client.post(
  677. "/api/v1/auth/oidc/providers",
  678. json={
  679. "name": "OldName",
  680. "issuer_url": "https://update.example.com",
  681. "client_id": "uc",
  682. "client_secret": "us",
  683. "scopes": "openid",
  684. "is_enabled": True,
  685. "auto_create_users": False,
  686. },
  687. headers=_auth_header(token),
  688. )
  689. provider_id = create_resp.json()["id"]
  690. put_resp = await async_client.put(
  691. f"/api/v1/auth/oidc/providers/{provider_id}",
  692. json={"name": "NewName"},
  693. headers=_auth_header(token),
  694. )
  695. assert put_resp.status_code == 200
  696. assert put_resp.json()["name"] == "NewName"
  697. @pytest.mark.asyncio
  698. @pytest.mark.integration
  699. async def test_delete_provider(self, async_client: AsyncClient):
  700. token = await _setup_and_login(async_client, "oidcdelete", "oidcdelete123")
  701. create_resp = await async_client.post(
  702. "/api/v1/auth/oidc/providers",
  703. json={
  704. "name": "ToDelete",
  705. "issuer_url": "https://delete.example.com",
  706. "client_id": "dc",
  707. "client_secret": "ds",
  708. "scopes": "openid",
  709. "is_enabled": True,
  710. "auto_create_users": False,
  711. },
  712. headers=_auth_header(token),
  713. )
  714. provider_id = create_resp.json()["id"]
  715. del_resp = await async_client.delete(
  716. f"/api/v1/auth/oidc/providers/{provider_id}",
  717. headers=_auth_header(token),
  718. )
  719. assert del_resp.status_code == 200
  720. # No longer in list
  721. all_resp = await async_client.get("/api/v1/auth/oidc/providers/all", headers=_auth_header(token))
  722. ids = [p["id"] for p in all_resp.json()]
  723. assert provider_id not in ids
  724. @pytest.mark.asyncio
  725. @pytest.mark.integration
  726. async def test_update_nonexistent_provider_returns_404(self, async_client: AsyncClient):
  727. token = await _setup_and_login(async_client, "oidc404", "oidc404pass1")
  728. response = await async_client.put(
  729. "/api/v1/auth/oidc/providers/99999",
  730. json={"name": "ghost"},
  731. headers=_auth_header(token),
  732. )
  733. assert response.status_code == 404
  734. @pytest.mark.asyncio
  735. @pytest.mark.integration
  736. async def test_create_provider_with_default_group_id(self, async_client: AsyncClient, db_session: AsyncSession):
  737. """Creating a provider with a valid default_group_id stores and returns the value."""
  738. from sqlalchemy import select
  739. from backend.app.models.group import Group
  740. token = await _setup_and_login(async_client, "oidcdg_create", "OidcDgCreate1!")
  741. grp_result = await db_session.execute(select(Group).where(Group.name == "Operators"))
  742. operators = grp_result.scalar_one()
  743. resp = await async_client.post(
  744. "/api/v1/auth/oidc/providers",
  745. json={
  746. "name": "DgCreateProvider",
  747. "issuer_url": "https://dgcreate.example.com",
  748. "client_id": "dgcreate-client",
  749. "client_secret": "secret",
  750. "scopes": "openid",
  751. "is_enabled": True,
  752. "auto_create_users": False,
  753. "default_group_id": operators.id,
  754. },
  755. headers=_auth_header(token),
  756. )
  757. assert resp.status_code == 201, resp.text
  758. assert resp.json()["default_group_id"] == operators.id
  759. @pytest.mark.asyncio
  760. @pytest.mark.integration
  761. async def test_create_provider_invalid_default_group_id_returns_422(self, async_client: AsyncClient):
  762. """A default_group_id referencing a non-existent group returns 422."""
  763. token = await _setup_and_login(async_client, "oidcdg_bad", "OidcDgBad1!")
  764. resp = await async_client.post(
  765. "/api/v1/auth/oidc/providers",
  766. json={
  767. "name": "DgBadProvider",
  768. "issuer_url": "https://dgbad.example.com",
  769. "client_id": "dgbad-client",
  770. "client_secret": "secret",
  771. "scopes": "openid",
  772. "is_enabled": True,
  773. "auto_create_users": False,
  774. "default_group_id": 999999,
  775. },
  776. headers=_auth_header(token),
  777. )
  778. assert resp.status_code == 422
  779. @pytest.mark.asyncio
  780. @pytest.mark.integration
  781. async def test_create_provider_omit_default_group_id_stores_null(self, async_client: AsyncClient):
  782. """Omitting default_group_id results in null in the response."""
  783. token = await _setup_and_login(async_client, "oidcdg_null", "OidcDgNull1!")
  784. resp = await async_client.post(
  785. "/api/v1/auth/oidc/providers",
  786. json={
  787. "name": "DgNullProvider",
  788. "issuer_url": "https://dgnull.example.com",
  789. "client_id": "dgnull-client",
  790. "client_secret": "secret",
  791. "scopes": "openid",
  792. "is_enabled": True,
  793. "auto_create_users": False,
  794. },
  795. headers=_auth_header(token),
  796. )
  797. assert resp.status_code == 201, resp.text
  798. assert resp.json()["default_group_id"] is None
  799. @pytest.mark.asyncio
  800. @pytest.mark.integration
  801. async def test_update_provider_default_group_id(self, async_client: AsyncClient, db_session: AsyncSession):
  802. """Updating default_group_id via PUT stores the new value."""
  803. from sqlalchemy import select
  804. from backend.app.models.group import Group
  805. token = await _setup_and_login(async_client, "oidcdg_update", "OidcDgUpdate1!")
  806. create_resp = await async_client.post(
  807. "/api/v1/auth/oidc/providers",
  808. json={
  809. "name": "DgUpdateProvider",
  810. "issuer_url": "https://dgupdate.example.com",
  811. "client_id": "dgupdate-client",
  812. "client_secret": "secret",
  813. "scopes": "openid",
  814. "is_enabled": True,
  815. "auto_create_users": False,
  816. },
  817. headers=_auth_header(token),
  818. )
  819. provider_id = create_resp.json()["id"]
  820. assert create_resp.json()["default_group_id"] is None
  821. grp_result = await db_session.execute(select(Group).where(Group.name == "Operators"))
  822. operators = grp_result.scalar_one()
  823. put_resp = await async_client.put(
  824. f"/api/v1/auth/oidc/providers/{provider_id}",
  825. json={"default_group_id": operators.id},
  826. headers=_auth_header(token),
  827. )
  828. assert put_resp.status_code == 200, put_resp.text
  829. assert put_resp.json()["default_group_id"] == operators.id
  830. @pytest.mark.asyncio
  831. @pytest.mark.integration
  832. async def test_default_group_id_in_public_and_admin_list(self, async_client: AsyncClient, db_session: AsyncSession):
  833. """default_group_id appears in the admin list response.
  834. #3107 review: the public list now serves the slim login-page shape
  835. (id, name, has_icon, is_autologin) so group sync config and other
  836. provider internals stay behind the permission gate — the previous
  837. expectation of default_group_id on the public list is what let the
  838. group mapping leak to anonymous callers.
  839. """
  840. from sqlalchemy import select
  841. from backend.app.models.group import Group
  842. token = await _setup_and_login(async_client, "oidcdg_list", "OidcDgList1!")
  843. grp_result = await db_session.execute(select(Group).where(Group.name == "Operators"))
  844. operators = grp_result.scalar_one()
  845. create_resp = await async_client.post(
  846. "/api/v1/auth/oidc/providers",
  847. json={
  848. "name": "DgListProvider",
  849. "issuer_url": "https://dglist.example.com",
  850. "client_id": "dglist-client",
  851. "client_secret": "secret",
  852. "scopes": "openid",
  853. "is_enabled": True,
  854. "auto_create_users": False,
  855. "default_group_id": operators.id,
  856. },
  857. headers=_auth_header(token),
  858. )
  859. provider_id = create_resp.json()["id"]
  860. all_resp = await async_client.get("/api/v1/auth/oidc/providers/all", headers=_auth_header(token))
  861. match = next((p for p in all_resp.json() if p["id"] == provider_id), None)
  862. assert match is not None
  863. assert match["default_group_id"] == operators.id
  864. pub_resp = await async_client.get("/api/v1/auth/oidc/providers")
  865. pub_match = next((p for p in pub_resp.json() if p["id"] == provider_id), None)
  866. assert pub_match is not None
  867. # Slim public shape: the config fields live on the admin response.
  868. assert set(pub_match.keys()) == {"id", "name", "has_icon", "is_autologin"}
  869. # ===========================================================================
  870. # Security: pre-auth token single-use
  871. # ===========================================================================
  872. class TestPreAuthTokenSingleUse:
  873. """pre_auth_token must be consumed on successful 2FA and cannot be reused."""
  874. @pytest.mark.asyncio
  875. @pytest.mark.integration
  876. async def test_pre_auth_token_is_single_use(self, async_client: AsyncClient):
  877. """A pre_auth_token that was successfully used cannot be reused."""
  878. token = await _setup_and_login(async_client, "singleusepat", "singleusepat1")
  879. setup_resp = await async_client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token))
  880. secret = setup_resp.json()["secret"]
  881. valid_code = pyotp.TOTP(secret).now()
  882. await async_client.post(
  883. "/api/v1/auth/2fa/totp/enable",
  884. json={"code": valid_code},
  885. headers=_auth_header(token),
  886. )
  887. pre_auth_token = await _login_get_pre_auth_token(async_client, "singleusepat", "singleusepat1")
  888. # First use — succeeds
  889. first = await async_client.post(
  890. "/api/v1/auth/2fa/verify",
  891. json={"pre_auth_token": pre_auth_token, "method": "totp", "code": pyotp.TOTP(secret).now()},
  892. )
  893. assert first.status_code == 200
  894. # Second use of the same token — must fail (token already consumed on success)
  895. second = await async_client.post(
  896. "/api/v1/auth/2fa/verify",
  897. json={"pre_auth_token": pre_auth_token, "method": "totp", "code": pyotp.TOTP(secret).now()},
  898. )
  899. assert second.status_code == 401
  900. @pytest.mark.asyncio
  901. @pytest.mark.integration
  902. async def test_pre_auth_token_survives_wrong_code(self, async_client: AsyncClient):
  903. """A wrong 2FA code must NOT burn the pre_auth_token (user can retry)."""
  904. token = await _setup_and_login(async_client, "survivepatuser", "survivepatuser1")
  905. setup_resp = await async_client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token))
  906. secret = setup_resp.json()["secret"]
  907. valid_code = pyotp.TOTP(secret).now()
  908. await async_client.post(
  909. "/api/v1/auth/2fa/totp/enable",
  910. json={"code": valid_code},
  911. headers=_auth_header(token),
  912. )
  913. pre_auth_token = await _login_get_pre_auth_token(async_client, "survivepatuser", "survivepatuser1")
  914. # Wrong code — should fail but not burn the token
  915. bad = await async_client.post(
  916. "/api/v1/auth/2fa/verify",
  917. json={"pre_auth_token": pre_auth_token, "method": "totp", "code": "000000"},
  918. )
  919. assert bad.status_code == 401
  920. # Same token, correct code — should succeed (token still valid)
  921. good = await async_client.post(
  922. "/api/v1/auth/2fa/verify",
  923. json={"pre_auth_token": pre_auth_token, "method": "totp", "code": pyotp.TOTP(secret).now()},
  924. )
  925. assert good.status_code == 200
  926. # ===========================================================================
  927. # Security: cross-user token isolation
  928. # ===========================================================================
  929. class TestCrossUserTokenIsolation:
  930. """A pre_auth_token issued for user A cannot authenticate as user B."""
  931. @pytest.mark.asyncio
  932. @pytest.mark.integration
  933. async def test_token_cannot_be_used_for_different_user(self, async_client: AsyncClient):
  934. """pre_auth_token is bound to the issuing user; using it to verify a different
  935. user's TOTP code must fail."""
  936. # Set up two users with TOTP
  937. token_a = await _setup_and_login(async_client, "crossusera", "crossusera1")
  938. setup_a = await async_client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token_a))
  939. secret_a = setup_a.json()["secret"]
  940. await async_client.post(
  941. "/api/v1/auth/2fa/totp/enable",
  942. json={"code": pyotp.TOTP(secret_a).now()},
  943. headers=_auth_header(token_a),
  944. )
  945. # Get pre_auth_token for user A
  946. pre_auth_a = await _login_get_pre_auth_token(async_client, "crossusera", "crossusera1")
  947. # Try to use user A's token but supply a clearly invalid code — must fail
  948. resp = await async_client.post(
  949. "/api/v1/auth/2fa/verify",
  950. json={"pre_auth_token": pre_auth_a, "method": "totp", "code": "000000"},
  951. )
  952. assert resp.status_code == 401
  953. # ===========================================================================
  954. # Security: admin disable non-admin rejection
  955. # ===========================================================================
  956. class TestAdminDisableNonAdminRejection:
  957. """Non-admin users must be rejected from the admin disable endpoint."""
  958. @pytest.mark.asyncio
  959. @pytest.mark.integration
  960. async def test_non_admin_cannot_disable_2fa(self, async_client: AsyncClient):
  961. """A regular (non-admin) user must receive 403 from DELETE /auth/2fa/admin/{id}."""
  962. # Set up admin, then create a regular user
  963. admin_token = await _setup_and_login(async_client, "adminusr2fa", "adminusr2fa1")
  964. # Create a regular user via user management
  965. create_resp = await async_client.post(
  966. "/api/v1/users",
  967. json={"username": "regularusr2fa", "password": "Regularusr2fa1!"},
  968. headers=_auth_header(admin_token),
  969. )
  970. assert create_resp.status_code == 201
  971. # Login as regular user
  972. login_resp = await async_client.post(
  973. LOGIN_URL,
  974. json={"username": "regularusr2fa", "password": "Regularusr2fa1!"},
  975. )
  976. regular_token = login_resp.json()["access_token"]
  977. # Try to call admin endpoint with the regular user's token
  978. resp = await async_client.delete(
  979. f"/api/v1/auth/2fa/admin/{create_resp.json()['id']}",
  980. headers=_auth_header(regular_token),
  981. )
  982. assert resp.status_code == 403
  983. @pytest.mark.asyncio
  984. @pytest.mark.integration
  985. async def test_users_update_permission_alone_is_not_enough(self, async_client: AsyncClient):
  986. """Editing users is admin-only; so is removing their 2FA."""
  987. admin_token = await _setup_and_login(async_client, "adminperm2fa", "adminperm2fa1")
  988. admin_id = (await async_client.get("/api/v1/auth/me", headers=_auth_header(admin_token))).json()["id"]
  989. group = await async_client.post(
  990. "/api/v1/groups",
  991. json={"name": "User managers", "permissions": ["users:read", "users:update"]},
  992. headers=_auth_header(admin_token),
  993. )
  994. assert group.status_code == 201, group.text
  995. created = await async_client.post(
  996. "/api/v1/users",
  997. json={"username": "usermgr2fa", "password": "Usermgr2fa1!", "group_ids": [group.json()["id"]]},
  998. headers=_auth_header(admin_token),
  999. )
  1000. assert created.status_code == 201, created.text
  1001. login = await async_client.post(LOGIN_URL, json={"username": "usermgr2fa", "password": "Usermgr2fa1!"})
  1002. manager_token = login.json()["access_token"]
  1003. resp = await async_client.request(
  1004. "DELETE",
  1005. f"/api/v1/auth/2fa/admin/{admin_id}",
  1006. json={"admin_password": "Usermgr2fa1!"},
  1007. headers=_auth_header(manager_token),
  1008. )
  1009. assert resp.status_code == 403
  1010. # ===========================================================================
  1011. # Regenerate backup codes
  1012. # ===========================================================================
  1013. class TestRegenerateBackupCodes:
  1014. """Tests for POST /api/v1/auth/2fa/totp/regenerate-backup-codes."""
  1015. @pytest.mark.asyncio
  1016. @pytest.mark.integration
  1017. async def test_regenerate_requires_totp_enabled(self, async_client: AsyncClient):
  1018. token = await _setup_and_login(async_client, "regennototp", "regennototp1")
  1019. resp = await async_client.post(
  1020. "/api/v1/auth/2fa/totp/regenerate-backup-codes",
  1021. json={"code": "123456"},
  1022. headers=_auth_header(token),
  1023. )
  1024. assert resp.status_code == 400
  1025. @pytest.mark.asyncio
  1026. @pytest.mark.integration
  1027. async def test_regenerate_invalidates_old_codes(self, async_client: AsyncClient):
  1028. """After regenerating, old backup codes must no longer work."""
  1029. token = await _setup_and_login(async_client, "regeninval", "regeninval1")
  1030. setup_resp = await async_client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token))
  1031. secret = setup_resp.json()["secret"]
  1032. enable_resp = await async_client.post(
  1033. "/api/v1/auth/2fa/totp/enable",
  1034. json={"code": pyotp.TOTP(secret).now()},
  1035. headers=_auth_header(token),
  1036. )
  1037. old_backup = enable_resp.json()["backup_codes"][0]
  1038. # Regenerate backup codes
  1039. regen_resp = await async_client.post(
  1040. "/api/v1/auth/2fa/totp/regenerate-backup-codes",
  1041. json={"code": pyotp.TOTP(secret).now()},
  1042. headers=_auth_header(token),
  1043. )
  1044. assert regen_resp.status_code == 200
  1045. new_codes = regen_resp.json()["backup_codes"]
  1046. assert len(new_codes) == 10
  1047. assert old_backup not in new_codes
  1048. # Old backup code must now fail
  1049. pre_auth_token = await _login_get_pre_auth_token(async_client, "regeninval", "regeninval1")
  1050. fail_resp = await async_client.post(
  1051. "/api/v1/auth/2fa/verify",
  1052. json={"pre_auth_token": pre_auth_token, "method": "backup", "code": old_backup},
  1053. )
  1054. assert fail_resp.status_code == 401
  1055. @pytest.mark.asyncio
  1056. @pytest.mark.integration
  1057. async def test_regenerate_with_invalid_code_fails(self, async_client: AsyncClient):
  1058. token = await _setup_and_login(async_client, "regeninvcode", "regeninvcode1")
  1059. setup_resp = await async_client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token))
  1060. secret = setup_resp.json()["secret"]
  1061. await async_client.post(
  1062. "/api/v1/auth/2fa/totp/enable",
  1063. json={"code": pyotp.TOTP(secret).now()},
  1064. headers=_auth_header(token),
  1065. )
  1066. resp = await async_client.post(
  1067. "/api/v1/auth/2fa/totp/regenerate-backup-codes",
  1068. json={"code": "000000"},
  1069. headers=_auth_header(token),
  1070. )
  1071. assert resp.status_code == 400
  1072. # ===========================================================================
  1073. # Security: method field validation
  1074. # ===========================================================================
  1075. class TestVerifyMethodValidation:
  1076. """The method field must be one of totp/email/backup (Pydantic Literal)."""
  1077. @pytest.mark.asyncio
  1078. @pytest.mark.integration
  1079. async def test_invalid_method_rejected_by_schema(self, async_client: AsyncClient):
  1080. """Pydantic should reject unknown method values with 422."""
  1081. resp = await async_client.post(
  1082. "/api/v1/auth/2fa/verify",
  1083. json={"pre_auth_token": "anytoken", "code": "123456", "method": "sms"},
  1084. )
  1085. assert resp.status_code == 422
  1086. @pytest.mark.asyncio
  1087. @pytest.mark.integration
  1088. async def test_oversized_pre_auth_token_rejected(self, async_client: AsyncClient):
  1089. """pre_auth_token exceeding max_length=128 should be rejected with 422."""
  1090. resp = await async_client.post(
  1091. "/api/v1/auth/2fa/verify",
  1092. json={"pre_auth_token": "x" * 200, "code": "123456", "method": "totp"},
  1093. )
  1094. assert resp.status_code == 422
  1095. # ===========================================================================
  1096. # Login response shape for 2FA users
  1097. # ===========================================================================
  1098. class TestLoginResponseShape:
  1099. """Login for a 2FA-enabled user must return requires_2fa+pre_auth_token
  1100. and must NOT include access_token (which would bypass the 2FA gate)."""
  1101. @pytest.mark.asyncio
  1102. @pytest.mark.integration
  1103. async def test_login_2fa_user_omits_access_token(self, async_client: AsyncClient):
  1104. """A user with TOTP enabled must not receive an access_token on /auth/login."""
  1105. token = await _setup_and_login(async_client, "loginshape", "loginshape1")
  1106. setup_resp = await async_client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token))
  1107. secret = setup_resp.json()["secret"]
  1108. await async_client.post(
  1109. "/api/v1/auth/2fa/totp/enable",
  1110. json={"code": pyotp.TOTP(secret).now()},
  1111. headers=_auth_header(token),
  1112. )
  1113. login_resp = await async_client.post(LOGIN_URL, json={"username": "loginshape", "password": "Loginshape1!"})
  1114. assert login_resp.status_code == 200
  1115. data = login_resp.json()
  1116. assert data.get("requires_2fa") is True
  1117. assert data.get("pre_auth_token") is not None
  1118. # access_token must NOT be present — it would bypass the 2FA gate
  1119. assert "access_token" not in data or data["access_token"] is None
  1120. # ===========================================================================
  1121. # TOTP replay protection
  1122. # ===========================================================================
  1123. async def _setup_totp_user(client: AsyncClient, username: str, password: str) -> tuple[str, str]:
  1124. """Create user, set up and enable TOTP; return (bearer_token, totp_secret)."""
  1125. token = await _setup_and_login(client, username, password)
  1126. setup_resp = await client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token))
  1127. secret = setup_resp.json()["secret"]
  1128. await client.post(
  1129. "/api/v1/auth/2fa/totp/enable",
  1130. json={"code": pyotp.TOTP(secret).now()},
  1131. headers=_auth_header(token),
  1132. )
  1133. return token, secret
  1134. class TestTOTPReplay:
  1135. """The same TOTP code must not be accepted twice within one 30-second window."""
  1136. @pytest.mark.asyncio
  1137. @pytest.mark.integration
  1138. async def test_totp_replay_rejected_on_verify(self, async_client: AsyncClient):
  1139. """Replaying the same code on /2fa/verify must return 400."""
  1140. _token, secret = await _setup_totp_user(async_client, "replayverify", "replayverify1")
  1141. code = pyotp.TOTP(secret).now()
  1142. pre_auth = await _login_get_pre_auth_token(async_client, "replayverify", "replayverify1")
  1143. first = await async_client.post(
  1144. "/api/v1/auth/2fa/verify",
  1145. json={"pre_auth_token": pre_auth, "method": "totp", "code": code},
  1146. )
  1147. assert first.status_code == 200
  1148. # Second login to get a fresh pre_auth_token (first was consumed)
  1149. pre_auth2 = await _login_get_pre_auth_token(async_client, "replayverify", "replayverify1")
  1150. second = await async_client.post(
  1151. "/api/v1/auth/2fa/verify",
  1152. json={"pre_auth_token": pre_auth2, "method": "totp", "code": code},
  1153. )
  1154. assert second.status_code == 400
  1155. @staticmethod
  1156. def _freeze_mfa_clock(monkeypatch, at: float) -> type:
  1157. """Pin the clock the MFA routes read; set ``clock.at`` to move it."""
  1158. from backend.app.api.routes import mfa as mfa_module
  1159. class Clock(datetime):
  1160. @classmethod
  1161. def now(cls, tz=None):
  1162. return datetime.fromtimestamp(Clock.at, tz)
  1163. Clock.at = at
  1164. monkeypatch.setattr(mfa_module, "datetime", Clock)
  1165. return Clock
  1166. async def _verify(self, client: AsyncClient, username: str, password: str, code: str):
  1167. pre_auth = await _login_get_pre_auth_token(client, username, password)
  1168. return await client.post(
  1169. "/api/v1/auth/2fa/verify",
  1170. json={"pre_auth_token": pre_auth, "method": "totp", "code": code},
  1171. )
  1172. @pytest.mark.asyncio
  1173. @pytest.mark.integration
  1174. async def test_totp_replay_in_the_next_step_is_rejected(self, async_client: AsyncClient, monkeypatch):
  1175. """A code stays valid into the next 30-second step; its reuse there must still fail."""
  1176. _token, secret = await _setup_totp_user(async_client, "replaynext", "replaynext1")
  1177. totp = pyotp.TOTP(secret)
  1178. step_start = (int(time.time()) // 30 + 1) * 30
  1179. code = totp.at(step_start)
  1180. clock = self._freeze_mfa_clock(monkeypatch, step_start + 29)
  1181. first = await self._verify(async_client, "replaynext", "replaynext1", code)
  1182. assert first.status_code == 200
  1183. clock.at = step_start + 31
  1184. second = await self._verify(async_client, "replaynext", "replaynext1", code)
  1185. assert second.status_code == 400
  1186. assert second.json()["detail"] == "TOTP code already used"
  1187. @pytest.mark.asyncio
  1188. @pytest.mark.integration
  1189. async def test_a_previous_step_code_records_its_own_step(self, async_client: AsyncClient, monkeypatch):
  1190. """Used first in the next step, the code is recorded under its own step: the
  1191. current step's code is still accepted afterwards, the replay is not."""
  1192. _token, secret = await _setup_totp_user(async_client, "prevstep", "prevstep12")
  1193. totp = pyotp.TOTP(secret)
  1194. step_start = (int(time.time()) // 30 + 1) * 30
  1195. old_code, new_code = totp.at(step_start), totp.at(step_start + 30)
  1196. self._freeze_mfa_clock(monkeypatch, step_start + 35)
  1197. assert (await self._verify(async_client, "prevstep", "prevstep12", old_code)).status_code == 200
  1198. assert (await self._verify(async_client, "prevstep", "prevstep12", old_code)).status_code == 400
  1199. assert (await self._verify(async_client, "prevstep", "prevstep12", new_code)).status_code == 200
  1200. @pytest.mark.asyncio
  1201. @pytest.mark.integration
  1202. async def test_a_code_two_steps_old_is_rejected(self, async_client: AsyncClient, monkeypatch):
  1203. _token, secret = await _setup_totp_user(async_client, "stalecode", "stalecode12")
  1204. step_start = (int(time.time()) // 30 + 1) * 30
  1205. code = pyotp.TOTP(secret).at(step_start)
  1206. self._freeze_mfa_clock(monkeypatch, step_start + 61)
  1207. resp = await self._verify(async_client, "stalecode", "stalecode12", code)
  1208. assert resp.status_code == 401
  1209. @pytest.mark.asyncio
  1210. @pytest.mark.integration
  1211. async def test_totp_replay_rejected_on_disable(self, async_client: AsyncClient):
  1212. """A code already used in verify_2fa must be rejected on /2fa/totp/disable."""
  1213. _setup_token, secret = await _setup_totp_user(async_client, "replaydisable", "replaydisable1")
  1214. code = pyotp.TOTP(secret).now()
  1215. # Use the code in verify_2fa — this sets last_totp_counter in DB
  1216. pre_auth = await _login_get_pre_auth_token(async_client, "replaydisable", "replaydisable1")
  1217. verify_resp = await async_client.post(
  1218. "/api/v1/auth/2fa/verify",
  1219. json={"pre_auth_token": pre_auth, "method": "totp", "code": code},
  1220. )
  1221. assert verify_resp.status_code == 200
  1222. authed_token = verify_resp.json()["access_token"]
  1223. # Replay the same code on disable — must be rejected (same 30-second window)
  1224. disable_resp = await async_client.post(
  1225. "/api/v1/auth/2fa/totp/disable",
  1226. json={"code": code},
  1227. headers=_auth_header(authed_token),
  1228. )
  1229. assert disable_resp.status_code == 400
  1230. # ===========================================================================
  1231. # Rate limiting on disable_totp and regenerate_backup_codes (I10)
  1232. # ===========================================================================
  1233. class TestRateLimitingDisableRegenerate:
  1234. """disable_totp and regenerate_backup_codes must enforce rate limiting (I10)."""
  1235. @pytest.mark.asyncio
  1236. @pytest.mark.integration
  1237. async def test_disable_totp_rate_limited_after_failures(self, async_client: AsyncClient):
  1238. """Repeated wrong codes on /2fa/totp/disable trigger 429."""
  1239. token, _secret = await _setup_totp_user(async_client, "rldisable", "rldisable1")
  1240. for _ in range(5):
  1241. await async_client.post(
  1242. "/api/v1/auth/2fa/totp/disable",
  1243. json={"code": "000000"},
  1244. headers=_auth_header(token),
  1245. )
  1246. resp = await async_client.post(
  1247. "/api/v1/auth/2fa/totp/disable",
  1248. json={"code": "000000"},
  1249. headers=_auth_header(token),
  1250. )
  1251. assert resp.status_code == 429
  1252. @pytest.mark.asyncio
  1253. @pytest.mark.integration
  1254. async def test_regenerate_backup_codes_rate_limited_after_failures(self, async_client: AsyncClient):
  1255. """Repeated wrong codes on /2fa/totp/regenerate-backup-codes trigger 429."""
  1256. token, _secret = await _setup_totp_user(async_client, "rlregen", "rlregen1")
  1257. for _ in range(5):
  1258. await async_client.post(
  1259. "/api/v1/auth/2fa/totp/regenerate-backup-codes",
  1260. json={"code": "000000"},
  1261. headers=_auth_header(token),
  1262. )
  1263. resp = await async_client.post(
  1264. "/api/v1/auth/2fa/totp/regenerate-backup-codes",
  1265. json={"code": "000000"},
  1266. headers=_auth_header(token),
  1267. )
  1268. assert resp.status_code == 429
  1269. # ===========================================================================
  1270. # Email OTP send → verify end-to-end (coverage gap C3)
  1271. # ===========================================================================
  1272. class TestEmailOTPSendVerify:
  1273. """Full email OTP login: send code → verify code → JWT."""
  1274. @pytest.mark.asyncio
  1275. @pytest.mark.integration
  1276. async def test_email_otp_send_and_verify(self, async_client: AsyncClient, db_session: AsyncSession):
  1277. """login → POST /2fa/email/send (patched SMTP) → POST /2fa/verify → JWT."""
  1278. import re
  1279. from unittest.mock import AsyncMock, MagicMock, patch
  1280. from sqlalchemy import select as sa_select
  1281. token = await _setup_and_login(async_client, "emailsendok", "emailsendok1")
  1282. # Give the user an email address
  1283. result = await db_session.execute(sa_select(User).where(User.username == "emailsendok"))
  1284. user = result.scalar_one()
  1285. user.email = "emailsendok@example.com"
  1286. await db_session.commit()
  1287. # Enable email OTP via DB injection
  1288. setup_code = "444444"
  1289. setup_token = secrets.token_urlsafe(32)
  1290. db_session.add(
  1291. AuthEphemeralToken(
  1292. token=setup_token,
  1293. token_type="email_otp_setup",
  1294. username="emailsendok",
  1295. nonce=_pwd_context.hash(setup_code),
  1296. expires_at=datetime.now(timezone.utc) + timedelta(minutes=10),
  1297. )
  1298. )
  1299. await db_session.commit()
  1300. await async_client.post(
  1301. "/api/v1/auth/2fa/email/enable/confirm",
  1302. json={"setup_token": setup_token, "code": setup_code},
  1303. headers=_auth_header(token),
  1304. )
  1305. # Login now requires 2FA — get pre_auth_token (cookie set automatically)
  1306. pre_auth_token = await _login_get_pre_auth_token(async_client, "emailsendok", "emailsendok1")
  1307. # Mock SMTP and capture the sent OTP code
  1308. captured: dict[str, str] = {}
  1309. smtp_settings_mock = MagicMock()
  1310. def _capture_email(smtp_settings, to_email, subject, body_text, body_html):
  1311. m = re.search(r"login code is: (\d{6})", body_text)
  1312. if m:
  1313. captured["otp"] = m.group(1)
  1314. with (
  1315. patch("backend.app.api.routes.mfa.get_smtp_settings", new=AsyncMock(return_value=smtp_settings_mock)),
  1316. patch("backend.app.api.routes.mfa.send_email", side_effect=_capture_email),
  1317. ):
  1318. send_resp = await async_client.post(
  1319. "/api/v1/auth/2fa/email/send",
  1320. json={"pre_auth_token": pre_auth_token},
  1321. )
  1322. assert send_resp.status_code == 200, send_resp.text
  1323. fresh_token = send_resp.json()["pre_auth_token"]
  1324. assert "otp" in captured, "send_email was not called or code not found in body"
  1325. # Verify with the captured OTP code — cookie still in the async_client jar
  1326. verify_resp = await async_client.post(
  1327. "/api/v1/auth/2fa/verify",
  1328. json={"pre_auth_token": fresh_token, "method": "email", "code": captured["otp"]},
  1329. )
  1330. assert verify_resp.status_code == 200
  1331. data = verify_resp.json()
  1332. assert "access_token" in data
  1333. assert data["user"]["username"] == "emailsendok"
  1334. @pytest.mark.asyncio
  1335. @pytest.mark.integration
  1336. async def test_email_otp_wrong_code_rejected(self, async_client: AsyncClient, db_session: AsyncSession):
  1337. """A wrong email OTP code must return 401 without burning the pre_auth_token."""
  1338. from unittest.mock import AsyncMock, MagicMock, patch
  1339. from sqlalchemy import select as sa_select
  1340. token = await _setup_and_login(async_client, "emailwrongcode", "emailwrongcode1")
  1341. result = await db_session.execute(sa_select(User).where(User.username == "emailwrongcode"))
  1342. user = result.scalar_one()
  1343. user.email = "emailwrongcode@example.com"
  1344. await db_session.commit()
  1345. setup_code = "555555"
  1346. setup_token = secrets.token_urlsafe(32)
  1347. db_session.add(
  1348. AuthEphemeralToken(
  1349. token=setup_token,
  1350. token_type="email_otp_setup",
  1351. username="emailwrongcode",
  1352. nonce=_pwd_context.hash(setup_code),
  1353. expires_at=datetime.now(timezone.utc) + timedelta(minutes=10),
  1354. )
  1355. )
  1356. await db_session.commit()
  1357. await async_client.post(
  1358. "/api/v1/auth/2fa/email/enable/confirm",
  1359. json={"setup_token": setup_token, "code": setup_code},
  1360. headers=_auth_header(token),
  1361. )
  1362. pre_auth_token = await _login_get_pre_auth_token(async_client, "emailwrongcode", "emailwrongcode1")
  1363. captured: dict[str, str] = {}
  1364. smtp_mock = MagicMock()
  1365. def _capture(smtp_settings, to_email, subject, body_text, body_html):
  1366. import re
  1367. m = re.search(r"login code is: (\d{6})", body_text)
  1368. if m:
  1369. captured["otp"] = m.group(1)
  1370. with (
  1371. patch("backend.app.api.routes.mfa.get_smtp_settings", new=AsyncMock(return_value=smtp_mock)),
  1372. patch("backend.app.api.routes.mfa.send_email", side_effect=_capture),
  1373. ):
  1374. send_resp = await async_client.post(
  1375. "/api/v1/auth/2fa/email/send",
  1376. json={"pre_auth_token": pre_auth_token},
  1377. )
  1378. assert send_resp.status_code == 200
  1379. fresh_token = send_resp.json()["pre_auth_token"]
  1380. # Wrong code → 401
  1381. bad = await async_client.post(
  1382. "/api/v1/auth/2fa/verify",
  1383. json={"pre_auth_token": fresh_token, "method": "email", "code": "000000"},
  1384. )
  1385. assert bad.status_code == 401
  1386. # Correct code still works (token not burned by wrong attempt)
  1387. good = await async_client.post(
  1388. "/api/v1/auth/2fa/verify",
  1389. json={"pre_auth_token": fresh_token, "method": "email", "code": captured["otp"]},
  1390. )
  1391. assert good.status_code == 200
  1392. # ===========================================================================
  1393. # OIDC end-to-end (coverage gap C4)
  1394. # ===========================================================================
  1395. def _make_test_rsa_key():
  1396. """Generate a throwaway RSA key pair and a matching JWK set for tests."""
  1397. import base64
  1398. from cryptography.hazmat.primitives import serialization
  1399. from cryptography.hazmat.primitives.asymmetric import rsa
  1400. private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
  1401. private_pem = private_key.private_bytes(
  1402. serialization.Encoding.PEM,
  1403. serialization.PrivateFormat.TraditionalOpenSSL,
  1404. serialization.NoEncryption(),
  1405. )
  1406. pub_numbers = private_key.public_key().public_numbers()
  1407. def _b64url(n: int, length: int) -> str:
  1408. return base64.urlsafe_b64encode(n.to_bytes(length, "big")).rstrip(b"=").decode()
  1409. jwks = {
  1410. "keys": [
  1411. {
  1412. "kty": "RSA",
  1413. "use": "sig",
  1414. "alg": "RS256",
  1415. "kid": "test-kid-1",
  1416. "n": _b64url(pub_numbers.n, 256),
  1417. "e": _b64url(pub_numbers.e, 3),
  1418. }
  1419. ]
  1420. }
  1421. return private_pem, jwks
  1422. class TestOIDCEndToEnd:
  1423. """Full OIDC auth-code flow: state → callback (mocked IdP) → exchange → JWT."""
  1424. @pytest.mark.asyncio
  1425. @pytest.mark.integration
  1426. async def test_oidc_callback_creates_user_and_issues_jwt(self, async_client: AsyncClient, db_session: AsyncSession):
  1427. """callback validates the mocked ID token, creates a user, and redirects
  1428. with an oidc_exchange token; exchanging that token returns a full JWT."""
  1429. import time
  1430. from unittest.mock import patch
  1431. import jwt as pyjwt
  1432. private_pem, jwks_data = _make_test_rsa_key()
  1433. issuer = "https://idp.test.example.com"
  1434. client_id = "oidc-test-client"
  1435. nonce = secrets.token_urlsafe(16)
  1436. now = int(time.time())
  1437. id_token = pyjwt.encode(
  1438. {
  1439. "sub": "oidc-sub-e2e",
  1440. "iss": issuer,
  1441. "aud": client_id,
  1442. "nonce": nonce,
  1443. "email": "oidce2e@example.com",
  1444. "email_verified": True,
  1445. "iat": now,
  1446. "exp": now + 300,
  1447. },
  1448. private_pem,
  1449. algorithm="RS256",
  1450. headers={"kid": "test-kid-1"},
  1451. )
  1452. # Create OIDC provider
  1453. admin_token = await _setup_and_login(async_client, "oidce2eadm", "oidce2eadm1")
  1454. create_resp = await async_client.post(
  1455. "/api/v1/auth/oidc/providers",
  1456. json={
  1457. "name": "E2E-IdP",
  1458. "issuer_url": issuer,
  1459. "client_id": client_id,
  1460. "client_secret": "test-secret",
  1461. "scopes": "openid email profile",
  1462. "is_enabled": True,
  1463. "auto_create_users": True,
  1464. },
  1465. headers=_auth_header(admin_token),
  1466. )
  1467. assert create_resp.status_code == 201
  1468. provider_id = create_resp.json()["id"]
  1469. # Simulate the authorize step: insert an oidc_state token directly
  1470. state = secrets.token_urlsafe(32)
  1471. code_verifier = secrets.token_urlsafe(48)
  1472. db_session.add(
  1473. AuthEphemeralToken(
  1474. token=state,
  1475. token_type="oidc_state",
  1476. provider_id=provider_id,
  1477. nonce=nonce,
  1478. code_verifier=code_verifier,
  1479. expires_at=datetime.now(timezone.utc) + timedelta(minutes=5),
  1480. )
  1481. )
  1482. await db_session.commit()
  1483. # Mock httpx calls made inside oidc_callback
  1484. discovery_doc = {
  1485. "issuer": issuer,
  1486. "authorization_endpoint": f"{issuer}/auth",
  1487. "token_endpoint": f"{issuer}/token",
  1488. "jwks_uri": f"{issuer}/.well-known/jwks.json",
  1489. }
  1490. token_response = {
  1491. "access_token": "mock-access",
  1492. "token_type": "Bearer",
  1493. "id_token": id_token,
  1494. }
  1495. class _MockResp:
  1496. def __init__(self, data):
  1497. self._data = data
  1498. self.status_code = 200
  1499. self.is_success = True
  1500. self.text = str(data)
  1501. def json(self):
  1502. return self._data
  1503. def raise_for_status(self):
  1504. pass
  1505. class _MockHttpxClient:
  1506. def __init__(self, *args, **kwargs):
  1507. pass
  1508. async def __aenter__(self):
  1509. return self
  1510. async def __aexit__(self, *args):
  1511. pass
  1512. async def get(self, url, **kwargs):
  1513. if "jwks" in url:
  1514. return _MockResp(jwks_data)
  1515. return _MockResp(discovery_doc)
  1516. async def post(self, url, **kwargs):
  1517. return _MockResp(token_response)
  1518. with patch("backend.app.api.routes.mfa.httpx.AsyncClient", _MockHttpxClient):
  1519. callback_resp = await async_client.get(
  1520. f"/api/v1/auth/oidc/callback?code=test-auth-code&state={state}",
  1521. follow_redirects=False,
  1522. )
  1523. assert callback_resp.status_code == 302, callback_resp.text
  1524. location = callback_resp.headers.get("location", "")
  1525. assert "oidc_token=" in location, f"Expected oidc_token in redirect, got: {location}"
  1526. # Extract and exchange the oidc_exchange token
  1527. oidc_exchange_token = location.split("oidc_token=")[1].split("&")[0]
  1528. exchange_resp = await async_client.post(
  1529. "/api/v1/auth/oidc/exchange",
  1530. json={"oidc_token": oidc_exchange_token},
  1531. )
  1532. assert exchange_resp.status_code == 200
  1533. data = exchange_resp.json()
  1534. assert "access_token" in data
  1535. assert data["user"]["username"] is not None
  1536. @pytest.mark.asyncio
  1537. @pytest.mark.integration
  1538. async def test_oidc_callback_invalid_state_redirects_error(self, async_client: AsyncClient):
  1539. """An unknown state token must redirect to /?oidc_error=invalid_state."""
  1540. resp = await async_client.get(
  1541. "/api/v1/auth/oidc/callback?code=x&state=totally-bogus-state",
  1542. follow_redirects=False,
  1543. )
  1544. assert resp.status_code == 302
  1545. assert "invalid_state" in resp.headers.get("location", "")
  1546. @pytest.mark.asyncio
  1547. @pytest.mark.integration
  1548. async def test_oidc_state_is_single_use(self, async_client: AsyncClient, db_session: AsyncSession):
  1549. """Replaying the same state token must fail on the second callback."""
  1550. import time
  1551. from unittest.mock import patch
  1552. import jwt as pyjwt
  1553. private_pem, jwks_data = _make_test_rsa_key()
  1554. issuer = "https://idp2.test.example.com"
  1555. client_id = "oidc-client-2"
  1556. nonce = secrets.token_urlsafe(16)
  1557. now = int(time.time())
  1558. id_token = pyjwt.encode(
  1559. {
  1560. "sub": "sub-single-use",
  1561. "iss": issuer,
  1562. "aud": client_id,
  1563. "nonce": nonce,
  1564. "email": "su@example.com",
  1565. "email_verified": True,
  1566. "iat": now,
  1567. "exp": now + 300,
  1568. },
  1569. private_pem,
  1570. algorithm="RS256",
  1571. headers={"kid": "test-kid-1"},
  1572. )
  1573. admin_token = await _setup_and_login(async_client, "oidcsuadm", "oidcsuadm1")
  1574. cr = await async_client.post(
  1575. "/api/v1/auth/oidc/providers",
  1576. json={
  1577. "name": "SU-IdP",
  1578. "issuer_url": issuer,
  1579. "client_id": client_id,
  1580. "client_secret": "s",
  1581. "scopes": "openid",
  1582. "is_enabled": True,
  1583. "auto_create_users": True,
  1584. },
  1585. headers=_auth_header(admin_token),
  1586. )
  1587. provider_id = cr.json()["id"]
  1588. state = secrets.token_urlsafe(32)
  1589. db_session.add(
  1590. AuthEphemeralToken(
  1591. token=state,
  1592. token_type="oidc_state",
  1593. provider_id=provider_id,
  1594. nonce=nonce,
  1595. code_verifier=secrets.token_urlsafe(48),
  1596. expires_at=datetime.now(timezone.utc) + timedelta(minutes=5),
  1597. )
  1598. )
  1599. await db_session.commit()
  1600. discovery_doc = {
  1601. "issuer": issuer,
  1602. "authorization_endpoint": f"{issuer}/auth",
  1603. "token_endpoint": f"{issuer}/token",
  1604. "jwks_uri": f"{issuer}/.well-known/jwks.json",
  1605. }
  1606. token_response = {"access_token": "a", "token_type": "Bearer", "id_token": id_token}
  1607. class _MockResp:
  1608. def __init__(self, data):
  1609. self._data = data
  1610. self.status_code = 200
  1611. self.is_success = True
  1612. self.text = str(data)
  1613. def json(self):
  1614. return self._data
  1615. def raise_for_status(self):
  1616. pass
  1617. class _MockHttpxClient:
  1618. def __init__(self, *a, **kw):
  1619. pass
  1620. async def __aenter__(self):
  1621. return self
  1622. async def __aexit__(self, *a):
  1623. pass
  1624. async def get(self, url, **kw):
  1625. return _MockResp(jwks_data if "jwks" in url else discovery_doc)
  1626. async def post(self, url, **kw):
  1627. return _MockResp(token_response)
  1628. with patch("backend.app.api.routes.mfa.httpx.AsyncClient", _MockHttpxClient):
  1629. first = await async_client.get(
  1630. f"/api/v1/auth/oidc/callback?code=c&state={state}",
  1631. follow_redirects=False,
  1632. )
  1633. assert first.status_code == 302
  1634. assert "oidc_token=" in first.headers.get("location", "")
  1635. # Replay: second callback with the same state must fail
  1636. second = await async_client.get(
  1637. f"/api/v1/auth/oidc/callback?code=c&state={state}",
  1638. follow_redirects=False,
  1639. )
  1640. assert second.status_code == 302
  1641. assert "invalid_state" in second.headers.get("location", "")
  1642. # ===========================================================================
  1643. # H-2: Wrong code must NOT consume the email OTP setup token (peek-then-consume)
  1644. # ===========================================================================
  1645. class TestEmailOTPSetupTokenPreservedOnWrongCode:
  1646. """After H-2 fix: a wrong code leaves the setup token intact so the user can retry."""
  1647. @pytest.mark.asyncio
  1648. @pytest.mark.integration
  1649. async def test_wrong_code_does_not_consume_setup_token(self, async_client: AsyncClient, db_session: AsyncSession):
  1650. """Wrong code returns 400 but the setup token survives; correct code then works."""
  1651. token = await _setup_and_login(async_client, "h2retryuser", "h2retrypass1")
  1652. code = "999999"
  1653. code_hash = _pwd_context.hash(code)
  1654. setup_token = secrets.token_urlsafe(32)
  1655. db_session.add(
  1656. AuthEphemeralToken(
  1657. token=setup_token,
  1658. token_type="email_otp_setup",
  1659. username="h2retryuser",
  1660. nonce=code_hash,
  1661. expires_at=datetime.now(timezone.utc) + timedelta(minutes=10),
  1662. )
  1663. )
  1664. await db_session.commit()
  1665. # First attempt: wrong code → 400
  1666. wrong = await async_client.post(
  1667. "/api/v1/auth/2fa/email/enable/confirm",
  1668. json={"setup_token": setup_token, "code": "000000"},
  1669. headers=_auth_header(token),
  1670. )
  1671. assert wrong.status_code == 400
  1672. # Second attempt: correct code → must succeed (token was NOT consumed)
  1673. correct = await async_client.post(
  1674. "/api/v1/auth/2fa/email/enable/confirm",
  1675. json={"setup_token": setup_token, "code": code},
  1676. headers=_auth_header(token),
  1677. )
  1678. assert correct.status_code == 200
  1679. # ===========================================================================
  1680. # M-2: New OIDC provider must default to auto_link_existing_accounts=False
  1681. # ===========================================================================
  1682. class TestOIDCProviderAutoLinkDefault:
  1683. """auto_link_existing_accounts must default to False (M-2 fix)."""
  1684. @pytest.mark.asyncio
  1685. @pytest.mark.integration
  1686. async def test_new_provider_auto_link_defaults_to_false(self, async_client: AsyncClient):
  1687. token = await _setup_and_login(async_client, "m2autolinkadmin", "m2autolinkadmin1")
  1688. resp = await async_client.post(
  1689. "/api/v1/auth/oidc/providers",
  1690. json={
  1691. "name": "AutoLinkTest",
  1692. "issuer_url": "https://autolink.example.com",
  1693. "client_id": "alc",
  1694. "client_secret": "als",
  1695. "scopes": "openid",
  1696. "is_enabled": True,
  1697. "auto_create_users": False,
  1698. # auto_link_existing_accounts intentionally omitted
  1699. },
  1700. headers=_auth_header(token),
  1701. )
  1702. assert resp.status_code == 201
  1703. assert resp.json()["auto_link_existing_accounts"] is False
  1704. # ===========================================================================
  1705. # L-5: 2FA verify code format validation
  1706. # ===========================================================================
  1707. class TestTwoFAVerifyCodeFormat:
  1708. """TwoFAVerifyRequest.code must be 6–8 alphanumeric characters (L-5)."""
  1709. @pytest.mark.asyncio
  1710. @pytest.mark.integration
  1711. async def test_code_too_long_rejected(self, async_client: AsyncClient):
  1712. """code > 8 characters must be rejected with 422."""
  1713. resp = await async_client.post(
  1714. "/api/v1/auth/2fa/verify",
  1715. json={"pre_auth_token": "anytoken", "code": "1" * 9, "method": "totp"},
  1716. )
  1717. assert resp.status_code == 422
  1718. @pytest.mark.asyncio
  1719. @pytest.mark.integration
  1720. async def test_code_non_alphanumeric_rejected(self, async_client: AsyncClient):
  1721. """code containing non-alphanumeric chars must be rejected with 422."""
  1722. resp = await async_client.post(
  1723. "/api/v1/auth/2fa/verify",
  1724. json={"pre_auth_token": "anytoken", "code": "12-456", "method": "totp"},
  1725. )
  1726. assert resp.status_code == 422
  1727. @pytest.mark.asyncio
  1728. @pytest.mark.integration
  1729. async def test_code_too_short_rejected(self, async_client: AsyncClient):
  1730. """code < 6 characters must be rejected with 422."""
  1731. resp = await async_client.post(
  1732. "/api/v1/auth/2fa/verify",
  1733. json={"pre_auth_token": "anytoken", "code": "12345", "method": "totp"},
  1734. )
  1735. assert resp.status_code == 422
  1736. @pytest.mark.asyncio
  1737. @pytest.mark.integration
  1738. async def test_code_exactly_6_passes_schema(self, async_client: AsyncClient):
  1739. """6-character alphanumeric code passes schema (may fail 2FA logic with 400)."""
  1740. resp = await async_client.post(
  1741. "/api/v1/auth/2fa/verify",
  1742. json={"pre_auth_token": "x" * 32, "code": "123456", "method": "totp"},
  1743. )
  1744. assert resp.status_code != 422
  1745. @pytest.mark.asyncio
  1746. @pytest.mark.integration
  1747. async def test_code_exactly_8_passes_schema(self, async_client: AsyncClient):
  1748. """8-character alphanumeric backup code passes schema."""
  1749. resp = await async_client.post(
  1750. "/api/v1/auth/2fa/verify",
  1751. json={"pre_auth_token": "x" * 32, "code": "ABCD1234", "method": "backup"},
  1752. )
  1753. assert resp.status_code != 422
  1754. # ===========================================================================
  1755. # M-NEW-1: verify_slicer_download_token must NOT consume token on wrong resource
  1756. # ===========================================================================
  1757. class TestSlicerTokenResourceBinding:
  1758. """Token for resource A must survive a wrong-resource check and still work for A."""
  1759. @pytest.mark.asyncio
  1760. @pytest.mark.integration
  1761. async def test_wrong_resource_does_not_consume_token(self, async_client: AsyncClient, db_session: AsyncSession):
  1762. """A slicer token bound to archive:5 must NOT be consumed when checked against archive:6."""
  1763. from datetime import datetime, timedelta, timezone
  1764. from backend.app.core.auth import verify_slicer_download_token
  1765. from backend.app.models.auth_ephemeral import AuthEphemeralToken
  1766. now = datetime.now(timezone.utc)
  1767. token_val = secrets.token_urlsafe(24)
  1768. db_session.add(
  1769. AuthEphemeralToken(
  1770. token=token_val,
  1771. token_type="slicer_download",
  1772. nonce="archive:5",
  1773. expires_at=now + timedelta(minutes=5),
  1774. )
  1775. )
  1776. await db_session.commit()
  1777. # Wrong resource → must return False and NOT consume the token
  1778. wrong = await verify_slicer_download_token(token_val, "archive", 6)
  1779. assert wrong is False
  1780. # Correct resource → must return True (token survived the wrong-resource check)
  1781. correct = await verify_slicer_download_token(token_val, "archive", 5)
  1782. assert correct is True
  1783. @pytest.mark.asyncio
  1784. @pytest.mark.integration
  1785. async def test_correct_resource_consumes_token(self, async_client: AsyncClient, db_session: AsyncSession):
  1786. """A slicer token is single-use: second correct-resource check must return False."""
  1787. from datetime import datetime, timedelta, timezone
  1788. from backend.app.core.auth import verify_slicer_download_token
  1789. from backend.app.models.auth_ephemeral import AuthEphemeralToken
  1790. now = datetime.now(timezone.utc)
  1791. token_val = secrets.token_urlsafe(24)
  1792. db_session.add(
  1793. AuthEphemeralToken(
  1794. token=token_val,
  1795. token_type="slicer_download",
  1796. nonce="library:99",
  1797. expires_at=now + timedelta(minutes=5),
  1798. )
  1799. )
  1800. await db_session.commit()
  1801. first = await verify_slicer_download_token(token_val, "library", 99)
  1802. assert first is True
  1803. second = await verify_slicer_download_token(token_val, "library", 99)
  1804. assert second is False
  1805. # ===========================================================================
  1806. # M-NEW-3 / L-NEW-1: Schema length validation for change-password & forgot-password
  1807. # ===========================================================================
  1808. class TestSchemaLengthValidationR2:
  1809. """Input length limits added in review round 2."""
  1810. @pytest.mark.asyncio
  1811. @pytest.mark.integration
  1812. async def test_change_password_current_too_long_rejected(self, async_client: AsyncClient):
  1813. """current_password > 256 chars must be rejected with 422 (prevents pbkdf2 DoS)."""
  1814. resp = await async_client.post(
  1815. "/api/v1/users/me/change-password",
  1816. json={"current_password": "x" * 257, "new_password": "ValidPass1!"},
  1817. )
  1818. assert resp.status_code == 422
  1819. @pytest.mark.asyncio
  1820. @pytest.mark.integration
  1821. async def test_forgot_password_email_too_long_rejected(self, async_client: AsyncClient):
  1822. """email > 254 chars must be rejected with 422."""
  1823. resp = await async_client.post(
  1824. "/api/v1/auth/forgot-password",
  1825. json={"email": "a" * 243 + "@example.com"},
  1826. )
  1827. assert resp.status_code == 422
  1828. @pytest.mark.asyncio
  1829. @pytest.mark.integration
  1830. async def test_forgot_password_email_at_limit_passes_schema(self, async_client: AsyncClient):
  1831. """Short email passes schema (may return 400/200 from business logic)."""
  1832. resp = await async_client.post(
  1833. "/api/v1/auth/forgot-password",
  1834. json={"email": "user@example.com"},
  1835. )
  1836. assert resp.status_code != 422
  1837. # ===========================================================================
  1838. # L-NEW-2: TOTPSetupRequest.code max_length
  1839. # ===========================================================================
  1840. class TestTOTPSetupCodeMaxLength:
  1841. """TOTPSetupRequest.code must be bounded (L-NEW-2)."""
  1842. @pytest.mark.asyncio
  1843. @pytest.mark.integration
  1844. async def test_setup_code_too_long_rejected(self, async_client: AsyncClient):
  1845. """code > 8 chars must be rejected with 422."""
  1846. import pyotp as _pyotp
  1847. token = await _setup_and_login(async_client, "totp_setup_maxlen", "totp_setup_maxlen1")
  1848. # Enable TOTP so the setup-code guard path is active
  1849. setup_resp = await async_client.post("/api/v1/auth/2fa/totp/setup", headers=_auth_header(token))
  1850. secret = setup_resp.json()["secret"]
  1851. await async_client.post(
  1852. "/api/v1/auth/2fa/totp/enable",
  1853. json={"code": _pyotp.TOTP(secret).now()},
  1854. headers=_auth_header(token),
  1855. )
  1856. resp = await async_client.post(
  1857. "/api/v1/auth/2fa/totp/setup",
  1858. json={"code": "1" * 9},
  1859. headers=_auth_header(token),
  1860. )
  1861. assert resp.status_code == 422
  1862. # ===========================================================================
  1863. # L-NEW-3: EmailOTPEnableConfirmRequest.code must be exactly 6 digits
  1864. # ===========================================================================
  1865. class TestEmailOTPConfirmCodeFormat:
  1866. """EmailOTPEnableConfirmRequest.code must be 6 digits (L-NEW-3)."""
  1867. @pytest.mark.asyncio
  1868. @pytest.mark.integration
  1869. async def test_non_digit_code_rejected(self, async_client: AsyncClient):
  1870. """Alpha characters in the email OTP confirm code must be rejected with 422."""
  1871. token = await _setup_and_login(async_client, "emailotpfmt", "emailotpfmt1")
  1872. resp = await async_client.post(
  1873. "/api/v1/auth/2fa/email/enable/confirm",
  1874. json={"setup_token": "x" * 32, "code": "ABCDEF"},
  1875. headers=_auth_header(token),
  1876. )
  1877. assert resp.status_code == 422
  1878. @pytest.mark.asyncio
  1879. @pytest.mark.integration
  1880. async def test_seven_digit_code_rejected(self, async_client: AsyncClient):
  1881. """7-digit code must be rejected with 422 (min_length=max_length=6)."""
  1882. token = await _setup_and_login(async_client, "emailotplen7", "emailotplen7x")
  1883. resp = await async_client.post(
  1884. "/api/v1/auth/2fa/email/enable/confirm",
  1885. json={"setup_token": "x" * 32, "code": "1234567"},
  1886. headers=_auth_header(token),
  1887. )
  1888. assert resp.status_code == 422
  1889. @pytest.mark.asyncio
  1890. @pytest.mark.integration
  1891. async def test_valid_six_digit_code_passes_schema(self, async_client: AsyncClient):
  1892. """6-digit numeric code passes schema (may return 400 on bad token — that's fine)."""
  1893. token = await _setup_and_login(async_client, "emailotpfmt6", "emailotpfmt6x")
  1894. resp = await async_client.post(
  1895. "/api/v1/auth/2fa/email/enable/confirm",
  1896. json={"setup_token": "x" * 32, "code": "123456"},
  1897. headers=_auth_header(token),
  1898. )
  1899. assert resp.status_code != 422
  1900. # ===========================================================================
  1901. # L-NEW-4: OIDCProviderCreate field max_length constraints
  1902. # ===========================================================================
  1903. class TestOIDCProviderFieldLengths:
  1904. """OIDCProviderCreate fields must reject inputs exceeding max_length (L-NEW-4)."""
  1905. @pytest.mark.asyncio
  1906. @pytest.mark.integration
  1907. async def test_name_too_long_rejected(self, async_client: AsyncClient):
  1908. token = await _setup_and_login(async_client, "oidcfldadmin", "oidcfldadmin1")
  1909. resp = await async_client.post(
  1910. "/api/v1/auth/oidc/providers",
  1911. json={
  1912. "name": "n" * 101,
  1913. "issuer_url": "https://test.example.com",
  1914. "client_id": "cid",
  1915. "client_secret": "csec",
  1916. "scopes": "openid",
  1917. },
  1918. headers=_auth_header(token),
  1919. )
  1920. assert resp.status_code == 422
  1921. @pytest.mark.asyncio
  1922. @pytest.mark.integration
  1923. async def test_client_secret_too_long_rejected(self, async_client: AsyncClient):
  1924. token = await _setup_and_login(async_client, "oidcseclen", "oidcseclen123")
  1925. resp = await async_client.post(
  1926. "/api/v1/auth/oidc/providers",
  1927. json={
  1928. "name": "ValidName",
  1929. "issuer_url": "https://test.example.com",
  1930. "client_id": "cid",
  1931. "client_secret": "s" * 513,
  1932. "scopes": "openid",
  1933. },
  1934. headers=_auth_header(token),
  1935. )
  1936. assert resp.status_code == 422
  1937. # ---------------------------------------------------------------------------
  1938. # M-NEW-4 / M-NEW-5 / L-NEW-5: UserCreate & UserUpdate field length limits
  1939. # ---------------------------------------------------------------------------
  1940. class TestUserCreateUpdateFieldLengths:
  1941. """UserCreate and UserUpdate must enforce max_length on username, password, email."""
  1942. @pytest.fixture
  1943. async def admin_token(self, async_client: AsyncClient) -> str:
  1944. return await _setup_and_login(async_client, "ucfldadmin", "ucfldadmin1!")
  1945. @pytest.mark.asyncio
  1946. @pytest.mark.integration
  1947. async def test_create_username_too_long_rejected(self, async_client: AsyncClient, admin_token: str):
  1948. resp = await async_client.post(
  1949. "/api/v1/users/",
  1950. json={
  1951. "username": "u" * 151,
  1952. "password": "ValidPass1!",
  1953. "role": "user",
  1954. },
  1955. headers=_auth_header(admin_token),
  1956. )
  1957. assert resp.status_code == 422
  1958. @pytest.mark.asyncio
  1959. @pytest.mark.integration
  1960. async def test_create_password_too_long_rejected(self, async_client: AsyncClient, admin_token: str):
  1961. resp = await async_client.post(
  1962. "/api/v1/users/",
  1963. json={
  1964. "username": "newuserX",
  1965. "password": "A1!" + "x" * 254,
  1966. "role": "user",
  1967. },
  1968. headers=_auth_header(admin_token),
  1969. )
  1970. assert resp.status_code == 422
  1971. @pytest.mark.asyncio
  1972. @pytest.mark.integration
  1973. async def test_create_email_too_long_rejected(self, async_client: AsyncClient, admin_token: str):
  1974. resp = await async_client.post(
  1975. "/api/v1/users/",
  1976. json={
  1977. "username": "newuserY",
  1978. "password": "ValidPass1!",
  1979. "email": "a" * 246 + "@x.com", # total 253 chars -> fine; 248+@x.com=255 -> too long
  1980. "role": "user",
  1981. },
  1982. headers=_auth_header(admin_token),
  1983. )
  1984. # 248 'a' + '@x.com' (6) = 254 chars — just at limit, should pass
  1985. # Use 249 + '@x.com' = 255 chars to trigger the 422
  1986. assert resp.status_code in (201, 422) # boundary sanity check
  1987. @pytest.mark.asyncio
  1988. @pytest.mark.integration
  1989. async def test_create_email_exceeds_limit_rejected(self, async_client: AsyncClient, admin_token: str):
  1990. resp = await async_client.post(
  1991. "/api/v1/users/",
  1992. json={
  1993. "username": "newuserZ",
  1994. "password": "ValidPass1!",
  1995. "email": "a" * 249 + "@x.com", # 255 chars — exceeds RFC 5321 max of 254
  1996. "role": "user",
  1997. },
  1998. headers=_auth_header(admin_token),
  1999. )
  2000. assert resp.status_code == 422
  2001. @pytest.mark.asyncio
  2002. @pytest.mark.integration
  2003. async def test_update_username_too_long_rejected(self, async_client: AsyncClient, admin_token: str):
  2004. # Create a user first
  2005. create_resp = await async_client.post(
  2006. "/api/v1/users/",
  2007. json={"username": "updusr1", "password": "ValidPass1!", "role": "user"},
  2008. headers=_auth_header(admin_token),
  2009. )
  2010. assert create_resp.status_code == 201
  2011. user_id = create_resp.json()["id"]
  2012. resp = await async_client.patch(
  2013. f"/api/v1/users/{user_id}",
  2014. json={"username": "u" * 151},
  2015. headers=_auth_header(admin_token),
  2016. )
  2017. assert resp.status_code == 422
  2018. @pytest.mark.asyncio
  2019. @pytest.mark.integration
  2020. async def test_update_password_too_long_rejected(self, async_client: AsyncClient, admin_token: str):
  2021. create_resp = await async_client.post(
  2022. "/api/v1/users/",
  2023. json={"username": "updusr2", "password": "ValidPass1!", "role": "user"},
  2024. headers=_auth_header(admin_token),
  2025. )
  2026. assert create_resp.status_code == 201
  2027. user_id = create_resp.json()["id"]
  2028. resp = await async_client.patch(
  2029. f"/api/v1/users/{user_id}",
  2030. json={"password": "A1!" + "x" * 254},
  2031. headers=_auth_header(admin_token),
  2032. )
  2033. assert resp.status_code == 422
  2034. @pytest.mark.asyncio
  2035. @pytest.mark.integration
  2036. async def test_update_email_too_long_rejected(self, async_client: AsyncClient, admin_token: str):
  2037. create_resp = await async_client.post(
  2038. "/api/v1/users/",
  2039. json={"username": "updusr3", "password": "ValidPass1!", "role": "user"},
  2040. headers=_auth_header(admin_token),
  2041. )
  2042. assert create_resp.status_code == 201
  2043. user_id = create_resp.json()["id"]
  2044. resp = await async_client.patch(
  2045. f"/api/v1/users/{user_id}",
  2046. json={"email": "a" * 249 + "@x.com"}, # 255 chars
  2047. headers=_auth_header(admin_token),
  2048. )
  2049. assert resp.status_code == 422
  2050. # ---------------------------------------------------------------------------
  2051. # L-NEW-6: per-IP rate limiting on /forgot-password
  2052. # ---------------------------------------------------------------------------
  2053. _SMTP_DATA_FOR_IPLIMIT = {
  2054. "smtp_host": "smtp.test.com",
  2055. "smtp_port": 587,
  2056. "smtp_username": "test@test.com",
  2057. "smtp_password": "testpass",
  2058. "smtp_security": "starttls",
  2059. "smtp_auth_enabled": True,
  2060. "smtp_from_email": "noreply@test.com",
  2061. }
  2062. class TestForgotPasswordPerIpRateLimit:
  2063. """POST /forgot-password must enforce a per-IP cap (L-NEW-6).
  2064. The test sends 11 requests from the simulated test-client IP using 11
  2065. different email addresses (so the per-email bucket is never exhausted).
  2066. The 11th request must be rejected with 429.
  2067. """
  2068. @pytest.fixture
  2069. async def advanced_auth_token(self, async_client: AsyncClient) -> str:
  2070. """Set up auth, SMTP, and enable advanced auth; return admin token."""
  2071. token = await _setup_and_login(async_client, "iprladmin", "iprladmin1!")
  2072. headers = _auth_header(token)
  2073. await async_client.post("/api/v1/auth/smtp", headers=headers, json=_SMTP_DATA_FOR_IPLIMIT)
  2074. await async_client.post("/api/v1/auth/advanced-auth/enable", headers=headers)
  2075. return token
  2076. @pytest.mark.asyncio
  2077. @pytest.mark.integration
  2078. async def test_per_ip_limit_triggers_429(self, async_client: AsyncClient, advanced_auth_token: str):
  2079. # Send 11 requests from the same test-client IP using unique email
  2080. # addresses so the per-email bucket (limit=3) is never exhausted.
  2081. responses = []
  2082. for i in range(11):
  2083. resp = await async_client.post(
  2084. "/api/v1/auth/forgot-password",
  2085. json={"email": f"unique{i}@example.com"},
  2086. )
  2087. responses.append(resp.status_code)
  2088. # First 10 must not be rate-limited by the IP bucket
  2089. for code in responses[:10]:
  2090. assert code != 429, f"Unexpected 429 before limit reached: {responses}"
  2091. # The 11th must be rate-limited
  2092. assert responses[10] == 429, f"Expected 429 on 11th request, got {responses[10]}"
  2093. # ---------------------------------------------------------------------------
  2094. # M-NEW-6: OIDC auto-link must be rejected if target user already has an
  2095. # OIDC link to a different provider
  2096. # ---------------------------------------------------------------------------
  2097. class TestOIDCAutoLinkExistingLinkRejection:
  2098. """OIDC callback must reject auto-linking when the email-matched user
  2099. already has an OIDC link to a different provider (M-NEW-6)."""
  2100. @pytest.mark.asyncio
  2101. @pytest.mark.integration
  2102. async def test_auto_link_rejected_when_user_already_linked(
  2103. self, async_client: AsyncClient, db_session: AsyncSession
  2104. ):
  2105. """Auto-link via email-match is rejected when the target user is
  2106. already linked to another OIDC provider."""
  2107. import base64
  2108. import hashlib
  2109. from unittest.mock import AsyncMock, MagicMock, patch
  2110. from backend.app.core.auth import get_password_hash
  2111. from backend.app.models.oidc_provider import OIDCProvider, UserOIDCLink
  2112. from backend.app.models.user import User
  2113. # ── 1. Target user with a known email ────────────────────────────
  2114. target = User(
  2115. username="oidcALTarget",
  2116. email="alinktest@example.com",
  2117. auth_source="oidc",
  2118. password_hash=get_password_hash(secrets.token_urlsafe(16)),
  2119. role="user",
  2120. is_active=True,
  2121. )
  2122. db_session.add(target)
  2123. await db_session.flush()
  2124. # ── 2. Provider B — legitimate, already linked to target ──────────
  2125. prov_b = OIDCProvider(
  2126. name="ProvB_m6test",
  2127. issuer_url="https://providerb-m6.example.com",
  2128. client_id="client_b",
  2129. _client_secret_enc="secret_b",
  2130. scopes="openid email profile",
  2131. is_enabled=True,
  2132. auto_link_existing_accounts=False,
  2133. auto_create_users=False,
  2134. )
  2135. db_session.add(prov_b)
  2136. await db_session.flush()
  2137. db_session.add(
  2138. UserOIDCLink(
  2139. user_id=target.id,
  2140. provider_id=prov_b.id,
  2141. provider_user_id="legitimate_sub",
  2142. provider_email="alinktest@example.com",
  2143. )
  2144. )
  2145. # ── 3. Provider A — attacker-controlled, auto_link=True ───────────
  2146. prov_a = OIDCProvider(
  2147. name="ProvA_m6test",
  2148. issuer_url="https://providera-m6.example.com",
  2149. client_id="client_a",
  2150. _client_secret_enc="secret_a",
  2151. scopes="openid email profile",
  2152. is_enabled=True,
  2153. auto_link_existing_accounts=True,
  2154. auto_create_users=False,
  2155. )
  2156. db_session.add(prov_a)
  2157. await db_session.flush()
  2158. # ── 4. OIDC state for Provider A ──────────────────────────────────
  2159. state = secrets.token_urlsafe(32)
  2160. nonce = secrets.token_urlsafe(32)
  2161. code_verifier = secrets.token_urlsafe(48)
  2162. db_session.add(
  2163. AuthEphemeralToken(
  2164. token=state,
  2165. token_type="oidc_state",
  2166. provider_id=prov_a.id,
  2167. nonce=nonce,
  2168. code_verifier=code_verifier,
  2169. expires_at=datetime.now(timezone.utc) + timedelta(minutes=10),
  2170. )
  2171. )
  2172. await db_session.commit()
  2173. # ── 5. Mock HTTP + JWT so the callback can reach the auto-link check ─
  2174. fake_discovery = {
  2175. "issuer": "https://providera-m6.example.com",
  2176. "token_endpoint": "https://providera-m6.example.com/token",
  2177. "jwks_uri": "https://providera-m6.example.com/jwks",
  2178. }
  2179. fake_token = {"access_token": "acc_tok", "id_token": "fake.id.token"}
  2180. fake_claims = {
  2181. "sub": "attacker_sub_unique",
  2182. "email": "alinktest@example.com",
  2183. "email_verified": True,
  2184. "nonce": nonce,
  2185. "iss": "https://providera-m6.example.com",
  2186. "aud": "client_a",
  2187. "exp": 9_999_999_999,
  2188. }
  2189. disc_resp = AsyncMock()
  2190. disc_resp.raise_for_status = MagicMock()
  2191. disc_resp.json = MagicMock(return_value=fake_discovery)
  2192. token_resp = AsyncMock()
  2193. token_resp.ok = True
  2194. token_resp.json = MagicMock(return_value=fake_token)
  2195. jwks_resp = AsyncMock()
  2196. jwks_resp.raise_for_status = MagicMock()
  2197. jwks_resp.json = MagicMock(return_value={})
  2198. mock_http = AsyncMock()
  2199. mock_http.get = AsyncMock(side_effect=[disc_resp, jwks_resp])
  2200. mock_http.post = AsyncMock(return_value=token_resp)
  2201. mock_signing_key = MagicMock()
  2202. mock_signing_key.key = "fake_key"
  2203. with (
  2204. patch("backend.app.api.routes.mfa.httpx.AsyncClient") as mock_httpx_cls,
  2205. patch("backend.app.api.routes.mfa.jwt.decode", return_value=fake_claims),
  2206. patch("backend.app.api.routes.mfa.PyJWKClient") as mock_jwks_cls,
  2207. ):
  2208. mock_httpx_cls.return_value.__aenter__ = AsyncMock(return_value=mock_http)
  2209. mock_httpx_cls.return_value.__aexit__ = AsyncMock(return_value=False)
  2210. mock_jwks_cls.return_value.get_signing_key_from_jwt.return_value = mock_signing_key
  2211. resp = await async_client.get(
  2212. f"/api/v1/auth/oidc/callback?code=fake_code&state={state}",
  2213. follow_redirects=False,
  2214. )
  2215. # M-NEW-6: must redirect with no_linked_account — NOT create a second link
  2216. assert resp.status_code == 302
  2217. location = resp.headers.get("location", "")
  2218. assert "no_linked_account" in location, f"Expected no_linked_account in redirect, got: {location}"
  2219. # Verify no second OIDC link was created for Provider A
  2220. from sqlalchemy import select as sa_select
  2221. from backend.app.models.oidc_provider import UserOIDCLink as _UOL
  2222. async with db_session as s:
  2223. links_result = await s.execute(
  2224. sa_select(_UOL).where(_UOL.user_id == target.id, _UOL.provider_id == prov_a.id)
  2225. )
  2226. assert links_result.scalar_one_or_none() is None, "No link to Provider A must exist"
  2227. # ===========================================================================
  2228. # Test Gap 1: OIDC state token is single-use — replay must be rejected
  2229. # ===========================================================================
  2230. class TestOIDCStateReplay:
  2231. """OIDC state token must be consumed on first use; a second callback with
  2232. the same state must redirect to ``?oidc_error=invalid_state``."""
  2233. @pytest.mark.asyncio
  2234. @pytest.mark.integration
  2235. async def test_state_replay_rejected(self, async_client: AsyncClient, db_session: AsyncSession):
  2236. """Replaying a consumed OIDC state token must return invalid_state."""
  2237. from backend.app.models.oidc_provider import OIDCProvider
  2238. # ── 1. Seed a minimal provider ────────────────────────────────────
  2239. provider = OIDCProvider(
  2240. name="StateReplayIdP",
  2241. issuer_url="https://statereplay-idp.example.com",
  2242. client_id="client_replay",
  2243. _client_secret_enc="secret_replay",
  2244. scopes="openid",
  2245. is_enabled=True,
  2246. auto_link_existing_accounts=False,
  2247. auto_create_users=False,
  2248. )
  2249. db_session.add(provider)
  2250. await db_session.flush()
  2251. # ── 2. Seed an OIDC state token ───────────────────────────────────
  2252. state = secrets.token_urlsafe(32)
  2253. db_session.add(
  2254. AuthEphemeralToken(
  2255. token=state,
  2256. token_type="oidc_state",
  2257. provider_id=provider.id,
  2258. nonce=secrets.token_urlsafe(32),
  2259. code_verifier=secrets.token_urlsafe(48),
  2260. expires_at=datetime.now(timezone.utc) + timedelta(minutes=10),
  2261. )
  2262. )
  2263. await db_session.commit()
  2264. # ── 3. First callback — discovery will fail (no real IdP), but the
  2265. # state token is atomically consumed (DELETE…RETURNING + commit)
  2266. # before the HTTP call is attempted.
  2267. first = await async_client.get(
  2268. f"/api/v1/auth/oidc/callback?code=any_code&state={state}",
  2269. follow_redirects=False,
  2270. )
  2271. assert first.status_code == 302
  2272. # The first call may fail for any reason except invalid_state
  2273. assert "invalid_state" not in first.headers.get("location", ""), (
  2274. f"First call should NOT get invalid_state: {first.headers.get('location')}"
  2275. )
  2276. # ── 4. Second callback with the same state → must be invalid_state ─
  2277. second = await async_client.get(
  2278. f"/api/v1/auth/oidc/callback?code=any_code&state={state}",
  2279. follow_redirects=False,
  2280. )
  2281. assert second.status_code == 302
  2282. assert "invalid_state" in second.headers.get("location", ""), (
  2283. f"Replayed state must redirect to invalid_state, got: {second.headers.get('location')}"
  2284. )
  2285. # ===========================================================================
  2286. # Test Gap 2: OIDC iss claim mismatch must redirect to token_validation_failed
  2287. # ===========================================================================
  2288. class TestOIDCIssMismatch:
  2289. """JWT whose iss claim does not match the discovery issuer must be rejected."""
  2290. @pytest.mark.asyncio
  2291. @pytest.mark.integration
  2292. async def test_iss_mismatch_redirects_token_validation_failed(
  2293. self, async_client: AsyncClient, db_session: AsyncSession
  2294. ):
  2295. import time
  2296. from unittest.mock import patch
  2297. import jwt as pyjwt
  2298. private_pem, jwks_data = _make_test_rsa_key()
  2299. correct_issuer = "https://correct-iss.example.com"
  2300. wrong_issuer = "https://wrong-iss.example.com"
  2301. client_id = "iss-mismatch-client"
  2302. nonce = secrets.token_urlsafe(16)
  2303. now = int(time.time())
  2304. # Sign the token with the WRONG issuer (iss != discovery_issuer)
  2305. id_token = pyjwt.encode(
  2306. {
  2307. "sub": "sub-iss-test",
  2308. "iss": wrong_issuer,
  2309. "aud": client_id,
  2310. "nonce": nonce,
  2311. "email": "iss@example.com",
  2312. "email_verified": True,
  2313. "iat": now,
  2314. "exp": now + 300,
  2315. },
  2316. private_pem,
  2317. algorithm="RS256",
  2318. headers={"kid": "test-kid-1"},
  2319. )
  2320. admin_token = await _setup_and_login(async_client, "issadmin1", "issadmin1!")
  2321. cr = await async_client.post(
  2322. "/api/v1/auth/oidc/providers",
  2323. json={
  2324. "name": "IssTest-IdP",
  2325. "issuer_url": correct_issuer,
  2326. "client_id": client_id,
  2327. "client_secret": "s",
  2328. "scopes": "openid",
  2329. "is_enabled": True,
  2330. "auto_create_users": True,
  2331. },
  2332. headers=_auth_header(admin_token),
  2333. )
  2334. assert cr.status_code in (200, 201), cr.text
  2335. provider_id = cr.json()["id"]
  2336. state = secrets.token_urlsafe(32)
  2337. db_session.add(
  2338. AuthEphemeralToken(
  2339. token=state,
  2340. token_type="oidc_state",
  2341. provider_id=provider_id,
  2342. nonce=nonce,
  2343. code_verifier=secrets.token_urlsafe(48),
  2344. expires_at=datetime.now(timezone.utc) + timedelta(minutes=5),
  2345. )
  2346. )
  2347. await db_session.commit()
  2348. # Discovery returns the CORRECT issuer; JWT carries the WRONG one.
  2349. discovery_doc = {
  2350. "issuer": correct_issuer,
  2351. "token_endpoint": f"{correct_issuer}/token",
  2352. "jwks_uri": f"{correct_issuer}/.well-known/jwks.json",
  2353. }
  2354. token_response = {"access_token": "a", "id_token": id_token}
  2355. class _MockResp:
  2356. def __init__(self, data):
  2357. self._data = data
  2358. self.status_code = 200
  2359. self.is_success = True
  2360. self.text = ""
  2361. def json(self):
  2362. return self._data
  2363. def raise_for_status(self):
  2364. pass
  2365. class _MockHttpxClient:
  2366. def __init__(self, *a, **kw):
  2367. pass
  2368. async def __aenter__(self):
  2369. return self
  2370. async def __aexit__(self, *a):
  2371. pass
  2372. async def get(self, url, **kw):
  2373. return _MockResp(jwks_data if "jwks" in url else discovery_doc)
  2374. async def post(self, url, **kw):
  2375. return _MockResp(token_response)
  2376. with patch("backend.app.api.routes.mfa.httpx.AsyncClient", _MockHttpxClient):
  2377. resp = await async_client.get(
  2378. f"/api/v1/auth/oidc/callback?code=c&state={state}",
  2379. follow_redirects=False,
  2380. )
  2381. assert resp.status_code == 302
  2382. location = resp.headers.get("location", "")
  2383. assert "token_validation_failed" in location, f"Expected token_validation_failed, got: {location}"
  2384. # ===========================================================================
  2385. # Test Gap 3: /forgot-password/confirm token is single-use
  2386. # ===========================================================================
  2387. class TestForgotPasswordTokenSingleUse:
  2388. """POST /forgot-password/confirm must reject a token after its first use."""
  2389. @pytest.mark.asyncio
  2390. @pytest.mark.integration
  2391. async def test_token_reuse_rejected(self, async_client: AsyncClient, db_session: AsyncSession):
  2392. from backend.app.core.auth import get_password_hash
  2393. from backend.app.models.user import User as _User
  2394. user = _User(
  2395. username="fpcuser1",
  2396. email="fpc@example.com",
  2397. password_hash=get_password_hash("OldPass1!"),
  2398. role="user",
  2399. is_active=True,
  2400. )
  2401. db_session.add(user)
  2402. await db_session.flush()
  2403. reset_token = secrets.token_urlsafe(32)
  2404. db_session.add(
  2405. AuthEphemeralToken(
  2406. token=reset_token,
  2407. token_type="password_reset",
  2408. username="fpcuser1",
  2409. expires_at=datetime.now(timezone.utc) + timedelta(hours=1),
  2410. )
  2411. )
  2412. await db_session.commit()
  2413. # First use → success
  2414. resp1 = await async_client.post(
  2415. "/api/v1/auth/forgot-password/confirm",
  2416. json={"token": reset_token, "new_password": "NewPass1!"},
  2417. )
  2418. assert resp1.status_code == 200, resp1.text
  2419. # Second use → token already consumed, must fail
  2420. resp2 = await async_client.post(
  2421. "/api/v1/auth/forgot-password/confirm",
  2422. json={"token": reset_token, "new_password": "AnotherNew1!"},
  2423. )
  2424. assert resp2.status_code == 400
  2425. # ===========================================================================
  2426. # C1 regression: setup_totp must reject a replayed TOTP code
  2427. # ===========================================================================
  2428. class TestSetupTOTPReplayRejected:
  2429. """setup_totp must reject a TOTP code that was already accepted in its window."""
  2430. @pytest.mark.asyncio
  2431. @pytest.mark.integration
  2432. async def test_replayed_setup_code_rejected(self, async_client: AsyncClient, db_session: AsyncSession):
  2433. from sqlalchemy import select as sa_select
  2434. from backend.app.models.user_totp import UserTOTP
  2435. token = await _setup_and_login(async_client, "setupreplay1", "setupreplay1!")
  2436. # Step 1: Initial TOTP setup (no active TOTP yet → no code required)
  2437. setup_resp = await async_client.post(
  2438. "/api/v1/auth/2fa/totp/setup",
  2439. headers=_auth_header(token),
  2440. )
  2441. assert setup_resp.status_code == 200
  2442. secret = setup_resp.json()["secret"]
  2443. # Step 2: Enable TOTP with a valid code
  2444. totp_obj = pyotp.TOTP(secret)
  2445. enable_resp = await async_client.post(
  2446. "/api/v1/auth/2fa/totp/enable",
  2447. json={"code": totp_obj.now()},
  2448. headers=_auth_header(token),
  2449. )
  2450. assert enable_resp.status_code == 200 # TOTP is now active (is_enabled=True)
  2451. # Step 3: Determine current valid code and its counter
  2452. me_resp = await async_client.get("/api/v1/auth/me", headers=_auth_header(token))
  2453. user_id = me_resp.json()["id"]
  2454. totp_result = await db_session.execute(sa_select(UserTOTP).where(UserTOTP.user_id == user_id))
  2455. totp_record = totp_result.scalar_one()
  2456. secret_now = totp_record.secret # decrypted via property
  2457. totp_now = pyotp.TOTP(secret_now)
  2458. valid_code = totp_now.now()
  2459. accepted_counter = totp_now.timecode(datetime.now(timezone.utc))
  2460. # Step 4: Pre-set last_totp_counter so this code looks already used
  2461. totp_record.last_totp_counter = accepted_counter
  2462. await db_session.commit()
  2463. # Step 5: Attempt setup_totp with the "already used" code → must be rejected
  2464. replay_resp = await async_client.post(
  2465. "/api/v1/auth/2fa/totp/setup",
  2466. json={"code": valid_code},
  2467. headers=_auth_header(token),
  2468. )
  2469. assert replay_resp.status_code == 400
  2470. assert "already used" in replay_resp.json()["detail"]
  2471. # ===========================================================================
  2472. # Nit8: OIDC aud mismatch and nonce mismatch tests
  2473. # ===========================================================================
  2474. class TestOIDCAudAndNonceMismatch:
  2475. """Nit8: aud != client_id and nonce != stored value must each fail the callback."""
  2476. def _make_oidc_provider_setup(self):
  2477. """Return a helper for building OIDC test fixtures inline."""
  2478. private_pem, jwks_data = _make_test_rsa_key()
  2479. return private_pem, jwks_data
  2480. @pytest.mark.asyncio
  2481. @pytest.mark.integration
  2482. async def test_aud_mismatch_redirects_token_validation_failed(
  2483. self, async_client: AsyncClient, db_session: AsyncSession
  2484. ):
  2485. """ID token with aud != client_id must be rejected (PyJWT InvalidAudienceError)."""
  2486. import time
  2487. from unittest.mock import patch
  2488. import jwt as pyjwt
  2489. private_pem, jwks_data = _make_test_rsa_key()
  2490. issuer = "https://aud-mismatch.example.com"
  2491. client_id = "aud-test-client"
  2492. wrong_aud = "some-other-client"
  2493. nonce = secrets.token_urlsafe(16)
  2494. now = int(time.time())
  2495. id_token = pyjwt.encode(
  2496. {
  2497. "sub": "sub-aud-test",
  2498. "iss": issuer,
  2499. "aud": wrong_aud, # <-- wrong audience
  2500. "nonce": nonce,
  2501. "email": "aud@example.com",
  2502. "email_verified": True,
  2503. "iat": now,
  2504. "exp": now + 300,
  2505. },
  2506. private_pem,
  2507. algorithm="RS256",
  2508. headers={"kid": "test-kid-1"},
  2509. )
  2510. admin_token = await _setup_and_login(async_client, "audmismatch_admin", "AudMismatch_admin1")
  2511. cr = await async_client.post(
  2512. "/api/v1/auth/oidc/providers",
  2513. json={
  2514. "name": "AudMismatch-IdP",
  2515. "issuer_url": issuer,
  2516. "client_id": client_id,
  2517. "client_secret": "s",
  2518. "scopes": "openid",
  2519. "is_enabled": True,
  2520. "auto_create_users": True,
  2521. },
  2522. headers=_auth_header(admin_token),
  2523. )
  2524. assert cr.status_code in (200, 201), cr.text
  2525. provider_id = cr.json()["id"]
  2526. state = secrets.token_urlsafe(32)
  2527. db_session.add(
  2528. AuthEphemeralToken(
  2529. token=state,
  2530. token_type="oidc_state",
  2531. provider_id=provider_id,
  2532. nonce=nonce,
  2533. code_verifier=secrets.token_urlsafe(48),
  2534. expires_at=datetime.now(timezone.utc) + timedelta(minutes=5),
  2535. )
  2536. )
  2537. await db_session.commit()
  2538. discovery_doc = {
  2539. "issuer": issuer,
  2540. "token_endpoint": f"{issuer}/token",
  2541. "jwks_uri": f"{issuer}/.well-known/jwks.json",
  2542. }
  2543. class _MockResp:
  2544. def __init__(self, data):
  2545. self._data = data
  2546. self.status_code = 200
  2547. self.is_success = True
  2548. self.text = ""
  2549. def json(self):
  2550. return self._data
  2551. def raise_for_status(self):
  2552. pass
  2553. class _MockHttpxClient:
  2554. def __init__(self, *a, **kw):
  2555. pass
  2556. async def __aenter__(self):
  2557. return self
  2558. async def __aexit__(self, *a):
  2559. pass
  2560. async def get(self, url, **kw):
  2561. return _MockResp(jwks_data if "jwks" in url else discovery_doc)
  2562. async def post(self, url, **kw):
  2563. return _MockResp({"access_token": "a", "id_token": id_token})
  2564. with patch("backend.app.api.routes.mfa.httpx.AsyncClient", _MockHttpxClient):
  2565. resp = await async_client.get(
  2566. f"/api/v1/auth/oidc/callback?code=c&state={state}",
  2567. follow_redirects=False,
  2568. )
  2569. assert resp.status_code == 302
  2570. location = resp.headers.get("location", "")
  2571. assert "token_validation_failed" in location, (
  2572. f"Expected token_validation_failed redirect for aud mismatch, got: {location}"
  2573. )
  2574. @pytest.mark.asyncio
  2575. @pytest.mark.integration
  2576. async def test_nonce_mismatch_redirects_token_validation_failed(
  2577. self, async_client: AsyncClient, db_session: AsyncSession
  2578. ):
  2579. """ID token with nonce != stored state nonce must be rejected."""
  2580. import time
  2581. from unittest.mock import patch
  2582. import jwt as pyjwt
  2583. private_pem, jwks_data = _make_test_rsa_key()
  2584. issuer = "https://nonce-mismatch.example.com"
  2585. client_id = "nonce-test-client"
  2586. stored_nonce = secrets.token_urlsafe(16)
  2587. wrong_nonce = secrets.token_urlsafe(16) # different from stored_nonce
  2588. now = int(time.time())
  2589. id_token = pyjwt.encode(
  2590. {
  2591. "sub": "sub-nonce-test",
  2592. "iss": issuer,
  2593. "aud": client_id,
  2594. "nonce": wrong_nonce, # <-- does not match stored_nonce
  2595. "email": "nonce@example.com",
  2596. "email_verified": True,
  2597. "iat": now,
  2598. "exp": now + 300,
  2599. },
  2600. private_pem,
  2601. algorithm="RS256",
  2602. headers={"kid": "test-kid-1"},
  2603. )
  2604. admin_token = await _setup_and_login(async_client, "noncemismatch_admin", "NonceMismatch_admin1")
  2605. cr = await async_client.post(
  2606. "/api/v1/auth/oidc/providers",
  2607. json={
  2608. "name": "NonceMismatch-IdP",
  2609. "issuer_url": issuer,
  2610. "client_id": client_id,
  2611. "client_secret": "s",
  2612. "scopes": "openid",
  2613. "is_enabled": True,
  2614. "auto_create_users": True,
  2615. },
  2616. headers=_auth_header(admin_token),
  2617. )
  2618. assert cr.status_code in (200, 201), cr.text
  2619. provider_id = cr.json()["id"]
  2620. state = secrets.token_urlsafe(32)
  2621. db_session.add(
  2622. AuthEphemeralToken(
  2623. token=state,
  2624. token_type="oidc_state",
  2625. provider_id=provider_id,
  2626. nonce=stored_nonce, # state has correct nonce; JWT carries wrong_nonce
  2627. code_verifier=secrets.token_urlsafe(48),
  2628. expires_at=datetime.now(timezone.utc) + timedelta(minutes=5),
  2629. )
  2630. )
  2631. await db_session.commit()
  2632. discovery_doc = {
  2633. "issuer": issuer,
  2634. "token_endpoint": f"{issuer}/token",
  2635. "jwks_uri": f"{issuer}/.well-known/jwks.json",
  2636. }
  2637. class _MockResp:
  2638. def __init__(self, data):
  2639. self._data = data
  2640. self.status_code = 200
  2641. self.is_success = True
  2642. self.text = ""
  2643. def json(self):
  2644. return self._data
  2645. def raise_for_status(self):
  2646. pass
  2647. class _MockHttpxClient:
  2648. def __init__(self, *a, **kw):
  2649. pass
  2650. async def __aenter__(self):
  2651. return self
  2652. async def __aexit__(self, *a):
  2653. pass
  2654. async def get(self, url, **kw):
  2655. return _MockResp(jwks_data if "jwks" in url else discovery_doc)
  2656. async def post(self, url, **kw):
  2657. return _MockResp({"access_token": "a", "id_token": id_token})
  2658. with patch("backend.app.api.routes.mfa.httpx.AsyncClient", _MockHttpxClient):
  2659. resp = await async_client.get(
  2660. f"/api/v1/auth/oidc/callback?code=c&state={state}",
  2661. follow_redirects=False,
  2662. )
  2663. assert resp.status_code == 302
  2664. location = resp.headers.get("location", "")
  2665. # The callback redirects to ?oidc_error=nonce_mismatch when nonces differ.
  2666. assert "nonce_mismatch" in location, f"Expected nonce_mismatch redirect for nonce mismatch, got: {location}"
  2667. # ===========================================================================
  2668. # Expired OIDC token rejection — state and exchange tokens
  2669. # ===========================================================================
  2670. class TestOIDCExpiredTokenRejection:
  2671. """Expired OIDC state and exchange tokens must be rejected atomically.
  2672. The DELETE … WHERE expires_at > now must ensure that an already-expired
  2673. token is never consumed (committed) before the expiry is checked, so the
  2674. token row stays in the DB and is not silently discarded.
  2675. """
  2676. @pytest.mark.asyncio
  2677. @pytest.mark.integration
  2678. async def test_expired_state_token_rejected_as_invalid_state(
  2679. self, async_client: AsyncClient, db_session: AsyncSession
  2680. ):
  2681. """An expired OIDC state token must redirect to invalid_state without
  2682. being consumed — it must still exist in the DB after the rejected call."""
  2683. from backend.app.models.oidc_provider import OIDCProvider
  2684. provider = OIDCProvider(
  2685. name="ExpiredStateIdP",
  2686. issuer_url="https://expired-state.example.com",
  2687. client_id="client_expired_state",
  2688. _client_secret_enc="secret_exp_state",
  2689. scopes="openid",
  2690. is_enabled=True,
  2691. auto_link_existing_accounts=False,
  2692. auto_create_users=False,
  2693. )
  2694. db_session.add(provider)
  2695. await db_session.flush()
  2696. state = secrets.token_urlsafe(32)
  2697. db_session.add(
  2698. AuthEphemeralToken(
  2699. token=state,
  2700. token_type="oidc_state",
  2701. provider_id=provider.id,
  2702. nonce=secrets.token_urlsafe(16),
  2703. code_verifier=secrets.token_urlsafe(48),
  2704. # already expired
  2705. expires_at=datetime.now(timezone.utc) - timedelta(minutes=5),
  2706. )
  2707. )
  2708. await db_session.commit()
  2709. resp = await async_client.get(
  2710. f"/api/v1/auth/oidc/callback?code=any_code&state={state}",
  2711. follow_redirects=False,
  2712. )
  2713. assert resp.status_code == 302
  2714. location = resp.headers.get("location", "")
  2715. assert "invalid_state" in location, f"Expected invalid_state redirect for expired state, got: {location}"
  2716. @pytest.mark.asyncio
  2717. @pytest.mark.integration
  2718. async def test_expired_exchange_token_rejected(self, async_client: AsyncClient, db_session: AsyncSession):
  2719. """An expired OIDC exchange token must return 401 without being consumed."""
  2720. from sqlalchemy import select as sa_select
  2721. expired_token = secrets.token_urlsafe(32)
  2722. db_session.add(
  2723. AuthEphemeralToken(
  2724. token=expired_token,
  2725. token_type="oidc_exchange",
  2726. username="some_user",
  2727. # already expired
  2728. expires_at=datetime.now(timezone.utc) - timedelta(minutes=5),
  2729. )
  2730. )
  2731. await db_session.commit()
  2732. resp = await async_client.post(
  2733. "/api/v1/auth/oidc/exchange",
  2734. json={"oidc_token": expired_token},
  2735. )
  2736. assert resp.status_code == 401
  2737. assert "expired" in resp.json().get("detail", "").lower() or "invalid" in resp.json().get("detail", "").lower()
  2738. # Token must NOT have been consumed — it should still be in the DB
  2739. # (the atomic DELETE WHERE expires_at > now left it untouched)
  2740. result = await db_session.execute(
  2741. sa_select(AuthEphemeralToken).where(AuthEphemeralToken.token == expired_token)
  2742. )
  2743. remaining = result.scalar_one_or_none()
  2744. assert remaining is not None, "Expired exchange token must not be consumed by a rejected request"
  2745. # ===========================================================================
  2746. # Trailing slash in issuer_url — discovery URL must not contain double slash
  2747. # ===========================================================================
  2748. class TestOIDCIssuerUrlTrailingSlash:
  2749. """Providers like Authentik use issuer URLs with a trailing slash.
  2750. BamBuddy must strip the slash before appending /.well-known/openid-configuration
  2751. to avoid a double-slash that results in a 404.
  2752. """
  2753. @pytest.mark.asyncio
  2754. @pytest.mark.integration
  2755. async def test_trailing_slash_issuer_url_fetches_correct_discovery_url(self, async_client: AsyncClient):
  2756. from unittest.mock import AsyncMock, MagicMock, patch
  2757. issuer_with_slash = "https://authentik.example.com/application/o/bambuddy/"
  2758. admin_token = await _setup_and_login(async_client, "oidcslashadm", "oidcslashadm1")
  2759. create_resp = await async_client.post(
  2760. "/api/v1/auth/oidc/providers",
  2761. json={
  2762. "name": "Authentik-Slash",
  2763. "issuer_url": issuer_with_slash,
  2764. "client_id": "bambuddy",
  2765. "client_secret": "secret",
  2766. "scopes": "openid email profile",
  2767. "is_enabled": True,
  2768. "auto_create_users": False,
  2769. },
  2770. headers=_auth_header(admin_token),
  2771. )
  2772. assert create_resp.status_code == 201
  2773. provider_id = create_resp.json()["id"]
  2774. fake_discovery = {
  2775. "issuer": issuer_with_slash,
  2776. "authorization_endpoint": "https://authentik.example.com/application/o/bambuddy/authorize",
  2777. }
  2778. disc_resp = AsyncMock()
  2779. disc_resp.raise_for_status = MagicMock()
  2780. disc_resp.json = MagicMock(return_value=fake_discovery)
  2781. mock_http = AsyncMock()
  2782. mock_http.get = AsyncMock(return_value=disc_resp)
  2783. with patch("backend.app.api.routes.mfa.httpx.AsyncClient") as mock_cls:
  2784. mock_cls.return_value.__aenter__ = AsyncMock(return_value=mock_http)
  2785. mock_cls.return_value.__aexit__ = AsyncMock(return_value=False)
  2786. resp = await async_client.get(f"/api/v1/auth/oidc/authorize/{provider_id}")
  2787. assert resp.status_code == 200
  2788. called_url = mock_http.get.call_args_list[0][0][0]
  2789. assert "//" not in called_url.replace("https://", ""), (
  2790. f"Discovery URL must not contain double slash: {called_url}"
  2791. )
  2792. assert called_url.endswith("/.well-known/openid-configuration"), (
  2793. f"Expected discovery URL to end with /.well-known/openid-configuration, got: {called_url}"
  2794. )
  2795. @pytest.mark.asyncio
  2796. @pytest.mark.integration
  2797. async def test_iss_claim_trailing_slash_accepted(self, async_client: AsyncClient, db_session: AsyncSession):
  2798. """Provider configured without trailing slash, Authentik JWT iss has trailing slash.
  2799. Both sides must be normalised before comparison so the login succeeds.
  2800. """
  2801. import time
  2802. from unittest.mock import patch
  2803. import jwt as pyjwt
  2804. private_pem, jwks_data = _make_test_rsa_key()
  2805. issuer_no_slash = "https://authentik.example.com/application/o/bambuddy"
  2806. issuer_with_slash = issuer_no_slash + "/"
  2807. client_id = "bambuddy-client"
  2808. nonce = secrets.token_urlsafe(16)
  2809. now = int(time.time())
  2810. id_token = pyjwt.encode(
  2811. {
  2812. "sub": "authentik-sub-123",
  2813. "iss": issuer_with_slash,
  2814. "aud": client_id,
  2815. "nonce": nonce,
  2816. "email": "authentik-user@example.com",
  2817. "email_verified": True,
  2818. "iat": now,
  2819. "exp": now + 300,
  2820. },
  2821. private_pem,
  2822. algorithm="RS256",
  2823. headers={"kid": "test-kid-1"},
  2824. )
  2825. admin_token = await _setup_and_login(async_client, "authentikadm", "authentikadm1")
  2826. create_resp = await async_client.post(
  2827. "/api/v1/auth/oidc/providers",
  2828. json={
  2829. "name": "Authentik-ISS",
  2830. "issuer_url": issuer_no_slash,
  2831. "client_id": client_id,
  2832. "client_secret": "secret",
  2833. "scopes": "openid email profile",
  2834. "is_enabled": True,
  2835. "auto_create_users": True,
  2836. },
  2837. headers=_auth_header(admin_token),
  2838. )
  2839. assert create_resp.status_code == 201
  2840. provider_id = create_resp.json()["id"]
  2841. state = secrets.token_urlsafe(32)
  2842. code_verifier = secrets.token_urlsafe(48)
  2843. db_session.add(
  2844. AuthEphemeralToken(
  2845. token=state,
  2846. token_type="oidc_state",
  2847. provider_id=provider_id,
  2848. nonce=nonce,
  2849. code_verifier=code_verifier,
  2850. expires_at=datetime.now(timezone.utc) + timedelta(minutes=5),
  2851. )
  2852. )
  2853. await db_session.commit()
  2854. discovery_doc = {
  2855. "issuer": issuer_with_slash,
  2856. "authorization_endpoint": f"{issuer_no_slash}/authorize",
  2857. "token_endpoint": f"{issuer_no_slash}/token",
  2858. "jwks_uri": f"{issuer_no_slash}/.well-known/jwks.json",
  2859. }
  2860. token_response = {"access_token": "mock", "token_type": "Bearer", "id_token": id_token}
  2861. class _MockResp:
  2862. def __init__(self, data):
  2863. self._data = data
  2864. self.is_success = True
  2865. self.status_code = 200
  2866. self.text = str(data)
  2867. def json(self):
  2868. return self._data
  2869. def raise_for_status(self):
  2870. pass
  2871. class _MockHttpxClient:
  2872. def __init__(self, *a, **kw):
  2873. pass
  2874. async def __aenter__(self):
  2875. return self
  2876. async def __aexit__(self, *a):
  2877. pass
  2878. async def get(self, url, **kw):
  2879. return _MockResp(jwks_data if "jwks" in url else discovery_doc)
  2880. async def post(self, url, **kw):
  2881. return _MockResp(token_response)
  2882. with patch("backend.app.api.routes.mfa.httpx.AsyncClient", _MockHttpxClient):
  2883. resp = await async_client.get(
  2884. f"/api/v1/auth/oidc/callback?code=auth-code&state={state}",
  2885. follow_redirects=False,
  2886. )
  2887. location = resp.headers.get("location", "")
  2888. assert resp.status_code == 302, f"Expected redirect, got {resp.status_code}"
  2889. assert "token_validation_failed" not in location, (
  2890. "Trailing slash mismatch in iss claim must not cause token_validation_failed"
  2891. )
  2892. assert "oidc_token=" in location, f"Expected oidc_token in redirect, got: {location}"
  2893. class TestOIDCCallbackCodeLength:
  2894. """OIDC callback code/state query params must accept up to 2048 characters (OAuth spec)."""
  2895. @pytest.mark.asyncio
  2896. @pytest.mark.integration
  2897. async def test_code_512_chars_accepted(self, async_client: AsyncClient):
  2898. """A 512-character code (old limit) must not be rejected with 422."""
  2899. code = "a" * 512
  2900. resp = await async_client.get(
  2901. f"/api/v1/auth/oidc/callback?code={code}&state=bogus-state",
  2902. follow_redirects=False,
  2903. )
  2904. assert resp.status_code != 422, "512-char code must not be rejected by Pydantic"
  2905. @pytest.mark.asyncio
  2906. @pytest.mark.integration
  2907. async def test_code_2048_chars_accepted(self, async_client: AsyncClient):
  2908. """A 2048-character code must not be rejected with 422."""
  2909. code = "a" * 2048
  2910. resp = await async_client.get(
  2911. f"/api/v1/auth/oidc/callback?code={code}&state=bogus-state",
  2912. follow_redirects=False,
  2913. )
  2914. assert resp.status_code != 422, "2048-char code must not be rejected by Pydantic"
  2915. @pytest.mark.asyncio
  2916. @pytest.mark.integration
  2917. async def test_code_2049_chars_rejected(self, async_client: AsyncClient):
  2918. """A 2049-character code must be rejected with 422."""
  2919. code = "a" * 2049
  2920. resp = await async_client.get(
  2921. f"/api/v1/auth/oidc/callback?code={code}&state=bogus-state",
  2922. follow_redirects=False,
  2923. )
  2924. assert resp.status_code == 422, "2049-char code must be rejected by Pydantic"
  2925. @pytest.mark.asyncio
  2926. @pytest.mark.integration
  2927. async def test_state_512_chars_accepted(self, async_client: AsyncClient):
  2928. """A 512-character state (old limit) must not be rejected with 422."""
  2929. state = "a" * 512
  2930. resp = await async_client.get(
  2931. f"/api/v1/auth/oidc/callback?code=bogus-code&state={state}",
  2932. follow_redirects=False,
  2933. )
  2934. assert resp.status_code != 422, "512-char state must not be rejected by Pydantic"
  2935. @pytest.mark.asyncio
  2936. @pytest.mark.integration
  2937. async def test_state_2048_chars_accepted(self, async_client: AsyncClient):
  2938. """A 2048-character state must not be rejected with 422."""
  2939. state = "a" * 2048
  2940. resp = await async_client.get(
  2941. f"/api/v1/auth/oidc/callback?code=bogus-code&state={state}",
  2942. follow_redirects=False,
  2943. )
  2944. assert resp.status_code != 422, "2048-char state must not be rejected by Pydantic"
  2945. @pytest.mark.asyncio
  2946. @pytest.mark.integration
  2947. async def test_state_2049_chars_rejected(self, async_client: AsyncClient):
  2948. """A 2049-character state must be rejected with 422."""
  2949. state = "a" * 2049
  2950. resp = await async_client.get(
  2951. f"/api/v1/auth/oidc/callback?code=bogus-code&state={state}",
  2952. follow_redirects=False,
  2953. )
  2954. assert resp.status_code == 422, "2049-char state must be rejected by Pydantic"
  2955. # ---------------------------------------------------------------------------
  2956. # Helpers shared by TestOIDCEmailClaimResolution
  2957. # ---------------------------------------------------------------------------
  2958. async def _run_oidc_callback(
  2959. async_client: AsyncClient,
  2960. db_session: AsyncSession,
  2961. *,
  2962. provider_id: int,
  2963. claims: dict,
  2964. private_pem: bytes,
  2965. jwks_data: dict,
  2966. issuer: str,
  2967. client_id: str,
  2968. ) -> str:
  2969. """Run a full OIDC callback flow and return the redirect location."""
  2970. nonce = secrets.token_urlsafe(16)
  2971. now = int(time.time())
  2972. token_claims = {
  2973. "sub": claims.get("sub", f"sub-{secrets.token_hex(8)}"),
  2974. "iss": issuer,
  2975. "aud": client_id,
  2976. "nonce": nonce,
  2977. "iat": now,
  2978. "exp": now + 300,
  2979. **{k: v for k, v in claims.items() if k not in ("sub",)},
  2980. }
  2981. id_token = pyjwt.encode(token_claims, private_pem, algorithm="RS256", headers={"kid": "test-kid-1"})
  2982. state = secrets.token_urlsafe(32)
  2983. code_verifier = secrets.token_urlsafe(48)
  2984. db_session.add(
  2985. AuthEphemeralToken(
  2986. token=state,
  2987. token_type="oidc_state",
  2988. provider_id=provider_id,
  2989. nonce=nonce,
  2990. code_verifier=code_verifier,
  2991. expires_at=datetime.now(timezone.utc) + timedelta(minutes=5),
  2992. )
  2993. )
  2994. await db_session.commit()
  2995. discovery_doc = {
  2996. "issuer": issuer,
  2997. "authorization_endpoint": f"{issuer}/auth",
  2998. "token_endpoint": f"{issuer}/token",
  2999. "jwks_uri": f"{issuer}/.well-known/jwks.json",
  3000. }
  3001. token_response = {"access_token": "mock-access", "token_type": "Bearer", "id_token": id_token}
  3002. class _R:
  3003. def __init__(self, data):
  3004. self._data = data
  3005. self.status_code = 200
  3006. self.is_success = True
  3007. self.text = str(data)
  3008. def json(self):
  3009. return self._data
  3010. def raise_for_status(self):
  3011. pass
  3012. class _C:
  3013. def __init__(self, *a, **kw):
  3014. pass
  3015. async def __aenter__(self):
  3016. return self
  3017. async def __aexit__(self, *a):
  3018. pass
  3019. async def get(self, url, **kw):
  3020. return _R(jwks_data if "jwks" in url else discovery_doc)
  3021. async def post(self, url, **kw):
  3022. return _R(token_response)
  3023. with patch("backend.app.api.routes.mfa.httpx.AsyncClient", _C):
  3024. resp = await async_client.get(
  3025. f"/api/v1/auth/oidc/callback?code=test-code&state={state}",
  3026. follow_redirects=False,
  3027. )
  3028. return resp.headers.get("location", "")
  3029. class TestOIDCEmailClaimResolution:
  3030. """Three-case email resolution logic: Fall A / Fall B / Fall C."""
  3031. # ── shared helpers ────────────────────────────────────────────────────────
  3032. async def _create_provider(
  3033. self,
  3034. async_client: AsyncClient,
  3035. admin_token: str,
  3036. issuer: str,
  3037. client_id: str,
  3038. *,
  3039. email_claim: str = "email",
  3040. require_email_verified: bool = True,
  3041. auto_link_existing_accounts: bool = False,
  3042. suffix: str = "",
  3043. ) -> int:
  3044. resp = await async_client.post(
  3045. "/api/v1/auth/oidc/providers",
  3046. json={
  3047. "name": f"TestIdP-{suffix or secrets.token_hex(4)}",
  3048. "issuer_url": issuer,
  3049. "client_id": client_id,
  3050. "client_secret": "sec",
  3051. "scopes": "openid email profile",
  3052. "is_enabled": True,
  3053. "auto_create_users": True,
  3054. "auto_link_existing_accounts": auto_link_existing_accounts,
  3055. "email_claim": email_claim,
  3056. "require_email_verified": require_email_verified,
  3057. },
  3058. headers={"Authorization": f"Bearer {admin_token}"},
  3059. )
  3060. assert resp.status_code == 201, resp.text
  3061. return resp.json()["id"]
  3062. async def _get_oidc_link(self, db_session: AsyncSession, provider_id: int, sub: str):
  3063. from sqlalchemy import select
  3064. from backend.app.models.oidc_provider import UserOIDCLink
  3065. result = await db_session.execute(
  3066. select(UserOIDCLink)
  3067. .where(UserOIDCLink.provider_id == provider_id)
  3068. .where(UserOIDCLink.provider_user_id == sub)
  3069. )
  3070. return result.scalar_one_or_none()
  3071. # ── Parametrized matrix: Fall A / Fall B / Fall C ─────────────────────────
  3072. @pytest.mark.asyncio
  3073. @pytest.mark.integration
  3074. @pytest.mark.parametrize(
  3075. "email_claim,require_ev,claims,expected",
  3076. [
  3077. # Fall A: standard claim + require_ev=True (default)
  3078. ("email", True, {"email": "fa@example.com", "email_verified": True}, "fa@example.com"),
  3079. ("email", True, {"email": "fa@example.com", "email_verified": False}, None),
  3080. ("email", True, {"email": "fa@example.com"}, None), # Azure Entra with default config
  3081. # Fall A + SEC-2: malformed email claim rejected even when email_verified=True
  3082. ("email", True, {"email": "notanemail", "email_verified": True}, None),
  3083. # Fall B: standard claim + require_ev=False (Azure Entra permissive)
  3084. ("email", False, {"email": "fb@example.com", "email_verified": True}, "fb@example.com"),
  3085. ("email", False, {"email": "fb@example.com", "email_verified": False}, None),
  3086. ("email", False, {"email": "azure@company.com"}, "azure@company.com"), # ev absent → kept
  3087. # Fall B + SEC-2: malformed email claim rejected in permissive mode (ev absent)
  3088. ("email", False, {"email": "user@nodot"}, None),
  3089. # Fall B + SEC-2: shape check fires before email_verified=False drop
  3090. ("email", False, {"email": "notanemail", "email_verified": False}, None),
  3091. # Fall C: custom claim (preferred_username) — no email_verified check
  3092. ("preferred_username", True, {"preferred_username": "User@Company.COM"}, "user@company.com"),
  3093. ("preferred_username", True, {"preferred_username": " User@EXAMPLE.COM "}, "user@example.com"),
  3094. ("preferred_username", True, {"preferred_username": "justausername"}, None),
  3095. ("preferred_username", True, {"preferred_username": "@"}, None), # SEC-2: "@" only
  3096. ("preferred_username", True, {"preferred_username": "@domain.com"}, None), # SEC-2: empty local
  3097. ("preferred_username", True, {"preferred_username": "user@"}, None), # SEC-2: empty domain
  3098. ("preferred_username", True, {"preferred_username": "user@nodot"}, None), # SEC-2: no dot in domain
  3099. ("preferred_username", True, {}, None), # claim absent
  3100. # Fall C: email_verified=False present alongside custom claim — must NOT suppress the email
  3101. ("preferred_username", True, {"preferred_username": "user@co.com", "email_verified": False}, "user@co.com"),
  3102. ],
  3103. ids=[
  3104. "fall-a-ev-true",
  3105. "fall-a-ev-false",
  3106. "fall-a-ev-absent",
  3107. "fall-a-malformed-email",
  3108. "fall-b-ev-true",
  3109. "fall-b-ev-false",
  3110. "fall-b-ev-absent",
  3111. "fall-b-malformed-email",
  3112. "fall-b-malformed-email-ev-false",
  3113. "fall-c-valid-upn",
  3114. "fall-c-lowercase-strip",
  3115. "fall-c-no-at",
  3116. "fall-c-at-only",
  3117. "fall-c-empty-local",
  3118. "fall-c-empty-domain",
  3119. "fall-c-no-dot-in-domain",
  3120. "fall-c-claim-absent",
  3121. "fall-c-ev-false-ignored",
  3122. ],
  3123. )
  3124. async def test_email_resolution_matrix(
  3125. self,
  3126. async_client: AsyncClient,
  3127. db_session: AsyncSession,
  3128. email_claim: str,
  3129. require_ev: bool,
  3130. claims: dict,
  3131. expected: str | None,
  3132. ):
  3133. """C4: Verify link exists AND check provider_email — avoids false-passing on callback failure."""
  3134. issuer = "https://matrix.test"
  3135. client_id = "matrix-client"
  3136. admin_token = await _setup_and_login(async_client, "matrix_adm", "Matrix123!")
  3137. private_pem, jwks_data = _make_test_rsa_key()
  3138. provider_id = await self._create_provider(
  3139. async_client,
  3140. admin_token,
  3141. issuer,
  3142. client_id,
  3143. email_claim=email_claim,
  3144. require_email_verified=require_ev,
  3145. suffix="matrix",
  3146. )
  3147. sub = f"sub-matrix-{secrets.token_hex(6)}"
  3148. await _run_oidc_callback(
  3149. async_client,
  3150. db_session,
  3151. provider_id=provider_id,
  3152. claims={"sub": sub, **claims},
  3153. private_pem=private_pem,
  3154. jwks_data=jwks_data,
  3155. issuer=issuer,
  3156. client_id=client_id,
  3157. )
  3158. db_session.expire_all()
  3159. link = await self._get_oidc_link(db_session, provider_id, sub)
  3160. assert link is not None, "UserOIDCLink must be created even when email is dropped"
  3161. assert link.provider_email == expected
  3162. # ── Security: auto_link guards (CREATE endpoint) ──────────────────────────
  3163. @pytest.mark.asyncio
  3164. @pytest.mark.integration
  3165. async def test_auto_link_blocked_with_require_ev_false(self, async_client: AsyncClient):
  3166. """SEC-1: auto_link + require_email_verified=False must be rejected at schema level (422)."""
  3167. admin_token = await _setup_and_login(async_client, "sec1_adm", "Sec1Adm123!")
  3168. resp = await async_client.post(
  3169. "/api/v1/auth/oidc/providers",
  3170. json={
  3171. "name": "SEC1-Test",
  3172. "issuer_url": "https://sec1.test",
  3173. "client_id": "sec1-client",
  3174. "client_secret": "sec",
  3175. "scopes": "openid email profile",
  3176. "auto_link_existing_accounts": True,
  3177. "require_email_verified": False,
  3178. },
  3179. headers={"Authorization": f"Bearer {admin_token}"},
  3180. )
  3181. assert resp.status_code == 422
  3182. @pytest.mark.asyncio
  3183. @pytest.mark.integration
  3184. async def test_auto_link_allowed_with_custom_claim_create(self, async_client: AsyncClient):
  3185. """Fall C: auto_link + email_claim!='email' must be accepted on CREATE (201).
  3186. Custom claims (e.g. Azure preferred_username/upn) never perform an email_verified
  3187. check, so auto_link is safe regardless of require_email_verified.
  3188. """
  3189. admin_token = await _setup_and_login(async_client, "sec6c_adm", "Sec6CAdm123!")
  3190. resp = await async_client.post(
  3191. "/api/v1/auth/oidc/providers",
  3192. json={
  3193. "name": "SEC6-Create-Test",
  3194. "issuer_url": "https://sec6c.test",
  3195. "client_id": "sec6c-client",
  3196. "client_secret": "sec",
  3197. "scopes": "openid email profile",
  3198. "auto_link_existing_accounts": True,
  3199. "email_claim": "upn",
  3200. },
  3201. headers={"Authorization": f"Bearer {admin_token}"},
  3202. )
  3203. assert resp.status_code == 201
  3204. assert resp.json()["auto_link_existing_accounts"] is True
  3205. assert resp.json()["email_claim"] == "upn"
  3206. @pytest.mark.asyncio
  3207. @pytest.mark.integration
  3208. async def test_auto_link_allowed_with_custom_claim_update(self, async_client: AsyncClient):
  3209. """Fall C: auto_link=True + email_claim='upn' in same UPDATE request → 200.
  3210. Custom claims never perform an email_verified check, so auto_link is safe.
  3211. """
  3212. admin_token = await _setup_and_login(async_client, "sec6u_adm", "Sec6UAdm123!")
  3213. create_resp = await async_client.post(
  3214. "/api/v1/auth/oidc/providers",
  3215. json={
  3216. "name": "SEC6-Update-Test",
  3217. "issuer_url": "https://sec6u.test",
  3218. "client_id": "sec6u-client",
  3219. "client_secret": "sec",
  3220. "scopes": "openid email profile",
  3221. },
  3222. headers={"Authorization": f"Bearer {admin_token}"},
  3223. )
  3224. assert create_resp.status_code == 201
  3225. provider_id = create_resp.json()["id"]
  3226. resp = await async_client.put(
  3227. f"/api/v1/auth/oidc/providers/{provider_id}",
  3228. json={"auto_link_existing_accounts": True, "email_claim": "upn"},
  3229. headers={"Authorization": f"Bearer {admin_token}"},
  3230. )
  3231. assert resp.status_code == 200
  3232. assert resp.json()["auto_link_existing_accounts"] is True
  3233. assert resp.json()["email_claim"] == "upn"
  3234. # ── Combined-State-Guard (partial updates across two requests) ─────────────
  3235. @pytest.mark.asyncio
  3236. @pytest.mark.integration
  3237. async def test_partial_update_guard_require_ev(self, async_client: AsyncClient):
  3238. """SEC-1 Combined-State-Guard: require_ev=False then auto_link=True → 422 (T1 require_ev path)."""
  3239. admin_token = await _setup_and_login(async_client, "pg_rev_adm", "PgRev123!")
  3240. create_resp = await async_client.post(
  3241. "/api/v1/auth/oidc/providers",
  3242. json={
  3243. "name": "PG-RequireEV-Test",
  3244. "issuer_url": "https://pg-rev.test",
  3245. "client_id": "pg-rev-client",
  3246. "client_secret": "sec",
  3247. "scopes": "openid email profile",
  3248. },
  3249. headers={"Authorization": f"Bearer {admin_token}"},
  3250. )
  3251. assert create_resp.status_code == 201
  3252. provider_id = create_resp.json()["id"]
  3253. upd1 = await async_client.put(
  3254. f"/api/v1/auth/oidc/providers/{provider_id}",
  3255. json={"require_email_verified": False},
  3256. headers={"Authorization": f"Bearer {admin_token}"},
  3257. )
  3258. assert upd1.status_code == 200
  3259. upd2 = await async_client.put(
  3260. f"/api/v1/auth/oidc/providers/{provider_id}",
  3261. json={"auto_link_existing_accounts": True},
  3262. headers={"Authorization": f"Bearer {admin_token}"},
  3263. )
  3264. assert upd2.status_code == 422
  3265. @pytest.mark.asyncio
  3266. @pytest.mark.integration
  3267. async def test_partial_update_custom_claim_then_auto_link_allowed(self, async_client: AsyncClient):
  3268. """Fall C: email_claim='upn' first, then auto_link=True → both 200 (custom claim is safe)."""
  3269. admin_token = await _setup_and_login(async_client, "pg_ec_adm", "PgEc123!")
  3270. create_resp = await async_client.post(
  3271. "/api/v1/auth/oidc/providers",
  3272. json={
  3273. "name": "PG-EmailClaim-Test",
  3274. "issuer_url": "https://pg-ec.test",
  3275. "client_id": "pg-ec-client",
  3276. "client_secret": "sec",
  3277. "scopes": "openid email profile",
  3278. },
  3279. headers={"Authorization": f"Bearer {admin_token}"},
  3280. )
  3281. assert create_resp.status_code == 201
  3282. provider_id = create_resp.json()["id"]
  3283. upd1 = await async_client.put(
  3284. f"/api/v1/auth/oidc/providers/{provider_id}",
  3285. json={"email_claim": "upn"},
  3286. headers={"Authorization": f"Bearer {admin_token}"},
  3287. )
  3288. assert upd1.status_code == 200
  3289. upd2 = await async_client.put(
  3290. f"/api/v1/auth/oidc/providers/{provider_id}",
  3291. json={"auto_link_existing_accounts": True},
  3292. headers={"Authorization": f"Bearer {admin_token}"},
  3293. )
  3294. assert upd2.status_code == 200
  3295. assert upd2.json()["auto_link_existing_accounts"] is True
  3296. assert upd2.json()["email_claim"] == "upn"
  3297. @pytest.mark.asyncio
  3298. @pytest.mark.integration
  3299. async def test_partial_update_auto_link_then_custom_claim_allowed(self, async_client: AsyncClient):
  3300. """Fall C: auto_link=True first (email_claim='email', safe), then email_claim='upn' → both 200."""
  3301. admin_token = await _setup_and_login(async_client, "pg_al_ec_adm", "PgAlEc123!")
  3302. create_resp = await async_client.post(
  3303. "/api/v1/auth/oidc/providers",
  3304. json={
  3305. "name": "PG-AutoLink-Claim-Test",
  3306. "issuer_url": "https://pg-al-ec.test",
  3307. "client_id": "pg-al-ec-client",
  3308. "client_secret": "sec",
  3309. "scopes": "openid email profile",
  3310. },
  3311. headers={"Authorization": f"Bearer {admin_token}"},
  3312. )
  3313. assert create_resp.status_code == 201
  3314. provider_id = create_resp.json()["id"]
  3315. upd1 = await async_client.put(
  3316. f"/api/v1/auth/oidc/providers/{provider_id}",
  3317. json={"auto_link_existing_accounts": True},
  3318. headers={"Authorization": f"Bearer {admin_token}"},
  3319. )
  3320. assert upd1.status_code == 200
  3321. upd2 = await async_client.put(
  3322. f"/api/v1/auth/oidc/providers/{provider_id}",
  3323. json={"email_claim": "preferred_username"},
  3324. headers={"Authorization": f"Bearer {admin_token}"},
  3325. )
  3326. assert upd2.status_code == 200
  3327. assert upd2.json()["auto_link_existing_accounts"] is True
  3328. assert upd2.json()["email_claim"] == "preferred_username"
  3329. @pytest.mark.asyncio
  3330. @pytest.mark.integration
  3331. async def test_partial_update_guard_inverse_order(self, async_client: AsyncClient):
  3332. """T2: auto_link=True first (valid), then require_ev=False → Combined-State-Guard fires (422)."""
  3333. admin_token = await _setup_and_login(async_client, "pg_inv_adm", "PgInv123!")
  3334. create_resp = await async_client.post(
  3335. "/api/v1/auth/oidc/providers",
  3336. json={
  3337. "name": "PG-Inverse-Test",
  3338. "issuer_url": "https://pg-inv.test",
  3339. "client_id": "pg-inv-client",
  3340. "client_secret": "sec",
  3341. "scopes": "openid email profile",
  3342. },
  3343. headers={"Authorization": f"Bearer {admin_token}"},
  3344. )
  3345. assert create_resp.status_code == 201
  3346. provider_id = create_resp.json()["id"]
  3347. # auto_link=True is safe when require_ev=True (default)
  3348. upd1 = await async_client.put(
  3349. f"/api/v1/auth/oidc/providers/{provider_id}",
  3350. json={"auto_link_existing_accounts": True},
  3351. headers={"Authorization": f"Bearer {admin_token}"},
  3352. )
  3353. assert upd1.status_code == 200
  3354. # Disabling require_ev with auto_link already on → unsafe combined state
  3355. upd2 = await async_client.put(
  3356. f"/api/v1/auth/oidc/providers/{provider_id}",
  3357. json={"require_email_verified": False},
  3358. headers={"Authorization": f"Bearer {admin_token}"},
  3359. )
  3360. assert upd2.status_code == 422
  3361. # ── Low5: Response fields verified ───────────────────────────────────────
  3362. @pytest.mark.asyncio
  3363. @pytest.mark.integration
  3364. async def test_create_response_includes_new_fields(self, async_client: AsyncClient):
  3365. """Low5: OIDCProviderResponse must include email_claim and require_email_verified."""
  3366. admin_token = await _setup_and_login(async_client, "resp_adm", "Resp123!")
  3367. resp = await async_client.post(
  3368. "/api/v1/auth/oidc/providers",
  3369. json={
  3370. "name": "ResponseFields-Test",
  3371. "issuer_url": "https://resp.test",
  3372. "client_id": "resp-client",
  3373. "client_secret": "sec",
  3374. "scopes": "openid email profile",
  3375. "email_claim": "preferred_username",
  3376. "require_email_verified": False,
  3377. },
  3378. headers={"Authorization": f"Bearer {admin_token}"},
  3379. )
  3380. assert resp.status_code == 201
  3381. data = resp.json()
  3382. assert data["email_claim"] == "preferred_username"
  3383. assert data["require_email_verified"] is False
  3384. @pytest.mark.asyncio
  3385. @pytest.mark.integration
  3386. async def test_update_response_reflects_new_fields(self, async_client: AsyncClient):
  3387. """Low5: PUT response must reflect updated email_claim and require_email_verified."""
  3388. admin_token = await _setup_and_login(async_client, "upd_resp_adm", "UpdResp123!")
  3389. create_resp = await async_client.post(
  3390. "/api/v1/auth/oidc/providers",
  3391. json={
  3392. "name": "UpdateResponse-Test",
  3393. "issuer_url": "https://upd-resp.test",
  3394. "client_id": "upd-resp-client",
  3395. "client_secret": "sec",
  3396. "scopes": "openid email profile",
  3397. },
  3398. headers={"Authorization": f"Bearer {admin_token}"},
  3399. )
  3400. assert create_resp.status_code == 201
  3401. provider_id = create_resp.json()["id"]
  3402. upd = await async_client.put(
  3403. f"/api/v1/auth/oidc/providers/{provider_id}",
  3404. json={"email_claim": "upn", "require_email_verified": True},
  3405. headers={"Authorization": f"Bearer {admin_token}"},
  3406. )
  3407. assert upd.status_code == 200
  3408. data = upd.json()
  3409. assert data["email_claim"] == "upn"
  3410. assert data["require_email_verified"] is True
  3411. # ===========================================================================
  3412. # TestOIDCEmailClaimValidation — T2: email_claim field validator coverage
  3413. # ===========================================================================
  3414. class TestOIDCEmailClaimValidation:
  3415. """Schema-level validation for the email_claim field."""
  3416. @pytest.mark.asyncio
  3417. @pytest.mark.integration
  3418. async def test_invalid_claim_name_dot_rejected(self, async_client: AsyncClient):
  3419. """email_claim with a dot (log-injection risk) must be rejected."""
  3420. admin_token = await _setup_and_login(async_client, "ecv_adm1", "Ecv123!")
  3421. resp = await async_client.post(
  3422. "/api/v1/auth/oidc/providers",
  3423. json={
  3424. "name": "ECVTest1",
  3425. "issuer_url": "https://ecv1.test",
  3426. "client_id": "ecv1",
  3427. "client_secret": "sec",
  3428. "scopes": "openid email",
  3429. "email_claim": "email.address",
  3430. },
  3431. headers={"Authorization": f"Bearer {admin_token}"},
  3432. )
  3433. assert resp.status_code == 422
  3434. @pytest.mark.asyncio
  3435. @pytest.mark.integration
  3436. async def test_invalid_claim_name_starts_with_digit_rejected(self, async_client: AsyncClient):
  3437. admin_token = await _setup_and_login(async_client, "ecv_adm2", "Ecv123!")
  3438. resp = await async_client.post(
  3439. "/api/v1/auth/oidc/providers",
  3440. json={
  3441. "name": "ECVTest2",
  3442. "issuer_url": "https://ecv2.test",
  3443. "client_id": "ecv2",
  3444. "client_secret": "sec",
  3445. "scopes": "openid email",
  3446. "email_claim": "1invalid",
  3447. },
  3448. headers={"Authorization": f"Bearer {admin_token}"},
  3449. )
  3450. assert resp.status_code == 422
  3451. @pytest.mark.asyncio
  3452. @pytest.mark.integration
  3453. async def test_invalid_claim_name_newline_rejected(self, async_client: AsyncClient):
  3454. """T2 regex-bug guard: re.fullmatch must reject trailing newline."""
  3455. admin_token = await _setup_and_login(async_client, "ecv_adm3", "Ecv123!")
  3456. resp = await async_client.post(
  3457. "/api/v1/auth/oidc/providers",
  3458. json={
  3459. "name": "ECVTest3",
  3460. "issuer_url": "https://ecv3.test",
  3461. "client_id": "ecv3",
  3462. "client_secret": "sec",
  3463. "scopes": "openid email",
  3464. "email_claim": "email\n",
  3465. },
  3466. headers={"Authorization": f"Bearer {admin_token}"},
  3467. )
  3468. assert resp.status_code == 422
  3469. @pytest.mark.asyncio
  3470. @pytest.mark.integration
  3471. async def test_claim_name_65_chars_rejected(self, async_client: AsyncClient):
  3472. """email_claim longer than 64 characters must be rejected."""
  3473. admin_token = await _setup_and_login(async_client, "ecv_adm4", "Ecv123!")
  3474. resp = await async_client.post(
  3475. "/api/v1/auth/oidc/providers",
  3476. json={
  3477. "name": "ECVTest4",
  3478. "issuer_url": "https://ecv4.test",
  3479. "client_id": "ecv4",
  3480. "client_secret": "sec",
  3481. "scopes": "openid email",
  3482. "email_claim": "a" * 65,
  3483. },
  3484. headers={"Authorization": f"Bearer {admin_token}"},
  3485. )
  3486. assert resp.status_code == 422
  3487. @pytest.mark.asyncio
  3488. @pytest.mark.integration
  3489. async def test_valid_claim_name_accepted(self, async_client: AsyncClient):
  3490. """Valid claim names like preferred_username and upn must be accepted."""
  3491. admin_token = await _setup_and_login(async_client, "ecv_adm5", "Ecv123!")
  3492. for claim in ("preferred_username", "upn", "email", "emailAddress"):
  3493. resp = await async_client.post(
  3494. "/api/v1/auth/oidc/providers",
  3495. json={
  3496. "name": f"ECVTest-{claim[:8]}",
  3497. "issuer_url": f"https://ecv-{claim[:8]}.test",
  3498. "client_id": f"ecv-{claim[:8]}",
  3499. "client_secret": "sec",
  3500. "scopes": "openid email",
  3501. "email_claim": claim,
  3502. },
  3503. headers={"Authorization": f"Bearer {admin_token}"},
  3504. )
  3505. assert resp.status_code == 201, f"claim {claim!r} was rejected: {resp.text}"
  3506. # ===========================================================================
  3507. # TestOIDCEmailResolutionExtra — T1 / T3 / T4 additional coverage
  3508. # ===========================================================================
  3509. async def _create_provider_via_api(
  3510. async_client: AsyncClient,
  3511. admin_token: str,
  3512. issuer: str,
  3513. client_id: str,
  3514. *,
  3515. email_claim: str = "email",
  3516. require_email_verified: bool = True,
  3517. suffix: str = "",
  3518. ) -> int:
  3519. resp = await async_client.post(
  3520. "/api/v1/auth/oidc/providers",
  3521. json={
  3522. "name": f"TestIdP-extra-{suffix or secrets.token_hex(4)}",
  3523. "issuer_url": issuer,
  3524. "client_id": client_id,
  3525. "client_secret": "sec",
  3526. "scopes": "openid email profile",
  3527. "is_enabled": True,
  3528. "auto_create_users": True,
  3529. "email_claim": email_claim,
  3530. "require_email_verified": require_email_verified,
  3531. },
  3532. headers={"Authorization": f"Bearer {admin_token}"},
  3533. )
  3534. assert resp.status_code == 201, resp.text
  3535. return resp.json()["id"]
  3536. class TestOIDCEmailResolutionExtra:
  3537. """T1: isinstance guard, T3: SEC-3 normalisation for Fall A/B, T4: inverse Combined-State-Guard."""
  3538. @pytest.mark.asyncio
  3539. @pytest.mark.integration
  3540. async def test_non_string_claim_value_drops_email(
  3541. self,
  3542. async_client: AsyncClient,
  3543. db_session: AsyncSession,
  3544. ):
  3545. """T1: A non-string email_claim value (list) must be silently dropped — no crash."""
  3546. private_pem, jwks_data = _make_test_rsa_key()
  3547. issuer = "https://nonstring-test.example"
  3548. client_id = "nonstring-client"
  3549. admin_token = await _setup_and_login(async_client, "nonstr_adm", "Nonstr123!")
  3550. provider_id = await _create_provider_via_api(
  3551. async_client,
  3552. admin_token,
  3553. issuer,
  3554. client_id,
  3555. email_claim="preferred_username",
  3556. require_email_verified=False,
  3557. suffix="nonstr",
  3558. )
  3559. from sqlalchemy import select
  3560. from backend.app.models.oidc_provider import UserOIDCLink
  3561. # IdP sends preferred_username as a list (non-string) — must not crash
  3562. location = await _run_oidc_callback(
  3563. async_client,
  3564. db_session,
  3565. provider_id=provider_id,
  3566. claims={"sub": "nonstr-sub-1", "preferred_username": ["user@example.com"]},
  3567. private_pem=private_pem,
  3568. jwks_data=jwks_data,
  3569. issuer=issuer,
  3570. client_id=client_id,
  3571. )
  3572. assert "internal_error" not in location, f"Unexpected error redirect: {location}"
  3573. link_result = await db_session.execute(
  3574. select(UserOIDCLink)
  3575. .where(UserOIDCLink.provider_id == provider_id)
  3576. .where(UserOIDCLink.provider_user_id == "nonstr-sub-1")
  3577. )
  3578. link = link_result.scalar_one_or_none()
  3579. assert link is not None
  3580. assert link.provider_email is None # list value dropped
  3581. @pytest.mark.asyncio
  3582. @pytest.mark.integration
  3583. async def test_fall_a_sec3_normalisation(
  3584. self,
  3585. async_client: AsyncClient,
  3586. db_session: AsyncSession,
  3587. ):
  3588. """T3: Fall A — uppercase + whitespace in email claim must be normalised to lowercase."""
  3589. private_pem, jwks_data = _make_test_rsa_key()
  3590. issuer = "https://sec3a-test.example"
  3591. client_id = "sec3a-client"
  3592. admin_token = await _setup_and_login(async_client, "sec3a_adm", "Sec3a123!")
  3593. provider_id = await _create_provider_via_api(
  3594. async_client,
  3595. admin_token,
  3596. issuer,
  3597. client_id,
  3598. email_claim="email",
  3599. require_email_verified=True,
  3600. suffix="sec3a",
  3601. )
  3602. from sqlalchemy import select
  3603. from backend.app.models.oidc_provider import UserOIDCLink
  3604. location = await _run_oidc_callback(
  3605. async_client,
  3606. db_session,
  3607. provider_id=provider_id,
  3608. claims={"sub": "sec3a-sub-1", "email": " USER@EXAMPLE.COM ", "email_verified": True},
  3609. private_pem=private_pem,
  3610. jwks_data=jwks_data,
  3611. issuer=issuer,
  3612. client_id=client_id,
  3613. )
  3614. assert "internal_error" not in location
  3615. link_result = await db_session.execute(
  3616. select(UserOIDCLink)
  3617. .where(UserOIDCLink.provider_id == provider_id)
  3618. .where(UserOIDCLink.provider_user_id == "sec3a-sub-1")
  3619. )
  3620. link = link_result.scalar_one_or_none()
  3621. assert link is not None
  3622. assert link.provider_email == "user@example.com"
  3623. @pytest.mark.asyncio
  3624. @pytest.mark.integration
  3625. async def test_fall_b_sec3_normalisation(
  3626. self,
  3627. async_client: AsyncClient,
  3628. db_session: AsyncSession,
  3629. ):
  3630. """T3: Fall B — uppercase + whitespace in email claim must be normalised to lowercase."""
  3631. private_pem, jwks_data = _make_test_rsa_key()
  3632. issuer = "https://sec3b-test.example"
  3633. client_id = "sec3b-client"
  3634. admin_token = await _setup_and_login(async_client, "sec3b_adm", "Sec3b123!")
  3635. provider_id = await _create_provider_via_api(
  3636. async_client,
  3637. admin_token,
  3638. issuer,
  3639. client_id,
  3640. email_claim="email",
  3641. require_email_verified=False,
  3642. suffix="sec3b",
  3643. )
  3644. from sqlalchemy import select
  3645. from backend.app.models.oidc_provider import UserOIDCLink
  3646. location = await _run_oidc_callback(
  3647. async_client,
  3648. db_session,
  3649. provider_id=provider_id,
  3650. claims={"sub": "sec3b-sub-1", "email": " USER@EXAMPLE.COM "},
  3651. private_pem=private_pem,
  3652. jwks_data=jwks_data,
  3653. issuer=issuer,
  3654. client_id=client_id,
  3655. )
  3656. assert "internal_error" not in location
  3657. link_result = await db_session.execute(
  3658. select(UserOIDCLink)
  3659. .where(UserOIDCLink.provider_id == provider_id)
  3660. .where(UserOIDCLink.provider_user_id == "sec3b-sub-1")
  3661. )
  3662. link = link_result.scalar_one_or_none()
  3663. assert link is not None
  3664. assert link.provider_email == "user@example.com"
  3665. @pytest.mark.asyncio
  3666. @pytest.mark.integration
  3667. async def test_combined_state_guard_email_claim_inverse_order(self, async_client: AsyncClient):
  3668. """Fall C: auto_link=True first, then switch email_claim to custom → both 200 (now allowed).
  3669. Custom claims never perform an email_verified check, so switching to a custom claim
  3670. while auto_link is on transitions from Fall A to Fall C — both are safe.
  3671. """
  3672. admin_token = await _setup_and_login(async_client, "inv_ec_adm", "InvEc123!")
  3673. create_resp = await async_client.post(
  3674. "/api/v1/auth/oidc/providers",
  3675. json={
  3676. "name": "InvEcTest",
  3677. "issuer_url": "https://inv-ec.test",
  3678. "client_id": "inv-ec",
  3679. "client_secret": "sec",
  3680. "scopes": "openid email",
  3681. },
  3682. headers={"Authorization": f"Bearer {admin_token}"},
  3683. )
  3684. assert create_resp.status_code == 201
  3685. provider_id = create_resp.json()["id"]
  3686. # First: enable auto_link (Fall A — email_claim='email', require_ev=True)
  3687. upd1 = await async_client.put(
  3688. f"/api/v1/auth/oidc/providers/{provider_id}",
  3689. json={"auto_link_existing_accounts": True},
  3690. headers={"Authorization": f"Bearer {admin_token}"},
  3691. )
  3692. assert upd1.status_code == 200
  3693. # Second: switch to custom claim → Fall C, still safe
  3694. upd2 = await async_client.put(
  3695. f"/api/v1/auth/oidc/providers/{provider_id}",
  3696. json={"email_claim": "preferred_username"},
  3697. headers={"Authorization": f"Bearer {admin_token}"},
  3698. )
  3699. assert upd2.status_code == 200
  3700. assert upd2.json()["auto_link_existing_accounts"] is True
  3701. assert upd2.json()["email_claim"] == "preferred_username"
  3702. # ===========================================================================
  3703. # Issue #1569: standard 'email' claim fallback for User.email during
  3704. # auto-provisioning when email_claim is a non-email identity claim.
  3705. # ===========================================================================
  3706. class TestOIDCStandardEmailFallback:
  3707. """Issue #1569: when email_claim is set to a non-email identity claim
  3708. (e.g. preferred_username on Authentik) and the IdP token also carries a
  3709. standard 'email' claim, auto-created users get User.email from the
  3710. standard claim — without affecting the auto-link gate."""
  3711. async def _get_user_and_link(self, db_session: AsyncSession, provider_id: int, sub: str):
  3712. from sqlalchemy import select
  3713. from backend.app.models.oidc_provider import UserOIDCLink
  3714. from backend.app.models.user import User as UserModel
  3715. link_result = await db_session.execute(
  3716. select(UserOIDCLink)
  3717. .where(UserOIDCLink.provider_id == provider_id)
  3718. .where(UserOIDCLink.provider_user_id == sub)
  3719. )
  3720. link = link_result.scalar_one_or_none()
  3721. if link is None:
  3722. return None, None
  3723. user_result = await db_session.execute(select(UserModel).where(UserModel.id == link.user_id))
  3724. return user_result.scalar_one_or_none(), link
  3725. @pytest.mark.asyncio
  3726. @pytest.mark.integration
  3727. async def test_email_claim_preferred_username_falls_back_to_standard_email(
  3728. self,
  3729. async_client: AsyncClient,
  3730. db_session: AsyncSession,
  3731. ):
  3732. """email_claim=preferred_username + both claims → username from preferred_username,
  3733. email populated from the standard 'email' claim."""
  3734. private_pem, jwks_data = _make_test_rsa_key()
  3735. issuer = "https://issue1569-both.example"
  3736. client_id = "issue1569-both-client"
  3737. admin_token = await _setup_and_login(async_client, "i1569b_adm", "I1569b123!")
  3738. provider_id = await _create_provider_via_api(
  3739. async_client,
  3740. admin_token,
  3741. issuer,
  3742. client_id,
  3743. email_claim="preferred_username",
  3744. require_email_verified=False,
  3745. suffix="i1569both",
  3746. )
  3747. sub = f"sub-i1569-both-{secrets.token_hex(6)}"
  3748. await _run_oidc_callback(
  3749. async_client,
  3750. db_session,
  3751. provider_id=provider_id,
  3752. claims={
  3753. "sub": sub,
  3754. "preferred_username": "jdoe",
  3755. "email": "jdoe@example.com",
  3756. "email_verified": True,
  3757. },
  3758. private_pem=private_pem,
  3759. jwks_data=jwks_data,
  3760. issuer=issuer,
  3761. client_id=client_id,
  3762. )
  3763. db_session.expire_all()
  3764. user, link = await self._get_user_and_link(db_session, provider_id, sub)
  3765. assert user is not None and link is not None
  3766. assert user.username == "jdoe"
  3767. assert user.email == "jdoe@example.com"
  3768. assert link.provider_email == "jdoe@example.com"
  3769. @pytest.mark.asyncio
  3770. @pytest.mark.integration
  3771. async def test_email_claim_preferred_username_no_standard_email_keeps_email_none(
  3772. self,
  3773. async_client: AsyncClient,
  3774. db_session: AsyncSession,
  3775. ):
  3776. """email_claim=preferred_username + no standard 'email' claim → behaviour unchanged:
  3777. username derived from preferred_username, User.email stays None."""
  3778. private_pem, jwks_data = _make_test_rsa_key()
  3779. issuer = "https://issue1569-noemail.example"
  3780. client_id = "issue1569-noemail-client"
  3781. admin_token = await _setup_and_login(async_client, "i1569n_adm", "I1569n123!")
  3782. provider_id = await _create_provider_via_api(
  3783. async_client,
  3784. admin_token,
  3785. issuer,
  3786. client_id,
  3787. email_claim="preferred_username",
  3788. require_email_verified=False,
  3789. suffix="i1569none",
  3790. )
  3791. sub = f"sub-i1569-none-{secrets.token_hex(6)}"
  3792. await _run_oidc_callback(
  3793. async_client,
  3794. db_session,
  3795. provider_id=provider_id,
  3796. claims={"sub": sub, "preferred_username": "jdoe2"},
  3797. private_pem=private_pem,
  3798. jwks_data=jwks_data,
  3799. issuer=issuer,
  3800. client_id=client_id,
  3801. )
  3802. db_session.expire_all()
  3803. user, link = await self._get_user_and_link(db_session, provider_id, sub)
  3804. assert user is not None and link is not None
  3805. assert user.username == "jdoe2"
  3806. assert user.email is None
  3807. assert link.provider_email is None
  3808. @pytest.mark.asyncio
  3809. @pytest.mark.integration
  3810. async def test_fallback_respects_email_verified_false(
  3811. self,
  3812. async_client: AsyncClient,
  3813. db_session: AsyncSession,
  3814. ):
  3815. """email_claim=preferred_username + standard 'email' claim with email_verified=False
  3816. → fallback drops the email (User.email None) — matches Fall B semantics."""
  3817. private_pem, jwks_data = _make_test_rsa_key()
  3818. issuer = "https://issue1569-evfalse.example"
  3819. client_id = "issue1569-evfalse-client"
  3820. admin_token = await _setup_and_login(async_client, "i1569f_adm", "I1569f123!")
  3821. provider_id = await _create_provider_via_api(
  3822. async_client,
  3823. admin_token,
  3824. issuer,
  3825. client_id,
  3826. email_claim="preferred_username",
  3827. require_email_verified=False,
  3828. suffix="i1569evfalse",
  3829. )
  3830. sub = f"sub-i1569-evfalse-{secrets.token_hex(6)}"
  3831. await _run_oidc_callback(
  3832. async_client,
  3833. db_session,
  3834. provider_id=provider_id,
  3835. claims={
  3836. "sub": sub,
  3837. "preferred_username": "jdoe3",
  3838. "email": "jdoe3@example.com",
  3839. "email_verified": False,
  3840. },
  3841. private_pem=private_pem,
  3842. jwks_data=jwks_data,
  3843. issuer=issuer,
  3844. client_id=client_id,
  3845. )
  3846. db_session.expire_all()
  3847. user, link = await self._get_user_and_link(db_session, provider_id, sub)
  3848. assert user is not None and link is not None
  3849. assert user.username == "jdoe3"
  3850. assert user.email is None
  3851. assert link.provider_email is None
  3852. @pytest.mark.asyncio
  3853. @pytest.mark.integration
  3854. async def test_fallback_skipped_when_email_claim_is_email(
  3855. self,
  3856. async_client: AsyncClient,
  3857. db_session: AsyncSession,
  3858. ):
  3859. """email_claim='email' (default) — fallback path must NOT fire. Primary
  3860. resolver result is authoritative; this guards against the fallback
  3861. accidentally widening Fall-A/B semantics."""
  3862. private_pem, jwks_data = _make_test_rsa_key()
  3863. issuer = "https://issue1569-default.example"
  3864. client_id = "issue1569-default-client"
  3865. admin_token = await _setup_and_login(async_client, "i1569d_adm", "I1569d123!")
  3866. provider_id = await _create_provider_via_api(
  3867. async_client,
  3868. admin_token,
  3869. issuer,
  3870. client_id,
  3871. email_claim="email",
  3872. require_email_verified=True,
  3873. suffix="i1569default",
  3874. )
  3875. sub = f"sub-i1569-default-{secrets.token_hex(6)}"
  3876. # email_verified absent → Fall A drops it. Fallback must NOT
  3877. # re-instate the email since email_claim='email' is already the
  3878. # primary path.
  3879. await _run_oidc_callback(
  3880. async_client,
  3881. db_session,
  3882. provider_id=provider_id,
  3883. claims={"sub": sub, "email": "jdoe4@example.com"},
  3884. private_pem=private_pem,
  3885. jwks_data=jwks_data,
  3886. issuer=issuer,
  3887. client_id=client_id,
  3888. )
  3889. db_session.expire_all()
  3890. user, link = await self._get_user_and_link(db_session, provider_id, sub)
  3891. assert user is not None and link is not None
  3892. assert user.email is None
  3893. assert link.provider_email is None
  3894. # ===========================================================================
  3895. # E2E: Fall C (custom email claim) auto-link actually links existing user
  3896. # ===========================================================================
  3897. class TestOIDCFallCAutoLinkE2E:
  3898. """OIDC callback with email_claim='preferred_username' (Fall C / Azure Entra ID)
  3899. must auto-link an existing local user when auto_link_existing_accounts=True.
  3900. This test exercises _resolve_provider_email Fall C and the auto-link path in
  3901. oidc_callback — a regression in either would silently drop the link without
  3902. being caught by the configuration-layer tests.
  3903. """
  3904. @pytest.mark.asyncio
  3905. @pytest.mark.integration
  3906. async def test_fall_c_auto_link_links_existing_user_via_callback(
  3907. self, async_client: AsyncClient, db_session: AsyncSession
  3908. ):
  3909. from unittest.mock import AsyncMock, MagicMock, patch
  3910. from sqlalchemy import select as sa_select
  3911. from backend.app.core.auth import get_password_hash
  3912. from backend.app.models.oidc_provider import OIDCProvider, UserOIDCLink
  3913. issuer = "https://entra.fallc.example.com"
  3914. nonce = secrets.token_urlsafe(32)
  3915. code_verifier = secrets.token_urlsafe(48)
  3916. # ── 1. Local user that should be linked ──────────────────────────────
  3917. alice = User(
  3918. username="fallc_alice",
  3919. email="alice.fallc@example.com",
  3920. password_hash=get_password_hash(secrets.token_urlsafe(16)),
  3921. role="user",
  3922. is_active=True,
  3923. )
  3924. db_session.add(alice)
  3925. await db_session.flush()
  3926. # ── 2. Provider: Fall C config (preferred_username, no email_verified) ─
  3927. provider = OIDCProvider(
  3928. name="AzureEntraFallC",
  3929. issuer_url=issuer,
  3930. client_id="azure-client",
  3931. _client_secret_enc="azure-secret",
  3932. scopes="openid profile",
  3933. is_enabled=True,
  3934. auto_link_existing_accounts=True,
  3935. auto_create_users=False,
  3936. email_claim="preferred_username",
  3937. require_email_verified=False,
  3938. )
  3939. db_session.add(provider)
  3940. await db_session.flush()
  3941. # ── 3. OIDC state token ───────────────────────────────────────────────
  3942. state = secrets.token_urlsafe(32)
  3943. db_session.add(
  3944. AuthEphemeralToken(
  3945. token=state,
  3946. token_type="oidc_state",
  3947. provider_id=provider.id,
  3948. nonce=nonce,
  3949. code_verifier=code_verifier,
  3950. expires_at=datetime.now(timezone.utc) + timedelta(minutes=10),
  3951. )
  3952. )
  3953. await db_session.commit()
  3954. # ── 4. Mock HTTP + JWT ────────────────────────────────────────────────
  3955. fake_discovery = {
  3956. "issuer": issuer,
  3957. "token_endpoint": f"{issuer}/token",
  3958. "jwks_uri": f"{issuer}/.well-known/jwks.json",
  3959. }
  3960. fake_token = {"access_token": "acc_tok", "id_token": "fake.id.token"}
  3961. # Fall C: preferred_username carries the email; no email_verified key at all
  3962. fake_claims = {
  3963. "sub": "azure-sub-alice",
  3964. "preferred_username": "alice.fallc@example.com",
  3965. "iss": issuer,
  3966. "aud": "azure-client",
  3967. "nonce": nonce,
  3968. "exp": 9_999_999_999,
  3969. }
  3970. disc_resp = AsyncMock()
  3971. disc_resp.raise_for_status = MagicMock()
  3972. disc_resp.json = MagicMock(return_value=fake_discovery)
  3973. token_resp = AsyncMock()
  3974. token_resp.json = MagicMock(return_value=fake_token)
  3975. jwks_resp = AsyncMock()
  3976. jwks_resp.raise_for_status = MagicMock()
  3977. jwks_resp.json = MagicMock(return_value={})
  3978. mock_http = AsyncMock()
  3979. mock_http.get = AsyncMock(side_effect=[disc_resp, jwks_resp])
  3980. mock_http.post = AsyncMock(return_value=token_resp)
  3981. mock_signing_key = MagicMock()
  3982. mock_signing_key.key = "fake_key"
  3983. with (
  3984. patch("backend.app.api.routes.mfa.httpx.AsyncClient") as mock_httpx_cls,
  3985. patch("backend.app.api.routes.mfa.jwt.decode", return_value=fake_claims),
  3986. patch("backend.app.api.routes.mfa.PyJWKClient") as mock_jwks_cls,
  3987. ):
  3988. mock_httpx_cls.return_value.__aenter__ = AsyncMock(return_value=mock_http)
  3989. mock_httpx_cls.return_value.__aexit__ = AsyncMock(return_value=False)
  3990. mock_jwks_cls.return_value.get_signing_key_from_jwt.return_value = mock_signing_key
  3991. callback_resp = await async_client.get(
  3992. f"/api/v1/auth/oidc/callback?code=fake_code&state={state}",
  3993. follow_redirects=False,
  3994. )
  3995. assert callback_resp.status_code == 302, callback_resp.text
  3996. location = callback_resp.headers.get("location", "")
  3997. assert "oidc_token=" in location, f"Expected oidc_token in redirect, got: {location}"
  3998. # ── 5. Exchange token → full JWT ──────────────────────────────────────
  3999. oidc_exchange_token = location.split("oidc_token=")[1].split("&")[0].split("#")[-1]
  4000. exchange_resp = await async_client.post(
  4001. "/api/v1/auth/oidc/exchange",
  4002. json={"oidc_token": oidc_exchange_token},
  4003. )
  4004. assert exchange_resp.status_code == 200
  4005. assert exchange_resp.json()["user"]["username"] == "fallc_alice"
  4006. # ── 6. Verify UserOIDCLink was created in DB ──────────────────────────
  4007. async with db_session as s:
  4008. result = await s.execute(
  4009. sa_select(UserOIDCLink).where(
  4010. UserOIDCLink.user_id == alice.id,
  4011. UserOIDCLink.provider_id == provider.id,
  4012. )
  4013. )
  4014. link = result.scalar_one_or_none()
  4015. assert link is not None, "UserOIDCLink must have been created by auto-link"
  4016. assert link.provider_user_id == "azure-sub-alice"
  4017. class TestOIDCAutoCreateUsername:
  4018. """Username derivation priority for auto-created OIDC users (#1173).
  4019. Priority order: email local-part > preferred_username > name > provider_sub.
  4020. Covers: plain claim, spaces-sanitized, name fallback, sub fallback,
  4021. non-string isinstance guard, sanitizes-to-empty fallback, collision counter.
  4022. """
  4023. # ── shared helpers ───────────────────────────────────────────────────────
  4024. @staticmethod
  4025. async def _create_provider(async_client: AsyncClient, admin_token: str, issuer: str, client_id: str) -> int:
  4026. resp = await async_client.post(
  4027. "/api/v1/auth/oidc/providers",
  4028. json={
  4029. "name": f"AutoUser-{secrets.token_hex(4)}",
  4030. "issuer_url": issuer,
  4031. "client_id": client_id,
  4032. "client_secret": "secret",
  4033. "scopes": "openid profile",
  4034. "is_enabled": True,
  4035. "auto_create_users": True,
  4036. "email_claim": "email",
  4037. "require_email_verified": True,
  4038. },
  4039. headers={"Authorization": f"Bearer {admin_token}"},
  4040. )
  4041. assert resp.status_code == 201, resp.text
  4042. return resp.json()["id"]
  4043. @staticmethod
  4044. async def _exchange_username(async_client: AsyncClient, location: str) -> str:
  4045. assert "oidc_token=" in location, f"No oidc_token in redirect: {location}"
  4046. token = location.split("oidc_token=")[1].split("&")[0].split("#")[-1]
  4047. resp = await async_client.post("/api/v1/auth/oidc/exchange", json={"oidc_token": token})
  4048. assert resp.status_code == 200, resp.text
  4049. return resp.json()["user"]["username"]
  4050. # ── tests ────────────────────────────────────────────────────────────────
  4051. @pytest.mark.asyncio
  4052. @pytest.mark.integration
  4053. async def test_preferred_username_used_when_no_email(self, async_client: AsyncClient, db_session: AsyncSession):
  4054. """preferred_username='johndoe' → username 'johndoe' (no email claim present)."""
  4055. private_pem, jwks_data = _make_test_rsa_key()
  4056. issuer = "https://au-pref.example"
  4057. client_id = "au-pref-client"
  4058. admin_token = await _setup_and_login(async_client, "au_pref_adm", "AuPrefAdm1!")
  4059. provider_id = await self._create_provider(async_client, admin_token, issuer, client_id)
  4060. location = await _run_oidc_callback(
  4061. async_client,
  4062. db_session,
  4063. provider_id=provider_id,
  4064. claims={"sub": "pref-sub-1", "preferred_username": "johndoe"},
  4065. private_pem=private_pem,
  4066. jwks_data=jwks_data,
  4067. issuer=issuer,
  4068. client_id=client_id,
  4069. )
  4070. username = await self._exchange_username(async_client, location)
  4071. assert username == "johndoe"
  4072. @pytest.mark.asyncio
  4073. @pytest.mark.integration
  4074. async def test_preferred_username_spaces_sanitized(self, async_client: AsyncClient, db_session: AsyncSession):
  4075. """preferred_username='John Doe' → sanitized to 'JohnDoe'."""
  4076. private_pem, jwks_data = _make_test_rsa_key()
  4077. issuer = "https://au-spaces.example"
  4078. client_id = "au-spaces-client"
  4079. admin_token = await _setup_and_login(async_client, "au_spaces_adm", "AuSpacesAdm1!")
  4080. provider_id = await self._create_provider(async_client, admin_token, issuer, client_id)
  4081. location = await _run_oidc_callback(
  4082. async_client,
  4083. db_session,
  4084. provider_id=provider_id,
  4085. claims={"sub": "spaces-sub-1", "preferred_username": "John Doe"},
  4086. private_pem=private_pem,
  4087. jwks_data=jwks_data,
  4088. issuer=issuer,
  4089. client_id=client_id,
  4090. )
  4091. username = await self._exchange_username(async_client, location)
  4092. assert username == "JohnDoe"
  4093. @pytest.mark.asyncio
  4094. @pytest.mark.integration
  4095. async def test_name_claim_used_when_no_preferred_username(
  4096. self, async_client: AsyncClient, db_session: AsyncSession
  4097. ):
  4098. """name='Jane Smith', no preferred_username → username 'JaneSmith'."""
  4099. private_pem, jwks_data = _make_test_rsa_key()
  4100. issuer = "https://au-name.example"
  4101. client_id = "au-name-client"
  4102. admin_token = await _setup_and_login(async_client, "au_name_adm", "AuNameAdm1!")
  4103. provider_id = await self._create_provider(async_client, admin_token, issuer, client_id)
  4104. location = await _run_oidc_callback(
  4105. async_client,
  4106. db_session,
  4107. provider_id=provider_id,
  4108. claims={"sub": "name-sub-1", "name": "Jane Smith"},
  4109. private_pem=private_pem,
  4110. jwks_data=jwks_data,
  4111. issuer=issuer,
  4112. client_id=client_id,
  4113. )
  4114. username = await self._exchange_username(async_client, location)
  4115. assert username == "JaneSmith"
  4116. @pytest.mark.asyncio
  4117. @pytest.mark.integration
  4118. async def test_provider_sub_fallback_when_no_claims(self, async_client: AsyncClient, db_session: AsyncSession):
  4119. """No preferred_username, no name, no email → username derived from provider_sub."""
  4120. private_pem, jwks_data = _make_test_rsa_key()
  4121. issuer = "https://au-sub.example"
  4122. client_id = "au-sub-client"
  4123. admin_token = await _setup_and_login(async_client, "au_sub_adm", "AuSubAdm1!")
  4124. provider_id = await self._create_provider(async_client, admin_token, issuer, client_id)
  4125. location = await _run_oidc_callback(
  4126. async_client,
  4127. db_session,
  4128. provider_id=provider_id,
  4129. claims={"sub": "abc123xyz"},
  4130. private_pem=private_pem,
  4131. jwks_data=jwks_data,
  4132. issuer=issuer,
  4133. client_id=client_id,
  4134. )
  4135. username = await self._exchange_username(async_client, location)
  4136. assert username == "abc123xyz"
  4137. @pytest.mark.asyncio
  4138. @pytest.mark.integration
  4139. async def test_non_string_preferred_username_falls_through_to_name(
  4140. self, async_client: AsyncClient, db_session: AsyncSession
  4141. ):
  4142. """preferred_username is a list (non-string) → isinstance guard skips it, uses name."""
  4143. private_pem, jwks_data = _make_test_rsa_key()
  4144. issuer = "https://au-nonstr.example"
  4145. client_id = "au-nonstr-client"
  4146. admin_token = await _setup_and_login(async_client, "au_nonstr_adm", "AuNonstrAdm1!")
  4147. provider_id = await self._create_provider(async_client, admin_token, issuer, client_id)
  4148. location = await _run_oidc_callback(
  4149. async_client,
  4150. db_session,
  4151. provider_id=provider_id,
  4152. claims={"sub": "nonstr-sub-2", "preferred_username": ["listval"], "name": "BobJones"},
  4153. private_pem=private_pem,
  4154. jwks_data=jwks_data,
  4155. issuer=issuer,
  4156. client_id=client_id,
  4157. )
  4158. username = await self._exchange_username(async_client, location)
  4159. assert username == "BobJones"
  4160. @pytest.mark.asyncio
  4161. @pytest.mark.integration
  4162. async def test_preferred_username_sanitizes_to_empty_falls_through_to_name(
  4163. self, async_client: AsyncClient, db_session: AsyncSession
  4164. ):
  4165. """preferred_username='!!!' sanitizes to '' → falls through to name claim."""
  4166. private_pem, jwks_data = _make_test_rsa_key()
  4167. issuer = "https://au-empty.example"
  4168. client_id = "au-empty-client"
  4169. admin_token = await _setup_and_login(async_client, "au_empty_adm", "AuEmptyAdm1!")
  4170. provider_id = await self._create_provider(async_client, admin_token, issuer, client_id)
  4171. location = await _run_oidc_callback(
  4172. async_client,
  4173. db_session,
  4174. provider_id=provider_id,
  4175. claims={"sub": "empty-sub-1", "preferred_username": "!!!", "name": "bob"},
  4176. private_pem=private_pem,
  4177. jwks_data=jwks_data,
  4178. issuer=issuer,
  4179. client_id=client_id,
  4180. )
  4181. username = await self._exchange_username(async_client, location)
  4182. assert username == "bob"
  4183. @pytest.mark.asyncio
  4184. @pytest.mark.integration
  4185. async def test_username_collision_appends_counter(self, async_client: AsyncClient, db_session: AsyncSession):
  4186. """When preferred_username 'collider' is already taken, counter suffix is appended."""
  4187. from backend.app.core.auth import get_password_hash
  4188. # Pre-create a user occupying the candidate username
  4189. existing = User(
  4190. username="collider",
  4191. email="collider@example.com",
  4192. password_hash=get_password_hash("irrelevant"),
  4193. role="user",
  4194. is_active=True,
  4195. )
  4196. db_session.add(existing)
  4197. await db_session.commit()
  4198. private_pem, jwks_data = _make_test_rsa_key()
  4199. issuer = "https://au-collision.example"
  4200. client_id = "au-collision-client"
  4201. admin_token = await _setup_and_login(async_client, "au_col_adm", "AuColAdm1!")
  4202. provider_id = await self._create_provider(async_client, admin_token, issuer, client_id)
  4203. location = await _run_oidc_callback(
  4204. async_client,
  4205. db_session,
  4206. provider_id=provider_id,
  4207. claims={"sub": "col-sub-1", "preferred_username": "collider"},
  4208. private_pem=private_pem,
  4209. jwks_data=jwks_data,
  4210. issuer=issuer,
  4211. client_id=client_id,
  4212. )
  4213. username = await self._exchange_username(async_client, location)
  4214. assert username == "collider1"
  4215. # ===========================================================================
  4216. # OIDC auto-create: configurable default group (#1173 Thread 2)
  4217. # ===========================================================================
  4218. class TestOIDCAutoCreateDefaultGroup:
  4219. """Auto-created OIDC users receive the provider's configured default group.
  4220. Resolution order:
  4221. 1. provider.default_group_id (configured)
  4222. 2. "Viewers" system group (fallback when default_group_id is None)
  4223. 3. no group (last resort when both are unavailable)
  4224. All tests are DB-agnostic: they verify group membership via the OIDC
  4225. exchange response, which includes the user's group list.
  4226. """
  4227. @staticmethod
  4228. async def _create_provider(
  4229. async_client: AsyncClient,
  4230. admin_token: str,
  4231. *,
  4232. issuer: str,
  4233. client_id: str,
  4234. default_group_id: int | None = None,
  4235. ) -> int:
  4236. payload: dict = {
  4237. "name": f"DgAutoProvider-{secrets.token_hex(4)}",
  4238. "issuer_url": issuer,
  4239. "client_id": client_id,
  4240. "client_secret": "secret",
  4241. "scopes": "openid profile",
  4242. "is_enabled": True,
  4243. "auto_create_users": True,
  4244. "email_claim": "email",
  4245. "require_email_verified": True,
  4246. }
  4247. if default_group_id is not None:
  4248. payload["default_group_id"] = default_group_id
  4249. resp = await async_client.post(
  4250. "/api/v1/auth/oidc/providers",
  4251. json=payload,
  4252. headers={"Authorization": f"Bearer {admin_token}"},
  4253. )
  4254. assert resp.status_code == 201, resp.text
  4255. return resp.json()["id"]
  4256. @staticmethod
  4257. async def _run_autocreate_and_get_groups(
  4258. async_client: AsyncClient,
  4259. db_session: AsyncSession,
  4260. *,
  4261. provider_id: int,
  4262. sub: str,
  4263. issuer: str,
  4264. client_id: str,
  4265. private_pem: bytes,
  4266. jwks_data: dict,
  4267. ) -> list[str]:
  4268. """Complete OIDC callback + exchange and return the new user's group names."""
  4269. location = await _run_oidc_callback(
  4270. async_client,
  4271. db_session,
  4272. provider_id=provider_id,
  4273. claims={"sub": sub},
  4274. private_pem=private_pem,
  4275. jwks_data=jwks_data,
  4276. issuer=issuer,
  4277. client_id=client_id,
  4278. )
  4279. assert "oidc_token=" in location, f"No oidc_token in redirect: {location}"
  4280. token = location.split("oidc_token=")[1].split("&")[0].split("#")[-1]
  4281. resp = await async_client.post("/api/v1/auth/oidc/exchange", json={"oidc_token": token})
  4282. assert resp.status_code == 200, resp.text
  4283. return [g["name"] for g in resp.json()["user"]["groups"]]
  4284. # ── tests ────────────────────────────────────────────────────────────────
  4285. @pytest.mark.asyncio
  4286. @pytest.mark.integration
  4287. async def test_configured_group_assigned_to_auto_created_user(
  4288. self, async_client: AsyncClient, db_session: AsyncSession
  4289. ):
  4290. """Auto-created user is placed in the provider's configured default_group_id."""
  4291. from sqlalchemy import select
  4292. from backend.app.models.group import Group
  4293. private_pem, jwks_data = _make_test_rsa_key()
  4294. issuer = "https://dg-configured.example"
  4295. client_id = "dg-configured-client"
  4296. admin_token = await _setup_and_login(async_client, "dg_cfg_adm", "DgCfgAdm1!")
  4297. grp_result = await db_session.execute(select(Group).where(Group.name == "Operators"))
  4298. operators = grp_result.scalar_one()
  4299. provider_id = await self._create_provider(
  4300. async_client,
  4301. admin_token,
  4302. issuer=issuer,
  4303. client_id=client_id,
  4304. default_group_id=operators.id,
  4305. )
  4306. group_names = await self._run_autocreate_and_get_groups(
  4307. async_client,
  4308. db_session,
  4309. provider_id=provider_id,
  4310. sub="dg-cfg-sub-1",
  4311. issuer=issuer,
  4312. client_id=client_id,
  4313. private_pem=private_pem,
  4314. jwks_data=jwks_data,
  4315. )
  4316. assert "Operators" in group_names, f"Expected Operators, got {group_names}"
  4317. assert "Viewers" not in group_names
  4318. @pytest.mark.asyncio
  4319. @pytest.mark.integration
  4320. async def test_null_default_group_id_falls_back_to_viewers(
  4321. self, async_client: AsyncClient, db_session: AsyncSession
  4322. ):
  4323. """When default_group_id is None, auto-created user falls back to Viewers."""
  4324. private_pem, jwks_data = _make_test_rsa_key()
  4325. issuer = "https://dg-null.example"
  4326. client_id = "dg-null-client"
  4327. admin_token = await _setup_and_login(async_client, "dg_null_adm", "DgNullAdm1!")
  4328. provider_id = await self._create_provider(
  4329. async_client,
  4330. admin_token,
  4331. issuer=issuer,
  4332. client_id=client_id,
  4333. )
  4334. group_names = await self._run_autocreate_and_get_groups(
  4335. async_client,
  4336. db_session,
  4337. provider_id=provider_id,
  4338. sub="dg-null-sub-1",
  4339. issuer=issuer,
  4340. client_id=client_id,
  4341. private_pem=private_pem,
  4342. jwks_data=jwks_data,
  4343. )
  4344. assert "Viewers" in group_names, f"Expected Viewers, got {group_names}"
  4345. @pytest.mark.asyncio
  4346. @pytest.mark.integration
  4347. async def test_dangling_default_group_id_falls_back_to_viewers(
  4348. self, async_client: AsyncClient, db_session: AsyncSession
  4349. ):
  4350. """When configured group is deleted, auto-created user falls back to Viewers.
  4351. SQLite does not enforce FK ON DELETE SET NULL (no PRAGMA foreign_keys=ON),
  4352. so provider.default_group_id may point to a deleted group. The runtime
  4353. resolution chain must handle this and fall back to Viewers.
  4354. """
  4355. from sqlalchemy import delete as sa_delete, select
  4356. from backend.app.models.group import Group
  4357. private_pem, jwks_data = _make_test_rsa_key()
  4358. issuer = "https://dg-dangling.example"
  4359. client_id = "dg-dangling-client"
  4360. admin_token = await _setup_and_login(async_client, "dg_dangle_adm", "DgDangleAdm1!")
  4361. # Create a temporary group and use it as default_group_id
  4362. temp_group = Group(name="TempGroup-DgDangle", permissions=[])
  4363. db_session.add(temp_group)
  4364. await db_session.commit()
  4365. await db_session.refresh(temp_group)
  4366. temp_group_id = temp_group.id
  4367. provider_id = await self._create_provider(
  4368. async_client,
  4369. admin_token,
  4370. issuer=issuer,
  4371. client_id=client_id,
  4372. default_group_id=temp_group_id,
  4373. )
  4374. # Delete the group — simulates dangling FK (especially on SQLite)
  4375. await db_session.execute(sa_delete(Group).where(Group.id == temp_group_id))
  4376. await db_session.commit()
  4377. group_names = await self._run_autocreate_and_get_groups(
  4378. async_client,
  4379. db_session,
  4380. provider_id=provider_id,
  4381. sub="dg-dangle-sub-1",
  4382. issuer=issuer,
  4383. client_id=client_id,
  4384. private_pem=private_pem,
  4385. jwks_data=jwks_data,
  4386. )
  4387. assert "Viewers" in group_names, f"Expected Viewers fallback, got {group_names}"
  4388. @pytest.mark.asyncio
  4389. @pytest.mark.integration
  4390. async def test_administrators_group_can_be_set_as_default(
  4391. self, async_client: AsyncClient, db_session: AsyncSession
  4392. ):
  4393. """Operators can configure Administrators as the default group (e.g. single-tenant IdP)."""
  4394. from sqlalchemy import select
  4395. from backend.app.models.group import Group
  4396. private_pem, jwks_data = _make_test_rsa_key()
  4397. issuer = "https://dg-admin.example"
  4398. client_id = "dg-admin-client"
  4399. admin_token = await _setup_and_login(async_client, "dg_admgrp_adm", "DgAdmgrpAdm1!")
  4400. grp_result = await db_session.execute(select(Group).where(Group.name == "Administrators"))
  4401. administrators = grp_result.scalar_one()
  4402. provider_id = await self._create_provider(
  4403. async_client,
  4404. admin_token,
  4405. issuer=issuer,
  4406. client_id=client_id,
  4407. default_group_id=administrators.id,
  4408. )
  4409. group_names = await self._run_autocreate_and_get_groups(
  4410. async_client,
  4411. db_session,
  4412. provider_id=provider_id,
  4413. sub="dg-admin-sub-1",
  4414. issuer=issuer,
  4415. client_id=client_id,
  4416. private_pem=private_pem,
  4417. jwks_data=jwks_data,
  4418. )
  4419. assert "Administrators" in group_names, f"Expected Administrators, got {group_names}"
  4420. class TestListOidcLinksDefensiveProviderNull:
  4421. """list_oidc_links must not crash if a link's provider is orphaned on SQLite.
  4422. PR for #1285 added a defensive null-check at mfa.py:1871 so the endpoint
  4423. returns ``provider_name="<deleted>"`` for orphan links instead of raising
  4424. AttributeError when accessing ``link.provider.name``. This scenario is
  4425. only reachable on SQLite (PRAGMA foreign_keys=OFF) when an OIDCProvider
  4426. row is removed without the ORM cascade running.
  4427. """
  4428. @pytest.mark.sqlite_only # a dangling reference needs foreign keys off
  4429. @pytest.mark.asyncio
  4430. @pytest.mark.integration
  4431. async def test_list_oidc_links_returns_deleted_marker_for_orphan_provider(
  4432. self, async_client: AsyncClient, db_session: AsyncSession
  4433. ):
  4434. from sqlalchemy import select
  4435. from backend.app.models.oidc_provider import UserOIDCLink
  4436. admin_token = await _setup_and_login(async_client, "linkorphan_adm", "LinkOrphanAdm1!")
  4437. admin_row = await db_session.execute(select(User).where(User.username == "linkorphan_adm"))
  4438. admin_user = admin_row.scalar_one()
  4439. # Orphan link: provider_id=99999 deliberately points at no row.
  4440. db_session.add(
  4441. UserOIDCLink(
  4442. user_id=admin_user.id,
  4443. provider_id=99999,
  4444. provider_user_id="orphan-sub",
  4445. provider_email="orphan@example.com",
  4446. )
  4447. )
  4448. await db_session.commit()
  4449. resp = await async_client.get(
  4450. "/api/v1/auth/oidc/links",
  4451. headers=_auth_header(admin_token),
  4452. )
  4453. assert resp.status_code == 200, resp.text
  4454. links = resp.json()
  4455. assert len(links) == 1
  4456. # The fix: orphan provider_id no longer crashes — returns "<deleted>" instead.
  4457. assert links[0]["provider_name"] == "<deleted>", (
  4458. f"Expected '<deleted>' fallback for orphan provider, got {links[0]['provider_name']!r}"
  4459. )
  4460. assert links[0]["provider_id"] == 99999