auth_oauth_pending_flow_test.go 127 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595
  1. package handler
  2. import (
  3. "bytes"
  4. "context"
  5. "database/sql"
  6. "encoding/json"
  7. "errors"
  8. "net/http"
  9. "net/http/httptest"
  10. "strings"
  11. "testing"
  12. "time"
  13. dbent "github.com/Wei-Shaw/sub2api/ent"
  14. "github.com/Wei-Shaw/sub2api/ent/authidentity"
  15. "github.com/Wei-Shaw/sub2api/ent/enttest"
  16. "github.com/Wei-Shaw/sub2api/ent/identityadoptiondecision"
  17. "github.com/Wei-Shaw/sub2api/ent/pendingauthsession"
  18. "github.com/Wei-Shaw/sub2api/ent/redeemcode"
  19. dbuser "github.com/Wei-Shaw/sub2api/ent/user"
  20. "github.com/Wei-Shaw/sub2api/internal/config"
  21. "github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
  22. "github.com/Wei-Shaw/sub2api/internal/service"
  23. "github.com/gin-gonic/gin"
  24. "github.com/pquerna/otp/totp"
  25. "github.com/stretchr/testify/require"
  26. "entgo.io/ent/dialect"
  27. entsql "entgo.io/ent/dialect/sql"
  28. _ "modernc.org/sqlite"
  29. )
  30. func TestApplySuggestedProfileToCompletionResponse(t *testing.T) {
  31. payload := map[string]any{
  32. "access_token": "token",
  33. }
  34. upstream := map[string]any{
  35. "suggested_display_name": "Alice",
  36. "suggested_avatar_url": "https://cdn.example/avatar.png",
  37. }
  38. applySuggestedProfileToCompletionResponse(payload, upstream)
  39. require.Equal(t, "Alice", payload["suggested_display_name"])
  40. require.Equal(t, "https://cdn.example/avatar.png", payload["suggested_avatar_url"])
  41. require.Equal(t, true, payload["adoption_required"])
  42. }
  43. func TestApplySuggestedProfileToCompletionResponseKeepsExistingPayloadValues(t *testing.T) {
  44. payload := map[string]any{
  45. "suggested_display_name": "Existing",
  46. "adoption_required": false,
  47. }
  48. upstream := map[string]any{
  49. "suggested_display_name": "Alice",
  50. "suggested_avatar_url": "https://cdn.example/avatar.png",
  51. }
  52. applySuggestedProfileToCompletionResponse(payload, upstream)
  53. require.Equal(t, "Existing", payload["suggested_display_name"])
  54. require.Equal(t, "https://cdn.example/avatar.png", payload["suggested_avatar_url"])
  55. require.Equal(t, true, payload["adoption_required"])
  56. }
  57. func TestSetOAuthPendingSessionCookieUsesProviderCompletionPathPrefix(t *testing.T) {
  58. recorder := httptest.NewRecorder()
  59. ginCtx, _ := gin.CreateTestContext(recorder)
  60. ginCtx.Request = httptest.NewRequest(http.MethodGet, "/api/v1/auth/oauth/oidc/callback", nil)
  61. setOAuthPendingSessionCookie(ginCtx, "pending-session-token", false)
  62. cookie := findCookie(recorder.Result().Cookies(), oauthPendingSessionCookieName)
  63. require.NotNil(t, cookie)
  64. require.Equal(t, "/api/v1/auth/oauth", cookie.Path)
  65. }
  66. func TestExchangePendingOAuthCompletionPreviewThenFinalizeAppliesAdoptionDecision(t *testing.T) {
  67. handler, client := newOAuthPendingFlowTestHandler(t, false)
  68. ctx := context.Background()
  69. userEntity, err := client.User.Create().
  70. SetEmail("linuxdo-123@linuxdo-connect.invalid").
  71. SetUsername("legacy-name").
  72. SetPasswordHash("hash").
  73. SetRole(service.RoleUser).
  74. SetStatus(service.StatusActive).
  75. Save(ctx)
  76. require.NoError(t, err)
  77. session, err := client.PendingAuthSession.Create().
  78. SetSessionToken("pending-session-token").
  79. SetIntent("login").
  80. SetProviderType("linuxdo").
  81. SetProviderKey("linuxdo").
  82. SetProviderSubject("123").
  83. SetTargetUserID(userEntity.ID).
  84. SetResolvedEmail(userEntity.Email).
  85. SetBrowserSessionKey("browser-session-key").
  86. SetUpstreamIdentityClaims(map[string]any{
  87. "username": "linuxdo_user",
  88. "suggested_display_name": "Alice Example",
  89. "suggested_avatar_url": "https://cdn.example/alice.png",
  90. }).
  91. SetLocalFlowState(map[string]any{
  92. oauthCompletionResponseKey: map[string]any{
  93. "access_token": "access-token",
  94. "redirect": "/dashboard",
  95. },
  96. }).
  97. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  98. Save(ctx)
  99. require.NoError(t, err)
  100. previewRecorder := httptest.NewRecorder()
  101. previewCtx, _ := gin.CreateTestContext(previewRecorder)
  102. previewReq := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", nil)
  103. previewReq.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  104. previewReq.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("browser-session-key")})
  105. previewCtx.Request = previewReq
  106. handler.ExchangePendingOAuthCompletion(previewCtx)
  107. require.Equal(t, http.StatusOK, previewRecorder.Code)
  108. previewData := decodeJSONResponseData(t, previewRecorder)
  109. require.Equal(t, "Alice Example", previewData["suggested_display_name"])
  110. require.Equal(t, "https://cdn.example/alice.png", previewData["suggested_avatar_url"])
  111. require.Equal(t, true, previewData["adoption_required"])
  112. storedUser, err := client.User.Get(ctx, userEntity.ID)
  113. require.NoError(t, err)
  114. require.Equal(t, "legacy-name", storedUser.Username)
  115. previewSession, err := client.PendingAuthSession.Query().
  116. Where(pendingauthsession.IDEQ(session.ID)).
  117. Only(ctx)
  118. require.NoError(t, err)
  119. require.Nil(t, previewSession.ConsumedAt)
  120. body := bytes.NewBufferString(`{"adopt_display_name":true,"adopt_avatar":true}`)
  121. finalizeRecorder := httptest.NewRecorder()
  122. finalizeCtx, _ := gin.CreateTestContext(finalizeRecorder)
  123. finalizeReq := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", body)
  124. finalizeReq.Header.Set("Content-Type", "application/json")
  125. finalizeReq.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  126. finalizeReq.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("browser-session-key")})
  127. finalizeCtx.Request = finalizeReq
  128. handler.ExchangePendingOAuthCompletion(finalizeCtx)
  129. require.Equal(t, http.StatusOK, finalizeRecorder.Code)
  130. storedUser, err = client.User.Get(ctx, userEntity.ID)
  131. require.NoError(t, err)
  132. require.Equal(t, "Alice Example", storedUser.Username)
  133. identity, err := client.AuthIdentity.Query().
  134. Where(
  135. authidentity.ProviderTypeEQ("linuxdo"),
  136. authidentity.ProviderKeyEQ("linuxdo"),
  137. authidentity.ProviderSubjectEQ("123"),
  138. ).
  139. Only(ctx)
  140. require.NoError(t, err)
  141. require.Equal(t, userEntity.ID, identity.UserID)
  142. require.Equal(t, "Alice Example", identity.Metadata["display_name"])
  143. require.Equal(t, "https://cdn.example/alice.png", identity.Metadata["avatar_url"])
  144. avatar := loadUserAvatarRecord(t, client, userEntity.ID)
  145. require.NotNil(t, avatar)
  146. require.Equal(t, "remote_url", avatar.StorageProvider)
  147. require.Equal(t, "https://cdn.example/alice.png", avatar.URL)
  148. decision, err := client.IdentityAdoptionDecision.Query().
  149. Where(identityadoptiondecision.PendingAuthSessionIDEQ(session.ID)).
  150. Only(ctx)
  151. require.NoError(t, err)
  152. require.NotNil(t, decision.IdentityID)
  153. require.Equal(t, identity.ID, *decision.IdentityID)
  154. require.True(t, decision.AdoptDisplayName)
  155. require.True(t, decision.AdoptAvatar)
  156. consumed, err := client.PendingAuthSession.Query().
  157. Where(pendingauthsession.IDEQ(session.ID)).
  158. Only(ctx)
  159. require.NoError(t, err)
  160. require.NotNil(t, consumed.ConsumedAt)
  161. }
  162. func TestExchangePendingOAuthCompletionSkipsInvalidAvatarAdoptionWithoutBlockingCompletion(t *testing.T) {
  163. handler, client := newOAuthPendingFlowTestHandler(t, false)
  164. ctx := context.Background()
  165. userEntity, err := client.User.Create().
  166. SetEmail("invalid-avatar@example.com").
  167. SetUsername("legacy-name").
  168. SetPasswordHash("hash").
  169. SetRole(service.RoleUser).
  170. SetStatus(service.StatusActive).
  171. Save(ctx)
  172. require.NoError(t, err)
  173. session, err := client.PendingAuthSession.Create().
  174. SetSessionToken("pending-invalid-avatar-token").
  175. SetIntent("login").
  176. SetProviderType("linuxdo").
  177. SetProviderKey("linuxdo").
  178. SetProviderSubject("invalid-avatar-123").
  179. SetTargetUserID(userEntity.ID).
  180. SetResolvedEmail(userEntity.Email).
  181. SetBrowserSessionKey("browser-invalid-avatar-key").
  182. SetUpstreamIdentityClaims(map[string]any{
  183. "username": "linuxdo_user",
  184. "suggested_display_name": "Alice Example",
  185. "suggested_avatar_url": "/avatars/alice.png",
  186. }).
  187. SetLocalFlowState(map[string]any{
  188. oauthCompletionResponseKey: map[string]any{
  189. "access_token": "access-token",
  190. "redirect": "/dashboard",
  191. },
  192. }).
  193. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  194. Save(ctx)
  195. require.NoError(t, err)
  196. body := bytes.NewBufferString(`{"adopt_display_name":true,"adopt_avatar":true}`)
  197. recorder := httptest.NewRecorder()
  198. ginCtx, _ := gin.CreateTestContext(recorder)
  199. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", body)
  200. req.Header.Set("Content-Type", "application/json")
  201. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  202. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("browser-invalid-avatar-key")})
  203. ginCtx.Request = req
  204. handler.ExchangePendingOAuthCompletion(ginCtx)
  205. require.Equal(t, http.StatusOK, recorder.Code)
  206. identity, err := client.AuthIdentity.Query().
  207. Where(
  208. authidentity.ProviderTypeEQ("linuxdo"),
  209. authidentity.ProviderKeyEQ("linuxdo"),
  210. authidentity.ProviderSubjectEQ("invalid-avatar-123"),
  211. ).
  212. Only(ctx)
  213. require.NoError(t, err)
  214. require.Equal(t, "Alice Example", identity.Metadata["display_name"])
  215. _, hasAdoptedAvatar := identity.Metadata["avatar_url"]
  216. require.False(t, hasAdoptedAvatar)
  217. avatar := loadUserAvatarRecord(t, client, userEntity.ID)
  218. require.Nil(t, avatar)
  219. consumed, err := client.PendingAuthSession.Query().
  220. Where(pendingauthsession.IDEQ(session.ID)).
  221. Only(ctx)
  222. require.NoError(t, err)
  223. require.NotNil(t, consumed.ConsumedAt)
  224. }
  225. func TestExchangePendingOAuthCompletionBindCurrentUserPreviewThenFinalizeBindsIdentityWithoutAdoption(t *testing.T) {
  226. handler, client := newOAuthPendingFlowTestHandler(t, false)
  227. ctx := context.Background()
  228. userEntity, err := client.User.Create().
  229. SetEmail("bind-target@example.com").
  230. SetUsername("legacy-name").
  231. SetPasswordHash("hash").
  232. SetRole(service.RoleUser).
  233. SetStatus(service.StatusActive).
  234. Save(ctx)
  235. require.NoError(t, err)
  236. session, err := client.PendingAuthSession.Create().
  237. SetSessionToken("bind-pending-session-token").
  238. SetIntent("bind_current_user").
  239. SetProviderType("linuxdo").
  240. SetProviderKey("linuxdo").
  241. SetProviderSubject("bind-123").
  242. SetTargetUserID(userEntity.ID).
  243. SetResolvedEmail(userEntity.Email).
  244. SetBrowserSessionKey("bind-browser-session-key").
  245. SetUpstreamIdentityClaims(map[string]any{
  246. "username": "linuxdo_user",
  247. "suggested_display_name": "Bound Example",
  248. "suggested_avatar_url": "https://cdn.example/bound.png",
  249. }).
  250. SetLocalFlowState(map[string]any{
  251. oauthCompletionResponseKey: map[string]any{
  252. "access_token": "access-token",
  253. "redirect": "/settings/profile",
  254. },
  255. }).
  256. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  257. Save(ctx)
  258. require.NoError(t, err)
  259. previewRecorder := httptest.NewRecorder()
  260. previewCtx, _ := gin.CreateTestContext(previewRecorder)
  261. previewReq := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", nil)
  262. previewReq.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  263. previewReq.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("bind-browser-session-key")})
  264. previewCtx.Request = previewReq
  265. handler.ExchangePendingOAuthCompletion(previewCtx)
  266. require.Equal(t, http.StatusOK, previewRecorder.Code)
  267. previewData := decodeJSONResponseData(t, previewRecorder)
  268. require.Equal(t, "Bound Example", previewData["suggested_display_name"])
  269. require.Equal(t, "https://cdn.example/bound.png", previewData["suggested_avatar_url"])
  270. require.Equal(t, true, previewData["adoption_required"])
  271. identityCount, err := client.AuthIdentity.Query().
  272. Where(
  273. authidentity.ProviderTypeEQ("linuxdo"),
  274. authidentity.ProviderKeyEQ("linuxdo"),
  275. authidentity.ProviderSubjectEQ("bind-123"),
  276. ).
  277. Count(ctx)
  278. require.NoError(t, err)
  279. require.Zero(t, identityCount)
  280. previewSession, err := client.PendingAuthSession.Query().
  281. Where(pendingauthsession.IDEQ(session.ID)).
  282. Only(ctx)
  283. require.NoError(t, err)
  284. require.Nil(t, previewSession.ConsumedAt)
  285. body := bytes.NewBufferString(`{"adopt_display_name":false,"adopt_avatar":false}`)
  286. finalizeRecorder := httptest.NewRecorder()
  287. finalizeCtx, _ := gin.CreateTestContext(finalizeRecorder)
  288. finalizeReq := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", body)
  289. finalizeReq.Header.Set("Content-Type", "application/json")
  290. finalizeReq.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  291. finalizeReq.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("bind-browser-session-key")})
  292. finalizeCtx.Request = finalizeReq
  293. handler.ExchangePendingOAuthCompletion(finalizeCtx)
  294. require.Equal(t, http.StatusOK, finalizeRecorder.Code)
  295. storedUser, err := client.User.Get(ctx, userEntity.ID)
  296. require.NoError(t, err)
  297. require.Equal(t, "legacy-name", storedUser.Username)
  298. identity, err := client.AuthIdentity.Query().
  299. Where(
  300. authidentity.ProviderTypeEQ("linuxdo"),
  301. authidentity.ProviderKeyEQ("linuxdo"),
  302. authidentity.ProviderSubjectEQ("bind-123"),
  303. ).
  304. Only(ctx)
  305. require.NoError(t, err)
  306. require.Equal(t, userEntity.ID, identity.UserID)
  307. require.Equal(t, "Bound Example", identity.Metadata["suggested_display_name"])
  308. require.Equal(t, "https://cdn.example/bound.png", identity.Metadata["suggested_avatar_url"])
  309. _, hasDisplayName := identity.Metadata["display_name"]
  310. require.False(t, hasDisplayName)
  311. _, hasAvatarURL := identity.Metadata["avatar_url"]
  312. require.False(t, hasAvatarURL)
  313. decision, err := client.IdentityAdoptionDecision.Query().
  314. Where(identityadoptiondecision.PendingAuthSessionIDEQ(session.ID)).
  315. Only(ctx)
  316. require.NoError(t, err)
  317. require.NotNil(t, decision.IdentityID)
  318. require.Equal(t, identity.ID, *decision.IdentityID)
  319. require.False(t, decision.AdoptDisplayName)
  320. require.False(t, decision.AdoptAvatar)
  321. consumed, err := client.PendingAuthSession.Query().
  322. Where(pendingauthsession.IDEQ(session.ID)).
  323. Only(ctx)
  324. require.NoError(t, err)
  325. require.NotNil(t, consumed.ConsumedAt)
  326. }
  327. func TestExchangePendingOAuthCompletionBindCurrentUserOwnershipConflict(t *testing.T) {
  328. handler, client := newOAuthPendingFlowTestHandler(t, false)
  329. ctx := context.Background()
  330. targetUser, err := client.User.Create().
  331. SetEmail("bind-conflict-target@example.com").
  332. SetUsername("target-user").
  333. SetPasswordHash("hash").
  334. SetRole(service.RoleUser).
  335. SetStatus(service.StatusActive).
  336. Save(ctx)
  337. require.NoError(t, err)
  338. ownerUser, err := client.User.Create().
  339. SetEmail("bind-conflict-owner@example.com").
  340. SetUsername("owner-user").
  341. SetPasswordHash("hash").
  342. SetRole(service.RoleUser).
  343. SetStatus(service.StatusActive).
  344. Save(ctx)
  345. require.NoError(t, err)
  346. existingIdentity, err := client.AuthIdentity.Create().
  347. SetUserID(ownerUser.ID).
  348. SetProviderType("linuxdo").
  349. SetProviderKey("linuxdo").
  350. SetProviderSubject("conflict-123").
  351. SetMetadata(map[string]any{"username": "owner-user"}).
  352. Save(ctx)
  353. require.NoError(t, err)
  354. session, err := client.PendingAuthSession.Create().
  355. SetSessionToken("bind-conflict-session-token").
  356. SetIntent("bind_current_user").
  357. SetProviderType("linuxdo").
  358. SetProviderKey("linuxdo").
  359. SetProviderSubject("conflict-123").
  360. SetTargetUserID(targetUser.ID).
  361. SetResolvedEmail(targetUser.Email).
  362. SetBrowserSessionKey("bind-conflict-browser-session-key").
  363. SetUpstreamIdentityClaims(map[string]any{
  364. "suggested_display_name": "Conflict Example",
  365. "suggested_avatar_url": "https://cdn.example/conflict.png",
  366. }).
  367. SetLocalFlowState(map[string]any{
  368. oauthCompletionResponseKey: map[string]any{
  369. "access_token": "access-token",
  370. },
  371. }).
  372. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  373. Save(ctx)
  374. require.NoError(t, err)
  375. body := bytes.NewBufferString(`{"adopt_display_name":false,"adopt_avatar":false}`)
  376. recorder := httptest.NewRecorder()
  377. ginCtx, _ := gin.CreateTestContext(recorder)
  378. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", body)
  379. req.Header.Set("Content-Type", "application/json")
  380. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  381. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("bind-conflict-browser-session-key")})
  382. ginCtx.Request = req
  383. handler.ExchangePendingOAuthCompletion(ginCtx)
  384. require.Equal(t, http.StatusInternalServerError, recorder.Code)
  385. payload := decodeJSONBody(t, recorder)
  386. require.Equal(t, "PENDING_AUTH_ADOPTION_APPLY_FAILED", payload["reason"])
  387. identity, err := client.AuthIdentity.Get(ctx, existingIdentity.ID)
  388. require.NoError(t, err)
  389. require.Equal(t, ownerUser.ID, identity.UserID)
  390. decision, err := client.IdentityAdoptionDecision.Query().
  391. Where(identityadoptiondecision.PendingAuthSessionIDEQ(session.ID)).
  392. Only(ctx)
  393. require.NoError(t, err)
  394. require.Nil(t, decision.IdentityID)
  395. require.False(t, decision.AdoptDisplayName)
  396. require.False(t, decision.AdoptAvatar)
  397. storedSession, err := client.PendingAuthSession.Query().
  398. Where(pendingauthsession.IDEQ(session.ID)).
  399. Only(ctx)
  400. require.NoError(t, err)
  401. require.Nil(t, storedSession.ConsumedAt)
  402. }
  403. func TestExchangePendingOAuthCompletionLoginFalseFalseBindsIdentityWithoutAdoption(t *testing.T) {
  404. handler, client := newOAuthPendingFlowTestHandler(t, false)
  405. ctx := context.Background()
  406. userEntity, err := client.User.Create().
  407. SetEmail("login-false@example.com").
  408. SetUsername("legacy-name").
  409. SetPasswordHash("hash").
  410. SetRole(service.RoleUser).
  411. SetStatus(service.StatusActive).
  412. Save(ctx)
  413. require.NoError(t, err)
  414. session, err := client.PendingAuthSession.Create().
  415. SetSessionToken("login-false-session-token").
  416. SetIntent("login").
  417. SetProviderType("linuxdo").
  418. SetProviderKey("linuxdo").
  419. SetProviderSubject("login-false-123").
  420. SetTargetUserID(userEntity.ID).
  421. SetResolvedEmail(userEntity.Email).
  422. SetBrowserSessionKey("login-false-browser-session-key").
  423. SetUpstreamIdentityClaims(map[string]any{
  424. "suggested_display_name": "Login Example",
  425. "suggested_avatar_url": "https://cdn.example/login.png",
  426. }).
  427. SetLocalFlowState(map[string]any{
  428. oauthCompletionResponseKey: map[string]any{
  429. "access_token": "access-token",
  430. },
  431. }).
  432. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  433. Save(ctx)
  434. require.NoError(t, err)
  435. body := bytes.NewBufferString(`{"adopt_display_name":false,"adopt_avatar":false}`)
  436. recorder := httptest.NewRecorder()
  437. ginCtx, _ := gin.CreateTestContext(recorder)
  438. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", body)
  439. req.Header.Set("Content-Type", "application/json")
  440. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  441. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("login-false-browser-session-key")})
  442. ginCtx.Request = req
  443. handler.ExchangePendingOAuthCompletion(ginCtx)
  444. require.Equal(t, http.StatusOK, recorder.Code)
  445. identity, err := client.AuthIdentity.Query().
  446. Where(
  447. authidentity.ProviderTypeEQ("linuxdo"),
  448. authidentity.ProviderKeyEQ("linuxdo"),
  449. authidentity.ProviderSubjectEQ("login-false-123"),
  450. ).
  451. Only(ctx)
  452. require.NoError(t, err)
  453. require.Equal(t, userEntity.ID, identity.UserID)
  454. decision, err := client.IdentityAdoptionDecision.Query().
  455. Where(identityadoptiondecision.PendingAuthSessionIDEQ(session.ID)).
  456. Only(ctx)
  457. require.NoError(t, err)
  458. require.NotNil(t, decision.IdentityID)
  459. require.Equal(t, identity.ID, *decision.IdentityID)
  460. require.False(t, decision.AdoptDisplayName)
  461. require.False(t, decision.AdoptAvatar)
  462. storedSession, err := client.PendingAuthSession.Query().
  463. Where(pendingauthsession.IDEQ(session.ID)).
  464. Only(ctx)
  465. require.NoError(t, err)
  466. require.NotNil(t, storedSession.ConsumedAt)
  467. }
  468. func TestExchangePendingOAuthCompletionLoginReassignsExistingDecisionIdentityReference(t *testing.T) {
  469. handler, client := newOAuthPendingFlowTestHandler(t, false)
  470. ctx := context.Background()
  471. userEntity, err := client.User.Create().
  472. SetEmail("login-reassign@example.com").
  473. SetUsername("legacy-name").
  474. SetPasswordHash("hash").
  475. SetRole(service.RoleUser).
  476. SetStatus(service.StatusActive).
  477. Save(ctx)
  478. require.NoError(t, err)
  479. existingIdentity, err := client.AuthIdentity.Create().
  480. SetUserID(userEntity.ID).
  481. SetProviderType("linuxdo").
  482. SetProviderKey("linuxdo").
  483. SetProviderSubject("login-reassign-123").
  484. SetMetadata(map[string]any{}).
  485. Save(ctx)
  486. require.NoError(t, err)
  487. previousSession, err := client.PendingAuthSession.Create().
  488. SetSessionToken("login-reassign-previous-session-token").
  489. SetIntent("login").
  490. SetProviderType("linuxdo").
  491. SetProviderKey("linuxdo").
  492. SetProviderSubject("login-reassign-123").
  493. SetTargetUserID(userEntity.ID).
  494. SetResolvedEmail(userEntity.Email).
  495. SetBrowserSessionKey("login-reassign-previous-browser-session-key").
  496. SetLocalFlowState(map[string]any{
  497. oauthCompletionResponseKey: map[string]any{
  498. "access_token": "previous-access-token",
  499. },
  500. }).
  501. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  502. Save(ctx)
  503. require.NoError(t, err)
  504. previousDecision, err := client.IdentityAdoptionDecision.Create().
  505. SetPendingAuthSessionID(previousSession.ID).
  506. SetIdentityID(existingIdentity.ID).
  507. SetAdoptDisplayName(true).
  508. SetAdoptAvatar(true).
  509. Save(ctx)
  510. require.NoError(t, err)
  511. session, err := client.PendingAuthSession.Create().
  512. SetSessionToken("login-reassign-session-token").
  513. SetIntent("login").
  514. SetProviderType("linuxdo").
  515. SetProviderKey("linuxdo").
  516. SetProviderSubject("login-reassign-123").
  517. SetTargetUserID(userEntity.ID).
  518. SetResolvedEmail(userEntity.Email).
  519. SetBrowserSessionKey("login-reassign-browser-session-key").
  520. SetUpstreamIdentityClaims(map[string]any{
  521. "suggested_display_name": "Login Reassign",
  522. "suggested_avatar_url": "https://cdn.example/login-reassign.png",
  523. }).
  524. SetLocalFlowState(map[string]any{
  525. oauthCompletionResponseKey: map[string]any{
  526. "access_token": "access-token",
  527. },
  528. }).
  529. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  530. Save(ctx)
  531. require.NoError(t, err)
  532. _, err = client.IdentityAdoptionDecision.Create().
  533. SetPendingAuthSessionID(session.ID).
  534. SetAdoptDisplayName(false).
  535. SetAdoptAvatar(false).
  536. Save(ctx)
  537. require.NoError(t, err)
  538. body := bytes.NewBufferString(`{"adopt_display_name":false,"adopt_avatar":false}`)
  539. recorder := httptest.NewRecorder()
  540. ginCtx, _ := gin.CreateTestContext(recorder)
  541. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", body)
  542. req.Header.Set("Content-Type", "application/json")
  543. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  544. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("login-reassign-browser-session-key")})
  545. ginCtx.Request = req
  546. handler.ExchangePendingOAuthCompletion(ginCtx)
  547. require.Equal(t, http.StatusOK, recorder.Code)
  548. reloadedPrevious, err := client.IdentityAdoptionDecision.Get(ctx, previousDecision.ID)
  549. require.NoError(t, err)
  550. require.Nil(t, reloadedPrevious.IdentityID)
  551. currentDecision, err := client.IdentityAdoptionDecision.Query().
  552. Where(identityadoptiondecision.PendingAuthSessionIDEQ(session.ID)).
  553. Only(ctx)
  554. require.NoError(t, err)
  555. require.NotNil(t, currentDecision.IdentityID)
  556. require.Equal(t, existingIdentity.ID, *currentDecision.IdentityID)
  557. storedSession, err := client.PendingAuthSession.Query().
  558. Where(pendingauthsession.IDEQ(session.ID)).
  559. Only(ctx)
  560. require.NoError(t, err)
  561. require.NotNil(t, storedSession.ConsumedAt)
  562. }
  563. func TestExchangePendingOAuthCompletionLoginWithoutDecisionStillBindsIdentity(t *testing.T) {
  564. handler, client := newOAuthPendingFlowTestHandler(t, false)
  565. ctx := context.Background()
  566. userEntity, err := client.User.Create().
  567. SetEmail("login-nodecision@example.com").
  568. SetUsername("legacy-name").
  569. SetPasswordHash("hash").
  570. SetRole(service.RoleUser).
  571. SetStatus(service.StatusActive).
  572. Save(ctx)
  573. require.NoError(t, err)
  574. session, err := client.PendingAuthSession.Create().
  575. SetSessionToken("login-nodecision-session-token").
  576. SetIntent("login").
  577. SetProviderType("linuxdo").
  578. SetProviderKey("linuxdo").
  579. SetProviderSubject("login-nodecision-123").
  580. SetTargetUserID(userEntity.ID).
  581. SetResolvedEmail(userEntity.Email).
  582. SetBrowserSessionKey("login-nodecision-browser-session-key").
  583. SetUpstreamIdentityClaims(map[string]any{
  584. "username": "login-nodecision-user",
  585. }).
  586. SetLocalFlowState(map[string]any{
  587. oauthCompletionResponseKey: map[string]any{
  588. "access_token": "access-token",
  589. },
  590. }).
  591. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  592. Save(ctx)
  593. require.NoError(t, err)
  594. recorder := httptest.NewRecorder()
  595. ginCtx, _ := gin.CreateTestContext(recorder)
  596. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", nil)
  597. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  598. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("login-nodecision-browser-session-key")})
  599. ginCtx.Request = req
  600. handler.ExchangePendingOAuthCompletion(ginCtx)
  601. require.Equal(t, http.StatusOK, recorder.Code)
  602. identity, err := client.AuthIdentity.Query().
  603. Where(
  604. authidentity.ProviderTypeEQ("linuxdo"),
  605. authidentity.ProviderKeyEQ("linuxdo"),
  606. authidentity.ProviderSubjectEQ("login-nodecision-123"),
  607. ).
  608. Only(ctx)
  609. require.NoError(t, err)
  610. require.Equal(t, userEntity.ID, identity.UserID)
  611. storedSession, err := client.PendingAuthSession.Query().
  612. Where(pendingauthsession.IDEQ(session.ID)).
  613. Only(ctx)
  614. require.NoError(t, err)
  615. require.NotNil(t, storedSession.ConsumedAt)
  616. }
  617. func TestExchangePendingOAuthCompletionExistingLoginWithSuggestedProfileSkipsAdoptionPrompt(t *testing.T) {
  618. handler, client := newOAuthPendingFlowTestHandler(t, false)
  619. ctx := context.Background()
  620. userEntity, err := client.User.Create().
  621. SetEmail("existing-login@example.com").
  622. SetUsername("existing-login-user").
  623. SetPasswordHash("hash").
  624. SetRole(service.RoleUser).
  625. SetStatus(service.StatusActive).
  626. Save(ctx)
  627. require.NoError(t, err)
  628. _, err = client.AuthIdentity.Create().
  629. SetUserID(userEntity.ID).
  630. SetProviderType("linuxdo").
  631. SetProviderKey("linuxdo").
  632. SetProviderSubject("existing-login-123").
  633. SetMetadata(map[string]any{
  634. "username": "existing-login-user",
  635. }).
  636. Save(ctx)
  637. require.NoError(t, err)
  638. session, err := client.PendingAuthSession.Create().
  639. SetSessionToken("existing-login-session-token").
  640. SetIntent("login").
  641. SetProviderType("linuxdo").
  642. SetProviderKey("linuxdo").
  643. SetProviderSubject("existing-login-123").
  644. SetTargetUserID(userEntity.ID).
  645. SetResolvedEmail(userEntity.Email).
  646. SetBrowserSessionKey("existing-login-browser-session-key").
  647. SetUpstreamIdentityClaims(map[string]any{
  648. "suggested_display_name": "Existing Login Example",
  649. "suggested_avatar_url": "https://cdn.example/existing-login.png",
  650. }).
  651. SetLocalFlowState(map[string]any{
  652. oauthCompletionResponseKey: map[string]any{
  653. "access_token": "legacy-access-token",
  654. "refresh_token": "legacy-refresh-token",
  655. "expires_in": float64(3600),
  656. "token_type": "Bearer",
  657. "redirect": "/dashboard",
  658. },
  659. }).
  660. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  661. Save(ctx)
  662. require.NoError(t, err)
  663. recorder := httptest.NewRecorder()
  664. ginCtx, _ := gin.CreateTestContext(recorder)
  665. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", nil)
  666. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  667. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("existing-login-browser-session-key")})
  668. ginCtx.Request = req
  669. handler.ExchangePendingOAuthCompletion(ginCtx)
  670. require.Equal(t, http.StatusOK, recorder.Code)
  671. payload := decodeJSONResponseData(t, recorder)
  672. require.NotEmpty(t, payload["access_token"])
  673. require.NotEmpty(t, payload["refresh_token"])
  674. require.NotEqual(t, "legacy-access-token", payload["access_token"])
  675. require.NotEqual(t, "legacy-refresh-token", payload["refresh_token"])
  676. require.Equal(t, "/dashboard", payload["redirect"])
  677. require.Equal(t, "Existing Login Example", payload["suggested_display_name"])
  678. require.Equal(t, "https://cdn.example/existing-login.png", payload["suggested_avatar_url"])
  679. require.NotContains(t, payload, "adoption_required")
  680. accessToken, ok := payload["access_token"].(string)
  681. require.True(t, ok)
  682. claims, err := handler.authService.ValidateToken(accessToken)
  683. require.NoError(t, err)
  684. reloadedUser, err := handler.userService.GetByID(ctx, userEntity.ID)
  685. require.NoError(t, err)
  686. require.Equal(t, reloadedUser.TokenVersion, claims.TokenVersion)
  687. decisionCount, err := client.IdentityAdoptionDecision.Query().
  688. Where(identityadoptiondecision.PendingAuthSessionIDEQ(session.ID)).
  689. Count(ctx)
  690. require.NoError(t, err)
  691. require.Equal(t, 1, decisionCount)
  692. storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
  693. require.NoError(t, err)
  694. require.NotNil(t, storedSession.ConsumedAt)
  695. completion, ok := storedSession.LocalFlowState[oauthCompletionResponseKey].(map[string]any)
  696. require.True(t, ok)
  697. require.NotContains(t, completion, "access_token")
  698. require.NotContains(t, completion, "refresh_token")
  699. require.NotContains(t, completion, "expires_in")
  700. require.NotContains(t, completion, "token_type")
  701. require.Equal(t, "/dashboard", completion["redirect"])
  702. }
  703. func TestExchangePendingOAuthCompletionBlocksBackendModeBeforeReturningTokenPayload(t *testing.T) {
  704. handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
  705. settingValues: map[string]string{
  706. service.SettingKeyBackendModeEnabled: "true",
  707. },
  708. })
  709. ctx := context.Background()
  710. userEntity, err := client.User.Create().
  711. SetEmail("blocked@example.com").
  712. SetUsername("blocked-user").
  713. SetPasswordHash("hash").
  714. SetRole(service.RoleUser).
  715. SetStatus(service.StatusActive).
  716. Save(ctx)
  717. require.NoError(t, err)
  718. session, err := client.PendingAuthSession.Create().
  719. SetSessionToken("blocked-backend-mode-session-token").
  720. SetIntent("login").
  721. SetProviderType("linuxdo").
  722. SetProviderKey("linuxdo").
  723. SetProviderSubject("blocked-subject-123").
  724. SetTargetUserID(userEntity.ID).
  725. SetResolvedEmail(userEntity.Email).
  726. SetBrowserSessionKey("blocked-backend-mode-browser-session-key").
  727. SetLocalFlowState(map[string]any{
  728. oauthCompletionResponseKey: map[string]any{
  729. "access_token": "access-token",
  730. "refresh_token": "refresh-token",
  731. "expires_in": float64(3600),
  732. "token_type": "Bearer",
  733. },
  734. }).
  735. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  736. Save(ctx)
  737. require.NoError(t, err)
  738. recorder := httptest.NewRecorder()
  739. ginCtx, _ := gin.CreateTestContext(recorder)
  740. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", nil)
  741. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  742. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("blocked-backend-mode-browser-session-key")})
  743. ginCtx.Request = req
  744. handler.ExchangePendingOAuthCompletion(ginCtx)
  745. require.Equal(t, http.StatusForbidden, recorder.Code)
  746. storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
  747. require.NoError(t, err)
  748. require.Nil(t, storedSession.ConsumedAt)
  749. }
  750. func TestExchangePendingOAuthCompletionRejectsDisabledTargetUser(t *testing.T) {
  751. handler, client := newOAuthPendingFlowTestHandler(t, false)
  752. ctx := context.Background()
  753. userEntity, err := client.User.Create().
  754. SetEmail("disabled-linked@example.com").
  755. SetUsername("disabled-linked-user").
  756. SetPasswordHash("hash").
  757. SetRole(service.RoleUser).
  758. SetStatus(service.StatusDisabled).
  759. Save(ctx)
  760. require.NoError(t, err)
  761. session, err := client.PendingAuthSession.Create().
  762. SetSessionToken("disabled-linked-session-token").
  763. SetIntent("login").
  764. SetProviderType("linuxdo").
  765. SetProviderKey("linuxdo").
  766. SetProviderSubject("disabled-linked-subject").
  767. SetTargetUserID(userEntity.ID).
  768. SetResolvedEmail(userEntity.Email).
  769. SetBrowserSessionKey("disabled-linked-browser-session-key").
  770. SetUpstreamIdentityClaims(map[string]any{
  771. "suggested_display_name": "Disabled Linked User",
  772. }).
  773. SetLocalFlowState(map[string]any{
  774. oauthCompletionResponseKey: map[string]any{
  775. "redirect": "/dashboard",
  776. },
  777. }).
  778. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  779. Save(ctx)
  780. require.NoError(t, err)
  781. recorder := httptest.NewRecorder()
  782. ginCtx, _ := gin.CreateTestContext(recorder)
  783. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", nil)
  784. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  785. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("disabled-linked-browser-session-key")})
  786. ginCtx.Request = req
  787. handler.ExchangePendingOAuthCompletion(ginCtx)
  788. require.Equal(t, http.StatusForbidden, recorder.Code)
  789. storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
  790. require.NoError(t, err)
  791. require.Nil(t, storedSession.ConsumedAt)
  792. }
  793. func TestExchangePendingOAuthCompletionChoiceStateDoesNotBindIdentity(t *testing.T) {
  794. // 回归测试:复刻"补邮箱/创建账户"路径的账号接管 0day。
  795. // 攻击者用自己的 OAuth 账号登录后,在 create-account 步骤提交受害者邮箱,
  796. // 后端发现邮箱已存在会把 pending session 转入 choice 状态并指向受害者
  797. // (TargetUserID=受害者、无密码/验证码证明)。此时带 adoption decision 调
  798. // exchange 绝不能把 OAuth identity 绑定到受害者账号。
  799. handler, client := newOAuthPendingFlowTestHandler(t, false)
  800. ctx := context.Background()
  801. victim, err := client.User.Create().
  802. SetEmail("victim@example.com").
  803. SetUsername("victim-user").
  804. SetPasswordHash("hash").
  805. SetRole(service.RoleUser).
  806. SetStatus(service.StatusActive).
  807. Save(ctx)
  808. require.NoError(t, err)
  809. session, err := client.PendingAuthSession.Create().
  810. SetSessionToken("choice-state-attack-session-token").
  811. SetIntent("login").
  812. SetProviderType("linuxdo").
  813. SetProviderKey("linuxdo").
  814. SetProviderSubject("attacker-subject-123").
  815. SetTargetUserID(victim.ID).
  816. SetResolvedEmail(victim.Email).
  817. SetBrowserSessionKey("choice-state-attack-browser-session-key").
  818. SetUpstreamIdentityClaims(map[string]any{
  819. "username": "attacker_linuxdo_user",
  820. "suggested_display_name": "Attacker Display Name",
  821. "suggested_avatar_url": "https://cdn.example/attacker.png",
  822. }).
  823. SetLocalFlowState(map[string]any{
  824. oauthCompletionResponseKey: map[string]any{
  825. "step": oauthPendingChoiceStep,
  826. "adoption_required": true,
  827. "force_email_on_signup": true,
  828. "email_binding_required": true,
  829. "existing_account_bindable": true,
  830. "email": victim.Email,
  831. "resolved_email": victim.Email,
  832. "redirect": "/dashboard",
  833. },
  834. }).
  835. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  836. Save(ctx)
  837. require.NoError(t, err)
  838. body := bytes.NewBufferString(`{"adopt_display_name":true,"adopt_avatar":true}`)
  839. recorder := httptest.NewRecorder()
  840. ginCtx, _ := gin.CreateTestContext(recorder)
  841. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", body)
  842. req.Header.Set("Content-Type", "application/json")
  843. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  844. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("choice-state-attack-browser-session-key")})
  845. ginCtx.Request = req
  846. handler.ExchangePendingOAuthCompletion(ginCtx)
  847. require.Equal(t, http.StatusOK, recorder.Code)
  848. data := decodeJSONResponseData(t, recorder)
  849. require.NotContains(t, data, "access_token")
  850. require.Equal(t, oauthPendingChoiceStep, data["step"])
  851. // 攻击者的 OAuth identity 绝不能绑定到受害者账号
  852. identityCount, err := client.AuthIdentity.Query().
  853. Where(
  854. authidentity.ProviderTypeEQ("linuxdo"),
  855. authidentity.ProviderKeyEQ("linuxdo"),
  856. authidentity.ProviderSubjectEQ("attacker-subject-123"),
  857. ).
  858. Count(ctx)
  859. require.NoError(t, err)
  860. require.Zero(t, identityCount)
  861. // 受害者资料不得被 adoption 篡改
  862. storedVictim, err := client.User.Get(ctx, victim.ID)
  863. require.NoError(t, err)
  864. require.Equal(t, "victim-user", storedVictim.Username)
  865. // session 不得被消费(攻击者无法进入下一环)
  866. storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
  867. require.NoError(t, err)
  868. require.Nil(t, storedSession.ConsumedAt)
  869. }
  870. func TestNormalizePendingOAuthCompletionResponseScrubsLegacyTokenPayload(t *testing.T) {
  871. payload := normalizePendingOAuthCompletionResponse(map[string]any{
  872. "access_token": "legacy-access-token",
  873. "refresh_token": "legacy-refresh-token",
  874. "expires_in": float64(3600),
  875. "token_type": "Bearer",
  876. "redirect": "/dashboard",
  877. })
  878. require.NotContains(t, payload, "access_token")
  879. require.NotContains(t, payload, "refresh_token")
  880. require.NotContains(t, payload, "expires_in")
  881. require.NotContains(t, payload, "token_type")
  882. require.Equal(t, "/dashboard", payload["redirect"])
  883. }
  884. func TestExchangePendingOAuthCompletionInvitationRequiredFalseFalsePersistsDecisionWithoutBinding(t *testing.T) {
  885. handler, client := newOAuthPendingFlowTestHandler(t, true)
  886. ctx := context.Background()
  887. session, err := client.PendingAuthSession.Create().
  888. SetSessionToken("invitation-required-session-token").
  889. SetIntent("login").
  890. SetProviderType("linuxdo").
  891. SetProviderKey("linuxdo").
  892. SetProviderSubject("invitation-123").
  893. SetBrowserSessionKey("invitation-required-browser-session-key").
  894. SetUpstreamIdentityClaims(map[string]any{
  895. "suggested_display_name": "Invite Example",
  896. "suggested_avatar_url": "https://cdn.example/invite.png",
  897. }).
  898. SetLocalFlowState(map[string]any{
  899. oauthCompletionResponseKey: map[string]any{
  900. "error": "invitation_required",
  901. },
  902. }).
  903. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  904. Save(ctx)
  905. require.NoError(t, err)
  906. body := bytes.NewBufferString(`{"adopt_display_name":false,"adopt_avatar":false}`)
  907. recorder := httptest.NewRecorder()
  908. ginCtx, _ := gin.CreateTestContext(recorder)
  909. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", body)
  910. req.Header.Set("Content-Type", "application/json")
  911. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  912. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("invitation-required-browser-session-key")})
  913. ginCtx.Request = req
  914. handler.ExchangePendingOAuthCompletion(ginCtx)
  915. require.Equal(t, http.StatusOK, recorder.Code)
  916. data := decodeJSONResponseData(t, recorder)
  917. require.Equal(t, "invitation_required", data["error"])
  918. require.Equal(t, true, data["adoption_required"])
  919. identityCount, err := client.AuthIdentity.Query().
  920. Where(
  921. authidentity.ProviderTypeEQ("linuxdo"),
  922. authidentity.ProviderKeyEQ("linuxdo"),
  923. authidentity.ProviderSubjectEQ("invitation-123"),
  924. ).
  925. Count(ctx)
  926. require.NoError(t, err)
  927. require.Zero(t, identityCount)
  928. decision, err := client.IdentityAdoptionDecision.Query().
  929. Where(identityadoptiondecision.PendingAuthSessionIDEQ(session.ID)).
  930. Only(ctx)
  931. require.NoError(t, err)
  932. require.Nil(t, decision.IdentityID)
  933. require.False(t, decision.AdoptDisplayName)
  934. require.False(t, decision.AdoptAvatar)
  935. storedSession, err := client.PendingAuthSession.Query().
  936. Where(pendingauthsession.IDEQ(session.ID)).
  937. Only(ctx)
  938. require.NoError(t, err)
  939. require.Nil(t, storedSession.ConsumedAt)
  940. }
  941. func TestCreateOIDCOAuthAccountCreatesUserBindsIdentityAndConsumesSession(t *testing.T) {
  942. handler, client := newOAuthPendingFlowTestHandlerWithEmailVerification(t, false, "fresh@example.com", "246810")
  943. ctx := context.Background()
  944. session, err := client.PendingAuthSession.Create().
  945. SetSessionToken("create-account-session-token").
  946. SetIntent("login").
  947. SetProviderType("oidc").
  948. SetProviderKey("https://issuer.example").
  949. SetProviderSubject("oidc-create-123").
  950. SetBrowserSessionKey("create-account-browser-session-key").
  951. SetUpstreamIdentityClaims(map[string]any{
  952. "username": "oidc_user",
  953. "suggested_display_name": "Fresh OIDC User",
  954. "suggested_avatar_url": "https://cdn.example/fresh.png",
  955. }).
  956. SetRedirectTo("/profile").
  957. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  958. Save(ctx)
  959. require.NoError(t, err)
  960. body := bytes.NewBufferString(`{"email":"fresh@example.com","verify_code":"246810","password":"secret-123","adopt_display_name":false,"adopt_avatar":false}`)
  961. recorder := httptest.NewRecorder()
  962. ginCtx, _ := gin.CreateTestContext(recorder)
  963. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
  964. req.Header.Set("Content-Type", "application/json")
  965. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  966. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("create-account-browser-session-key")})
  967. ginCtx.Request = req
  968. handler.CreateOIDCOAuthAccount(ginCtx)
  969. require.Equal(t, http.StatusOK, recorder.Code)
  970. var payload map[string]any
  971. require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &payload))
  972. require.NotEmpty(t, payload["access_token"])
  973. require.NotEmpty(t, payload["refresh_token"])
  974. require.Equal(t, "Bearer", payload["token_type"])
  975. createdUser, err := client.User.Query().Where(dbuser.EmailEQ("fresh@example.com")).Only(ctx)
  976. require.NoError(t, err)
  977. require.Equal(t, service.StatusActive, createdUser.Status)
  978. identity, err := client.AuthIdentity.Query().
  979. Where(
  980. authidentity.ProviderTypeEQ("oidc"),
  981. authidentity.ProviderKeyEQ("https://issuer.example"),
  982. authidentity.ProviderSubjectEQ("oidc-create-123"),
  983. ).
  984. Only(ctx)
  985. require.NoError(t, err)
  986. require.Equal(t, createdUser.ID, identity.UserID)
  987. storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
  988. require.NoError(t, err)
  989. require.NotNil(t, storedSession.ConsumedAt)
  990. }
  991. func TestCreateOIDCOAuthAccountAppliesPromoCodeFromPendingSession(t *testing.T) {
  992. promoRepo := newOAuthPendingFlowPromoRepoStub("WELCOME2024", 25)
  993. emailCache := &oauthPendingFlowEmailCacheStub{
  994. verificationCodes: map[string]*service.VerificationCodeData{
  995. "promo@example.com": {
  996. Code: "246810",
  997. CreatedAt: time.Now().UTC(),
  998. ExpiresAt: time.Now().UTC().Add(15 * time.Minute),
  999. },
  1000. },
  1001. }
  1002. handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
  1003. emailVerifyEnabled: true,
  1004. emailCache: emailCache,
  1005. promoRepo: promoRepo,
  1006. settingValues: map[string]string{
  1007. service.SettingKeyPromoCodeEnabled: "true",
  1008. },
  1009. })
  1010. ctx := context.Background()
  1011. session, err := client.PendingAuthSession.Create().
  1012. SetSessionToken("promo-create-account-session-token").
  1013. SetIntent(oauthIntentLogin).
  1014. SetProviderType("oidc").
  1015. SetProviderKey("https://issuer.example").
  1016. SetProviderSubject("oidc-promo-123").
  1017. SetBrowserSessionKey("promo-create-account-browser-key").
  1018. SetUpstreamIdentityClaims(map[string]any{"username": "promo_user"}).
  1019. SetLocalFlowState(map[string]any{oauthPromoCodeStateKey: "WELCOME2024"}).
  1020. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  1021. Save(ctx)
  1022. require.NoError(t, err)
  1023. body := bytes.NewBufferString(`{"email":"promo@example.com","verify_code":"246810","password":"secret-123"}`)
  1024. recorder := httptest.NewRecorder()
  1025. ginCtx, _ := gin.CreateTestContext(recorder)
  1026. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
  1027. req.Header.Set("Content-Type", "application/json")
  1028. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  1029. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue(session.BrowserSessionKey)})
  1030. ginCtx.Request = req
  1031. handler.CreateOIDCOAuthAccount(ginCtx)
  1032. require.Equal(t, http.StatusOK, recorder.Code)
  1033. require.Equal(t, []string{"WELCOME2024"}, promoRepo.applyCalls)
  1034. createdUser, err := client.User.Query().Where(dbuser.EmailEQ("promo@example.com")).Only(ctx)
  1035. require.NoError(t, err)
  1036. require.Equal(t, 25.0, createdUser.Balance)
  1037. require.Len(t, promoRepo.usages, 1)
  1038. require.Equal(t, createdUser.ID, promoRepo.usages[0].UserID)
  1039. }
  1040. func TestCreateOIDCOAuthAccountWithoutPromoCodeDoesNotApplyPromo(t *testing.T) {
  1041. promoRepo := newOAuthPendingFlowPromoRepoStub("WELCOME2024", 25)
  1042. emailCache := &oauthPendingFlowEmailCacheStub{
  1043. verificationCodes: map[string]*service.VerificationCodeData{
  1044. "no-promo@example.com": {
  1045. Code: "246810",
  1046. CreatedAt: time.Now().UTC(),
  1047. ExpiresAt: time.Now().UTC().Add(15 * time.Minute),
  1048. },
  1049. },
  1050. }
  1051. handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
  1052. emailVerifyEnabled: true,
  1053. emailCache: emailCache,
  1054. promoRepo: promoRepo,
  1055. settingValues: map[string]string{
  1056. service.SettingKeyPromoCodeEnabled: "true",
  1057. },
  1058. })
  1059. ctx := context.Background()
  1060. session, err := client.PendingAuthSession.Create().
  1061. SetSessionToken("no-promo-create-account-session-token").
  1062. SetIntent(oauthIntentLogin).
  1063. SetProviderType("oidc").
  1064. SetProviderKey("https://issuer.example").
  1065. SetProviderSubject("oidc-no-promo-123").
  1066. SetBrowserSessionKey("no-promo-create-account-browser-key").
  1067. SetUpstreamIdentityClaims(map[string]any{"username": "no_promo_user"}).
  1068. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  1069. Save(ctx)
  1070. require.NoError(t, err)
  1071. body := bytes.NewBufferString(`{"email":"no-promo@example.com","verify_code":"246810","password":"secret-123"}`)
  1072. recorder := httptest.NewRecorder()
  1073. ginCtx, _ := gin.CreateTestContext(recorder)
  1074. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
  1075. req.Header.Set("Content-Type", "application/json")
  1076. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  1077. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue(session.BrowserSessionKey)})
  1078. ginCtx.Request = req
  1079. handler.CreateOIDCOAuthAccount(ginCtx)
  1080. require.Equal(t, http.StatusOK, recorder.Code)
  1081. require.Empty(t, promoRepo.applyCalls)
  1082. createdUser, err := client.User.Query().Where(dbuser.EmailEQ("no-promo@example.com")).Only(ctx)
  1083. require.NoError(t, err)
  1084. require.Zero(t, createdUser.Balance)
  1085. }
  1086. func TestCreateOIDCOAuthAccountDoesNotApplyPromoWhenDisabled(t *testing.T) {
  1087. promoRepo := newOAuthPendingFlowPromoRepoStub("WELCOME2024", 25)
  1088. emailCache := &oauthPendingFlowEmailCacheStub{
  1089. verificationCodes: map[string]*service.VerificationCodeData{
  1090. "promo-disabled@example.com": {
  1091. Code: "246810",
  1092. CreatedAt: time.Now().UTC(),
  1093. ExpiresAt: time.Now().UTC().Add(15 * time.Minute),
  1094. },
  1095. },
  1096. }
  1097. handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
  1098. emailVerifyEnabled: true,
  1099. emailCache: emailCache,
  1100. promoRepo: promoRepo,
  1101. settingValues: map[string]string{
  1102. service.SettingKeyPromoCodeEnabled: "false",
  1103. },
  1104. })
  1105. ctx := context.Background()
  1106. session, err := client.PendingAuthSession.Create().
  1107. SetSessionToken("promo-disabled-session-token").
  1108. SetIntent(oauthIntentLogin).
  1109. SetProviderType("oidc").
  1110. SetProviderKey("https://issuer.example").
  1111. SetProviderSubject("oidc-promo-disabled-123").
  1112. SetBrowserSessionKey("promo-disabled-browser-key").
  1113. SetUpstreamIdentityClaims(map[string]any{"username": "promo_disabled_user"}).
  1114. SetLocalFlowState(map[string]any{oauthPromoCodeStateKey: "WELCOME2024"}).
  1115. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  1116. Save(ctx)
  1117. require.NoError(t, err)
  1118. body := bytes.NewBufferString(`{"email":"promo-disabled@example.com","verify_code":"246810","password":"secret-123"}`)
  1119. recorder := httptest.NewRecorder()
  1120. ginCtx, _ := gin.CreateTestContext(recorder)
  1121. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
  1122. req.Header.Set("Content-Type", "application/json")
  1123. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  1124. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue(session.BrowserSessionKey)})
  1125. ginCtx.Request = req
  1126. handler.CreateOIDCOAuthAccount(ginCtx)
  1127. require.Equal(t, http.StatusOK, recorder.Code)
  1128. require.Empty(t, promoRepo.applyCalls)
  1129. createdUser, err := client.User.Query().Where(dbuser.EmailEQ("promo-disabled@example.com")).Only(ctx)
  1130. require.NoError(t, err)
  1131. require.Zero(t, createdUser.Balance)
  1132. }
  1133. func TestOAuthExistingUserLoginDoesNotApplyPromoCode(t *testing.T) {
  1134. promoRepo := newOAuthPendingFlowPromoRepoStub("WELCOME2024", 25)
  1135. handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
  1136. promoRepo: promoRepo,
  1137. settingValues: map[string]string{
  1138. service.SettingKeyPromoCodeEnabled: "true",
  1139. },
  1140. })
  1141. ctx := context.Background()
  1142. existingUser, err := client.User.Create().
  1143. SetEmail("existing-promo@example.com").
  1144. SetUsername("existing").
  1145. SetPasswordHash("hash").
  1146. SetRole(service.RoleUser).
  1147. SetStatus(service.StatusActive).
  1148. SetBalance(7).
  1149. Save(ctx)
  1150. require.NoError(t, err)
  1151. _, loggedInUser, err := handler.authService.LoginOrRegisterOAuthWithTokenPairAndPromoCode(
  1152. ctx,
  1153. existingUser.Email,
  1154. existingUser.Username,
  1155. "",
  1156. "",
  1157. "WELCOME2024",
  1158. "oidc",
  1159. )
  1160. require.NoError(t, err)
  1161. require.Equal(t, existingUser.ID, loggedInUser.ID)
  1162. require.Empty(t, promoRepo.applyCalls)
  1163. reloadedUser, err := client.User.Get(ctx, existingUser.ID)
  1164. require.NoError(t, err)
  1165. require.Equal(t, 7.0, reloadedUser.Balance)
  1166. }
  1167. func TestCreateOIDCOAuthAccountExistingEmailReturnsChoicePendingSessionState(t *testing.T) {
  1168. handler, client := newOAuthPendingFlowTestHandlerWithEmailVerification(t, false, "owner@example.com", "135790")
  1169. ctx := context.Background()
  1170. existingUser, err := client.User.Create().
  1171. SetEmail("owner@example.com").
  1172. SetUsername("owner-user").
  1173. SetPasswordHash("hash").
  1174. SetRole(service.RoleUser).
  1175. SetStatus(service.StatusActive).
  1176. Save(ctx)
  1177. require.NoError(t, err)
  1178. session, err := client.PendingAuthSession.Create().
  1179. SetSessionToken("existing-email-session-token").
  1180. SetIntent("login").
  1181. SetProviderType("oidc").
  1182. SetProviderKey("https://issuer.example").
  1183. SetProviderSubject("oidc-existing-123").
  1184. SetBrowserSessionKey("existing-email-browser-session-key").
  1185. SetUpstreamIdentityClaims(map[string]any{
  1186. "username": "oidc_user",
  1187. "suggested_display_name": "Existing OIDC User",
  1188. "suggested_avatar_url": "https://cdn.example/existing.png",
  1189. }).
  1190. SetRedirectTo("/dashboard").
  1191. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  1192. Save(ctx)
  1193. require.NoError(t, err)
  1194. body := bytes.NewBufferString(`{"email":"owner@example.com","verify_code":"135790","password":"secret-123"}`)
  1195. recorder := httptest.NewRecorder()
  1196. ginCtx, _ := gin.CreateTestContext(recorder)
  1197. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
  1198. req.Header.Set("Content-Type", "application/json")
  1199. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  1200. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("existing-email-browser-session-key")})
  1201. ginCtx.Request = req
  1202. handler.CreateOIDCOAuthAccount(ginCtx)
  1203. require.Equal(t, http.StatusOK, recorder.Code)
  1204. var payload map[string]any
  1205. require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &payload))
  1206. require.Equal(t, "pending_session", payload["auth_result"])
  1207. require.Equal(t, oauthIntentLogin, payload["intent"])
  1208. require.Equal(t, "oidc", payload["provider"])
  1209. require.Equal(t, "/dashboard", payload["redirect"])
  1210. require.Equal(t, true, payload["adoption_required"])
  1211. require.Equal(t, oauthPendingChoiceStep, payload["step"])
  1212. require.Equal(t, "owner@example.com", payload["email"])
  1213. require.Equal(t, "Existing OIDC User", payload["suggested_display_name"])
  1214. require.Equal(t, "https://cdn.example/existing.png", payload["suggested_avatar_url"])
  1215. storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
  1216. require.NoError(t, err)
  1217. require.Equal(t, oauthIntentLogin, storedSession.Intent)
  1218. require.NotNil(t, storedSession.TargetUserID)
  1219. require.Equal(t, existingUser.ID, *storedSession.TargetUserID)
  1220. require.Equal(t, "owner@example.com", storedSession.ResolvedEmail)
  1221. require.Nil(t, storedSession.ConsumedAt)
  1222. identityCount, err := client.AuthIdentity.Query().
  1223. Where(
  1224. authidentity.ProviderTypeEQ("oidc"),
  1225. authidentity.ProviderKeyEQ("https://issuer.example"),
  1226. authidentity.ProviderSubjectEQ("oidc-existing-123"),
  1227. ).
  1228. Count(ctx)
  1229. require.NoError(t, err)
  1230. require.Zero(t, identityCount)
  1231. }
  1232. func TestCreateOIDCOAuthAccountExistingEmailNormalizesLegacySpacingAndCase(t *testing.T) {
  1233. handler, client := newOAuthPendingFlowTestHandlerWithEmailVerification(t, false, "owner@example.com", "135790")
  1234. ctx := context.Background()
  1235. existingUser, err := client.User.Create().
  1236. SetEmail(" Owner@Example.com ").
  1237. SetUsername("owner-user").
  1238. SetPasswordHash("hash").
  1239. SetRole(service.RoleUser).
  1240. SetStatus(service.StatusActive).
  1241. Save(ctx)
  1242. require.NoError(t, err)
  1243. session, err := client.PendingAuthSession.Create().
  1244. SetSessionToken("existing-email-normalized-session-token").
  1245. SetIntent("login").
  1246. SetProviderType("oidc").
  1247. SetProviderKey("https://issuer.example").
  1248. SetProviderSubject("oidc-existing-normalized-123").
  1249. SetBrowserSessionKey("existing-email-normalized-browser-session-key").
  1250. SetUpstreamIdentityClaims(map[string]any{
  1251. "username": "oidc_user",
  1252. "suggested_display_name": "Existing OIDC User",
  1253. "suggested_avatar_url": "https://cdn.example/existing.png",
  1254. }).
  1255. SetRedirectTo("/dashboard").
  1256. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  1257. Save(ctx)
  1258. require.NoError(t, err)
  1259. body := bytes.NewBufferString(`{"email":"owner@example.com","verify_code":"135790","password":"secret-123"}`)
  1260. recorder := httptest.NewRecorder()
  1261. ginCtx, _ := gin.CreateTestContext(recorder)
  1262. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
  1263. req.Header.Set("Content-Type", "application/json")
  1264. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  1265. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("existing-email-normalized-browser-session-key")})
  1266. ginCtx.Request = req
  1267. handler.CreateOIDCOAuthAccount(ginCtx)
  1268. require.Equal(t, http.StatusOK, recorder.Code)
  1269. var payload map[string]any
  1270. require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &payload))
  1271. require.Equal(t, oauthIntentLogin, payload["intent"])
  1272. require.Equal(t, oauthPendingChoiceStep, payload["step"])
  1273. storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
  1274. require.NoError(t, err)
  1275. require.NotNil(t, storedSession.TargetUserID)
  1276. require.Equal(t, existingUser.ID, *storedSession.TargetUserID)
  1277. require.Equal(t, "owner@example.com", storedSession.ResolvedEmail)
  1278. }
  1279. func TestCreateOIDCOAuthAccountRejectsSecondEmailOutsideRegistrationSuffixWhitelist(t *testing.T) {
  1280. handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
  1281. emailVerifyEnabled: true,
  1282. emailCache: &oauthPendingFlowEmailCacheStub{
  1283. verificationCodes: map[string]*service.VerificationCodeData{
  1284. "foo@gmail.com": {
  1285. Code: "135790",
  1286. CreatedAt: time.Now().UTC(),
  1287. ExpiresAt: time.Now().UTC().Add(15 * time.Minute),
  1288. },
  1289. },
  1290. },
  1291. settingValues: map[string]string{
  1292. service.SettingKeyRegistrationEmailSuffixWhitelist: `["@qq.com"]`,
  1293. service.SettingKeyRegistrationEmailDomainQuotaEnabled: "true",
  1294. },
  1295. })
  1296. ctx := context.Background()
  1297. _, err := client.User.Create().
  1298. SetEmail("existing@gmail.com").
  1299. SetUsername("existing-gmail-user").
  1300. SetPasswordHash("hash").
  1301. SetRole(service.RoleUser).
  1302. SetStatus(service.StatusActive).
  1303. Save(ctx)
  1304. require.NoError(t, err)
  1305. session, err := client.PendingAuthSession.Create().
  1306. SetSessionToken("suffix-whitelist-session-token").
  1307. SetIntent("login").
  1308. SetProviderType("oidc").
  1309. SetProviderKey("https://issuer.example").
  1310. SetProviderSubject("oidc-suffix-whitelist-123").
  1311. SetBrowserSessionKey("suffix-whitelist-browser-session-key").
  1312. SetUpstreamIdentityClaims(map[string]any{
  1313. "username": "oidc_user",
  1314. }).
  1315. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  1316. Save(ctx)
  1317. require.NoError(t, err)
  1318. body := bytes.NewBufferString(`{"email":"foo@gmail.com","verify_code":"135790","password":"secret-123"}`)
  1319. recorder := httptest.NewRecorder()
  1320. ginCtx, _ := gin.CreateTestContext(recorder)
  1321. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
  1322. req.Header.Set("Content-Type", "application/json")
  1323. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  1324. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("suffix-whitelist-browser-session-key")})
  1325. ginCtx.Request = req
  1326. handler.CreateOIDCOAuthAccount(ginCtx)
  1327. require.Equal(t, http.StatusBadRequest, recorder.Code)
  1328. payload := decodeJSONBody(t, recorder)
  1329. require.Equal(t, "EMAIL_DOMAIN_REGISTRATION_LIMIT", payload["reason"])
  1330. count, err := client.User.Query().Where(dbuser.EmailEQ("foo@gmail.com")).Count(ctx)
  1331. require.NoError(t, err)
  1332. require.Zero(t, count)
  1333. }
  1334. // 域名限量注册开关默认关闭:白名单外域名保持 PR5423 之前的严格拒绝语义,
  1335. // 即使该域名下还没有任何账户也不放行。
  1336. func TestCreateOIDCOAuthAccountRejectsEmailOutsideWhitelistWhenQuotaDisabled(t *testing.T) {
  1337. handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
  1338. emailVerifyEnabled: true,
  1339. emailCache: &oauthPendingFlowEmailCacheStub{
  1340. verificationCodes: map[string]*service.VerificationCodeData{
  1341. "foo@gmail.com": {
  1342. Code: "135790",
  1343. CreatedAt: time.Now().UTC(),
  1344. ExpiresAt: time.Now().UTC().Add(15 * time.Minute),
  1345. },
  1346. },
  1347. },
  1348. settingValues: map[string]string{
  1349. service.SettingKeyRegistrationEmailSuffixWhitelist: `["@qq.com"]`,
  1350. },
  1351. })
  1352. ctx := context.Background()
  1353. session, err := client.PendingAuthSession.Create().
  1354. SetSessionToken("suffix-strict-session-token").
  1355. SetIntent("login").
  1356. SetProviderType("oidc").
  1357. SetProviderKey("https://issuer.example").
  1358. SetProviderSubject("oidc-suffix-strict-123").
  1359. SetBrowserSessionKey("suffix-strict-browser-session-key").
  1360. SetUpstreamIdentityClaims(map[string]any{
  1361. "username": "oidc_user",
  1362. }).
  1363. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  1364. Save(ctx)
  1365. require.NoError(t, err)
  1366. body := bytes.NewBufferString(`{"email":"foo@gmail.com","verify_code":"135790","password":"secret-123"}`)
  1367. recorder := httptest.NewRecorder()
  1368. ginCtx, _ := gin.CreateTestContext(recorder)
  1369. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
  1370. req.Header.Set("Content-Type", "application/json")
  1371. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  1372. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("suffix-strict-browser-session-key")})
  1373. ginCtx.Request = req
  1374. handler.CreateOIDCOAuthAccount(ginCtx)
  1375. require.Equal(t, http.StatusBadRequest, recorder.Code)
  1376. payload := decodeJSONBody(t, recorder)
  1377. require.Equal(t, "EMAIL_SUFFIX_NOT_ALLOWED", payload["reason"])
  1378. count, err := client.User.Query().Where(dbuser.EmailEQ("foo@gmail.com")).Count(ctx)
  1379. require.NoError(t, err)
  1380. require.Zero(t, count)
  1381. }
  1382. func TestSendPendingOAuthVerifyCodeExistingEmailReturnsBindLoginState(t *testing.T) {
  1383. handler, client := newOAuthPendingFlowTestHandlerWithEmailVerification(t, false, "owner@example.com", "135790")
  1384. ctx := context.Background()
  1385. existingUser, err := client.User.Create().
  1386. SetEmail("owner@example.com").
  1387. SetUsername("owner-user").
  1388. SetPasswordHash("hash").
  1389. SetRole(service.RoleUser).
  1390. SetStatus(service.StatusActive).
  1391. Save(ctx)
  1392. require.NoError(t, err)
  1393. session, err := client.PendingAuthSession.Create().
  1394. SetSessionToken("existing-email-send-code-session-token").
  1395. SetIntent("login").
  1396. SetProviderType("oidc").
  1397. SetProviderKey("https://issuer.example").
  1398. SetProviderSubject("oidc-existing-send-code-123").
  1399. SetBrowserSessionKey("existing-email-send-code-browser-session-key").
  1400. SetLocalFlowState(map[string]any{
  1401. oauthCompletionResponseKey: map[string]any{
  1402. "step": "email_required",
  1403. },
  1404. }).
  1405. SetRedirectTo("/dashboard").
  1406. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  1407. Save(ctx)
  1408. require.NoError(t, err)
  1409. body := bytes.NewBufferString(`{"email":"owner@example.com"}`)
  1410. recorder := httptest.NewRecorder()
  1411. ginCtx, _ := gin.CreateTestContext(recorder)
  1412. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/send-verify-code", body)
  1413. req.Header.Set("Content-Type", "application/json")
  1414. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  1415. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("existing-email-send-code-browser-session-key")})
  1416. ginCtx.Request = req
  1417. handler.SendPendingOAuthVerifyCode(ginCtx)
  1418. require.Equal(t, http.StatusOK, recorder.Code)
  1419. var payload map[string]any
  1420. require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &payload))
  1421. require.Equal(t, "pending_session", payload["auth_result"])
  1422. require.Equal(t, oauthPendingChoiceStep, payload["step"])
  1423. require.Equal(t, "owner@example.com", payload["email"])
  1424. storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
  1425. require.NoError(t, err)
  1426. require.Equal(t, oauthIntentLogin, storedSession.Intent)
  1427. require.NotNil(t, storedSession.TargetUserID)
  1428. require.Equal(t, existingUser.ID, *storedSession.TargetUserID)
  1429. require.Equal(t, "owner@example.com", storedSession.ResolvedEmail)
  1430. }
  1431. func TestCreateOIDCOAuthAccountBlocksBackendModeBeforeCreatingUser(t *testing.T) {
  1432. handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
  1433. emailVerifyEnabled: true,
  1434. emailCache: &oauthPendingFlowEmailCacheStub{
  1435. verificationCodes: map[string]*service.VerificationCodeData{
  1436. "fresh@example.com": {
  1437. Code: "246810",
  1438. CreatedAt: time.Now().UTC(),
  1439. ExpiresAt: time.Now().UTC().Add(15 * time.Minute),
  1440. },
  1441. },
  1442. },
  1443. settingValues: map[string]string{
  1444. service.SettingKeyBackendModeEnabled: "true",
  1445. },
  1446. })
  1447. ctx := context.Background()
  1448. session, err := client.PendingAuthSession.Create().
  1449. SetSessionToken("create-account-backend-mode-session-token").
  1450. SetIntent("login").
  1451. SetProviderType("oidc").
  1452. SetProviderKey("https://issuer.example").
  1453. SetProviderSubject("oidc-create-backend-mode-123").
  1454. SetBrowserSessionKey("create-account-backend-mode-browser-session-key").
  1455. SetUpstreamIdentityClaims(map[string]any{
  1456. "username": "oidc_user",
  1457. }).
  1458. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  1459. Save(ctx)
  1460. require.NoError(t, err)
  1461. body := bytes.NewBufferString(`{"email":"fresh@example.com","verify_code":"246810","password":"secret-123"}`)
  1462. recorder := httptest.NewRecorder()
  1463. ginCtx, _ := gin.CreateTestContext(recorder)
  1464. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
  1465. req.Header.Set("Content-Type", "application/json")
  1466. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  1467. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("create-account-backend-mode-browser-session-key")})
  1468. ginCtx.Request = req
  1469. handler.CreateOIDCOAuthAccount(ginCtx)
  1470. require.Equal(t, http.StatusForbidden, recorder.Code)
  1471. userCount, err := client.User.Query().Where(dbuser.EmailEQ("fresh@example.com")).Count(ctx)
  1472. require.NoError(t, err)
  1473. require.Zero(t, userCount)
  1474. storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
  1475. require.NoError(t, err)
  1476. require.Nil(t, storedSession.ConsumedAt)
  1477. }
  1478. func TestLogoutClearsPendingOAuthAndBindCookies(t *testing.T) {
  1479. handler, _ := newOAuthPendingFlowTestHandler(t, false)
  1480. recorder := httptest.NewRecorder()
  1481. ginCtx, _ := gin.CreateTestContext(recorder)
  1482. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/logout", bytes.NewBufferString(`{}`))
  1483. req.Header.Set("Content-Type", "application/json")
  1484. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue("pending-session-token")})
  1485. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("pending-browser-key")})
  1486. req.AddCookie(&http.Cookie{Name: oauthBindAccessTokenCookieName, Value: "bind-token"})
  1487. ginCtx.Request = req
  1488. handler.Logout(ginCtx)
  1489. require.Equal(t, http.StatusOK, recorder.Code)
  1490. require.Equal(t, -1, findCookie(recorder.Result().Cookies(), oauthPendingSessionCookieName).MaxAge)
  1491. require.Equal(t, -1, findCookie(recorder.Result().Cookies(), oauthPendingBrowserCookieName).MaxAge)
  1492. require.Equal(t, -1, findCookie(recorder.Result().Cookies(), oauthBindAccessTokenCookieName).MaxAge)
  1493. }
  1494. func TestCreateOIDCOAuthAccountRollsBackCreatedUserWhenBindingFails(t *testing.T) {
  1495. handler, client := newOAuthPendingFlowTestHandlerWithEmailVerification(t, true, "fresh@example.com", "246810")
  1496. ctx := context.Background()
  1497. conflictOwner, err := client.User.Create().
  1498. SetEmail("owner@example.com").
  1499. SetUsername("owner-user").
  1500. SetPasswordHash("hash").
  1501. SetRole(service.RoleUser).
  1502. SetStatus(service.StatusActive).
  1503. Save(ctx)
  1504. require.NoError(t, err)
  1505. _, err = client.AuthIdentity.Create().
  1506. SetUserID(conflictOwner.ID).
  1507. SetProviderType("oidc").
  1508. SetProviderKey("https://issuer.example").
  1509. SetProviderSubject("oidc-conflict-123").
  1510. SetMetadata(map[string]any{
  1511. "username": "owner-user",
  1512. }).
  1513. Save(ctx)
  1514. require.NoError(t, err)
  1515. invitation, err := client.RedeemCode.Create().
  1516. SetCode("INVITE123").
  1517. SetType(service.RedeemTypeInvitation).
  1518. SetStatus(service.StatusUnused).
  1519. SetValue(0).
  1520. Save(ctx)
  1521. require.NoError(t, err)
  1522. session, err := client.PendingAuthSession.Create().
  1523. SetSessionToken("create-account-conflict-session-token").
  1524. SetIntent("login").
  1525. SetProviderType("oidc").
  1526. SetProviderKey("https://issuer.example").
  1527. SetProviderSubject("oidc-conflict-123").
  1528. SetBrowserSessionKey("create-account-conflict-browser-session-key").
  1529. SetUpstreamIdentityClaims(map[string]any{
  1530. "username": "oidc_user",
  1531. }).
  1532. SetRedirectTo("/profile").
  1533. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  1534. Save(ctx)
  1535. require.NoError(t, err)
  1536. body := bytes.NewBufferString(`{"email":"fresh@example.com","verify_code":"246810","password":"secret-123","invitation_code":"INVITE123"}`)
  1537. recorder := httptest.NewRecorder()
  1538. ginCtx, _ := gin.CreateTestContext(recorder)
  1539. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
  1540. req.Header.Set("Content-Type", "application/json")
  1541. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  1542. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("create-account-conflict-browser-session-key")})
  1543. ginCtx.Request = req
  1544. handler.CreateOIDCOAuthAccount(ginCtx)
  1545. require.Equal(t, http.StatusConflict, recorder.Code)
  1546. userCount, err := client.User.Query().Where(dbuser.EmailEQ("fresh@example.com")).Count(ctx)
  1547. require.NoError(t, err)
  1548. require.Zero(t, userCount)
  1549. storedInvitation, err := client.RedeemCode.Get(ctx, invitation.ID)
  1550. require.NoError(t, err)
  1551. require.Equal(t, service.StatusUnused, storedInvitation.Status)
  1552. require.Nil(t, storedInvitation.UsedBy)
  1553. require.Nil(t, storedInvitation.UsedAt)
  1554. storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
  1555. require.NoError(t, err)
  1556. require.Nil(t, storedSession.ConsumedAt)
  1557. }
  1558. func TestCreateOIDCOAuthAccountRollsBackPostBindFailureBeforeIdentityCanCommit(t *testing.T) {
  1559. handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
  1560. emailVerifyEnabled: true,
  1561. emailCache: &oauthPendingFlowEmailCacheStub{
  1562. verificationCodes: map[string]*service.VerificationCodeData{
  1563. "fresh@example.com": {
  1564. Code: "246810",
  1565. CreatedAt: time.Now().UTC(),
  1566. ExpiresAt: time.Now().UTC().Add(15 * time.Minute),
  1567. },
  1568. },
  1569. },
  1570. userRepoOptions: oauthPendingFlowUserRepoOptions{
  1571. rejectDeleteWhileAuthIdentityExists: true,
  1572. },
  1573. })
  1574. ctx := context.Background()
  1575. session, err := client.PendingAuthSession.Create().
  1576. SetSessionToken("create-account-finalize-failure-session-token").
  1577. SetIntent("login").
  1578. SetProviderType("oidc").
  1579. SetProviderKey("https://issuer.example").
  1580. SetProviderSubject("oidc-finalize-failure-123").
  1581. SetBrowserSessionKey("create-account-finalize-failure-browser-session-key").
  1582. SetUpstreamIdentityClaims(map[string]any{
  1583. "username": "oidc_user",
  1584. }).
  1585. SetRedirectTo("/profile").
  1586. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  1587. Save(ctx)
  1588. require.NoError(t, err)
  1589. pendingOAuthCreateAccountPreCommitHook = func(context.Context, *dbent.PendingAuthSession) error {
  1590. return errors.New("forced post-bind failure")
  1591. }
  1592. t.Cleanup(func() {
  1593. pendingOAuthCreateAccountPreCommitHook = nil
  1594. })
  1595. body := bytes.NewBufferString(`{"email":"fresh@example.com","verify_code":"246810","password":"secret-123"}`)
  1596. recorder := httptest.NewRecorder()
  1597. ginCtx, _ := gin.CreateTestContext(recorder)
  1598. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
  1599. req.Header.Set("Content-Type", "application/json")
  1600. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  1601. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("create-account-finalize-failure-browser-session-key")})
  1602. ginCtx.Request = req
  1603. handler.CreateOIDCOAuthAccount(ginCtx)
  1604. require.Equal(t, http.StatusInternalServerError, recorder.Code)
  1605. userCount, err := client.User.Query().Where(dbuser.EmailEQ("fresh@example.com")).Count(ctx)
  1606. require.NoError(t, err)
  1607. require.Zero(t, userCount)
  1608. identityCount, err := client.AuthIdentity.Query().
  1609. Where(
  1610. authidentity.ProviderTypeEQ("oidc"),
  1611. authidentity.ProviderKeyEQ("https://issuer.example"),
  1612. authidentity.ProviderSubjectEQ("oidc-finalize-failure-123"),
  1613. ).
  1614. Count(ctx)
  1615. require.NoError(t, err)
  1616. require.Zero(t, identityCount)
  1617. storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
  1618. require.NoError(t, err)
  1619. require.Nil(t, storedSession.ConsumedAt)
  1620. }
  1621. func TestBindOIDCOAuthLoginBindsExistingUserAndConsumesSession(t *testing.T) {
  1622. handler, client := newOAuthPendingFlowTestHandler(t, false)
  1623. ctx := context.Background()
  1624. passwordHash, err := handler.authService.HashPassword("secret-123")
  1625. require.NoError(t, err)
  1626. existingUser, err := client.User.Create().
  1627. SetEmail("owner@example.com").
  1628. SetUsername("owner-user").
  1629. SetPasswordHash(passwordHash).
  1630. SetRole(service.RoleUser).
  1631. SetStatus(service.StatusActive).
  1632. Save(ctx)
  1633. require.NoError(t, err)
  1634. session, err := client.PendingAuthSession.Create().
  1635. SetSessionToken("bind-login-session-token").
  1636. SetIntent("adopt_existing_user_by_email").
  1637. SetProviderType("oidc").
  1638. SetProviderKey("https://issuer.example").
  1639. SetProviderSubject("oidc-bind-123").
  1640. SetTargetUserID(existingUser.ID).
  1641. SetResolvedEmail(existingUser.Email).
  1642. SetBrowserSessionKey("bind-login-browser-session-key").
  1643. SetUpstreamIdentityClaims(map[string]any{
  1644. "username": "oidc_user",
  1645. "suggested_display_name": "Bound OIDC User",
  1646. "suggested_avatar_url": "https://cdn.example/bound.png",
  1647. }).
  1648. SetRedirectTo("/profile").
  1649. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  1650. Save(ctx)
  1651. require.NoError(t, err)
  1652. body := bytes.NewBufferString(`{"email":"owner@example.com","password":"secret-123","adopt_display_name":false,"adopt_avatar":false}`)
  1653. recorder := httptest.NewRecorder()
  1654. ginCtx, _ := gin.CreateTestContext(recorder)
  1655. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/bind-login", body)
  1656. req.Header.Set("Content-Type", "application/json")
  1657. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  1658. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("bind-login-browser-session-key")})
  1659. ginCtx.Request = req
  1660. handler.BindOIDCOAuthLogin(ginCtx)
  1661. require.Equal(t, http.StatusOK, recorder.Code)
  1662. var payload map[string]any
  1663. require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &payload))
  1664. require.NotEmpty(t, payload["access_token"])
  1665. require.NotEmpty(t, payload["refresh_token"])
  1666. require.Equal(t, "Bearer", payload["token_type"])
  1667. identity, err := client.AuthIdentity.Query().
  1668. Where(
  1669. authidentity.ProviderTypeEQ("oidc"),
  1670. authidentity.ProviderKeyEQ("https://issuer.example"),
  1671. authidentity.ProviderSubjectEQ("oidc-bind-123"),
  1672. ).
  1673. Only(ctx)
  1674. require.NoError(t, err)
  1675. require.Equal(t, existingUser.ID, identity.UserID)
  1676. storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
  1677. require.NoError(t, err)
  1678. require.NotNil(t, storedSession.ConsumedAt)
  1679. }
  1680. func TestBindOIDCOAuthLoginBlocksBackendModeBeforeTokenIssue(t *testing.T) {
  1681. handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
  1682. settingValues: map[string]string{
  1683. service.SettingKeyBackendModeEnabled: "true",
  1684. },
  1685. })
  1686. ctx := context.Background()
  1687. passwordHash, err := handler.authService.HashPassword("secret-123")
  1688. require.NoError(t, err)
  1689. existingUser, err := client.User.Create().
  1690. SetEmail("owner@example.com").
  1691. SetUsername("owner-user").
  1692. SetPasswordHash(passwordHash).
  1693. SetRole(service.RoleUser).
  1694. SetStatus(service.StatusActive).
  1695. Save(ctx)
  1696. require.NoError(t, err)
  1697. session, err := client.PendingAuthSession.Create().
  1698. SetSessionToken("bind-login-backend-mode-session-token").
  1699. SetIntent("adopt_existing_user_by_email").
  1700. SetProviderType("oidc").
  1701. SetProviderKey("https://issuer.example").
  1702. SetProviderSubject("oidc-bind-backend-mode-123").
  1703. SetTargetUserID(existingUser.ID).
  1704. SetResolvedEmail(existingUser.Email).
  1705. SetBrowserSessionKey("bind-login-backend-mode-browser-session-key").
  1706. SetUpstreamIdentityClaims(map[string]any{
  1707. "username": "oidc_user",
  1708. }).
  1709. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  1710. Save(ctx)
  1711. require.NoError(t, err)
  1712. body := bytes.NewBufferString(`{"email":"owner@example.com","password":"secret-123"}`)
  1713. recorder := httptest.NewRecorder()
  1714. ginCtx, _ := gin.CreateTestContext(recorder)
  1715. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/bind-login", body)
  1716. req.Header.Set("Content-Type", "application/json")
  1717. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  1718. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("bind-login-backend-mode-browser-session-key")})
  1719. ginCtx.Request = req
  1720. handler.BindOIDCOAuthLogin(ginCtx)
  1721. require.Equal(t, http.StatusForbidden, recorder.Code)
  1722. identityCount, err := client.AuthIdentity.Query().
  1723. Where(
  1724. authidentity.ProviderTypeEQ("oidc"),
  1725. authidentity.ProviderKeyEQ("https://issuer.example"),
  1726. authidentity.ProviderSubjectEQ("oidc-bind-backend-mode-123"),
  1727. ).
  1728. Count(ctx)
  1729. require.NoError(t, err)
  1730. require.Zero(t, identityCount)
  1731. storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
  1732. require.NoError(t, err)
  1733. require.Nil(t, storedSession.ConsumedAt)
  1734. }
  1735. func TestBindOIDCOAuthLoginRejectsInvalidPasswordWithoutConsumingSession(t *testing.T) {
  1736. handler, client := newOAuthPendingFlowTestHandler(t, false)
  1737. ctx := context.Background()
  1738. passwordHash, err := handler.authService.HashPassword("secret-123")
  1739. require.NoError(t, err)
  1740. existingUser, err := client.User.Create().
  1741. SetEmail("owner@example.com").
  1742. SetUsername("owner-user").
  1743. SetPasswordHash(passwordHash).
  1744. SetRole(service.RoleUser).
  1745. SetStatus(service.StatusActive).
  1746. Save(ctx)
  1747. require.NoError(t, err)
  1748. session, err := client.PendingAuthSession.Create().
  1749. SetSessionToken("bind-login-invalid-password-session-token").
  1750. SetIntent("adopt_existing_user_by_email").
  1751. SetProviderType("oidc").
  1752. SetProviderKey("https://issuer.example").
  1753. SetProviderSubject("oidc-bind-invalid-123").
  1754. SetTargetUserID(existingUser.ID).
  1755. SetResolvedEmail(existingUser.Email).
  1756. SetBrowserSessionKey("bind-login-invalid-password-browser-session-key").
  1757. SetUpstreamIdentityClaims(map[string]any{
  1758. "username": "oidc_user",
  1759. "suggested_display_name": "Bound OIDC User",
  1760. "suggested_avatar_url": "https://cdn.example/bound.png",
  1761. }).
  1762. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  1763. Save(ctx)
  1764. require.NoError(t, err)
  1765. body := bytes.NewBufferString(`{"email":"owner@example.com","password":"wrong-password"}`)
  1766. recorder := httptest.NewRecorder()
  1767. ginCtx, _ := gin.CreateTestContext(recorder)
  1768. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/bind-login", body)
  1769. req.Header.Set("Content-Type", "application/json")
  1770. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  1771. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("bind-login-invalid-password-browser-session-key")})
  1772. ginCtx.Request = req
  1773. handler.BindOIDCOAuthLogin(ginCtx)
  1774. require.Equal(t, http.StatusUnauthorized, recorder.Code)
  1775. payload := decodeJSONBody(t, recorder)
  1776. require.Equal(t, "INVALID_CREDENTIALS", payload["reason"])
  1777. identityCount, err := client.AuthIdentity.Query().
  1778. Where(
  1779. authidentity.ProviderTypeEQ("oidc"),
  1780. authidentity.ProviderKeyEQ("https://issuer.example"),
  1781. authidentity.ProviderSubjectEQ("oidc-bind-invalid-123"),
  1782. ).
  1783. Count(ctx)
  1784. require.NoError(t, err)
  1785. require.Zero(t, identityCount)
  1786. storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
  1787. require.NoError(t, err)
  1788. require.Nil(t, storedSession.ConsumedAt)
  1789. }
  1790. func TestBindOIDCOAuthLoginReclaimsIdentityOwnedBySoftDeletedUser(t *testing.T) {
  1791. handler, client := newOAuthPendingFlowTestHandler(t, false)
  1792. ctx := context.Background()
  1793. oldOwnerHash, err := handler.authService.HashPassword("old-secret")
  1794. require.NoError(t, err)
  1795. oldOwner, err := client.User.Create().
  1796. SetEmail("old-owner@example.com").
  1797. SetUsername("old-owner").
  1798. SetPasswordHash(oldOwnerHash).
  1799. SetRole(service.RoleUser).
  1800. SetStatus(service.StatusActive).
  1801. Save(ctx)
  1802. require.NoError(t, err)
  1803. identity, err := client.AuthIdentity.Create().
  1804. SetUserID(oldOwner.ID).
  1805. SetProviderType("oidc").
  1806. SetProviderKey("https://issuer.example").
  1807. SetProviderSubject("oidc-bind-soft-deleted-123").
  1808. SetMetadata(map[string]any{"username": "old-owner"}).
  1809. Save(ctx)
  1810. require.NoError(t, err)
  1811. _, err = client.User.Delete().Where(dbuser.IDEQ(oldOwner.ID)).Exec(ctx)
  1812. require.NoError(t, err)
  1813. newOwnerHash, err := handler.authService.HashPassword("secret-123")
  1814. require.NoError(t, err)
  1815. newOwner, err := client.User.Create().
  1816. SetEmail("owner@example.com").
  1817. SetUsername("owner-user").
  1818. SetPasswordHash(newOwnerHash).
  1819. SetRole(service.RoleUser).
  1820. SetStatus(service.StatusActive).
  1821. Save(ctx)
  1822. require.NoError(t, err)
  1823. session, err := client.PendingAuthSession.Create().
  1824. SetSessionToken("bind-login-soft-deleted-owner-session-token").
  1825. SetIntent("adopt_existing_user_by_email").
  1826. SetProviderType("oidc").
  1827. SetProviderKey("https://issuer.example").
  1828. SetProviderSubject("oidc-bind-soft-deleted-123").
  1829. SetTargetUserID(newOwner.ID).
  1830. SetResolvedEmail(newOwner.Email).
  1831. SetBrowserSessionKey("bind-login-soft-deleted-owner-browser-session-key").
  1832. SetUpstreamIdentityClaims(map[string]any{
  1833. "username": "oidc_user",
  1834. "suggested_display_name": "Recovered OIDC User",
  1835. }).
  1836. SetRedirectTo("/profile").
  1837. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  1838. Save(ctx)
  1839. require.NoError(t, err)
  1840. body := bytes.NewBufferString(`{"email":"owner@example.com","password":"secret-123","adopt_display_name":false,"adopt_avatar":false}`)
  1841. recorder := httptest.NewRecorder()
  1842. ginCtx, _ := gin.CreateTestContext(recorder)
  1843. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/bind-login", body)
  1844. req.Header.Set("Content-Type", "application/json")
  1845. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  1846. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("bind-login-soft-deleted-owner-browser-session-key")})
  1847. ginCtx.Request = req
  1848. handler.BindOIDCOAuthLogin(ginCtx)
  1849. require.Equal(t, http.StatusOK, recorder.Code)
  1850. identity, err = client.AuthIdentity.Get(ctx, identity.ID)
  1851. require.NoError(t, err)
  1852. require.Equal(t, newOwner.ID, identity.UserID)
  1853. }
  1854. func TestBindOIDCOAuthLoginAppliesFirstBindGrantOnce(t *testing.T) {
  1855. defaultSubAssigner := &oauthPendingFlowDefaultSubAssignerStub{}
  1856. handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
  1857. settingValues: map[string]string{
  1858. service.SettingKeyAuthSourceDefaultOIDCBalance: "12.5",
  1859. service.SettingKeyAuthSourceDefaultOIDCConcurrency: "3",
  1860. service.SettingKeyAuthSourceDefaultOIDCSubscriptions: `[{"group_id":101,"validity_days":30}]`,
  1861. service.SettingKeyAuthSourceDefaultOIDCGrantOnFirstBind: "true",
  1862. },
  1863. defaultSubAssigner: defaultSubAssigner,
  1864. })
  1865. ctx := context.Background()
  1866. passwordHash, err := handler.authService.HashPassword("secret-123")
  1867. require.NoError(t, err)
  1868. existingUser, err := client.User.Create().
  1869. SetEmail("owner@example.com").
  1870. SetUsername("owner-user").
  1871. SetPasswordHash(passwordHash).
  1872. SetBalance(5).
  1873. SetConcurrency(2).
  1874. SetRole(service.RoleUser).
  1875. SetStatus(service.StatusActive).
  1876. Save(ctx)
  1877. require.NoError(t, err)
  1878. firstSession, err := client.PendingAuthSession.Create().
  1879. SetSessionToken("first-bind-session-token").
  1880. SetIntent("adopt_existing_user_by_email").
  1881. SetProviderType("oidc").
  1882. SetProviderKey("https://issuer.example").
  1883. SetProviderSubject("oidc-bind-first-123").
  1884. SetTargetUserID(existingUser.ID).
  1885. SetResolvedEmail(existingUser.Email).
  1886. SetBrowserSessionKey("first-bind-browser-session-key").
  1887. SetUpstreamIdentityClaims(map[string]any{
  1888. "suggested_display_name": "Bound OIDC User",
  1889. "suggested_avatar_url": "https://cdn.example/bound.png",
  1890. }).
  1891. SetRedirectTo("/profile").
  1892. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  1893. Save(ctx)
  1894. require.NoError(t, err)
  1895. firstBody := bytes.NewBufferString(`{"email":"owner@example.com","password":"secret-123","adopt_display_name":false,"adopt_avatar":false}`)
  1896. firstRecorder := httptest.NewRecorder()
  1897. firstGinCtx, _ := gin.CreateTestContext(firstRecorder)
  1898. firstReq := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/bind-login", firstBody)
  1899. firstReq.Header.Set("Content-Type", "application/json")
  1900. firstReq.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(firstSession.SessionToken)})
  1901. firstReq.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("first-bind-browser-session-key")})
  1902. firstGinCtx.Request = firstReq
  1903. handler.BindOIDCOAuthLogin(firstGinCtx)
  1904. require.Equal(t, http.StatusOK, firstRecorder.Code)
  1905. storedUser, err := client.User.Get(ctx, existingUser.ID)
  1906. require.NoError(t, err)
  1907. require.Equal(t, 17.5, storedUser.Balance)
  1908. require.Equal(t, 5, storedUser.Concurrency)
  1909. require.Zero(t, storedUser.TotalRecharged)
  1910. require.Len(t, defaultSubAssigner.calls, 1)
  1911. require.Equal(t, int64(existingUser.ID), defaultSubAssigner.calls[0].UserID)
  1912. require.Equal(t, int64(101), defaultSubAssigner.calls[0].GroupID)
  1913. require.Equal(t, 30, defaultSubAssigner.calls[0].ValidityDays)
  1914. require.Equal(t, 1, countProviderGrantRecords(t, client, existingUser.ID, "oidc", "first_bind"))
  1915. secondSession, err := client.PendingAuthSession.Create().
  1916. SetSessionToken("second-bind-session-token").
  1917. SetIntent("adopt_existing_user_by_email").
  1918. SetProviderType("oidc").
  1919. SetProviderKey("https://issuer.example").
  1920. SetProviderSubject("oidc-bind-second-456").
  1921. SetTargetUserID(existingUser.ID).
  1922. SetResolvedEmail(existingUser.Email).
  1923. SetBrowserSessionKey("second-bind-browser-session-key").
  1924. SetUpstreamIdentityClaims(map[string]any{
  1925. "suggested_display_name": "Second OIDC User",
  1926. "suggested_avatar_url": "https://cdn.example/second.png",
  1927. }).
  1928. SetRedirectTo("/profile").
  1929. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  1930. Save(ctx)
  1931. require.NoError(t, err)
  1932. secondBody := bytes.NewBufferString(`{"email":"owner@example.com","password":"secret-123","adopt_display_name":false,"adopt_avatar":false}`)
  1933. secondRecorder := httptest.NewRecorder()
  1934. secondGinCtx, _ := gin.CreateTestContext(secondRecorder)
  1935. secondReq := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/bind-login", secondBody)
  1936. secondReq.Header.Set("Content-Type", "application/json")
  1937. secondReq.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(secondSession.SessionToken)})
  1938. secondReq.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("second-bind-browser-session-key")})
  1939. secondGinCtx.Request = secondReq
  1940. handler.BindOIDCOAuthLogin(secondGinCtx)
  1941. require.Equal(t, http.StatusOK, secondRecorder.Code)
  1942. storedUser, err = client.User.Get(ctx, existingUser.ID)
  1943. require.NoError(t, err)
  1944. require.Equal(t, 17.5, storedUser.Balance)
  1945. require.Equal(t, 5, storedUser.Concurrency)
  1946. require.Zero(t, storedUser.TotalRecharged)
  1947. require.Len(t, defaultSubAssigner.calls, 1)
  1948. require.Equal(t, 1, countProviderGrantRecords(t, client, existingUser.ID, "oidc", "first_bind"))
  1949. }
  1950. func TestResolvePendingOAuthTargetUserIDNormalizesLegacySpacingAndCase(t *testing.T) {
  1951. handler, client := newOAuthPendingFlowTestHandler(t, false)
  1952. _ = handler
  1953. ctx := context.Background()
  1954. existingUser, err := client.User.Create().
  1955. SetEmail(" Owner@Example.com ").
  1956. SetUsername("owner-user").
  1957. SetPasswordHash("hash").
  1958. SetRole(service.RoleUser).
  1959. SetStatus(service.StatusActive).
  1960. Save(ctx)
  1961. require.NoError(t, err)
  1962. session, err := client.PendingAuthSession.Create().
  1963. SetSessionToken("resolve-target-session-token").
  1964. SetIntent("login").
  1965. SetProviderType("oidc").
  1966. SetProviderKey("https://issuer.example").
  1967. SetProviderSubject("oidc-target-123").
  1968. SetResolvedEmail("owner@example.com").
  1969. SetBrowserSessionKey("resolve-target-browser-session-key").
  1970. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  1971. Save(ctx)
  1972. require.NoError(t, err)
  1973. resolvedUserID, err := resolvePendingOAuthTargetUserID(ctx, client, session)
  1974. require.NoError(t, err)
  1975. require.Equal(t, existingUser.ID, resolvedUserID)
  1976. }
  1977. func TestBindOIDCOAuthLoginReturns2FAChallengeWhenUserHasTotp(t *testing.T) {
  1978. totpCache := &oauthPendingFlowTotpCacheStub{}
  1979. handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
  1980. settingValues: map[string]string{
  1981. service.SettingKeyTotpEnabled: "true",
  1982. },
  1983. totpCache: totpCache,
  1984. totpEncryptor: oauthPendingFlowTotpEncryptorStub{},
  1985. })
  1986. ctx := context.Background()
  1987. passwordHash, err := handler.authService.HashPassword("secret-123")
  1988. require.NoError(t, err)
  1989. totpEnabledAt := time.Now().UTC().Add(-time.Hour)
  1990. secret := "JBSWY3DPEHPK3PXP"
  1991. existingUser, err := client.User.Create().
  1992. SetEmail("owner@example.com").
  1993. SetUsername("owner-user").
  1994. SetPasswordHash(passwordHash).
  1995. SetRole(service.RoleUser).
  1996. SetStatus(service.StatusActive).
  1997. SetTotpEnabled(true).
  1998. SetTotpSecretEncrypted(secret).
  1999. SetTotpEnabledAt(totpEnabledAt).
  2000. Save(ctx)
  2001. require.NoError(t, err)
  2002. session, err := client.PendingAuthSession.Create().
  2003. SetSessionToken("bind-login-2fa-session-token").
  2004. SetIntent("adopt_existing_user_by_email").
  2005. SetProviderType("oidc").
  2006. SetProviderKey("https://issuer.example").
  2007. SetProviderSubject("oidc-bind-2fa-123").
  2008. SetTargetUserID(existingUser.ID).
  2009. SetResolvedEmail(existingUser.Email).
  2010. SetBrowserSessionKey("bind-login-2fa-browser-session-key").
  2011. SetUpstreamIdentityClaims(map[string]any{
  2012. "suggested_display_name": "Bound OIDC User",
  2013. "suggested_avatar_url": "https://cdn.example/bound.png",
  2014. }).
  2015. SetRedirectTo("/profile").
  2016. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  2017. Save(ctx)
  2018. require.NoError(t, err)
  2019. body := bytes.NewBufferString(`{"email":"owner@example.com","password":"secret-123","adopt_display_name":false,"adopt_avatar":false}`)
  2020. recorder := httptest.NewRecorder()
  2021. ginCtx, _ := gin.CreateTestContext(recorder)
  2022. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/bind-login", body)
  2023. req.Header.Set("Content-Type", "application/json")
  2024. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  2025. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("bind-login-2fa-browser-session-key")})
  2026. ginCtx.Request = req
  2027. handler.BindOIDCOAuthLogin(ginCtx)
  2028. require.Equal(t, http.StatusOK, recorder.Code)
  2029. data := decodeJSONResponseData(t, recorder)
  2030. require.Equal(t, true, data["requires_2fa"])
  2031. require.Equal(t, "o***r@example.com", data["user_email_masked"])
  2032. tempToken, ok := data["temp_token"].(string)
  2033. require.True(t, ok)
  2034. require.NotEmpty(t, tempToken)
  2035. loginSession, err := totpCache.GetLoginSession(ctx, tempToken)
  2036. require.NoError(t, err)
  2037. require.NotNil(t, loginSession)
  2038. require.NotNil(t, loginSession.PendingOAuthBind)
  2039. require.Equal(t, session.SessionToken, loginSession.PendingOAuthBind.PendingSessionToken)
  2040. require.Equal(t, session.BrowserSessionKey, loginSession.PendingOAuthBind.BrowserSessionKey)
  2041. identityCount, err := client.AuthIdentity.Query().
  2042. Where(
  2043. authidentity.ProviderTypeEQ("oidc"),
  2044. authidentity.ProviderKeyEQ("https://issuer.example"),
  2045. authidentity.ProviderSubjectEQ("oidc-bind-2fa-123"),
  2046. ).
  2047. Count(ctx)
  2048. require.NoError(t, err)
  2049. require.Zero(t, identityCount)
  2050. storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
  2051. require.NoError(t, err)
  2052. require.Nil(t, storedSession.ConsumedAt)
  2053. }
  2054. func TestLogin2FACompletesPendingOAuthBindAndConsumesSession(t *testing.T) {
  2055. totpCache := &oauthPendingFlowTotpCacheStub{}
  2056. defaultSubAssigner := &oauthPendingFlowDefaultSubAssignerStub{}
  2057. handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
  2058. settingValues: map[string]string{
  2059. service.SettingKeyTotpEnabled: "true",
  2060. service.SettingKeyAuthSourceDefaultOIDCBalance: "8",
  2061. service.SettingKeyAuthSourceDefaultOIDCConcurrency: "2",
  2062. service.SettingKeyAuthSourceDefaultOIDCGrantOnFirstBind: "true",
  2063. },
  2064. defaultSubAssigner: defaultSubAssigner,
  2065. totpCache: totpCache,
  2066. totpEncryptor: oauthPendingFlowTotpEncryptorStub{},
  2067. })
  2068. ctx := context.Background()
  2069. passwordHash, err := handler.authService.HashPassword("secret-123")
  2070. require.NoError(t, err)
  2071. totpEnabledAt := time.Now().UTC().Add(-time.Hour)
  2072. secret := "JBSWY3DPEHPK3PXP"
  2073. existingUser, err := client.User.Create().
  2074. SetEmail("owner@example.com").
  2075. SetUsername("owner-user").
  2076. SetPasswordHash(passwordHash).
  2077. SetBalance(1.5).
  2078. SetConcurrency(4).
  2079. SetRole(service.RoleUser).
  2080. SetStatus(service.StatusActive).
  2081. SetTotpEnabled(true).
  2082. SetTotpSecretEncrypted(secret).
  2083. SetTotpEnabledAt(totpEnabledAt).
  2084. Save(ctx)
  2085. require.NoError(t, err)
  2086. session, err := client.PendingAuthSession.Create().
  2087. SetSessionToken("login-2fa-pending-session-token").
  2088. SetIntent("adopt_existing_user_by_email").
  2089. SetProviderType("oidc").
  2090. SetProviderKey("https://issuer.example").
  2091. SetProviderSubject("oidc-login-2fa-123").
  2092. SetTargetUserID(existingUser.ID).
  2093. SetResolvedEmail(existingUser.Email).
  2094. SetBrowserSessionKey("login-2fa-browser-session-key").
  2095. SetUpstreamIdentityClaims(map[string]any{
  2096. "suggested_display_name": "Bound OIDC User",
  2097. "suggested_avatar_url": "https://cdn.example/bound.png",
  2098. }).
  2099. SetRedirectTo("/profile").
  2100. SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
  2101. Save(ctx)
  2102. require.NoError(t, err)
  2103. _, err = client.IdentityAdoptionDecision.Create().
  2104. SetPendingAuthSessionID(session.ID).
  2105. SetAdoptDisplayName(false).
  2106. SetAdoptAvatar(false).
  2107. Save(ctx)
  2108. require.NoError(t, err)
  2109. tempToken, err := handler.totpService.CreatePendingOAuthBindLoginSession(
  2110. ctx,
  2111. existingUser.ID,
  2112. existingUser.Email,
  2113. session.SessionToken,
  2114. session.BrowserSessionKey,
  2115. )
  2116. require.NoError(t, err)
  2117. code, err := totp.GenerateCode(secret, time.Now().UTC())
  2118. require.NoError(t, err)
  2119. body := bytes.NewBufferString(`{"temp_token":"` + tempToken + `","totp_code":"` + code + `"}`)
  2120. recorder := httptest.NewRecorder()
  2121. ginCtx, _ := gin.CreateTestContext(recorder)
  2122. req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login/2fa", body)
  2123. req.Header.Set("Content-Type", "application/json")
  2124. req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
  2125. req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue(session.BrowserSessionKey)})
  2126. ginCtx.Request = req
  2127. handler.Login2FA(ginCtx)
  2128. require.Equal(t, http.StatusOK, recorder.Code)
  2129. payload := decodeJSONResponseData(t, recorder)
  2130. require.NotEmpty(t, payload["access_token"])
  2131. require.NotEmpty(t, payload["refresh_token"])
  2132. accessToken, ok := payload["access_token"].(string)
  2133. require.True(t, ok)
  2134. claims, err := handler.authService.ValidateToken(accessToken)
  2135. require.NoError(t, err)
  2136. reloadedUser, err := handler.userService.GetByID(ctx, existingUser.ID)
  2137. require.NoError(t, err)
  2138. require.Equal(t, reloadedUser.TokenVersion, claims.TokenVersion)
  2139. identity, err := client.AuthIdentity.Query().
  2140. Where(
  2141. authidentity.ProviderTypeEQ("oidc"),
  2142. authidentity.ProviderKeyEQ("https://issuer.example"),
  2143. authidentity.ProviderSubjectEQ("oidc-login-2fa-123"),
  2144. ).
  2145. Only(ctx)
  2146. require.NoError(t, err)
  2147. require.Equal(t, existingUser.ID, identity.UserID)
  2148. storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
  2149. require.NoError(t, err)
  2150. require.NotNil(t, storedSession.ConsumedAt)
  2151. loginSession, err := totpCache.GetLoginSession(ctx, tempToken)
  2152. require.NoError(t, err)
  2153. require.Nil(t, loginSession)
  2154. storedUser, err := client.User.Get(ctx, existingUser.ID)
  2155. require.NoError(t, err)
  2156. require.Equal(t, 9.5, storedUser.Balance)
  2157. require.Equal(t, 6, storedUser.Concurrency)
  2158. require.Equal(t, 1, countProviderGrantRecords(t, client, existingUser.ID, "oidc", "first_bind"))
  2159. require.Empty(t, defaultSubAssigner.calls)
  2160. }
  2161. func newOAuthPendingFlowTestHandler(t *testing.T, invitationEnabled bool) (*AuthHandler, *dbent.Client) {
  2162. t.Helper()
  2163. return newOAuthPendingFlowTestHandlerWithOptions(t, invitationEnabled, false, nil)
  2164. }
  2165. func newOAuthPendingFlowTestHandlerWithEmailVerification(
  2166. t *testing.T,
  2167. invitationEnabled bool,
  2168. email string,
  2169. code string,
  2170. ) (*AuthHandler, *dbent.Client) {
  2171. t.Helper()
  2172. cache := &oauthPendingFlowEmailCacheStub{
  2173. verificationCodes: map[string]*service.VerificationCodeData{
  2174. email: {
  2175. Code: code,
  2176. Attempts: 0,
  2177. CreatedAt: time.Now().UTC(),
  2178. ExpiresAt: time.Now().UTC().Add(15 * time.Minute),
  2179. },
  2180. },
  2181. }
  2182. return newOAuthPendingFlowTestHandlerWithOptions(t, invitationEnabled, true, cache)
  2183. }
  2184. func newOAuthPendingFlowTestHandlerWithOptions(
  2185. t *testing.T,
  2186. invitationEnabled bool,
  2187. emailVerifyEnabled bool,
  2188. emailCache service.EmailCache,
  2189. ) (*AuthHandler, *dbent.Client) {
  2190. return newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
  2191. invitationEnabled: invitationEnabled,
  2192. emailVerifyEnabled: emailVerifyEnabled,
  2193. emailCache: emailCache,
  2194. })
  2195. }
  2196. type oauthPendingFlowTestHandlerOptions struct {
  2197. invitationEnabled bool
  2198. emailVerifyEnabled bool
  2199. emailCache service.EmailCache
  2200. settingValues map[string]string
  2201. promoRepo service.PromoCodeRepository
  2202. defaultSubAssigner service.DefaultSubscriptionAssigner
  2203. affiliateService *service.AffiliateService
  2204. affiliateFactory func(*dbent.Client, *service.SettingService) *service.AffiliateService
  2205. totpCache service.TotpCache
  2206. totpEncryptor service.SecretEncryptor
  2207. userRepoOptions oauthPendingFlowUserRepoOptions
  2208. }
  2209. func newOAuthPendingFlowTestHandlerWithDependencies(
  2210. t *testing.T,
  2211. options oauthPendingFlowTestHandlerOptions,
  2212. ) (*AuthHandler, *dbent.Client) {
  2213. t.Helper()
  2214. db, err := sql.Open("sqlite", "file:auth_oauth_pending_flow_handler?mode=memory&cache=shared")
  2215. require.NoError(t, err)
  2216. t.Cleanup(func() { _ = db.Close() })
  2217. _, err = db.Exec("PRAGMA foreign_keys = ON")
  2218. require.NoError(t, err)
  2219. _, err = db.Exec(`
  2220. CREATE TABLE IF NOT EXISTS user_provider_default_grants (
  2221. id INTEGER PRIMARY KEY AUTOINCREMENT,
  2222. user_id INTEGER NOT NULL,
  2223. provider_type TEXT NOT NULL,
  2224. grant_reason TEXT NOT NULL DEFAULT 'first_bind',
  2225. created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  2226. UNIQUE(user_id, provider_type, grant_reason)
  2227. )`)
  2228. require.NoError(t, err)
  2229. _, err = db.Exec(`
  2230. CREATE TABLE IF NOT EXISTS user_avatars (
  2231. user_id INTEGER PRIMARY KEY,
  2232. storage_provider TEXT NOT NULL,
  2233. storage_key TEXT NOT NULL DEFAULT '',
  2234. url TEXT NOT NULL,
  2235. content_type TEXT NOT NULL DEFAULT '',
  2236. byte_size INTEGER NOT NULL DEFAULT 0,
  2237. sha256 TEXT NOT NULL DEFAULT '',
  2238. updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
  2239. )`)
  2240. require.NoError(t, err)
  2241. _, err = db.Exec(`
  2242. CREATE TABLE IF NOT EXISTS user_affiliates (
  2243. user_id INTEGER PRIMARY KEY,
  2244. aff_code TEXT NOT NULL UNIQUE,
  2245. aff_code_custom BOOLEAN NOT NULL DEFAULT false,
  2246. aff_rebate_rate_percent REAL NULL,
  2247. inviter_id INTEGER NULL,
  2248. aff_count INTEGER NOT NULL DEFAULT 0,
  2249. aff_quota REAL NOT NULL DEFAULT 0,
  2250. aff_frozen_quota REAL NOT NULL DEFAULT 0,
  2251. aff_history_quota REAL NOT NULL DEFAULT 0,
  2252. created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  2253. updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
  2254. )`)
  2255. require.NoError(t, err)
  2256. drv := entsql.OpenDB(dialect.SQLite, db)
  2257. client := enttest.NewClient(t, enttest.WithOptions(dbent.Driver(drv)))
  2258. cfg := &config.Config{
  2259. JWT: config.JWTConfig{
  2260. Secret: "test-secret",
  2261. ExpireHour: 1,
  2262. AccessTokenExpireMinutes: 60,
  2263. RefreshTokenExpireDays: 7,
  2264. },
  2265. Default: config.DefaultConfig{
  2266. UserBalance: 0,
  2267. UserConcurrency: 1,
  2268. },
  2269. }
  2270. settingValues := map[string]string{
  2271. service.SettingKeyRegistrationEnabled: "true",
  2272. service.SettingKeyInvitationCodeEnabled: boolSettingValue(options.invitationEnabled),
  2273. service.SettingKeyEmailVerifyEnabled: boolSettingValue(options.emailVerifyEnabled),
  2274. service.SettingKeyRegistrationEmailSuffixWhitelist: "[]",
  2275. }
  2276. for key, value := range options.settingValues {
  2277. settingValues[key] = value
  2278. }
  2279. settingSvc := service.NewSettingService(&oauthPendingFlowSettingRepoStub{values: settingValues}, cfg)
  2280. affiliateService := options.affiliateService
  2281. if affiliateService == nil && options.affiliateFactory != nil {
  2282. affiliateService = options.affiliateFactory(client, settingSvc)
  2283. }
  2284. userRepo := &oauthPendingFlowUserRepo{
  2285. client: client,
  2286. options: options.userRepoOptions,
  2287. }
  2288. redeemRepo := &oauthPendingFlowRedeemCodeRepo{client: client}
  2289. var promoService *service.PromoService
  2290. if options.promoRepo != nil {
  2291. promoService = service.NewPromoService(options.promoRepo, userRepo, nil, client, nil)
  2292. }
  2293. var emailService *service.EmailService
  2294. if options.emailCache != nil {
  2295. emailService = service.NewEmailService(&oauthPendingFlowSettingRepoStub{
  2296. values: map[string]string{
  2297. service.SettingKeyEmailVerifyEnabled: boolSettingValue(options.emailVerifyEnabled),
  2298. },
  2299. }, options.emailCache)
  2300. }
  2301. authSvc := service.NewAuthService(
  2302. client,
  2303. userRepo,
  2304. redeemRepo,
  2305. &oauthPendingFlowRefreshTokenCacheStub{},
  2306. cfg,
  2307. settingSvc,
  2308. emailService,
  2309. nil,
  2310. nil,
  2311. promoService,
  2312. options.defaultSubAssigner,
  2313. affiliateService,
  2314. nil,
  2315. )
  2316. userSvc := service.NewUserService(userRepo, nil, nil, nil)
  2317. var totpSvc *service.TotpService
  2318. if options.totpCache != nil || options.totpEncryptor != nil {
  2319. totpCache := options.totpCache
  2320. if totpCache == nil {
  2321. totpCache = &oauthPendingFlowTotpCacheStub{}
  2322. }
  2323. totpEncryptor := options.totpEncryptor
  2324. if totpEncryptor == nil {
  2325. totpEncryptor = oauthPendingFlowTotpEncryptorStub{}
  2326. }
  2327. totpSvc = service.NewTotpService(userRepo, totpEncryptor, totpCache, settingSvc, nil, nil)
  2328. }
  2329. return &AuthHandler{
  2330. authService: authSvc,
  2331. userService: userSvc,
  2332. settingSvc: settingSvc,
  2333. promoService: promoService,
  2334. totpService: totpSvc,
  2335. }, client
  2336. }
  2337. func boolSettingValue(v bool) string {
  2338. if v {
  2339. return "true"
  2340. }
  2341. return "false"
  2342. }
  2343. func boolPtr(v bool) *bool {
  2344. return &v
  2345. }
  2346. type oauthPendingFlowSettingRepoStub struct {
  2347. values map[string]string
  2348. }
  2349. type oauthPendingFlowPromoRepoStub struct {
  2350. promo *service.PromoCode
  2351. applyCalls []string
  2352. usages []service.PromoCodeUsage
  2353. }
  2354. func newOAuthPendingFlowPromoRepoStub(code string, bonusAmount float64) *oauthPendingFlowPromoRepoStub {
  2355. return &oauthPendingFlowPromoRepoStub{
  2356. promo: &service.PromoCode{
  2357. ID: 1,
  2358. Code: code,
  2359. BonusAmount: bonusAmount,
  2360. Status: service.PromoCodeStatusActive,
  2361. },
  2362. }
  2363. }
  2364. func (r *oauthPendingFlowPromoRepoStub) Create(context.Context, *service.PromoCode) error {
  2365. panic("unexpected Create call")
  2366. }
  2367. func (r *oauthPendingFlowPromoRepoStub) GetByID(context.Context, int64) (*service.PromoCode, error) {
  2368. panic("unexpected GetByID call")
  2369. }
  2370. func (r *oauthPendingFlowPromoRepoStub) GetByCode(_ context.Context, code string) (*service.PromoCode, error) {
  2371. if r.promo == nil || !strings.EqualFold(strings.TrimSpace(code), r.promo.Code) {
  2372. return nil, service.ErrPromoCodeNotFound
  2373. }
  2374. clone := *r.promo
  2375. return &clone, nil
  2376. }
  2377. func (r *oauthPendingFlowPromoRepoStub) GetByCodeForUpdate(ctx context.Context, code string) (*service.PromoCode, error) {
  2378. promoCode, err := r.GetByCode(ctx, code)
  2379. if err != nil {
  2380. return nil, err
  2381. }
  2382. r.applyCalls = append(r.applyCalls, strings.TrimSpace(code))
  2383. return promoCode, nil
  2384. }
  2385. func (r *oauthPendingFlowPromoRepoStub) Update(context.Context, *service.PromoCode) error {
  2386. panic("unexpected Update call")
  2387. }
  2388. func (r *oauthPendingFlowPromoRepoStub) Delete(context.Context, int64) error {
  2389. panic("unexpected Delete call")
  2390. }
  2391. func (r *oauthPendingFlowPromoRepoStub) List(context.Context, pagination.PaginationParams) ([]service.PromoCode, *pagination.PaginationResult, error) {
  2392. panic("unexpected List call")
  2393. }
  2394. func (r *oauthPendingFlowPromoRepoStub) ListWithFilters(context.Context, pagination.PaginationParams, string, string) ([]service.PromoCode, *pagination.PaginationResult, error) {
  2395. panic("unexpected ListWithFilters call")
  2396. }
  2397. func (r *oauthPendingFlowPromoRepoStub) CreateUsage(_ context.Context, usage *service.PromoCodeUsage) error {
  2398. r.usages = append(r.usages, *usage)
  2399. return nil
  2400. }
  2401. func (r *oauthPendingFlowPromoRepoStub) GetUsageByPromoCodeAndUser(context.Context, int64, int64) (*service.PromoCodeUsage, error) {
  2402. return nil, nil
  2403. }
  2404. func (r *oauthPendingFlowPromoRepoStub) ListUsagesByPromoCode(context.Context, int64, pagination.PaginationParams) ([]service.PromoCodeUsage, *pagination.PaginationResult, error) {
  2405. panic("unexpected ListUsagesByPromoCode call")
  2406. }
  2407. func (r *oauthPendingFlowPromoRepoStub) IncrementUsedCount(context.Context, int64) error {
  2408. if r.promo != nil {
  2409. r.promo.UsedCount++
  2410. }
  2411. return nil
  2412. }
  2413. func (s *oauthPendingFlowSettingRepoStub) Get(context.Context, string) (*service.Setting, error) {
  2414. return nil, service.ErrSettingNotFound
  2415. }
  2416. func (s *oauthPendingFlowSettingRepoStub) GetValue(_ context.Context, key string) (string, error) {
  2417. value, ok := s.values[key]
  2418. if !ok {
  2419. return "", service.ErrSettingNotFound
  2420. }
  2421. return value, nil
  2422. }
  2423. func (s *oauthPendingFlowSettingRepoStub) Set(context.Context, string, string) error {
  2424. return nil
  2425. }
  2426. func (s *oauthPendingFlowSettingRepoStub) GetMultiple(_ context.Context, keys []string) (map[string]string, error) {
  2427. result := make(map[string]string, len(keys))
  2428. for _, key := range keys {
  2429. if value, ok := s.values[key]; ok {
  2430. result[key] = value
  2431. }
  2432. }
  2433. return result, nil
  2434. }
  2435. func (s *oauthPendingFlowSettingRepoStub) SetMultiple(context.Context, map[string]string) error {
  2436. return nil
  2437. }
  2438. func (s *oauthPendingFlowSettingRepoStub) GetAll(context.Context) (map[string]string, error) {
  2439. result := make(map[string]string, len(s.values))
  2440. for key, value := range s.values {
  2441. result[key] = value
  2442. }
  2443. return result, nil
  2444. }
  2445. func (s *oauthPendingFlowSettingRepoStub) Delete(context.Context, string) error {
  2446. return nil
  2447. }
  2448. type oauthPendingFlowRefreshTokenCacheStub struct{}
  2449. type oauthPendingFlowEmailCacheStub struct {
  2450. verificationCodes map[string]*service.VerificationCodeData
  2451. }
  2452. func (s *oauthPendingFlowEmailCacheStub) GetVerificationCode(_ context.Context, email string) (*service.VerificationCodeData, error) {
  2453. if s == nil || s.verificationCodes == nil {
  2454. return nil, nil
  2455. }
  2456. return s.verificationCodes[email], nil
  2457. }
  2458. func (s *oauthPendingFlowEmailCacheStub) SetVerificationCode(_ context.Context, email string, data *service.VerificationCodeData, _ time.Duration) error {
  2459. if s.verificationCodes == nil {
  2460. s.verificationCodes = map[string]*service.VerificationCodeData{}
  2461. }
  2462. s.verificationCodes[email] = data
  2463. return nil
  2464. }
  2465. func (s *oauthPendingFlowEmailCacheStub) DeleteVerificationCode(_ context.Context, email string) error {
  2466. delete(s.verificationCodes, email)
  2467. return nil
  2468. }
  2469. func (s *oauthPendingFlowEmailCacheStub) GetNotifyVerifyCode(context.Context, string) (*service.VerificationCodeData, error) {
  2470. return nil, nil
  2471. }
  2472. func (s *oauthPendingFlowEmailCacheStub) SetNotifyVerifyCode(context.Context, string, *service.VerificationCodeData, time.Duration) error {
  2473. return nil
  2474. }
  2475. func (s *oauthPendingFlowEmailCacheStub) DeleteNotifyVerifyCode(context.Context, string) error {
  2476. return nil
  2477. }
  2478. func (s *oauthPendingFlowEmailCacheStub) GetPasswordResetToken(context.Context, string) (*service.PasswordResetTokenData, error) {
  2479. return nil, nil
  2480. }
  2481. func (s *oauthPendingFlowEmailCacheStub) SetPasswordResetToken(context.Context, string, *service.PasswordResetTokenData, time.Duration) error {
  2482. return nil
  2483. }
  2484. func (s *oauthPendingFlowEmailCacheStub) DeletePasswordResetToken(context.Context, string) error {
  2485. return nil
  2486. }
  2487. func (s *oauthPendingFlowEmailCacheStub) IsPasswordResetEmailInCooldown(context.Context, string) bool {
  2488. return false
  2489. }
  2490. func (s *oauthPendingFlowEmailCacheStub) SetPasswordResetEmailCooldown(context.Context, string, time.Duration) error {
  2491. return nil
  2492. }
  2493. func (s *oauthPendingFlowEmailCacheStub) IncrNotifyCodeUserRate(context.Context, int64, time.Duration) (int64, error) {
  2494. return 0, nil
  2495. }
  2496. func (s *oauthPendingFlowEmailCacheStub) GetNotifyCodeUserRate(context.Context, int64) (int64, error) {
  2497. return 0, nil
  2498. }
  2499. func (s *oauthPendingFlowRefreshTokenCacheStub) StoreRefreshToken(context.Context, string, *service.RefreshTokenData, time.Duration) error {
  2500. return nil
  2501. }
  2502. func (s *oauthPendingFlowRefreshTokenCacheStub) GetRefreshToken(context.Context, string) (*service.RefreshTokenData, error) {
  2503. return nil, service.ErrRefreshTokenNotFound
  2504. }
  2505. func (s *oauthPendingFlowRefreshTokenCacheStub) DeleteRefreshToken(context.Context, string) error {
  2506. return nil
  2507. }
  2508. func (s *oauthPendingFlowRefreshTokenCacheStub) DeleteUserRefreshTokens(context.Context, int64) error {
  2509. return nil
  2510. }
  2511. func (s *oauthPendingFlowRefreshTokenCacheStub) DeleteTokenFamily(context.Context, string) error {
  2512. return nil
  2513. }
  2514. func (s *oauthPendingFlowRefreshTokenCacheStub) AddToUserTokenSet(context.Context, int64, string, time.Duration) error {
  2515. return nil
  2516. }
  2517. func (s *oauthPendingFlowRefreshTokenCacheStub) AddToFamilyTokenSet(context.Context, string, string, time.Duration) error {
  2518. return nil
  2519. }
  2520. func (s *oauthPendingFlowRefreshTokenCacheStub) GetUserTokenHashes(context.Context, int64) ([]string, error) {
  2521. return nil, nil
  2522. }
  2523. func (s *oauthPendingFlowRefreshTokenCacheStub) GetFamilyTokenHashes(context.Context, string) ([]string, error) {
  2524. return nil, nil
  2525. }
  2526. func (s *oauthPendingFlowRefreshTokenCacheStub) IsTokenInFamily(context.Context, string, string) (bool, error) {
  2527. return false, nil
  2528. }
  2529. type oauthPendingFlowRedeemCodeRepo struct {
  2530. client *dbent.Client
  2531. }
  2532. func (r *oauthPendingFlowRedeemCodeRepo) Create(context.Context, *service.RedeemCode) error {
  2533. panic("unexpected Create call")
  2534. }
  2535. func (r *oauthPendingFlowRedeemCodeRepo) CreateBatch(context.Context, []service.RedeemCode) error {
  2536. panic("unexpected CreateBatch call")
  2537. }
  2538. func (r *oauthPendingFlowRedeemCodeRepo) GetByID(context.Context, int64) (*service.RedeemCode, error) {
  2539. panic("unexpected GetByID call")
  2540. }
  2541. func (r *oauthPendingFlowRedeemCodeRepo) GetByCode(ctx context.Context, code string) (*service.RedeemCode, error) {
  2542. entity, err := r.client.RedeemCode.Query().Where(redeemcode.CodeEQ(code)).Only(ctx)
  2543. if err != nil {
  2544. if dbent.IsNotFound(err) {
  2545. return nil, service.ErrRedeemCodeNotFound
  2546. }
  2547. return nil, err
  2548. }
  2549. notes := ""
  2550. if entity.Notes != nil {
  2551. notes = *entity.Notes
  2552. }
  2553. return &service.RedeemCode{
  2554. ID: entity.ID,
  2555. Code: entity.Code,
  2556. Type: entity.Type,
  2557. Value: entity.Value,
  2558. Status: entity.Status,
  2559. UsedBy: entity.UsedBy,
  2560. UsedAt: entity.UsedAt,
  2561. Notes: notes,
  2562. CreatedAt: entity.CreatedAt,
  2563. GroupID: entity.GroupID,
  2564. ValidityDays: entity.ValidityDays,
  2565. }, nil
  2566. }
  2567. func (r *oauthPendingFlowRedeemCodeRepo) Update(ctx context.Context, code *service.RedeemCode) error {
  2568. if code == nil {
  2569. return nil
  2570. }
  2571. update := r.client.RedeemCode.UpdateOneID(code.ID).
  2572. SetCode(code.Code).
  2573. SetType(code.Type).
  2574. SetValue(code.Value).
  2575. SetStatus(code.Status).
  2576. SetNotes(code.Notes).
  2577. SetValidityDays(code.ValidityDays)
  2578. if code.UsedBy != nil {
  2579. update = update.SetUsedBy(*code.UsedBy)
  2580. } else {
  2581. update = update.ClearUsedBy()
  2582. }
  2583. if code.UsedAt != nil {
  2584. update = update.SetUsedAt(*code.UsedAt)
  2585. } else {
  2586. update = update.ClearUsedAt()
  2587. }
  2588. if code.GroupID != nil {
  2589. update = update.SetGroupID(*code.GroupID)
  2590. } else {
  2591. update = update.ClearGroupID()
  2592. }
  2593. _, err := update.Save(ctx)
  2594. return err
  2595. }
  2596. func (r *oauthPendingFlowRedeemCodeRepo) BatchUpdate(context.Context, []int64, service.RedeemCodeBatchUpdateFields) (int64, error) {
  2597. panic("unexpected BatchUpdate call")
  2598. }
  2599. func (r *oauthPendingFlowRedeemCodeRepo) Delete(context.Context, int64) error {
  2600. panic("unexpected Delete call")
  2601. }
  2602. func (r *oauthPendingFlowRedeemCodeRepo) Use(ctx context.Context, id, userID int64) error {
  2603. affected, err := r.client.RedeemCode.Update().
  2604. Where(redeemcode.IDEQ(id), redeemcode.StatusEQ(service.StatusUnused)).
  2605. SetStatus(service.StatusUsed).
  2606. SetUsedBy(userID).
  2607. SetUsedAt(time.Now().UTC()).
  2608. Save(ctx)
  2609. if err != nil {
  2610. return err
  2611. }
  2612. if affected == 0 {
  2613. return service.ErrRedeemCodeUsed
  2614. }
  2615. return nil
  2616. }
  2617. func (r *oauthPendingFlowRedeemCodeRepo) List(context.Context, pagination.PaginationParams) ([]service.RedeemCode, *pagination.PaginationResult, error) {
  2618. panic("unexpected List call")
  2619. }
  2620. func (r *oauthPendingFlowRedeemCodeRepo) ListWithFilters(context.Context, pagination.PaginationParams, string, string, string) ([]service.RedeemCode, *pagination.PaginationResult, error) {
  2621. panic("unexpected ListWithFilters call")
  2622. }
  2623. func (r *oauthPendingFlowRedeemCodeRepo) ListByUser(context.Context, int64, int) ([]service.RedeemCode, error) {
  2624. panic("unexpected ListByUser call")
  2625. }
  2626. func (r *oauthPendingFlowRedeemCodeRepo) ListByUserPaginated(context.Context, int64, pagination.PaginationParams, string) ([]service.RedeemCode, *pagination.PaginationResult, error) {
  2627. panic("unexpected ListByUserPaginated call")
  2628. }
  2629. func (r *oauthPendingFlowRedeemCodeRepo) SumPositiveBalanceByUser(context.Context, int64) (float64, error) {
  2630. panic("unexpected SumPositiveBalanceByUser call")
  2631. }
  2632. func decodeJSONResponseData(t *testing.T, recorder *httptest.ResponseRecorder) map[string]any {
  2633. t.Helper()
  2634. var envelope struct {
  2635. Data map[string]any `json:"data"`
  2636. }
  2637. require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &envelope))
  2638. return envelope.Data
  2639. }
  2640. func decodeJSONBody(t *testing.T, recorder *httptest.ResponseRecorder) map[string]any {
  2641. t.Helper()
  2642. var payload map[string]any
  2643. require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &payload))
  2644. return payload
  2645. }
  2646. type oauthPendingFlowAvatarRecord struct {
  2647. StorageProvider string
  2648. URL string
  2649. }
  2650. func loadUserAvatarRecord(t *testing.T, client *dbent.Client, userID int64) *oauthPendingFlowAvatarRecord {
  2651. t.Helper()
  2652. var rows entsql.Rows
  2653. err := client.Driver().Query(
  2654. context.Background(),
  2655. `SELECT storage_provider, url FROM user_avatars WHERE user_id = ?`,
  2656. []any{userID},
  2657. &rows,
  2658. )
  2659. require.NoError(t, err)
  2660. defer func() { _ = rows.Close() }()
  2661. if !rows.Next() {
  2662. require.NoError(t, rows.Err())
  2663. return nil
  2664. }
  2665. var record oauthPendingFlowAvatarRecord
  2666. require.NoError(t, rows.Scan(&record.StorageProvider, &record.URL))
  2667. require.NoError(t, rows.Err())
  2668. return &record
  2669. }
  2670. func countProviderGrantRecords(
  2671. t *testing.T,
  2672. client *dbent.Client,
  2673. userID int64,
  2674. providerType string,
  2675. grantReason string,
  2676. ) int {
  2677. t.Helper()
  2678. var rows entsql.Rows
  2679. err := client.Driver().Query(
  2680. context.Background(),
  2681. `SELECT COUNT(*) FROM user_provider_default_grants WHERE user_id = ? AND provider_type = ? AND grant_reason = ?`,
  2682. []any{userID, providerType, grantReason},
  2683. &rows,
  2684. )
  2685. require.NoError(t, err)
  2686. defer func() { _ = rows.Close() }()
  2687. require.True(t, rows.Next())
  2688. var count int
  2689. require.NoError(t, rows.Scan(&count))
  2690. require.False(t, rows.Next())
  2691. return count
  2692. }
  2693. type oauthPendingFlowUserRepo struct {
  2694. client *dbent.Client
  2695. options oauthPendingFlowUserRepoOptions
  2696. }
  2697. var _ service.RegistrationEmailDomainRepository = (*oauthPendingFlowUserRepo)(nil)
  2698. type oauthPendingFlowUserRepoOptions struct {
  2699. rejectDeleteWhileAuthIdentityExists bool
  2700. }
  2701. func (r *oauthPendingFlowUserRepo) Create(ctx context.Context, user *service.User) error {
  2702. entity, err := r.client.User.Create().
  2703. SetEmail(user.Email).
  2704. SetUsername(user.Username).
  2705. SetNotes(user.Notes).
  2706. SetPasswordHash(user.PasswordHash).
  2707. SetRole(user.Role).
  2708. SetBalance(user.Balance).
  2709. SetConcurrency(user.Concurrency).
  2710. SetStatus(user.Status).
  2711. SetNillableTotpSecretEncrypted(user.TotpSecretEncrypted).
  2712. SetTotpEnabled(user.TotpEnabled).
  2713. SetNillableTotpEnabledAt(user.TotpEnabledAt).
  2714. SetTotalRecharged(user.TotalRecharged).
  2715. SetSignupSource(user.SignupSource).
  2716. SetNillableLastLoginAt(user.LastLoginAt).
  2717. SetNillableLastActiveAt(user.LastActiveAt).
  2718. Save(ctx)
  2719. if err != nil {
  2720. return err
  2721. }
  2722. user.ID = entity.ID
  2723. user.CreatedAt = entity.CreatedAt
  2724. user.UpdatedAt = entity.UpdatedAt
  2725. return nil
  2726. }
  2727. func (r *oauthPendingFlowUserRepo) CreateWithEmailAliasGuard(ctx context.Context, user *service.User) error {
  2728. aliasExists, err := r.ExistsByEmailAlias(ctx, user.Email)
  2729. if err != nil {
  2730. return err
  2731. }
  2732. if aliasExists {
  2733. return service.ErrEmailExists
  2734. }
  2735. return r.Create(ctx, user)
  2736. }
  2737. func (r *oauthPendingFlowUserRepo) CountUsersByEmailDomain(ctx context.Context, domain string) (int, error) {
  2738. domain = service.NormalizeRegistrationEmailDomain(domain)
  2739. if domain == "" {
  2740. return 0, nil
  2741. }
  2742. emails, err := r.client.User.Query().Select(dbuser.FieldEmail).Strings(ctx)
  2743. if err != nil {
  2744. return 0, err
  2745. }
  2746. count := 0
  2747. for _, email := range emails {
  2748. if service.RegistrationEmailDomain(email) == domain {
  2749. count++
  2750. }
  2751. }
  2752. return count, nil
  2753. }
  2754. func (r *oauthPendingFlowUserRepo) CreateWithEmailAliasGuardAndDomainLimit(ctx context.Context, user *service.User, domain string) error {
  2755. count, err := r.CountUsersByEmailDomain(ctx, domain)
  2756. if err != nil {
  2757. return err
  2758. }
  2759. if count > 0 {
  2760. return service.ErrEmailDomainRegistrationLimit
  2761. }
  2762. return r.CreateWithEmailAliasGuard(ctx, user)
  2763. }
  2764. func (r *oauthPendingFlowUserRepo) GetByID(ctx context.Context, id int64) (*service.User, error) {
  2765. entity, err := r.client.User.Get(ctx, id)
  2766. if err != nil {
  2767. if dbent.IsNotFound(err) {
  2768. return nil, service.ErrUserNotFound
  2769. }
  2770. return nil, err
  2771. }
  2772. return oauthPendingFlowServiceUser(entity), nil
  2773. }
  2774. func (r *oauthPendingFlowUserRepo) GetByEmail(ctx context.Context, email string) (*service.User, error) {
  2775. entity, err := r.client.User.Query().Where(dbuser.EmailEQ(email)).Only(ctx)
  2776. if err != nil {
  2777. if dbent.IsNotFound(err) {
  2778. return nil, service.ErrUserNotFound
  2779. }
  2780. return nil, err
  2781. }
  2782. return oauthPendingFlowServiceUser(entity), nil
  2783. }
  2784. func (r *oauthPendingFlowUserRepo) GetFirstAdmin(context.Context) (*service.User, error) {
  2785. panic("unexpected GetFirstAdmin call")
  2786. }
  2787. func (r *oauthPendingFlowUserRepo) Update(ctx context.Context, user *service.User, fields service.UserUpdateFields) error {
  2788. entity, err := r.client.User.UpdateOneID(user.ID).
  2789. SetEmail(user.Email).
  2790. SetUsername(user.Username).
  2791. SetNotes(user.Notes).
  2792. SetPasswordHash(user.PasswordHash).
  2793. SetRole(user.Role).
  2794. SetBalance(user.Balance).
  2795. SetConcurrency(user.Concurrency).
  2796. SetStatus(user.Status).
  2797. SetNillableTotpSecretEncrypted(user.TotpSecretEncrypted).
  2798. SetTotpEnabled(user.TotpEnabled).
  2799. SetNillableTotpEnabledAt(user.TotpEnabledAt).
  2800. SetTotalRecharged(user.TotalRecharged).
  2801. SetSignupSource(user.SignupSource).
  2802. SetNillableLastLoginAt(user.LastLoginAt).
  2803. SetNillableLastActiveAt(user.LastActiveAt).
  2804. Save(ctx)
  2805. if err != nil {
  2806. return err
  2807. }
  2808. user.UpdatedAt = entity.UpdatedAt
  2809. return nil
  2810. }
  2811. func (r *oauthPendingFlowUserRepo) UpdateUserLastActiveAt(ctx context.Context, userID int64, activeAt time.Time) error {
  2812. return r.client.User.UpdateOneID(userID).SetLastActiveAt(activeAt).Exec(ctx)
  2813. }
  2814. func (r *oauthPendingFlowUserRepo) Delete(ctx context.Context, id int64) error {
  2815. if r.options.rejectDeleteWhileAuthIdentityExists {
  2816. count, err := r.client.AuthIdentity.Query().Where(authidentity.UserIDEQ(id)).Count(ctx)
  2817. if err != nil {
  2818. return err
  2819. }
  2820. if count > 0 {
  2821. return errors.New("cannot delete user while auth identities still exist")
  2822. }
  2823. }
  2824. return r.client.User.DeleteOneID(id).Exec(ctx)
  2825. }
  2826. func (r *oauthPendingFlowUserRepo) GetUserAvatar(ctx context.Context, userID int64) (*service.UserAvatar, error) {
  2827. driver := r.client.Driver()
  2828. if tx := dbent.TxFromContext(ctx); tx != nil {
  2829. driver = tx.Client().Driver()
  2830. }
  2831. var rows entsql.Rows
  2832. if err := driver.Query(
  2833. ctx,
  2834. `SELECT storage_provider, storage_key, url, content_type, byte_size, sha256 FROM user_avatars WHERE user_id = ?`,
  2835. []any{userID},
  2836. &rows,
  2837. ); err != nil {
  2838. return nil, err
  2839. }
  2840. defer func() { _ = rows.Close() }()
  2841. if !rows.Next() {
  2842. return nil, rows.Err()
  2843. }
  2844. var avatar service.UserAvatar
  2845. if err := rows.Scan(
  2846. &avatar.StorageProvider,
  2847. &avatar.StorageKey,
  2848. &avatar.URL,
  2849. &avatar.ContentType,
  2850. &avatar.ByteSize,
  2851. &avatar.SHA256,
  2852. ); err != nil {
  2853. return nil, err
  2854. }
  2855. if err := rows.Err(); err != nil {
  2856. return nil, err
  2857. }
  2858. return &avatar, nil
  2859. }
  2860. func (r *oauthPendingFlowUserRepo) UpsertUserAvatar(ctx context.Context, userID int64, input service.UpsertUserAvatarInput) (*service.UserAvatar, error) {
  2861. driver := r.client.Driver()
  2862. if tx := dbent.TxFromContext(ctx); tx != nil {
  2863. driver = tx.Client().Driver()
  2864. }
  2865. var result entsql.Result
  2866. if err := driver.Exec(
  2867. ctx,
  2868. `INSERT INTO user_avatars (user_id, storage_provider, storage_key, url, content_type, byte_size, sha256, updated_at)
  2869. VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
  2870. ON CONFLICT(user_id) DO UPDATE SET
  2871. storage_provider = excluded.storage_provider,
  2872. storage_key = excluded.storage_key,
  2873. url = excluded.url,
  2874. content_type = excluded.content_type,
  2875. byte_size = excluded.byte_size,
  2876. sha256 = excluded.sha256,
  2877. updated_at = CURRENT_TIMESTAMP`,
  2878. []any{
  2879. userID,
  2880. input.StorageProvider,
  2881. input.StorageKey,
  2882. input.URL,
  2883. input.ContentType,
  2884. input.ByteSize,
  2885. input.SHA256,
  2886. },
  2887. &result,
  2888. ); err != nil {
  2889. return nil, err
  2890. }
  2891. return &service.UserAvatar{
  2892. StorageProvider: input.StorageProvider,
  2893. StorageKey: input.StorageKey,
  2894. URL: input.URL,
  2895. ContentType: input.ContentType,
  2896. ByteSize: input.ByteSize,
  2897. SHA256: input.SHA256,
  2898. }, nil
  2899. }
  2900. func (r *oauthPendingFlowUserRepo) DeleteUserAvatar(ctx context.Context, userID int64) error {
  2901. driver := r.client.Driver()
  2902. if tx := dbent.TxFromContext(ctx); tx != nil {
  2903. driver = tx.Client().Driver()
  2904. }
  2905. var result entsql.Result
  2906. return driver.Exec(ctx, `DELETE FROM user_avatars WHERE user_id = ?`, []any{userID}, &result)
  2907. }
  2908. func (r *oauthPendingFlowUserRepo) List(context.Context, pagination.PaginationParams) ([]service.User, *pagination.PaginationResult, error) {
  2909. panic("unexpected List call")
  2910. }
  2911. func (r *oauthPendingFlowUserRepo) ListWithFilters(context.Context, pagination.PaginationParams, service.UserListFilters) ([]service.User, *pagination.PaginationResult, error) {
  2912. panic("unexpected ListWithFilters call")
  2913. }
  2914. func (r *oauthPendingFlowUserRepo) UpdateBalance(ctx context.Context, userID int64, amount float64) error {
  2915. client := r.client
  2916. if tx := dbent.TxFromContext(ctx); tx != nil {
  2917. client = tx.Client()
  2918. }
  2919. return client.User.UpdateOneID(userID).AddBalance(amount).Exec(ctx)
  2920. }
  2921. func (r *oauthPendingFlowUserRepo) DeductBalance(context.Context, int64, float64) error {
  2922. panic("unexpected DeductBalance call")
  2923. }
  2924. func (r *oauthPendingFlowUserRepo) AdjustBalance(ctx context.Context, id int64, delta float64) (service.BalanceChange, error) {
  2925. panic("unexpected AdjustBalance call")
  2926. }
  2927. func (r *oauthPendingFlowUserRepo) SetBalance(ctx context.Context, id int64, value float64) (service.BalanceChange, error) {
  2928. panic("unexpected SetBalance call")
  2929. }
  2930. func (r *oauthPendingFlowUserRepo) UpdateConcurrency(context.Context, int64, int) error {
  2931. panic("unexpected UpdateConcurrency call")
  2932. }
  2933. func (r *oauthPendingFlowUserRepo) BatchSetConcurrency(context.Context, []int64, int) (int, error) {
  2934. panic("unexpected BatchSetConcurrency call")
  2935. }
  2936. func (r *oauthPendingFlowUserRepo) BatchAddConcurrency(context.Context, []int64, int) (int, error) {
  2937. panic("unexpected BatchAddConcurrency call")
  2938. }
  2939. func (r *oauthPendingFlowUserRepo) BatchUpdateLimits(context.Context, []int64, *int, *int) (int, error) {
  2940. panic("unexpected BatchUpdateLimits call")
  2941. }
  2942. func (r *oauthPendingFlowUserRepo) GetLatestUsedAtByUserIDs(context.Context, []int64) (map[int64]*time.Time, error) {
  2943. return map[int64]*time.Time{}, nil
  2944. }
  2945. func (r *oauthPendingFlowUserRepo) GetLatestUsedAtByUserID(context.Context, int64) (*time.Time, error) {
  2946. return nil, nil
  2947. }
  2948. func (r *oauthPendingFlowUserRepo) ExistsByEmail(ctx context.Context, email string) (bool, error) {
  2949. count, err := r.client.User.Query().Where(dbuser.EmailEQ(email)).Count(ctx)
  2950. return count > 0, err
  2951. }
  2952. func (r *oauthPendingFlowUserRepo) ExistsByEmailAlias(ctx context.Context, email string) (bool, error) {
  2953. identity := service.NormalizeEmailForAliasDedup(email)
  2954. emails, err := r.client.User.Query().Select(dbuser.FieldEmail).Strings(ctx)
  2955. if err != nil {
  2956. return false, err
  2957. }
  2958. for _, stored := range emails {
  2959. if service.NormalizeEmailForAliasDedup(stored) == identity {
  2960. return true, nil
  2961. }
  2962. }
  2963. return false, nil
  2964. }
  2965. func (r *oauthPendingFlowUserRepo) RemoveGroupFromAllowedGroups(context.Context, int64) (int64, error) {
  2966. panic("unexpected RemoveGroupFromAllowedGroups call")
  2967. }
  2968. func (r *oauthPendingFlowUserRepo) AddGroupToAllowedGroups(context.Context, int64, int64) error {
  2969. panic("unexpected AddGroupToAllowedGroups call")
  2970. }
  2971. func (r *oauthPendingFlowUserRepo) RemoveGroupFromUserAllowedGroups(context.Context, int64, int64) error {
  2972. panic("unexpected RemoveGroupFromUserAllowedGroups call")
  2973. }
  2974. func (r *oauthPendingFlowUserRepo) ListUserAuthIdentities(ctx context.Context, userID int64) ([]service.UserAuthIdentityRecord, error) {
  2975. identities, err := r.client.AuthIdentity.Query().
  2976. Where(authidentity.UserIDEQ(userID)).
  2977. All(ctx)
  2978. if err != nil {
  2979. return nil, err
  2980. }
  2981. records := make([]service.UserAuthIdentityRecord, 0, len(identities))
  2982. for _, identity := range identities {
  2983. if identity == nil {
  2984. continue
  2985. }
  2986. records = append(records, service.UserAuthIdentityRecord{
  2987. ProviderType: identity.ProviderType,
  2988. ProviderKey: identity.ProviderKey,
  2989. ProviderSubject: identity.ProviderSubject,
  2990. VerifiedAt: identity.VerifiedAt,
  2991. Issuer: identity.Issuer,
  2992. Metadata: identity.Metadata,
  2993. CreatedAt: identity.CreatedAt,
  2994. UpdatedAt: identity.UpdatedAt,
  2995. })
  2996. }
  2997. return records, nil
  2998. }
  2999. func (r *oauthPendingFlowUserRepo) UnbindUserAuthProvider(context.Context, int64, string) error {
  3000. panic("unexpected UnbindUserAuthProvider call")
  3001. }
  3002. func (r *oauthPendingFlowUserRepo) UpdateTotpSecret(ctx context.Context, userID int64, encryptedSecret *string) error {
  3003. update := r.client.User.UpdateOneID(userID)
  3004. if encryptedSecret == nil {
  3005. update = update.ClearTotpSecretEncrypted()
  3006. } else {
  3007. update = update.SetTotpSecretEncrypted(*encryptedSecret)
  3008. }
  3009. return update.Exec(ctx)
  3010. }
  3011. func (r *oauthPendingFlowUserRepo) EnableTotp(ctx context.Context, userID int64) error {
  3012. return r.client.User.UpdateOneID(userID).
  3013. SetTotpEnabled(true).
  3014. SetTotpEnabledAt(time.Now().UTC()).
  3015. Exec(ctx)
  3016. }
  3017. func (r *oauthPendingFlowUserRepo) DisableTotp(ctx context.Context, userID int64) error {
  3018. return r.client.User.UpdateOneID(userID).
  3019. SetTotpEnabled(false).
  3020. ClearTotpSecretEncrypted().
  3021. ClearTotpEnabledAt().
  3022. Exec(ctx)
  3023. }
  3024. func (r *oauthPendingFlowUserRepo) GetByIDIncludeDeleted(ctx context.Context, id int64) (*service.User, error) {
  3025. return r.GetByID(ctx, id)
  3026. }
  3027. func oauthPendingFlowServiceUser(entity *dbent.User) *service.User {
  3028. if entity == nil {
  3029. return nil
  3030. }
  3031. return &service.User{
  3032. ID: entity.ID,
  3033. Email: entity.Email,
  3034. Username: entity.Username,
  3035. Notes: entity.Notes,
  3036. PasswordHash: entity.PasswordHash,
  3037. Role: entity.Role,
  3038. Balance: entity.Balance,
  3039. Concurrency: entity.Concurrency,
  3040. Status: entity.Status,
  3041. SignupSource: entity.SignupSource,
  3042. LastLoginAt: entity.LastLoginAt,
  3043. LastActiveAt: entity.LastActiveAt,
  3044. TotpSecretEncrypted: entity.TotpSecretEncrypted,
  3045. TotpEnabled: entity.TotpEnabled,
  3046. TotpEnabledAt: entity.TotpEnabledAt,
  3047. TotalRecharged: entity.TotalRecharged,
  3048. CreatedAt: entity.CreatedAt,
  3049. UpdatedAt: entity.UpdatedAt,
  3050. }
  3051. }
  3052. type oauthPendingFlowDefaultSubAssignerStub struct {
  3053. calls []service.AssignSubscriptionInput
  3054. }
  3055. func (s *oauthPendingFlowDefaultSubAssignerStub) AssignOrExtendSubscription(
  3056. _ context.Context,
  3057. input *service.AssignSubscriptionInput,
  3058. ) (*service.UserSubscription, bool, error) {
  3059. if input != nil {
  3060. s.calls = append(s.calls, *input)
  3061. }
  3062. return nil, false, nil
  3063. }
  3064. type oauthPendingFlowTotpCacheStub struct {
  3065. setupSessions map[int64]*service.TotpSetupSession
  3066. loginSessions map[string]*service.TotpLoginSession
  3067. verifyAttempts map[int64]int
  3068. }
  3069. func (s *oauthPendingFlowTotpCacheStub) GetSetupSession(_ context.Context, userID int64) (*service.TotpSetupSession, error) {
  3070. if s == nil || s.setupSessions == nil {
  3071. return nil, nil
  3072. }
  3073. return s.setupSessions[userID], nil
  3074. }
  3075. func (s *oauthPendingFlowTotpCacheStub) SetSetupSession(_ context.Context, userID int64, session *service.TotpSetupSession, _ time.Duration) error {
  3076. if s.setupSessions == nil {
  3077. s.setupSessions = map[int64]*service.TotpSetupSession{}
  3078. }
  3079. s.setupSessions[userID] = session
  3080. return nil
  3081. }
  3082. func (s *oauthPendingFlowTotpCacheStub) DeleteSetupSession(_ context.Context, userID int64) error {
  3083. delete(s.setupSessions, userID)
  3084. return nil
  3085. }
  3086. func (s *oauthPendingFlowTotpCacheStub) GetLoginSession(_ context.Context, tempToken string) (*service.TotpLoginSession, error) {
  3087. if s == nil || s.loginSessions == nil {
  3088. return nil, nil
  3089. }
  3090. return s.loginSessions[tempToken], nil
  3091. }
  3092. func (s *oauthPendingFlowTotpCacheStub) SetLoginSession(_ context.Context, tempToken string, session *service.TotpLoginSession, _ time.Duration) error {
  3093. if s.loginSessions == nil {
  3094. s.loginSessions = map[string]*service.TotpLoginSession{}
  3095. }
  3096. s.loginSessions[tempToken] = session
  3097. return nil
  3098. }
  3099. func (s *oauthPendingFlowTotpCacheStub) DeleteLoginSession(_ context.Context, tempToken string) error {
  3100. delete(s.loginSessions, tempToken)
  3101. return nil
  3102. }
  3103. func (s *oauthPendingFlowTotpCacheStub) IncrementVerifyAttempts(_ context.Context, userID int64) (int, error) {
  3104. if s.verifyAttempts == nil {
  3105. s.verifyAttempts = map[int64]int{}
  3106. }
  3107. s.verifyAttempts[userID]++
  3108. return s.verifyAttempts[userID], nil
  3109. }
  3110. func (s *oauthPendingFlowTotpCacheStub) GetVerifyAttempts(_ context.Context, userID int64) (int, error) {
  3111. if s == nil || s.verifyAttempts == nil {
  3112. return 0, nil
  3113. }
  3114. return s.verifyAttempts[userID], nil
  3115. }
  3116. func (s *oauthPendingFlowTotpCacheStub) ClearVerifyAttempts(_ context.Context, userID int64) error {
  3117. delete(s.verifyAttempts, userID)
  3118. return nil
  3119. }
  3120. func (s *oauthPendingFlowTotpCacheStub) SetStepUpGrant(_ context.Context, _ int64, _ string, _ time.Duration) error {
  3121. return nil
  3122. }
  3123. func (s *oauthPendingFlowTotpCacheStub) HasStepUpGrant(_ context.Context, _ int64, _ string) (bool, error) {
  3124. return false, nil
  3125. }
  3126. type oauthPendingFlowTotpEncryptorStub struct{}
  3127. func (oauthPendingFlowTotpEncryptorStub) Encrypt(plaintext string) (string, error) {
  3128. return plaintext, nil
  3129. }
  3130. func (oauthPendingFlowTotpEncryptorStub) Decrypt(ciphertext string) (string, error) {
  3131. return ciphertext, nil
  3132. }