mongo 2.26.0 → 2.26.2

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.
Files changed (42) hide show
  1. checksums.yaml +4 -4
  2. data/lib/mongo/address/validator.rb +14 -9
  3. data/lib/mongo/auth.rb +8 -3
  4. data/lib/mongo/client.rb +40 -9
  5. data/lib/mongo/client_encryption.rb +47 -1
  6. data/lib/mongo/cluster/topology.rb +3 -3
  7. data/lib/mongo/collection/view/aggregation.rb +9 -9
  8. data/lib/mongo/collection/view/change_stream.rb +1 -5
  9. data/lib/mongo/collection/view/iterable.rb +2 -9
  10. data/lib/mongo/collection/view/map_reduce.rb +5 -4
  11. data/lib/mongo/collection/view/readable.rb +3 -3
  12. data/lib/mongo/crypt/auto_encrypter.rb +15 -1
  13. data/lib/mongo/crypt/context.rb +30 -4
  14. data/lib/mongo/crypt/encryption_io.rb +103 -17
  15. data/lib/mongo/crypt/explicit_encrypter.rb +6 -2
  16. data/lib/mongo/csot_timeout_holder.rb +5 -2
  17. data/lib/mongo/cursor.rb +13 -0
  18. data/lib/mongo/database/view.rb +7 -6
  19. data/lib/mongo/database.rb +7 -10
  20. data/lib/mongo/error/invalid_read_option.rb +9 -2
  21. data/lib/mongo/error/invalid_uri.rb +14 -6
  22. data/lib/mongo/index/view.rb +3 -2
  23. data/lib/mongo/monitoring/event/secure.rb +6 -1
  24. data/lib/mongo/operation/map_reduce/result.rb +6 -2
  25. data/lib/mongo/operation/shared/result/aggregatable.rb +3 -3
  26. data/lib/mongo/options/redacted.rb +230 -30
  27. data/lib/mongo/protocol/serializers.rb +1 -9
  28. data/lib/mongo/server/app_metadata.rb +1 -2
  29. data/lib/mongo/server/connection.rb +7 -0
  30. data/lib/mongo/server/connection_pool.rb +60 -9
  31. data/lib/mongo/session.rb +7 -0
  32. data/lib/mongo/socket/ssl.rb +32 -6
  33. data/lib/mongo/srv/resolver.rb +38 -6
  34. data/lib/mongo/srv/result.rb +8 -6
  35. data/lib/mongo/tracing/open_telemetry/command_tracer.rb +142 -103
  36. data/lib/mongo/tracing/open_telemetry/operation_tracer.rb +56 -32
  37. data/lib/mongo/tracing/open_telemetry/tracer.rb +16 -30
  38. data/lib/mongo/uri/options_mapper.rb +44 -22
  39. data/lib/mongo/uri/srv_protocol.rb +18 -11
  40. data/lib/mongo/uri.rb +174 -41
  41. data/lib/mongo/version.rb +1 -1
  42. metadata +545 -537
@@ -16,27 +16,47 @@
16
16
 
17
17
  module Mongo
18
18
  module Options
19
- # Class for wrapping options that could be sensitive.
20
- # When printed, the sensitive values will be redacted.
19
+ # Shared string, debug and serialization representations for option
20
+ # objects that may carry sensitive values.
21
21
  #
22
- # @since 2.1.0
23
- class Redacted < BSON::Document
24
- # The options whose values will be redacted.
25
- #
26
- # @since 2.1.0
27
- SENSITIVE_OPTIONS = %i[password
28
- pwd].freeze
22
+ # Sensitive values are replaced by {Redacted::STRING_REPLACEMENT} in
23
+ # inspect, to_s, pretty printing, JSON, YAML, Extended JSON and Marshal
24
+ # output. The stored values are not changed.
25
+ #
26
+ # BSON encoding is intentionally not overridden: these objects are BSON
27
+ # documents, and BSON is the wire representation used by the driver. The
28
+ # native BSON encoder writes nested hashes without dispatching to Ruby
29
+ # methods on them, so a Ruby-level to_bson override would be both
30
+ # incomplete and would change what is written to the wire.
31
+ #
32
+ # @api private
33
+ module RedactedRepresentation
34
+ # Envelope keys used by YAML and Marshal. They surround, rather than
35
+ # live inside, the user's options hash.
36
+ # @api private
37
+ SERIALIZATION_REDACTED_KEY = 'redacted'
29
38
 
