ldap_groups_lookup 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: e986ac6ae6b5a7ef3fa46acd0cba75ea50fcea73
4
+ data.tar.gz: 967e36cea4f0fdcbeaec12e8191e00bdffdc8976
5
+ SHA512:
6
+ metadata.gz: c394f00e5269767de53bdca4668b31a9de715e09382a63f5bacb4aa0a099c48d500985327f22a95a17687b2bdb5a4cc0715290082403afad286feb11f815bc6b
7
+ data.tar.gz: 23d5349dfa67d42cc8faf029db21b9a2c1c1f1617ebffa8b5c7d7bd6303194ffef9bc883d933277d86cc82b5b0e718aa0e6f548fe87b5df4aebb25402b6ab4f7
data/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ Gemfile.lock
2
+ .ruby-version
3
+ .ruby-gemset
4
+
5
+ # YARD folders
6
+ doc/
7
+ .yardoc/
8
+
9
+ # temporary files
10
+ *.swp
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.3
4
+ - 2.4
5
+ - 2.5
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify gem's dependencies in ldap_groups_lookup.gemspec
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,29 @@
1
+ # IU LDAP Groups Lookup
2
+
3
+ Adds an LDAPGroupsLookup that can be included in a a class to provide an #ldap_groups instance method:
4
+
5
+ ```
6
+ class User
7
+ attr_accessor :ldap_lookup_key
8
+ include LDAPGroupsLookup::Behavior
9
+ end
10
+
11
+ u = User.new
12
+ u.ldap_lookup_key = 'some_username'
13
+ u.ldap_groups
14
+ u.member_of_ldap_group?(['Some-Group'])
15
+ ```
16
+
17
+ The LDAP search will be run by the value of #ldap_lookup_key, so your instance object must provide that through some means:
18
+
19
+ ```
20
+ class User < ActiveRecord::Base
21
+ validates :username, presence: true, uniqueness: true
22
+ alias_attribute :ldap_lookup_key, :username
23
+ include LDAPGroupsLookup::Behavior
24
+ end
25
+
26
+ u = User.find_by(username: 'some_username')
27
+ u.ldap_groups
28
+ u.member_of_ldap_group?(['Some-Group'])
29
+ ```
data/Rakefile ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env rake
2
+ require 'rspec/core/rake_task'
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+ task default: :spec
@@ -0,0 +1,24 @@
1
+ # -*- encoding: utf-8 -*-
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'ldap_groups_lookup/version'
5
+
6
+ Gem::Specification.new do |gem|
7
+ gem.name = 'ldap_groups_lookup'
8
+ gem.version = LDAPGroupsLookup::VERSION
9
+ gem.authors = ['Adam Ploshay', 'Daniel Pierce', 'Avalon Media System']
10
+ gem.email = ['aploshay@iu.edu', 'dlpierce@iu.edu']
11
+ gem.description = 'Provides easy access to the list of LDAP groups a username is a member of.'
12
+ gem.summary = 'Provides easy access to the list of LDAP groups a username is a member of.'
13
+ gem.homepage = 'http://github.com/IUBLibTech/ldap_groups_lookup'
14
+
15
+ gem.files = `git ls-files -z`.split("\x0")
16
+ gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
17
+ gem.require_paths = ['lib']
18
+ gem.required_ruby_version = '>= 2.3.0'
19
+
20
+ gem.add_dependency 'net-ldap'
21
+ gem.add_development_dependency 'rake'
22
+ gem.add_development_dependency 'rspec'
23
+ gem.add_development_dependency 'pry'
24
+ end
@@ -0,0 +1,16 @@
1
+ require 'net/ldap'
2
+
3
+ # Adds #ldap_groups instance method
4
+ # Object must provide #ldap_lookup_key to use for LDAP group search
5
+ module LDAPGroupsLookup
6
+ class InitializationError < RuntimeError; end
7
+
8
+ autoload :Configuration, 'ldap_groups_lookup/configuration'
9
+ autoload :Search, 'ldap_groups_lookup/search'
10
+ autoload :Behavior, 'ldap_groups_lookup/behavior'
11
+
12
+ class << self
13
+ include LDAPGroupsLookup::Configuration
14
+ include LDAPGroupsLookup::Search
15
+ end
16
+ end
@@ -0,0 +1,27 @@
1
+ # Adds #ldap_groups instance method
2
+ # Object must provide #ldap_lookup_key to use for LDAP group search
3
+ module LDAPGroupsLookup
4
+ module Behavior
5
+ require 'ldap_groups_lookup'
6
+
7
+ # Searches object's nested LDAP groups by value of ldap_lookup_key
8
+ # @return [Array] all of the object's LDAP groups, sorted
9
+ def ldap_groups
10
+ return [] unless respond_to? :ldap_lookup_key
11
+ LDAPGroupsLookup.walk_ldap_groups(
12
+ LDAPGroupsLookup.ldap_member_of(ldap_lookup_key)
13
+ ).sort
14
+ end
15
+
16
+ # Checks if a user is in a group's membership tree
17
+ # @param [Array] groups is a list of group CN strings to search within
18
+ # @return [Boolean]
19
+ def member_of_ldap_group?(groups)
20
+ return false unless respond_to? :ldap_lookup_key
21
+ return false if LDAPGroupsLookup.service.nil?
22
+ groups = [groups] if groups.is_a? String
23
+ dn = LDAPGroupsLookup.lookup_dn ldap_lookup_key
24
+ return LDAPGroupsLookup.walk_ldap_members(groups, dn)
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,63 @@
1
+ require 'yaml'
2
+
3
+ # Provides access to the configuration YAML file.
4
+ module LDAPGroupsLookup
5
+ module Configuration
6
+
7
+ # Attempts to create a connection to LDAP and returns a cached Net::LDAP instance if successful.
8
+ def service
9
+ return nil if config[:enabled] == false
10
+ if @ldap_service.nil?
11
+ @ldap_service = Net::LDAP.new(host: config[:host], auth: config[:auth])
12
+ raise Net::LDAP::Error unless @ldap_service.bind
13
+ end
14
+ @ldap_service
15
+ end
16
+
17
+ # Loads LDAP host and authentication configuration
18
+ def config
19
+ if @config.nil?
20
+ if defined? Rails
21
+ configure(Rails.root.join('config', 'ldap_groups_lookup.yml').to_s)
22
+ else
23
+ configure(File.join(__dir__, 'config', 'ldap_groups_lookup.yml').to_s)
24
+ end
25
+ end
26
+ @config
27
+ end
28
+
29
+ # Clears internal cached objects.
30
+ def reset
31
+ @ldap_service = nil
32
+ @config = nil
33
+ end
34
+
35
+ def group_tree
36
+ "#{config[:group_ou]},#{tree}"
37
+ end
38
+
39
+ def account_tree
40
+ "#{config[:account_ou]},#{tree}"
41
+ end
42
+
43
+ def tree
44
+ config[:tree]
45
+ end
46
+
47
+ private
48
+
49
+ def configure(value)
50
+ if value.nil? || value.is_a?(Hash)
51
+ @config = value
52
+ elsif value.is_a?(String)
53
+ if File.exists?(value)
54
+ @config = YAML.load(ERB.new(File.read(value)).result)
55
+ else
56
+ @config = { enabled: false }
57
+ end
58
+ else
59
+ raise InitializationError, "Unrecognized configuration: #{value.inspect}"
60
+ end
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,117 @@
1
+ module LDAPGroupsLookup
2
+ module Search
3
+ # Searches (without recursion) LDAP groups
4
+ # @param [String] cn the group or user to search by
5
+ # @return [Array] LDAP groups for cn, one level deep, unsorted
6
+ def ldap_member_of(cn)
7
+ return [] if service.nil?
8
+ entry = service.search(base: tree,
9
+ filter: Net::LDAP::Filter.equals('cn', cn),
10
+ attributes: ['memberof']).first
11
+ if entry.nil?
12
+ []
13
+ else
14
+ entry['memberof'].collect { |mo| mo.split(',').first.split('=')[1] }
15
+ end
16
+ end
17
+
18
+ # Searches (recursively) LDAP group membership tree
19
+ # @param [Array] groups to search group membership of
20
+ # @param [Array] seen the accumulated list of group membership, defaults to []
21
+ # @return [Array] results of searching group membership tree
22
+ def walk_ldap_groups(groups, seen = [])
23
+ groups.each do |g|
24
+ next if seen.include? g
25
+ seen << g
26
+ walk_ldap_groups(ldap_member_of(g), seen)
27
+ end
28
+ seen
29
+ end
30
+
31
+ # Returns the DN for the given CN attribute
32
+ def lookup_dn(cn)
33
+ service.search(base: tree, filter: Net::LDAP::Filter.equals('cn', cn), attributes: 'dn').first&.dn
34
+ end
35
+
36
+ # Strips a DN string down to just its CN segment.
37
+ def dn_to_cn(dn)
38
+ dn.match(/CN=(.+?),/)[1]
39
+ end
40
+
41
+ # Searches a group and its nested member groups for a member DN
42
+ # @param [Array] groups CNs to search
43
+ # @param [String] dn the DN to search for
44
+ # @param [Array] seen groups that have already been traversed
45
+ # @return [Boolean] true if dn was seen in groups
46
+ def walk_ldap_members(groups, dn, seen = [])
47
+ groups.each do |g|
48
+ members = ldap_members(g)
49
+ return true if members.include? dn
50
+ next if seen.include? g
51
+ seen << g
52
+ member_groups = members.collect do |mg|
53
+ dn_to_cn(mg) if mg.include? 'OU=Groups'
54
+ end
55
+ member_groups.compact!
56
+ return true if walk_ldap_members(member_groups, dn, seen)
57
+ end
58
+ return false
59
+ end
60
+
61
+ # Gets the entire list of members for a CN.
62
+ # Handles range results.
63
+ # @param [String] cn of the entry to fetch.
64
+ # @param [Integer] start index of range result
65
+ # @return [Array] list of member CNs
66
+ def ldap_members(cn, start=0)
67
+ return [] if service.nil?
68
+ # print "Getting members of #{cn} at index #{start}\n"
69
+ entry = service.search(base: tree,
70
+ filter: Net::LDAP::Filter.equals('cn', cn),
71
+ attributes: ["member;range=#{start}-*"]).first
72
+ return [] if entry.nil?
73
+
74
+ field_name = entry.attribute_names[1] # Is this always ordered [dn, member]?
75
+ return [] if field_name.nil? # Sometimes member is not present.
76
+
77
+ range_end = field_name.to_s.match(/^member;range=\d+-([0-9*]+)$/)[1]
78
+ # print "#{start}-#{range_end}\n"
79
+ members = entry[field_name]#.collect { |mo| mo.split(',').first.split('=')[1] }
80
+ members.concat ldap_members(cn, range_end.to_i+1) unless range_end == '*'
81
+ return members
82
+ end
83
+
84
+ # Checks if a user is in a group's membership tree
85
+ # @param [String] username to search for
86
+ # @param [String] groupname to search within
87
+ # @return [Boolean]
88
+ def belongs_to_ldap_group?(username, groupname)
89
+ return false if service.nil?
90
+ group_filter = Net::LDAP::Filter.equals('cn', groupname)
91
+ member_filter = Net::LDAP::Filter.equals('member', "cn=#{username},#{account_tree}")
92
+ entry = service.search(base: tree,
93
+ filter: group_filter & member_filter,
94
+ attributes: ['cn'])
95
+ entry.count > 0
96
+ end
97
+
98
+ # Lists all groups that a user belongs to.
99
+ # Warning: Utilizes server-side recursive search but may be slower than walking the tree client-side.
100
+ # @param [string] username the user to search by
101
+ def all_ldap_groups(username)
102
+ return [] if service.nil?
103
+ results = service.search(base: group_tree,
104
+ filter: Net::LDAP::Filter.eq('objectcategory', 'group') &
105
+ Net::LDAP::Filter.ex('member:1.2.840.113556.1.4.1941',
106
+ "CN=#{Net::LDAP::Filter.escape(username)},#{account_tree}"),
107
+ attributes: ['cn'])
108
+ if results.nil?
109
+ []
110
+ else
111
+ results.collect do |entry|
112
+ entry[:cn].first
113
+ end
114
+ end
115
+ end
116
+ end
117
+ end
@@ -0,0 +1,5 @@
1
+ # Gem version release tracking
2
+ module LDAPGroupsLookup
3
+ # Define release version
4
+ VERSION = '0.4.3'.freeze
5
+ end
@@ -0,0 +1,9 @@
1
+ :enabled: true
2
+ :host: ads.example.net
3
+ :auth:
4
+ :method: :simple
5
+ :username: example
6
+ :password: changeme
7
+ :tree: dc=ads,dc=example,dc=net
8
+ :account_ou: ou=Accounts
9
+ :group_ou: ou=Groups
@@ -0,0 +1,186 @@
1
+ require 'spec_helper'
2
+ require 'ldap_groups_lookup/behavior'
3
+ require 'pry'
4
+
5
+ RSpec.describe LDAPGroupsLookup do
6
+ let(:user_class) do
7
+ class User
8
+ def ldap_lookup_key
9
+ 'user'
10
+ end
11
+ include LDAPGroupsLookup::Behavior
12
+ end
13
+ end
14
+ let(:user) { user_class.new }
15
+
16
+ # Load the example config from fixtures
17
+ let(:config) { YAML.load(ERB.new(File.read(File.join(File.dirname(__dir__), 'fixtures', 'ldap_groups_lookup.yml.example'))).result) }
18
+
19
+ before do
20
+ allow(LDAPGroupsLookup).to receive(:config).and_return(config)
21
+ end
22
+
23
+ after do
24
+ LDAPGroupsLookup.reset
25
+ end
26
+
27
+ describe '#service' do
28
+ context 'when the config file is missing' do
29
+ before do
30
+ allow(LDAPGroupsLookup).to receive(:config).and_call_original
31
+ expect(File).to receive(:exists?).with(/config\/ldap_groups_lookup\.yml$/)
32
+ end
33
+ it 'should return nil' do
34
+ expect(LDAPGroupsLookup.service).to be_nil
35
+ end
36
+ end
37
+ context 'when disabled in the configuration file' do
38
+ before do
39
+ config[:enabled] = false
40
+ end
41
+ it 'should return nil' do
42
+ expect(LDAPGroupsLookup.service).to be_nil
43
+ end
44
+ end
45
+ context 'when enabled in the configuration file' do
46
+ it 'should be enabled' do
47
+ expect(config[:enabled]).to eq(true)
48
+ end
49
+ context 'when the auth credentials are incorrect' do
50
+ before do
51
+ allow_any_instance_of(Net::LDAP).to receive(:bind).and_return(false)
52
+ end
53
+ it 'should raise an LdapError' do
54
+ expect { LDAPGroupsLookup.service }.to raise_error(Net::LDAP::Error)
55
+ end
56
+ end
57
+ context 'when the auth credentials are correct' do
58
+ before do
59
+ allow_any_instance_of(Net::LDAP).to receive(:bind).and_return(true)
60
+ end
61
+ it 'should return a Net::LDAP instance' do
62
+ expect(LDAPGroupsLookup.service).to be_an_instance_of(Net::LDAP)
63
+ end
64
+ end
65
+ end
66
+ end
67
+
68
+ describe '#ldap_groups' do
69
+ before(:each) do
70
+ entry = Net::LDAP::Entry.new('CN=user,DC=ads,DC=example,DC=net')
71
+ entry['memberof'] = ['CN=Group1,DC=ads,DC=example,DC=net',
72
+ 'CN=Group2,DC=ads,DC=example,DC=net']
73
+ allow_any_instance_of(Net::LDAP).to receive(:search).and_return([entry])
74
+ allow_any_instance_of(Net::LDAP).to receive(:bind).and_return(true)
75
+ end
76
+ context 'when subject does not provide ldap_lookup_key' do
77
+ before(:each) { user.class.send(:remove_method, :ldap_lookup_key) }
78
+ it 'should return []' do
79
+ expect(user.ldap_groups).to eq([])
80
+ end
81
+ end
82
+ context 'when subject provides ldap_lookup_key' do
83
+ context 'when LDAP is not configured' do
84
+ before(:each) do
85
+ config[:enabled] = false
86
+ end
87
+ it 'should return []' do
88
+ expect(user.ldap_groups).to eq([])
89
+ end
90
+ end
91
+ context 'when LDAP is configured' do
92
+ it 'user should belong to Group1 and Group2 in mock LDAP' do
93
+ expect(user.ldap_groups).to eq(%w(Group1 Group2))
94
+ end
95
+ end
96
+ end
97
+ end
98
+
99
+ describe '#member_of_ldap_group?' do
100
+ context 'when subject does not provide ldap_lookup_key' do
101
+ before(:each) { user.class.send(:remove_method, :ldap_lookup_key) }
102
+ it 'should return false' do
103
+ expect(user.member_of_ldap_group?('Test-Group')).to eq(false)
104
+ end
105
+ end
106
+ context 'when subject provides ldap_lookup_key' do
107
+ context 'when LDAP is not configured' do
108
+ before(:each) do
109
+ config[:enabled] = false
110
+ end
111
+ it 'should return false' do
112
+ expect(user.member_of_ldap_group?('Test-Group')).to eq(false)
113
+ end
114
+ end
115
+ context 'when LDAP is configured' do
116
+ before(:each) do
117
+ @service = double('ldap_service')
118
+ allow(LDAPGroupsLookup).to receive(:service).and_return(@service)
119
+
120
+ allow(LDAPGroupsLookup).to receive(:lookup_dn) do |args|
121
+ Net::LDAP::Entry.new("CN=#{args},DC=ads,DC=example,DC=net").dn
122
+ end
123
+
124
+ @other_group = Net::LDAP::Entry.new('CN=Other-Group,OU=Groups,DC=ads,DC=example,DC=net')
125
+ @other_group['member;range=0-*'] = ['CN=otheruser,DC=ads,DC=example,DC=net']
126
+
127
+ @nested_group_page_1 = Net::LDAP::Entry.new('CN=Nested-Group,OU=Groups,DC=ads,DC=example,DC=net')
128
+ @nested_group_page_1['member;range=0-0'] = ['CN=otheruser,DC=ads,DC=example,DC=net']
129
+
130
+ @nested_group_page_2 = Net::LDAP::Entry.new('CN=Nested-Group,OU=Groups,DC=ads,DC=example,DC=net')
131
+ @nested_group_page_2['member;range=1-*'] = ['CN=user,DC=ads,DC=example,DC=net']
132
+
133
+ @top_group = Net::LDAP::Entry.new('CN=Top-Group,OU=Groups,DC=ads,DC=example,DC=net')
134
+ @top_group['member;range=0-*'] = ['CN=Nested-Group,OU=Groups,DC=ads,DC=example,DC=net']
135
+
136
+ @no_member_group = Net::LDAP::Entry.new('CN=No-Member-Group,OU=Groups,DC=ads,DC=example,DC=net')
137
+ end
138
+ context 'when searching for a group that does not exist' do
139
+ it 'should return false' do
140
+ expect(@service).to receive(:search).with(
141
+ hash_including(filter: Net::LDAP::Filter.equals('cn', 'Fake-Group'))).and_return([])
142
+ expect(user.member_of_ldap_group?('Fake-Group')).to eq(false)
143
+ end
144
+ end
145
+ context 'when searching for a group that user is not a member of' do
146
+ it 'should return false' do
147
+ expect(@service).to receive(:search).with(
148
+ hash_including(filter: Net::LDAP::Filter.equals('cn', 'Other-Group'))).and_return([@other_group])
149
+ expect(user.member_of_ldap_group?('Other-Group')).to eq(false)
150
+ end
151
+ end
152
+ context 'when searching for a group that has no members' do
153
+ it 'should return false' do
154
+ expect(@service).to receive(:search).with(
155
+ hash_including(filter: Net::LDAP::Filter.equals('cn', 'No-Member-Group'))).and_return([@no_member_group])
156
+ expect(user.member_of_ldap_group?('No-Member-Group')).to eq(false)
157
+ end
158
+ end
159
+ context 'when searching for a group that user is a direct member of on the second page' do
160
+ it 'should return true' do
161
+ expect(@service).to receive(:search).with(
162
+ hash_including(filter: Net::LDAP::Filter.equals('cn', 'Nested-Group'),
163
+ attributes: ['member;range=0-*'])).and_return([@nested_group_page_1])
164
+ expect(@service).to receive(:search).with(
165
+ hash_including(filter: Net::LDAP::Filter.equals('cn', 'Nested-Group'),
166
+ attributes: ['member;range=1-*'])).and_return([@nested_group_page_2])
167
+ expect(user.member_of_ldap_group?('Nested-Group')).to eq(true)
168
+ end
169
+ end
170
+ context 'when searching for a group that user is a nested member of' do
171
+ it 'should return true' do
172
+ expect(@service).to receive(:search).with(
173
+ hash_including(filter: Net::LDAP::Filter.equals('cn', 'Top-Group'))).and_return([@top_group])
174
+ expect(@service).to receive(:search).with(
175
+ hash_including(filter: Net::LDAP::Filter.equals('cn', 'Nested-Group'),
176
+ attributes: ['member;range=0-*'])).and_return([@nested_group_page_1])
177
+ expect(@service).to receive(:search).with(
178
+ hash_including(filter: Net::LDAP::Filter.equals('cn', 'Nested-Group'),
179
+ attributes: ['member;range=1-*'])).and_return([@nested_group_page_2])
180
+ expect(user.member_of_ldap_group?('Top-Group')).to eq(true)
181
+ end
182
+ end
183
+ end
184
+ end
185
+ end
186
+ end
@@ -0,0 +1,102 @@
1
+ # This file was generated by the `rspec --init` command. Conventionally, all
2
+ # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
3
+ # The generated `.rspec` file contains `--require spec_helper` which will cause
4
+ # this file to always be loaded, without a need to explicitly require it in any
5
+ # files.
6
+ #
7
+ # Given that it is always loaded, you are encouraged to keep this file as
8
+ # light-weight as possible. Requiring heavyweight dependencies from this file
9
+ # will add to the boot time of your test suite on EVERY test run, even for an
10
+ # individual file that may not need all of that loaded. Instead, consider making
11
+ # a separate helper file that requires the additional dependencies and performs
12
+ # the additional setup, and require it from the spec files that actually need
13
+ # it.
14
+ #
15
+ # The `.rspec` file also contains a few flags that are not defaults but that
16
+ # users commonly want.
17
+ #
18
+ # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
19
+ RSpec.configure do |config|
20
+ # rspec-expectations config goes here. You can use an alternate
21
+ # assertion/expectation library such as wrong or the stdlib/minitest
22
+ # assertions if you prefer.
23
+ config.expect_with :rspec do |expectations|
24
+ # This option will default to `true` in RSpec 4. It makes the `description`
25
+ # and `failure_message` of custom matchers include text for helper methods
26
+ # defined using `chain`, e.g.:
27
+ # be_bigger_than(2).and_smaller_than(4).description
28
+ # # => "be bigger than 2 and smaller than 4"
29
+ # ...rather than:
30
+ # # => "be bigger than 2"
31
+ expectations.include_chain_clauses_in_custom_matcher_descriptions = true
32
+ end
33
+
34
+ # rspec-mocks config goes here. You can use an alternate test double
35
+ # library (such as bogus or mocha) by changing the `mock_with` option here.
36
+ config.mock_with :rspec do |mocks|
37
+ # Prevents you from mocking or stubbing a method that does not exist on
38
+ # a real object. This is generally recommended, and will default to
39
+ # `true` in RSpec 4.
40
+ mocks.verify_partial_doubles = true
41
+ end
42
+
43
+ # This option will default to `:apply_to_host_groups` in RSpec 4 (and will
44
+ # have no way to turn it off -- the option exists only for backwards
45
+ # compatibility in RSpec 3). It causes shared context metadata to be
46
+ # inherited by the metadata hash of host groups and examples, rather than
47
+ # triggering implicit auto-inclusion in groups with matching metadata.
48
+ config.shared_context_metadata_behavior = :apply_to_host_groups
49
+
50
+ # The settings below are suggested to provide a good initial experience
51
+ # with RSpec, but feel free to customize to your heart's content.
52
+
53
+ # This allows you to limit a spec run to individual examples or groups
54
+ # you care about by tagging them with `:focus` metadata. When nothing
55
+ # is tagged with `:focus`, all examples get run. RSpec also provides
56
+ # aliases for `it`, `describe`, and `context` that include `:focus`
57
+ # metadata: `fit`, `fdescribe` and `fcontext`, respectively.
58
+ config.filter_run_when_matching :focus
59
+
60
+ # Allows RSpec to persist some state between runs in order to support
61
+ # the `--only-failures` and `--next-failure` CLI options. We recommend
62
+ # you configure your source control system to ignore this file.
63
+ # config.example_status_persistence_file_path = "spec/examples.txt"
64
+
65
+ # Limits the available syntax to the non-monkey patched syntax that is
66
+ # recommended. For more details, see:
67
+ # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
68
+ # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
69
+ # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
70
+ config.disable_monkey_patching!
71
+
72
+ # This setting enables warnings. It's recommended, but in some cases may
73
+ # be too noisy due to issues in dependencies.
74
+ config.warnings = true
75
+
76
+ # Many RSpec users commonly either run the entire suite or an individual
77
+ # file, and it's useful to allow more verbose output when running an
78
+ # individual spec file.
79
+ if config.files_to_run.one?
80
+ # Use the documentation formatter for detailed output,
81
+ # unless a formatter has already been configured
82
+ # (e.g. via a command-line flag).
83
+ config.default_formatter = 'doc'
84
+ end
85
+
86
+ # Print the 10 slowest examples and example groups at the
87
+ # end of the spec run, to help surface which specs are running
88
+ # particularly slow.
89
+ config.profile_examples = 10
90
+
91
+ # Run specs in random order to surface order dependencies. If you find an
92
+ # order dependency and want to debug it, you can fix the order by providing
93
+ # the seed, which is printed after each run.
94
+ # --seed 1234
95
+ config.order = :random
96
+
97
+ # Seed global randomization in this process using the `--seed` CLI option.
98
+ # Setting this allows you to use `--seed` to deterministically reproduce
99
+ # test failures related to randomization by passing the same `--seed` value
100
+ # as the one that triggered the failure.
101
+ Kernel.srand config.seed
102
+ end
metadata ADDED
@@ -0,0 +1,122 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ldap_groups_lookup
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.4.3
5
+ platform: ruby
6
+ authors:
7
+ - Adam Ploshay
8
+ - Daniel Pierce
9
+ - Avalon Media System
10
+ autorequire:
11
+ bindir: bin
12
+ cert_chain: []
13
+ date: 2018-06-19 00:00:00.000000000 Z
14
+ dependencies:
15
+ - !ruby/object:Gem::Dependency
16
+ name: net-ldap
17
+ requirement: !ruby/object:Gem::Requirement
18
+ requirements:
19
+ - - ">="
20
+ - !ruby/object:Gem::Version
21
+ version: '0'
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ requirements:
26
+ - - ">="
27
+ - !ruby/object:Gem::Version
28
+ version: '0'
29
+ - !ruby/object:Gem::Dependency
30
+ name: rake
31
+ requirement: !ruby/object:Gem::Requirement
32
+ requirements:
33
+ - - ">="
34
+ - !ruby/object:Gem::Version
35
+ version: '0'
36
+ type: :development
37
+ prerelease: false
38
+ version_requirements: !ruby/object:Gem::Requirement
39
+ requirements:
40
+ - - ">="
41
+ - !ruby/object:Gem::Version
42
+ version: '0'
43
+ - !ruby/object:Gem::Dependency
44
+ name: rspec
45
+ requirement: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: '0'
50
+ type: :development
51
+ prerelease: false
52
+ version_requirements: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - ">="
55
+ - !ruby/object:Gem::Version
56
+ version: '0'
57
+ - !ruby/object:Gem::Dependency
58
+ name: pry
59
+ requirement: !ruby/object:Gem::Requirement
60
+ requirements:
61
+ - - ">="
62
+ - !ruby/object:Gem::Version
63
+ version: '0'
64
+ type: :development
65
+ prerelease: false
66
+ version_requirements: !ruby/object:Gem::Requirement
67
+ requirements:
68
+ - - ">="
69
+ - !ruby/object:Gem::Version
70
+ version: '0'
71
+ description: Provides easy access to the list of LDAP groups a username is a member
72
+ of.
73
+ email:
74
+ - aploshay@iu.edu
75
+ - dlpierce@iu.edu
76
+ executables: []
77
+ extensions: []
78
+ extra_rdoc_files: []
79
+ files:
80
+ - ".gitignore"
81
+ - ".rspec"
82
+ - ".travis.yml"
83
+ - Gemfile
84
+ - LICENSE
85
+ - README.md
86
+ - Rakefile
87
+ - ldap_groups_lookup.gemspec
88
+ - lib/ldap_groups_lookup.rb
89
+ - lib/ldap_groups_lookup/behavior.rb
90
+ - lib/ldap_groups_lookup/configuration.rb
91
+ - lib/ldap_groups_lookup/search.rb
92
+ - lib/ldap_groups_lookup/version.rb
93
+ - spec/fixtures/ldap_groups_lookup.yml.example
94
+ - spec/lib/ldap_groups_lookup_spec.rb
95
+ - spec/spec_helper.rb
96
+ homepage: http://github.com/IUBLibTech/ldap_groups_lookup
97
+ licenses: []
98
+ metadata: {}
99
+ post_install_message:
100
+ rdoc_options: []
101
+ require_paths:
102
+ - lib
103
+ required_ruby_version: !ruby/object:Gem::Requirement
104
+ requirements:
105
+ - - ">="
106
+ - !ruby/object:Gem::Version
107
+ version: 2.3.0
108
+ required_rubygems_version: !ruby/object:Gem::Requirement
109
+ requirements:
110
+ - - ">="
111
+ - !ruby/object:Gem::Version
112
+ version: '0'
113
+ requirements: []
114
+ rubyforge_project:
115
+ rubygems_version: 2.6.14.1
116
+ signing_key:
117
+ specification_version: 4
118
+ summary: Provides easy access to the list of LDAP groups a username is a member of.
119
+ test_files:
120
+ - spec/fixtures/ldap_groups_lookup.yml.example
121
+ - spec/lib/ldap_groups_lookup_spec.rb
122
+ - spec/spec_helper.rb