omniauth-ldap 2.0.0 → 2.3.1

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.
data/REEK ADDED
File without changes
data/RUBOCOP.md ADDED
@@ -0,0 +1,71 @@
1
+ # RuboCop Usage Guide
2
+
3
+ ## Overview
4
+
5
+ A tale of two RuboCop plugin gems.
6
+
7
+ ### RuboCop Gradual
8
+
9
+ This project uses `rubocop_gradual` instead of vanilla RuboCop for code style checking. The `rubocop_gradual` tool allows for gradual adoption of RuboCop rules by tracking violations in a lock file.
10
+
11
+ ### RuboCop LTS
12
+
13
+ This project uses `rubocop-lts` to ensure, on a best-effort basis, compatibility with Ruby >= 1.9.2.
14
+ RuboCop rules are meticulously configured by the `rubocop-lts` family of gems to ensure that a project is compatible with a specific version of Ruby. See: https://rubocop-lts.gitlab.io for more.
15
+
16
+ ## Checking RuboCop Violations
17
+
18
+ To check for RuboCop violations in this project, always use:
19
+
20
+ ```bash
21
+ bundle exec rake rubocop_gradual:check
22
+ ```
23
+
24
+ **Do not use** the standard RuboCop commands like:
25
+ - `bundle exec rubocop`
26
+ - `rubocop`
27
+
28
+ ## Understanding the Lock File
29
+
30
+ The `.rubocop_gradual.lock` file tracks all current RuboCop violations in the project. This allows the team to:
31
+
32
+ 1. Prevent new violations while gradually fixing existing ones
33
+ 2. Track progress on code style improvements
34
+ 3. Ensure CI builds don't fail due to pre-existing violations
35
+
36
+ ## Common Commands
37
+
38
+ - **Check violations**
39
+ - `bundle exec rake rubocop_gradual`
40
+ - `bundle exec rake rubocop_gradual:check`
41
+ - **(Safe) Autocorrect violations, and update lockfile if no new violations**
42
+ - `bundle exec rake rubocop_gradual:autocorrect`
43
+ - **Force update the lock file (w/o autocorrect) to match violations present in code**
44
+ - `bundle exec rake rubocop_gradual:force_update`
45
+
46
+ ## Workflow
47
+
48
+ 1. Before submitting a PR, run `bundle exec rake rubocop_gradual:autocorrect`
49
+ a. or just the default `bundle exec rake`, as autocorrection is a pre-requisite of the default task.
50
+ 2. If there are new violations, either:
51
+ - Fix them in your code
52
+ - Run `bundle exec rake rubocop_gradual:force_update` to update the lock file (only for violations you can't fix immediately)
53
+ 3. Commit the updated `.rubocop_gradual.lock` file along with your changes
54
+
55
+ ## Never add inline RuboCop disables
56
+
57
+ Do not add inline `rubocop:disable` / `rubocop:enable` comments anywhere in the codebase (including specs, except when following the few existing `rubocop:disable` patterns for a rule already being disabled elsewhere in the code). We handle exceptions in two supported ways:
58
+
59
+ - Permanent/structural exceptions: prefer adjusting the RuboCop configuration (e.g., in `.rubocop.yml`) to exclude a rule for a path or file pattern when it makes sense project-wide.
60
+ - Temporary exceptions while improving code: record the current violations in `.rubocop_gradual.lock` via the gradual workflow:
61
+ - `bundle exec rake rubocop_gradual:autocorrect` (preferred; will autocorrect what it can and update the lock only if no new violations were introduced)
62
+ - If needed, `bundle exec rake rubocop_gradual:force_update` (as a last resort when you cannot fix the newly reported violations immediately)
63
+
64
+ In general, treat the rules as guidance to follow; fix violations rather than ignore them. For example, RSpec conventions in this project expect `described_class` to be used in specs that target a specific class under test.
65
+
66
+ ## Benefits of rubocop_gradual
67
+
68
+ - Allows incremental adoption of code style rules
69
+ - Prevents CI failures due to pre-existing violations
70
+ - Provides a clear record of code style debt
71
+ - Enables focused efforts on improving code quality over time
data/SECURITY.md ADDED
@@ -0,0 +1,21 @@
1
+ # Security Policy
2
+
3
+ ## Supported Versions
4
+
5
+ | Version | Supported |
6
+ |----------|-----------|
7
+ | 1.latest | ✅ |
8
+
9
+ ## Security contact information
10
+
11
+ To report a security vulnerability, please use the
12
+ [Tidelift security contact](https://tidelift.com/security).
13
+ Tidelift will coordinate the fix and disclosure.
14
+
15
+ ## Additional Support
16
+
17
+ If you are interested in support for versions older than the latest release,
18
+ please consider sponsoring the project / maintainer @ https://liberapay.com/pboling/donate,
19
+ or find other sponsorship links in the [README].
20
+
21
+ [README]: README.md
@@ -1,59 +1,121 @@
1
- require 'omniauth'
1
+ require "omniauth"
2
+ require "omniauth/version"
2
3
 
3
4
  module OmniAuth
4
5
  module Strategies
5
6
  class LDAP
7
+ OMNIAUTH_GTE_V2 = Gem::Version.new(OmniAuth::VERSION) >= Gem::Version.new("2.0.0")
6
8
  include OmniAuth::Strategy
7
- @@config = {
8
- 'name' => 'cn',
9
- 'first_name' => 'givenName',
10
- 'last_name' => 'sn',
11
- 'email' => ['mail', "email", 'userPrincipalName'],
12
- 'phone' => ['telephoneNumber', 'homePhone', 'facsimileTelephoneNumber'],
13
- 'mobile' => ['mobile', 'mobileTelephoneNumber'],
14
- 'nickname' => ['uid', 'userid', 'sAMAccountName'],
15
- 'title' => 'title',
16
- 'location' => {"%0, %1, %2, %3 %4" => [['address', 'postalAddress', 'homePostalAddress', 'street', 'streetAddress'], ['l'], ['st'],['co'],['postOfficeBox']]},
17
- 'uid' => 'dn',
18
- 'url' => ['wwwhomepage'],
19
- 'image' => 'jpegPhoto',
20
- 'description' => 'description'
21
- }
22
- option :title, "LDAP Authentication" #default title for authentication form
9
+
10
+ InvalidCredentialsError = Class.new(StandardError)
11
+
12
+ CONFIG = {
13
+ "name" => "cn",
14
+ "first_name" => "givenName",
15
+ "last_name" => "sn",
16
+ "email" => ["mail", "email", "userPrincipalName"],
17
+ "phone" => ["telephoneNumber", "homePhone", "facsimileTelephoneNumber"],
18
+ "mobile" => ["mobile", "mobileTelephoneNumber"],
19
+ "nickname" => ["uid", "userid", "sAMAccountName"],
20
+ "title" => "title",
21
+ "location" => {"%0, %1, %2, %3 %4" => [["address", "postalAddress", "homePostalAddress", "street", "streetAddress"], ["l"], ["st"], ["co"], ["postOfficeBox"]]},
22
+ "uid" => "dn",
23
+ "url" => ["wwwhomepage"],
24
+ "image" => "jpegPhoto",
25
+ "description" => "description",
26
+ }.freeze
27
+ option :title, "LDAP Authentication" # default title for authentication form
28
+ # For OmniAuth >= 2.0 the default allowed request method is POST only.
29
+ # Ensure the strategy follows that default so GET /auth/:provider returns 404 as expected in tests.
30
+ if OMNIAUTH_GTE_V2
31
+ option(:request_methods, [:post])
32
+ else
33
+ option(:request_methods, [:get, :post])
34
+ end
23
35
  option :port, 389
24
36
  option :method, :plain
25
- option :uid, 'sAMAccountName'
26
- option :name_proc, lambda {|n| n}
37
+ option :disable_verify_certificates, false
38
+ option :ca_file, nil
39
+ option :ssl_version, nil # use OpenSSL default if nil
40
+ option :uid, "sAMAccountName"
41
+ option :name_proc, lambda { |n| n }
42
+ # Trusted header SSO support (disabled by default)
43
+ # :header_auth - when true and the header is present, the strategy trusts the upstream gateway
44
+ # and searches the directory for the user without requiring a user password.
45
+ # :header_name - which header/env key to read (default: "REMOTE_USER"). We will also check the
46
+ # standard Rack "HTTP_" variant automatically.
47
+ option :header_auth, false
48
+ option :header_name, "REMOTE_USER"
27
49
 
28
50
  def request_phase
29
- OmniAuth::LDAP::Adaptor.validate @options
30
- f = OmniAuth::Form.new(:title => (options[:title] || "LDAP Authentication"), :url => callback_path)
31
- f.text_field 'Login', 'username'
32
- f.password_field 'Password', 'password'
33
- f.button "Sign In"
51
+ # OmniAuth >= 2.0 expects the request phase to be POST-only for /auth/:provider.
52
+ # Some test environments (and OmniAuth itself) enforce this by returning 404 on GET.
53
+ if OMNIAUTH_GTE_V2 && request.get?
54
+ return Rack::Response.new("", 404, {"Content-Type" => "text/plain"}).finish
55
+ end
56
+
57
+ # Fast-path: if a trusted identity header is present, skip the login form
58
+ # and jump to the callback where we will complete using directory lookup.
59
+ if header_username
60
+ return Rack::Response.new([], 302, "Location" => callback_path).finish
61
+ end
62
+
63
+ # If credentials were POSTed directly to /auth/:provider, redirect to the callback path.
64
+ # This mirrors the behavior of many OmniAuth providers and allows test helpers (like
65
+ # OmniAuth::Test::PhonySession) to populate `env['omniauth.auth']` on the callback request.
66
+ if request.post? && request.params["username"].to_s != "" && request.params["password"].to_s != ""
67
+ return Rack::Response.new([], 302, "Location" => callback_path).finish
68
+ end
69
+
70
+ OmniAuth::LDAP::Adaptor.validate(@options)
71
+ f = OmniAuth::Form.new(title: options[:title] || "LDAP Authentication", url: callback_path)
72
+ f.text_field("Login", "username")
73
+ f.password_field("Password", "password")
74
+ f.button("Sign In")
34
75
  f.to_response
35
76
  end
36
77
 
37
78
  def callback_phase
38
- @adaptor = OmniAuth::LDAP::Adaptor.new @options
79
+ @adaptor = OmniAuth::LDAP::Adaptor.new(@options)
80
+
81
+ return fail!(:invalid_request_method) unless valid_request_method?
82
+
83
+ # Header-based SSO (REMOTE_USER-style) path
84
+ if (hu = header_username)
85
+ begin
86
+ entry = directory_lookup(@adaptor, hu)
87
+ unless entry
88
+ return fail!(:invalid_credentials, InvalidCredentialsError.new("User not found for header #{hu}"))
89
+ end
90
+ @ldap_user_info = entry
91
+ @user_info = self.class.map_user(CONFIG, @ldap_user_info)
92
+ return super
93
+ rescue => e
94
+ return fail!(:ldap_error, e)
95
+ end
96
+ end
39
97
 
40
98
  return fail!(:missing_credentials) if missing_credentials?
41
99
  begin
42
- @ldap_user_info = @adaptor.bind_as(:filter => filter(@adaptor), :size => 1, :password => request['password'])
43
- return fail!(:invalid_credentials) if !@ldap_user_info
100
+ @ldap_user_info = @adaptor.bind_as(filter: filter(@adaptor), size: 1, password: request.params["password"])
101
+
102
+ unless @ldap_user_info
103
+ return fail!(:invalid_credentials, InvalidCredentialsError.new("Invalid credentials for #{request.params["username"]}"))
104
+ end
44
105
 
45
- @user_info = self.class.map_user(@@config, @ldap_user_info)
106
+ @user_info = self.class.map_user(CONFIG, @ldap_user_info)
46
107
  super
47
- rescue Exception => e
48
- return fail!(:ldap_error, e)
108
+ rescue => e
109
+ fail!(:ldap_error, e)
49
110
  end
50
111
  end
51
112
 
52
- def filter adaptor
53
- if adaptor.filter and !adaptor.filter.empty?
54
- Net::LDAP::Filter.construct(adaptor.filter % {username: @options[:name_proc].call(request['username'])})
113
+ def filter(adaptor, username_override = nil)
114
+ if adaptor.filter && !adaptor.filter.empty?
115
+ username = Net::LDAP::Filter.escape(@options[:name_proc].call(username_override || request.params["username"]))
116
+ Net::LDAP::Filter.construct(adaptor.filter % {username: username})
55
117
  else
56
- Net::LDAP::Filter.eq(adaptor.uid, @options[:name_proc].call(request['username']))
118
+ Net::LDAP::Filter.equals(adaptor.uid, @options[:name_proc].call(username_override || request.params["username"]))
57
119
  end
58
120
  end
59
121
 
@@ -64,38 +126,82 @@ module OmniAuth
64
126
  @user_info
65
127
  }
66
128
  extra {
67
- { :raw_info => @ldap_user_info }
129
+ {raw_info: @ldap_user_info}
68
130
  }
69
131
 
70
- def self.map_user(mapper, object)
71
- user = {}
72
- mapper.each do |key, value|
73
- case value
74
- when String
75
- user[key] = object[value.downcase.to_sym].first if object.respond_to? value.downcase.to_sym
76
- when Array
77
- value.each {|v| (user[key] = object[v.downcase.to_sym].first; break;) if object.respond_to? v.downcase.to_sym}
78
- when Hash
79
- value.map do |key1, value1|
80
- pattern = key1.dup
81
- value1.each_with_index do |v,i|
82
- part = ''; v.collect(&:downcase).collect(&:to_sym).each {|v1| (part = object[v1].first; break;) if object.respond_to? v1}
83
- pattern.gsub!("%#{i}",part||'')
132
+ class << self
133
+ def map_user(mapper, object)
134
+ user = {}
135
+ mapper.each do |key, value|
136
+ case value
137
+ when String
138
+ user[key] = object[value.downcase.to_sym].first if object.respond_to?(value.downcase.to_sym)
139
+ when Array
140
+ value.each do |v|
141
+ if object.respond_to?(v.downcase.to_sym)
142
+ user[key] = object[v.downcase.to_sym].first
143
+ break
144
+ end
145
+ end
146
+ when Hash
147
+ value.map do |key1, value1|
148
+ pattern = key1.dup
149
+ value1.each_with_index do |v, i|
150
+ part = ""
151
+ v.collect(&:downcase).collect(&:to_sym).each do |v1|
152
+ if object.respond_to?(v1)
153
+ part = object[v1].first
154
+ break
155
+ end
156
+ end
157
+ pattern.gsub!("%#{i}", part || "")
158
+ end
159
+ user[key] = pattern
84
160
  end
85
- user[key] = pattern
161
+ else
162
+ # unknown mapping type; ignore
86
163
  end
87
164
  end
165
+ user
88
166
  end
89
- user
90
167
  end
91
168
 
92
169
  protected
93
170
 
171
+ def valid_request_method?
172
+ request.env["REQUEST_METHOD"] == "POST"
173
+ end
174
+
94
175
  def missing_credentials?
95
- request['username'].nil? or request['username'].empty? or request['password'].nil? or request['password'].empty?
176
+ request.params["username"].nil? || request.params["username"].empty? || request.params["password"].nil? || request.params["password"].empty?
96
177
  end # missing_credentials?
178
+
179
+ # Extract a normalized username from a trusted header when enabled.
180
+ # Returns nil when not configured or not present.
181
+ def header_username
182
+ return unless options[:header_auth]
183
+
184
+ name = options[:header_name] || "REMOTE_USER"
185
+ # Try both the raw env var (e.g., REMOTE_USER) and the Rack HTTP_ variant (e.g., HTTP_REMOTE_USER or HTTP_X_REMOTE_USER)
186
+ raw = request.env[name] || request.env["HTTP_#{name.upcase.tr("-", "_")}"]
187
+ return if raw.nil? || raw.to_s.strip.empty?
188
+
189
+ options[:name_proc].call(raw.to_s)
190
+ end
191
+
192
+ # Perform a directory lookup for the given username using the strategy configuration
193
+ # (bind_dn/password or anonymous). Does not attempt to bind as the user.
194
+ def directory_lookup(adaptor, username)
195
+ entry = nil
196
+ filter = filter(adaptor, username)
197
+ adaptor.connection.open do |conn|
198
+ rs = conn.search(filter: filter, size: 1)
199
+ entry = rs.first if rs && rs.first
200
+ end
201
+ entry
202
+ end
97
203
  end
98
204
  end
99
205
  end
100
206
 
101
- OmniAuth.config.add_camelization 'ldap', 'LDAP'
207
+ OmniAuth.config.add_camelization("ldap", "LDAP")
@@ -1,10 +1,13 @@
1
- #this code borrowed pieces from activeldap and net-ldap
1
+ # frozen_string_literal: true
2
+
3
+ # this code borrowed pieces from activeldap and net-ldap
4
+
5
+ # External Gems
6
+ require "net/ldap"
7
+ require "net/ntlm"
8
+ require "rack"
9
+ require "sasl"
2
10
 
3
- require 'rack'
4
- require 'net/ldap'
5
- require 'net/ntlm'
6
- require 'sasl'
7
- require 'kconv'
8
11
  module OmniAuth
9
12
  module LDAP
10
13
  class Adaptor
@@ -13,31 +16,64 @@ module OmniAuth
13
16
  class AuthenticationError < StandardError; end
14
17
  class ConnectionError < StandardError; end
15
18
 
16
- VALID_ADAPTER_CONFIGURATION_KEYS = [:host, :port, :method, :bind_dn, :password, :try_sasl, :sasl_mechanisms, :uid, :base, :allow_anonymous, :filter]
19
+ VALID_ADAPTER_CONFIGURATION_KEYS = [
20
+ :hosts,
21
+ :host,
22
+ :port,
23
+ :encryption,
24
+ :disable_verify_certificates,
25
+ :bind_dn,
26
+ :password,
27
+ :try_sasl,
28
+ :sasl_mechanisms,
29
+ :uid,
30
+ :base,
31
+ :allow_anonymous,
32
+ :filter,
33
+ :tls_options,
34
+
35
+ # Deprecated
36
+ :method,
37
+ :ca_file,
38
+ :ssl_version,
39
+ ]
17
40
 
18
41
  # A list of needed keys. Possible alternatives are specified using sub-lists.
19
- MUST_HAVE_KEYS = [:host, :port, :method, [:uid, :filter], :base]
42
+ MUST_HAVE_KEYS = [
43
+ :base,
44
+ [:encryption, :method], # :method is deprecated
45
+ [:hosts, :host],
46
+ [:hosts, :port],
47
+ [:uid, :filter],
48
+ ]
20
49
 
21
- METHOD = {
22
- :ssl => :simple_tls,
23
- :tls => :start_tls,
24
- :plain => nil,
50
+ ENCRYPTION_METHOD = {
51
+ simple_tls: :simple_tls,
52
+ start_tls: :start_tls,
53
+ plain: nil,
54
+
55
+ # Deprecated. This mapping aimed to be user-friendly, but only caused
56
+ # confusion. Better to pass through the actual `Net::LDAP` encryption type.
57
+ ssl: :simple_tls,
58
+ tls: :start_tls,
25
59
  }
26
60
 
27
61
  attr_accessor :bind_dn, :password
28
62
  attr_reader :connection, :uid, :base, :auth, :filter
29
- def self.validate(configuration={})
63
+
64
+ def self.validate(configuration = {})
30
65
  message = []
31
66
  MUST_HAVE_KEYS.each do |names|
32
67
  names = [names].flatten
33
- missing_keys = names.select{|name| configuration[name].nil?}
68
+ missing_keys = names.select { |name| configuration[name].nil? }
34
69
  if missing_keys == names
35
- message << names.join(' or ')
70
+ message << names.join(" or ")
36
71
  end
37
72
  end
38
- raise ArgumentError.new(message.join(",") +" MUST be provided") unless message.empty?
73
+ raise ArgumentError.new(message.join(",") + " MUST be provided") unless message.empty?
39
74
  end
40
- def initialize(configuration={})
75
+
76
+ def initialize(configuration = {})
41
77
  Adaptor.validate(configuration)
42
78
  @configuration = configuration.dup
43
79
  @configuration[:allow_anonymous] ||= false
@@ -45,23 +81,27 @@ module OmniAuth
45
81
  VALID_ADAPTER_CONFIGURATION_KEYS.each do |name|
46
82
  instance_variable_set("@#{name}", @configuration[name])
47
83
  end
48
- method = ensure_method(@method)
49
84
  config = {
50
- :host => @host,
51
- :port => @port,
52
- :base => @base
85
+ base: @base,
86
+ hosts: @hosts,
87
+ host: @host,
88
+ port: @port,
89
+ encryption: encryption_options,
53
90
  }
54
- @bind_method = @try_sasl ? :sasl : (@allow_anonymous||!@bind_dn||!@password ? :anonymous : :simple)
55
-
91
+ @bind_method = if @try_sasl
92
+ :sasl
93
+ else
94
+ ((@allow_anonymous || !@bind_dn || !@password) ? :anonymous : :simple)
95
+ end
56
96
 
57
- @auth = sasl_auths({:username => @bind_dn, :password => @password}).first if @bind_method == :sasl
58
- @auth ||= { :method => @bind_method,
59
- :username => @bind_dn,
60
- :password => @password
61
- }
97
+ @auth = sasl_auths({username: @bind_dn, password: @password}).first if @bind_method == :sasl
98
+ @auth ||= {
99
+ method: @bind_method,
100
+ username: @bind_dn,
101
+ password: @password,
102
+ }
62
103
  config[:auth] = @auth
63
104
  @connection = Net::LDAP.new(config)
64
- @connection.encryption(method)
65
105
  end
66
106
 
67
107
  #:base => "dc=yourcompany, dc=com",
@@ -70,16 +110,19 @@ module OmniAuth
70
110
  def bind_as(args = {})
71
111
  result = false
72
112
  @connection.open do |me|
73
- rs = me.search args
113
+ rs = me.search(args)
74
114
  if rs and rs.first and dn = rs.first.dn
75
115
  password = args[:password]
76
116
  method = args[:method] || @method
77
117
  password = password.call if password.respond_to?(:call)
78
- if method == 'sasl'
79
- result = rs.first if me.bind(sasl_auths({:username => dn, :password => password}).first)
80
- else
81
- result = rs.first if me.bind(:method => :simple, :username => dn,
82
- :password => password)
118
+ if method == "sasl"
119
+ result = rs.first if me.bind(sasl_auths({username: dn, password: password}).first)
120
+ elsif me.bind(
121
+ method: :simple,
122
+ username: dn,
123
+ password: password,
124
+ )
125
+ result = rs.first
83
126
  end
84
127
  end
85
128
  end
@@ -87,29 +130,64 @@ module OmniAuth
87
130
  end
88
131
 
89
132
  private
90
- def ensure_method(method)
91
- method ||= "plain"
92
- normalized_method = method.to_s.downcase.to_sym
93
- return METHOD[normalized_method] if METHOD.has_key?(normalized_method)
94
133
 
95
- available_methods = METHOD.keys.collect {|m| m.inspect}.join(", ")
134
+ def encryption_options
135
+ translated_method = translate_method
136
+ return unless translated_method
137
+
138
+ {
139
+ method: translated_method,
140
+ tls_options: tls_options(translated_method),
141
+ }
142
+ end
143
+
144
+ def translate_method
145
+ method = @encryption || @method
146
+ method ||= "plain"
147
+ normalized_method = method.to_s.downcase.to_sym
148
+
149
+ unless ENCRYPTION_METHOD.has_key?(normalized_method)
150
+ available_methods = ENCRYPTION_METHOD.keys.collect { |m| m.inspect }.join(", ")
96
151
  format = "%s is not one of the available connect methods: %s"
97
152
  raise ConfigurationError, format % [method.inspect, available_methods]
153
+ end
154
+
155
+ ENCRYPTION_METHOD[normalized_method]
156
+ end
157
+
158
+ def tls_options(translated_method)
159
+ return {} if translated_method.nil? # (plain)
160
+
161
+ options = default_options
162
+
163
+ if @tls_options
164
+ # Prevent blank config values from overwriting SSL defaults
165
+ configured_options = sanitize_hash_values(@tls_options)
166
+ configured_options = symbolize_hash_keys(configured_options)
167
+
168
+ options.merge!(configured_options)
169
+ end
170
+
171
+ # Retain backward compatibility until deprecated configs are removed.
172
+ options[:ca_file] = @ca_file if @ca_file
173
+ options[:ssl_version] = @ssl_version if @ssl_version
174
+
175
+ options
98
176
  end
99
177
 
100
- def sasl_auths(options={})
178
+ def sasl_auths(options = {})
101
179
  auths = []
102
180
  sasl_mechanisms = options[:sasl_mechanisms] || @sasl_mechanisms
103
181
  sasl_mechanisms.each do |mechanism|
104
- normalized_mechanism = mechanism.downcase.gsub(/-/, '_')
182
+ normalized_mechanism = mechanism.downcase.tr("-", "_")
105
183
  sasl_bind_setup = "sasl_bind_setup_#{normalized_mechanism}"
106
184
  next unless respond_to?(sasl_bind_setup, true)
107
185
  initial_credential, challenge_response = send(sasl_bind_setup, options)
108
186
  auths << {
109
- :method => :sasl,
110
- :initial_credential => initial_credential,
111
- :mechanism => mechanism,
112
- :challenge_response => challenge_response
187
+ method: :sasl,
188
+ initial_credential: initial_credential,
189
+ mechanism: mechanism,
190
+ challenge_response: challenge_response,
113
191
  }
114
192
  end
115
193
  auths
@@ -118,8 +196,8 @@ module OmniAuth
118
196
  def sasl_bind_setup_digest_md5(options)
119
197
  bind_dn = options[:username]
120
198
  initial_credential = ""
121
- challenge_response = Proc.new do |cred|
122
- pref = SASL::Preferences.new :digest_uri => "ldap/#{@host}", :username => bind_dn, :has_password? => true, :password => options[:password]
199
+ challenge_response = proc do |cred|
200
+ pref = SASL::Preferences.new(digest_uri: "ldap/#{@host}", username: bind_dn, has_password?: true, password: options[:password])
123
201
  sasl = SASL.new("DIGEST-MD5", pref)
124
202
  response = sasl.receive("challenge", cred)
125
203
  response[1]
@@ -130,18 +208,48 @@ module OmniAuth
130
208
  def sasl_bind_setup_gss_spnego(options)
131
209
  bind_dn = options[:username]
132
210
  psw = options[:password]
133
- raise LdapError.new( "invalid binding information" ) unless (bind_dn && psw)
211
+ raise LdapError.new("invalid binding information") unless bind_dn && psw
134
212
 
135
- nego = proc {|challenge|
136
- t2_msg = Net::NTLM::Message.parse( challenge )
137
- bind_dn, domain = bind_dn.split('\\').reverse
138
- t2_msg.target_name = Net::NTLM::encode_utf16le(domain) if domain
139
- t3_msg = t2_msg.response( {:user => bind_dn, :password => psw}, {:ntlmv2 => true} )
213
+ nego = proc { |challenge|
214
+ t2_msg = Net::NTLM::Message.parse(challenge)
215
+ bind_dn, domain = bind_dn.split("\\").reverse
216
+ t2_msg.target_name = Net::NTLM.encode_utf16le(domain) if domain
217
+ t3_msg = t2_msg.response({user: bind_dn, password: psw}, {ntlmv2: true})
140
218
  t3_msg.serialize
141
219
  }
142
220
  [Net::NTLM::Message::Type1.new.serialize, nego]
143
221
  end
144
222
 
223
+ private
224
+
225
+ def default_options
226
+ if @disable_verify_certificates
227
+ # It is important to explicitly set verify_mode for two reasons:
228
+ # 1. The behavior of OpenSSL is undefined when verify_mode is not set.
229
+ # 2. The net-ldap gem implementation verifies the certificate hostname
230
+ # unless verify_mode is set to VERIFY_NONE.
231
+ {verify_mode: OpenSSL::SSL::VERIFY_NONE}
232
+ else
233
+ OpenSSL::SSL::SSLContext::DEFAULT_PARAMS.dup
234
+ end
235
+ end
236
+
237
+ # Removes keys that have blank values
238
+ #
239
+ # This gem may not always be in the context of Rails so we
240
+ # do this rather than `.blank?`.
241
+ def sanitize_hash_values(hash)
242
+ hash.delete_if do |_, value|
243
+ value.nil? ||
244
+ (value.is_a?(String) && value !~ /\S/)
245
+ end
246
+ end
247
+
248
+ def symbolize_hash_keys(hash)
249
+ hash.each_with_object({}) do |(key, value), result|
250
+ result[key.to_sym] = value
251
+ end
252
+ end
145
253
  end
146
254
  end
147
255
  end
@@ -1,5 +1,8 @@
1
1
  module OmniAuth
2
2
  module LDAP
3
- VERSION = "2.0.0"
3
+ module Version
4
+ VERSION = "2.3.1"
5
+ end
6
+ VERSION = Version::VERSION # Make VERSION available in traditional way
4
7
  end
5
8
  end