test_mfa_api.py 200 KB

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