OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
Update users using their LDAP attributes when logging in
Oliver Günther7a09676adc96
diff --git a/app/models/ldap_auth_source.rb b/app/models/ldap_auth_source.rbindex 7578654d365..56c650bf125 100644--- a/app/models/ldap_auth_source.rb+++ b/app/models/ldap_auth_source.rb@@ -69,12 +69,12 @@ class LdapAuthSource < ApplicationRecordwhere(onthefly_register: true).find_each do |source|beginRails.logger.debug { "Authenticating '#{login}' against '#{source.name}'" }- attrs = source.authenticate(login, password)+ user = source.authenticate(login, password)rescue StandardError => eRails.logger.error "Error during authentication: #{e.message}"- attrs = nil+ user = nilend- return attrs if attrs+ return user if userendnilend@@ -83,13 +83,13 @@ class LdapAuthSource < ApplicationRecordwhere(onthefly_register: true).find_each do |source|beginRails.logger.debug { "Looking up '#{login}' in '#{source.name}'" }- attrs = source.find_user login+ user = source.find_user loginrescue StandardError => eRails.logger.error "Error during authentication: #{e.message}"- attrs = nil+ user = nilend- return attrs if attrs+ return user if userendnilend@@ -109,11 +109,11 @@ class LdapAuthSource < ApplicationRecorddef authenticate(login, password)return nil if login.blank? || password.blank?- attrs = get_user_dn(login)+ attrs = get_user_attributes(login)if attrs && attrs[:dn] && authenticate_dn(attrs[:dn], password)Rails.logger.debug { "Authentication successful for '#{login}'" }- attrs.except(:dn)+ synchronize_user(login, attrs)endrescue Net::LDAP::Error => eraise LdapAuthSource::Error, "LdapError: #{e.message}"@@ -122,11 +122,11 @@ class LdapAuthSource < ApplicationRecorddef find_user(login)return nil if login.blank?- attrs = get_user_dn(login)+ attrs = get_user_attributes(login)if attrs && attrs[:dn]Rails.logger.debug { "Lookup successful for '#{login}'" }- attrs.except(:dn)+ synchronize_user(login, attrs)endrescue Net::LDAP::Error => eraise LdapAuthSource::Error, "LdapError: #{e.message}"@@ -170,15 +170,8 @@ class LdapAuthSource < ApplicationRecord# Return the attributes needed for the LDAP search.#- # @param all_attributes [Boolean] Whether to return all user attributes- #- # By default, it will only include the user attributes if on-the-fly registration is enabled- def search_attributes(all_attributes = onthefly_register?)- if all_attributes- ['dn', attr_login, attr_firstname, attr_lastname, attr_mail, attr_admin].compact- else- ['dn', attr_login]- end+ def search_attributes+ ['dn', attr_login, attr_firstname, attr_lastname, attr_mail, attr_admin].compactend##@@ -217,6 +210,29 @@ class LdapAuthSource < ApplicationRecordprivate+ def synchronize_user(login, attrs)+ user = mapped_user(login)++ # If onthefly_register is false, and the user is not found, do nothing+ return if user.nil?++ ::Ldap::PostLoginSyncService+ .new(self, user:, attributes: attrs.except(:dn))+ .call+ .result+ end++ def mapped_user(login)+ User.find_by(login:, ldap_auth_source_id: id) || onthefly_user(login)+ end++ def onthefly_user(login)+ return unless onthefly_register?+ return if User.by_login(login).exists?++ User.new(login:, ldap_auth_source_id: id)+ end+def strip_ldap_attributes%i[attr_login attr_firstname attr_lastname attr_mail attr_admin].each do |attr|self[attr] = self[attr].strip unless self[attr].nil?@@ -230,8 +246,7 @@ class LdapAuthSource < ApplicationRecordoptions = ldap_connection_optionsunless ldap_user.blank? && ldap_password.blank?- options.merge!(auth: { method: :simple, username: ldap_user,- password: ldap_password })+ options[:auth] = { method: :simple, username: ldap_user, password: ldap_password }endNet::LDAP.new optionsend@@ -276,7 +291,7 @@ class LdapAuthSource < ApplicationRecordend# Get the user's dn and any attributes for them, given their login- def get_user_dn(login)+ def get_user_attributes(login)ldap_con = initialize_ldap_con(account, account_password)attrs = {}@@ -289,13 +304,7 @@ class LdapAuthSource < ApplicationRecordldap_con.search(base: base_dn,filter:,attributes: search_attributes) do |entry|- attrs =- if onthefly_register?- get_user_attributes_from_ldap_entry(entry)- else- { dn: entry.dn }- end-+ attrs = get_user_attributes_from_ldap_entry(entry)Rails.logger.debug { "DN found for #{login}: #{attrs[:dn]}" }enddiff --git a/app/services/ldap/base_service.rb b/app/services/ldap/base_service.rbindex 02c481a83c4..78cfd3e5d97 100644--- a/app/services/ldap/base_service.rb+++ b/app/services/ldap/base_service.rb@@ -24,13 +24,16 @@ module LdapRails.logger.debug { "[LDAP user sync] Synchronizing user #{user.login}." }update_attributes = user_attributes(user.login, ldap_con)- lock_user!(user) if update_attributes.nil? && user.persisted?- return unless update_attributes+ synchronize_user_attributes(user, update_attributes)+ end- if user.new_record?- try_to_create(update_attributes)+ def synchronize_user_attributes(user, attributes)+ if attributes.blank?+ lock_user!(user)+ elsif user.new_record?+ try_to_create(attributes)else- try_to_update(user, update_attributes)+ try_to_update(user, attributes)endend@@ -38,7 +41,7 @@ module Ldapdef try_to_update(user, attrs)call = Users::UpdateService.new(model: user, user: User.system)- .call(attrs)+ .call(attrs.merge(ldap_auth_source_id: ldap.id))if call.success?activate_user!(user)@@ -46,18 +49,22 @@ module LdapelseRails.logger.error { "[LDAP user sync] User '#{user.login}' could not be updated: #{call.message}" }end++ callenddef try_to_create(attrs)call = Users::CreateService.new(user: User.system)- .call(attrs)+ .call(attrs.merge(ldap_auth_source_id: ldap.id))if call.success?Rails.logger.info { "[LDAP user sync] User '#{call.result.login}' created." }elseRails.logger.error { "[LDAP user sync] User '#{attrs[:login]}' could not be created: #{call.message}" }end++ callend##@@ -113,7 +120,7 @@ module Ldap.search(base: ldap.base_dn,filter: ldap.login_filter(login),- attributes: ldap.search_attributes(true)+ attributes: ldap.search_attributes).map { |entry| ldap.get_user_attributes_from_ldap_entry(entry).except(:dn) }enddiff --git a/app/services/ldap/import_users_from_filter_service.rb b/app/services/ldap/import_users_from_filter_service.rbindex 2e2cda1f3e9..a5f236b409f 100644--- a/app/services/ldap/import_users_from_filter_service.rb+++ b/app/services/ldap/import_users_from_filter_service.rb@@ -22,7 +22,7 @@ module Ldapldap_con.search(base: ldap.base_dn,filter: filter & ldap.default_filter,- attributes: ldap.search_attributes(true),+ attributes: ldap.search_attributes,&)enddiff --git a/app/services/ldap/post_login_sync_service.rb b/app/services/ldap/post_login_sync_service.rbnew file mode 100644index 00000000000..0d03a25c146--- /dev/null+++ b/app/services/ldap/post_login_sync_service.rb@@ -0,0 +1,21 @@+module Ldap+ class PostLoginSyncService < BaseService+ attr_reader :user, :update_attributes++ def initialize(ldap, user:, attributes:)+ super(ldap)++ @user = user+ @update_attributes = attributes+ end++ private++ def perform+ synchronize_user_attributes(user, update_attributes)+ rescue StandardError => e+ Rails.logger.error { "Failed to synchronize user after login #{ldap.name}: #{e.message}" }+ ServiceResult.failure(message: "Failed to synchronize user #{user.login}: #{e.message}")+ end+ end+enddiff --git a/config/locales/en.yml b/config/locales/en.ymlindex 63a51557a13..c7cc9e2a445 100644--- a/config/locales/en.yml+++ b/config/locales/en.yml@@ -117,6 +117,7 @@ en:ldap_auth_sources:ldap_error: "LDAP-Error: %{error_message}"ldap_auth_failed: "Could not authenticate at the LDAP-Server."+ sync_failed: "Failed to synchronize from LDAP: %{message}."back_to_index: "Click here to go back to the list of connection."technical_warning_html: |This LDAP form requires technical knowledge of your LDAP / Active Directory setup.diff --git a/modules/ldap_groups/app/services/ldap_groups/synchronize_groups_service.rb b/modules/ldap_groups/app/services/ldap_groups/synchronize_groups_service.rbindex 3de04be8196..d7257958c13 100644--- a/modules/ldap_groups/app/services/ldap_groups/synchronize_groups_service.rb+++ b/modules/ldap_groups/app/services/ldap_groups/synchronize_groups_service.rb@@ -101,7 +101,7 @@ module LdapGroupsusers = {}# Override the default search attributes from the ldap# if we have sync_users enabled, to also get user attributes- search_attributes = ldap.search_attributes(group.sync_users)+ search_attributes = ldap.search_attributesldap_con.search(base: base_dn,filter: memberof_filter(group),attributes: search_attributes) do |entry|diff --git a/modules/ldap_groups/lib/tasks/ldap_groups.rake b/modules/ldap_groups/lib/tasks/ldap_groups.rakeindex 541e34a640c..c8bbf70fc51 100644--- a/modules/ldap_groups/lib/tasks/ldap_groups.rake+++ b/modules/ldap_groups/lib/tasks/ldap_groups.rake@@ -28,7 +28,7 @@namespace :ldap_groups dodesc 'Synchronize groups and their users from the LDAP auth source.' \- 'Will only synchronize for those users already present in the application.'+ 'Will only synchronize for those users already present in the application.'task synchronize: :environment doLdapGroups::SynchronizationService.synchronize!end@@ -53,40 +53,70 @@ namespace :ldap_groups donamespace :development dodesc 'Create a development LDAP server from the fixtures LDIF'- task :ldap_server do+ task ldap_server: :environment dorequire 'ladle'ldif = ENV.fetch('LDIF_FILE') { Rails.root.join('spec/fixtures/ldap/users.ldif') }ldap_server = Ladle::Server.new(quiet: false, port: '12389', domain: 'dc=example,dc=com', ldif:).start- puts <<~EOS- #{' '}- LDAP server ready at localhost:12389- Users Base dn: ou=people,dc=example,dc=com- Admin account: uid=admin,ou=system- Admin password: secret- #{' '}- --------------------------------------------------------- #{' '}- Attributes- Login: uid- First name: givenName- Last name: sn- Email: mail- memberOf: (Hard-coded, not virtual)- #{' '}- --------------------------------------------------------- #{' '}- Users:- uid=aa729,ou=people,dc=example,dc=com (Password: smada)- uid=bb459,ou=people,dc=example,dc=com (Password: niwdlab)- uid=cc414,ou=people,dc=example,dc=com (Password: retneprac)- #{' '}- --------------------------------------------------------- #{' '}- Groups:- cn=foo,ou=groups,dc=example,dc=com (Members: aa729)- cn=bar,ou=groups,dc=example,dc=com (Members: aa729, bb459, cc414)- EOS+ puts <<~INFO+ LDAP server ready at localhost:12389+ Users Base dn: ou=people,dc=example,dc=com+ Admin account: uid=admin,ou=system+ Admin password: secret++ --------------------------------------------------------++ Attributes+ Login: uid+ First name: givenName+ Last name: sn+ Email: mail+ Admin: isAdmin+ memberOf: (Hard-coded, not virtual)++ --------------------------------------------------------++ Users:+ uid=aa729,ou=people,dc=example,dc=com (Password: smada)+ uid=bb459,ou=people,dc=example,dc=com (Password: niwdlab)+ uid=cc414,ou=people,dc=example,dc=com (Password: retneprac)++ --------------------------------------------------------++ Groups:+ cn=foo,ou=groups,dc=example,dc=com (Members: aa729)+ cn=bar,ou=groups,dc=example,dc=com (Members: aa729, bb459, cc414)+ INFO++ puts "Creating a connection called ladle"+ source = LdapAuthSource.find_or_initialize_by(name: 'ladle local development')++ source.attributes = {+ host: 'localhost',+ port: '12389',+ tls_mode: 'plain_ldap',+ account: 'uid=admin,ou=system',+ account_password: 'secret',+ base_dn: 'dc=example,dc=com',+ onthefly_register: true,+ attr_login: 'uid',+ attr_firstname: 'givenName',+ attr_lastname: 'sn',+ attr_mail: 'mail',+ attr_admin: 'isAdmin'+ }++ source.save!++ filter = LdapGroups::SynchronizedFilter.find_or_initialize_by(ldap_auth_source: source, name: 'All groups')+ filter.group_name_attribute = 'dn'+ filter.sync_users = true+ filter.filter_string = '(cn=*)'+ filter.base_dn = 'ou=groups,dc=example,dc=com'++ filter.save!++ ::LdapGroups::SynchronizationJob.perform_nowputs "Send CTRL+D to stop the server"require 'irb'diff --git a/spec/models/ldap_auth_source_spec.rb b/spec/models/ldap_auth_source_spec.rbindex 617770fed94..e932106156d 100644--- a/spec/models/ldap_auth_source_spec.rb+++ b/spec/models/ldap_auth_source_spec.rb@@ -236,7 +236,7 @@ RSpec.describe LdapAuthSource doaccount_password: 'secret',base_dn: 'ou=people,dc=example,dc=com',filter_string:,- onthefly_register: true,+ onthefly_register:,attr_login: 'uid',attr_firstname: 'givenName',attr_lastname: 'sn',@@ -244,6 +244,7 @@ RSpec.describe LdapAuthSource doattr_admin:)end+ let(:onthefly_register) { true }let(:filter_string) { nil }let(:attr_admin) { nil }@@ -252,45 +253,144 @@ RSpec.describe LdapAuthSource dolet(:attr_admin) { 'isAdmin' }it 'maps for the admin user in ldap', :aggregate_failures do- admin_attributes = ldap.find_user('ldap_admin')- expect(admin_attributes).to be_a Hash- expect(admin_attributes[:firstname]).to eq 'LDAP'- expect(admin_attributes[:lastname]).to eq 'Adminuser'- expect(admin_attributes[:admin]).to eq true-- admin_attributes = ldap.find_user('bb459')- expect(admin_attributes).to be_a Hash- expect(admin_attributes[:firstname]).to eq 'Belle'- expect(admin_attributes[:lastname]).to eq 'Baldwin'- expect(admin_attributes[:admin]).to eq false+ admin = ldap.find_user('ldap_admin')+ expect(admin).to be_a User+ expect(admin.firstname).to eq 'LDAP'+ expect(admin.lastname).to eq 'Adminuser'+ expect(admin.admin).to eq true++ user = ldap.find_user('bb459')+ expect(user).to be_a User+ expect(user.firstname).to eq 'Belle'+ expect(user.lastname).to eq 'Baldwin'+ expect(user.admin).to eq false+ end++ context 'with an existing user and different attributes' do+ let!(:user) { create(:user, ldap_auth_source: ldap, login: 'ldap_admin') }++ it 'updates the user' do+ expect(user.firstname).to eq 'Bob'+ expect(user).not_to be_admin++ user = ldap.find_user('ldap_admin')+ expect(user).to be_a User+ expect(user.firstname).to eq 'LDAP'+ expect(user.lastname).to eq 'Adminuser'+ expect(user).to be_admin+ expect(user.ldap_auth_source_id).to eq ldap.id+ endendendend- describe '#authenticate' do+ describe 'looking up and authenticating users' docontext 'with a valid LDAP user' do- it 'returns the user attributes' do- attributes = ldap.authenticate('bb459', 'niwdlab')- expect(attributes).to be_a Hash- expect(attributes[:firstname]).to eq 'Belle'- expect(attributes[:lastname]).to eq 'Baldwin'- expect(attributes[:mail]).to eq '[email protected]'- expect(attributes[:ldap_auth_source_id]).to eq ldap.id-- expect { User.new(attributes) }.not_to raise_error+ it 'authenticates the user' do+ user = ldap.authenticate('bb459', 'niwdlab')+ expect(user).to be_a User+ expect(user.firstname).to eq 'Belle'+ expect(user.lastname).to eq 'Baldwin'+ expect(user.mail).to eq '[email protected]'+ expect(user.ldap_auth_source_id).to eq ldap.id+ end++ it 'finds the user' do+ user = ldap.find_user('bb459')+ expect(user).to be_a User+ expect(user.firstname).to eq 'Belle'+ expect(user.lastname).to eq 'Baldwin'+ expect(user.mail).to eq '[email protected]'+ expect(user.ldap_auth_source_id).to eq ldap.id+ end+ end++ context 'with an existing user and different attributes' do+ let!(:user) { create(:user, ldap_auth_source: ldap, login: 'bb459') }++ it 'updates the user' do+ expect(user.firstname).to eq 'Bob'++ user = ldap.find_user('bb459')+ expect(user).to be_a User+ expect(user.firstname).to eq 'Belle'+ expect(user.lastname).to eq 'Baldwin'+ expect(user.mail).to eq '[email protected]'+ expect(user.ldap_auth_source_id).to eq ldap.id+ end+ end++ context 'with a valid LDAP user that exists, but not for the ldap connection' do+ let!(:other_ldap) { create(:ldap_auth_source, name: 'other') }+ let!(:user) { create(:user, ldap_auth_source: other_ldap, login: 'bb459') }++ it 'does not authenticate as the user does not exist for the ldap' do+ user = ldap.authenticate('bb459', 'niwdlab')+ expect(user).to be_nil+ end++ it 'does not find as the user does not exist for the ldap' do+ user = ldap.find_user('bb459')+ expect(user).to be_nil+ end+ end++ context 'when the LDAP is not onthefly_register' do+ let(:onthefly_register) { false }++ context 'with a valid LDAP user that does not exist' do+ it 'does not authenticate as the user does not exist' do+ user = ldap.authenticate('bb459', 'niwdlab')+ expect(user).to be_nil+ end++ it 'does not find as the user does not exist' do+ user = ldap.find_user('bb459')+ expect(user).to be_nil+ end+ end++ context 'with a valid LDAP user that exists, but not for the ldap connection' do+ let!(:other_ldap) { create(:ldap_auth_source, name: 'other') }+ let!(:user) { create(:user, ldap_auth_source: other_ldap, login: 'bb459') }++ it 'does not authenticate as the user does not exist for the ldap' do+ user = ldap.authenticate('bb459', 'niwdlab')+ expect(user).to be_nil+ end++ it 'does not find as the user does not exist for the ldap' do+ user = ldap.find_user('bb459')+ expect(user).to be_nil+ end+ end+ end++ context 'with the wrong LDAP user password' do+ it 'does not authenticate' do+ user = ldap.authenticate('bb459', 'asdf')+ expect(user).to be_nilendendcontext 'with an invalid LDAP user' do- it 'returns nil' do+ it 'returns nil for authenticate' doexpect(ldap.authenticate('nouser', 'whatever')).to be_nilend++ it 'returns nil for find_user' do+ expect(ldap.find_user('nouser')).to be_nil+ endendcontext 'without a login' do- it 'returns nil' do+ it 'returns nil for authenticate' doexpect(ldap.authenticate('', 'whatever')).to be_nilend++ it 'returns nil for find_user' do+ expect(ldap.find_user('')).to be_nil+ endendcontext 'without a password' do@@ -306,9 +406,20 @@ RSpec.describe LdapAuthSource doexpect(ldap.authenticate('bb459', 'niwdlab')).to be_nilend+ it 'no longer finds bb254' do+ expect(ldap.find_user('bb459')).to be_nil+ end++ it 'still finds aa729' do+ user = ldap.find_user('aa729')+ expect(user).to be_a User+ expect(user.firstname).to eq 'Alexandra'+ end+it 'still authenticates aa729' do- attributes = ldap.authenticate('aa729', 'smada')- expect(attributes[:firstname]).to eq 'Alexandra'+ user = ldap.authenticate('aa729', 'smada')+ expect(user).to be_a User+ expect(user.firstname).to eq 'Alexandra'endendenddiff --git a/spec/services/ldap/post_login_sync_service_spec.rb b/spec/services/ldap/post_login_sync_service_spec.rbnew file mode 100644index 00000000000..d2ea4f0cba9--- /dev/null+++ b/spec/services/ldap/post_login_sync_service_spec.rb@@ -0,0 +1,92 @@+require 'spec_helper'++RSpec.describe Ldap::PostLoginSyncService do+ let!(:ldap) { create(:ldap_auth_source) }+ let(:admin) { false }+ let(:attributes) do+ {+ login: 'aa729',+ admin:,+ firstname: 'Alexandra',+ lastname: 'Adams',+ mail: '[email protected]',+ ldap_auth_source_id: ldap.id+ }+ end++ subject do+ described_class.new(ldap, user:, attributes:).call+ end++ context 'with an existing user' do+ let!(:user) { create(:user, firstname: 'Bob', lastname: 'Bobbit', mail: '[email protected]', login: 'aa729') }++ it 'syncs the attributes' do+ expect(user.firstname).to eq 'Bob'+ expect(user.lastname).to eq 'Bobbit'+ expect(user.mail).to eq '[email protected]'++ expect(subject).to be_success+ expect(subject.result).to be_a User+ expect(subject.result).to be_valid+ expect(subject.result.firstname).to eq 'Alexandra'+ expect(subject.result.lastname).to eq 'Adams'+ expect(subject.result.mail).to eq '[email protected]'+ end++ context 'with nil attributes' do+ let(:attributes) { nil }++ it 'locks the user when enabled', with_config: { ldap_users_sync_status: true } do+ expect(user).to be_active++ subject++ expect(user.reload).to be_locked+ end++ it 'does nothing when not enabled', with_config: { ldap_users_sync_status: false } do+ expect(user).to be_active++ expect { subject }.not_to change(user, :attributes)+ end+ end++ context 'with empty attributes' do+ let(:attributes) { {} }++ it 'locks the user when enabled', with_config: { ldap_users_sync_status: true } do+ expect(user).to be_active++ subject++ expect(user.reload).to be_locked+ end++ it 'does nothing when not enabled', with_config: { ldap_users_sync_status: false } do+ expect(user).to be_active++ expect { subject }.not_to change(user, :attributes)+ end+ end+ end++ context 'with a new user' do+ let!(:user) { build(:user, firstname: 'Bob', lastname: 'Bobbit', mail: '[email protected]', login: 'aa729') }++ it 'creates the user' do+ expect(user.firstname).to eq 'Bob'+ expect(user.lastname).to eq 'Bobbit'+ expect(user.mail).to eq '[email protected]'+ expect(user).to be_new_record++ expect(subject).to be_success+ expect(subject.result).to be_a User+ expect(subject.result).to be_valid+ expect(subject.result.firstname).to eq 'Alexandra'+ expect(subject.result.lastname).to eq 'Adams'+ expect(subject.result.mail).to eq '[email protected]'+ expect(subject.result).to be_persisted+ end+ end+end