tina4ruby 3.13.164 → 3.13.166

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.
@@ -75,15 +75,33 @@ module Tina4
75
75
  # on it and a reader recognises it on sight.
76
76
  REDACTED = "***"
77
77
 
78
+ # sqlite's in-memory spellings. ":memory:" looks like host:port to the
79
+ # credential locator, and is not one.
80
+ SQLITE_MEMORY_FORMS = ["sqlite::memory:", "sqlite:///:memory:", "sqlite://:memory:"].freeze
81
+
78
82
  # RFC 3986 scheme grammar. A scheme cannot contain ":", "@", "/" or a space,
79
83
  # which is what makes it the ONLY part of an unparseable string that is
80
84
  # provably not a password.
81
85
  SCHEME = /\A[A-Za-z][A-Za-z0-9+.\-]*\z/.freeze
82
86
 
83
- # host[:port][/path] with a NUMERIC port. The digit requirement is what does
84
- # the work: it is why "user:secret" (a URL with the host left off) fails to
85
- # match and gets redacted, while "192.168.88.99:55432/tina4_py" is echoed.
86
- HOST_PORT = %r{\A(?:\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9._-]+)(?::\d+)?(?:/.*)?\z}m.freeze
87
+ # Where the authority starts (GHSA-h2mr-m3v3-cq8c): after "scheme://", and
88
+ # ALSO after the two typos "scheme:/" and "scheme//". A URL that lost a "/"
89
+ # or its ":" still carries the password in the same place, and treating the
90
+ # rest as an opaque path is how `postgres:/u:pw@h` was printed verbatim.
91
+ AUTHORITY_START = %r{\A[A-Za-z][A-Za-z0-9+.\-]*(?:://|:/|//)}.freeze
92
+
93
+ # "scheme:" alone - only trusted as a prefix when an "@" follows.
94
+ OPAQUE_SCHEME = /\A[A-Za-z][A-Za-z0-9+.\-]*:/.freeze
95
+
96
+ # The only prefix a PARSER accepts. Anything else is refused.
97
+ URL_PREFIX = %r{\A([A-Za-z][A-Za-z0-9+.\-]*)://}.freeze
98
+
99
+ # The generic refusal: it never echoes the value, because a value whose
100
+ # shape the parser cannot trust is exactly one where the password could be
101
+ # anywhere.
102
+ AMBIGUOUS_URL = "Invalid URL format - the value is not scheme://[user[:password]@]host[:port][/path], " \
103
+ "or an '@' appears outside the user:password part (percent-encode it as %40). " \
104
+ "The URL itself is not shown because it can contain a password."
87
105
 
88
106
  # Credential KEYWORDS in the two keyword=value forms that carry one: the
89
107
  # ODBC connection string (";"-separated) and the libpq/JDBC query string
@@ -161,20 +179,107 @@ module Tina4
161
179
  # URL, and detect_driver raises it on the BOOT path, so one typo in
162
180
  # TINA4_DATABASE_URL wrote the password into the boot log and CI output.
163
181
  # One primitive means the next such bug is fixed once, not four times.
182
+ #
183
+ # GHSA-h2mr-m3v3-cq8c: this used to trust URI.parse, which ACCEPTS
184
+ # `postgres:/u:pw@h` (password in the path), `u:p@/q@h` and `u:12?q@h`
185
+ # (password in the query), and its fallback cut the authority at the first
186
+ # "?" or "#" - so a password holding / ? # @ % or a space, a URL with one
187
+ # slash or no colon after the scheme, a URL with no host, and a non-numeric
188
+ # port were all printed in clear. It is now purely structural: the ONE
189
+ # locator, #password_span, decides what the password is, and every caller
190
+ # in the framework goes through it.
164
191
  def self.redact(raw)
165
192
  text = raw.to_s
166
193
  return "" if text.empty?
167
194
 
168
- begin
169
- # A URL that PARSES gets the round-tripping form rebuilt from the parsed
170
- # FIELDS. That form cannot leak: the password is never copied into it.
171
- new(text).to_safe_string
172
- rescue StandardError
173
- # Unparseable - fall back to the structural scrub. Redaction must never
174
- # raise; a raise here would mask the error we were called to describe.
175
- scrub(text)
176
- end
195
+ # A head before "://" that is not a scheme is unknown text, and unknown
196
+ # text may BE the secret (the measured Python case was
197
+ # `notaurl-with-SuperSecret123://`). Say nothing about it rather than guess.
198
+ head, separator, = text.partition("://")
199
+ return REDACTED if !separator.empty? && !head.match?(SCHEME)
200
+
201
+ span = password_span(text)
202
+ text = "#{text[0, span.first]}#{REDACTED}#{text[span.last..]}" if span
203
+ scrub_keywords(text)
204
+ rescue StandardError
205
+ # Redaction must never raise - a raise here would mask the error we were
206
+ # called to describe - and must never fall back to the input.
207
+ REDACTED
208
+ end
209
+
210
+ # Where the password is in a raw connection string, as [start, stop)
211
+ # character offsets, or nil when there is none. THE rule, shared by every
212
+ # redaction and every parser in the framework:
213
+ #
214
+ # * The authority starts after "scheme://", "scheme:/" or "scheme//".
215
+ # * Userinfo ends at the LAST "@" on the value (RFC 3986); the password
216
+ # starts at the first ":" after the authority start. A "/" before that
217
+ # ":" means the text is a path, not a password.
218
+ # * With no "@", a non-numeric port is the password of a URL that lost its
219
+ # host (`postgres://u:secret`), masked to the end of the value - except a
220
+ # trailing "?key=value" query, which is kept.
221
+ #
222
+ # KNOWN LIMIT: a host-less URL whose password is all digits
223
+ # (`postgres://u:123/x`) cannot be told apart from host:port, so it stays
224
+ # unmasked. Likewise in `postgres://u:pw@word` the text after the last "@"
225
+ # IS the host, by the RFC, and is shown as one.
226
+ def self.password_span(raw)
227
+ text = raw.to_s
228
+ start = authority_start(text)
229
+ return nil if start.nil?
230
+
231
+ rest = text[start..]
232
+ span = rest.include?("@") ? userinfo_span(rest) : port_span(rest)
233
+ span && [start + span.first, start + span.last]
234
+ end
235
+
236
+ # Offset where the authority starts: after "scheme://", "scheme:/" or
237
+ # "scheme//"; when the value has an "@" but none of those, after a bare
238
+ # "scheme:" or at the very start. nil when there is nothing to look in.
239
+ def self.authority_start(text)
240
+ prefix = text[AUTHORITY_START]
241
+ return prefix.length if prefix
242
+ return nil unless text.include?("@")
243
+
244
+ text[OPAQUE_SCHEME].to_s.length
245
+ end
246
+ private_class_method :authority_start
247
+
248
+ # With an "@": the password runs from the first ":" to the LAST "@".
249
+ def self.userinfo_span(rest)
250
+ at = rest.rindex("@")
251
+ colon = rest.index(":")
252
+ return nil if colon.nil? || colon > at || path_before?(rest, colon)
253
+
254
+ [colon + 1, at]
255
+ end
256
+ private_class_method :userinfo_span
257
+
258
+ # No "@": only a non-numeric PORT can be a password (an IPv6 literal is
259
+ # skipped). Masked to the end, keeping a trailing "?key=value" query.
260
+ def self.port_span(rest)
261
+ host_end = rest.start_with?("[") ? (rest.index("]") || rest.length) : 0
262
+ colon = rest.index(":", host_end)
263
+ return nil if colon.nil? || path_before?(rest, colon)
264
+ return nil if rest[(colon + 1)..][%r{\A[^/?#\\]*}].match?(/\A\d*\z/)
265
+
266
+ [colon + 1, kept_query_start(rest, colon) || rest.length]
267
+ end
268
+ private_class_method :port_span
269
+
270
+ def self.kept_query_start(rest, colon)
271
+ query = rest.rindex("?")
272
+ return nil if query.nil? || query < colon
273
+
274
+ query if rest[(query + 1)..].match?(/\A[A-Za-z_][A-Za-z0-9_.\-]*=/)
177
275
  end
276
+ private_class_method :kept_query_start
277
+
278
+ def self.path_before?(rest, colon)
279
+ separator = rest.index(%r{[/\\]})
280
+ !separator.nil? && separator < colon
281
+ end
282
+ private_class_method :path_before?
178
283
 
179
284
  # The connection string with the whole `user:pass@` removed, for log lines
180
285
  # that only need to say WHICH database. Stricter than #redact (the user name
@@ -183,71 +288,177 @@ module Tina4
183
288
  redact(raw).gsub(%r{://[^/\s@]*@}, "://")
184
289
  end
185
290
 
186
- # Structural redaction of a string that did NOT parse.
291
+ # Kept for callers of the old name; it is #redact.
187
292
  def self.scrub(text)
188
- head, separator, rest = text.to_s.partition("://")
189
-
190
- # No "://" - a bare file path, an ODBC/keyword string, or a URL that lost
191
- # its ":" or a "/" (`postgres//u:pass@host/app`). An "@" means userinfo may
192
- # be in front of it, so take the credential out the same way as below.
193
- if separator.empty?
194
- text = text.to_s
195
- return scrub_keywords(text.include?("@") ? redact_authority(text) : text)
196
- end
293
+ redact(text)
294
+ end
197
295
 
198
- # A head that is not a scheme is unknown text, and unknown text may BE the
199
- # secret (the measured Python case was `notaurl-with-SuperSecret123`).
200
- # Say nothing about it rather than guess.
201
- return REDACTED unless head.match?(SCHEME)
296
+ # Redact the value side of a credential keyword, leaving every other
297
+ # keyword visible so the string is still diagnosable.
298
+ def self.scrub_keywords(text)
299
+ text.gsub(CREDENTIAL_KEYWORDS) { "#{Regexp.last_match(1)}=#{REDACTED}" }
300
+ end
202
301
 
203
- # The authority is taken to the first "?" or "#", NOT to the first "/".
204
- # An unencoded "/" inside a password would otherwise cut the region short,
205
- # push the "@" outside it, and let the password prefix survive.
206
- cut = rest.index(/[?#]/) || rest.length
207
- "#{head}://#{redact_authority(rest[0, cut])}#{scrub_keywords(rest[cut..].to_s)}"
302
+ # A third party's error message (a driver, a client gem) with the
303
+ # connection string taken out. The whole raw value is replaced by its
304
+ # redacted form, and so is the password itself and every piece of it: a
305
+ # driver that splits the value on its own terms (libpq splits a conninfo on
306
+ # whitespace, the mongo gem quotes "the database name" after a "/") quotes a
307
+ # PART of it, which a whole-string replace never finds. Pieces shorter than
308
+ # three characters are left alone - masking them would shred the message.
309
+ def self.scrub_message(message, raw, replacement = nil)
310
+ text = message.to_s
311
+ raw = raw.to_s
312
+ return text if raw.empty?
313
+
314
+ text = text.gsub(raw) { replacement || redact(raw) }
315
+ secrets = []
316
+ span = password_span(raw)
317
+ secrets << raw[span.first...span.last] if span
318
+ begin
319
+ secrets << new(raw).password
320
+ rescue StandardError
321
+ nil
322
+ end
323
+ mask_pieces(text, secrets.compact)
324
+ rescue StandardError
325
+ REDACTED
208
326
  end
209
327
 
210
- # Take the credential out of a URL authority.
211
- #
212
- # user:pass@host:5432/db -> user:***@host:5432/db
213
- # host:5432/db -> host:5432/db (no credential present)
214
- # user:pass -> user:*** (host left off - a real typo,
215
- # and the only reason the no-"@"
216
- # branch cannot echo blindly)
217
- def self.redact_authority(authority)
218
- # The LAST "@", because userinfo ends at the last "@" (RFC 3986). Splitting
219
- # on the FIRST one is how an unencoded "@" inside a password leaves a tail
220
- # in the output.
221
- at = authority.rindex("@")
222
- if at
223
- userinfo = authority[0, at]
224
- host = authority[(at + 1)..].to_s
225
- name, colon, = userinfo.partition(":")
226
- return colon.empty? ? "#{name}@#{host}" : "#{name}:#{REDACTED}@#{host}"
328
+ # Replace each secret, and each piece of it, with the marker. A piece is
329
+ # only masked where it is not part of a longer word: the driver quotes it
330
+ # cut at a delimiter, so it stands alone there - while "word" from a
331
+ # password "my word" must not turn "password authentication failed" into
332
+ # "pass*** authentication failed".
333
+ def self.mask_pieces(text, secrets)
334
+ pieces = secrets.flat_map { |s| [s, *s.split(%r{[\s/?#@:%]+})] }
335
+ pieces.select { |p| p.length >= 3 }.uniq.sort_by { |p| -p.length }.each do |piece|
336
+ text = text.gsub(standalone(piece), REDACTED)
227
337
  end
338
+ text
339
+ end
340
+ private_class_method :mask_pieces
341
+
342
+ # A pattern for +piece+ that does not match inside a longer alphanumeric
343
+ # run (a boundary is only required on a side where the piece itself ends
344
+ # in a letter or digit).
345
+ def self.standalone(piece)
346
+ left = piece.match?(/\A[[:alnum:]]/) ? "(?<![[:alnum:]])" : ""
347
+ right = piece.match?(/[[:alnum:]]\z/) ? "(?![[:alnum:]])" : ""
348
+ Regexp.new("#{left}#{Regexp.escape(piece)}#{right}")
349
+ end
350
+ private_class_method :standalone
351
+
352
+ # Split what follows "scheme://" into [userinfo, host_and_rest]. Userinfo
353
+ # ends at the LAST "@". REFUSES (generic message, nothing echoed, no cause)
354
+ # when that "@" cannot be ending a userinfo - a "/", "?", "#" or a bracket
355
+ # before the user name's end means it sits in the path or query - because
356
+ # then the parser and the redaction would disagree about where the password
357
+ # is. Shared by every URL parser in the framework.
358
+ def self.split_userinfo(rest, label = "DatabaseUrl")
359
+ at = rest.rindex("@")
360
+ return [nil, rest] if at.nil?
361
+
362
+ userinfo = rest[0, at]
363
+ name = userinfo.partition(":").first
364
+ raise ArgumentError.new("#{label}: #{AMBIGUOUS_URL}"), cause: nil if name.match?(%r{[/?#\[\]\\]})
365
+
366
+ [userinfo, rest[(at + 1)..]]
367
+ end
368
+
369
+ # URI.parse of the userinfo-free remainder, or nil. Never raises, so a
370
+ # caller's refusal cannot chain the InvalidURIError (which quotes it).
371
+ def self.parse_hostpart(scheme, hostpart)
372
+ URI.parse("#{scheme}://#{hostpart}")
373
+ rescue URI::InvalidURIError
374
+ nil
375
+ end
228
376
 
229
- return authority if authority.match?(HOST_PORT)
377
+ # [user, password] decoded from a userinfo, [nil, nil] without one. No
378
+ # ":" means no password (nil); "user:" is an explicitly EMPTY one ("").
379
+ def self.split_credentials(userinfo)
380
+ return [nil, nil] if userinfo.nil?
230
381
 
231
- name, colon, = authority.partition(":")
232
- colon.empty? ? name : "#{name}:#{REDACTED}"
382
+ user, colon, pass = userinfo.partition(":")
383
+ [decode_userinfo(user), colon.empty? ? nil : decode_userinfo(pass)]
233
384
  end
234
385
 
235
- # Redact the value side of a credential keyword, leaving every other
236
- # keyword visible so the string is still diagnosable.
237
- def self.scrub_keywords(text)
238
- text.gsub(CREDENTIAL_KEYWORDS) { "#{Regexp.last_match(1)}=#{REDACTED}" }
386
+ # Percent-decode one userinfo part. A "%" that does not start a valid %XX
387
+ # is a literal "%": URI.decode_www_form_component RAISES on it with the
388
+ # value in the message, which put the password in the exception.
389
+ def self.decode_userinfo(part)
390
+ URI.decode_www_form_component(part.gsub(/%(?![0-9A-Fa-f]{2})/, "%25"))
391
+ end
392
+
393
+ # Characters a userinfo part cannot carry literally. Encoding them is what
394
+ # lets a driver that re-parses the URL itself see the same password the
395
+ # framework did, instead of cutting it at the first "/" or "@". ":" is
396
+ # encoded too: the mongo gem refuses an unencoded ":" inside a password,
397
+ # and every driver decodes %3A back to ":".
398
+ USERINFO_UNSAFE = %r{[:/?#@\[\]\s"<>^`{|}\\]|%(?![0-9A-Fa-f]{2})}.freeze
399
+
400
+ # Percent-encode a DECODED user name or password for a URL's userinfo:
401
+ # every byte outside RFC 3986 "unreserved", "%" included, so the receiver
402
+ # decodes exactly the original. #driver_url leaves an existing %XX alone
403
+ # because its input is already a URL; this takes a raw credential.
404
+ def self.encode_credential(value)
405
+ value.to_s.gsub(/[^A-Za-z0-9\-._~]/) { |c| c.bytes.map { |b| format("%%%02X", b) }.join }
406
+ end
407
+
408
+ # The URL a DRIVER should be handed: identical to the input except that the
409
+ # userinfo's unsafe characters are percent-encoded. A value that does not
410
+ # parse, or needs nothing encoding, is returned unchanged.
411
+ def self.driver_url(raw)
412
+ text = raw.to_s
413
+ prefix = text[URL_PREFIX]
414
+ return text if prefix.nil? || text.start_with?("sqlite", "odbc:")
415
+
416
+ userinfo, hostpart = split_userinfo(text[prefix.length..])
417
+ return text if userinfo.nil?
418
+
419
+ user, colon, pass = userinfo.partition(":")
420
+ encode = ->(s) { s.gsub(USERINFO_UNSAFE) { |c| c.bytes.map { |b| format("%%%02X", b) }.join } }
421
+ "#{prefix}#{encode.call(user)}#{colon}#{encode.call(pass)}@#{hostpart}"
422
+ rescue StandardError
423
+ text
424
+ end
425
+
426
+ # Raise unless +url+ is a URL whose userinfo a URI.parse-based client (the
427
+ # redis gem, nats-pure) will read the way #password_span does: it has
428
+ # "scheme://", URI.parse accepts it, and every "@" is accounted for by the
429
+ # userinfo URI took. `redis://u:12?q@h` parses as host "u", port 12, query
430
+ # "q@h" - a client would dial "u" and quote the password tail - so it is
431
+ # refused. No "scheme://", or an "@" that cannot end the userinfo, gets the
432
+ # generic message; a URL URI.parse merely rejects (a space, a bad port) is
433
+ # named in its redacted form so it stays diagnosable. Never a cause.
434
+ def self.assert_client_url!(url, label)
435
+ text = url.to_s
436
+ prefix = text[URL_PREFIX]
437
+ raise ArgumentError.new("#{label}: #{AMBIGUOUS_URL}"), cause: nil if prefix.nil?
438
+
439
+ split_userinfo(text[prefix.length..], label)
440
+ parsed = begin
441
+ URI.parse(text)
442
+ rescue URI::InvalidURIError
443
+ nil
444
+ end
445
+ raise ArgumentError.new("#{label}: #{redact(text)}"), cause: nil if parsed.nil?
446
+ raise ArgumentError.new("#{label}: #{AMBIGUOUS_URL}"), cause: nil if text.count("@") != (parsed.userinfo ? 1 : 0)
447
+
448
+ parsed
239
449
  end
240
450
 
241
451
  # The invalid-URL message, with the credential taken OUT.
242
452
  #
243
453
  # It still has to be diagnosable, so it keeps the scheme, the host, the port
244
454
  # as written (the usual fault) and the database name - only the password
245
- # becomes ***. When the value has no "://" there is no structure to trust,
246
- # so the value is not shown at all and the message says why.
455
+ # becomes ***. When the value does not start with "scheme://" there is no
456
+ # structure to trust, so the value is not shown at all and the message says
457
+ # why.
247
458
  def self.invalid_url_error(url)
248
459
  text = url.to_s
249
- if text.include?("://")
250
- "DatabaseUrl: Invalid URL format '#{scrub(text)}' - expected " \
460
+ if text.match?(URL_PREFIX)
461
+ "DatabaseUrl: Invalid URL format '#{redact(text)}' - expected " \
251
462
  "scheme://user:password@host:port/database"
252
463
  else
253
464
  "DatabaseUrl: Invalid URL format - no '://', so there is no scheme to " \
@@ -330,7 +541,18 @@ module Tina4
330
541
  @engine = "sqlite"
331
542
  url = "sqlite:#{url[("sqlite3:".length)..]}" if url.start_with?("sqlite3:")
332
543
 
333
- @database = if ["sqlite::memory:", "sqlite:///:memory:"].include?(url)
544
+ # A sqlite URL names a FILE and carries no credentials. One that has a
545
+ # user:password part anyway (`sqlite://u:secret@host/db`) would otherwise
546
+ # become a filename - and a filename is printed in the connected line, in
547
+ # the "resolves outside the project" refusal and in the driver's own
548
+ # error. Refused, generically. The in-memory forms are not credentials.
549
+ if !SQLITE_MEMORY_FORMS.include?(url) && self.class.password_span(url)
550
+ raise ArgumentError.new("DatabaseUrl: a sqlite URL names a file and carries no " \
551
+ "user:password, but this one has one. The URL itself is not " \
552
+ "shown because it can contain a password."), cause: nil
553
+ end
554
+
555
+ @database = if SQLITE_MEMORY_FORMS.include?(url)
334
556
  ":memory:"
335
557
  elsif url.start_with?("sqlite:///")
336
558
  strip_one_slash(url[("sqlite://".length)..])
@@ -341,32 +563,30 @@ module Tina4
341
563
  end
342
564
  end
343
565
 
566
+ # GHSA-h2mr-m3v3-cq8c: no longer URI.parse on the whole value. URI.parse
567
+ # accepts `postgres:/u:pw@h` (password in the path) and `u:12?q@h` (host
568
+ # "u", port 12, password tail in the query), and its InvalidURIError quotes
569
+ # the raw URL - which used to be kept as this error's `cause`. Now:
570
+ # * "scheme://" is required; anything else is refused, generically;
571
+ # * userinfo is split off at the LAST "@" by the shared #split_userinfo,
572
+ # which refuses an "@" that cannot be ending a userinfo;
573
+ # * only the userinfo-free remainder goes through URI.parse, and every
574
+ # refusal is raised with `cause: nil`.
344
575
  def parse_standard(url)
345
- parsed = begin
346
- URI.parse(url)
347
- rescue URI::InvalidURIError
348
- # NEVER interpolate the raw URL here. Measured 2026-08-02: a malformed
349
- # TINA4_DATABASE_URL put the password verbatim into this ArgumentError,
350
- # and Database#detect_driver raises it during boot - so the credential
351
- # reached the boot log, the error overlay, a crash report and CI output.
352
- raise ArgumentError, self.class.invalid_url_error(url)
353
- end
354
-
355
- scheme = parsed.scheme.to_s.downcase
356
- raise ArgumentError, self.class.invalid_url_error(url) if scheme.empty?
576
+ match = url.match(URL_PREFIX)
577
+ raise ArgumentError.new(self.class.invalid_url_error(url)), cause: nil if match.nil?
357
578
 
358
- engine = ENGINE_ALIASES[scheme]
359
- if engine.nil?
360
- raise ArgumentError,
361
- "DatabaseUrl: Unsupported database scheme '#{scheme}'. " \
362
- "Supported: #{ENGINE_ALIASES.keys.join(', ')}"
363
- end
579
+ scheme = match[1].downcase
580
+ @engine = engine_for!(scheme)
581
+ userinfo, hostpart = self.class.split_userinfo(url[match[0].length..])
582
+ parsed = self.class.parse_hostpart(scheme, hostpart)
583
+ # Raised OUTSIDE any rescue, and with cause: nil, so the InvalidURIError
584
+ # (whose message holds the value) is never chained onto this one.
585
+ raise ArgumentError.new(self.class.invalid_url_error(url)), cause: nil if parsed.nil?
364
586
 
365
- @engine = engine
366
- @host = parsed.host && !parsed.host.empty? ? parsed.host : nil
367
- @port = parsed.port || DEFAULT_PORTS[engine]
368
- @username = parsed.user ? URI.decode_www_form_component(parsed.user) : nil
369
- @password = parsed.password ? URI.decode_www_form_component(parsed.password) : nil
587
+ @host = parsed.host.to_s.empty? ? nil : parsed.host
588
+ @port = parsed.port || DEFAULT_PORTS[@engine]
589
+ @username, @password = self.class.split_credentials(userinfo)
370
590
 
371
591
  # Strip EXACTLY ONE leading slash - the URL path separator. Stripping every
372
592
  # slash turns the documented absolute Firebird form
@@ -374,7 +594,16 @@ module Tina4
374
594
  # `var/lib/db.fdb`. Verified against live Firebird 5.0.4: the driver takes
375
595
  # one or two leading slashes and rejects a relative path outright.
376
596
  database = strip_one_slash(parsed.path.to_s)
377
- @database = database.empty? && engine == "mongodb" ? "tina4" : database
597
+ @database = database.empty? && @engine == "mongodb" ? "tina4" : database
598
+ end
599
+
600
+ # The canonical engine for a scheme, or a refusal naming the scheme only.
601
+ def engine_for!(scheme)
602
+ engine = ENGINE_ALIASES[scheme]
603
+ return engine if engine
604
+
605
+ raise ArgumentError.new("DatabaseUrl: Unsupported database scheme '#{scheme}'. " \
606
+ "Supported: #{ENGINE_ALIASES.keys.join(', ')}"), cause: nil
378
607
  end
379
608
  end
380
609
  end
@@ -1147,25 +1147,19 @@ module Tina4
1147
1147
 
1148
1148
  # POST /__dev/api/seed/run — run every seed file in seeds/ for real
1149
1149
  # (each file `load`ed in the project context, exactly like `tina4ruby
1150
- # seed`). Counts files that ran vs. files that raised.
1150
+ # seed`). Stops at the first file that raises and names it (ADR-0108).
1151
1151
  def run_seeds_payload
1152
1152
  seed_folder = File.join(Dir.pwd, "seeds")
1153
1153
  return { seeded: 0, failed: 0, error: "No seeds folder" } unless Dir.exist?(seed_folder)
1154
1154
 
1155
- files = Dir.glob(File.join(seed_folder, "*.rb")).sort
1156
- .reject { |f| File.basename(f).start_with?("_") }
1157
- seeded = 0
1158
- failed = 0
1159
- files.each do |filepath|
1160
- begin
1161
- load filepath
1162
- seeded += 1
1163
- rescue StandardError => e
1164
- failed += 1
1165
- Tina4::Log.error("Seed failed: #{File.basename(filepath)} - #{e.message}") if defined?(Tina4::Log)
1166
- end
1167
- end
1168
- { seeded: seeded, failed: failed }
1155
+ # ADR-0108: the same runner as `tina4ruby seed`; the first failing file
1156
+ # stops the run and is reported by name. seeder.rb is autoloaded only
1157
+ # through Tina4::FakeData, so load it before calling Tina4.seed_dir.
1158
+ require_relative "seeder"
1159
+ executed = Tina4.seed_dir(seed_folder: seed_folder)
1160
+ { seeded: executed.length, failed: 0 }
1161
+ rescue Tina4::SeedError => e
1162
+ { seeded: e.completed.length, failed: 1, error: "#{File.basename(e.seed_file)}: #{e.cause&.message}" }
1169
1163
  rescue => e
1170
1164
  { seeded: 0, failed: 0, error: e.message }
1171
1165
  end
@@ -1927,7 +1921,7 @@ module Tina4
1927
1921
  def read_project_bytes(target)
1928
1922
  flags = File::RDONLY
1929
1923
  flags |= File::NOFOLLOW if defined?(File::NOFOLLOW)
1930
- flags |= File::NONBLOCK if defined?(File::NONBLOCK)
1924
+ flags |= Tina4::SecretFile::OPEN_NONBLOCK
1931
1925
  File.open(target, flags) do |file|
1932
1926
  file.binmode
1933
1927
  info = file.stat
@@ -23,6 +23,20 @@ module Tina4
23
23
  include SchemaSplit
24
24
  attr_reader :connection
25
25
 
26
+ # The URL handed to libpq, with the separately-passed credentials in its
27
+ # userinfo. They are percent-encoded: URI#password= REFUSES "/", "@", "%"
28
+ # and a space (URI::InvalidComponentError), so such a password could never
29
+ # connect - even spelled percent-encoded in the URL, because Tina4 decodes
30
+ # it and passes the decoded value here. libpq decodes the userinfo.
31
+ def self.connection_url(connection_string, username, password)
32
+ return connection_string unless username || password
33
+
34
+ uri = URI.parse(connection_string)
35
+ uri.user = Tina4::DatabaseUrl.encode_credential(username) if username
36
+ uri.password = Tina4::DatabaseUrl.encode_credential(password) if password
37
+ uri.to_s
38
+ end
39
+
26
40
  def connect(connection_string, username: nil, password: nil)
27
41
  @connect_args = [connection_string, username, password]
28
42
  begin
@@ -33,13 +47,7 @@ module Tina4
33
47
  " bundle add pg # if your project uses Bundler\n" \
34
48
  " gem install pg # bare driver"
35
49
  end
36
- url = connection_string
37
- if username || password
38
- uri = URI.parse(url)
39
- uri.user = username if username
40
- uri.password = password if password
41
- url = uri.to_s
42
- end
50
+ url = self.class.connection_url(connection_string, username, password)
43
51
  # libpq's OWN connect_timeout, in whole seconds. MEASURED: it bounds the
44
52
  # entire connect INCLUDING the startup handshake - 3.01s against a
45
53
  # TCPServer that accepts and never replies, where the same connect with
data/lib/tina4/graph.rb CHANGED
@@ -82,34 +82,51 @@ module Tina4
82
82
  attr_reader :raw, :scheme, :engine, :host, :port, :graph, :username,
83
83
  :password, :params, :use_tls
84
84
 
85
+ INVALID = "GraphUrl: Invalid URL format — expected scheme://[user[:password]@]host:port/graph. " \
86
+ "The URL itself is not shown because it can contain a password."
87
+
88
+ # GHSA-h2mr-m3v3-cq8c: the same rule as DatabaseUrl, through the same
89
+ # shared helpers. URI.parse on the whole value accepted `bolt:/u:pw@h`
90
+ # (password in the path, so in the graph name) and `bolt://u:12?q@h`, and
91
+ # the InvalidURIError it raised - message holding the raw URL - was kept as
92
+ # this error's `cause`. Now "scheme://" is required, userinfo is split at
93
+ # the LAST "@", only the userinfo-free rest goes through URI.parse, and
94
+ # every refusal is raised with `cause: nil`.
85
95
  def initialize(url)
86
96
  @raw = url
87
- parsed = begin
88
- URI.parse(url.to_s)
89
- rescue URI::InvalidURIError
90
- raise ArgumentError, "GraphUrl: Invalid URL format — expected scheme://host:port/graph"
91
- end
92
-
93
- scheme = (parsed.scheme || "").downcase
94
- engine = SCHEME_ENGINE[scheme]
95
- if engine.nil?
96
- raise ArgumentError,
97
- "GraphUrl: Unsupported graph URL scheme '#{scheme}'. Supported: " \
98
- "#{SCHEME_ENGINE.keys.sort.join(', ')} (e.g. ultipa://host:60061/mygraph)."
99
- end
100
-
101
- @scheme = scheme
102
- @engine = engine
103
- @host = parsed.host && !parsed.host.empty? ? parsed.host : "localhost"
104
- @port = parsed.port || ENGINE_DEFAULT_PORT[engine]
97
+ text = url.to_s
98
+ match = text.match(Tina4::DatabaseUrl::URL_PREFIX)
99
+ raise ArgumentError.new(INVALID), cause: nil if match.nil?
100
+
101
+ @scheme = match[1].downcase
102
+ @engine = engine_for!(@scheme)
103
+ userinfo, hostpart = Tina4::DatabaseUrl.split_userinfo(text[match[0].length..], "GraphUrl")
104
+ parsed = Tina4::DatabaseUrl.parse_hostpart(@scheme, hostpart)
105
+ raise ArgumentError.new(INVALID), cause: nil if parsed.nil?
106
+
107
+ @host = parsed.host.to_s.empty? ? "localhost" : parsed.host
108
+ @port = parsed.port || ENGINE_DEFAULT_PORT[@engine]
105
109
  # The path is the graph/database name (one leading slash stripped).
106
- graph = (parsed.path || "").sub(%r{\A/}, "")
110
+ graph = parsed.path.to_s.sub(%r{\A/}, "")
107
111
  @graph = graph.empty? ? nil : graph
108
- @username = parsed.user ? URI.decode_www_form_component(parsed.user) : nil
109
- @password = parsed.password ? URI.decode_www_form_component(parsed.password) : nil
112
+ @username, @password = Tina4::DatabaseUrl.split_credentials(userinfo)
110
113
  @params = URI.decode_www_form(parsed.query || "").to_h
111
114
  # TLS if the scheme says so (…s) or ?tls=1.
112
- @use_tls = scheme.end_with?("s") || %w[1 true].include?(@params["tls"])
115
+ @use_tls = @scheme.end_with?("s") || %w[1 true].include?(@params["tls"])
116
+ end
117
+
118
+ # The URL with the password masked - the only form for a log line.
119
+ def to_safe_string
120
+ Tina4::DatabaseUrl.redact(@raw)
121
+ end
122
+
123
+ # inspect lands in consoles and backtraces; the default dumps @password.
124
+ def inspect
125
+ "#<Tina4::GraphUrl #{to_safe_string}>"
126
+ end
127
+
128
+ def to_s
129
+ to_safe_string
113
130
  end
114
131
 
115
132
  # host:port/graph — for messages, never carrying credentials.
@@ -123,6 +140,18 @@ module Tina4
123
140
  url = (ENV[env_key] || "").strip
124
141
  url.empty? ? nil : new(url)
125
142
  end
143
+
144
+ private
145
+
146
+ # The canonical engine for a scheme, or a refusal naming the scheme only.
147
+ def engine_for!(scheme)
148
+ engine = SCHEME_ENGINE[scheme]
149
+ return engine if engine
150
+
151
+ raise ArgumentError.new("GraphUrl: Unsupported graph URL scheme '#{scheme}'. Supported: " \
152
+ "#{SCHEME_ENGINE.keys.sort.join(', ')} (e.g. ultipa://host:60061/mygraph)."),
153
+ cause: nil
154
+ end
126
155
  end
127
156
 
128
157
  # An engine-neutral vertex: id, labels, properties.