30
- # The replacement string used in place of the value for sensitive keys.
31
- #
32
- # @since 2.1.0
33
- STRING_REPLACEMENT = '<REDACTED>'
39
+ # @api private
40
+ SERIALIZATION_OPTIONS_KEY = 'options'
41
+
42
+ # Error raised when deserializing a representation whose sensitive
43
+ # values were redacted.
44
+ REDACTED_SERIALIZATION_ERROR =
45
+ 'Cannot deserialize options whose sensitive values were redacted: ' \
46
+ 'recreate the options from configuration instead.'
47
+
48
+ # Error raised for a payload that reaches the new object-tag YAML
49
+ # loader or the user-defined Marshal loader but does not contain the
50
+ # redaction envelope. Legacy Hash formats (for example YAML with a
51
+ # !ruby/hash tag, or standard Marshal data for a Hash subclass) can
52
+ # bypass those hooks and are not covered by this error.
53
+ LEGACY_SERIALIZATION_ERROR =
54
+ 'Cannot deserialize options without a redaction envelope: ' \
55
+ 'recreate the options from configuration instead.'
34
56
 
35
57
  # Get a string representation of the options.
36
58
  #
37
59
  # @return [ String ] The string representation of the options.
38
- #
39
- # @since 2.1.0
40
60
  def inspect
41
61
  redacted_string(:inspect)
42
62
  end
@@ -44,12 +64,191 @@ module Mongo
44
64
  # Get a string representation of the options.
45
65
  #
46
66
  # @return [ String ] The string representation of the options.
47
- #
48
- # @since 2.1.0
49
67
  def to_s
50
68
  redacted_string(:to_s)
51
69
  end
52
70
 
