From b3b2f688a7e297274f0478537cf68f1b614c28a2 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Fri, 13 Nov 2026 17:25:10 -0600 Subject: [PATCH 1/3] fix(magiclink): store the link in the user's environment /send built its token with account.NewVerification, which leaves the environment empty. The SQL stores hold env_id to a foreign key, so the insert failed and every send for a real account returned a 500. Unknown addresses still got a 200, which hid it. The memory store doesn't enforce the key, so the tests never saw it. The token now takes the user's environment, the way email verification already does. Co-Authored-By: Claude Opus 5.5 --- plugins/magiclink/plugin.go | 5 +++++ plugins/magiclink/sendverify_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/plugins/magiclink/plugin.go b/plugins/magiclink/plugin.go index 702302e2..44e2626c 100644 --- a/plugins/magiclink/plugin.go +++ b/plugins/magiclink/plugin.go @@ -294,6 +294,11 @@ func (p *Plugin) handleSend(ctx forge.Context, req *SendRequest) (*SendResponse, if err != nil { return nil, middleware.InternalError(ctx, fmt.Errorf("failed to create magic link token: %w", err)) } + // NewVerification leaves the environment empty, and the SQL stores hold + // env_id to a foreign key, so an empty one fails the insert and every + // send for a real account is a 500. The link lives in the user's own + // environment. + v.EnvID = u.EnvID if err := p.store.CreateVerification(ctx.Context(), v); err != nil { return nil, middleware.InternalError(ctx, fmt.Errorf("failed to create magic link: %w", err)) diff --git a/plugins/magiclink/sendverify_test.go b/plugins/magiclink/sendverify_test.go index 1e4761a3..a45e69c1 100644 --- a/plugins/magiclink/sendverify_test.go +++ b/plugins/magiclink/sendverify_test.go @@ -10,6 +10,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/xraph/forge" + + "github.com/xraph/authsome/id" ) // TestMagicLink_SendThenVerify_Succeeds is the end-to-end flow: /send must @@ -65,3 +67,29 @@ func TestMagicLink_Send_UnknownEmail_UniformSuccessNoLink(t *testing.T) { require.Equal(t, http.StatusOK, rec.Code, "send must return a uniform success even for unknown emails; body=%s", rec.Body.String()) assert.Empty(t, mailer.sent, "no magic link should be sent to an unregistered email") } + +// TestMagicLink_Send_StoresUserEnvironment pins the token to the user's +// environment. The SQL stores hold env_id to a foreign key, so a token +// saved with an empty one fails the insert and /send returns a 500 for +// every real account. The memory store doesn't enforce the key, so check +// the field itself. +func TestMagicLink_Send_StoresUserEnvironment(t *testing.T) { + p, s, mailer := newTestPlugin(t) + u := createTestUser(t, s) + u.EnvID = id.NewEnvironmentID() + require.NoError(t, s.UpdateUser(context.Background(), u)) + + mux := forge.NewRouter() + require.NoError(t, p.RegisterRoutes(mux)) + + req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/v1/magic-link/send", jsonBody(t, map[string]string{"email": u.Email})) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + mux.Handler().ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code, "send body=%s", rec.Body.String()) + require.Len(t, mailer.sent, 1) + + v, err := s.GetVerification(context.Background(), mailer.sent[0].Token) + require.NoError(t, err) + assert.Equal(t, u.EnvID.String(), v.EnvID.String(), "the link must be stored in the user's environment") +} From 4f9537fdb3940e6baaadde29ba8e01f65a2b6226 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Fri, 13 Nov 2026 17:31:50 -0600 Subject: [PATCH 2/3] style(mfa): group test imports the way goimports wants 2255356c left two mfa tests with imports out of goimports order, so the Format check fails on main and on every PR. Imports only. Co-Authored-By: Claude Opus 5.5 --- plugins/mfa/plugin_test.go | 3 ++- plugins/mfa/verify_session_test.go | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/plugins/mfa/plugin_test.go b/plugins/mfa/plugin_test.go index 2e2a0636..773ff9a1 100644 --- a/plugins/mfa/plugin_test.go +++ b/plugins/mfa/plugin_test.go @@ -4,12 +4,13 @@ import ( "bytes" "context" "encoding/json" - "github.com/pquerna/otp/totp" "net/http" "net/http/httptest" "testing" "time" + "github.com/pquerna/otp/totp" + log "github.com/xraph/go-utils/log" "github.com/stretchr/testify/assert" diff --git a/plugins/mfa/verify_session_test.go b/plugins/mfa/verify_session_test.go index 41a2f913..e03cb95b 100644 --- a/plugins/mfa/verify_session_test.go +++ b/plugins/mfa/verify_session_test.go @@ -10,9 +10,10 @@ import ( "time" "github.com/pquerna/otp/totp" - "github.com/xraph/authsome/session" "github.com/xraph/forge" + "github.com/xraph/authsome/session" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" From 3fe16441538e5a5f3c57dda06da85fa4337c101d Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Fri, 13 Nov 2026 17:44:00 -0600 Subject: [PATCH 3/3] style: clear the golangci-lint findings on main The mfa and organization changes left eight findings that fail Lint on main and every PR. None changes behaviour: - organization: check the notification plugin's type assertion, and name authorizeInvitationChange's results. - mfa: stop the SMS override's errors shadowing the handler's err. - mfa tests: drop the dead first sid, and the parameters that only ever got one value (the rate limit, the enrolled phone), which become constants. - organization tests: the invite helper's result was never used. Co-Authored-By: Claude Opus 5.5 --- plugins/mfa/plugin.go | 6 ++--- plugins/mfa/ratelimit_test.go | 27 ++++++++++--------- plugins/mfa/verify_session_test.go | 25 +++++++++-------- plugins/organization/handlers.go | 6 ++--- .../organization/invitation_accept_test.go | 3 +-- plugins/organization/service.go | 4 ++- 6 files changed, 39 insertions(+), 32 deletions(-) diff --git a/plugins/mfa/plugin.go b/plugins/mfa/plugin.go index a95d74aa..cb5b017c 100644 --- a/plugins/mfa/plugin.go +++ b/plugins/mfa/plugin.go @@ -1294,12 +1294,12 @@ func (p *Plugin) handleSMSSend(ctx forge.Context, req *SMSSendRequest) (*SMSSend // got the code. phone := enrollment.Secret // Phone stored as the enrollment secret if req.Phone != "" && req.Phone != phone && !enrollment.Verified { - if err := p.requireStepUp(ctx, userID, ""); err != nil { - return nil, err + if stepErr := p.requireStepUp(ctx, userID, ""); stepErr != nil { + return nil, stepErr } enrollment.Secret = req.Phone enrollment.UpdatedAt = time.Now() - if err := p.store.UpdateEnrollment(ctx.Context(), enrollment); err != nil { + if err = p.store.UpdateEnrollment(ctx.Context(), enrollment); err != nil { return nil, middleware.InternalError(ctx, fmt.Errorf("failed to update SMS enrollment: %w", err)) } phone = req.Phone diff --git a/plugins/mfa/ratelimit_test.go b/plugins/mfa/ratelimit_test.go index 6815e0f6..3d521a67 100644 --- a/plugins/mfa/ratelimit_test.go +++ b/plugins/mfa/ratelimit_test.go @@ -20,14 +20,17 @@ import ( wardenmem "github.com/xraph/warden/store/memory" ) -// newMFARateLimited builds an engine with rate limiting enabled at the given -// MFA-challenge limit, mounts the MFA plugin routes, and returns the handler. -func newMFARateLimited(t *testing.T, limit int) http.Handler { +// mfaChallengeLimit is the MFA-challenge limit newMFARateLimited sets. +const mfaChallengeLimit = 3 + +// newMFARateLimited builds an engine with rate limiting enabled at +// mfaChallengeLimit, mounts the MFA plugin routes, and returns the handler. +func newMFARateLimited(t *testing.T) http.Handler { t.Helper() cfg := authsome.DefaultConfig() cfg.AppID = "aapp_01jf0000000000000000000000" cfg.RateLimit.Enabled = true - cfg.RateLimit.MFAChallengeLimit = limit + cfg.RateLimit.MFAChallengeLimit = mfaChallengeLimit cfg.RateLimit.WindowSeconds = 60 w, err := warden.NewEngine(warden.WithStore(wardenmem.New())) @@ -55,8 +58,8 @@ func newMFARateLimited(t *testing.T, limit int) http.Handler { // throttled: past the MFAChallengeLimit, further attempts return 429. Without // this an attacker can brute-force the 6-digit code space unthrottled. func TestMFAVerify_RateLimited(t *testing.T) { - const limit = 3 - h := newMFARateLimited(t, limit) + const limit = mfaChallengeLimit + h := newMFARateLimited(t) var lastCode int for i := 0; i < limit+1; i++ { @@ -73,8 +76,8 @@ func TestMFAVerify_RateLimited(t *testing.T) { // TestMFASMSVerify_RateLimited pins the same protection on the SMS verify route. func TestMFASMSVerify_RateLimited(t *testing.T) { - const limit = 3 - h := newMFARateLimited(t, limit) + const limit = mfaChallengeLimit + h := newMFARateLimited(t) var lastCode int for i := 0; i < limit+1; i++ { @@ -92,8 +95,8 @@ func TestMFASMSVerify_RateLimited(t *testing.T) { // TestMFARecoveryRegenerate_RateLimited pins that regenerate, which accepts a // TOTP code, is throttled like the other code-submission routes. func TestMFARecoveryRegenerate_RateLimited(t *testing.T) { - const limit = 3 - h := newMFARateLimited(t, limit) + const limit = mfaChallengeLimit + h := newMFARateLimited(t) var lastCode int for i := 0; i < limit+1; i++ { @@ -113,12 +116,12 @@ func TestMFARecoveryRegenerate_RateLimited(t *testing.T) { // factor) and DELETE /enrollment (turning MFA off). Without it a stolen // session can guess the code that removes the second factor. func TestMFAEnrollAndDisable_RateLimited(t *testing.T) { - const limit = 3 + const limit = mfaChallengeLimit for _, c := range []struct{ method, path, addr string }{ {"POST", "/v1/mfa/enroll", "203.0.113.10:5555"}, {"DELETE", "/v1/mfa/enrollment", "203.0.113.11:5555"}, } { - h := newMFARateLimited(t, limit) + h := newMFARateLimited(t) var lastCode int for i := 0; i < limit+1; i++ { req := httptest.NewRequestWithContext(context.Background(), c.method, c.path, nil) diff --git a/plugins/mfa/verify_session_test.go b/plugins/mfa/verify_session_test.go index e03cb95b..6709abef 100644 --- a/plugins/mfa/verify_session_test.go +++ b/plugins/mfa/verify_session_test.go @@ -99,11 +99,11 @@ func TestRecoveryVerify_StampsTheSession(t *testing.T) { require.NoError(t, err) require.NoError(t, s.CreateRecoveryCodes(context.Background(), codes)) - rec, sid := postAs(t, h, "/v1/mfa/recovery/verify", map[string]string{"code": "wrong"}, uid) + rec, _ := postAs(t, h, "/v1/mfa/recovery/verify", map[string]string{"code": "wrong"}, uid) assert.Equal(t, http.StatusUnauthorized, rec.Code) assert.Zero(t, r.calls, "a wrong code stamps nothing") - rec, sid = postAs(t, h, "/v1/mfa/recovery/verify", map[string]string{"code": plain[0]}, uid) + rec, sid := postAs(t, h, "/v1/mfa/recovery/verify", map[string]string{"code": plain[0]}, uid) require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) assert.Equal(t, 1, r.calls) assert.Equal(t, sid, r.sid) @@ -112,7 +112,7 @@ func TestRecoveryVerify_StampsTheSession(t *testing.T) { func TestSMSVerify_StampsTheSession(t *testing.T) { p, s, r, h := stampingPlugin(t) uid := id.NewUserID() - smsEnrollment(t, s, uid, "+15550001", true) + smsEnrollment(t, s, uid, true) raw, err := json.Marshal(SMSChallenge{Code: "123456", ExpiresAt: time.Now().Add(time.Minute)}) require.NoError(t, err) require.NoError(t, p.ceremonies.Set(context.Background(), "mfa:sms:"+uid.String(), raw, time.Minute)) @@ -150,10 +150,13 @@ func (r *recordingSMS) SendSMS(_ context.Context, msg *bridge.SMSMessage) error return nil } -func smsEnrollment(t *testing.T, s *MemoryStore, uid id.UserID, phone string, verified bool) { +// enrolledPhone is the number every SMS enrollment in these tests uses. +const enrolledPhone = "+15550001" + +func smsEnrollment(t *testing.T, s *MemoryStore, uid id.UserID, verified bool) { t.Helper() require.NoError(t, s.CreateEnrollment(context.Background(), &Enrollment{ - ID: id.NewMFAID(), UserID: uid, Method: "sms", Secret: phone, Verified: verified, + ID: id.NewMFAID(), UserID: uid, Method: "sms", Secret: enrolledPhone, Verified: verified, CreatedAt: time.Now(), UpdatedAt: time.Now(), })) } @@ -175,11 +178,11 @@ func TestSMSSend_VerifiedEnrollmentIgnoresThePhoneOverride(t *testing.T) { sms := &recordingSMS{} p.SetSMSSender(sms) uid := id.NewUserID() - smsEnrollment(t, s, uid, "+15550001", true) + smsEnrollment(t, s, uid, true) rec, _ := postAs(t, h, "/v1/mfa/sms/send", map[string]string{"phone": "+15559999"}, uid) require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) - assert.Equal(t, []string{"+15550001"}, sms.to, "the code went to the enrolled number only") + assert.Equal(t, []string{enrolledPhone}, sms.to, "the code went to the enrolled number only") // And the code that went there is what stamps the session. rec, sid := postAs(t, h, "/v1/mfa/sms/verify", map[string]string{"code": pendingSMSCode(t, p, uid)}, uid) @@ -197,7 +200,7 @@ func TestSMSSend_UnverifiedEnrollmentOverrideConfirmsWithoutStamping(t *testing. sms := &recordingSMS{} p.SetSMSSender(sms) uid := id.NewUserID() - smsEnrollment(t, s, uid, "+15550001", false) + smsEnrollment(t, s, uid, false) rec, _ := postAs(t, h, "/v1/mfa/sms/send", map[string]string{"phone": "+15550002"}, uid) require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) @@ -223,19 +226,19 @@ func TestSMSSend_UnverifiedOverrideNeedsTheExistingFactor(t *testing.T) { ID: id.NewMFAID(), UserID: uid, Method: "totp", Secret: "JBSWY3DPEHPK3PXP", Verified: true, CreatedAt: time.Now(), UpdatedAt: time.Now(), })) - smsEnrollment(t, s, uid, "+15550001", false) + smsEnrollment(t, s, uid, false) rec, _ := postAs(t, h, "/v1/mfa/sms/send", map[string]string{"phone": "+15559999"}, uid) assert.Equal(t, http.StatusUnauthorized, rec.Code, rec.Body.String()) assert.Empty(t, sms.to, "nothing was sent to the new number") e, err := s.GetEnrollment(context.Background(), uid, "sms") require.NoError(t, err) - assert.Equal(t, "+15550001", e.Secret) + assert.Equal(t, enrolledPhone, e.Secret) // Without an override it goes to the pending number, as before. rec, _ = postAs(t, h, "/v1/mfa/sms/send", map[string]string{}, uid) require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) - assert.Equal(t, []string{"+15550001"}, sms.to) + assert.Equal(t, []string{enrolledPhone}, sms.to) } // Removing the factor removes what the session's stamp stood for, so the diff --git a/plugins/organization/handlers.go b/plugins/organization/handlers.go index 80c446ee..b2866121 100644 --- a/plugins/organization/handlers.go +++ b/plugins/organization/handlers.go @@ -639,12 +639,12 @@ func (p *Plugin) handleListInvitations(ctx forge.Context, req *ListInvitationsRe // an invitation: the caller is an admin of the org, and may grant the role the // invitation carries (an admin cannot touch an owner's invitation). It returns // the invitation's org and ID. -func (p *Plugin) authorizeInvitationChange(ctx forge.Context) (id.OrgID, id.InvitationID, error) { - orgID, err := id.ParseOrgID(ctx.Param("orgId")) +func (p *Plugin) authorizeInvitationChange(ctx forge.Context) (orgID id.OrgID, invID id.InvitationID, err error) { + orgID, err = id.ParseOrgID(ctx.Param("orgId")) if err != nil { return id.OrgID{}, id.InvitationID{}, forge.BadRequest(fmt.Sprintf("invalid org id: %v", err)) } - invID, err := id.ParseInvitationID(ctx.Param("invitationId")) + invID, err = id.ParseInvitationID(ctx.Param("invitationId")) if err != nil { return id.OrgID{}, id.InvitationID{}, forge.BadRequest(fmt.Sprintf("invalid invitation id: %v", err)) } diff --git a/plugins/organization/invitation_accept_test.go b/plugins/organization/invitation_accept_test.go index 36434d46..c1da15d9 100644 --- a/plugins/organization/invitation_accept_test.go +++ b/plugins/organization/invitation_accept_test.go @@ -230,13 +230,12 @@ func TestInvitationTokens_onlyAVerifiedAddressCounts(t *testing.T) { appID, err := id.ParseAppID(orgTestAppID) require.NoError(t, err) - invite := func(email, token string) *organization.Invitation { + invite := func(email, token string) { inv := &organization.Invitation{ ID: id.NewInvitationID(), OrgID: f.org.ID, Email: email, Role: organization.RoleMember, Status: organization.InvitationPending, Token: token, } require.NoError(t, f.plugin.CreateInvitation(ctx, inv)) - return inv } signUp := func(email string) id.UserID { u, _, err := f.eng.SignUp(ctx, &account.SignUpRequest{AppID: appID, Email: email, Password: "SecureP@ss123", FirstName: "T"}) diff --git a/plugins/organization/service.go b/plugins/organization/service.go index c4a24321..42560918 100644 --- a/plugins/organization/service.go +++ b/plugins/organization/service.go @@ -455,7 +455,9 @@ func (p *Plugin) sendInvitationEmail(ctx context.Context, inv *organization.Invi var sender invitationSender if p.plugins != nil { if np := p.plugins.Plugin("notification"); np != nil { - sender, _ = np.(invitationSender) + if s, ok := np.(invitationSender); ok { + sender = s + } } } if sender == nil {