Skip to content

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

Add LDAP auth source filter functionality

Oliver Günthera8c6e45a92ea
diff --git a/app/models/ldap_auth_source.rb b/app/models/ldap_auth_source.rb
index c03c7933852..686756f1c1d 100644
--- a/app/models/ldap_auth_source.rb
+++ b/app/models/ldap_auth_source.rb
@@ -39,6 +39,8 @@ class LdapAuthSource < AuthSource
validates_length_of :attr_login, :attr_firstname, :attr_lastname, :attr_mail, :attr_admin, maximum: 30, allow_nil: true
validates_numericality_of :port, only_integer: true
+ validate :validate_filter_string
+
before_validation :strip_ldap_attributes
after_initialize :set_default_port
@@ -106,6 +108,13 @@ class LdapAuthSource < AuthSource
end
end
+ ##
+ # Returns the filter object used for searching
+ def default_filter
+ object_filter = Net::LDAP::Filter.eq('objectClass', '*')
+ parsed_filter_string || object_filter
+ end
+
private
def strip_ldap_attributes
@@ -143,14 +152,14 @@ class LdapAuthSource < AuthSource
def get_user_dn(login)
ldap_con = initialize_ldap_con(account, account_password)
login_filter = Net::LDAP::Filter.eq(attr_login, login)
- object_filter = Net::LDAP::Filter.eq('objectClass', '*')
+
attrs = {}
Rails.logger.debug {
- "LDAP initializing search (BASE=#{base_dn}), (FILTER=#{(object_filter & login_filter).to_s})"
+ "LDAP initializing search (BASE=#{base_dn}), (FILTER=#{(default_filter & login_filter).to_s})"
}
ldap_con.search(base: base_dn,
- filter: object_filter & login_filter,
+ filter: default_filter & login_filter,
attributes: search_attributes) do |entry|
if onthefly_register?
attrs = get_user_attributes_from_ldap_entry(entry)
@@ -173,4 +182,16 @@ class LdapAuthSource < AuthSource
def set_default_port
self.port = 389 if port.to_i == 0
end
+
+ def parsed_filter_string
+ Net::LDAP::Filter.from_rfc2254(filter_string) if filter_string
+ end
+
+ private
+
+ def validate_filter_string
+ parsed_filter_string
+ rescue Net::LDAP::FilterSyntaxInvalidError
+ errors.add :filter_string, :invalid
+ end
end
diff --git a/app/models/permitted_params.rb b/app/models/permitted_params.rb
index 5a755513f77..8fd848ff39b 100644
--- a/app/models/permitted_params.rb
+++ b/app/models/permitted_params.rb
@@ -449,6 +449,7 @@ class PermittedParams
account
account_password
base_dn
+ filter_string
onthefly_register
attr_login
attr_firstname
diff --git a/app/views/ldap_auth_sources/_form.html.erb b/app/views/ldap_auth_sources/_form.html.erb
index 1f9a47ef3bb..1ed4d10bb36 100644
--- a/app/views/ldap_auth_sources/_form.html.erb
+++ b/app/views/ldap_auth_sources/_form.html.erb
@@ -118,11 +118,21 @@ See docs/COPYRIGHT.rdoc for more details.
<fieldset class="form--fieldset">
<legend class="form--fieldset-legend"><%=t('ldap_auth_sources.ldap_details')%></legend>
<div class="form--field">
- <%= f.text_field 'base_dn', size: 60, container_class: '-wide' %>
+ <%= f.text_field :base_dn, size: 60, container_class: '-wide' %>
<span class="form--field-instructions">
<%= t('ldap_auth_sources.attribute_texts.base_dn') %>
</span>
</div>
+ <div class="form--field">
+ <%= f.text_area :filter_string,
+ rows: 10,
+ placeholder: "#{t(:label_default)}: (objectClass=*)",
+ container_class: '-wide' %>
+ <div class="form--field-instructions">
+ <p><%= t('ldap_auth_sources.attribute_texts.filter_string') %></p>
+ <p><%= t('ldap_auth_sources.attribute_texts.filter_string_concat') %></p>
+ </div>
+ </div>
<div class="form--field">
<%= f.check_box 'onthefly_register', label: AuthSource.human_attribute_name(:onthefly) %>
<div class="form--field-instructions">
diff --git a/config/locales/en.yml b/config/locales/en.yml
index 35266aecf16..bb90add6c37 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -120,6 +120,12 @@ en:
Enter the Base DN of the subtree in LDAP you want OpenProject to look for users and groups.
OpenProject will filter for provided usernames in this subtree only.
Example: ou=users,dc=example,dc=com
+ filter_string: |
+ Add an optional RFC4515 filter to apply to the results returned for users filtered in the LDAP.
+ This can be used to restrict the set of users that are found by OpenProject for authentication and group synchronization.
+ filter_string_concat: |
+ OpenProject will always filter for the login attribute provided by the user to identify the record. If you provide a filter here,
+ it will be concatenated with an AND. By default, a catch-all (objectClass=*) will be used as a filter.
onthefly_register: |
If you check this box, OpenProject will automatically create new users from their LDAP entries
when they first authenticate with OpenProject.
@@ -402,7 +408,7 @@ en:
attr_mail: "Email attribute"
base_dn: "Base DN"
host: "Host"
- onthefly: "On-the-fly user creation"
+ onthefly: "Automatic user creation"
port: "Port"
changeset:
repository: "Repository"
diff --git a/db/migrate/20200427121606_add_filter_to_ldap.rb b/db/migrate/20200427121606_add_filter_to_ldap.rb
new file mode 100644
index 00000000000..d2fa9097064
--- /dev/null
+++ b/db/migrate/20200427121606_add_filter_to_ldap.rb
@@ -0,0 +1,5 @@
+class AddFilterToLdap < ActiveRecord::Migration[6.0]
+ def change
+ add_column :auth_sources, :filter_string, :text, null: true
+ end
+end
diff --git a/modules/ldap_groups/app/models/ldap_groups/synchronized_group.rb b/modules/ldap_groups/app/models/ldap_groups/synchronized_group.rb
index 3616274fae0..af9cb3ad047 100644
--- a/modules/ldap_groups/app/models/ldap_groups/synchronized_group.rb
+++ b/modules/ldap_groups/app/models/ldap_groups/synchronized_group.rb
@@ -13,6 +13,7 @@ module LdapGroups
has_many :users,
class_name: '::LdapGroups::Membership',
+ dependent: :delete_all,
foreign_key: 'group_id'
validates_presence_of :dn
@@ -35,7 +36,6 @@ module LdapGroups
def remove_members!(users_to_remove)
self.class.transaction do
user_ids = users_to_remove.pluck(:user_id)
- users_to_remove.destroy_all
# We don't have access to the join table
# so we need to ensure we delete the users that are still present in the group
diff --git a/modules/ldap_groups/lib/open_project/ldap_groups/synchronization.rb b/modules/ldap_groups/lib/open_project/ldap_groups/synchronization.rb
index 1b96e087cca..78047bfa962 100644
--- a/modules/ldap_groups/lib/open_project/ldap_groups/synchronization.rb
+++ b/modules/ldap_groups/lib/open_project/ldap_groups/synchronization.rb
@@ -79,11 +79,9 @@ module OpenProject::LdapGroups
# memberOf filter to identifiy member entries of the group
memberof_filter = Net::LDAP::Filter.eq('memberOf', group.dn)
- # TODO add ldap filter
-
users = {}
ldap_con.search(base: base_dn,
- filter: memberof_filter,
+ filter: ldap.default_filter & memberof_filter,
attributes: ldap.search_attributes) do |entry|
data = ldap.get_user_attributes_from_ldap_entry(entry)
users[data[:login]] = data.except(:dn)
@@ -125,6 +123,7 @@ module OpenProject::LdapGroups
Rails.logger.info "[LDAP groups] Removing users #{memberships.pluck(:user_id)} from #{sync.dn}"
sync.remove_members!(memberships)
+ memberships.delete_all
end
end
end
diff --git a/modules/ldap_groups/lib/open_project/ldap_groups/synchronize_filter.rb b/modules/ldap_groups/lib/open_project/ldap_groups/synchronize_filter.rb
index d54d9c43d96..9e3f897d824 100644
--- a/modules/ldap_groups/lib/open_project/ldap_groups/synchronize_filter.rb
+++ b/modules/ldap_groups/lib/open_project/ldap_groups/synchronize_filter.rb
@@ -77,7 +77,7 @@ module OpenProject::LdapGroups
Group.where(id: sync.group_id).update_all(lastname: name)
else
# Create an OpenProject group
- entry.group = Group.find_or_initialize_by(groupname: name)
+ sync.group = Group.find_or_initialize_by(groupname: name)
end
end
diff --git a/modules/ldap_groups/spec/lib/synchronization_spec.rb b/modules/ldap_groups/spec/lib/synchronization_spec.rb
index c40d6f53b7b..4a032f0101b 100644
--- a/modules/ldap_groups/spec/lib/synchronization_spec.rb
+++ b/modules/ldap_groups/spec/lib/synchronization_spec.rb
@@ -7,7 +7,7 @@ describe OpenProject::LdapGroups::Synchronization, with_ee: %i[ldap_groups] do
end
before(:all) do
- ldif = File.expand_path('../../fixtures/users.ldif', __FILE__)
+ ldif = Rails.root.join('spec/fixtures/ldap/users.ldif')
@ldap_server = Ladle::Server.new(quiet: false, port: '12389', domain: 'dc=example,dc=com', ldif: ldif).start
end
@@ -25,6 +25,7 @@ describe OpenProject::LdapGroups::Synchronization, with_ee: %i[ldap_groups] do
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',
@@ -32,6 +33,7 @@ describe OpenProject::LdapGroups::Synchronization, with_ee: %i[ldap_groups] do
end
let(:onthefly_register) { false }
+ let(:ldap_filter) { nil }
let(:user_aa729) { FactoryBot.create :user, login: 'aa729', auth_source: auth_source }
let(:user_bb459) { FactoryBot.create :user, login: 'bb459', auth_source: auth_source }
@@ -177,6 +179,22 @@ describe OpenProject::LdapGroups::Synchronization, with_ee: %i[ldap_groups] do
expect(group_bar.users).to contain_exactly(user_aa729, user_bb459, user_cc414)
end
end
+
+ context 'with an LDAP filter for users starting with b and on-the-fly enabled' do
+ let(:onthefly_register) { true }
+ let(:ldap_filter) { '(uid=b*)' }
+ let(:user_bb459) { User.find_by login: 'bb459' }
+
+ it 'creates the remaining users' do
+ subject
+ expect(synced_foo.users.count).to eq(0)
+ expect(synced_bar.users.count).to eq(1)
+
+ expect(User.find_by(login: 'aa729')).to eq nil
+ # Only matched users are added to the group, meaning cc414 is not added
+ expect(group_bar.users).to contain_exactly(user_bb459)
+ end
+ end
end
end
diff --git a/modules/ldap_groups/spec/lib/synchronize_filter_spec.rb b/modules/ldap_groups/spec/lib/synchronize_filter_spec.rb
index 920d52e9c16..82d18a5720d 100644
--- a/modules/ldap_groups/spec/lib/synchronize_filter_spec.rb
+++ b/modules/ldap_groups/spec/lib/synchronize_filter_spec.rb
@@ -3,7 +3,7 @@ require 'ladle'
describe OpenProject::LdapGroups::SynchronizeFilter, with_ee: %i[ldap_groups] do
before(:all) do
- ldif = File.expand_path('../../fixtures/users.ldif', __FILE__)
+ ldif = Rails.root.join('spec/fixtures/ldap/users.ldif')
@ldap_server = Ladle::Server.new(quiet: false, port: '12389', domain: 'dc=example,dc=com', ldif: ldif).start
end
diff --git a/spec/fixtures/ldap/slapd.conf b/spec/fixtures/ldap/slapd.conf
deleted file mode 100644
index 290f358e267..00000000000
--- a/spec/fixtures/ldap/slapd.conf
+++ /dev/null
@@ -1,19 +0,0 @@
-# Sample OpenLDAP configuration file for Redmine LDAP test server
-#
-ucdata-path ./ucdata
-include ./schema/core.schema
-include ./schema/cosine.schema
-include ./schema/inetorgperson.schema
-include ./schema/openldap.schema
-include ./schema/nis.schema
-
-pidfile ./run/slapd.pid
-argsfile ./run/slapd.args
-
-database bdb
-suffix "dc=redmine,dc=org"
-rootdn "cn=Manager,dc=redmine,dc=org"
-rootpw secret
-directory ./redmine
-# Indices to maintain
-index objectClass eq
diff --git a/spec/fixtures/ldap/test-ldap.ldif b/spec/fixtures/ldap/test-ldap.ldif
deleted file mode 100644
index 7d9e109cc44..00000000000
--- a/spec/fixtures/ldap/test-ldap.ldif
+++ /dev/null
@@ -1,82 +0,0 @@
-dn: dc=redmine,dc=org
-objectClass: top
-objectClass: dcObject
-objectClass: organization
-o: redmine.org
-dc: redmine
-structuralObjectClass: organization
-entryUUID: 886f5fca-0a87-102e-8d06-67c361d9bd2d
-creatorsName:
-createTimestamp: 20090721211642Z
-entryCSN: 20090721211642.955188Z#000000#000#000000
-modifiersName:
-modifyTimestamp: 20090721211642Z
-
-dn: cn=admin,dc=redmine,dc=org
-objectClass: simpleSecurityObject
-objectClass: organizationalRole
-cn: admin
-description: LDAP administrator
-userPassword:: e2NyeXB0fWlWTU9DcUt6WWxXRDI=
-structuralObjectClass: organizationalRole
-entryUUID: 88704e44-0a87-102e-8d07-67c361d9bd2d
-creatorsName:
-createTimestamp: 20090721211642Z
-entryCSN: 20090721211642.961418Z#000000#000#000000
-modifiersName:
-modifyTimestamp: 20090721211642Z
-
-dn: ou=Person,dc=redmine,dc=org
-ou: Person
-objectClass: top
-objectClass: organizationalUnit
-structuralObjectClass: organizationalUnit
-entryUUID: d39dd388-0c84-102e-82fa-dff86c63a7d6
-creatorsName: cn=admin,dc=redmine,dc=org
-createTimestamp: 20090724100222Z
-entryCSN: 20090724100222.924226Z#000000#000#000000
-modifiersName: cn=admin,dc=redmine,dc=org
-modifyTimestamp: 20090724100222Z
-
-dn: uid=example1,ou=Person,dc=redmine,dc=org
-objectClass: posixAccount
-objectClass: top
-objectClass: inetOrgPerson
-gidNumber: 0
-givenName: Example
-sn: One
-uid: example1
-homeDirectory: /home/example1
-cn: Example One
-structuralObjectClass: inetOrgPerson
-entryUUID: 285d304e-0c8a-102e-82fc-dff86c63a7d6
-creatorsName: cn=admin,dc=redmine,dc=org
-createTimestamp: 20090724104032Z
-uidNumber: 0
-userPassword:: e1NIQX1mRXFOQ2NvM1lxOWg1WlVnbEQzQ1pKVDRsQnM9
-entryCSN: 20090724105945.375801Z#000000#000#000000
-modifiersName: cn=admin,dc=redmine,dc=org
-modifyTimestamp: 20090724105945Z
-
-dn: uid=edavis,ou=Person,dc=redmine,dc=org
-objectClass: posixAccount
-objectClass: top
-objectClass: inetOrgPerson
-gidNumber: 0
-givenName: Eric
-sn: Davis
-uid: edavis
-structuralObjectClass: inetOrgPerson
-entryUUID: 9c5f0502-0c8b-102e-82fe-dff86c63a7d6
-creatorsName: cn=admin,dc=redmine,dc=org
-createTimestamp: 20090724105056Z
-homeDirectory: /home/edavis
-cn: Eric Davis
-uidNumber: 0
-userPassword:: e1NIQX1mRXFOQ2NvM1lxOWg1WlVnbEQzQ1pKVDRsQnM9
-entryCSN: 20090724105937.734480Z#000000#000#000000
-modifiersName: cn=admin,dc=redmine,dc=org
-modifyTimestamp: 20090724105937Z
-
diff --git a/modules/ldap_groups/spec/fixtures/users.ldif b/spec/fixtures/ldap/users.ldif
similarity index 100%
rename from modules/ldap_groups/spec/fixtures/users.ldif
rename to spec/fixtures/ldap/users.ldif
diff --git a/spec_legacy/unit/ldap_auth_source_spec.rb b/spec/models/ldap_auth_source_spec.rb
similarity index 50%
rename from spec_legacy/unit/ldap_auth_source_spec.rb
rename to spec/models/ldap_auth_source_spec.rb
index 56c837dbc9c..44205f10dcc 100644
--- a/spec_legacy/unit/ldap_auth_source_spec.rb
+++ b/spec/models/ldap_auth_source_spec.rb
@@ -1,4 +1,3 @@
-#-- encoding: UTF-8
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2020 the OpenProject GmbH
@@ -26,62 +25,93 @@
#
# See docs/COPYRIGHT.rdoc for more details.
#++
-require 'legacy_spec_helper'
-describe LdapAuthSource, type: :model do
- fixtures :all
+require 'spec_helper'
+describe LdapAuthSource, type: :model do
it 'should create' do
a = LdapAuthSource.new(name: 'My LDAP', host: 'ldap.example.net', port: 389, base_dn: 'dc=example,dc=net', attr_login: 'sAMAccountName')
- assert a.save
+ expect(a.save).to eq true
end
it 'should strip ldap attributes' do
a = LdapAuthSource.new(name: 'My LDAP', host: 'ldap.example.net', port: 389, base_dn: 'dc=example,dc=net', attr_login: 'sAMAccountName',
attr_firstname: 'givenName ')
- assert a.save
- assert_equal 'givenName', a.reload.attr_firstname
+ expect(a.save).to eq true
+ expect(a.reload.attr_firstname).to eq 'givenName'
end
- if ldap_configured?
- context '#authenticate' do
- before do
- @auth = LdapAuthSource.find(1)
- end
+ describe 'with live LDAP' do
+ before(:all) do
+ ldif = Rails.root.join('spec/fixtures/ldap/users.ldif')
+ @ldap_server = Ladle::Server.new(quiet: false, port: '12389', domain: 'dc=example,dc=com', ldif: ldif).start
+ end
+
+ after(:all) do
+ @ldap_server.stop
+ end
+
+ # Ldap has three users aa729, bb459, cc414
+ let(:ldap) do
+ FactoryBot.create :ldap_auth_source,
+ port: '12389',
+ account: 'uid=admin,ou=system',
+ account_password: 'secret',
+ base_dn: 'ou=people,dc=example,dc=com',
+ filter_string: filter_string,
+ onthefly_register: true,
+ attr_login: 'uid',
+ attr_firstname: 'givenName',
+ attr_lastname: 'sn',
+ attr_mail: 'mail'
+ end
+ let(:filter_string) { nil }
+
+ context '#authenticate' do
context 'with a valid LDAP user' do
it 'should return the user attributes' do
- attributes = @auth.authenticate('example1', '123456')
- assert attributes.is_a?(Hash), 'An hash was not returned'
- assert_equal 'Example', attributes[:firstname]
- assert_equal 'One', attributes[:lastname]
- assert_equal '[email protected]', attributes[:mail]
- assert_equal @auth.id, attributes[:auth_source_id]
- attributes.keys.each do |attribute|
- assert User.new.respond_to?("#{attribute}="), "Unexpected :#{attribute} attribute returned"
- end
+ attributes = ldap.authenticate('bb459', 'niwdlab')
+ expect(attributes).to be_kind_of Hash
+ expect(attributes[:firstname]).to eq 'Belle'
+ expect(attributes[:lastname]).to eq 'Baldwin'
+ expect(attributes[:mail]).to eq '[email protected]'
+ expect(attributes[:auth_source_id]).to eq ldap.id
+
+ expect { User.new(attributes) }.not_to raise_error
end
end
context 'with an invalid LDAP user' do
it 'should return nil' do
- assert_equal nil, @auth.authenticate('nouser', '123456')
+ expect(ldap.authenticate('nouser', 'whatever')).to eq nil
end
end
context 'without a login' do
it 'should return nil' do
- assert_equal nil, @auth.authenticate('', '123456')
+ expect(ldap.authenticate('', 'whatever')).to eq nil
end
end
context 'without a password' do
it 'should return nil' do
- assert_equal nil, @auth.authenticate('edavis', '')
+ expect(ldap.authenticate('whatever', 'nil')).to eq nil
+ end
+ end
+
+ context 'with a filter string returning only users with a*' do
+ let(:filter_string) { '(uid=a*)' }
+
+ it 'no longer authenticates bb254' do
+ expect(ldap.authenticate('bb459', 'niwdlab')).to eq nil
+ end
+
+ it 'still authenticates aa729' do
+ attributes = ldap.authenticate('aa729', 'smada')
+ expect(attributes[:firstname]).to eq 'Alexandra'
end
end
end
- else
- puts '(Test LDAP server not configured)'
end
end