71
+ # Pretty print the options, redacting sensitive values.
72
+ #
73
+ # @param [ PP ] q The pretty printer.
74
+ def pretty_print(q)
75
+ q.pp(redacted_serialization_hash)
76
+ end
77
+
78
+ # Serialize the options to JSON, redacting sensitive values.
79
+ #
80
+ # @param [ Array ] args JSON generator arguments and state.
81
+ #
82
+ # @return [ String ] The JSON representation.
83
+ def to_json(*args)
84
+ redacted_serialization_hash.to_json(*args)
85
+ end
86
+
87
+ # Serialize the options to YAML, redacting sensitive values.
88
+ #
89
+ # The user's options are nested under an envelope so that metadata
90
+ # cannot collide with option names. Deserialization raises when
91
+ # sensitive values were redacted.
92
+ #
93
+ # @param [ Psych::Coder ] coder The YAML coder.
94
+ def encode_with(coder)
95
+ coder.tag = "!ruby/object:#{self.class.name}"
96
+ serialization_envelope.each do |key, value|
97
+ coder[key] = value
98
+ end
99
+ end
100
+
101
+ # Initialize options from YAML.
102
+ #
103
+ # Raises if the serialized form contains redacted sensitive values or
104
+ # does not use the redaction envelope. It never creates an object with
105
+ # marker strings standing in for credentials.
106
+ #
107
+ # @param [ Psych::Coder ] coder The YAML coder.
108
+ def init_with(coder)
109
+ load_serialization_envelope(coder.map)
110
+ end
111
+
112
+ # Serialize the options to Extended JSON, redacting sensitive values.
113
+ #
114
+ # @param [ Hash ] options BSON Extended JSON options.
115
+ #
116
+ # @return [ String ] The Extended JSON representation.
117
+ def to_extended_json(**options)
118
+ redacted_serialization_hash.to_extended_json(**options)
119
+ end
120
+
121
+ # Convert the options to a Hash for BSON Extended JSON encoding.
122
+ #
123
+ # @param [ Hash ] options BSON Extended JSON options.
124
+ #
125
+ # @return [ Hash ] The redacted Hash.
126
+ def as_extended_json(**options)
127
+ redacted_serialization_hash.as_extended_json(**options)
128
+ end
129
+
130
+ # Convert the options to a Hash for ActiveSupport's JSON encoding.
131
+ #
132
+ # @param [ Hash | nil ] options The ActiveSupport options.
133
+ #
134
+ # @return [ Hash ] The redacted Hash.
135
+ def as_json(options = nil)
136
+ redacted = redacted_serialization_hash
137
+ if redacted.respond_to?(:as_json)
138
+ redacted.as_json(options)
139
+ else
140
+ redacted
141
+ end
142
+ end
143
+
144
+ # Dump the options for Marshal, redacting sensitive values.
145
+ #
146
+ # @return [ Hash ] The envelope with redacted options.
147
+ def marshal_dump
148
+ serialization_envelope
149
+ end
150
+
151
+ # Load the options from Marshal.
152
+ #
153
+ # Raises if the serialized form contains redacted sensitive values or
154
+ # does not use the redaction envelope. It never creates an object with
155
+ # marker strings standing in for credentials.
156
+ #
157
+ # @param [ Hash ] hash The dumped envelope.
158
+ def marshal_load(hash)
159
+ load_serialization_envelope(hash)
160
+ end
161
+
162
+ private
163
+
164
+ def redacted_string(method)
165
+ '{' + map do |key, value|
166
+ "#{key.public_send(method)}=>#{redacted_value(key, value, method)}"
167
+ end.join(', ') + '}'
168
+ end
169
+
170
+ def redacted_value(key, value, method)
171
+ return Redacted::STRING_REPLACEMENT if sensitive_key?(key)
172
+
173
+ value.public_send(method)
174
+ end
175
+
176
+ def redacted_serialization_hash
177
+ each_with_object({}) do |(key, value), copy|
178
+ copy[key] = sensitive_key?(key) ? Redacted::STRING_REPLACEMENT : value
179
+ end
180
+ end
181
+
182
+ def sensitive_key?(key)
183
+ return false unless key.respond_to?(:to_sym)
184
+
185
+ Redacted::SENSITIVE_OPTIONS.include?(key.to_sym)
186
+ end
187
+
188
+ def has_sensitive_keys?
189
+ keys.any? { |key| sensitive_key?(key) }
190
+ end
191
+
192
+ def serialization_envelope
193
+ {
194
+ SERIALIZATION_REDACTED_KEY => has_sensitive_keys?,
195
+ SERIALIZATION_OPTIONS_KEY => redacted_serialization_hash,
196
+ }
197
+ end
198
+
199
+ def load_serialization_envelope(envelope)
200
+ unless envelope.is_a?(Hash) &&
201
+ envelope.key?(SERIALIZATION_REDACTED_KEY) &&
202
+ envelope.key?(SERIALIZATION_OPTIONS_KEY)
203
+ raise ArgumentError, LEGACY_SERIALIZATION_ERROR
204
+ end
205
+
206
+ options = envelope[SERIALIZATION_OPTIONS_KEY] || {}
207
+ if envelope[SERIALIZATION_REDACTED_KEY] ||
208
+ options.keys.any? { |key| sensitive_key?(key) }
209
+ raise ArgumentError, REDACTED_SERIALIZATION_ERROR
210
+ end
211
+
212
+ options.each do |key, value|
213
+ self[key] = value
214
+ end
215
+ end
216
+ end
217
+
218
+ # Class for wrapping options that could be sensitive.
219
+ #
220
+ # Sensitive values are redacted in inspect, to_s, pretty printed, JSON,
221
+ # YAML and Marshal output. The stored values are unchanged. Deserializing
222
+ # a YAML or Marshal representation that contained sensitive values raises
223
+ # ArgumentError instead of creating an object with marker credentials.
224
+ #
225
+ # @since 2.1.0
226
+ class Redacted < BSON::Document
227
+ include RedactedRepresentation
228
+
229
+ # The options whose values will be redacted. The username is included
230
+ # because it is part of the userinfo segment, whose components the
231
+ # connection string specification treats as sensitive values.
232
+ #
233
+ # The arguments of the sensitive URI options are redacted as a whole:
234
+ # authMechanismProperties may carry a credential in any of its
235
+ # properties (for example an AWS session token), and the driver cannot
236
+ # know which properties a future mechanism will treat as secret.
237
+ #
238
+ # @since 2.1.0
239
+ SENSITIVE_OPTIONS = %i[user
240
+ password
241
+ pwd
242
+ proxy_password
243
+ proxy_username
244
+ ssl_key_pass_phrase
245
+ auth_mech_properties].freeze
246
+
247
+ # The replacement string used in place of the value for sensitive keys.
248
+ #
249
+ # @since 2.1.0
250
+ STRING_REPLACEMENT = '<REDACTED>'
251
+
53
252
  # Whether these options contain a given key.
