| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595 |
- package handler
- import (
- "bytes"
- "context"
- "database/sql"
- "encoding/json"
- "errors"
- "net/http"
- "net/http/httptest"
- "strings"
- "testing"
- "time"
- dbent "github.com/Wei-Shaw/sub2api/ent"
- "github.com/Wei-Shaw/sub2api/ent/authidentity"
- "github.com/Wei-Shaw/sub2api/ent/enttest"
- "github.com/Wei-Shaw/sub2api/ent/identityadoptiondecision"
- "github.com/Wei-Shaw/sub2api/ent/pendingauthsession"
- "github.com/Wei-Shaw/sub2api/ent/redeemcode"
- dbuser "github.com/Wei-Shaw/sub2api/ent/user"
- "github.com/Wei-Shaw/sub2api/internal/config"
- "github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
- "github.com/Wei-Shaw/sub2api/internal/service"
- "github.com/gin-gonic/gin"
- "github.com/pquerna/otp/totp"
- "github.com/stretchr/testify/require"
- "entgo.io/ent/dialect"
- entsql "entgo.io/ent/dialect/sql"
- _ "modernc.org/sqlite"
- )
- func TestApplySuggestedProfileToCompletionResponse(t *testing.T) {
- payload := map[string]any{
- "access_token": "token",
- }
- upstream := map[string]any{
- "suggested_display_name": "Alice",
- "suggested_avatar_url": "https://cdn.example/avatar.png",
- }
- applySuggestedProfileToCompletionResponse(payload, upstream)
- require.Equal(t, "Alice", payload["suggested_display_name"])
- require.Equal(t, "https://cdn.example/avatar.png", payload["suggested_avatar_url"])
- require.Equal(t, true, payload["adoption_required"])
- }
- func TestApplySuggestedProfileToCompletionResponseKeepsExistingPayloadValues(t *testing.T) {
- payload := map[string]any{
- "suggested_display_name": "Existing",
- "adoption_required": false,
- }
- upstream := map[string]any{
- "suggested_display_name": "Alice",
- "suggested_avatar_url": "https://cdn.example/avatar.png",
- }
- applySuggestedProfileToCompletionResponse(payload, upstream)
- require.Equal(t, "Existing", payload["suggested_display_name"])
- require.Equal(t, "https://cdn.example/avatar.png", payload["suggested_avatar_url"])
- require.Equal(t, true, payload["adoption_required"])
- }
- func TestSetOAuthPendingSessionCookieUsesProviderCompletionPathPrefix(t *testing.T) {
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- ginCtx.Request = httptest.NewRequest(http.MethodGet, "/api/v1/auth/oauth/oidc/callback", nil)
- setOAuthPendingSessionCookie(ginCtx, "pending-session-token", false)
- cookie := findCookie(recorder.Result().Cookies(), oauthPendingSessionCookieName)
- require.NotNil(t, cookie)
- require.Equal(t, "/api/v1/auth/oauth", cookie.Path)
- }
- func TestExchangePendingOAuthCompletionPreviewThenFinalizeAppliesAdoptionDecision(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandler(t, false)
- ctx := context.Background()
- userEntity, err := client.User.Create().
- SetEmail("linuxdo-123@linuxdo-connect.invalid").
- SetUsername("legacy-name").
- SetPasswordHash("hash").
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("pending-session-token").
- SetIntent("login").
- SetProviderType("linuxdo").
- SetProviderKey("linuxdo").
- SetProviderSubject("123").
- SetTargetUserID(userEntity.ID).
- SetResolvedEmail(userEntity.Email).
- SetBrowserSessionKey("browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "username": "linuxdo_user",
- "suggested_display_name": "Alice Example",
- "suggested_avatar_url": "https://cdn.example/alice.png",
- }).
- SetLocalFlowState(map[string]any{
- oauthCompletionResponseKey: map[string]any{
- "access_token": "access-token",
- "redirect": "/dashboard",
- },
- }).
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- previewRecorder := httptest.NewRecorder()
- previewCtx, _ := gin.CreateTestContext(previewRecorder)
- previewReq := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", nil)
- previewReq.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- previewReq.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("browser-session-key")})
- previewCtx.Request = previewReq
- handler.ExchangePendingOAuthCompletion(previewCtx)
- require.Equal(t, http.StatusOK, previewRecorder.Code)
- previewData := decodeJSONResponseData(t, previewRecorder)
- require.Equal(t, "Alice Example", previewData["suggested_display_name"])
- require.Equal(t, "https://cdn.example/alice.png", previewData["suggested_avatar_url"])
- require.Equal(t, true, previewData["adoption_required"])
- storedUser, err := client.User.Get(ctx, userEntity.ID)
- require.NoError(t, err)
- require.Equal(t, "legacy-name", storedUser.Username)
- previewSession, err := client.PendingAuthSession.Query().
- Where(pendingauthsession.IDEQ(session.ID)).
- Only(ctx)
- require.NoError(t, err)
- require.Nil(t, previewSession.ConsumedAt)
- body := bytes.NewBufferString(`{"adopt_display_name":true,"adopt_avatar":true}`)
- finalizeRecorder := httptest.NewRecorder()
- finalizeCtx, _ := gin.CreateTestContext(finalizeRecorder)
- finalizeReq := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", body)
- finalizeReq.Header.Set("Content-Type", "application/json")
- finalizeReq.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- finalizeReq.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("browser-session-key")})
- finalizeCtx.Request = finalizeReq
- handler.ExchangePendingOAuthCompletion(finalizeCtx)
- require.Equal(t, http.StatusOK, finalizeRecorder.Code)
- storedUser, err = client.User.Get(ctx, userEntity.ID)
- require.NoError(t, err)
- require.Equal(t, "Alice Example", storedUser.Username)
- identity, err := client.AuthIdentity.Query().
- Where(
- authidentity.ProviderTypeEQ("linuxdo"),
- authidentity.ProviderKeyEQ("linuxdo"),
- authidentity.ProviderSubjectEQ("123"),
- ).
- Only(ctx)
- require.NoError(t, err)
- require.Equal(t, userEntity.ID, identity.UserID)
- require.Equal(t, "Alice Example", identity.Metadata["display_name"])
- require.Equal(t, "https://cdn.example/alice.png", identity.Metadata["avatar_url"])
- avatar := loadUserAvatarRecord(t, client, userEntity.ID)
- require.NotNil(t, avatar)
- require.Equal(t, "remote_url", avatar.StorageProvider)
- require.Equal(t, "https://cdn.example/alice.png", avatar.URL)
- decision, err := client.IdentityAdoptionDecision.Query().
- Where(identityadoptiondecision.PendingAuthSessionIDEQ(session.ID)).
- Only(ctx)
- require.NoError(t, err)
- require.NotNil(t, decision.IdentityID)
- require.Equal(t, identity.ID, *decision.IdentityID)
- require.True(t, decision.AdoptDisplayName)
- require.True(t, decision.AdoptAvatar)
- consumed, err := client.PendingAuthSession.Query().
- Where(pendingauthsession.IDEQ(session.ID)).
- Only(ctx)
- require.NoError(t, err)
- require.NotNil(t, consumed.ConsumedAt)
- }
- func TestExchangePendingOAuthCompletionSkipsInvalidAvatarAdoptionWithoutBlockingCompletion(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandler(t, false)
- ctx := context.Background()
- userEntity, err := client.User.Create().
- SetEmail("invalid-avatar@example.com").
- SetUsername("legacy-name").
- SetPasswordHash("hash").
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("pending-invalid-avatar-token").
- SetIntent("login").
- SetProviderType("linuxdo").
- SetProviderKey("linuxdo").
- SetProviderSubject("invalid-avatar-123").
- SetTargetUserID(userEntity.ID).
- SetResolvedEmail(userEntity.Email).
- SetBrowserSessionKey("browser-invalid-avatar-key").
- SetUpstreamIdentityClaims(map[string]any{
- "username": "linuxdo_user",
- "suggested_display_name": "Alice Example",
- "suggested_avatar_url": "/avatars/alice.png",
- }).
- SetLocalFlowState(map[string]any{
- oauthCompletionResponseKey: map[string]any{
- "access_token": "access-token",
- "redirect": "/dashboard",
- },
- }).
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"adopt_display_name":true,"adopt_avatar":true}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("browser-invalid-avatar-key")})
- ginCtx.Request = req
- handler.ExchangePendingOAuthCompletion(ginCtx)
- require.Equal(t, http.StatusOK, recorder.Code)
- identity, err := client.AuthIdentity.Query().
- Where(
- authidentity.ProviderTypeEQ("linuxdo"),
- authidentity.ProviderKeyEQ("linuxdo"),
- authidentity.ProviderSubjectEQ("invalid-avatar-123"),
- ).
- Only(ctx)
- require.NoError(t, err)
- require.Equal(t, "Alice Example", identity.Metadata["display_name"])
- _, hasAdoptedAvatar := identity.Metadata["avatar_url"]
- require.False(t, hasAdoptedAvatar)
- avatar := loadUserAvatarRecord(t, client, userEntity.ID)
- require.Nil(t, avatar)
- consumed, err := client.PendingAuthSession.Query().
- Where(pendingauthsession.IDEQ(session.ID)).
- Only(ctx)
- require.NoError(t, err)
- require.NotNil(t, consumed.ConsumedAt)
- }
- func TestExchangePendingOAuthCompletionBindCurrentUserPreviewThenFinalizeBindsIdentityWithoutAdoption(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandler(t, false)
- ctx := context.Background()
- userEntity, err := client.User.Create().
- SetEmail("bind-target@example.com").
- SetUsername("legacy-name").
- SetPasswordHash("hash").
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("bind-pending-session-token").
- SetIntent("bind_current_user").
- SetProviderType("linuxdo").
- SetProviderKey("linuxdo").
- SetProviderSubject("bind-123").
- SetTargetUserID(userEntity.ID).
- SetResolvedEmail(userEntity.Email).
- SetBrowserSessionKey("bind-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "username": "linuxdo_user",
- "suggested_display_name": "Bound Example",
- "suggested_avatar_url": "https://cdn.example/bound.png",
- }).
- SetLocalFlowState(map[string]any{
- oauthCompletionResponseKey: map[string]any{
- "access_token": "access-token",
- "redirect": "/settings/profile",
- },
- }).
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- previewRecorder := httptest.NewRecorder()
- previewCtx, _ := gin.CreateTestContext(previewRecorder)
- previewReq := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", nil)
- previewReq.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- previewReq.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("bind-browser-session-key")})
- previewCtx.Request = previewReq
- handler.ExchangePendingOAuthCompletion(previewCtx)
- require.Equal(t, http.StatusOK, previewRecorder.Code)
- previewData := decodeJSONResponseData(t, previewRecorder)
- require.Equal(t, "Bound Example", previewData["suggested_display_name"])
- require.Equal(t, "https://cdn.example/bound.png", previewData["suggested_avatar_url"])
- require.Equal(t, true, previewData["adoption_required"])
- identityCount, err := client.AuthIdentity.Query().
- Where(
- authidentity.ProviderTypeEQ("linuxdo"),
- authidentity.ProviderKeyEQ("linuxdo"),
- authidentity.ProviderSubjectEQ("bind-123"),
- ).
- Count(ctx)
- require.NoError(t, err)
- require.Zero(t, identityCount)
- previewSession, err := client.PendingAuthSession.Query().
- Where(pendingauthsession.IDEQ(session.ID)).
- Only(ctx)
- require.NoError(t, err)
- require.Nil(t, previewSession.ConsumedAt)
- body := bytes.NewBufferString(`{"adopt_display_name":false,"adopt_avatar":false}`)
- finalizeRecorder := httptest.NewRecorder()
- finalizeCtx, _ := gin.CreateTestContext(finalizeRecorder)
- finalizeReq := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", body)
- finalizeReq.Header.Set("Content-Type", "application/json")
- finalizeReq.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- finalizeReq.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("bind-browser-session-key")})
- finalizeCtx.Request = finalizeReq
- handler.ExchangePendingOAuthCompletion(finalizeCtx)
- require.Equal(t, http.StatusOK, finalizeRecorder.Code)
- storedUser, err := client.User.Get(ctx, userEntity.ID)
- require.NoError(t, err)
- require.Equal(t, "legacy-name", storedUser.Username)
- identity, err := client.AuthIdentity.Query().
- Where(
- authidentity.ProviderTypeEQ("linuxdo"),
- authidentity.ProviderKeyEQ("linuxdo"),
- authidentity.ProviderSubjectEQ("bind-123"),
- ).
- Only(ctx)
- require.NoError(t, err)
- require.Equal(t, userEntity.ID, identity.UserID)
- require.Equal(t, "Bound Example", identity.Metadata["suggested_display_name"])
- require.Equal(t, "https://cdn.example/bound.png", identity.Metadata["suggested_avatar_url"])
- _, hasDisplayName := identity.Metadata["display_name"]
- require.False(t, hasDisplayName)
- _, hasAvatarURL := identity.Metadata["avatar_url"]
- require.False(t, hasAvatarURL)
- decision, err := client.IdentityAdoptionDecision.Query().
- Where(identityadoptiondecision.PendingAuthSessionIDEQ(session.ID)).
- Only(ctx)
- require.NoError(t, err)
- require.NotNil(t, decision.IdentityID)
- require.Equal(t, identity.ID, *decision.IdentityID)
- require.False(t, decision.AdoptDisplayName)
- require.False(t, decision.AdoptAvatar)
- consumed, err := client.PendingAuthSession.Query().
- Where(pendingauthsession.IDEQ(session.ID)).
- Only(ctx)
- require.NoError(t, err)
- require.NotNil(t, consumed.ConsumedAt)
- }
- func TestExchangePendingOAuthCompletionBindCurrentUserOwnershipConflict(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandler(t, false)
- ctx := context.Background()
- targetUser, err := client.User.Create().
- SetEmail("bind-conflict-target@example.com").
- SetUsername("target-user").
- SetPasswordHash("hash").
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- ownerUser, err := client.User.Create().
- SetEmail("bind-conflict-owner@example.com").
- SetUsername("owner-user").
- SetPasswordHash("hash").
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- existingIdentity, err := client.AuthIdentity.Create().
- SetUserID(ownerUser.ID).
- SetProviderType("linuxdo").
- SetProviderKey("linuxdo").
- SetProviderSubject("conflict-123").
- SetMetadata(map[string]any{"username": "owner-user"}).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("bind-conflict-session-token").
- SetIntent("bind_current_user").
- SetProviderType("linuxdo").
- SetProviderKey("linuxdo").
- SetProviderSubject("conflict-123").
- SetTargetUserID(targetUser.ID).
- SetResolvedEmail(targetUser.Email).
- SetBrowserSessionKey("bind-conflict-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "suggested_display_name": "Conflict Example",
- "suggested_avatar_url": "https://cdn.example/conflict.png",
- }).
- SetLocalFlowState(map[string]any{
- oauthCompletionResponseKey: map[string]any{
- "access_token": "access-token",
- },
- }).
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"adopt_display_name":false,"adopt_avatar":false}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("bind-conflict-browser-session-key")})
- ginCtx.Request = req
- handler.ExchangePendingOAuthCompletion(ginCtx)
- require.Equal(t, http.StatusInternalServerError, recorder.Code)
- payload := decodeJSONBody(t, recorder)
- require.Equal(t, "PENDING_AUTH_ADOPTION_APPLY_FAILED", payload["reason"])
- identity, err := client.AuthIdentity.Get(ctx, existingIdentity.ID)
- require.NoError(t, err)
- require.Equal(t, ownerUser.ID, identity.UserID)
- decision, err := client.IdentityAdoptionDecision.Query().
- Where(identityadoptiondecision.PendingAuthSessionIDEQ(session.ID)).
- Only(ctx)
- require.NoError(t, err)
- require.Nil(t, decision.IdentityID)
- require.False(t, decision.AdoptDisplayName)
- require.False(t, decision.AdoptAvatar)
- storedSession, err := client.PendingAuthSession.Query().
- Where(pendingauthsession.IDEQ(session.ID)).
- Only(ctx)
- require.NoError(t, err)
- require.Nil(t, storedSession.ConsumedAt)
- }
- func TestExchangePendingOAuthCompletionLoginFalseFalseBindsIdentityWithoutAdoption(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandler(t, false)
- ctx := context.Background()
- userEntity, err := client.User.Create().
- SetEmail("login-false@example.com").
- SetUsername("legacy-name").
- SetPasswordHash("hash").
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("login-false-session-token").
- SetIntent("login").
- SetProviderType("linuxdo").
- SetProviderKey("linuxdo").
- SetProviderSubject("login-false-123").
- SetTargetUserID(userEntity.ID).
- SetResolvedEmail(userEntity.Email).
- SetBrowserSessionKey("login-false-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "suggested_display_name": "Login Example",
- "suggested_avatar_url": "https://cdn.example/login.png",
- }).
- SetLocalFlowState(map[string]any{
- oauthCompletionResponseKey: map[string]any{
- "access_token": "access-token",
- },
- }).
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"adopt_display_name":false,"adopt_avatar":false}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("login-false-browser-session-key")})
- ginCtx.Request = req
- handler.ExchangePendingOAuthCompletion(ginCtx)
- require.Equal(t, http.StatusOK, recorder.Code)
- identity, err := client.AuthIdentity.Query().
- Where(
- authidentity.ProviderTypeEQ("linuxdo"),
- authidentity.ProviderKeyEQ("linuxdo"),
- authidentity.ProviderSubjectEQ("login-false-123"),
- ).
- Only(ctx)
- require.NoError(t, err)
- require.Equal(t, userEntity.ID, identity.UserID)
- decision, err := client.IdentityAdoptionDecision.Query().
- Where(identityadoptiondecision.PendingAuthSessionIDEQ(session.ID)).
- Only(ctx)
- require.NoError(t, err)
- require.NotNil(t, decision.IdentityID)
- require.Equal(t, identity.ID, *decision.IdentityID)
- require.False(t, decision.AdoptDisplayName)
- require.False(t, decision.AdoptAvatar)
- storedSession, err := client.PendingAuthSession.Query().
- Where(pendingauthsession.IDEQ(session.ID)).
- Only(ctx)
- require.NoError(t, err)
- require.NotNil(t, storedSession.ConsumedAt)
- }
- func TestExchangePendingOAuthCompletionLoginReassignsExistingDecisionIdentityReference(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandler(t, false)
- ctx := context.Background()
- userEntity, err := client.User.Create().
- SetEmail("login-reassign@example.com").
- SetUsername("legacy-name").
- SetPasswordHash("hash").
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- existingIdentity, err := client.AuthIdentity.Create().
- SetUserID(userEntity.ID).
- SetProviderType("linuxdo").
- SetProviderKey("linuxdo").
- SetProviderSubject("login-reassign-123").
- SetMetadata(map[string]any{}).
- Save(ctx)
- require.NoError(t, err)
- previousSession, err := client.PendingAuthSession.Create().
- SetSessionToken("login-reassign-previous-session-token").
- SetIntent("login").
- SetProviderType("linuxdo").
- SetProviderKey("linuxdo").
- SetProviderSubject("login-reassign-123").
- SetTargetUserID(userEntity.ID).
- SetResolvedEmail(userEntity.Email).
- SetBrowserSessionKey("login-reassign-previous-browser-session-key").
- SetLocalFlowState(map[string]any{
- oauthCompletionResponseKey: map[string]any{
- "access_token": "previous-access-token",
- },
- }).
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- previousDecision, err := client.IdentityAdoptionDecision.Create().
- SetPendingAuthSessionID(previousSession.ID).
- SetIdentityID(existingIdentity.ID).
- SetAdoptDisplayName(true).
- SetAdoptAvatar(true).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("login-reassign-session-token").
- SetIntent("login").
- SetProviderType("linuxdo").
- SetProviderKey("linuxdo").
- SetProviderSubject("login-reassign-123").
- SetTargetUserID(userEntity.ID).
- SetResolvedEmail(userEntity.Email).
- SetBrowserSessionKey("login-reassign-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "suggested_display_name": "Login Reassign",
- "suggested_avatar_url": "https://cdn.example/login-reassign.png",
- }).
- SetLocalFlowState(map[string]any{
- oauthCompletionResponseKey: map[string]any{
- "access_token": "access-token",
- },
- }).
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- _, err = client.IdentityAdoptionDecision.Create().
- SetPendingAuthSessionID(session.ID).
- SetAdoptDisplayName(false).
- SetAdoptAvatar(false).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"adopt_display_name":false,"adopt_avatar":false}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("login-reassign-browser-session-key")})
- ginCtx.Request = req
- handler.ExchangePendingOAuthCompletion(ginCtx)
- require.Equal(t, http.StatusOK, recorder.Code)
- reloadedPrevious, err := client.IdentityAdoptionDecision.Get(ctx, previousDecision.ID)
- require.NoError(t, err)
- require.Nil(t, reloadedPrevious.IdentityID)
- currentDecision, err := client.IdentityAdoptionDecision.Query().
- Where(identityadoptiondecision.PendingAuthSessionIDEQ(session.ID)).
- Only(ctx)
- require.NoError(t, err)
- require.NotNil(t, currentDecision.IdentityID)
- require.Equal(t, existingIdentity.ID, *currentDecision.IdentityID)
- storedSession, err := client.PendingAuthSession.Query().
- Where(pendingauthsession.IDEQ(session.ID)).
- Only(ctx)
- require.NoError(t, err)
- require.NotNil(t, storedSession.ConsumedAt)
- }
- func TestExchangePendingOAuthCompletionLoginWithoutDecisionStillBindsIdentity(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandler(t, false)
- ctx := context.Background()
- userEntity, err := client.User.Create().
- SetEmail("login-nodecision@example.com").
- SetUsername("legacy-name").
- SetPasswordHash("hash").
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("login-nodecision-session-token").
- SetIntent("login").
- SetProviderType("linuxdo").
- SetProviderKey("linuxdo").
- SetProviderSubject("login-nodecision-123").
- SetTargetUserID(userEntity.ID).
- SetResolvedEmail(userEntity.Email).
- SetBrowserSessionKey("login-nodecision-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "username": "login-nodecision-user",
- }).
- SetLocalFlowState(map[string]any{
- oauthCompletionResponseKey: map[string]any{
- "access_token": "access-token",
- },
- }).
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", nil)
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("login-nodecision-browser-session-key")})
- ginCtx.Request = req
- handler.ExchangePendingOAuthCompletion(ginCtx)
- require.Equal(t, http.StatusOK, recorder.Code)
- identity, err := client.AuthIdentity.Query().
- Where(
- authidentity.ProviderTypeEQ("linuxdo"),
- authidentity.ProviderKeyEQ("linuxdo"),
- authidentity.ProviderSubjectEQ("login-nodecision-123"),
- ).
- Only(ctx)
- require.NoError(t, err)
- require.Equal(t, userEntity.ID, identity.UserID)
- storedSession, err := client.PendingAuthSession.Query().
- Where(pendingauthsession.IDEQ(session.ID)).
- Only(ctx)
- require.NoError(t, err)
- require.NotNil(t, storedSession.ConsumedAt)
- }
- func TestExchangePendingOAuthCompletionExistingLoginWithSuggestedProfileSkipsAdoptionPrompt(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandler(t, false)
- ctx := context.Background()
- userEntity, err := client.User.Create().
- SetEmail("existing-login@example.com").
- SetUsername("existing-login-user").
- SetPasswordHash("hash").
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- _, err = client.AuthIdentity.Create().
- SetUserID(userEntity.ID).
- SetProviderType("linuxdo").
- SetProviderKey("linuxdo").
- SetProviderSubject("existing-login-123").
- SetMetadata(map[string]any{
- "username": "existing-login-user",
- }).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("existing-login-session-token").
- SetIntent("login").
- SetProviderType("linuxdo").
- SetProviderKey("linuxdo").
- SetProviderSubject("existing-login-123").
- SetTargetUserID(userEntity.ID).
- SetResolvedEmail(userEntity.Email).
- SetBrowserSessionKey("existing-login-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "suggested_display_name": "Existing Login Example",
- "suggested_avatar_url": "https://cdn.example/existing-login.png",
- }).
- SetLocalFlowState(map[string]any{
- oauthCompletionResponseKey: map[string]any{
- "access_token": "legacy-access-token",
- "refresh_token": "legacy-refresh-token",
- "expires_in": float64(3600),
- "token_type": "Bearer",
- "redirect": "/dashboard",
- },
- }).
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", nil)
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("existing-login-browser-session-key")})
- ginCtx.Request = req
- handler.ExchangePendingOAuthCompletion(ginCtx)
- require.Equal(t, http.StatusOK, recorder.Code)
- payload := decodeJSONResponseData(t, recorder)
- require.NotEmpty(t, payload["access_token"])
- require.NotEmpty(t, payload["refresh_token"])
- require.NotEqual(t, "legacy-access-token", payload["access_token"])
- require.NotEqual(t, "legacy-refresh-token", payload["refresh_token"])
- require.Equal(t, "/dashboard", payload["redirect"])
- require.Equal(t, "Existing Login Example", payload["suggested_display_name"])
- require.Equal(t, "https://cdn.example/existing-login.png", payload["suggested_avatar_url"])
- require.NotContains(t, payload, "adoption_required")
- accessToken, ok := payload["access_token"].(string)
- require.True(t, ok)
- claims, err := handler.authService.ValidateToken(accessToken)
- require.NoError(t, err)
- reloadedUser, err := handler.userService.GetByID(ctx, userEntity.ID)
- require.NoError(t, err)
- require.Equal(t, reloadedUser.TokenVersion, claims.TokenVersion)
- decisionCount, err := client.IdentityAdoptionDecision.Query().
- Where(identityadoptiondecision.PendingAuthSessionIDEQ(session.ID)).
- Count(ctx)
- require.NoError(t, err)
- require.Equal(t, 1, decisionCount)
- storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
- require.NoError(t, err)
- require.NotNil(t, storedSession.ConsumedAt)
- completion, ok := storedSession.LocalFlowState[oauthCompletionResponseKey].(map[string]any)
- require.True(t, ok)
- require.NotContains(t, completion, "access_token")
- require.NotContains(t, completion, "refresh_token")
- require.NotContains(t, completion, "expires_in")
- require.NotContains(t, completion, "token_type")
- require.Equal(t, "/dashboard", completion["redirect"])
- }
- func TestExchangePendingOAuthCompletionBlocksBackendModeBeforeReturningTokenPayload(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
- settingValues: map[string]string{
- service.SettingKeyBackendModeEnabled: "true",
- },
- })
- ctx := context.Background()
- userEntity, err := client.User.Create().
- SetEmail("blocked@example.com").
- SetUsername("blocked-user").
- SetPasswordHash("hash").
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("blocked-backend-mode-session-token").
- SetIntent("login").
- SetProviderType("linuxdo").
- SetProviderKey("linuxdo").
- SetProviderSubject("blocked-subject-123").
- SetTargetUserID(userEntity.ID).
- SetResolvedEmail(userEntity.Email).
- SetBrowserSessionKey("blocked-backend-mode-browser-session-key").
- SetLocalFlowState(map[string]any{
- oauthCompletionResponseKey: map[string]any{
- "access_token": "access-token",
- "refresh_token": "refresh-token",
- "expires_in": float64(3600),
- "token_type": "Bearer",
- },
- }).
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", nil)
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("blocked-backend-mode-browser-session-key")})
- ginCtx.Request = req
- handler.ExchangePendingOAuthCompletion(ginCtx)
- require.Equal(t, http.StatusForbidden, recorder.Code)
- storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
- require.NoError(t, err)
- require.Nil(t, storedSession.ConsumedAt)
- }
- func TestExchangePendingOAuthCompletionRejectsDisabledTargetUser(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandler(t, false)
- ctx := context.Background()
- userEntity, err := client.User.Create().
- SetEmail("disabled-linked@example.com").
- SetUsername("disabled-linked-user").
- SetPasswordHash("hash").
- SetRole(service.RoleUser).
- SetStatus(service.StatusDisabled).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("disabled-linked-session-token").
- SetIntent("login").
- SetProviderType("linuxdo").
- SetProviderKey("linuxdo").
- SetProviderSubject("disabled-linked-subject").
- SetTargetUserID(userEntity.ID).
- SetResolvedEmail(userEntity.Email).
- SetBrowserSessionKey("disabled-linked-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "suggested_display_name": "Disabled Linked User",
- }).
- SetLocalFlowState(map[string]any{
- oauthCompletionResponseKey: map[string]any{
- "redirect": "/dashboard",
- },
- }).
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", nil)
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("disabled-linked-browser-session-key")})
- ginCtx.Request = req
- handler.ExchangePendingOAuthCompletion(ginCtx)
- require.Equal(t, http.StatusForbidden, recorder.Code)
- storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
- require.NoError(t, err)
- require.Nil(t, storedSession.ConsumedAt)
- }
- func TestExchangePendingOAuthCompletionChoiceStateDoesNotBindIdentity(t *testing.T) {
- // 回归测试:复刻"补邮箱/创建账户"路径的账号接管 0day。
- // 攻击者用自己的 OAuth 账号登录后,在 create-account 步骤提交受害者邮箱,
- // 后端发现邮箱已存在会把 pending session 转入 choice 状态并指向受害者
- // (TargetUserID=受害者、无密码/验证码证明)。此时带 adoption decision 调
- // exchange 绝不能把 OAuth identity 绑定到受害者账号。
- handler, client := newOAuthPendingFlowTestHandler(t, false)
- ctx := context.Background()
- victim, err := client.User.Create().
- SetEmail("victim@example.com").
- SetUsername("victim-user").
- SetPasswordHash("hash").
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("choice-state-attack-session-token").
- SetIntent("login").
- SetProviderType("linuxdo").
- SetProviderKey("linuxdo").
- SetProviderSubject("attacker-subject-123").
- SetTargetUserID(victim.ID).
- SetResolvedEmail(victim.Email).
- SetBrowserSessionKey("choice-state-attack-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "username": "attacker_linuxdo_user",
- "suggested_display_name": "Attacker Display Name",
- "suggested_avatar_url": "https://cdn.example/attacker.png",
- }).
- SetLocalFlowState(map[string]any{
- oauthCompletionResponseKey: map[string]any{
- "step": oauthPendingChoiceStep,
- "adoption_required": true,
- "force_email_on_signup": true,
- "email_binding_required": true,
- "existing_account_bindable": true,
- "email": victim.Email,
- "resolved_email": victim.Email,
- "redirect": "/dashboard",
- },
- }).
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"adopt_display_name":true,"adopt_avatar":true}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("choice-state-attack-browser-session-key")})
- ginCtx.Request = req
- handler.ExchangePendingOAuthCompletion(ginCtx)
- require.Equal(t, http.StatusOK, recorder.Code)
- data := decodeJSONResponseData(t, recorder)
- require.NotContains(t, data, "access_token")
- require.Equal(t, oauthPendingChoiceStep, data["step"])
- // 攻击者的 OAuth identity 绝不能绑定到受害者账号
- identityCount, err := client.AuthIdentity.Query().
- Where(
- authidentity.ProviderTypeEQ("linuxdo"),
- authidentity.ProviderKeyEQ("linuxdo"),
- authidentity.ProviderSubjectEQ("attacker-subject-123"),
- ).
- Count(ctx)
- require.NoError(t, err)
- require.Zero(t, identityCount)
- // 受害者资料不得被 adoption 篡改
- storedVictim, err := client.User.Get(ctx, victim.ID)
- require.NoError(t, err)
- require.Equal(t, "victim-user", storedVictim.Username)
- // session 不得被消费(攻击者无法进入下一环)
- storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
- require.NoError(t, err)
- require.Nil(t, storedSession.ConsumedAt)
- }
- func TestNormalizePendingOAuthCompletionResponseScrubsLegacyTokenPayload(t *testing.T) {
- payload := normalizePendingOAuthCompletionResponse(map[string]any{
- "access_token": "legacy-access-token",
- "refresh_token": "legacy-refresh-token",
- "expires_in": float64(3600),
- "token_type": "Bearer",
- "redirect": "/dashboard",
- })
- require.NotContains(t, payload, "access_token")
- require.NotContains(t, payload, "refresh_token")
- require.NotContains(t, payload, "expires_in")
- require.NotContains(t, payload, "token_type")
- require.Equal(t, "/dashboard", payload["redirect"])
- }
- func TestExchangePendingOAuthCompletionInvitationRequiredFalseFalsePersistsDecisionWithoutBinding(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandler(t, true)
- ctx := context.Background()
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("invitation-required-session-token").
- SetIntent("login").
- SetProviderType("linuxdo").
- SetProviderKey("linuxdo").
- SetProviderSubject("invitation-123").
- SetBrowserSessionKey("invitation-required-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "suggested_display_name": "Invite Example",
- "suggested_avatar_url": "https://cdn.example/invite.png",
- }).
- SetLocalFlowState(map[string]any{
- oauthCompletionResponseKey: map[string]any{
- "error": "invitation_required",
- },
- }).
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"adopt_display_name":false,"adopt_avatar":false}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/exchange", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("invitation-required-browser-session-key")})
- ginCtx.Request = req
- handler.ExchangePendingOAuthCompletion(ginCtx)
- require.Equal(t, http.StatusOK, recorder.Code)
- data := decodeJSONResponseData(t, recorder)
- require.Equal(t, "invitation_required", data["error"])
- require.Equal(t, true, data["adoption_required"])
- identityCount, err := client.AuthIdentity.Query().
- Where(
- authidentity.ProviderTypeEQ("linuxdo"),
- authidentity.ProviderKeyEQ("linuxdo"),
- authidentity.ProviderSubjectEQ("invitation-123"),
- ).
- Count(ctx)
- require.NoError(t, err)
- require.Zero(t, identityCount)
- decision, err := client.IdentityAdoptionDecision.Query().
- Where(identityadoptiondecision.PendingAuthSessionIDEQ(session.ID)).
- Only(ctx)
- require.NoError(t, err)
- require.Nil(t, decision.IdentityID)
- require.False(t, decision.AdoptDisplayName)
- require.False(t, decision.AdoptAvatar)
- storedSession, err := client.PendingAuthSession.Query().
- Where(pendingauthsession.IDEQ(session.ID)).
- Only(ctx)
- require.NoError(t, err)
- require.Nil(t, storedSession.ConsumedAt)
- }
- func TestCreateOIDCOAuthAccountCreatesUserBindsIdentityAndConsumesSession(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandlerWithEmailVerification(t, false, "fresh@example.com", "246810")
- ctx := context.Background()
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("create-account-session-token").
- SetIntent("login").
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-create-123").
- SetBrowserSessionKey("create-account-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "username": "oidc_user",
- "suggested_display_name": "Fresh OIDC User",
- "suggested_avatar_url": "https://cdn.example/fresh.png",
- }).
- SetRedirectTo("/profile").
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"email":"fresh@example.com","verify_code":"246810","password":"secret-123","adopt_display_name":false,"adopt_avatar":false}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("create-account-browser-session-key")})
- ginCtx.Request = req
- handler.CreateOIDCOAuthAccount(ginCtx)
- require.Equal(t, http.StatusOK, recorder.Code)
- var payload map[string]any
- require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &payload))
- require.NotEmpty(t, payload["access_token"])
- require.NotEmpty(t, payload["refresh_token"])
- require.Equal(t, "Bearer", payload["token_type"])
- createdUser, err := client.User.Query().Where(dbuser.EmailEQ("fresh@example.com")).Only(ctx)
- require.NoError(t, err)
- require.Equal(t, service.StatusActive, createdUser.Status)
- identity, err := client.AuthIdentity.Query().
- Where(
- authidentity.ProviderTypeEQ("oidc"),
- authidentity.ProviderKeyEQ("https://issuer.example"),
- authidentity.ProviderSubjectEQ("oidc-create-123"),
- ).
- Only(ctx)
- require.NoError(t, err)
- require.Equal(t, createdUser.ID, identity.UserID)
- storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
- require.NoError(t, err)
- require.NotNil(t, storedSession.ConsumedAt)
- }
- func TestCreateOIDCOAuthAccountAppliesPromoCodeFromPendingSession(t *testing.T) {
- promoRepo := newOAuthPendingFlowPromoRepoStub("WELCOME2024", 25)
- emailCache := &oauthPendingFlowEmailCacheStub{
- verificationCodes: map[string]*service.VerificationCodeData{
- "promo@example.com": {
- Code: "246810",
- CreatedAt: time.Now().UTC(),
- ExpiresAt: time.Now().UTC().Add(15 * time.Minute),
- },
- },
- }
- handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
- emailVerifyEnabled: true,
- emailCache: emailCache,
- promoRepo: promoRepo,
- settingValues: map[string]string{
- service.SettingKeyPromoCodeEnabled: "true",
- },
- })
- ctx := context.Background()
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("promo-create-account-session-token").
- SetIntent(oauthIntentLogin).
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-promo-123").
- SetBrowserSessionKey("promo-create-account-browser-key").
- SetUpstreamIdentityClaims(map[string]any{"username": "promo_user"}).
- SetLocalFlowState(map[string]any{oauthPromoCodeStateKey: "WELCOME2024"}).
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"email":"promo@example.com","verify_code":"246810","password":"secret-123"}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue(session.BrowserSessionKey)})
- ginCtx.Request = req
- handler.CreateOIDCOAuthAccount(ginCtx)
- require.Equal(t, http.StatusOK, recorder.Code)
- require.Equal(t, []string{"WELCOME2024"}, promoRepo.applyCalls)
- createdUser, err := client.User.Query().Where(dbuser.EmailEQ("promo@example.com")).Only(ctx)
- require.NoError(t, err)
- require.Equal(t, 25.0, createdUser.Balance)
- require.Len(t, promoRepo.usages, 1)
- require.Equal(t, createdUser.ID, promoRepo.usages[0].UserID)
- }
- func TestCreateOIDCOAuthAccountWithoutPromoCodeDoesNotApplyPromo(t *testing.T) {
- promoRepo := newOAuthPendingFlowPromoRepoStub("WELCOME2024", 25)
- emailCache := &oauthPendingFlowEmailCacheStub{
- verificationCodes: map[string]*service.VerificationCodeData{
- "no-promo@example.com": {
- Code: "246810",
- CreatedAt: time.Now().UTC(),
- ExpiresAt: time.Now().UTC().Add(15 * time.Minute),
- },
- },
- }
- handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
- emailVerifyEnabled: true,
- emailCache: emailCache,
- promoRepo: promoRepo,
- settingValues: map[string]string{
- service.SettingKeyPromoCodeEnabled: "true",
- },
- })
- ctx := context.Background()
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("no-promo-create-account-session-token").
- SetIntent(oauthIntentLogin).
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-no-promo-123").
- SetBrowserSessionKey("no-promo-create-account-browser-key").
- SetUpstreamIdentityClaims(map[string]any{"username": "no_promo_user"}).
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"email":"no-promo@example.com","verify_code":"246810","password":"secret-123"}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue(session.BrowserSessionKey)})
- ginCtx.Request = req
- handler.CreateOIDCOAuthAccount(ginCtx)
- require.Equal(t, http.StatusOK, recorder.Code)
- require.Empty(t, promoRepo.applyCalls)
- createdUser, err := client.User.Query().Where(dbuser.EmailEQ("no-promo@example.com")).Only(ctx)
- require.NoError(t, err)
- require.Zero(t, createdUser.Balance)
- }
- func TestCreateOIDCOAuthAccountDoesNotApplyPromoWhenDisabled(t *testing.T) {
- promoRepo := newOAuthPendingFlowPromoRepoStub("WELCOME2024", 25)
- emailCache := &oauthPendingFlowEmailCacheStub{
- verificationCodes: map[string]*service.VerificationCodeData{
- "promo-disabled@example.com": {
- Code: "246810",
- CreatedAt: time.Now().UTC(),
- ExpiresAt: time.Now().UTC().Add(15 * time.Minute),
- },
- },
- }
- handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
- emailVerifyEnabled: true,
- emailCache: emailCache,
- promoRepo: promoRepo,
- settingValues: map[string]string{
- service.SettingKeyPromoCodeEnabled: "false",
- },
- })
- ctx := context.Background()
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("promo-disabled-session-token").
- SetIntent(oauthIntentLogin).
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-promo-disabled-123").
- SetBrowserSessionKey("promo-disabled-browser-key").
- SetUpstreamIdentityClaims(map[string]any{"username": "promo_disabled_user"}).
- SetLocalFlowState(map[string]any{oauthPromoCodeStateKey: "WELCOME2024"}).
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"email":"promo-disabled@example.com","verify_code":"246810","password":"secret-123"}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue(session.BrowserSessionKey)})
- ginCtx.Request = req
- handler.CreateOIDCOAuthAccount(ginCtx)
- require.Equal(t, http.StatusOK, recorder.Code)
- require.Empty(t, promoRepo.applyCalls)
- createdUser, err := client.User.Query().Where(dbuser.EmailEQ("promo-disabled@example.com")).Only(ctx)
- require.NoError(t, err)
- require.Zero(t, createdUser.Balance)
- }
- func TestOAuthExistingUserLoginDoesNotApplyPromoCode(t *testing.T) {
- promoRepo := newOAuthPendingFlowPromoRepoStub("WELCOME2024", 25)
- handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
- promoRepo: promoRepo,
- settingValues: map[string]string{
- service.SettingKeyPromoCodeEnabled: "true",
- },
- })
- ctx := context.Background()
- existingUser, err := client.User.Create().
- SetEmail("existing-promo@example.com").
- SetUsername("existing").
- SetPasswordHash("hash").
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- SetBalance(7).
- Save(ctx)
- require.NoError(t, err)
- _, loggedInUser, err := handler.authService.LoginOrRegisterOAuthWithTokenPairAndPromoCode(
- ctx,
- existingUser.Email,
- existingUser.Username,
- "",
- "",
- "WELCOME2024",
- "oidc",
- )
- require.NoError(t, err)
- require.Equal(t, existingUser.ID, loggedInUser.ID)
- require.Empty(t, promoRepo.applyCalls)
- reloadedUser, err := client.User.Get(ctx, existingUser.ID)
- require.NoError(t, err)
- require.Equal(t, 7.0, reloadedUser.Balance)
- }
- func TestCreateOIDCOAuthAccountExistingEmailReturnsChoicePendingSessionState(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandlerWithEmailVerification(t, false, "owner@example.com", "135790")
- ctx := context.Background()
- existingUser, err := client.User.Create().
- SetEmail("owner@example.com").
- SetUsername("owner-user").
- SetPasswordHash("hash").
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("existing-email-session-token").
- SetIntent("login").
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-existing-123").
- SetBrowserSessionKey("existing-email-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "username": "oidc_user",
- "suggested_display_name": "Existing OIDC User",
- "suggested_avatar_url": "https://cdn.example/existing.png",
- }).
- SetRedirectTo("/dashboard").
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"email":"owner@example.com","verify_code":"135790","password":"secret-123"}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("existing-email-browser-session-key")})
- ginCtx.Request = req
- handler.CreateOIDCOAuthAccount(ginCtx)
- require.Equal(t, http.StatusOK, recorder.Code)
- var payload map[string]any
- require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &payload))
- require.Equal(t, "pending_session", payload["auth_result"])
- require.Equal(t, oauthIntentLogin, payload["intent"])
- require.Equal(t, "oidc", payload["provider"])
- require.Equal(t, "/dashboard", payload["redirect"])
- require.Equal(t, true, payload["adoption_required"])
- require.Equal(t, oauthPendingChoiceStep, payload["step"])
- require.Equal(t, "owner@example.com", payload["email"])
- require.Equal(t, "Existing OIDC User", payload["suggested_display_name"])
- require.Equal(t, "https://cdn.example/existing.png", payload["suggested_avatar_url"])
- storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
- require.NoError(t, err)
- require.Equal(t, oauthIntentLogin, storedSession.Intent)
- require.NotNil(t, storedSession.TargetUserID)
- require.Equal(t, existingUser.ID, *storedSession.TargetUserID)
- require.Equal(t, "owner@example.com", storedSession.ResolvedEmail)
- require.Nil(t, storedSession.ConsumedAt)
- identityCount, err := client.AuthIdentity.Query().
- Where(
- authidentity.ProviderTypeEQ("oidc"),
- authidentity.ProviderKeyEQ("https://issuer.example"),
- authidentity.ProviderSubjectEQ("oidc-existing-123"),
- ).
- Count(ctx)
- require.NoError(t, err)
- require.Zero(t, identityCount)
- }
- func TestCreateOIDCOAuthAccountExistingEmailNormalizesLegacySpacingAndCase(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandlerWithEmailVerification(t, false, "owner@example.com", "135790")
- ctx := context.Background()
- existingUser, err := client.User.Create().
- SetEmail(" Owner@Example.com ").
- SetUsername("owner-user").
- SetPasswordHash("hash").
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("existing-email-normalized-session-token").
- SetIntent("login").
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-existing-normalized-123").
- SetBrowserSessionKey("existing-email-normalized-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "username": "oidc_user",
- "suggested_display_name": "Existing OIDC User",
- "suggested_avatar_url": "https://cdn.example/existing.png",
- }).
- SetRedirectTo("/dashboard").
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"email":"owner@example.com","verify_code":"135790","password":"secret-123"}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("existing-email-normalized-browser-session-key")})
- ginCtx.Request = req
- handler.CreateOIDCOAuthAccount(ginCtx)
- require.Equal(t, http.StatusOK, recorder.Code)
- var payload map[string]any
- require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &payload))
- require.Equal(t, oauthIntentLogin, payload["intent"])
- require.Equal(t, oauthPendingChoiceStep, payload["step"])
- storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
- require.NoError(t, err)
- require.NotNil(t, storedSession.TargetUserID)
- require.Equal(t, existingUser.ID, *storedSession.TargetUserID)
- require.Equal(t, "owner@example.com", storedSession.ResolvedEmail)
- }
- func TestCreateOIDCOAuthAccountRejectsSecondEmailOutsideRegistrationSuffixWhitelist(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
- emailVerifyEnabled: true,
- emailCache: &oauthPendingFlowEmailCacheStub{
- verificationCodes: map[string]*service.VerificationCodeData{
- "foo@gmail.com": {
- Code: "135790",
- CreatedAt: time.Now().UTC(),
- ExpiresAt: time.Now().UTC().Add(15 * time.Minute),
- },
- },
- },
- settingValues: map[string]string{
- service.SettingKeyRegistrationEmailSuffixWhitelist: `["@qq.com"]`,
- service.SettingKeyRegistrationEmailDomainQuotaEnabled: "true",
- },
- })
- ctx := context.Background()
- _, err := client.User.Create().
- SetEmail("existing@gmail.com").
- SetUsername("existing-gmail-user").
- SetPasswordHash("hash").
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("suffix-whitelist-session-token").
- SetIntent("login").
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-suffix-whitelist-123").
- SetBrowserSessionKey("suffix-whitelist-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "username": "oidc_user",
- }).
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"email":"foo@gmail.com","verify_code":"135790","password":"secret-123"}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("suffix-whitelist-browser-session-key")})
- ginCtx.Request = req
- handler.CreateOIDCOAuthAccount(ginCtx)
- require.Equal(t, http.StatusBadRequest, recorder.Code)
- payload := decodeJSONBody(t, recorder)
- require.Equal(t, "EMAIL_DOMAIN_REGISTRATION_LIMIT", payload["reason"])
- count, err := client.User.Query().Where(dbuser.EmailEQ("foo@gmail.com")).Count(ctx)
- require.NoError(t, err)
- require.Zero(t, count)
- }
- // 域名限量注册开关默认关闭:白名单外域名保持 PR5423 之前的严格拒绝语义,
- // 即使该域名下还没有任何账户也不放行。
- func TestCreateOIDCOAuthAccountRejectsEmailOutsideWhitelistWhenQuotaDisabled(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
- emailVerifyEnabled: true,
- emailCache: &oauthPendingFlowEmailCacheStub{
- verificationCodes: map[string]*service.VerificationCodeData{
- "foo@gmail.com": {
- Code: "135790",
- CreatedAt: time.Now().UTC(),
- ExpiresAt: time.Now().UTC().Add(15 * time.Minute),
- },
- },
- },
- settingValues: map[string]string{
- service.SettingKeyRegistrationEmailSuffixWhitelist: `["@qq.com"]`,
- },
- })
- ctx := context.Background()
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("suffix-strict-session-token").
- SetIntent("login").
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-suffix-strict-123").
- SetBrowserSessionKey("suffix-strict-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "username": "oidc_user",
- }).
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"email":"foo@gmail.com","verify_code":"135790","password":"secret-123"}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("suffix-strict-browser-session-key")})
- ginCtx.Request = req
- handler.CreateOIDCOAuthAccount(ginCtx)
- require.Equal(t, http.StatusBadRequest, recorder.Code)
- payload := decodeJSONBody(t, recorder)
- require.Equal(t, "EMAIL_SUFFIX_NOT_ALLOWED", payload["reason"])
- count, err := client.User.Query().Where(dbuser.EmailEQ("foo@gmail.com")).Count(ctx)
- require.NoError(t, err)
- require.Zero(t, count)
- }
- func TestSendPendingOAuthVerifyCodeExistingEmailReturnsBindLoginState(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandlerWithEmailVerification(t, false, "owner@example.com", "135790")
- ctx := context.Background()
- existingUser, err := client.User.Create().
- SetEmail("owner@example.com").
- SetUsername("owner-user").
- SetPasswordHash("hash").
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("existing-email-send-code-session-token").
- SetIntent("login").
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-existing-send-code-123").
- SetBrowserSessionKey("existing-email-send-code-browser-session-key").
- SetLocalFlowState(map[string]any{
- oauthCompletionResponseKey: map[string]any{
- "step": "email_required",
- },
- }).
- SetRedirectTo("/dashboard").
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"email":"owner@example.com"}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/pending/send-verify-code", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("existing-email-send-code-browser-session-key")})
- ginCtx.Request = req
- handler.SendPendingOAuthVerifyCode(ginCtx)
- require.Equal(t, http.StatusOK, recorder.Code)
- var payload map[string]any
- require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &payload))
- require.Equal(t, "pending_session", payload["auth_result"])
- require.Equal(t, oauthPendingChoiceStep, payload["step"])
- require.Equal(t, "owner@example.com", payload["email"])
- storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
- require.NoError(t, err)
- require.Equal(t, oauthIntentLogin, storedSession.Intent)
- require.NotNil(t, storedSession.TargetUserID)
- require.Equal(t, existingUser.ID, *storedSession.TargetUserID)
- require.Equal(t, "owner@example.com", storedSession.ResolvedEmail)
- }
- func TestCreateOIDCOAuthAccountBlocksBackendModeBeforeCreatingUser(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
- emailVerifyEnabled: true,
- emailCache: &oauthPendingFlowEmailCacheStub{
- verificationCodes: map[string]*service.VerificationCodeData{
- "fresh@example.com": {
- Code: "246810",
- CreatedAt: time.Now().UTC(),
- ExpiresAt: time.Now().UTC().Add(15 * time.Minute),
- },
- },
- },
- settingValues: map[string]string{
- service.SettingKeyBackendModeEnabled: "true",
- },
- })
- ctx := context.Background()
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("create-account-backend-mode-session-token").
- SetIntent("login").
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-create-backend-mode-123").
- SetBrowserSessionKey("create-account-backend-mode-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "username": "oidc_user",
- }).
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"email":"fresh@example.com","verify_code":"246810","password":"secret-123"}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("create-account-backend-mode-browser-session-key")})
- ginCtx.Request = req
- handler.CreateOIDCOAuthAccount(ginCtx)
- require.Equal(t, http.StatusForbidden, recorder.Code)
- userCount, err := client.User.Query().Where(dbuser.EmailEQ("fresh@example.com")).Count(ctx)
- require.NoError(t, err)
- require.Zero(t, userCount)
- storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
- require.NoError(t, err)
- require.Nil(t, storedSession.ConsumedAt)
- }
- func TestLogoutClearsPendingOAuthAndBindCookies(t *testing.T) {
- handler, _ := newOAuthPendingFlowTestHandler(t, false)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/logout", bytes.NewBufferString(`{}`))
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue("pending-session-token")})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("pending-browser-key")})
- req.AddCookie(&http.Cookie{Name: oauthBindAccessTokenCookieName, Value: "bind-token"})
- ginCtx.Request = req
- handler.Logout(ginCtx)
- require.Equal(t, http.StatusOK, recorder.Code)
- require.Equal(t, -1, findCookie(recorder.Result().Cookies(), oauthPendingSessionCookieName).MaxAge)
- require.Equal(t, -1, findCookie(recorder.Result().Cookies(), oauthPendingBrowserCookieName).MaxAge)
- require.Equal(t, -1, findCookie(recorder.Result().Cookies(), oauthBindAccessTokenCookieName).MaxAge)
- }
- func TestCreateOIDCOAuthAccountRollsBackCreatedUserWhenBindingFails(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandlerWithEmailVerification(t, true, "fresh@example.com", "246810")
- ctx := context.Background()
- conflictOwner, err := client.User.Create().
- SetEmail("owner@example.com").
- SetUsername("owner-user").
- SetPasswordHash("hash").
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- _, err = client.AuthIdentity.Create().
- SetUserID(conflictOwner.ID).
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-conflict-123").
- SetMetadata(map[string]any{
- "username": "owner-user",
- }).
- Save(ctx)
- require.NoError(t, err)
- invitation, err := client.RedeemCode.Create().
- SetCode("INVITE123").
- SetType(service.RedeemTypeInvitation).
- SetStatus(service.StatusUnused).
- SetValue(0).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("create-account-conflict-session-token").
- SetIntent("login").
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-conflict-123").
- SetBrowserSessionKey("create-account-conflict-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "username": "oidc_user",
- }).
- SetRedirectTo("/profile").
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"email":"fresh@example.com","verify_code":"246810","password":"secret-123","invitation_code":"INVITE123"}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("create-account-conflict-browser-session-key")})
- ginCtx.Request = req
- handler.CreateOIDCOAuthAccount(ginCtx)
- require.Equal(t, http.StatusConflict, recorder.Code)
- userCount, err := client.User.Query().Where(dbuser.EmailEQ("fresh@example.com")).Count(ctx)
- require.NoError(t, err)
- require.Zero(t, userCount)
- storedInvitation, err := client.RedeemCode.Get(ctx, invitation.ID)
- require.NoError(t, err)
- require.Equal(t, service.StatusUnused, storedInvitation.Status)
- require.Nil(t, storedInvitation.UsedBy)
- require.Nil(t, storedInvitation.UsedAt)
- storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
- require.NoError(t, err)
- require.Nil(t, storedSession.ConsumedAt)
- }
- func TestCreateOIDCOAuthAccountRollsBackPostBindFailureBeforeIdentityCanCommit(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
- emailVerifyEnabled: true,
- emailCache: &oauthPendingFlowEmailCacheStub{
- verificationCodes: map[string]*service.VerificationCodeData{
- "fresh@example.com": {
- Code: "246810",
- CreatedAt: time.Now().UTC(),
- ExpiresAt: time.Now().UTC().Add(15 * time.Minute),
- },
- },
- },
- userRepoOptions: oauthPendingFlowUserRepoOptions{
- rejectDeleteWhileAuthIdentityExists: true,
- },
- })
- ctx := context.Background()
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("create-account-finalize-failure-session-token").
- SetIntent("login").
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-finalize-failure-123").
- SetBrowserSessionKey("create-account-finalize-failure-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "username": "oidc_user",
- }).
- SetRedirectTo("/profile").
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- pendingOAuthCreateAccountPreCommitHook = func(context.Context, *dbent.PendingAuthSession) error {
- return errors.New("forced post-bind failure")
- }
- t.Cleanup(func() {
- pendingOAuthCreateAccountPreCommitHook = nil
- })
- body := bytes.NewBufferString(`{"email":"fresh@example.com","verify_code":"246810","password":"secret-123"}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("create-account-finalize-failure-browser-session-key")})
- ginCtx.Request = req
- handler.CreateOIDCOAuthAccount(ginCtx)
- require.Equal(t, http.StatusInternalServerError, recorder.Code)
- userCount, err := client.User.Query().Where(dbuser.EmailEQ("fresh@example.com")).Count(ctx)
- require.NoError(t, err)
- require.Zero(t, userCount)
- identityCount, err := client.AuthIdentity.Query().
- Where(
- authidentity.ProviderTypeEQ("oidc"),
- authidentity.ProviderKeyEQ("https://issuer.example"),
- authidentity.ProviderSubjectEQ("oidc-finalize-failure-123"),
- ).
- Count(ctx)
- require.NoError(t, err)
- require.Zero(t, identityCount)
- storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
- require.NoError(t, err)
- require.Nil(t, storedSession.ConsumedAt)
- }
- func TestBindOIDCOAuthLoginBindsExistingUserAndConsumesSession(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandler(t, false)
- ctx := context.Background()
- passwordHash, err := handler.authService.HashPassword("secret-123")
- require.NoError(t, err)
- existingUser, err := client.User.Create().
- SetEmail("owner@example.com").
- SetUsername("owner-user").
- SetPasswordHash(passwordHash).
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("bind-login-session-token").
- SetIntent("adopt_existing_user_by_email").
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-bind-123").
- SetTargetUserID(existingUser.ID).
- SetResolvedEmail(existingUser.Email).
- SetBrowserSessionKey("bind-login-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "username": "oidc_user",
- "suggested_display_name": "Bound OIDC User",
- "suggested_avatar_url": "https://cdn.example/bound.png",
- }).
- SetRedirectTo("/profile").
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"email":"owner@example.com","password":"secret-123","adopt_display_name":false,"adopt_avatar":false}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/bind-login", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("bind-login-browser-session-key")})
- ginCtx.Request = req
- handler.BindOIDCOAuthLogin(ginCtx)
- require.Equal(t, http.StatusOK, recorder.Code)
- var payload map[string]any
- require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &payload))
- require.NotEmpty(t, payload["access_token"])
- require.NotEmpty(t, payload["refresh_token"])
- require.Equal(t, "Bearer", payload["token_type"])
- identity, err := client.AuthIdentity.Query().
- Where(
- authidentity.ProviderTypeEQ("oidc"),
- authidentity.ProviderKeyEQ("https://issuer.example"),
- authidentity.ProviderSubjectEQ("oidc-bind-123"),
- ).
- Only(ctx)
- require.NoError(t, err)
- require.Equal(t, existingUser.ID, identity.UserID)
- storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
- require.NoError(t, err)
- require.NotNil(t, storedSession.ConsumedAt)
- }
- func TestBindOIDCOAuthLoginBlocksBackendModeBeforeTokenIssue(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
- settingValues: map[string]string{
- service.SettingKeyBackendModeEnabled: "true",
- },
- })
- ctx := context.Background()
- passwordHash, err := handler.authService.HashPassword("secret-123")
- require.NoError(t, err)
- existingUser, err := client.User.Create().
- SetEmail("owner@example.com").
- SetUsername("owner-user").
- SetPasswordHash(passwordHash).
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("bind-login-backend-mode-session-token").
- SetIntent("adopt_existing_user_by_email").
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-bind-backend-mode-123").
- SetTargetUserID(existingUser.ID).
- SetResolvedEmail(existingUser.Email).
- SetBrowserSessionKey("bind-login-backend-mode-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "username": "oidc_user",
- }).
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"email":"owner@example.com","password":"secret-123"}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/bind-login", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("bind-login-backend-mode-browser-session-key")})
- ginCtx.Request = req
- handler.BindOIDCOAuthLogin(ginCtx)
- require.Equal(t, http.StatusForbidden, recorder.Code)
- identityCount, err := client.AuthIdentity.Query().
- Where(
- authidentity.ProviderTypeEQ("oidc"),
- authidentity.ProviderKeyEQ("https://issuer.example"),
- authidentity.ProviderSubjectEQ("oidc-bind-backend-mode-123"),
- ).
- Count(ctx)
- require.NoError(t, err)
- require.Zero(t, identityCount)
- storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
- require.NoError(t, err)
- require.Nil(t, storedSession.ConsumedAt)
- }
- func TestBindOIDCOAuthLoginRejectsInvalidPasswordWithoutConsumingSession(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandler(t, false)
- ctx := context.Background()
- passwordHash, err := handler.authService.HashPassword("secret-123")
- require.NoError(t, err)
- existingUser, err := client.User.Create().
- SetEmail("owner@example.com").
- SetUsername("owner-user").
- SetPasswordHash(passwordHash).
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("bind-login-invalid-password-session-token").
- SetIntent("adopt_existing_user_by_email").
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-bind-invalid-123").
- SetTargetUserID(existingUser.ID).
- SetResolvedEmail(existingUser.Email).
- SetBrowserSessionKey("bind-login-invalid-password-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "username": "oidc_user",
- "suggested_display_name": "Bound OIDC User",
- "suggested_avatar_url": "https://cdn.example/bound.png",
- }).
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"email":"owner@example.com","password":"wrong-password"}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/bind-login", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("bind-login-invalid-password-browser-session-key")})
- ginCtx.Request = req
- handler.BindOIDCOAuthLogin(ginCtx)
- require.Equal(t, http.StatusUnauthorized, recorder.Code)
- payload := decodeJSONBody(t, recorder)
- require.Equal(t, "INVALID_CREDENTIALS", payload["reason"])
- identityCount, err := client.AuthIdentity.Query().
- Where(
- authidentity.ProviderTypeEQ("oidc"),
- authidentity.ProviderKeyEQ("https://issuer.example"),
- authidentity.ProviderSubjectEQ("oidc-bind-invalid-123"),
- ).
- Count(ctx)
- require.NoError(t, err)
- require.Zero(t, identityCount)
- storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
- require.NoError(t, err)
- require.Nil(t, storedSession.ConsumedAt)
- }
- func TestBindOIDCOAuthLoginReclaimsIdentityOwnedBySoftDeletedUser(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandler(t, false)
- ctx := context.Background()
- oldOwnerHash, err := handler.authService.HashPassword("old-secret")
- require.NoError(t, err)
- oldOwner, err := client.User.Create().
- SetEmail("old-owner@example.com").
- SetUsername("old-owner").
- SetPasswordHash(oldOwnerHash).
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- identity, err := client.AuthIdentity.Create().
- SetUserID(oldOwner.ID).
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-bind-soft-deleted-123").
- SetMetadata(map[string]any{"username": "old-owner"}).
- Save(ctx)
- require.NoError(t, err)
- _, err = client.User.Delete().Where(dbuser.IDEQ(oldOwner.ID)).Exec(ctx)
- require.NoError(t, err)
- newOwnerHash, err := handler.authService.HashPassword("secret-123")
- require.NoError(t, err)
- newOwner, err := client.User.Create().
- SetEmail("owner@example.com").
- SetUsername("owner-user").
- SetPasswordHash(newOwnerHash).
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("bind-login-soft-deleted-owner-session-token").
- SetIntent("adopt_existing_user_by_email").
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-bind-soft-deleted-123").
- SetTargetUserID(newOwner.ID).
- SetResolvedEmail(newOwner.Email).
- SetBrowserSessionKey("bind-login-soft-deleted-owner-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "username": "oidc_user",
- "suggested_display_name": "Recovered OIDC User",
- }).
- SetRedirectTo("/profile").
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"email":"owner@example.com","password":"secret-123","adopt_display_name":false,"adopt_avatar":false}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/bind-login", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("bind-login-soft-deleted-owner-browser-session-key")})
- ginCtx.Request = req
- handler.BindOIDCOAuthLogin(ginCtx)
- require.Equal(t, http.StatusOK, recorder.Code)
- identity, err = client.AuthIdentity.Get(ctx, identity.ID)
- require.NoError(t, err)
- require.Equal(t, newOwner.ID, identity.UserID)
- }
- func TestBindOIDCOAuthLoginAppliesFirstBindGrantOnce(t *testing.T) {
- defaultSubAssigner := &oauthPendingFlowDefaultSubAssignerStub{}
- handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
- settingValues: map[string]string{
- service.SettingKeyAuthSourceDefaultOIDCBalance: "12.5",
- service.SettingKeyAuthSourceDefaultOIDCConcurrency: "3",
- service.SettingKeyAuthSourceDefaultOIDCSubscriptions: `[{"group_id":101,"validity_days":30}]`,
- service.SettingKeyAuthSourceDefaultOIDCGrantOnFirstBind: "true",
- },
- defaultSubAssigner: defaultSubAssigner,
- })
- ctx := context.Background()
- passwordHash, err := handler.authService.HashPassword("secret-123")
- require.NoError(t, err)
- existingUser, err := client.User.Create().
- SetEmail("owner@example.com").
- SetUsername("owner-user").
- SetPasswordHash(passwordHash).
- SetBalance(5).
- SetConcurrency(2).
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- firstSession, err := client.PendingAuthSession.Create().
- SetSessionToken("first-bind-session-token").
- SetIntent("adopt_existing_user_by_email").
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-bind-first-123").
- SetTargetUserID(existingUser.ID).
- SetResolvedEmail(existingUser.Email).
- SetBrowserSessionKey("first-bind-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "suggested_display_name": "Bound OIDC User",
- "suggested_avatar_url": "https://cdn.example/bound.png",
- }).
- SetRedirectTo("/profile").
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- firstBody := bytes.NewBufferString(`{"email":"owner@example.com","password":"secret-123","adopt_display_name":false,"adopt_avatar":false}`)
- firstRecorder := httptest.NewRecorder()
- firstGinCtx, _ := gin.CreateTestContext(firstRecorder)
- firstReq := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/bind-login", firstBody)
- firstReq.Header.Set("Content-Type", "application/json")
- firstReq.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(firstSession.SessionToken)})
- firstReq.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("first-bind-browser-session-key")})
- firstGinCtx.Request = firstReq
- handler.BindOIDCOAuthLogin(firstGinCtx)
- require.Equal(t, http.StatusOK, firstRecorder.Code)
- storedUser, err := client.User.Get(ctx, existingUser.ID)
- require.NoError(t, err)
- require.Equal(t, 17.5, storedUser.Balance)
- require.Equal(t, 5, storedUser.Concurrency)
- require.Zero(t, storedUser.TotalRecharged)
- require.Len(t, defaultSubAssigner.calls, 1)
- require.Equal(t, int64(existingUser.ID), defaultSubAssigner.calls[0].UserID)
- require.Equal(t, int64(101), defaultSubAssigner.calls[0].GroupID)
- require.Equal(t, 30, defaultSubAssigner.calls[0].ValidityDays)
- require.Equal(t, 1, countProviderGrantRecords(t, client, existingUser.ID, "oidc", "first_bind"))
- secondSession, err := client.PendingAuthSession.Create().
- SetSessionToken("second-bind-session-token").
- SetIntent("adopt_existing_user_by_email").
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-bind-second-456").
- SetTargetUserID(existingUser.ID).
- SetResolvedEmail(existingUser.Email).
- SetBrowserSessionKey("second-bind-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "suggested_display_name": "Second OIDC User",
- "suggested_avatar_url": "https://cdn.example/second.png",
- }).
- SetRedirectTo("/profile").
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- secondBody := bytes.NewBufferString(`{"email":"owner@example.com","password":"secret-123","adopt_display_name":false,"adopt_avatar":false}`)
- secondRecorder := httptest.NewRecorder()
- secondGinCtx, _ := gin.CreateTestContext(secondRecorder)
- secondReq := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/bind-login", secondBody)
- secondReq.Header.Set("Content-Type", "application/json")
- secondReq.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(secondSession.SessionToken)})
- secondReq.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("second-bind-browser-session-key")})
- secondGinCtx.Request = secondReq
- handler.BindOIDCOAuthLogin(secondGinCtx)
- require.Equal(t, http.StatusOK, secondRecorder.Code)
- storedUser, err = client.User.Get(ctx, existingUser.ID)
- require.NoError(t, err)
- require.Equal(t, 17.5, storedUser.Balance)
- require.Equal(t, 5, storedUser.Concurrency)
- require.Zero(t, storedUser.TotalRecharged)
- require.Len(t, defaultSubAssigner.calls, 1)
- require.Equal(t, 1, countProviderGrantRecords(t, client, existingUser.ID, "oidc", "first_bind"))
- }
- func TestResolvePendingOAuthTargetUserIDNormalizesLegacySpacingAndCase(t *testing.T) {
- handler, client := newOAuthPendingFlowTestHandler(t, false)
- _ = handler
- ctx := context.Background()
- existingUser, err := client.User.Create().
- SetEmail(" Owner@Example.com ").
- SetUsername("owner-user").
- SetPasswordHash("hash").
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("resolve-target-session-token").
- SetIntent("login").
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-target-123").
- SetResolvedEmail("owner@example.com").
- SetBrowserSessionKey("resolve-target-browser-session-key").
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- resolvedUserID, err := resolvePendingOAuthTargetUserID(ctx, client, session)
- require.NoError(t, err)
- require.Equal(t, existingUser.ID, resolvedUserID)
- }
- func TestBindOIDCOAuthLoginReturns2FAChallengeWhenUserHasTotp(t *testing.T) {
- totpCache := &oauthPendingFlowTotpCacheStub{}
- handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
- settingValues: map[string]string{
- service.SettingKeyTotpEnabled: "true",
- },
- totpCache: totpCache,
- totpEncryptor: oauthPendingFlowTotpEncryptorStub{},
- })
- ctx := context.Background()
- passwordHash, err := handler.authService.HashPassword("secret-123")
- require.NoError(t, err)
- totpEnabledAt := time.Now().UTC().Add(-time.Hour)
- secret := "JBSWY3DPEHPK3PXP"
- existingUser, err := client.User.Create().
- SetEmail("owner@example.com").
- SetUsername("owner-user").
- SetPasswordHash(passwordHash).
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- SetTotpEnabled(true).
- SetTotpSecretEncrypted(secret).
- SetTotpEnabledAt(totpEnabledAt).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("bind-login-2fa-session-token").
- SetIntent("adopt_existing_user_by_email").
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-bind-2fa-123").
- SetTargetUserID(existingUser.ID).
- SetResolvedEmail(existingUser.Email).
- SetBrowserSessionKey("bind-login-2fa-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "suggested_display_name": "Bound OIDC User",
- "suggested_avatar_url": "https://cdn.example/bound.png",
- }).
- SetRedirectTo("/profile").
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"email":"owner@example.com","password":"secret-123","adopt_display_name":false,"adopt_avatar":false}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/bind-login", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("bind-login-2fa-browser-session-key")})
- ginCtx.Request = req
- handler.BindOIDCOAuthLogin(ginCtx)
- require.Equal(t, http.StatusOK, recorder.Code)
- data := decodeJSONResponseData(t, recorder)
- require.Equal(t, true, data["requires_2fa"])
- require.Equal(t, "o***r@example.com", data["user_email_masked"])
- tempToken, ok := data["temp_token"].(string)
- require.True(t, ok)
- require.NotEmpty(t, tempToken)
- loginSession, err := totpCache.GetLoginSession(ctx, tempToken)
- require.NoError(t, err)
- require.NotNil(t, loginSession)
- require.NotNil(t, loginSession.PendingOAuthBind)
- require.Equal(t, session.SessionToken, loginSession.PendingOAuthBind.PendingSessionToken)
- require.Equal(t, session.BrowserSessionKey, loginSession.PendingOAuthBind.BrowserSessionKey)
- identityCount, err := client.AuthIdentity.Query().
- Where(
- authidentity.ProviderTypeEQ("oidc"),
- authidentity.ProviderKeyEQ("https://issuer.example"),
- authidentity.ProviderSubjectEQ("oidc-bind-2fa-123"),
- ).
- Count(ctx)
- require.NoError(t, err)
- require.Zero(t, identityCount)
- storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
- require.NoError(t, err)
- require.Nil(t, storedSession.ConsumedAt)
- }
- func TestLogin2FACompletesPendingOAuthBindAndConsumesSession(t *testing.T) {
- totpCache := &oauthPendingFlowTotpCacheStub{}
- defaultSubAssigner := &oauthPendingFlowDefaultSubAssignerStub{}
- handler, client := newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
- settingValues: map[string]string{
- service.SettingKeyTotpEnabled: "true",
- service.SettingKeyAuthSourceDefaultOIDCBalance: "8",
- service.SettingKeyAuthSourceDefaultOIDCConcurrency: "2",
- service.SettingKeyAuthSourceDefaultOIDCGrantOnFirstBind: "true",
- },
- defaultSubAssigner: defaultSubAssigner,
- totpCache: totpCache,
- totpEncryptor: oauthPendingFlowTotpEncryptorStub{},
- })
- ctx := context.Background()
- passwordHash, err := handler.authService.HashPassword("secret-123")
- require.NoError(t, err)
- totpEnabledAt := time.Now().UTC().Add(-time.Hour)
- secret := "JBSWY3DPEHPK3PXP"
- existingUser, err := client.User.Create().
- SetEmail("owner@example.com").
- SetUsername("owner-user").
- SetPasswordHash(passwordHash).
- SetBalance(1.5).
- SetConcurrency(4).
- SetRole(service.RoleUser).
- SetStatus(service.StatusActive).
- SetTotpEnabled(true).
- SetTotpSecretEncrypted(secret).
- SetTotpEnabledAt(totpEnabledAt).
- Save(ctx)
- require.NoError(t, err)
- session, err := client.PendingAuthSession.Create().
- SetSessionToken("login-2fa-pending-session-token").
- SetIntent("adopt_existing_user_by_email").
- SetProviderType("oidc").
- SetProviderKey("https://issuer.example").
- SetProviderSubject("oidc-login-2fa-123").
- SetTargetUserID(existingUser.ID).
- SetResolvedEmail(existingUser.Email).
- SetBrowserSessionKey("login-2fa-browser-session-key").
- SetUpstreamIdentityClaims(map[string]any{
- "suggested_display_name": "Bound OIDC User",
- "suggested_avatar_url": "https://cdn.example/bound.png",
- }).
- SetRedirectTo("/profile").
- SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
- Save(ctx)
- require.NoError(t, err)
- _, err = client.IdentityAdoptionDecision.Create().
- SetPendingAuthSessionID(session.ID).
- SetAdoptDisplayName(false).
- SetAdoptAvatar(false).
- Save(ctx)
- require.NoError(t, err)
- tempToken, err := handler.totpService.CreatePendingOAuthBindLoginSession(
- ctx,
- existingUser.ID,
- existingUser.Email,
- session.SessionToken,
- session.BrowserSessionKey,
- )
- require.NoError(t, err)
- code, err := totp.GenerateCode(secret, time.Now().UTC())
- require.NoError(t, err)
- body := bytes.NewBufferString(`{"temp_token":"` + tempToken + `","totp_code":"` + code + `"}`)
- recorder := httptest.NewRecorder()
- ginCtx, _ := gin.CreateTestContext(recorder)
- req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login/2fa", body)
- req.Header.Set("Content-Type", "application/json")
- req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
- req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue(session.BrowserSessionKey)})
- ginCtx.Request = req
- handler.Login2FA(ginCtx)
- require.Equal(t, http.StatusOK, recorder.Code)
- payload := decodeJSONResponseData(t, recorder)
- require.NotEmpty(t, payload["access_token"])
- require.NotEmpty(t, payload["refresh_token"])
- accessToken, ok := payload["access_token"].(string)
- require.True(t, ok)
- claims, err := handler.authService.ValidateToken(accessToken)
- require.NoError(t, err)
- reloadedUser, err := handler.userService.GetByID(ctx, existingUser.ID)
- require.NoError(t, err)
- require.Equal(t, reloadedUser.TokenVersion, claims.TokenVersion)
- identity, err := client.AuthIdentity.Query().
- Where(
- authidentity.ProviderTypeEQ("oidc"),
- authidentity.ProviderKeyEQ("https://issuer.example"),
- authidentity.ProviderSubjectEQ("oidc-login-2fa-123"),
- ).
- Only(ctx)
- require.NoError(t, err)
- require.Equal(t, existingUser.ID, identity.UserID)
- storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
- require.NoError(t, err)
- require.NotNil(t, storedSession.ConsumedAt)
- loginSession, err := totpCache.GetLoginSession(ctx, tempToken)
- require.NoError(t, err)
- require.Nil(t, loginSession)
- storedUser, err := client.User.Get(ctx, existingUser.ID)
- require.NoError(t, err)
- require.Equal(t, 9.5, storedUser.Balance)
- require.Equal(t, 6, storedUser.Concurrency)
- require.Equal(t, 1, countProviderGrantRecords(t, client, existingUser.ID, "oidc", "first_bind"))
- require.Empty(t, defaultSubAssigner.calls)
- }
- func newOAuthPendingFlowTestHandler(t *testing.T, invitationEnabled bool) (*AuthHandler, *dbent.Client) {
- t.Helper()
- return newOAuthPendingFlowTestHandlerWithOptions(t, invitationEnabled, false, nil)
- }
- func newOAuthPendingFlowTestHandlerWithEmailVerification(
- t *testing.T,
- invitationEnabled bool,
- email string,
- code string,
- ) (*AuthHandler, *dbent.Client) {
- t.Helper()
- cache := &oauthPendingFlowEmailCacheStub{
- verificationCodes: map[string]*service.VerificationCodeData{
- email: {
- Code: code,
- Attempts: 0,
- CreatedAt: time.Now().UTC(),
- ExpiresAt: time.Now().UTC().Add(15 * time.Minute),
- },
- },
- }
- return newOAuthPendingFlowTestHandlerWithOptions(t, invitationEnabled, true, cache)
- }
- func newOAuthPendingFlowTestHandlerWithOptions(
- t *testing.T,
- invitationEnabled bool,
- emailVerifyEnabled bool,
- emailCache service.EmailCache,
- ) (*AuthHandler, *dbent.Client) {
- return newOAuthPendingFlowTestHandlerWithDependencies(t, oauthPendingFlowTestHandlerOptions{
- invitationEnabled: invitationEnabled,
- emailVerifyEnabled: emailVerifyEnabled,
- emailCache: emailCache,
- })
- }
- type oauthPendingFlowTestHandlerOptions struct {
- invitationEnabled bool
- emailVerifyEnabled bool
- emailCache service.EmailCache
- settingValues map[string]string
- promoRepo service.PromoCodeRepository
- defaultSubAssigner service.DefaultSubscriptionAssigner
- affiliateService *service.AffiliateService
- affiliateFactory func(*dbent.Client, *service.SettingService) *service.AffiliateService
- totpCache service.TotpCache
- totpEncryptor service.SecretEncryptor
- userRepoOptions oauthPendingFlowUserRepoOptions
- }
- func newOAuthPendingFlowTestHandlerWithDependencies(
- t *testing.T,
- options oauthPendingFlowTestHandlerOptions,
- ) (*AuthHandler, *dbent.Client) {
- t.Helper()
- db, err := sql.Open("sqlite", "file:auth_oauth_pending_flow_handler?mode=memory&cache=shared")
- require.NoError(t, err)
- t.Cleanup(func() { _ = db.Close() })
- _, err = db.Exec("PRAGMA foreign_keys = ON")
- require.NoError(t, err)
- _, err = db.Exec(`
- CREATE TABLE IF NOT EXISTS user_provider_default_grants (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- user_id INTEGER NOT NULL,
- provider_type TEXT NOT NULL,
- grant_reason TEXT NOT NULL DEFAULT 'first_bind',
- created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
- UNIQUE(user_id, provider_type, grant_reason)
- )`)
- require.NoError(t, err)
- _, err = db.Exec(`
- CREATE TABLE IF NOT EXISTS user_avatars (
- user_id INTEGER PRIMARY KEY,
- storage_provider TEXT NOT NULL,
- storage_key TEXT NOT NULL DEFAULT '',
- url TEXT NOT NULL,
- content_type TEXT NOT NULL DEFAULT '',
- byte_size INTEGER NOT NULL DEFAULT 0,
- sha256 TEXT NOT NULL DEFAULT '',
- updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
- )`)
- require.NoError(t, err)
- _, err = db.Exec(`
- CREATE TABLE IF NOT EXISTS user_affiliates (
- user_id INTEGER PRIMARY KEY,
- aff_code TEXT NOT NULL UNIQUE,
- aff_code_custom BOOLEAN NOT NULL DEFAULT false,
- aff_rebate_rate_percent REAL NULL,
- inviter_id INTEGER NULL,
- aff_count INTEGER NOT NULL DEFAULT 0,
- aff_quota REAL NOT NULL DEFAULT 0,
- aff_frozen_quota REAL NOT NULL DEFAULT 0,
- aff_history_quota REAL NOT NULL DEFAULT 0,
- created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
- updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
- )`)
- require.NoError(t, err)
- drv := entsql.OpenDB(dialect.SQLite, db)
- client := enttest.NewClient(t, enttest.WithOptions(dbent.Driver(drv)))
- cfg := &config.Config{
- JWT: config.JWTConfig{
- Secret: "test-secret",
- ExpireHour: 1,
- AccessTokenExpireMinutes: 60,
- RefreshTokenExpireDays: 7,
- },
- Default: config.DefaultConfig{
- UserBalance: 0,
- UserConcurrency: 1,
- },
- }
- settingValues := map[string]string{
- service.SettingKeyRegistrationEnabled: "true",
- service.SettingKeyInvitationCodeEnabled: boolSettingValue(options.invitationEnabled),
- service.SettingKeyEmailVerifyEnabled: boolSettingValue(options.emailVerifyEnabled),
- service.SettingKeyRegistrationEmailSuffixWhitelist: "[]",
- }
- for key, value := range options.settingValues {
- settingValues[key] = value
- }
- settingSvc := service.NewSettingService(&oauthPendingFlowSettingRepoStub{values: settingValues}, cfg)
- affiliateService := options.affiliateService
- if affiliateService == nil && options.affiliateFactory != nil {
- affiliateService = options.affiliateFactory(client, settingSvc)
- }
- userRepo := &oauthPendingFlowUserRepo{
- client: client,
- options: options.userRepoOptions,
- }
- redeemRepo := &oauthPendingFlowRedeemCodeRepo{client: client}
- var promoService *service.PromoService
- if options.promoRepo != nil {
- promoService = service.NewPromoService(options.promoRepo, userRepo, nil, client, nil)
- }
- var emailService *service.EmailService
- if options.emailCache != nil {
- emailService = service.NewEmailService(&oauthPendingFlowSettingRepoStub{
- values: map[string]string{
- service.SettingKeyEmailVerifyEnabled: boolSettingValue(options.emailVerifyEnabled),
- },
- }, options.emailCache)
- }
- authSvc := service.NewAuthService(
- client,
- userRepo,
- redeemRepo,
- &oauthPendingFlowRefreshTokenCacheStub{},
- cfg,
- settingSvc,
- emailService,
- nil,
- nil,
- promoService,
- options.defaultSubAssigner,
- affiliateService,
- nil,
- )
- userSvc := service.NewUserService(userRepo, nil, nil, nil)
- var totpSvc *service.TotpService
- if options.totpCache != nil || options.totpEncryptor != nil {
- totpCache := options.totpCache
- if totpCache == nil {
- totpCache = &oauthPendingFlowTotpCacheStub{}
- }
- totpEncryptor := options.totpEncryptor
- if totpEncryptor == nil {
- totpEncryptor = oauthPendingFlowTotpEncryptorStub{}
- }
- totpSvc = service.NewTotpService(userRepo, totpEncryptor, totpCache, settingSvc, nil, nil)
- }
- return &AuthHandler{
- authService: authSvc,
- userService: userSvc,
- settingSvc: settingSvc,
- promoService: promoService,
- totpService: totpSvc,
- }, client
- }
- func boolSettingValue(v bool) string {
- if v {
- return "true"
- }
- return "false"
- }
- func boolPtr(v bool) *bool {
- return &v
- }
- type oauthPendingFlowSettingRepoStub struct {
- values map[string]string
- }
- type oauthPendingFlowPromoRepoStub struct {
- promo *service.PromoCode
- applyCalls []string
- usages []service.PromoCodeUsage
- }
- func newOAuthPendingFlowPromoRepoStub(code string, bonusAmount float64) *oauthPendingFlowPromoRepoStub {
- return &oauthPendingFlowPromoRepoStub{
- promo: &service.PromoCode{
- ID: 1,
- Code: code,
- BonusAmount: bonusAmount,
- Status: service.PromoCodeStatusActive,
- },
- }
- }
- func (r *oauthPendingFlowPromoRepoStub) Create(context.Context, *service.PromoCode) error {
- panic("unexpected Create call")
- }
- func (r *oauthPendingFlowPromoRepoStub) GetByID(context.Context, int64) (*service.PromoCode, error) {
- panic("unexpected GetByID call")
- }
- func (r *oauthPendingFlowPromoRepoStub) GetByCode(_ context.Context, code string) (*service.PromoCode, error) {
- if r.promo == nil || !strings.EqualFold(strings.TrimSpace(code), r.promo.Code) {
- return nil, service.ErrPromoCodeNotFound
- }
- clone := *r.promo
- return &clone, nil
- }
- func (r *oauthPendingFlowPromoRepoStub) GetByCodeForUpdate(ctx context.Context, code string) (*service.PromoCode, error) {
- promoCode, err := r.GetByCode(ctx, code)
- if err != nil {
- return nil, err
- }
- r.applyCalls = append(r.applyCalls, strings.TrimSpace(code))
- return promoCode, nil
- }
- func (r *oauthPendingFlowPromoRepoStub) Update(context.Context, *service.PromoCode) error {
- panic("unexpected Update call")
- }
- func (r *oauthPendingFlowPromoRepoStub) Delete(context.Context, int64) error {
- panic("unexpected Delete call")
- }
- func (r *oauthPendingFlowPromoRepoStub) List(context.Context, pagination.PaginationParams) ([]service.PromoCode, *pagination.PaginationResult, error) {
- panic("unexpected List call")
- }
- func (r *oauthPendingFlowPromoRepoStub) ListWithFilters(context.Context, pagination.PaginationParams, string, string) ([]service.PromoCode, *pagination.PaginationResult, error) {
- panic("unexpected ListWithFilters call")
- }
- func (r *oauthPendingFlowPromoRepoStub) CreateUsage(_ context.Context, usage *service.PromoCodeUsage) error {
- r.usages = append(r.usages, *usage)
- return nil
- }
- func (r *oauthPendingFlowPromoRepoStub) GetUsageByPromoCodeAndUser(context.Context, int64, int64) (*service.PromoCodeUsage, error) {
- return nil, nil
- }
- func (r *oauthPendingFlowPromoRepoStub) ListUsagesByPromoCode(context.Context, int64, pagination.PaginationParams) ([]service.PromoCodeUsage, *pagination.PaginationResult, error) {
- panic("unexpected ListUsagesByPromoCode call")
- }
- func (r *oauthPendingFlowPromoRepoStub) IncrementUsedCount(context.Context, int64) error {
- if r.promo != nil {
- r.promo.UsedCount++
- }
- return nil
- }
- func (s *oauthPendingFlowSettingRepoStub) Get(context.Context, string) (*service.Setting, error) {
- return nil, service.ErrSettingNotFound
- }
- func (s *oauthPendingFlowSettingRepoStub) GetValue(_ context.Context, key string) (string, error) {
- value, ok := s.values[key]
- if !ok {
- return "", service.ErrSettingNotFound
- }
- return value, nil
- }
- func (s *oauthPendingFlowSettingRepoStub) Set(context.Context, string, string) error {
- return nil
- }
- func (s *oauthPendingFlowSettingRepoStub) GetMultiple(_ context.Context, keys []string) (map[string]string, error) {
- result := make(map[string]string, len(keys))
- for _, key := range keys {
- if value, ok := s.values[key]; ok {
- result[key] = value
- }
- }
- return result, nil
- }
- func (s *oauthPendingFlowSettingRepoStub) SetMultiple(context.Context, map[string]string) error {
- return nil
- }
- func (s *oauthPendingFlowSettingRepoStub) GetAll(context.Context) (map[string]string, error) {
- result := make(map[string]string, len(s.values))
- for key, value := range s.values {
- result[key] = value
- }
- return result, nil
- }
- func (s *oauthPendingFlowSettingRepoStub) Delete(context.Context, string) error {
- return nil
- }
- type oauthPendingFlowRefreshTokenCacheStub struct{}
- type oauthPendingFlowEmailCacheStub struct {
- verificationCodes map[string]*service.VerificationCodeData
- }
- func (s *oauthPendingFlowEmailCacheStub) GetVerificationCode(_ context.Context, email string) (*service.VerificationCodeData, error) {
- if s == nil || s.verificationCodes == nil {
- return nil, nil
- }
- return s.verificationCodes[email], nil
- }
- func (s *oauthPendingFlowEmailCacheStub) SetVerificationCode(_ context.Context, email string, data *service.VerificationCodeData, _ time.Duration) error {
- if s.verificationCodes == nil {
- s.verificationCodes = map[string]*service.VerificationCodeData{}
- }
- s.verificationCodes[email] = data
- return nil
- }
- func (s *oauthPendingFlowEmailCacheStub) DeleteVerificationCode(_ context.Context, email string) error {
- delete(s.verificationCodes, email)
- return nil
- }
- func (s *oauthPendingFlowEmailCacheStub) GetNotifyVerifyCode(context.Context, string) (*service.VerificationCodeData, error) {
- return nil, nil
- }
- func (s *oauthPendingFlowEmailCacheStub) SetNotifyVerifyCode(context.Context, string, *service.VerificationCodeData, time.Duration) error {
- return nil
- }
- func (s *oauthPendingFlowEmailCacheStub) DeleteNotifyVerifyCode(context.Context, string) error {
- return nil
- }
- func (s *oauthPendingFlowEmailCacheStub) GetPasswordResetToken(context.Context, string) (*service.PasswordResetTokenData, error) {
- return nil, nil
- }
- func (s *oauthPendingFlowEmailCacheStub) SetPasswordResetToken(context.Context, string, *service.PasswordResetTokenData, time.Duration) error {
- return nil
- }
- func (s *oauthPendingFlowEmailCacheStub) DeletePasswordResetToken(context.Context, string) error {
- return nil
- }
- func (s *oauthPendingFlowEmailCacheStub) IsPasswordResetEmailInCooldown(context.Context, string) bool {
- return false
- }
- func (s *oauthPendingFlowEmailCacheStub) SetPasswordResetEmailCooldown(context.Context, string, time.Duration) error {
- return nil
- }
- func (s *oauthPendingFlowEmailCacheStub) IncrNotifyCodeUserRate(context.Context, int64, time.Duration) (int64, error) {
- return 0, nil
- }
- func (s *oauthPendingFlowEmailCacheStub) GetNotifyCodeUserRate(context.Context, int64) (int64, error) {
- return 0, nil
- }
- func (s *oauthPendingFlowRefreshTokenCacheStub) StoreRefreshToken(context.Context, string, *service.RefreshTokenData, time.Duration) error {
- return nil
- }
- func (s *oauthPendingFlowRefreshTokenCacheStub) GetRefreshToken(context.Context, string) (*service.RefreshTokenData, error) {
- return nil, service.ErrRefreshTokenNotFound
- }
- func (s *oauthPendingFlowRefreshTokenCacheStub) DeleteRefreshToken(context.Context, string) error {
- return nil
- }
- func (s *oauthPendingFlowRefreshTokenCacheStub) DeleteUserRefreshTokens(context.Context, int64) error {
- return nil
- }
- func (s *oauthPendingFlowRefreshTokenCacheStub) DeleteTokenFamily(context.Context, string) error {
- return nil
- }
- func (s *oauthPendingFlowRefreshTokenCacheStub) AddToUserTokenSet(context.Context, int64, string, time.Duration) error {
- return nil
- }
- func (s *oauthPendingFlowRefreshTokenCacheStub) AddToFamilyTokenSet(context.Context, string, string, time.Duration) error {
- return nil
- }
- func (s *oauthPendingFlowRefreshTokenCacheStub) GetUserTokenHashes(context.Context, int64) ([]string, error) {
- return nil, nil
- }
- func (s *oauthPendingFlowRefreshTokenCacheStub) GetFamilyTokenHashes(context.Context, string) ([]string, error) {
- return nil, nil
- }
- func (s *oauthPendingFlowRefreshTokenCacheStub) IsTokenInFamily(context.Context, string, string) (bool, error) {
- return false, nil
- }
- type oauthPendingFlowRedeemCodeRepo struct {
- client *dbent.Client
- }
- func (r *oauthPendingFlowRedeemCodeRepo) Create(context.Context, *service.RedeemCode) error {
- panic("unexpected Create call")
- }
- func (r *oauthPendingFlowRedeemCodeRepo) CreateBatch(context.Context, []service.RedeemCode) error {
- panic("unexpected CreateBatch call")
- }
- func (r *oauthPendingFlowRedeemCodeRepo) GetByID(context.Context, int64) (*service.RedeemCode, error) {
- panic("unexpected GetByID call")
- }
- func (r *oauthPendingFlowRedeemCodeRepo) GetByCode(ctx context.Context, code string) (*service.RedeemCode, error) {
- entity, err := r.client.RedeemCode.Query().Where(redeemcode.CodeEQ(code)).Only(ctx)
- if err != nil {
- if dbent.IsNotFound(err) {
- return nil, service.ErrRedeemCodeNotFound
- }
- return nil, err
- }
- notes := ""
- if entity.Notes != nil {
- notes = *entity.Notes
- }
- return &service.RedeemCode{
- ID: entity.ID,
- Code: entity.Code,
- Type: entity.Type,
- Value: entity.Value,
- Status: entity.Status,
- UsedBy: entity.UsedBy,
- UsedAt: entity.UsedAt,
- Notes: notes,
- CreatedAt: entity.CreatedAt,
- GroupID: entity.GroupID,
- ValidityDays: entity.ValidityDays,
- }, nil
- }
- func (r *oauthPendingFlowRedeemCodeRepo) Update(ctx context.Context, code *service.RedeemCode) error {
- if code == nil {
- return nil
- }
- update := r.client.RedeemCode.UpdateOneID(code.ID).
- SetCode(code.Code).
- SetType(code.Type).
- SetValue(code.Value).
- SetStatus(code.Status).
- SetNotes(code.Notes).
- SetValidityDays(code.ValidityDays)
- if code.UsedBy != nil {
- update = update.SetUsedBy(*code.UsedBy)
- } else {
- update = update.ClearUsedBy()
- }
- if code.UsedAt != nil {
- update = update.SetUsedAt(*code.UsedAt)
- } else {
- update = update.ClearUsedAt()
- }
- if code.GroupID != nil {
- update = update.SetGroupID(*code.GroupID)
- } else {
- update = update.ClearGroupID()
- }
- _, err := update.Save(ctx)
- return err
- }
- func (r *oauthPendingFlowRedeemCodeRepo) BatchUpdate(context.Context, []int64, service.RedeemCodeBatchUpdateFields) (int64, error) {
- panic("unexpected BatchUpdate call")
- }
- func (r *oauthPendingFlowRedeemCodeRepo) Delete(context.Context, int64) error {
- panic("unexpected Delete call")
- }
- func (r *oauthPendingFlowRedeemCodeRepo) Use(ctx context.Context, id, userID int64) error {
- affected, err := r.client.RedeemCode.Update().
- Where(redeemcode.IDEQ(id), redeemcode.StatusEQ(service.StatusUnused)).
- SetStatus(service.StatusUsed).
- SetUsedBy(userID).
- SetUsedAt(time.Now().UTC()).
- Save(ctx)
- if err != nil {
- return err
- }
- if affected == 0 {
- return service.ErrRedeemCodeUsed
- }
- return nil
- }
- func (r *oauthPendingFlowRedeemCodeRepo) List(context.Context, pagination.PaginationParams) ([]service.RedeemCode, *pagination.PaginationResult, error) {
- panic("unexpected List call")
- }
- func (r *oauthPendingFlowRedeemCodeRepo) ListWithFilters(context.Context, pagination.PaginationParams, string, string, string) ([]service.RedeemCode, *pagination.PaginationResult, error) {
- panic("unexpected ListWithFilters call")
- }
- func (r *oauthPendingFlowRedeemCodeRepo) ListByUser(context.Context, int64, int) ([]service.RedeemCode, error) {
- panic("unexpected ListByUser call")
- }
- func (r *oauthPendingFlowRedeemCodeRepo) ListByUserPaginated(context.Context, int64, pagination.PaginationParams, string) ([]service.RedeemCode, *pagination.PaginationResult, error) {
- panic("unexpected ListByUserPaginated call")
- }
- func (r *oauthPendingFlowRedeemCodeRepo) SumPositiveBalanceByUser(context.Context, int64) (float64, error) {
- panic("unexpected SumPositiveBalanceByUser call")
- }
- func decodeJSONResponseData(t *testing.T, recorder *httptest.ResponseRecorder) map[string]any {
- t.Helper()
- var envelope struct {
- Data map[string]any `json:"data"`
- }
- require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &envelope))
- return envelope.Data
- }
- func decodeJSONBody(t *testing.T, recorder *httptest.ResponseRecorder) map[string]any {
- t.Helper()
- var payload map[string]any
- require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &payload))
- return payload
- }
- type oauthPendingFlowAvatarRecord struct {
- StorageProvider string
- URL string
- }
- func loadUserAvatarRecord(t *testing.T, client *dbent.Client, userID int64) *oauthPendingFlowAvatarRecord {
- t.Helper()
- var rows entsql.Rows
- err := client.Driver().Query(
- context.Background(),
- `SELECT storage_provider, url FROM user_avatars WHERE user_id = ?`,
- []any{userID},
- &rows,
- )
- require.NoError(t, err)
- defer func() { _ = rows.Close() }()
- if !rows.Next() {
- require.NoError(t, rows.Err())
- return nil
- }
- var record oauthPendingFlowAvatarRecord
- require.NoError(t, rows.Scan(&record.StorageProvider, &record.URL))
- require.NoError(t, rows.Err())
- return &record
- }
- func countProviderGrantRecords(
- t *testing.T,
- client *dbent.Client,
- userID int64,
- providerType string,
- grantReason string,
- ) int {
- t.Helper()
- var rows entsql.Rows
- err := client.Driver().Query(
- context.Background(),
- `SELECT COUNT(*) FROM user_provider_default_grants WHERE user_id = ? AND provider_type = ? AND grant_reason = ?`,
- []any{userID, providerType, grantReason},
- &rows,
- )
- require.NoError(t, err)
- defer func() { _ = rows.Close() }()
- require.True(t, rows.Next())
- var count int
- require.NoError(t, rows.Scan(&count))
- require.False(t, rows.Next())
- return count
- }
- type oauthPendingFlowUserRepo struct {
- client *dbent.Client
- options oauthPendingFlowUserRepoOptions
- }
- var _ service.RegistrationEmailDomainRepository = (*oauthPendingFlowUserRepo)(nil)
- type oauthPendingFlowUserRepoOptions struct {
- rejectDeleteWhileAuthIdentityExists bool
- }
- func (r *oauthPendingFlowUserRepo) Create(ctx context.Context, user *service.User) error {
- entity, err := r.client.User.Create().
- SetEmail(user.Email).
- SetUsername(user.Username).
- SetNotes(user.Notes).
- SetPasswordHash(user.PasswordHash).
- SetRole(user.Role).
- SetBalance(user.Balance).
- SetConcurrency(user.Concurrency).
- SetStatus(user.Status).
- SetNillableTotpSecretEncrypted(user.TotpSecretEncrypted).
- SetTotpEnabled(user.TotpEnabled).
- SetNillableTotpEnabledAt(user.TotpEnabledAt).
- SetTotalRecharged(user.TotalRecharged).
- SetSignupSource(user.SignupSource).
- SetNillableLastLoginAt(user.LastLoginAt).
- SetNillableLastActiveAt(user.LastActiveAt).
- Save(ctx)
- if err != nil {
- return err
- }
- user.ID = entity.ID
- user.CreatedAt = entity.CreatedAt
- user.UpdatedAt = entity.UpdatedAt
- return nil
- }
- func (r *oauthPendingFlowUserRepo) CreateWithEmailAliasGuard(ctx context.Context, user *service.User) error {
- aliasExists, err := r.ExistsByEmailAlias(ctx, user.Email)
- if err != nil {
- return err
- }
- if aliasExists {
- return service.ErrEmailExists
- }
- return r.Create(ctx, user)
- }
- func (r *oauthPendingFlowUserRepo) CountUsersByEmailDomain(ctx context.Context, domain string) (int, error) {
- domain = service.NormalizeRegistrationEmailDomain(domain)
- if domain == "" {
- return 0, nil
- }
- emails, err := r.client.User.Query().Select(dbuser.FieldEmail).Strings(ctx)
- if err != nil {
- return 0, err
- }
- count := 0
- for _, email := range emails {
- if service.RegistrationEmailDomain(email) == domain {
- count++
- }
- }
- return count, nil
- }
- func (r *oauthPendingFlowUserRepo) CreateWithEmailAliasGuardAndDomainLimit(ctx context.Context, user *service.User, domain string) error {
- count, err := r.CountUsersByEmailDomain(ctx, domain)
- if err != nil {
- return err
- }
- if count > 0 {
- return service.ErrEmailDomainRegistrationLimit
- }
- return r.CreateWithEmailAliasGuard(ctx, user)
- }
- func (r *oauthPendingFlowUserRepo) GetByID(ctx context.Context, id int64) (*service.User, error) {
- entity, err := r.client.User.Get(ctx, id)
- if err != nil {
- if dbent.IsNotFound(err) {
- return nil, service.ErrUserNotFound
- }
- return nil, err
- }
- return oauthPendingFlowServiceUser(entity), nil
- }
- func (r *oauthPendingFlowUserRepo) GetByEmail(ctx context.Context, email string) (*service.User, error) {
- entity, err := r.client.User.Query().Where(dbuser.EmailEQ(email)).Only(ctx)
- if err != nil {
- if dbent.IsNotFound(err) {
- return nil, service.ErrUserNotFound
- }
- return nil, err
- }
- return oauthPendingFlowServiceUser(entity), nil
- }
- func (r *oauthPendingFlowUserRepo) GetFirstAdmin(context.Context) (*service.User, error) {
- panic("unexpected GetFirstAdmin call")
- }
- func (r *oauthPendingFlowUserRepo) Update(ctx context.Context, user *service.User, fields service.UserUpdateFields) error {
- entity, err := r.client.User.UpdateOneID(user.ID).
- SetEmail(user.Email).
- SetUsername(user.Username).
- SetNotes(user.Notes).
- SetPasswordHash(user.PasswordHash).
- SetRole(user.Role).
- SetBalance(user.Balance).
- SetConcurrency(user.Concurrency).
- SetStatus(user.Status).
- SetNillableTotpSecretEncrypted(user.TotpSecretEncrypted).
- SetTotpEnabled(user.TotpEnabled).
- SetNillableTotpEnabledAt(user.TotpEnabledAt).
- SetTotalRecharged(user.TotalRecharged).
- SetSignupSource(user.SignupSource).
- SetNillableLastLoginAt(user.LastLoginAt).
- SetNillableLastActiveAt(user.LastActiveAt).
- Save(ctx)
- if err != nil {
- return err
- }
- user.UpdatedAt = entity.UpdatedAt
- return nil
- }
- func (r *oauthPendingFlowUserRepo) UpdateUserLastActiveAt(ctx context.Context, userID int64, activeAt time.Time) error {
- return r.client.User.UpdateOneID(userID).SetLastActiveAt(activeAt).Exec(ctx)
- }
- func (r *oauthPendingFlowUserRepo) Delete(ctx context.Context, id int64) error {
- if r.options.rejectDeleteWhileAuthIdentityExists {
- count, err := r.client.AuthIdentity.Query().Where(authidentity.UserIDEQ(id)).Count(ctx)
- if err != nil {
- return err
- }
- if count > 0 {
- return errors.New("cannot delete user while auth identities still exist")
- }
- }
- return r.client.User.DeleteOneID(id).Exec(ctx)
- }
- func (r *oauthPendingFlowUserRepo) GetUserAvatar(ctx context.Context, userID int64) (*service.UserAvatar, error) {
- driver := r.client.Driver()
- if tx := dbent.TxFromContext(ctx); tx != nil {
- driver = tx.Client().Driver()
- }
- var rows entsql.Rows
- if err := driver.Query(
- ctx,
- `SELECT storage_provider, storage_key, url, content_type, byte_size, sha256 FROM user_avatars WHERE user_id = ?`,
- []any{userID},
- &rows,
- ); err != nil {
- return nil, err
- }
- defer func() { _ = rows.Close() }()
- if !rows.Next() {
- return nil, rows.Err()
- }
- var avatar service.UserAvatar
- if err := rows.Scan(
- &avatar.StorageProvider,
- &avatar.StorageKey,
- &avatar.URL,
- &avatar.ContentType,
- &avatar.ByteSize,
- &avatar.SHA256,
- ); err != nil {
- return nil, err
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
- return &avatar, nil
- }
- func (r *oauthPendingFlowUserRepo) UpsertUserAvatar(ctx context.Context, userID int64, input service.UpsertUserAvatarInput) (*service.UserAvatar, error) {
- driver := r.client.Driver()
- if tx := dbent.TxFromContext(ctx); tx != nil {
- driver = tx.Client().Driver()
- }
- var result entsql.Result
- if err := driver.Exec(
- ctx,
- `INSERT INTO user_avatars (user_id, storage_provider, storage_key, url, content_type, byte_size, sha256, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
- ON CONFLICT(user_id) DO UPDATE SET
- storage_provider = excluded.storage_provider,
- storage_key = excluded.storage_key,
- url = excluded.url,
- content_type = excluded.content_type,
- byte_size = excluded.byte_size,
- sha256 = excluded.sha256,
- updated_at = CURRENT_TIMESTAMP`,
- []any{
- userID,
- input.StorageProvider,
- input.StorageKey,
- input.URL,
- input.ContentType,
- input.ByteSize,
- input.SHA256,
- },
- &result,
- ); err != nil {
- return nil, err
- }
- return &service.UserAvatar{
- StorageProvider: input.StorageProvider,
- StorageKey: input.StorageKey,
- URL: input.URL,
- ContentType: input.ContentType,
- ByteSize: input.ByteSize,
- SHA256: input.SHA256,
- }, nil
- }
- func (r *oauthPendingFlowUserRepo) DeleteUserAvatar(ctx context.Context, userID int64) error {
- driver := r.client.Driver()
- if tx := dbent.TxFromContext(ctx); tx != nil {
- driver = tx.Client().Driver()
- }
- var result entsql.Result
- return driver.Exec(ctx, `DELETE FROM user_avatars WHERE user_id = ?`, []any{userID}, &result)
- }
- func (r *oauthPendingFlowUserRepo) List(context.Context, pagination.PaginationParams) ([]service.User, *pagination.PaginationResult, error) {
- panic("unexpected List call")
- }
- func (r *oauthPendingFlowUserRepo) ListWithFilters(context.Context, pagination.PaginationParams, service.UserListFilters) ([]service.User, *pagination.PaginationResult, error) {
- panic("unexpected ListWithFilters call")
- }
- func (r *oauthPendingFlowUserRepo) UpdateBalance(ctx context.Context, userID int64, amount float64) error {
- client := r.client
- if tx := dbent.TxFromContext(ctx); tx != nil {
- client = tx.Client()
- }
- return client.User.UpdateOneID(userID).AddBalance(amount).Exec(ctx)
- }
- func (r *oauthPendingFlowUserRepo) DeductBalance(context.Context, int64, float64) error {
- panic("unexpected DeductBalance call")
- }
- func (r *oauthPendingFlowUserRepo) AdjustBalance(ctx context.Context, id int64, delta float64) (service.BalanceChange, error) {
- panic("unexpected AdjustBalance call")
- }
- func (r *oauthPendingFlowUserRepo) SetBalance(ctx context.Context, id int64, value float64) (service.BalanceChange, error) {
- panic("unexpected SetBalance call")
- }
- func (r *oauthPendingFlowUserRepo) UpdateConcurrency(context.Context, int64, int) error {
- panic("unexpected UpdateConcurrency call")
- }
- func (r *oauthPendingFlowUserRepo) BatchSetConcurrency(context.Context, []int64, int) (int, error) {
- panic("unexpected BatchSetConcurrency call")
- }
- func (r *oauthPendingFlowUserRepo) BatchAddConcurrency(context.Context, []int64, int) (int, error) {
- panic("unexpected BatchAddConcurrency call")
- }
- func (r *oauthPendingFlowUserRepo) BatchUpdateLimits(context.Context, []int64, *int, *int) (int, error) {
- panic("unexpected BatchUpdateLimits call")
- }
- func (r *oauthPendingFlowUserRepo) GetLatestUsedAtByUserIDs(context.Context, []int64) (map[int64]*time.Time, error) {
- return map[int64]*time.Time{}, nil
- }
- func (r *oauthPendingFlowUserRepo) GetLatestUsedAtByUserID(context.Context, int64) (*time.Time, error) {
- return nil, nil
- }
- func (r *oauthPendingFlowUserRepo) ExistsByEmail(ctx context.Context, email string) (bool, error) {
- count, err := r.client.User.Query().Where(dbuser.EmailEQ(email)).Count(ctx)
- return count > 0, err
- }
- func (r *oauthPendingFlowUserRepo) ExistsByEmailAlias(ctx context.Context, email string) (bool, error) {
- identity := service.NormalizeEmailForAliasDedup(email)
- emails, err := r.client.User.Query().Select(dbuser.FieldEmail).Strings(ctx)
- if err != nil {
- return false, err
- }
- for _, stored := range emails {
- if service.NormalizeEmailForAliasDedup(stored) == identity {
- return true, nil
- }
- }
- return false, nil
- }
- func (r *oauthPendingFlowUserRepo) RemoveGroupFromAllowedGroups(context.Context, int64) (int64, error) {
- panic("unexpected RemoveGroupFromAllowedGroups call")
- }
- func (r *oauthPendingFlowUserRepo) AddGroupToAllowedGroups(context.Context, int64, int64) error {
- panic("unexpected AddGroupToAllowedGroups call")
- }
- func (r *oauthPendingFlowUserRepo) RemoveGroupFromUserAllowedGroups(context.Context, int64, int64) error {
- panic("unexpected RemoveGroupFromUserAllowedGroups call")
- }
- func (r *oauthPendingFlowUserRepo) ListUserAuthIdentities(ctx context.Context, userID int64) ([]service.UserAuthIdentityRecord, error) {
- identities, err := r.client.AuthIdentity.Query().
- Where(authidentity.UserIDEQ(userID)).
- All(ctx)
- if err != nil {
- return nil, err
- }
- records := make([]service.UserAuthIdentityRecord, 0, len(identities))
- for _, identity := range identities {
- if identity == nil {
- continue
- }
- records = append(records, service.UserAuthIdentityRecord{
- ProviderType: identity.ProviderType,
- ProviderKey: identity.ProviderKey,
- ProviderSubject: identity.ProviderSubject,
- VerifiedAt: identity.VerifiedAt,
- Issuer: identity.Issuer,
- Metadata: identity.Metadata,
- CreatedAt: identity.CreatedAt,
- UpdatedAt: identity.UpdatedAt,
- })
- }
- return records, nil
- }
- func (r *oauthPendingFlowUserRepo) UnbindUserAuthProvider(context.Context, int64, string) error {
- panic("unexpected UnbindUserAuthProvider call")
- }
- func (r *oauthPendingFlowUserRepo) UpdateTotpSecret(ctx context.Context, userID int64, encryptedSecret *string) error {
- update := r.client.User.UpdateOneID(userID)
- if encryptedSecret == nil {
- update = update.ClearTotpSecretEncrypted()
- } else {
- update = update.SetTotpSecretEncrypted(*encryptedSecret)
- }
- return update.Exec(ctx)
- }
- func (r *oauthPendingFlowUserRepo) EnableTotp(ctx context.Context, userID int64) error {
- return r.client.User.UpdateOneID(userID).
- SetTotpEnabled(true).
- SetTotpEnabledAt(time.Now().UTC()).
- Exec(ctx)
- }
- func (r *oauthPendingFlowUserRepo) DisableTotp(ctx context.Context, userID int64) error {
- return r.client.User.UpdateOneID(userID).
- SetTotpEnabled(false).
- ClearTotpSecretEncrypted().
- ClearTotpEnabledAt().
- Exec(ctx)
- }
- func (r *oauthPendingFlowUserRepo) GetByIDIncludeDeleted(ctx context.Context, id int64) (*service.User, error) {
- return r.GetByID(ctx, id)
- }
- func oauthPendingFlowServiceUser(entity *dbent.User) *service.User {
- if entity == nil {
- return nil
- }
- return &service.User{
- ID: entity.ID,
- Email: entity.Email,
- Username: entity.Username,
- Notes: entity.Notes,
- PasswordHash: entity.PasswordHash,
- Role: entity.Role,
- Balance: entity.Balance,
- Concurrency: entity.Concurrency,
- Status: entity.Status,
- SignupSource: entity.SignupSource,
- LastLoginAt: entity.LastLoginAt,
- LastActiveAt: entity.LastActiveAt,
- TotpSecretEncrypted: entity.TotpSecretEncrypted,
- TotpEnabled: entity.TotpEnabled,
- TotpEnabledAt: entity.TotpEnabledAt,
- TotalRecharged: entity.TotalRecharged,
- CreatedAt: entity.CreatedAt,
- UpdatedAt: entity.UpdatedAt,
- }
- }
- type oauthPendingFlowDefaultSubAssignerStub struct {
- calls []service.AssignSubscriptionInput
- }
- func (s *oauthPendingFlowDefaultSubAssignerStub) AssignOrExtendSubscription(
- _ context.Context,
- input *service.AssignSubscriptionInput,
- ) (*service.UserSubscription, bool, error) {
- if input != nil {
- s.calls = append(s.calls, *input)
- }
- return nil, false, nil
- }
- type oauthPendingFlowTotpCacheStub struct {
- setupSessions map[int64]*service.TotpSetupSession
- loginSessions map[string]*service.TotpLoginSession
- verifyAttempts map[int64]int
- }
- func (s *oauthPendingFlowTotpCacheStub) GetSetupSession(_ context.Context, userID int64) (*service.TotpSetupSession, error) {
- if s == nil || s.setupSessions == nil {
- return nil, nil
- }
- return s.setupSessions[userID], nil
- }
- func (s *oauthPendingFlowTotpCacheStub) SetSetupSession(_ context.Context, userID int64, session *service.TotpSetupSession, _ time.Duration) error {
- if s.setupSessions == nil {
- s.setupSessions = map[int64]*service.TotpSetupSession{}
- }
- s.setupSessions[userID] = session
- return nil
- }
- func (s *oauthPendingFlowTotpCacheStub) DeleteSetupSession(_ context.Context, userID int64) error {
- delete(s.setupSessions, userID)
- return nil
- }
- func (s *oauthPendingFlowTotpCacheStub) GetLoginSession(_ context.Context, tempToken string) (*service.TotpLoginSession, error) {
- if s == nil || s.loginSessions == nil {
- return nil, nil
- }
- return s.loginSessions[tempToken], nil
- }
- func (s *oauthPendingFlowTotpCacheStub) SetLoginSession(_ context.Context, tempToken string, session *service.TotpLoginSession, _ time.Duration) error {
- if s.loginSessions == nil {
- s.loginSessions = map[string]*service.TotpLoginSession{}
- }
- s.loginSessions[tempToken] = session
- return nil
- }
- func (s *oauthPendingFlowTotpCacheStub) DeleteLoginSession(_ context.Context, tempToken string) error {
- delete(s.loginSessions, tempToken)
- return nil
- }
- func (s *oauthPendingFlowTotpCacheStub) IncrementVerifyAttempts(_ context.Context, userID int64) (int, error) {
- if s.verifyAttempts == nil {
- s.verifyAttempts = map[int64]int{}
- }
- s.verifyAttempts[userID]++
- return s.verifyAttempts[userID], nil
- }
- func (s *oauthPendingFlowTotpCacheStub) GetVerifyAttempts(_ context.Context, userID int64) (int, error) {
- if s == nil || s.verifyAttempts == nil {
- return 0, nil
- }
- return s.verifyAttempts[userID], nil
- }
- func (s *oauthPendingFlowTotpCacheStub) ClearVerifyAttempts(_ context.Context, userID int64) error {
- delete(s.verifyAttempts, userID)
- return nil
- }
- func (s *oauthPendingFlowTotpCacheStub) SetStepUpGrant(_ context.Context, _ int64, _ string, _ time.Duration) error {
- return nil
- }
- func (s *oauthPendingFlowTotpCacheStub) HasStepUpGrant(_ context.Context, _ int64, _ string) (bool, error) {
- return false, nil
- }
- type oauthPendingFlowTotpEncryptorStub struct{}
- func (oauthPendingFlowTotpEncryptorStub) Encrypt(plaintext string) (string, error) {
- return plaintext, nil
- }
- func (oauthPendingFlowTotpEncryptorStub) Decrypt(ciphertext string) (string, error) {
- return ciphertext, nil
- }
|