Class: Mongo::URI
- Inherits:
-
Object
- Object
- Mongo::URI
- Includes:
- Address::Validator, Loggable
- Defined in:
- lib/mongo/uri.rb,
lib/mongo/uri/srv_protocol.rb,
lib/mongo/uri/options_mapper.rb
Overview
The URI class provides a way for users to parse the MongoDB uri as defined in the connection string format spec.
https://www.mongodb.com/docs/manual/reference/connection-string/
Defined Under Namespace
Classes: OptionsMapper, SRVProtocol
Constant Summary collapse
- SCHEME =
Deprecated.
Will be removed in 3.0.
The mongodb connection string scheme.
'mongodb://'- MONGODB_SCHEME =
The mongodb connection string scheme root.
'mongodb'- MONGODB_SRV_SCHEME =
The mongodb srv protocol connection string scheme root.
'mongodb+srv'- INVALID_SCHEME =
Deprecated.
Error details for an invalid scheme.
"Invalid scheme. Scheme must be '#{MONGODB_SCHEME}' or '#{MONGODB_SRV_SCHEME}'"- FORMAT =
MongoDB URI format specification.
'mongodb://[username:password@]host1[:port1][,host2[:port2]' + ',...[,hostN[:portN]]][/[database][?options]]'
- HELP =
MongoDB URI (connection string) documentation url
'https://www.mongodb.com/docs/manual/reference/connection-string/'- UNSAFE =
Unsafe characters that must be urlencoded.
%r{[:/@]}- PERCENT_CHAR =
Percent sign that must be encoded in user creds.
/%/- UNIX_SOCKET =
Unix socket suffix.
/.sock/- HOST_DELIM =
The character delimiting hosts.
','- HOST_PORT_DELIM =
The character separating a host and port.
':'- DATABASE_DELIM =
The character delimiting a database.
'/'- URI_OPTS_DELIM =
The character delimiting options.
'?'- INDIV_URI_OPTS_DELIM =
Deprecated.
The character delimiting multiple options.
'&'- URI_OPTS_VALUE_DELIM =
The character delimiting an option and its value.
'='- AUTH_USER_PWD_DELIM =
The character separating a username from the password.
':'- AUTH_DELIM =
The character delimiting auth credentials.
'@'- SCHEME_DELIM =
Scheme delimiter.
'://'- CREDENTIALS_PLACEHOLDER =
Placeholder used in place of cleartext credentials and sensitive URI option arguments when a URI is rendered for display, logging, or error reporting. The same marker is used for every sensitive value in a representation, as required by the connection string specification.
'<credentials>'- SENSITIVE_URI_OPTIONS =
URI options whose values are sensitive and are replaced with CREDENTIALS_PLACEHOLDER in string representations.
authMechanismProperties is hidden as a whole: any of its properties may carry a credential (for example the AWS session token), and the driver cannot know which properties a future mechanism will treat as secret.
%w[tlsCertificateKeyFilePassword authMechanismProperties].freeze
- USERINFO_REDACTION_REGEX =
Pattern matching the userinfo portion of a MongoDB connection string. Anchors at the start and is bounded to the authority component (stops at the first '/', '?', or '#'), but matches greedily up to the last '@' in that component so passwords containing an unescaped '@' are still fully redacted. Case-insensitive so an unusual scheme like 'MongoDB://' is redacted too — the parser will reject it, and the redactor must not be the thing that leaks the credentials in the resulting error.
%r{\A(mongodb(?:\+srv)?://)[^/?#]*@}i.freeze
- INVALID_OPTS_VALUE_DELIM =
Error details for an invalid options format.
'Options and their values must be delimited' + " by '#{URI_OPTS_VALUE_DELIM}'"
- UNESCAPED_USER_PWD =
Error details for an non-urlencoded user name or password.
'User name and password must be urlencoded.'- UNESCAPED_UNIX_SOCKET =
Error details for a non-urlencoded unix socket path.
'UNIX domain sockets must be urlencoded.'- UNESCAPED_DATABASE =
Error details for a non-urlencoded auth database name.
'Auth database must be urlencoded.'- INVALID_OPTS_DELIM =
Error details for providing options without a database delimiter.
"Database delimiter '#{DATABASE_DELIM}' must be present if options are specified."- INVALID_HOST =
Error details for a missing host.
'Missing host; at least one must be provided.'- INVALID_PORT =
Error details for an invalid port.
'Invalid port. Port must be an integer greater than 0 and less than 65536'- READ_MODE_MAP =
Map of URI read preference modes to Ruby driver read preference modes
{ 'primary' => :primary, 'primarypreferred' => :primary_preferred, 'secondary' => :secondary, 'secondarypreferred' => :secondary_preferred, 'nearest' => :nearest }.freeze
- AUTH_MECH_MAP =
Map of URI authentication mechanisms to Ruby driver mechanisms
{ 'GSSAPI' => :gssapi, 'MONGODB-AWS' => :aws, # MONGODB-CR is deprecated and will be removed in driver version 3.0 'MONGODB-CR' => :mongodb_cr, 'MONGODB-X509' => :mongodb_x509, 'PLAIN' => :plain, 'SCRAM-SHA-1' => :scram, 'SCRAM-SHA-256' => :scram256, }.freeze
- SERVER_MONITORING_MODES =
Valid values for the serverMonitoringMode URI option.
%w[stream poll auto].freeze
- REPEATABLE_OPTIONS =
Options that are allowed to appear more than once in the uri.
In order to follow the URI options spec requirement that all instances of 'tls' and 'ssl' have the same value, we need to keep track of all of the values passed in for those options. Assuming they don't conflict, they will be condensed to a single value immediately after parsing the URI.
%i[tag_sets ssl]
Constants included from Loggable
Instance Attribute Summary collapse
-
#options ⇒ Object
readonly
The uri parser object options.
Class Method Summary collapse
-
.get(string, opts = {}) ⇒ URI, URI::SRVProtocol
Get either a URI object or a SRVProtocol URI object.
-
.redact(string) ⇒ String
Replace the userinfo portion of a MongoDB connection string with a placeholder so the result can be logged, displayed, or embedded in an exception message.
Instance Method Summary collapse
-
#as_json(_options = nil) ⇒ String
Return the redacted URI for ActiveSupport's JSON encoding.
-
#client_options ⇒ Mongo::Options::Redacted
Gets the options hash that needs to be passed to a Mongo::Client on instantiation, so we don't have to merge the credentials and database in at that point - we only have a single point here.
-
#credentials ⇒ Hash
Get the credentials provided in the URI.
-
#database ⇒ String
Get the database provided in the URI.
-
#encode_with(coder) ⇒ Object
Serialize the URI in a redacted form.
-
#init_with(coder) ⇒ Object
Initialize a redacted URI from YAML.
-
#initialize(string, options = {}) ⇒ URI
constructor
Create the new uri from the provided string.
-
#inspect ⇒ String
Return a redacted, human-readable representation of the URI.
-
#marshal_dump ⇒ Hash
Dump the URI for Marshal in a redacted form.
-
#marshal_load(hash) ⇒ Object
Load a redacted URI from Marshal.
-
#servers ⇒ Array<String>
Get the servers provided in the URI.
- #srv_records ⇒ Object
-
#to_s ⇒ String
Get the uri as a string with credentials and sensitive option arguments redacted.
-
#uri_options ⇒ Mongo::Options::Redacted
Get the URI options.
Methods included from Address::Validator
Methods included from Loggable
#log_debug, #log_error, #log_fatal, #log_info, #log_warn, #logger
Constructor Details
#initialize(string, options = {}) ⇒ URI
Create the new uri from the provided string.
320 321 322 323 324 325 326 327 328 329 330 331 332 333 |
# File 'lib/mongo/uri.rb', line 320 def initialize(string, = {}) raise Error::InvalidURI.new(string, 'URI must be a string, not nil.') unless string raise Error::InvalidURI.new(string, 'Cannot parse an empty URI.') if string.empty? @string = string @options = parsed_scheme, _, remaining = string.partition(SCHEME_DELIM) unless parsed_scheme == scheme raise_invalid_error!("Invalid scheme. Scheme must be '#{MONGODB_SCHEME}'. Use URI#get to parse SRV URIs.") end raise_invalid_error!('No hosts in the URI') if remaining.empty? parse!(remaining) end |
Instance Attribute Details
#options ⇒ Object (readonly)
The uri parser object options.
37 38 39 |
# File 'lib/mongo/uri.rb', line 37 def @options end |
Class Method Details
.get(string, opts = {}) ⇒ URI, URI::SRVProtocol
Get either a URI object or a SRVProtocol URI object.
268 269 270 271 272 273 274 275 276 277 278 279 280 281 |
# File 'lib/mongo/uri.rb', line 268 def self.get(string, opts = {}) raise Error::InvalidURI.new(string, 'URI must be a string, not nil.') unless string raise Error::InvalidURI.new(string, 'Cannot parse an empty URI.') if string.empty? scheme, = string.partition(SCHEME_DELIM) case scheme when MONGODB_SCHEME URI.new(string, opts) when MONGODB_SRV_SCHEME SRVProtocol.new(string, opts) else raise Error::InvalidURI.new(string, INVALID_SCHEME) end end |
.redact(string) ⇒ String
Replace the userinfo portion of a MongoDB connection string with a placeholder so the result can be logged, displayed, or embedded in an exception message.
The input is matched as a string, not parsed. It is a best-effort helper for strings that are already known to be well-formed; it must not be used to make a parse failure safe, because a string the parser rejected may not have delimited its credentials with '@'. Diagnostics for parse failures must not include any part of the input; see InvalidURI.
249 250 251 252 253 |
# File 'lib/mongo/uri.rb', line 249 def self.redact(string) return string unless string.is_a?(String) string.sub(USERINFO_REDACTION_REGEX, "\\1#{CREDENTIALS_PLACEHOLDER}@") end |
Instance Method Details
#as_json(_options = nil) ⇒ String
Return the redacted URI for ActiveSupport's JSON encoding.
ActiveSupport calls this method when encoding the URI (directly or as a value in a Hash or Array). The result is built from the parsed components and contains the credentials and sensitive option arguments as redaction markers.
423 424 425 |
# File 'lib/mongo/uri.rb', line 423 def as_json( = nil) to_s end |
#client_options ⇒ Mongo::Options::Redacted
Gets the options hash that needs to be passed to a Mongo::Client on instantiation, so we don't have to merge the credentials and database in at that point - we only have a single point here.
293 294 295 296 297 298 299 300 301 |
# File 'lib/mongo/uri.rb', line 293 def ensure_not_redacted_serialization! opts = .tap do |opts| opts[:database] = @database if @database end @user ? opts.merge(credentials) : opts end |
#credentials ⇒ Hash
Get the credentials provided in the URI.
345 346 347 348 349 |
# File 'lib/mongo/uri.rb', line 345 def credentials ensure_not_redacted_serialization! { user: @user, password: @password } end |
#database ⇒ String
Get the database provided in the URI.
377 378 379 380 381 |
# File 'lib/mongo/uri.rb', line 377 def database ensure_not_redacted_serialization! @database || Database::ADMIN end |
#encode_with(coder) ⇒ Object
Serialize the URI in a redacted form.
Serialized URIs are redacted representations and are intentionally not restored as usable connection configurations: methods that would expose or use credentials and connection options raise Error::InvalidURI. The redacted string is still available through #to_s and #inspect.
435 436 437 438 |
# File 'lib/mongo/uri.rb', line 435 def encode_with(coder) coder.tag = "!ruby/object:#{self.class.name}" coder['redacted_uri'] = to_s end |
#init_with(coder) ⇒ Object
Initialize a redacted URI from YAML.
443 444 445 |
# File 'lib/mongo/uri.rb', line 443 def init_with(coder) initialize_redacted_serialization(coder['redacted_uri']) end |
#inspect ⇒ String
Return a redacted, human-readable representation of the URI. The default Object#inspect would dump @string and @password as instance variables, leaking credentials.
409 410 411 |
# File 'lib/mongo/uri.rb', line 409 def inspect "#<#{self.class.name}: #{self}>" end |
#marshal_dump ⇒ Hash
Dump the URI for Marshal in a redacted form.
450 451 452 |
# File 'lib/mongo/uri.rb', line 450 def marshal_dump { 'redacted_uri' => to_s } end |
#marshal_load(hash) ⇒ Object
Load a redacted URI from Marshal.
457 458 459 |
# File 'lib/mongo/uri.rb', line 457 def marshal_load(hash) initialize_redacted_serialization(hash['redacted_uri']) end |
#servers ⇒ Array<String>
Get the servers provided in the URI.
354 355 356 357 358 |
# File 'lib/mongo/uri.rb', line 354 def servers ensure_not_redacted_serialization! @servers end |
#srv_records ⇒ Object
303 304 305 |
# File 'lib/mongo/uri.rb', line 303 def srv_records nil end |
#to_s ⇒ String
Get the uri as a string with credentials and sensitive option arguments redacted.
Every sensitive value, including the arguments of SENSITIVE_URI_OPTIONS, is replaced with the same CREDENTIALS_PLACEHOLDER marker, so the result is safe to log or display. The representation is built from the parsed components. Use #credentials and #uri_options to obtain the real values.
396 397 398 399 400 401 402 |
# File 'lib/mongo/uri.rb', line 396 def to_s if redacted_serialization? @redacted_uri else reconstruct_uri end end |
#uri_options ⇒ Mongo::Options::Redacted
Get the URI options.
363 364 365 366 367 |
# File 'lib/mongo/uri.rb', line 363 def ensure_not_redacted_serialization! @uri_options end |