54
253
  #
55
254
  # @example Determine if the options contain a given key.
@@ -138,20 +337,21 @@ module Mongo
138
337
  to_enum
139
338
  end
140
339
  end
340
+ end
141
341
 
142
- private
143
-
144
- def redacted_string(method)
145
- '{' + reduce([]) do |list, (k, v)|
146
- list << "#{k.public_send(method)}=>#{redact(k, v, method)}"
147
- end.join(', ') + '}'
148
- end
149
-
150
- def redact(k, v, method)
151
- return STRING_REPLACEMENT if SENSITIVE_OPTIONS.include?(k.to_sym)
152
-
153
- v.public_send(method)
154
- end
342
+ # A plain Hash whose string and serialized representations redact
343
+ # sensitive values.
344
+ #
345
+ # Unlike {Redacted}, which is a BSON::Document and normalizes its keys to
346
+ # strings, this class preserves the keys exactly as they were inserted.
347
+ # It is used for option hashes whose key types are part of the driver's
348
+ # observable behavior. Accessing the hash returns the real values;
349
+ # deserializing a representation with sensitive values raises
350
+ # ArgumentError.
351
+ #
352
+ # @api private
353
+ class RedactedHash < Hash
354
+ include RedactedRepresentation
155
355
  end
156
356
  end
157
357
  end
@@ -319,16 +319,8 @@ module Mongo
319
319
  # @return [ Array<BSON::Document> ] Deserialized section.
320
320
  #
321
321
  # @since 2.5.0
322
- def self.deserialize(buffer)
322
+ def self.deserialize(buffer, _options = {})
323
323
  raise NotImplementedError
324
-
325
- start_size = buffer.length
326
- section_size = buffer.get_int32 # get the size
327
- end_size = start_size - section_size
328
- buffer.get_cstring # get the identifier
329
- documents = []
330
- documents << BSON::Document.from_bson(buffer) until buffer.length == end_size
331
- documents
332
324
  end
333
325
  end
334
326
  end
@@ -130,7 +130,6 @@ module Mongo
130
130
  doc[:driver] = driver_doc
131
131
  doc[:os] = os_doc
132
132
  doc[:platform] = platform_string
133
- doc[:backpressure] = '2'
134
133
  env_doc.tap { |env| doc[:env] = env if env }
135
134
  end
136
135
  end
@@ -157,7 +156,7 @@ module Mongo
157
156
  def document
158
157
  @document ||= begin
159
158
  client = Truncator.new(client_document).document
160
- BSON::Document.new(compression: @compressors, client: client).tap do |doc|
159
+ BSON::Document.new(compression: @compressors, client: client, backpressure: '2').tap do |doc|
161
160
  doc[:saslSupportedMechs] = @request_auth_mech if @request_auth_mech
162
161
  doc.update(Utils.transform_server_api(@server_api)) if @server_api
163
162
  end
@@ -124,6 +124,13 @@ module Mongo
124
124
  # across all connections.
125
125
  attr_reader :global_id
126
126
 
127
+ # @return [ Hash | nil ] OpenTelemetry span attributes describing this
128
+ # connection. Built once by the tracer and reused for every command
129
+ # on the connection.
130
+ #
131
+ # @api private
132
+ attr_accessor :tracing_attributes
133
+
127
134
  def_delegators :server, :tracer
128
135
 
129
136
  # The connection pool from which this connection was created.
@@ -432,6 +432,30 @@ module Mongo
432
432
  check_invariants
433
433
  end
434
434
 
435
+ # Check a connection back into the pool only if this pool still holds
436
+ # it as checked out and no other owner has claimed it.
437
+ #
438
+ # Unlike #check_in, this method is safe to call when the connection may
439
+ # have been checked in already (e.g. by Session#unpin while handling a
440
+ # transient transaction error) or may be pinned to a transaction or
441
+ # cursor that will check it in later; in both cases it does nothing.
442
+ #
443
+ # @param [ Mongo::Server::Connection ] connection The connection.
444
+ #
445
+ # @api private
446
+ def check_in_if_checked_out(connection)
447
+ check_invariants
448
+
449
+ @lock.synchronize do
450
+ return if connection.pinned?
451
+ return unless @checked_out_connections.include?(connection)
452
+
453
+ do_check_in(connection)
454
+ end
455
+ ensure
456
+ check_invariants
457
+ end
458
+
435
459
  # Executes the check in after having already acquired the lock.
