Skip to content

Fix LDAP sync when Username Attribute is empty #25278

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Jun 20, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 32 additions & 32 deletions services/auth/source/ldap/source_sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ package ldap
import (
"context"
"fmt"
"sort"
"strings"

asymkey_model "code.gitea.io/gitea/models/asymkey"
Expand All @@ -24,7 +23,6 @@ import (
func (source *Source) Sync(ctx context.Context, updateExisting bool) error {
log.Trace("Doing: SyncExternalUsers[%s]", source.authSource.Name)

var existingUsers []int
isAttributeSSHPublicKeySet := len(strings.TrimSpace(source.AttributeSSHPublicKey)) > 0
var sshKeysNeedUpdate bool

Expand All @@ -41,9 +39,15 @@ func (source *Source) Sync(ctx context.Context, updateExisting bool) error {
default:
}

sort.Slice(users, func(i, j int) bool {
return users[i].LowerName < users[j].LowerName
})
usernameUsers := make(map[string]*user_model.User, len(users))
mailUsers := make(map[string]*user_model.User, len(users))
existingUsers := make(map[int64]struct{})

for i := range users {
u := users[i]
usernameUsers[u.LowerName] = u
mailUsers[u.Email] = u
}

sr, err := source.SearchEntries()
if err != nil {
Expand All @@ -59,11 +63,6 @@ func (source *Source) Sync(ctx context.Context, updateExisting bool) error {
log.Warn("LDAP search found no entries but did not report an error. All users will be deactivated as per settings")
}

sort.Slice(sr, func(i, j int) bool {
return sr[i].LowerName < sr[j].LowerName
})

userPos := 0
orgCache := make(map[string]*organization.Organization)
teamCache := make(map[string]*organization.Team)

Expand All @@ -86,26 +85,28 @@ func (source *Source) Sync(ctx context.Context, updateExisting bool) error {
return db.ErrCancelledf("During update of %s before completed update of users", source.authSource.Name)
default:
}
if len(su.Username) == 0 {
if len(su.Username) == 0 && len(su.Mail) == 0 {
continue
}

if len(su.Mail) == 0 {
su.Mail = fmt.Sprintf("%s@localhost", su.Username)
}

var usr *user_model.User
for userPos < len(users) && users[userPos].LowerName < su.LowerName {
userPos++
if len(su.Username) > 0 {
usr = usernameUsers[su.LowerName]
}
if usr == nil && len(su.Mail) > 0 {
usr = mailUsers[su.Mail]
}
if userPos < len(users) && users[userPos].LowerName == su.LowerName {
usr = users[userPos]
existingUsers = append(existingUsers, userPos)
if usr != nil {
existingUsers[usr.ID] = struct{}{}
}

if len(su.Mail) == 0 {
su.Mail = fmt.Sprintf("%s@localhost", su.Username)
}

fullName := composeFullName(su.Name, su.Surname, su.Username)
// If no existing user found, create one
if usr == nil {
if usr == nil && len(su.Username) > 0 {
log.Trace("SyncExternalUsers[%s]: Creating user %s", source.authSource.Name, su.Username)

usr = &user_model.User{
Expand Down Expand Up @@ -203,19 +204,18 @@ func (source *Source) Sync(ctx context.Context, updateExisting bool) error {

// Deactivate users not present in LDAP
if updateExisting {
existPos := 0
for i, usr := range users {
for existPos < len(existingUsers) && i > existingUsers[existPos] {
existPos++
for i := range users {
usr := users[i]
if _, ok := existingUsers[usr.ID]; ok {
continue
}
if usr.IsActive && (existPos >= len(existingUsers) || i < existingUsers[existPos]) {
log.Trace("SyncExternalUsers[%s]: Deactivating user %s", source.authSource.Name, usr.Name)

usr.IsActive = false
err = user_model.UpdateUserCols(ctx, usr, "is_active")
if err != nil {
log.Error("SyncExternalUsers[%s]: Error deactivating user %s: %v", source.authSource.Name, usr.Name, err)
}
log.Trace("SyncExternalUsers[%s]: Deactivating user %s", source.authSource.Name, usr.Name)

usr.IsActive = false
err = user_model.UpdateUserCols(ctx, usr, "is_active")
if err != nil {
log.Error("SyncExternalUsers[%s]: Error deactivating user %s: %v", source.authSource.Name, usr.Name, err)
}
}
}
Expand Down
24 changes: 24 additions & 0 deletions tests/integration/auth_ldap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,30 @@ func TestLDAPUserSync(t *testing.T) {
}
}

func TestLDAPUserSyncWithEmptyUsernameAttribute(t *testing.T) {
if skipLDAPTests() {
t.Skip()
return
}

session := loginUser(t, "user1")
csrf := GetCSRF(t, session, "/admin/auths/new")
payload := buildAuthSourceLDAPPayload(csrf, "", "", "", "")
payload["attribute_username"] = ""
req := NewRequestWithValues(t, "POST", "/admin/auths/new", payload)
session.MakeRequest(t, req, http.StatusSeeOther)

for _, u := range gitLDAPUsers {
req := NewRequest(t, "GET", "/admin/users?q="+u.UserName)
resp := session.MakeRequest(t, req, http.StatusOK)

htmlDoc := NewHTMLParser(t, resp.Body)

tr := htmlDoc.doc.Find("table.table tbody tr")
assert.True(t, tr.Length() == 0)
}
}

func TestLDAPUserSyncWithGroupFilter(t *testing.T) {
if skipLDAPTests() {
t.Skip()
Expand Down