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
Add LDAP user synchronization job
Oliver Günther22cf9ea47cfd
diff --git a/app/models/auth_source.rb b/app/models/auth_source.rbindex 7b9d176f9fb..d678a3b11ff 100644--- a/app/models/auth_source.rb+++ b/app/models/auth_source.rb@@ -29,6 +29,8 @@class AuthSource < ApplicationRecordinclude Redmine::Ciphering+ class Error < ::StandardError; end+has_many :usersvalidates :name,diff --git a/app/models/ldap_auth_source.rb b/app/models/ldap_auth_source.rbindex 345c5517197..545e0d23a5a 100644--- a/app/models/ldap_auth_source.rb+++ b/app/models/ldap_auth_source.rb@@ -53,7 +53,7 @@ class LdapAuthSource < AuthSourceattrs.except(:dn)endrescue Net::LDAP::Error => e- raise 'LdapError: ' + e.message+ raise AuthSource::Error, "LdapError: #{e.message}"enddef find_user(login)@@ -66,7 +66,7 @@ class LdapAuthSource < AuthSourceattrs.except(:dn)endrescue Net::LDAP::Error => e- raise 'LdapError: ' + e.message+ raise AuthSource::Error, "LdapError: #{e.message}"end# Open and return a system connection@@ -77,10 +77,10 @@ class LdapAuthSource < AuthSource# test the connection to the LDAPdef test_connectionunless authenticate_dn(account, account_password)- raise I18n.t('auth_source.ldap_error', error_message: I18n.t('auth_source.ldap_auth_failed'))+ raise AuthSource::Error, I18n.t('auth_source.ldap_error', error_message: I18n.t('auth_source.ldap_auth_failed'))endrescue Net::LDAP::Error => e- raise I18n.t('auth_source.ldap_error', error_message: e.to_s)+ raise AuthSource::Error, I18n.t('auth_source.ldap_error', error_message: e.to_s)enddef auth_method_namediff --git a/app/services/ldap/synchronize_users_service.rb b/app/services/ldap/synchronize_users_service.rbnew file mode 100644index 00000000000..401dd6768ab--- /dev/null+++ b/app/services/ldap/synchronize_users_service.rb@@ -0,0 +1,95 @@+module Ldap+ class SynchronizeUsersService+ attr_reader :ldap, :logins++ def initialize(ldap, logins = nil)+ @ldap = ldap+ @logins = logins+ end++ def call+ Rails.logger.debug { "Start LDAP user synchronization for #{ldap.name}." }+ User.system.run_given do+ OpenProject::Mutex.with_advisory_lock_transaction(ldap, 'synchronize_users') do+ synchronize!+ end+ end+ end++ private++ def synchronize!+ ldap_con = new_ldap_connection++ applicable_users.find_each do |user|+ synchronize_user(user, ldap_con)+ rescue ::AuthSource::Error => e+ Rails.logger.error { "Failed to synchronize user #{ldap.name} due to LDAP error: #{e.message}" }+ # Reset the LDAP connection+ ldap_con = new_ldap_connection+ rescue StandardError => e+ Rails.logger.error { "Failed to synchronize user #{ldap.name}: #{e.message}" }+ end+ end++ # Get the applicable users+ # as the service can be called with just a subset of users+ # from rake/external services.+ def applicable_users+ if logins.present?+ ldap.users.where("LOWER(login) in (?)", logins.map(&:downcase))+ else+ ldap.users+ end+ end++ def new_ldap_connection+ ldap.instance_eval { initialize_ldap_con(account, account_password) }+ end++ def synchronize_user(user, ldap_con)+ Rails.logger.debug { "Synchronizing user #{user.login}." }++ update_attributes = user_attributes(user.login, ldap_con)+ if update_attributes+ try_to_update(user, update_attributes)+ else+ Rails.logger.info { "Could not find user #{user.login} in #{ldap.name}. Locking the user." }+ user.update_column(:status, Principal.statuses[:locked])+ end+ end++ # Try to create the user from attributes+ # rubocop:disable Metrics/AbcSize+ def try_to_update(user, attrs)+ call = Users::UpdateService+ .new(model: user, user: User.system)+ .call(attrs.merge)++ if call.success?+ # Ensure the user is activated+ call.result.update_column(:status, Principal.statuses[:active])+ Rails.logger.info { "[LDAP user sync] User '#{call.result.login}' updated" }+ else+ Rails.logger.error { "[LDAP user sync] User '#{user.login}' could not be updated: #{call.message}" }+ end+ end+ # rubocop:enable Metrics/AbcSize++ def user_attributes(login, ldap_con)+ # Get user login attribute and base dn which are private+ base_dn = ldap.base_dn++ search_attributes = ldap.search_attributes(true)+ login_filter = Net::LDAP::Filter.eq(ldap.attr_login, login)+ ldap_con.search(base: base_dn,+ filter: ldap.default_filter & login_filter,+ attributes: search_attributes) do |entry|+ data = ldap.get_user_attributes_from_ldap_entry(entry)+ return data.except(:dn)+ end++ nil+ end+ end+enddiff --git a/app/workers/ldap/synchronization_job.rb b/app/workers/ldap/synchronization_job.rbnew file mode 100644index 00000000000..776967bf538--- /dev/null+++ b/app/workers/ldap/synchronization_job.rb@@ -0,0 +1,49 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2022 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See COPYRIGHT and LICENSE files for more details.+#++++module Ldap+ class SynchronizationJob < ::Cron::CronJob+ # Run once per night at 11:30pm+ self.cron_expression = '30 23 * * *'++ def perform+ run_user_sync+ end++ private++ def run_user_sync+ return if OpenProject::Configuration.ldap_users_disable_sync_job?++ ::LdapAuthSource.find_each do |ldap|+ Rails.logger.info { "[LDAP groups] Synchronizing users for LDAP connection #{ldap.name}" }+ ::Ldap::SynchronizeUsersService.new(ldap).perform+ end+ end+ end+enddiff --git a/config/initializers/cronjobs.rb b/config/initializers/cronjobs.rbindex e41da17a053..3273c00a18a 100644--- a/config/initializers/cronjobs.rb+++ b/config/initializers/cronjobs.rb@@ -7,6 +7,7 @@ OpenProject::Application.configure do |application|::Cron::ClearUploadedFilesJob,::OAuth::CleanupJob,::Attachments::CleanupUncontaineredJob,- ::Notifications::ScheduleReminderMailsJob+ ::Notifications::ScheduleReminderMailsJob,+ ::Ldap::SynchronizationJobendenddiff --git a/lib/open_project/mutex.rb b/lib/open_project/mutex.rbindex 1dd1b34bf6f..84d172905ca 100644--- a/lib/open_project/mutex.rb+++ b/lib/open_project/mutex.rb@@ -54,17 +54,18 @@ module OpenProject# attachable journals for the attachment added by themselves. To the user this will look as if one of the actions# deleted the other attachment. The next action, Action 3, will then seem to have readded the attachment,# seemingly removed before.- def with_advisory_lock_transaction(entry, &block)+ def with_advisory_lock_transaction(entry, suffix = nil, &block)+ lock_name = "mutex_on_#{entry.class.name}_#{entry.id}"+ lock_name << "_#{suffix}" if suffix+ActiveRecord::Base.transaction do- with_advisory_lock(entry, &block)+ with_advisory_lock(entry.class, lock_name, &block)endend- def with_advisory_lock(entry)- lock_name = "mutex_on_#{entry.class.name}_#{entry.id}"-+ def with_advisory_lock(resource_class, lock_name)debug_log("Attempting to fetched advisory lock", lock_name)- result = entry.class.with_advisory_lock(lock_name, transaction: true) do+ result = resource_class.with_advisory_lock(lock_name, transaction: true) dodebug_log("Fetched advisory lock", lock_name)yieldenddiff --git a/lib/tasks/ldap.rake b/lib/tasks/ldap.rakeindex 48271a54439..ef372b9888a 100644--- a/lib/tasks/ldap.rake+++ b/lib/tasks/ldap.rake@@ -38,91 +38,16 @@ namespace :ldap doargsend- desc 'Synchronize users from the LDAP auth source with an optional filter' \- 'rake ldap:sync["name=<LdapAuthSource Name>", filter=<Optional RFC2254 filter string>]'+ desc 'Synchronize existing users from the LDAP auth source' \+ 'rake ldap:sync["name=<LdapAuthSource Name>", users=<login1,login2,...>]'task sync: :environment doargs = parse_argsldap = LdapAuthSource.find_by!(name: args.fetch(:name))- # Parse filter string if available- filter = Net::LDAP::Filter.from_rfc2254 args.fetch(:filter, 'objectClass = *')-- # Open LDAP connection- ldap_con = ldap.send(:initialize_ldap_con, ldap.account, ldap.account_password)-- User.transaction do- ldap_con.search(base: ldap.base_dn, filter: filter) do |entry|- user = User.find_or_initialize_by(login: entry[ldap.attr_login])- user.attributes = {- firstname: entry[ldap.attr_firstname],- lastname: entry[ldap.attr_lastname],- mail: entry[ldap.attr_mail],- admin: entry[ldap.attr_admin],- auth_source: ldap- }-- if user.changed?- prefix = user.new_record? ? 'Created' : 'Updated'- Rails.logger.info "#{prefix} user #{user.login} from ldap synchronization"- user.save- end- end- end- end-- desc 'Synchronize a list of user IDs with the LDAP auth source' \- 'rake ldap:sync_user_list LDAP=<LdapAuthSource Name>" USERLIST=<Path to file with newline separated USER ids>'- task sync_user_list: :environment do- file = ENV['USERLIST']- ldap_name = ENV['LDAP']-- ldap = LdapAuthSource.find_by!(name: ldap_name)-- # Open connection- puts "--> Opening LDAP connection"- ldap_con = ldap.instance_eval { initialize_ldap_con(account, account_password) }- base_dn = ldap.send :base_dn-- attr_login = ldap.send :attr_login- object_filter = Net::LDAP::Filter.eq('objectClass', '*')- attributes = ldap.instance_eval do- ['dn', attr_login, attr_firstname, attr_lastname, attr_mail, attr_admin]- end-- puts "--> Reading username file #{file}"- File.read(file).lines.each do |username|- # Trim and skip empty- username.chomp!- next unless username.present?-- login_filter = Net::LDAP::Filter.eq(attr_login, username)-- entries = ldap_con.search(base: base_dn, filter: object_filter & login_filter, attributes: attributes)-- if entries.count == 0- warn "Did not find entry for #{username}"- next- end-- if entries.count > 1- warn "Found multiple entries for #{username}: #{entries.map(&:dn)}. Skipping"- next- end-- entry = entries.first- user = User.find_or_initialize_by(login: LdapAuthSource.get_attr(entry, ldap.attr_login))- user.attributes = ldap.send(:get_user_attributes_from_ldap_entry, entry).except(:dn)-- if user.changed?- prefix = user.new_record? ? 'Created' : 'Updated'-- if user.save- puts "#{prefix} user #{user.login} from ldap synchronization"- else- puts "Failed to save #{user.login}: #{user.errors.full_messages.join(', ')}."- end- end- end+ logins = args.fetch(:logins, '').split(/\s*,\s*/)+ ::Ldap::SynchronizeUsersService+ .new(ldap, logins)+ .callenddesc 'Register a LDAP auth source for the given LDAP URL and attribute mapping: ' \diff --git a/modules/ldap_groups/spec/services/synchronization_spec.rb b/modules/ldap_groups/spec/services/synchronization_spec.rbindex 72d5bfee491..295accf2359 100644--- a/modules/ldap_groups/spec/services/synchronization_spec.rb+++ b/modules/ldap_groups/spec/services/synchronization_spec.rb@@ -2,20 +2,12 @@ require File.dirname(__FILE__) + '/../spec_helper'require 'ladle'describe LdapGroups::SynchronizeGroupsService, with_ee: %i[ldap_groups] do+ include_context 'with temporary LDAP'+let(:plugin_settings) do{ group_base: 'ou=groups,dc=example,dc=com', group_key: 'cn' }end- before(:all) do- ldif = Rails.root.join('spec/fixtures/ldap/users.ldif')- @ldap_server = Ladle::Server.new(quiet: false, port: ParallelHelper.port_for_ldap.to_s, domain: 'dc=example,dc=com',- ldif: ldif).start- end-- after(:all) do- @ldap_server.stop- end-# Ldap has:# three users aa729, bb459, cc414# two groups foo (aa729), bar(aa729, bb459, cc414)diff --git a/spec/services/ldap/synchronize_users_service_integration_spec.rb b/spec/services/ldap/synchronize_users_service_integration_spec.rbnew file mode 100644index 00000000000..52e9b5f24ed--- /dev/null+++ b/spec/services/ldap/synchronize_users_service_integration_spec.rb@@ -0,0 +1,115 @@+require 'spec_helper'++describe Ldap::SynchronizeUsersService do+ include_context 'with temporary LDAP'++ subject do+ described_class.new(auth_source).call+ end++ context 'when updating users' do+ let!(:user_aa729) { create :user, login: 'aa729', firstname: 'Foobar', auth_source: auth_source }+ let!(:user_bb459) { create :user, login: 'bb459', firstname: 'Bla', auth_source: auth_source }++ it 'updates the attributes of those users' do+ subject++ user_aa729.reload+ user_bb459.reload++ expect(user_aa729.firstname).to eq 'Alexandra'+ expect(user_aa729.lastname).to eq 'Adams'+ expect(user_aa729.mail).to eq '[email protected]'++ expect(user_bb459.firstname).to eq 'Belle'+ expect(user_bb459.lastname).to eq 'Baldwin'+ expect(user_bb459.mail).to eq '[email protected]'+ end++ it 'updates one user if the other fails' do+ allow(Users::UpdateService)+ .to receive(:new)+ .and_call_original++ allow(Users::UpdateService)+ .to receive(:new)+ .with(model: user_aa729, user: User.system)+ .and_raise("Some bad error happening here")++ subject++ user_aa729.reload+ user_bb459.reload++ expect(user_aa729.firstname).to eq 'Foobar'+ expect(user_aa729.lastname).to eq 'Bobbit'++ expect(user_bb459.firstname).to eq 'Belle'+ expect(user_bb459.lastname).to eq 'Baldwin'+ expect(user_bb459.mail).to eq '[email protected]'+ end++ it 'reactivates the account if it is locked' do+ user_aa729.lock!++ expect(user_aa729.reload).to be_locked++ subject++ expect(user_aa729.reload).not_to be_locked+ expect(user_aa729).to be_active+ end++ context 'when requesting only a subset of users' do+ let!(:user_cc414) { create :user, login: 'cc414', auth_source: auth_source }++ subject do+ described_class.new(auth_source, %w[Aa729 cc414]).call+ end++ it 'syncs all case-insensitive users' do+ subject++ user_aa729.reload+ user_bb459.reload+ user_cc414.reload++ expect(user_aa729.firstname).to eq 'Alexandra'+ expect(user_aa729.lastname).to eq 'Adams'+ expect(user_aa729.mail).to eq '[email protected]'++ expect(user_cc414.firstname).to eq 'Claire'+ expect(user_cc414.lastname).to eq 'Carpenter'+ expect(user_cc414.mail).to eq '[email protected]'++ expect(user_bb459.firstname).to eq 'Bla'+ expect(user_bb459.lastname).to eq 'Bobbit'+ end+ end+ end++ context 'with a user that is no longer in LDAP' do+ let(:user_foo) { create :user, login: 'login', auth_source: auth_source }++ it 'locks that user' do+ expect(user_foo).to be_active++ subject++ expect(user_foo.reload).to be_locked+ end+ end++ context 'with a user that is in another LDAP' do+ let(:auth_source2) { create :ldap_auth_source, name: 'Another LDAP' }+ let(:user_foo) { create :user, login: 'login', auth_source: auth_source2 }++ it 'does not touch that user' do+ expect(user_foo).to be_active++ subject++ expect(user_foo.reload).to be_active+ end+ end+enddiff --git a/spec/support/shared/with_test_ldap.rb b/spec/support/shared/with_test_ldap.rbnew file mode 100644index 00000000000..f564ed402ec--- /dev/null+++ b/spec/support/shared/with_test_ldap.rb@@ -0,0 +1,64 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2022 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See COPYRIGHT and LICENSE files for more details.+#+++require 'ladle'++shared_context 'with temporary LDAP' do+ # rubocop:disable RSpec/InstanceVariable+ before(:all) do+ ldif = Rails.root.join('spec/fixtures/ldap/users.ldif')+ @ldap_server = Ladle::Server.new(quiet: false,+ port: ParallelHelper.port_for_ldap.to_s,+ domain: 'dc=example,dc=com',+ ldif: ldif).start+ end++ after(:all) do+ @ldap_server.stop+ end+ # rubocop:enable RSpec/InstanceVariable++ # Ldap has:+ # three users aa729, bb459, cc414+ # two groups foo (aa729), bar(aa729, bb459, cc414)+ let(:auth_source) do+ create :ldap_auth_source,+ port: ParallelHelper.port_for_ldap.to_s,+ account: 'uid=admin,ou=system',+ account_password: 'secret',+ base_dn: 'ou=people,dc=example,dc=com',+ onthefly_register: onthefly_register,+ filter_string: ldap_filter,+ attr_login: 'uid',+ attr_firstname: 'givenName',+ attr_lastname: 'sn',+ attr_mail: 'mail'+ end++ let(:onthefly_register) { false }+ let(:ldap_filter) { nil }+end