436
460
  #
437
461
  # @param [ Mongo::Server::Connection ] connection The connection.
@@ -758,16 +782,43 @@ module Mongo
758
782
  rescue Error::SocketError, Error::SocketTimeoutError, Error::ConnectionPerished => e
759
783
  maybe_raise_pool_cleared!(connection, e)
760
784
  ensure
761
- if connection && !connection.pinned?
762
- # Do not check in if the connection is pinned (the session or cursor
763
- # owns it and will check it in later when unpinning). Also skip
764
- # check-in if the connection was already checked in during the block
765
- # (e.g. by Session#unpin after an error on the first operation).
766
- checked_out = @lock.synchronize do
767
- @checked_out_connections.include?(connection)
768
- end
769
- check_in(connection) if checked_out
785
+ # Do not check in if the connection is pinned (the session or cursor
786
+ # owns it and will check it in later when unpinning) or was already
787
+ # checked in during the block (e.g. by Session#unpin after an error
788
+ # on the first operation).
789
+ check_in_if_checked_out(connection) if connection
790
+ end
791
+
792
+ # Check out a connection for the initial command of a cursor-returning
793
+ # operation in load-balanced topology and yield it to the block.
794
+ #
795
+ # On success the connection remains checked out: the cursor assumes
796
+ # ownership and checks it in when drained or closed. If the block
797
+ # raises, no cursor exists to do that, so the connection is checked
798
+ # back in here before the error propagates, unless another owner
799
+ # already claimed it (it is pinned to a transaction, or Session#unpin
800
+ # checked it in while handling a transient transaction error).
801
+ #
802
+ # If the operation context is pinned to a connection (e.g. inside a
803
+ # transaction), the pinned connection is reused.
804
+ #
805
+ # @param [ Mongo::Operation::Context | nil ] :context Context of the
806
+ # operation the connection is requested for, if any.
807
+ #
808
+ # @return [ Object ] The result of the block.
809
+ #
810
+ # @api private
811
+ def with_cursor_connection(context:)
812
+ if context&.connection_global_id
813
+ connection = check_out_pinned_connection(context.connection_global_id)
770
814
  end
815
+ connection ||= check_out(context: context)
816
+ succeeded = false
817
+ result = yield(connection)
818
+ succeeded = true
819
+ result
820
+ ensure
821
+ check_in_if_checked_out(connection) if connection && !succeeded
771
822
  end
772
823
 
773
824
  # Close sockets that have been open for longer than the max idle time,
data/lib/mongo/session.rb CHANGED
@@ -297,6 +297,13 @@ module Mongo
297
297
  # @api private
298
298
  attr_accessor :recovery_token
299
299
 
300
+ # @return [ Array<Integer, String> | nil ] The transaction number and the
301
+ # OpenTelemetry tracer's key for that transaction. Built once by the
302
+ # tracer and reused for every operation in the transaction.
303
+ #
304
+ # @api private
305
+ attr_accessor :tracing_transaction_key
306
+
300
307
  # Error message indicating that the session was retrieved from a client with a different cluster than that of the
301
308
  # client through which it is currently being used.
302
309
  #
@@ -102,12 +102,17 @@ module Mongo
102
102
  def initialize(host, port, host_name, timeout, family, options = {})
103
103
  super(timeout, options)
104
104
  @host, @port, @host_name = host, port, host_name
105
- @context = create_context(options)
105
+ begin
106
+ @context = create_context(options)
107
+ rescue StandardError
108
+ # The caller-provided socket has not been assigned to @tcp_socket
109
+ # yet, so close it here to avoid leaking it.
110
+ options[:connected_socket]&.close
111
+ raise
112
+ end
106
113
  @family = family
107
- @tcp_socket = ::Socket.new(family, SOCK_STREAM, 0)
114
+ @tcp_socket = options[:connected_socket] || build_tcp_socket(family)
108
115
  begin
