mirror of
https://github.com/QuantumNous/new-api.git
synced 2026-12-05 08:03:01 +00:00
fix(oauth): require account evidence before migrating legacy GitHub bindings
Legacy GitHub bindings stored the login name, while current bindings store the numeric account ID. A legacy match no longer signs the user in on its own. When the account has two-factor or a passkey, the binding is rewritten only after that verification completes, inside the transaction that issues the session. Otherwise it is rewritten when one of the GitHub account's verified emails matches the account email. Without either, the login is declined with guidance to sign in another way and relink GitHub in account settings. All-digit login names never take part in the comparison, the bind flow no longer compares login names, and every migration or declined attempt is recorded as an account binding audit event.
This commit is contained in:
18 files changed
+565
-81
No files matched your search
@@ -76,7 +76,7 @@ func TestSecurityLoginCodeCompletesOnce(t *testing.T) {
|
||||
user, _ := setupSecurityEnrollmentTest(t)
|
||||
factor := &model.TwoFA{UserId: user.Id, Secret: "JBSWY3DPEHPK3PXP", IsEnabled: true}
|
||||
require.NoError(t, model.DB.Create(factor).Error)
|
||||
challenge, err := service.StartLoginVerification(user, "password")
|
||||
challenge, err := service.StartLoginVerification(user, "password", nil)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, challenge)
|
||||
code, err := totp.GenerateCode(factor.Secret, time.Now())
|
||||
@@ -121,7 +121,7 @@ func TestSecurityLoginRejectsChangedOrExpiredAuthorization(t *testing.T) {
|
||||
user, _ := setupSecurityEnrollmentTest(t)
|
||||
factor := &model.TwoFA{UserId: user.Id, Secret: "JBSWY3DPEHPK3PXP", IsEnabled: true}
|
||||
require.NoError(t, model.DB.Create(factor).Error)
|
||||
challenge, err := service.StartLoginVerification(user, "password")
|
||||
challenge, err := service.StartLoginVerification(user, "password", nil)
|
||||
require.NoError(t, err)
|
||||
method := "2fa"
|
||||
switch change {
|
||||
@@ -183,7 +183,7 @@ func TestSecurityLoginPasskeyDoesNotRequireAdditionalTwoFA(t *testing.T) {
|
||||
require.Equal(t, "required", result.Data.Options.PublicKey.UserVerification)
|
||||
flowToken, challenge = result.Data.FlowToken, result.Data.Options.PublicKey.Challenge
|
||||
} else {
|
||||
pending, err := service.StartLoginVerification(user, "oauth:github")
|
||||
pending, err := service.StartLoginVerification(user, "oauth:github", nil)
|
||||
require.NoError(t, err)
|
||||
parentToken = pending.FlowToken
|
||||
flowToken, challenge = beginSecurityLoginPasskey(t, parentToken)
|
||||
@@ -225,7 +225,7 @@ func TestSecurityLoginPasskeyDoesNotRequireAdditionalTwoFA(t *testing.T) {
|
||||
func TestSecurityLoginPasskeyConcurrentCompletionCreatesOneSession(t *testing.T) {
|
||||
user, _ := setupSecurityEnrollmentTest(t)
|
||||
key := newSecurityLoginPasskey(t, user.Id)
|
||||
pending, err := service.StartLoginVerification(user, "password")
|
||||
pending, err := service.StartLoginVerification(user, "password", nil)
|
||||
require.NoError(t, err)
|
||||
requests := make([]string, 2)
|
||||
for index := range requests {
|
||||
@@ -266,7 +266,7 @@ func TestSecurityLoginPasskeyConcurrentCompletionCreatesOneSession(t *testing.T)
|
||||
func TestSecurityLoginSessionFailureRollsBackChallengeConsumption(t *testing.T) {
|
||||
user, _ := setupSecurityEnrollmentTest(t)
|
||||
key := newSecurityLoginPasskey(t, user.Id)
|
||||
pending, err := service.StartLoginVerification(user, "password")
|
||||
pending, err := service.StartLoginVerification(user, "password", nil)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, model.DB.Callback().Create().Before("gorm:create").Register("login_session_failure", func(tx *gorm.DB) {
|
||||
if tx.Statement.Table == "user_sessions" {
|
||||
@@ -410,7 +410,7 @@ func TestSecurityLoginPasskeyCannotCompleteAnotherChallenge(t *testing.T) {
|
||||
t.Run(fmt.Sprintf("other-user=%t", otherUser), func(t *testing.T) {
|
||||
user, _ := setupSecurityEnrollmentTest(t)
|
||||
key := newSecurityLoginPasskey(t, user.Id)
|
||||
first, err := service.StartLoginVerification(user, "password")
|
||||
first, err := service.StartLoginVerification(user, "password", nil)
|
||||
require.NoError(t, err)
|
||||
passkeyToken, challenge := beginSecurityLoginPasskey(t, first.FlowToken)
|
||||
if otherUser {
|
||||
@@ -418,7 +418,7 @@ func TestSecurityLoginPasskeyCannotCompleteAnotherChallenge(t *testing.T) {
|
||||
require.NoError(t, model.DB.Create(user).Error)
|
||||
newSecurityLoginPasskey(t, user.Id)
|
||||
}
|
||||
second, err := service.StartLoginVerification(user, "password")
|
||||
second, err := service.StartLoginVerification(user, "password", nil)
|
||||
require.NoError(t, err)
|
||||
body, err := common.Marshal(map[string]any{"flow_token": second.FlowToken, "passkey_flow_token": passkeyToken, "credential": securityPasskeyResponse(t, key, challenge, false, 0)})
|
||||
require.NoError(t, err)
|
||||
@@ -816,3 +816,310 @@ func TestOAuthBindProviderErrorConsumesSessionBoundFlow(t *testing.T) {
|
||||
assert.Zero(t, provider.exchangeCalls)
|
||||
assert.Zero(t, provider.userInfoCalls)
|
||||
}
|
||||
|
||||
// legacyGitHubOAuthProvider follows the GitHub provider contract: the numeric
|
||||
// account ID identifies the user, Extra["legacy_id"] carries the username and
|
||||
// the verified email list is served on demand. Lookups go through the real
|
||||
// github_id model queries.
|
||||
type legacyGitHubOAuthProvider struct {
|
||||
authFlowTestOAuthProvider
|
||||
providerUserID string
|
||||
legacyID string
|
||||
verifiedEmails []string
|
||||
verifiedEmailsErr error
|
||||
verifiedEmailCalls int
|
||||
}
|
||||
|
||||
func (*legacyGitHubOAuthProvider) GetName() string { return "GitHub" }
|
||||
func (provider *legacyGitHubOAuthProvider) GetUserInfo(context.Context, *oauth.OAuthToken) (*oauth.OAuthUser, error) {
|
||||
return &oauth.OAuthUser{ProviderUserID: provider.providerUserID, Username: provider.legacyID, Extra: map[string]any{"legacy_id": provider.legacyID}}, nil
|
||||
}
|
||||
func (provider *legacyGitHubOAuthProvider) GetVerifiedEmails(context.Context, *oauth.OAuthToken) ([]string, error) {
|
||||
provider.verifiedEmailCalls++
|
||||
return provider.verifiedEmails, provider.verifiedEmailsErr
|
||||
}
|
||||
func (*legacyGitHubOAuthProvider) IsUserIDTaken(providerUserID string) bool {
|
||||
return model.IsGitHubIdAlreadyTaken(providerUserID)
|
||||
}
|
||||
func (*legacyGitHubOAuthProvider) FillUserByProviderID(user *model.User, providerUserID string) error {
|
||||
user.GitHubId = providerUserID
|
||||
return user.FillUserByGitHubId()
|
||||
}
|
||||
func (*legacyGitHubOAuthProvider) SetProviderUserID(user *model.User, providerUserID string) {
|
||||
user.GitHubId = providerUserID
|
||||
}
|
||||
func (*legacyGitHubOAuthProvider) GetProviderPrefix() string { return "github_" }
|
||||
func (*legacyGitHubOAuthProvider) ProviderUserIDColumn() string { return "github_id" }
|
||||
|
||||
// legacyGitHubOAuthLogin registers provider for one test and completes an OAuth
|
||||
// login callback with it.
|
||||
func legacyGitHubOAuthLogin(t *testing.T, provider *legacyGitHubOAuthProvider) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
const slug = "github-legacy-login-test"
|
||||
oauth.Register(slug, provider)
|
||||
t.Cleanup(func() { oauth.Unregister(slug) })
|
||||
token, _, err := model.CreateAuthFlow(model.AuthFlowCreate{Purpose: model.AuthFlowPurposeOAuth, Provider: slug, Intent: model.AuthFlowIntentLogin, Payload: `{}`, ExpiresAt: time.Now().Add(time.Minute)})
|
||||
require.NoError(t, err)
|
||||
router := gin.New()
|
||||
router.GET("/api/oauth/:provider", HandleOAuth)
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/oauth/"+slug+"?state="+token+"&code=provider-code", nil))
|
||||
return response
|
||||
}
|
||||
|
||||
// legacyGitHubBindingAudits returns the account binding audit rows in creation
|
||||
// order together with their encoded parameters.
|
||||
func legacyGitHubBindingAudits(t *testing.T) ([]model.AuditLog, []string) {
|
||||
t.Helper()
|
||||
var audits []model.AuditLog
|
||||
require.NoError(t, model.LOG_DB.Where("action = ?", "user.binding_bind").Order("id").Find(&audits).Error)
|
||||
params := make([]string, 0, len(audits))
|
||||
for _, audit := range audits {
|
||||
require.NotNil(t, audit.Other.Op)
|
||||
encoded, err := common.Marshal(audit.Other.Op.Params)
|
||||
require.NoError(t, err)
|
||||
params = append(params, string(encoded))
|
||||
}
|
||||
return audits, params
|
||||
}
|
||||
|
||||
func TestOAuthLoginLegacyGitHubBindingRequiresAccountEvidence(t *testing.T) {
|
||||
const declined = "This GitHub account cannot be linked to an existing account automatically, please sign in or register another way and then link GitHub in account settings"
|
||||
tests := []struct {
|
||||
name string
|
||||
existingGitHubID string
|
||||
existingDeleted bool
|
||||
withoutEmail bool
|
||||
legacyID string
|
||||
verifiedEmails []string
|
||||
verifiedEmailsErr error
|
||||
registerEnabled bool
|
||||
expectLogin bool
|
||||
expectMigration bool
|
||||
expectNewAccount bool
|
||||
expectEmailCalls int
|
||||
expectAuditParams string
|
||||
}{
|
||||
{name: "numeric legacy value registers a new account", existingGitHubID: "424242", legacyID: "424242", verifiedEmails: []string{"legacy-github@example.com"}, registerEnabled: true, expectLogin: true, expectNewAccount: true},
|
||||
{name: "numeric legacy value with registration disabled", existingGitHubID: "424242", legacyID: "424242", verifiedEmails: []string{"legacy-github@example.com"}},
|
||||
{name: "soft-deleted legacy row registers a new account", existingGitHubID: "octocat-legacy", existingDeleted: true, legacyID: "octocat-legacy", verifiedEmails: []string{"legacy-github@example.com"}, registerEnabled: true, expectLogin: true, expectNewAccount: true},
|
||||
{
|
||||
name: "verified email match migrates", existingGitHubID: "octocat-legacy", legacyID: "octocat-legacy",
|
||||
verifiedEmails: []string{"other@example.com", " Legacy-GitHub@Example.com "}, expectLogin: true, expectMigration: true, expectEmailCalls: 1,
|
||||
// No SMTP server is configured in tests, so the notification attempt is recorded as failed.
|
||||
expectAuditParams: `{"provider":"github","legacy_migration":true,"legacy_id":"octocat-legacy","provider_user_id":"900001","verified_email_matched":true,"success":true,"notification_failed":true}`,
|
||||
},
|
||||
{
|
||||
name: "no matching verified email declines", existingGitHubID: "octocat-legacy", legacyID: "octocat-legacy",
|
||||
verifiedEmails: []string{"other@example.com"}, registerEnabled: true, expectEmailCalls: 1,
|
||||
expectAuditParams: `{"provider":"github","legacy_migration":true,"legacy_id":"octocat-legacy","provider_user_id":"900001","success":false,"reason":"no_matching_evidence"}`,
|
||||
},
|
||||
{
|
||||
name: "verified emails failure declines", existingGitHubID: "octocat-legacy", legacyID: "octocat-legacy",
|
||||
verifiedEmailsErr: errors.New("emails unavailable"), registerEnabled: true, expectEmailCalls: 1,
|
||||
expectAuditParams: `{"provider":"github","legacy_migration":true,"legacy_id":"octocat-legacy","provider_user_id":"900001","success":false,"reason":"verified_emails_unavailable"}`,
|
||||
},
|
||||
{
|
||||
name: "account without email declines before asking the provider", existingGitHubID: "octocat-legacy", withoutEmail: true, legacyID: "octocat-legacy",
|
||||
verifiedEmails: []string{"legacy-github@example.com"}, registerEnabled: true,
|
||||
expectAuditParams: `{"provider":"github","legacy_migration":true,"legacy_id":"octocat-legacy","provider_user_id":"900001","success":false,"reason":"no_matching_evidence"}`,
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
setupSecurityEnrollmentTest(t)
|
||||
previousRegister := common.RegisterEnabled
|
||||
common.RegisterEnabled = test.registerEnabled
|
||||
t.Cleanup(func() { common.RegisterEnabled = previousRegister })
|
||||
existing := &model.User{Username: "legacy-github", Email: "legacy-github@example.com", Role: common.RoleCommonUser, Status: common.UserStatusEnabled, Group: "default", AffCode: "legacy-github", AuthVersion: 1, GitHubId: test.existingGitHubID}
|
||||
if test.withoutEmail {
|
||||
existing.Email = ""
|
||||
}
|
||||
require.NoError(t, model.DB.Create(existing).Error)
|
||||
if test.existingDeleted {
|
||||
require.NoError(t, model.DB.Delete(existing).Error)
|
||||
}
|
||||
provider := &legacyGitHubOAuthProvider{providerUserID: "900001", legacyID: test.legacyID, verifiedEmails: test.verifiedEmails, verifiedEmailsErr: test.verifiedEmailsErr}
|
||||
response := legacyGitHubOAuthLogin(t, provider)
|
||||
var result struct {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message"`
|
||||
Data struct {
|
||||
User struct {
|
||||
Id int `json:"id"`
|
||||
} `json:"user"`
|
||||
} `json:"data"`
|
||||
}
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result))
|
||||
require.Equal(t, test.expectLogin, result.Success, response.Body.String())
|
||||
assert.Equal(t, test.expectEmailCalls, provider.verifiedEmailCalls)
|
||||
|
||||
var reloaded model.User
|
||||
require.NoError(t, model.DB.Unscoped().First(&reloaded, existing.Id).Error)
|
||||
audits, params := legacyGitHubBindingAudits(t)
|
||||
if test.expectAuditParams == "" {
|
||||
assert.Empty(t, audits)
|
||||
} else {
|
||||
require.Len(t, audits, 1)
|
||||
assert.Equal(t, existing.Id, audits[0].UserId)
|
||||
assert.Equal(t, common.RoleCommonUser, audits[0].ActorRole)
|
||||
assert.Equal(t, test.expectMigration, audits[0].Success)
|
||||
assert.JSONEq(t, test.expectAuditParams, params[0])
|
||||
}
|
||||
if test.expectMigration {
|
||||
assert.Equal(t, existing.Id, result.Data.User.Id)
|
||||
assert.Equal(t, "900001", reloaded.GitHubId)
|
||||
assert.NotEmpty(t, response.Header().Values("Set-Cookie"))
|
||||
return
|
||||
}
|
||||
assert.Equal(t, test.existingGitHubID, reloaded.GitHubId, "the existing binding must stay untouched")
|
||||
if test.expectNewAccount {
|
||||
var created model.User
|
||||
require.NoError(t, model.DB.Where("github_id = ?", "900001").First(&created).Error)
|
||||
assert.NotEqual(t, existing.Id, created.Id)
|
||||
assert.Equal(t, created.Id, result.Data.User.Id)
|
||||
return
|
||||
}
|
||||
assert.Empty(t, response.Header().Values("Set-Cookie"))
|
||||
if test.expectAuditParams != "" {
|
||||
assert.Equal(t, declined, result.Message)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOAuthLoginLegacyGitHubBindingMigratesAfterLoginVerification(t *testing.T) {
|
||||
for _, interference := range []string{"none", "pending id claimed by another account", "binding relinked meanwhile"} {
|
||||
t.Run(interference, func(t *testing.T) {
|
||||
setupSecurityEnrollmentTest(t)
|
||||
existing := &model.User{Username: "legacy-github", Email: "legacy-github@example.com", Role: common.RoleCommonUser, Status: common.UserStatusEnabled, Group: "default", AffCode: "legacy-github", AuthVersion: 1, GitHubId: "octocat-legacy"}
|
||||
require.NoError(t, model.DB.Create(existing).Error)
|
||||
factor := &model.TwoFA{UserId: existing.Id, Secret: "JBSWY3DPEHPK3PXP", IsEnabled: true}
|
||||
require.NoError(t, model.DB.Create(factor).Error)
|
||||
provider := &legacyGitHubOAuthProvider{providerUserID: "900001", legacyID: "octocat-legacy", verifiedEmails: []string{"legacy-github@example.com"}}
|
||||
response := legacyGitHubOAuthLogin(t, provider)
|
||||
var challenge struct {
|
||||
Success bool `json:"success"`
|
||||
Data service.LoginChallenge `json:"data"`
|
||||
}
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &challenge))
|
||||
require.True(t, challenge.Success, response.Body.String())
|
||||
require.True(t, challenge.Data.RequireVerification)
|
||||
assert.Equal(t, []service.VerificationMethodOption{{Method: "2fa", Available: true}}, challenge.Data.Methods)
|
||||
assert.Empty(t, response.Header().Values("Set-Cookie"))
|
||||
assert.Zero(t, provider.verifiedEmailCalls, "a second factor is checked before the provider emails")
|
||||
var reloaded model.User
|
||||
require.NoError(t, model.DB.First(&reloaded, existing.Id).Error)
|
||||
assert.Equal(t, "octocat-legacy", reloaded.GitHubId, "the binding waits for the verification")
|
||||
audits, _ := legacyGitHubBindingAudits(t)
|
||||
assert.Empty(t, audits)
|
||||
|
||||
expectedGitHubID, expectLogin := "900001", true
|
||||
switch interference {
|
||||
case "pending id claimed by another account":
|
||||
other := &model.User{Username: "other-github", Role: common.RoleCommonUser, Status: common.UserStatusEnabled, Group: "default", AffCode: "other-github", AuthVersion: 1, GitHubId: "900001"}
|
||||
require.NoError(t, model.DB.Create(other).Error)
|
||||
expectedGitHubID, expectLogin = "octocat-legacy", false
|
||||
case "binding relinked meanwhile":
|
||||
require.NoError(t, model.DB.Model(existing).Update("github_id", "relinked-legacy").Error)
|
||||
expectedGitHubID = "relinked-legacy"
|
||||
}
|
||||
code, err := totp.GenerateCode(factor.Secret, time.Now())
|
||||
require.NoError(t, err)
|
||||
body, err := common.Marshal(map[string]string{"flow_token": challenge.Data.FlowToken, "code": code})
|
||||
require.NoError(t, err)
|
||||
for attempt := range 2 {
|
||||
response = securityEnrollmentRequest(http.MethodPost, "/api/user/login/verify", string(body), "", service.AuthIdentity{}, VerifyLogin)
|
||||
var result securityEnrollmentResponse
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result))
|
||||
assert.Equal(t, attempt == 0 && expectLogin, result.Success, response.Body.String())
|
||||
if attempt == 0 && !expectLogin {
|
||||
assert.Equal(t, "ACCOUNT_ALREADY_BOUND", result.Code)
|
||||
}
|
||||
if result.Success {
|
||||
assert.NotEmpty(t, response.Header().Values("Set-Cookie"))
|
||||
} else {
|
||||
assert.Empty(t, response.Header().Values("Set-Cookie"))
|
||||
}
|
||||
}
|
||||
require.NoError(t, model.DB.First(&reloaded, existing.Id).Error)
|
||||
assert.Equal(t, expectedGitHubID, reloaded.GitHubId)
|
||||
sessions, err := model.CountActiveUserSessions(existing.Id, time.Now().Unix())
|
||||
require.NoError(t, err)
|
||||
expectedSessions := 0
|
||||
if expectLogin {
|
||||
expectedSessions = 1
|
||||
}
|
||||
assert.EqualValues(t, expectedSessions, sessions, "the consumed challenge cannot be replayed")
|
||||
audits, params := legacyGitHubBindingAudits(t)
|
||||
if interference != "none" {
|
||||
assert.Empty(t, audits)
|
||||
return
|
||||
}
|
||||
require.Len(t, audits, 1)
|
||||
assert.Equal(t, existing.Id, audits[0].UserId)
|
||||
assert.Equal(t, common.RoleCommonUser, audits[0].ActorRole)
|
||||
assert.True(t, audits[0].Success)
|
||||
// No SMTP server is configured in tests, so the notification attempt is recorded as failed.
|
||||
assert.JSONEq(t, `{"provider":"github","legacy_migration":true,"legacy_id":"octocat-legacy","provider_user_id":"900001","verification_method":"2fa","success":true,"notification_failed":true}`, params[0])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOAuthBindIgnoresLegacyGitHubUsernames(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ownGitHubID string
|
||||
otherGitHubID string
|
||||
legacyID string
|
||||
expectBound bool
|
||||
}{
|
||||
{name: "another account's legacy username does not block binding", otherGitHubID: "octocat-legacy", legacyID: "octocat-legacy", expectBound: true},
|
||||
{name: "own legacy username is replaced", ownGitHubID: "octocat-legacy", otherGitHubID: "unrelated-legacy", legacyID: "octocat-legacy", expectBound: true},
|
||||
{name: "numeric legacy value does not collide", otherGitHubID: "424242", legacyID: "424242", expectBound: true},
|
||||
{name: "numeric ID held by another account is rejected", otherGitHubID: "900001", legacyID: "octocat-legacy"},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
user, identity := setupSecurityEnrollmentTest(t)
|
||||
if test.ownGitHubID != "" {
|
||||
require.NoError(t, model.DB.Model(user).Update("github_id", test.ownGitHubID).Error)
|
||||
}
|
||||
other := &model.User{Username: "other-github", Role: common.RoleCommonUser, Status: common.UserStatusEnabled, Group: "default", AffCode: "other-github", AuthVersion: 1, GitHubId: test.otherGitHubID}
|
||||
require.NoError(t, model.DB.Create(other).Error)
|
||||
const slug = "github-legacy-bind-test"
|
||||
oauth.Register(slug, &legacyGitHubOAuthProvider{providerUserID: "900001", legacyID: test.legacyID})
|
||||
t.Cleanup(func() { oauth.Unregister(slug) })
|
||||
proof := issueSecurityEnrollmentProof(t, identity, service.VerificationOperation{Scope: service.VerificationScopeAccountBind, Context: []byte(`{"provider":"` + slug + `"}`)}, service.VerificationMethodPassword)
|
||||
started := securityEnrollmentRequest(http.MethodPost, "/api/oauth/state", `{"provider":"`+slug+`","intent":"bind"}`, proof, identity, GenerateOAuthCode)
|
||||
var flow struct {
|
||||
Data struct {
|
||||
FlowToken string `json:"flow_token"`
|
||||
} `json:"data"`
|
||||
}
|
||||
require.NoError(t, common.Unmarshal(started.Body.Bytes(), &flow))
|
||||
require.NotEmpty(t, flow.Data.FlowToken, started.Body.String())
|
||||
response := securityEnrollmentRequest(http.MethodGet, "/api/oauth/"+slug+"?state="+flow.Data.FlowToken+"&code=provider-code", "", "", identity, func(c *gin.Context) {
|
||||
c.Params = gin.Params{{Key: "provider", Value: slug}}
|
||||
HandleOAuth(c)
|
||||
})
|
||||
var result struct {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result))
|
||||
assert.Equal(t, test.expectBound, result.Success, response.Body.String())
|
||||
|
||||
var bound, untouched model.User
|
||||
require.NoError(t, model.DB.First(&bound, user.Id).Error)
|
||||
require.NoError(t, model.DB.First(&untouched, other.Id).Error)
|
||||
assert.Equal(t, test.otherGitHubID, untouched.GitHubId)
|
||||
if test.expectBound {
|
||||
assert.Equal(t, "900001", bound.GitHubId)
|
||||
return
|
||||
}
|
||||
assert.Equal(t, test.ownGitHubID, bound.GitHubId)
|
||||
assert.Equal(t, "This GitHub account has already been bound", result.Message)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -146,7 +146,7 @@ func TestSessionLimitDoesNotRecordRejectedLoginAsSuccessful(t *testing.T) {
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/api/user/login", nil)
|
||||
setupLogin(user, c)
|
||||
setupLogin(user, nil, c)
|
||||
|
||||
assert.Equal(t, http.StatusConflict, recorder.Code)
|
||||
var stored model.User
|
||||
|
||||
@@ -30,12 +30,12 @@ func VerifyLogin(c *gin.Context) {
|
||||
writeSecurityOperationError(c, service.ErrProofMethod)
|
||||
return
|
||||
}
|
||||
bundle, err := service.VerifyLoginCode(request.FlowToken, request.Code, c.ClientIP(), c.Request.UserAgent())
|
||||
bundle, migration, err := service.VerifyLoginCode(request.FlowToken, request.Code, c.ClientIP(), c.Request.UserAgent())
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
completeVerifiedLoginResponse(c, bundle, service.VerificationMethodTwoFA)
|
||||
completeVerifiedLoginResponse(c, bundle, service.VerificationMethodTwoFA, migration)
|
||||
}
|
||||
|
||||
func LoginPasskeyBegin(c *gin.Context) {
|
||||
@@ -137,15 +137,15 @@ func LoginPasskeyFinish(c *gin.Context) {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
bundle, err := service.CompleteLoginVerification(request.FlowToken, verification, service.VerificationMethodPasskey, c.ClientIP(), c.Request.UserAgent())
|
||||
bundle, migration, err := service.CompleteLoginVerification(request.FlowToken, verification, service.VerificationMethodPasskey, c.ClientIP(), c.Request.UserAgent())
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
completeVerifiedLoginResponse(c, bundle, service.VerificationMethodPasskey)
|
||||
completeVerifiedLoginResponse(c, bundle, service.VerificationMethodPasskey, migration)
|
||||
}
|
||||
|
||||
func completeVerifiedLoginResponse(c *gin.Context, bundle *service.AuthBundle, method string) {
|
||||
func completeVerifiedLoginResponse(c *gin.Context, bundle *service.AuthBundle, method string, migration *service.LegacyGitHubMigration) {
|
||||
identity, err := service.ParseAccessToken(bundle.AccessToken)
|
||||
if err != nil {
|
||||
writeAuthSessionError(c, err)
|
||||
@@ -157,5 +157,13 @@ func completeVerifiedLoginResponse(c *gin.Context, bundle *service.AuthBundle, m
|
||||
return
|
||||
}
|
||||
c.Set("login_verification_method", method)
|
||||
if migration != nil {
|
||||
// The legacy GitHub binding was rewritten together with this session.
|
||||
notificationFailed := service.NotifyAccountSecurityChange(user.Email, "Login account linked: GitHub") != nil
|
||||
recordLegacyGitHubBindingAudit(c, user, true, map[string]any{
|
||||
"legacy_id": migration.LegacyID, "provider_user_id": migration.GitHubID,
|
||||
"verification_method": method, "notification_failed": notificationFailed,
|
||||
})
|
||||
}
|
||||
writeLoginResponse(c, user, bundle)
|
||||
}
|
||||
@@ -517,7 +517,7 @@ func TestSetupLoginDoesNotTouchPasswordWhenPasswordFieldOmitted(t *testing.T) {
|
||||
Role: user.Role,
|
||||
Status: user.Status,
|
||||
Group: user.Group,
|
||||
}, c)
|
||||
}, nil, c)
|
||||
})
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
+89
-34
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -292,7 +293,7 @@ func HandleOAuth(c *gin.Context) {
|
||||
|
||||
switch flow.Intent {
|
||||
case model.AuthFlowIntentLogin:
|
||||
handleOAuthLogin(c, provider, oauthUser, flow)
|
||||
handleOAuthLogin(c, provider, oauthUser, token, flow)
|
||||
case model.AuthFlowIntentVerify:
|
||||
handleOAuthVerification(c, providerName, oauthUser, flow)
|
||||
}
|
||||
@@ -314,14 +315,14 @@ func handleOAuthVerification(c *gin.Context, provider string, oauthUser *oauth.O
|
||||
common.ApiSuccess(c, proof)
|
||||
}
|
||||
|
||||
func handleOAuthLogin(c *gin.Context, provider oauth.Provider, oauthUser *oauth.OAuthUser, flow *model.AuthFlow) {
|
||||
func handleOAuthLogin(c *gin.Context, provider oauth.Provider, oauthUser *oauth.OAuthUser, token *oauth.OAuthToken, flow *model.AuthFlow) {
|
||||
// 7. Find or create user
|
||||
var payload oauthFlowPayload
|
||||
if err := common.UnmarshalJsonStr(flow.Payload, &payload); err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
}
|
||||
user, err := findOrCreateOAuthUser(c, provider, oauthUser, payload.AffiliateCode)
|
||||
user, migration, err := findOrCreateOAuthUser(c, provider, oauthUser, token, payload.AffiliateCode)
|
||||
if err != nil {
|
||||
if errors.Is(err, model.ErrEmailAlreadyTaken) {
|
||||
common.ApiErrorI18n(c, i18n.MsgUserEmailAlreadyTaken)
|
||||
@@ -334,6 +335,8 @@ func handleOAuthLogin(c *gin.Context, provider oauth.Provider, oauthUser *oauth.
|
||||
common.ApiErrorI18n(c, i18n.MsgUserRegisterDisabled)
|
||||
case *OAuthEmailAlreadyTakenError:
|
||||
common.ApiErrorI18n(c, i18n.MsgUserEmailAlreadyTaken)
|
||||
case *OAuthLegacyBindingNotConfirmedError:
|
||||
common.ApiErrorI18n(c, i18n.MsgOAuthNotAutoLinked, providerParams(provider.GetName()))
|
||||
default:
|
||||
writeSecurityOperationError(c, err)
|
||||
}
|
||||
@@ -347,7 +350,7 @@ func handleOAuthLogin(c *gin.Context, provider oauth.Provider, oauthUser *oauth.
|
||||
}
|
||||
|
||||
// 9. Setup login
|
||||
setupLogin(user, c)
|
||||
setupLogin(user, migration, c)
|
||||
}
|
||||
|
||||
// handleOAuthBind handles binding OAuth account to existing user
|
||||
@@ -377,10 +380,6 @@ func handleOAuthBind(c *gin.Context, providerName string, provider oauth.Provide
|
||||
common.ApiErrorI18n(c, i18n.MsgOAuthAlreadyBound, providerParams(provider.GetName()))
|
||||
return false, false
|
||||
}
|
||||
if legacyID, ok := oauthUser.Extra["legacy_id"].(string); ok && legacyID != "" && provider.IsUserIDTaken(legacyID) {
|
||||
common.ApiErrorI18n(c, i18n.MsgOAuthAlreadyBound, providerParams(provider.GetName()))
|
||||
return false, false
|
||||
}
|
||||
_, err = model.ConsumeAuthFlowWithAction(state, match, func(tx *gorm.DB, _ *model.AuthFlow) error {
|
||||
if providerName == "telegram" {
|
||||
return model.BindTelegramForSessionWithTx(tx, identity, oauthUser.ProviderUserID)
|
||||
@@ -404,53 +403,91 @@ func handleOAuthBind(c *gin.Context, providerName string, provider oauth.Provide
|
||||
return true, notificationFailed
|
||||
}
|
||||
|
||||
// findOrCreateOAuthUser finds existing user or creates new user
|
||||
func findOrCreateOAuthUser(c *gin.Context, provider oauth.Provider, oauthUser *oauth.OAuthUser, affiliateCode string) (*model.User, error) {
|
||||
// findOrCreateOAuthUser finds the existing user or creates a new one. For a
|
||||
// legacy GitHub binding that still waits for the login verification, it also
|
||||
// returns the rewrite to carry into the challenge.
|
||||
func findOrCreateOAuthUser(c *gin.Context, provider oauth.Provider, oauthUser *oauth.OAuthUser, token *oauth.OAuthToken, affiliateCode string) (*model.User, *service.LegacyGitHubMigration, error) {
|
||||
user := &model.User{}
|
||||
if provider.ProviderUserIDColumn() == "telegram_id" {
|
||||
err := provider.FillUserByProviderID(user, oauthUser.ProviderUserID)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, oauth.ErrTelegramAccountNotBound
|
||||
return nil, nil, oauth.ErrTelegramAccountNotBound
|
||||
}
|
||||
return user, err
|
||||
return user, nil, err
|
||||
}
|
||||
|
||||
// Check if user already exists with new ID
|
||||
if provider.IsUserIDTaken(oauthUser.ProviderUserID) {
|
||||
err := provider.FillUserByProviderID(user, oauthUser.ProviderUserID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
// Check if user has been deleted
|
||||
if user.Id == 0 {
|
||||
return nil, &OAuthUserDeletedError{}
|
||||
return nil, nil, &OAuthUserDeletedError{}
|
||||
}
|
||||
return user, nil
|
||||
return user, nil, nil
|
||||
}
|
||||
|
||||
// Try to find user with legacy ID (for GitHub migration from login to numeric ID)
|
||||
if legacyID, ok := oauthUser.Extra["legacy_id"].(string); ok && legacyID != "" {
|
||||
if provider.IsUserIDTaken(legacyID) {
|
||||
err := provider.FillUserByProviderID(user, legacyID)
|
||||
// Legacy GitHub bindings stored the login name, which only points at a
|
||||
// candidate account. Values that are all digits are already numeric account
|
||||
// IDs and never take part in the comparison.
|
||||
legacyID, _ := oauthUser.Extra["legacy_id"].(string)
|
||||
if strings.ContainsFunc(legacyID, func(r rune) bool { return r < '0' || r > '9' }) && provider.IsUserIDTaken(legacyID) {
|
||||
if err := provider.FillUserByProviderID(user, legacyID); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if user.Id != 0 {
|
||||
state, err := model.GetUserVerificationState(user.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
if user.Id != 0 {
|
||||
// Found user with legacy ID, migrate to new ID
|
||||
common.SysLog(fmt.Sprintf("[OAuth] Migrating user %d from legacy_id=%s to new_id=%s",
|
||||
user.Id, legacyID, oauthUser.ProviderUserID))
|
||||
if err := user.UpdateGitHubId(oauthUser.ProviderUserID); err != nil {
|
||||
common.SysError(fmt.Sprintf("[OAuth] Failed to migrate user %d: %s", user.Id, err.Error()))
|
||||
// Continue with login even if migration fails
|
||||
if state.HasTwoFA || state.HasPasskey {
|
||||
// The rewrite is written in the transaction that issues the session
|
||||
// once the login verification completes.
|
||||
return user, &service.LegacyGitHubMigration{GitHubID: oauthUser.ProviderUserID, LegacyID: legacyID}, nil
|
||||
}
|
||||
// Without a second factor, one of the addresses the provider has
|
||||
// confirmed must match the account email. The list is fetched only here
|
||||
// and never recorded.
|
||||
reason, matched := "no_matching_evidence", false
|
||||
if emailProvider, ok := provider.(oauth.VerifiedEmailProvider); ok && user.Email != "" {
|
||||
emails, err := emailProvider.GetVerifiedEmails(c.Request.Context(), token)
|
||||
if err != nil {
|
||||
common.SysError(fmt.Sprintf("[OAuth] Failed to load verified emails for user %d: %s", user.Id, err.Error()))
|
||||
reason = "verified_emails_unavailable"
|
||||
}
|
||||
return user, nil
|
||||
accountEmail := model.NormalizeEmail(user.Email)
|
||||
matched = slices.ContainsFunc(emails, func(email string) bool { return model.NormalizeEmail(email) == accountEmail })
|
||||
}
|
||||
if !matched {
|
||||
recordLegacyGitHubBindingAudit(c, user, false, map[string]any{"legacy_id": legacyID, "provider_user_id": oauthUser.ProviderUserID, "reason": reason})
|
||||
return nil, nil, &OAuthLegacyBindingNotConfirmedError{}
|
||||
}
|
||||
written := false
|
||||
err = model.DB.Transaction(func(tx *gorm.DB) error {
|
||||
var err error
|
||||
written, err = model.MigrateLegacyGitHubBindingWithTx(tx, user.Id, legacyID, oauthUser.ProviderUserID)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if written {
|
||||
user.GitHubId = oauthUser.ProviderUserID
|
||||
notificationFailed := service.NotifyAccountSecurityChange(user.Email, "Login account linked: "+provider.GetName()) != nil
|
||||
recordLegacyGitHubBindingAudit(c, user, true, map[string]any{
|
||||
"legacy_id": legacyID, "provider_user_id": oauthUser.ProviderUserID,
|
||||
"verified_email_matched": true, "notification_failed": notificationFailed,
|
||||
})
|
||||
}
|
||||
return user, nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
// User doesn't exist, create new user if registration is enabled
|
||||
if !common.RegisterEnabled {
|
||||
return nil, &OAuthRegistrationDisabledError{}
|
||||
return nil, nil, &OAuthRegistrationDisabledError{}
|
||||
}
|
||||
|
||||
// Set up new user
|
||||
@@ -476,9 +513,9 @@ func findOrCreateOAuthUser(c *gin.Context, provider oauth.Provider, oauthUser *o
|
||||
user.Email = model.NormalizeEmail(oauthUser.Email)
|
||||
if err := model.EnsureEmailAvailable(user.Email, 0); err != nil {
|
||||
if errors.Is(err, model.ErrEmailAlreadyTaken) {
|
||||
return nil, &OAuthEmailAlreadyTakenError{}
|
||||
return nil, nil, &OAuthEmailAlreadyTakenError{}
|
||||
}
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
user.Role = common.RoleCommonUser
|
||||
@@ -512,7 +549,7 @@ func findOrCreateOAuthUser(c *gin.Context, provider oauth.Provider, oauthUser *o
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
// Perform post-transaction tasks (logs, sidebar config, inviter rewards)
|
||||
@@ -541,14 +578,24 @@ func findOrCreateOAuthUser(c *gin.Context, provider oauth.Provider, oauthUser *o
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
// Perform post-transaction tasks
|
||||
user.FinalizeOAuthUserCreation(inviterId)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
return user, nil, nil
|
||||
}
|
||||
|
||||
// recordLegacyGitHubBindingAudit records the outcome of a legacy GitHub binding
|
||||
// rewrite as an account binding event. No session exists yet on the login path,
|
||||
// so the row carries the user's own role instead of the request context.
|
||||
func recordLegacyGitHubBindingAudit(c *gin.Context, user *model.User, success bool, params map[string]any) {
|
||||
params["provider"], params["legacy_migration"], params["success"] = "github", true, success
|
||||
model.RecordOperationAuditLog(user.Id, user.Role, auditContentEN("user.binding_bind", params), c.ClientIP(), "user.binding_bind", params, nil, &model.AuditRequestInfo{
|
||||
Method: c.Request.Method, Route: c.FullPath(), Path: c.FullPath(), Status: c.Writer.Status(), Success: success,
|
||||
}, c)
|
||||
}
|
||||
|
||||
// Error types for OAuth
|
||||
@@ -570,6 +617,14 @@ func (e *OAuthEmailAlreadyTakenError) Error() string {
|
||||
return "email is already in use"
|
||||
}
|
||||
|
||||
// OAuthLegacyBindingNotConfirmedError reports a legacy GitHub binding match that
|
||||
// neither a second factor nor a confirmed provider email backed.
|
||||
type OAuthLegacyBindingNotConfirmedError struct{}
|
||||
|
||||
func (e *OAuthLegacyBindingNotConfirmedError) Error() string {
|
||||
return "legacy binding was not confirmed"
|
||||
}
|
||||
|
||||
// handleOAuthError handles OAuth errors and returns translated message
|
||||
func handleOAuthError(c *gin.Context, err error) {
|
||||
switch e := err.(type) {
|
||||
|
||||
@@ -146,7 +146,7 @@ func TestPasskeyDomainsPreserveCredentialsAcrossVerificationFlows(t *testing.T)
|
||||
beginHandler, finishHandler := PasskeyLoginBegin, PasskeyLoginFinish
|
||||
request := map[string]any{"rp_id": legacyRPID}
|
||||
if kind == "login factor" {
|
||||
pending, err := service.StartLoginVerification(user, "password")
|
||||
pending, err := service.StartLoginVerification(user, "password", nil)
|
||||
require.NoError(t, err)
|
||||
request["flow_token"] = pending.FlowToken
|
||||
beginPath, finishPath = "/api/user/login/passkey/begin", "/api/user/login/passkey/finish"
|
||||
|
||||
+6
-4
@@ -96,7 +96,7 @@ func Login(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
setupLogin(&user, c)
|
||||
setupLogin(&user, nil, c)
|
||||
}
|
||||
|
||||
// loginMethodFromContext 根据请求路径推导登录方式,用于登录审计日志。
|
||||
@@ -144,9 +144,11 @@ func recordLoginAudit(user *model.User, c *gin.Context) {
|
||||
}
|
||||
|
||||
// setupLogin evaluates the shared login policy after primary authentication.
|
||||
// Only a completed Passkey ceremony may go directly to session issuance.
|
||||
func setupLogin(user *model.User, c *gin.Context) {
|
||||
challenge, err := service.StartLoginVerification(user, loginMethodFromContext(c))
|
||||
// Only a completed Passkey ceremony may go directly to session issuance. A
|
||||
// pending legacy GitHub binding rewrite travels inside the challenge and is
|
||||
// written only when the verification completes.
|
||||
func setupLogin(user *model.User, migration *service.LegacyGitHubMigration, c *gin.Context) {
|
||||
challenge, err := service.StartLoginVerification(user, loginMethodFromContext(c), migration)
|
||||
if err != nil {
|
||||
writeSecurityOperationError(c, err)
|
||||
return
|
||||
|
||||
@@ -121,7 +121,7 @@ func WeChatAuth(c *gin.Context) {
|
||||
})
|
||||
return
|
||||
}
|
||||
setupLogin(&user, c)
|
||||
setupLogin(&user, nil, c)
|
||||
}
|
||||
|
||||
type wechatBindRequest struct {
|
||||
|
||||
@@ -300,6 +300,7 @@ const (
|
||||
MsgOAuthUserBanned = "oauth.user_banned"
|
||||
MsgOAuthBindSuccess = "oauth.bind_success"
|
||||
MsgOAuthAlreadyBound = "oauth.already_bound"
|
||||
MsgOAuthNotAutoLinked = "oauth.not_auto_linked"
|
||||
MsgOAuthConnectFailed = "oauth.connect_failed"
|
||||
MsgOAuthTokenFailed = "oauth.token_failed"
|
||||
MsgOAuthUserInfoEmpty = "oauth.user_info_empty"
|
||||
|
||||
@@ -255,6 +255,7 @@ oauth.user_deleted: "User has been deleted"
|
||||
oauth.user_banned: "User has been banned"
|
||||
oauth.bind_success: "Binding successful"
|
||||
oauth.already_bound: "This {{.Provider}} account has already been bound"
|
||||
oauth.not_auto_linked: "This {{.Provider}} account cannot be linked to an existing account automatically, please sign in or register another way and then link {{.Provider}} in account settings"
|
||||
oauth.connect_failed: "Unable to connect to {{.Provider}} server, please try again later"
|
||||
oauth.token_failed: "Failed to get token from {{.Provider}}, please check settings"
|
||||
oauth.user_info_empty: "{{.Provider}} returned empty user info, please check settings"
|
||||
|
||||
@@ -256,6 +256,7 @@ oauth.user_deleted: "用户已注销"
|
||||
oauth.user_banned: "用户已被封禁"
|
||||
oauth.bind_success: "绑定成功"
|
||||
oauth.already_bound: "该 {{.Provider}} 账户已被绑定"
|
||||
oauth.not_auto_linked: "无法自动将该 {{.Provider}} 账户关联到现有账户,请使用其他方式登录或注册后,在账户设置中绑定 {{.Provider}}"
|
||||
oauth.connect_failed: "无法连接至 {{.Provider}} 服务器,请稍后重试"
|
||||
oauth.token_failed: "{{.Provider}} 获取 Token 失败,请检查设置"
|
||||
oauth.user_info_empty: "{{.Provider}} 获取用户信息为空,请检查设置"
|
||||
|
||||
@@ -256,6 +256,7 @@ oauth.user_deleted: "使用者已註銷"
|
||||
oauth.user_banned: "使用者已被封禁"
|
||||
oauth.bind_success: "綁定成功"
|
||||
oauth.already_bound: "該 {{.Provider}} 帳號已被綁定"
|
||||
oauth.not_auto_linked: "無法自動將該 {{.Provider}} 帳號關聯到現有帳號,請使用其他方式登入或註冊後,在帳號設定中綁定 {{.Provider}}"
|
||||
oauth.connect_failed: "無法連接至 {{.Provider}} 伺服器,請稍後重試"
|
||||
oauth.token_failed: "{{.Provider}} 獲取 Token 失敗,請檢查設定"
|
||||
oauth.user_info_empty: "{{.Provider}} 獲取使用者資訊為空,請檢查設定"
|
||||
|
||||
@@ -149,3 +149,25 @@ func UpdateUserOAuthBindingForSessionWithTx(tx *gorm.DB, identity AuthSessionIde
|
||||
// The existing unique provider/subject index rejects concurrent ownership.
|
||||
return tx.Model(&binding).Update("provider_user_id", subject).Error
|
||||
}
|
||||
|
||||
// MigrateLegacyGitHubBindingWithTx rewrites a login-name GitHub binding to the
|
||||
// numeric account ID once the login flow has confirmed the account. It reports
|
||||
// whether the row was rewritten; a row whose binding changed since it was read
|
||||
// is left untouched.
|
||||
func MigrateLegacyGitHubBindingWithTx(tx *gorm.DB, userID int, legacyID, gitHubID string) (bool, error) {
|
||||
if userID <= 0 || legacyID == "" || gitHubID == "" {
|
||||
return false, ErrAccountBindingChanged
|
||||
}
|
||||
var count int64
|
||||
if err := tx.Model(&User{}).Where("github_id = ? AND id <> ?", gitHubID, userID).Count(&count).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
if count != 0 {
|
||||
return false, ErrExternalIdentityAlreadyClaimed
|
||||
}
|
||||
result := tx.Model(&User{}).Where("id = ? AND github_id = ?", userID, legacyID).Update("github_id", gitHubID)
|
||||
if result.Error != nil {
|
||||
return false, result.Error
|
||||
}
|
||||
return result.RowsAffected == 1, nil
|
||||
}
|
||||
@@ -47,8 +47,9 @@ func getUserVerificationState(tx *gorm.DB, userID int, forUpdate bool) (*UserVer
|
||||
|
||||
// CreateUserSessionFromLoginFlow commits the one-time login authorization and
|
||||
// the resulting session together. The user lock serializes credential changes
|
||||
// and session issuance, including the per-user session limits.
|
||||
func CreateUserSessionFromLoginFlow(token string, session *UserSession, validate func(*AuthFlow, *UserVerificationState) error) error {
|
||||
// and session issuance, including the per-user session limits. validate runs
|
||||
// inside the transaction and may write through tx.
|
||||
func CreateUserSessionFromLoginFlow(token string, session *UserSession, validate func(*gorm.DB, *AuthFlow, *UserVerificationState) error) error {
|
||||
if session == nil || validate == nil {
|
||||
return ErrUserSessionInvalid
|
||||
}
|
||||
@@ -63,7 +64,7 @@ func CreateUserSessionFromLoginFlow(token string, session *UserSession, validate
|
||||
if state.Status != common.UserStatusEnabled || state.AuthVersion != session.UserAuthVersion {
|
||||
return ErrUserSessionInactive
|
||||
}
|
||||
if err := validate(flow, state); err != nil {
|
||||
if err := validate(tx, flow, state); err != nil {
|
||||
return err
|
||||
}
|
||||
now := time.Now().Unix()
|
||||
|
||||
@@ -1106,14 +1106,6 @@ func (user *User) FillUserByGitHubId() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateGitHubId updates the user's GitHub ID (used for migration from login to numeric ID)
|
||||
func (user *User) UpdateGitHubId(newGitHubId string) error {
|
||||
if user.Id == 0 {
|
||||
return errors.New("user id is empty")
|
||||
}
|
||||
return DB.Model(user).Update("github_id", newGitHubId).Error
|
||||
}
|
||||
|
||||
func (user *User) FillUserByDiscordId() error {
|
||||
if user.DiscordId == "" {
|
||||
return errors.New("discord id 为空!")
|
||||
|
||||
@@ -37,6 +37,11 @@ type gitHubUser struct {
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
type gitHubEmail struct {
|
||||
Email string `json:"email"`
|
||||
Verified bool `json:"verified"`
|
||||
}
|
||||
|
||||
func (p *GitHubProvider) GetName() string {
|
||||
return "GitHub"
|
||||
}
|
||||
@@ -158,6 +163,47 @@ func (p *GitHubProvider) GetUserInfo(ctx context.Context, token *OAuthToken) (*O
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetVerifiedEmails lists the addresses GitHub has confirmed for the signed-in
|
||||
// account. The email field of the user endpoint carries no confirmation status
|
||||
// and is not used for this.
|
||||
func (p *GitHubProvider) GetVerifiedEmails(ctx context.Context, token *OAuthToken) ([]string, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.github.com/user/emails", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token.AccessToken)
|
||||
req.Header.Set("Accept", "application/vnd.github+json")
|
||||
|
||||
client := http.Client{
|
||||
Timeout: 20 * time.Second,
|
||||
}
|
||||
res, err := client.Do(req)
|
||||
if err != nil {
|
||||
logger.LogError(ctx, fmt.Sprintf("[OAuth-GitHub] GetVerifiedEmails error: %s", err.Error()))
|
||||
return nil, NewOAuthErrorWithRaw(i18n.MsgOAuthConnectFailed, map[string]any{"Provider": "GitHub"}, err.Error())
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
if res.StatusCode != http.StatusOK {
|
||||
logger.LogError(ctx, fmt.Sprintf("[OAuth-GitHub] GetVerifiedEmails failed: status=%d", res.StatusCode))
|
||||
return nil, NewOAuthErrorWithRaw(i18n.MsgOAuthGetUserErr, map[string]any{"Provider": "GitHub"}, fmt.Sprintf("status %d", res.StatusCode))
|
||||
}
|
||||
|
||||
var emails []gitHubEmail
|
||||
if err := common.DecodeJson(res.Body, &emails); err != nil {
|
||||
logger.LogError(ctx, fmt.Sprintf("[OAuth-GitHub] GetVerifiedEmails decode error: %s", err.Error()))
|
||||
return nil, err
|
||||
}
|
||||
verified := make([]string, 0, len(emails))
|
||||
for _, email := range emails {
|
||||
if email.Verified && email.Email != "" {
|
||||
verified = append(verified, email.Email)
|
||||
}
|
||||
}
|
||||
logger.LogDebug(ctx, "[OAuth-GitHub] GetVerifiedEmails success: verified=%d", len(verified))
|
||||
return verified, nil
|
||||
}
|
||||
|
||||
func (p *GitHubProvider) IsUserIDTaken(providerUserID string) bool {
|
||||
return model.IsGitHubIdAlreadyTaken(providerUserID)
|
||||
}
|
||||
|
||||
@@ -40,3 +40,10 @@ type Provider interface {
|
||||
// (e.g. the user_oauth_bindings table) return an empty string.
|
||||
ProviderUserIDColumn() string
|
||||
}
|
||||
|
||||
// VerifiedEmailProvider is implemented by providers that can list the email
|
||||
// addresses they have confirmed for the signed-in account. The login flow uses
|
||||
// it to match a provider account against an existing account's email.
|
||||
type VerifiedEmailProvider interface {
|
||||
GetVerifiedEmails(ctx context.Context, token *OAuthToken) ([]string, error)
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"github.com/QuantumNous/new-api/model"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const LoginVerificationTTL = 5 * time.Minute
|
||||
@@ -16,9 +17,21 @@ type LoginChallenge struct {
|
||||
Methods []VerificationMethodOption `json:"methods"`
|
||||
}
|
||||
|
||||
// LegacyGitHubMigration is a GitHub binding rewrite from the stored login name
|
||||
// to the numeric account ID. On the login path it waits for the login
|
||||
// verification and is written in the transaction that issues the session.
|
||||
type LegacyGitHubMigration struct {
|
||||
GitHubID string
|
||||
LegacyID string
|
||||
}
|
||||
|
||||
// loginFlowPayload stays comparable; completion compares it with the bound copy.
|
||||
type loginFlowPayload struct {
|
||||
AuthVersion int64 `json:"auth_version"`
|
||||
LoginMethod string `json:"login_method"`
|
||||
// The GitHub binding rewrite waiting for this verification, if any.
|
||||
PendingGitHubID string `json:"pending_github_id,omitempty"`
|
||||
PendingGitHubLegacyID string `json:"pending_github_legacy_id,omitempty"`
|
||||
}
|
||||
|
||||
// LoginVerification is server-owned state read from a primary-authenticated flow.
|
||||
@@ -29,7 +42,7 @@ type LoginVerification struct {
|
||||
payload loginFlowPayload
|
||||
}
|
||||
|
||||
func StartLoginVerification(user *model.User, loginMethod string) (*LoginChallenge, error) {
|
||||
func StartLoginVerification(user *model.User, loginMethod string, migration *LegacyGitHubMigration) (*LoginChallenge, error) {
|
||||
if user == nil || user.Id <= 0 || user.AuthVersion <= 0 || loginMethod == "" {
|
||||
return nil, model.ErrAuthFlowInvalid
|
||||
}
|
||||
@@ -42,6 +55,11 @@ func StartLoginVerification(user *model.User, loginMethod string) (*LoginChallen
|
||||
}
|
||||
methods, err := securityVerificationPolicy(VerificationScopeLogin, *state)
|
||||
if err != nil || len(methods) == 0 {
|
||||
if err == nil && migration != nil {
|
||||
// The rewrite is written only after a verification, so a login that
|
||||
// no longer requires one cannot carry it.
|
||||
return nil, ErrVerificationUnavailable
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
available := false
|
||||
@@ -51,14 +69,18 @@ func StartLoginVerification(user *model.User, loginMethod string) (*LoginChallen
|
||||
if !available {
|
||||
return nil, ErrVerificationUnavailable
|
||||
}
|
||||
payload, err := common.Marshal(loginFlowPayload{AuthVersion: state.AuthVersion, LoginMethod: loginMethod})
|
||||
payload := loginFlowPayload{AuthVersion: state.AuthVersion, LoginMethod: loginMethod}
|
||||
if migration != nil {
|
||||
payload.PendingGitHubID, payload.PendingGitHubLegacyID = migration.GitHubID, migration.LegacyID
|
||||
}
|
||||
encoded, err := common.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
expiresAt := time.Now().Add(LoginVerificationTTL)
|
||||
token, _, err := model.CreateAuthFlow(model.AuthFlowCreate{
|
||||
Purpose: model.AuthFlowPurposeLoginVerification, UserId: user.Id,
|
||||
Payload: string(payload), ExpiresAt: expiresAt,
|
||||
Payload: string(encoded), ExpiresAt: expiresAt,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -105,45 +127,63 @@ func requireLoginVerificationMethod(state *model.UserVerificationState, method s
|
||||
return ErrProofMethod
|
||||
}
|
||||
|
||||
func VerifyLoginCode(token, code, ip, userAgent string) (*AuthBundle, error) {
|
||||
func VerifyLoginCode(token, code, ip, userAgent string) (*AuthBundle, *LegacyGitHubMigration, error) {
|
||||
verification, err := RequireLoginVerification(token, VerificationMethodTwoFA)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
twoFA, err := model.GetTwoFAByUserId(verification.State.UserID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
if err := VerifyTwoFactorCode(twoFA, code); err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
return CompleteLoginVerification(token, verification, VerificationMethodTwoFA, ip, userAgent)
|
||||
}
|
||||
|
||||
// CompleteLoginVerification must only run after a concrete factor ceremony.
|
||||
// Recheck the bound version and method while consuming the flow and creating the
|
||||
// session atomically; a different request cannot reuse this authorization.
|
||||
func CompleteLoginVerification(token string, verification *LoginVerification, method, ip, userAgent string) (*AuthBundle, error) {
|
||||
// session atomically; a different request cannot reuse this authorization. The
|
||||
// returned migration is non-nil when the flow's pending GitHub binding rewrite
|
||||
// was written together with the session.
|
||||
func CompleteLoginVerification(token string, verification *LoginVerification, method, ip, userAgent string) (*AuthBundle, *LegacyGitHubMigration, error) {
|
||||
if verification == nil || verification.Flow == nil || verification.State == nil {
|
||||
return nil, model.ErrAuthFlowInvalid
|
||||
return nil, nil, model.ErrAuthFlowInvalid
|
||||
}
|
||||
session, refreshSecret, err := newLoginSession(verification.State.UserID, verification.payload.AuthVersion, verification.payload.LoginMethod, ip, userAgent)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
if err := model.CreateUserSessionFromLoginFlow(token, session, func(flow *model.AuthFlow, state *model.UserVerificationState) error {
|
||||
var migration *LegacyGitHubMigration
|
||||
if err := model.CreateUserSessionFromLoginFlow(token, session, func(tx *gorm.DB, flow *model.AuthFlow, state *model.UserVerificationState) error {
|
||||
var payload loginFlowPayload
|
||||
if flow.Id != verification.Flow.Id || common.UnmarshalJsonStr(flow.Payload, &payload) != nil || payload != verification.payload {
|
||||
return model.ErrAuthFlowInvalid
|
||||
}
|
||||
return requireLoginVerificationMethod(state, method)
|
||||
if err := requireLoginVerificationMethod(state, method); err != nil {
|
||||
return err
|
||||
}
|
||||
if payload.PendingGitHubID == "" {
|
||||
return nil
|
||||
}
|
||||
// A binding that was relinked while the challenge was open is left as it
|
||||
// is and the login continues without the rewrite.
|
||||
written, err := model.MigrateLegacyGitHubBindingWithTx(tx, state.UserID, payload.PendingGitHubLegacyID, payload.PendingGitHubID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if written {
|
||||
migration = &LegacyGitHubMigration{GitHubID: payload.PendingGitHubID, LegacyID: payload.PendingGitHubLegacyID}
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
bundle, err := issueAuthBundle(session, session.SID+"."+refreshSecret, true)
|
||||
if err != nil {
|
||||
_, _ = model.RevokeUserSession(session.UserID, session.SID, "token_issue_failed")
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
return bundle, nil
|
||||
return bundle, migration, nil
|
||||
}
|
||||
Reference in new issue
Block a user