109
- @tcp_socket.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1)
110
- set_socket_options(@tcp_socket)
111
116
  run_tls_context_hooks
112
117
 
113
118
  connect!
@@ -141,7 +146,7 @@ module Mongo
141
146
  #
142
147
  # @since 2.0.0
143
148
  def connect!
144
- sockaddr = ::Socket.pack_sockaddr_in(port, host)
149
+ sockaddr = options[:connected_socket] ? nil : ::Socket.pack_sockaddr_in(port, host)
145
150
  connect_timeout = options[:connect_timeout]
146
151
  map_exceptions do
147
152
  if connect_timeout && connect_timeout != 0
@@ -193,11 +198,30 @@ module Mongo
193
198
 
194
199
  private
195
200
 
201
+ # Creates and configures a TCP socket for a driver-initiated connection.
202
+ #
203
+ # @param [ Integer ] family The socket family.
204
+ #
205
+ # @return [ ::Socket ] The configured, unconnected socket.
206
+ def build_tcp_socket(family)
207
+ socket = ::Socket.new(family, SOCK_STREAM, 0)
208
+ begin
209
+ socket.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1)
210
+ set_socket_options(socket)
211
+ rescue StandardError
212
+ # The socket has not been assigned to @tcp_socket yet, so close it
213
+ # here to avoid leaking the file descriptor.
214
+ socket.close
215
+ raise
216
+ end
217
+ socket
218
+ end
219
+
196
220
  # Connects the socket without a timeout provided.
197
221
  #
198
222
  # @param [ String ] sockaddr Address to connect to.
199
223
  def connect_without_timeout(sockaddr)
200
- @tcp_socket.connect(sockaddr)
224
+ @tcp_socket.connect(sockaddr) unless options[:connected_socket]
201
225
  @socket = OpenSSL::SSL::SSLSocket.new(@tcp_socket, context)
202
226
  @socket.hostname = @host_name
203
227
  @socket.sync_close = true
@@ -219,6 +243,8 @@ module Mongo
219
243
  end
220
244
 
221
245
  def connect_tcp_socket_with_timeout(sockaddr, deadline, connect_timeout)
246
+ return if options[:connected_socket]
247
+
222
248
  if deadline <= Utils.monotonic_time
223
249
  raise Error::SocketTimeoutError, "The socket took over #{connect_timeout} seconds to connect"
224
250
  end
@@ -27,6 +27,23 @@ module Mongo
27
27
  # before querying SRV records.
28
28
  RECORD_PREFIX = '_mongodb._tcp.'
29
29
 
30
+ # @return [ String ] DNS_QUERY_FAILED Error message used when the DNS
31
+ # resolver raises an error. Resolver error messages quote the query
32
+ # name, which for a malformed connection string may contain part of a
33
+ # credential, so they are replaced with this fixed message.
34
+ DNS_QUERY_FAILED = 'The DNS query failed'
35
+
36
+ # @return [ Array<Class> ] DNS_ERRORS Errors raised by the DNS resolver
37
+ # whose messages may quote the query name.
38
+ DNS_ERRORS = [
39
+ Resolv::ResolvError,
40
+ Resolv::ResolvTimeout,
41
+ Timeout::Error,
42
+ IOError,
43
+ SystemCallError,
44
+ SocketError,
45
+ ].freeze
46
+
30
47
  # Generates the record prefix with a custom SRV service name if it is
31
48
  # provided.
32
49
  #
@@ -81,7 +98,7 @@ module Mongo
81
98
  # @return [ Mongo::Srv::Result ] SRV lookup result.
82
99
  def get_records(hostname, srv_service_name = nil, srv_max_hosts = nil)
83
100
  query_name = record_prefix(srv_service_name) + hostname
84
- resources = @resolver.getresources(query_name, Resolv::DNS::Resource::IN::SRV)
101
+ resources = get_resources(query_name, Resolv::DNS::Resource::IN::SRV)
85
102
 
86
103
  # Collect all of the records into a Result object, raising an error
87
104
  # or logging a warning if a record with a mismatched domain is found.
@@ -99,10 +116,9 @@ module Mongo
99
116
  # If no records are found, either raise an error or log a warning
100
117
  # based on the Resolver's :raise_on_invalid option.
101
118
  if result.empty?
102
- raise Error::NoSRVRecords.new(URI::SRVProtocol::NO_SRV_RECORDS % hostname) if raise_on_invalid?
103
-
104
- log_warn(URI::SRVProtocol::NO_SRV_RECORDS % hostname)
119
+ raise Error::NoSRVRecords.new(URI::SRVProtocol::NO_SRV_RECORDS) if raise_on_invalid?
105
120
 
121
+ log_warn(URI::SRVProtocol::NO_SRV_RECORDS)
106
122
  end
107
123
 
108
124
  # if srv_max_hosts is in [1, #addresses)
@@ -123,11 +139,11 @@ module Mongo
123
139
  #
124
140
  # @raise [ Mongo::Error::InvalidTXTRecord ] If more than one TXT record is found.
125
141
  def get_txt_options_string(hostname)
126
- records = @resolver.getresources(hostname, Resolv::DNS::Resource::IN::TXT)
142
+ records = get_resources(hostname, Resolv::DNS::Resource::IN::TXT)
127
143
  return nil if records.empty?
128
144
 
129
145
  if records.length > 1
130
- msg = "Only one TXT record is allowed: querying hostname #{hostname} returned #{records.length} records"
146
+ msg = "Only one TXT record is allowed (found #{records.length})"
131
147
 
132
148
  raise Error::InvalidTXTRecord, msg
133
149
  end
@@ -137,6 +153,22 @@ module Mongo
137
153
 
138
154
  private
139
155
 
156
+ # Performs a DNS query, replacing any resolver error with a fixed
157
+ # message. Resolver error messages quote the query name, and the cause
158
+ # chain would quote it again, so both are dropped. The exception class
159
+ # is preserved so callers can still distinguish timeouts from other
160
+ # failures.
161
+ #
162
+ # @param [ String ] query_name The name to query.
163
+ # @param [ Class ] resource_class The record type.
164
+ #
165
+ # @return [ Array<Resolv::DNS::Resource> ] The records.
166
+ def get_resources(query_name, resource_class)
167
+ @resolver.getresources(query_name, resource_class)
168
+ rescue *DNS_ERRORS => e
169
+ raise e.class.new("#{DNS_QUERY_FAILED} (#{e.class})"), cause: nil
170
+ end
171
+
140
172
  # Checks whether an error should be raised due to either a record with
141
173
  # a mismatched domain being found or no records being found.
142
174
  #
@@ -25,10 +25,12 @@ module Mongo
25
25
  class Result
26
26
  include Address::Validator
27
27
 
28
- # @return [ String ] MISMATCHED_DOMAINNAME Error message format string indicating that an SRV
29
- # record found does not match the domain of a hostname.
30
- MISMATCHED_DOMAINNAME = 'Parent domain name in SRV record result (%s) does not match ' +
31
- 'that of the hostname (%s)'
28
+ # @return [ String ] MISMATCHED_DOMAINNAME Error message indicating that an SRV
29
+ # record found does not match the domain of a hostname. The names are not
30
+ # included: during initial parsing the hostname may contain text the user
31
+ # intended as part of a credential.
32
+ MISMATCHED_DOMAINNAME = 'Parent domain name in SRV record result does not match ' +
33
+ 'that of the hostname'
32
34
 
33
35
  # @return [ String ] query_hostname The hostname pointing to the DNS records.
34
36
  attr_reader :query_hostname
@@ -120,14 +122,14 @@ module Mongo
120
122
  record_host_parts = record_host.split('.')
121
123
 
122
124
  if srv_is_less_than_three_parts && record_host_parts.length <= srv_host_domain.length
123
- raise Error::MismatchedDomain.new(format(MISMATCHED_DOMAINNAME, record_host, srv_host_domain))
125
+ raise Error::MismatchedDomain.new(MISMATCHED_DOMAINNAME)
124
126
  end
125
127
 
126
128
  record_matches_domain = (record_host_parts.size > srv_host_domain.size) &&
127
129
  (srv_host_domain == record_host_parts[-srv_host_domain.size..-1])
128
130
  return if record_matches_domain
129
131
 
130
- raise Error::MismatchedDomain.new(format(MISMATCHED_DOMAINNAME, record_host, srv_host_domain))
132
+ raise Error::MismatchedDomain.new(MISMATCHED_DOMAINNAME)
131
133
  end
132
134
  end
133
135
  end