Module: Mutineer::OutputFilter

Defined in:
lib/mutineer/output_filter.rb

Overview

Copies the process's stdout and stderr through Redaction.text. A fork child and a subprocess inherit the pipe. The child starts its own copier so a DATABASE_URL it sets is hidden (#341). Before a fork child execs, its copier stops, so the program writes to the parent's pipe and the parent redacts it with the parent's environment. A program that would run with a DATABASE_URL the parent does not know writes to the null device. A --test-command Ruby process restores the captured descriptors before exec, and the next Ruby loads its own copier (#457).

Stdlib only, so the app-side daemon can load this file. A chunk with no password is copied unchanged, including its bytes.

Defined Under Namespace

Modules: ExecHook, ExitHook, ForkHook, SpawnHook, SystemHook

Constant Summary collapse

QUIET_POLL =

Seconds to wait for a last buffered chunk after uninstall closes this process's write end. A grandchild that still holds the pipe does not extend the wait. Bytes already read are written before the copier returns; a slow reader blocks that write, and the bytes are not dropped.

0.05

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.after_fork! ⇒ void

This method returns an undefined value.

Start a copier in a fork child. The parent's thread was not copied. This process redacts with its own environment, then writes to the parent's pipe. The parent's read ends are closed so this process does not steal the parent's bytes.



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/mutineer/output_filter.rb', line 180

def after_fork!
  return unless installed?

  names = @streams
  reads = (@readers || {}).keys.dup
  @fork_child = true
  # The parent's copier redacts with this URL, read before child code runs.
  @parent_url = ENV["DATABASE_URL"].to_s
  @installed = false
  @thread = nil
  @stopping = false
  @hooked = false
  @readers = {}
  @saved = {}
  @stdio = {}
  reads.each { |io| io.close unless io.closed? }
  silence_stdio unless install(streams: names || [:stderr]) == :started
rescue StandardError
  silence_stdio
end

.before_exec(args = []) ⇒ void

This method returns an undefined value.

In a fork child, put the parent's pipe back on stdout and stderr and flush this copier. When the program would run with a DATABASE_URL the parent does not know, its output goes to the null device instead: the parent could not hide that password. A --test-command Ruby process also puts the captured descriptors back, so the program that replaces it does not write to a pipe whose reader died. The next Ruby loads its own copier from RUBYOPT (#457). The same null-device rule holds there when the program would run with a URL the tool did not know at start: a program that is not Ruby has no copier.

Parameters:

  • args (Array) (defaults to: []) —

    the arguments given to exec; a leading Hash is its environment.



214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/mutineer/output_filter.rb', line 214

def before_exec(args = [])
  if @fork_child
    known = known_url?(args, @parent_url)
    uninstall
    silence_stdio unless known
    return
  end
  return unless installed? && command_ruby?

  # The next Ruby loads its own copier. A program that is not Ruby does not,
  # so drop its output when it would run with a URL nobody here knows.
  known = known_url?(args, @install_url)
  uninstall
  silence_stdio unless known
end

.command_ruby? ⇒ Boolean

True when this process was started as a --test-command Ruby, which loads the copier from RUBYOPT.

Returns:

  • (Boolean)


234
235
236
# File 'lib/mutineer/output_filter.rb', line 234

def command_ruby?
  ENV["RUBYOPT"].to_s.include?("command_redact.rb")
end

.drain ⇒ void

This method returns an undefined value.

Read both pipes until they close, or until uninstall has closed this process's write ends and the pipes are empty. A password that contains a newline stays in the buffer until the whole form has arrived.



332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
# File 'lib/mutineer/output_filter.rb', line 332

def drain
  pending = Hash.new { |buffer, io| buffer[io] = +"".b }
  open = (@readers || {}).keys
  until open.empty?
    if @stopping
      drain_ready(open, pending)
      break
    end
    ready, = IO.select(open, nil, nil, QUIET_POLL)
    next unless ready

    ready.each do |io|
      chunk = io.read_nonblock(4096, exception: false)
      if chunk.nil?
        flush_pending(io, pending, flush: true)
        open.delete(io)
        io.close unless io.closed?
        next
      end
      next if chunk == :wait_readable

      pending[io] << chunk.b
      # Nothing new can be emitted before a newline, so a long line is not
      # rescanned on every read.
      flush_pending(io, pending, flush: false) if chunk.include?("\n")
    end
  end
  open.each { |io| flush_pending(io, pending, flush: true) }
rescue StandardError
  nil
end

.drain_ready(open, pending) ⇒ void

This method returns an undefined value.

Read what is already buffered, plus one quiet poll, then stop. Used after uninstall closes this process's write ends.

Parameters:

  • open (Array<IO>)
  • pending (Hash{IO => String})


370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/mutineer/output_filter.rb', line 370

def drain_ready(open, pending)
  open.each do |io|
    loop do
      chunk = io.read_nonblock(4096, exception: false)
      if chunk == :wait_readable
        break unless io.wait_readable(QUIET_POLL)

        next
      end
      break if chunk.nil?

      pending[io] << chunk.b
    end
    flush_pending(io, pending, flush: true)
  end
end

.emit(stream, chunk) ⇒ void

This method returns an undefined value.

Write chunk to the original stream, redacted. The original bytes are kept when redaction changes nothing, so a report with no password stays byte for byte. An error writes Redaction::FAILED, never the raw chunk.

Parameters:

  • stream (Symbol, nil)
  • chunk (String) —

    raw bytes. May contain newlines.



405
406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/mutineer/output_filter.rb', line 405

def emit(stream, chunk)
  return if stream.nil? || chunk.nil? || chunk.empty?

  text = chunk.dup.force_encoding(Encoding::UTF_8)
  clean = text.dup
  clean.scrub! unless clean.valid_encoding?
  redacted = Redaction.text(clean)
  # Unchanged text keeps the original bytes, including invalid ones.
  # A replaced secret is the redacted UTF-8 string.
  payload = redacted == clean ? chunk : redacted.b
  write_out(stream, payload)
rescue StandardError
  write_out(stream, Redaction::FAILED.b)
end

.flush_pending(io, pending, flush:) ⇒ void

This method returns an undefined value.

Redact and write the part of pending[io] that is safe to emit.

Parameters:

  • io (IO)
  • pending (Hash{IO => String})
  • flush (Boolean)


393
394
395
396
# File 'lib/mutineer/output_filter.rb', line 393

def flush_pending(io, pending, flush:)
  ready, pending[io] = Redaction.take_redactable(pending[io], flush: flush)
  emit(@readers[io], ready)
end

.hook_exit ⇒ void

This method returns an undefined value.

Register the process-exit flush once. exit! skips at_exit; ExitHook covers that.



296
297
298
299
300
301
# File 'lib/mutineer/output_filter.rb', line 296

def hook_exit
  return if @hooked

  @hooked = true
  at_exit { uninstall }
end

.hook_exit! ⇒ void

This method returns an undefined value.



320
321
322
323
324
325
# File 'lib/mutineer/output_filter.rb', line 320

def hook_exit!
  return if @exit_hooked

  @exit_hooked = true
  Kernel.prepend(ExitHook)
end

.hook_fork ⇒ void

This method returns an undefined value.

Wrap fork, exec, spawn, and system once per process.



306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/mutineer/output_filter.rb', line 306

def hook_fork
  return if @fork_hooked

  @fork_hooked = true
  [Kernel, Kernel.singleton_class, Process.singleton_class].each do |target|
    target.prepend(ForkHook)
    target.prepend(ExecHook)
    target.prepend(SpawnHook)
  end
  Kernel.prepend(SystemHook)
  Kernel.singleton_class.prepend(SystemHook)
end

.install(streams: %i[stdout stderr])) ⇒ Symbol

Point each named stream at a pipe and start the copier. A second call does nothing and returns false, so the caller that turned it on is the one that turns it off. streams is :stdout, :stderr, or both. Returns :failed without leaving the descriptors redirected when they cannot be moved (a closed stream). Returns :already when a copier is already running, so the caller that started it stays the one that stops it.

Parameters:

  • streams (Array<Symbol>) (defaults to: %i[stdout stderr]))

Returns:

  • (Symbol) —

    :started, :already, or :failed.



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/mutineer/output_filter.rb', line 104

def install(streams: %i[stdout stderr])
  return :already if installed?

  names = Array(streams)
  saved = {}
  stdio = {}
  readers = {}
  names.each do |name|
    io = stream_io(name)
    copy = io.dup
    copy.sync = true
    read, write = IO.pipe
    write.sync = true
    read.binmode
    read.close_on_exec = true
    io.reopen(write)
    io.sync = true
    write.close
    saved[name] = copy
    stdio[name] = io
    readers[read] = name
  end
  @streams = names
  @saved = saved
  @stdio = stdio
  @readers = readers
  @stopping = false
  @installed = true
  # What the process that reads this pipe knows, for {before_exec}.
  @install_url = ENV["DATABASE_URL"].to_s
  hook_fork
  hook_exit!
  @thread = Thread.new { drain } # rubocop:disable ThreadSafety/NewThread
  @thread.report_on_exception = false
  hook_exit
  :started
rescue StandardError
  restore(stdio || {}, saved || {})
  readers&.each_key { |io| io.close unless io.closed? }
  :failed
end

.installed? ⇒ Boolean

True while the descriptors point at the pipe.

Returns:

  • (Boolean)


90
91
92
# File 'lib/mutineer/output_filter.rb', line 90

def installed?
  @installed == true
end

.known_url?(args, current) ⇒ Boolean

True when the program args start would run with no DATABASE_URL, with current, or with a dotenv URL redaction already knows. The env hash wins; ENV counts only when unsetenv_others does not clear it.

Parameters:

  • args (Array) —

    exec, spawn, or system arguments.

  • current (String, nil) —

    the URL the redacting copier knows.

Returns:

  • (Boolean)


262
263
264
265
266
267
268
# File 'lib/mutineer/output_filter.rb', line 262

def known_url?(args, current)
  env = args.first.is_a?(Hash) ? args.first : {}
  options = args.size > 1 && args.last.is_a?(Hash) ? args.last : {}
  inherited = options[:unsetenv_others] ? nil : ENV.fetch("DATABASE_URL", nil)
  url = (env.key?("DATABASE_URL") ? env["DATABASE_URL"] : inherited).to_s
  url.empty? || url == current.to_s || Redaction.extra_urls.include?(url)
end

.restore(stdio, saved) ⇒ void

This method returns an undefined value.

Put any streams this failed install already moved back where they were.

Parameters:

  • stdio (Hash{Symbol => IO})
  • saved (Hash{Symbol => IO})


441
442
443
444
445
446
447
448
449
# File 'lib/mutineer/output_filter.rb', line 441

def restore(stdio, saved)
  stdio.each do |name, io|
    copy = saved[name]
    io.reopen(copy) if copy && !copy.closed? && !io.closed?
  end
  saved.each_value { |io| io.close unless io.closed? }
rescue StandardError
  nil
end

.silence_stdio ⇒ void

This method returns an undefined value.

Point stdout and stderr at the null device. Used when this fork cannot start its own copier: the parent's pipe would otherwise publish a password this process set and the parent does not know.



275
276
277
278
279
280
281
282
# File 'lib/mutineer/output_filter.rb', line 275

def silence_stdio
  File.open(File::NULL, "w") do |null|
    STDOUT.reopen(null) unless STDOUT.closed?
    STDERR.reopen(null) unless STDERR.closed?
  end
rescue StandardError
  nil
end

.spawn_args(args) ⇒ Array

args for spawn or system, with stdout and stderr sent to the null device when the program's env hash sets a DATABASE_URL this process does not know. The caller's own redirects of stdout and stderr are dropped too: a target such as err: :out or err: STDOUT would still reach this pipe, and Ruby refuses a stream given twice.

Parameters:

  • args (Array) —

    the arguments given to spawn or system.

Returns:

  • (Array)


246
247
248
249
250
251
252
253
# File 'lib/mutineer/output_filter.rb', line 246

def spawn_args(args)
  return args if !installed? || known_url?(args, ENV.fetch("DATABASE_URL", nil))

  options = args.size > 1 && args.last.is_a?(Hash) ? args.last : {}
  kept = options.reject { |key, _| Array(key).intersect?([:out, :err, 1, 2, STDOUT, STDERR]) }
  command = options.empty? ? args : args[0...-1]
  command + [kept.merge(out: File::NULL, err: File::NULL)]
end

.stream_io(name) ⇒ IO

The real stream for name.

Parameters:

  • name (Symbol) —

    :stdout or :stderr.

Returns:

  • (IO)


288
289
290
# File 'lib/mutineer/output_filter.rb', line 288

def stream_io(name)
  name == :stdout ? STDOUT : STDERR
end

.uninstall ⇒ void

This method returns an undefined value.

Put the descriptors back and write every byte already queued. Does nothing when install is not on. Safe to call twice. Does not kill the copier: a slow stdout must still receive the report. A grandchild that holds the pipe does not add a wait past QUIET_POLL, because the copier stops reading once the pipe is empty.



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/mutineer/output_filter.rb', line 153

def uninstall
  return unless installed?

  @stopping = true
  saved = @saved || {}
  stdio = @stdio || {}
  stdio.each do |name, io|
    copy = saved[name]
    io.reopen(copy) if copy && !copy.closed? && !io.closed?
  end
  @thread&.join
  saved.each_value { |io| io.close unless io.closed? }
  (@readers || {}).each_key { |io| io.close unless io.closed? }
  @installed = false
  @thread = nil
  @stopping = false
  @saved = {}
  @stdio = {}
  @readers = {}
end

.write_out(stream, data) ⇒ void

This method returns an undefined value.

Write to $stdout or $stderr when the caller replaced that variable (a test capture). Otherwise write to the descriptor saved before install, never back into the pipe.

Parameters:

  • stream (Symbol)
  • data (String)


427
428
429
430
431
432
433
434
# File 'lib/mutineer/output_filter.rb', line 427

def write_out(stream, data)
  current = stream == :stdout ? $stdout : $stderr
  pipe = @stdio[stream]
  target = current.equal?(pipe) ? @saved[stream] : current
  target&.write(data)
rescue Errno::EPIPE, IOError
  nil
end

Instance Method Details

#after_fork! ⇒ void (private)

This method returns an undefined value.

Start a copier in a fork child. The parent's thread was not copied. This process redacts with its own environment, then writes to the parent's pipe. The parent's read ends are closed so this process does not steal the parent's bytes.



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/mutineer/output_filter.rb', line 180

def after_fork!
  return unless installed?

  names = @streams
  reads = (@readers || {}).keys.dup
  @fork_child = true
  # The parent's copier redacts with this URL, read before child code runs.
  @parent_url = ENV["DATABASE_URL"].to_s
  @installed = false
  @thread = nil
  @stopping = false
  @hooked = false
  @readers = {}
  @saved = {}
  @stdio = {}
  reads.each { |io| io.close unless io.closed? }
  silence_stdio unless install(streams: names || [:stderr]) == :started
rescue StandardError
  silence_stdio
end

#before_exec(args = []) ⇒ void (private)

This method returns an undefined value.

In a fork child, put the parent's pipe back on stdout and stderr and flush this copier. When the program would run with a DATABASE_URL the parent does not know, its output goes to the null device instead: the parent could not hide that password. A --test-command Ruby process also puts the captured descriptors back, so the program that replaces it does not write to a pipe whose reader died. The next Ruby loads its own copier from RUBYOPT (#457). The same null-device rule holds there when the program would run with a URL the tool did not know at start: a program that is not Ruby has no copier.

Parameters:

  • args (Array) (defaults to: []) —

    the arguments given to exec; a leading Hash is its environment.



214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/mutineer/output_filter.rb', line 214

def before_exec(args = [])
  if @fork_child
    known = known_url?(args, @parent_url)
    uninstall
    silence_stdio unless known
    return
  end
  return unless installed? && command_ruby?

  # The next Ruby loads its own copier. A program that is not Ruby does not,
  # so drop its output when it would run with a URL nobody here knows.
  known = known_url?(args, @install_url)
  uninstall
  silence_stdio unless known
end

#command_ruby? ⇒ Boolean (private)

True when this process was started as a --test-command Ruby, which loads the copier from RUBYOPT.

Returns:

  • (Boolean)


234
235
236
# File 'lib/mutineer/output_filter.rb', line 234

def command_ruby?
  ENV["RUBYOPT"].to_s.include?("command_redact.rb")
end

#drain ⇒ void (private)

This method returns an undefined value.

Read both pipes until they close, or until uninstall has closed this process's write ends and the pipes are empty. A password that contains a newline stays in the buffer until the whole form has arrived.



332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
# File 'lib/mutineer/output_filter.rb', line 332

def drain
  pending = Hash.new { |buffer, io| buffer[io] = +"".b }
  open = (@readers || {}).keys
  until open.empty?
    if @stopping
      drain_ready(open, pending)
      break
    end
    ready, = IO.select(open, nil, nil, QUIET_POLL)
    next unless ready

    ready.each do |io|
      chunk = io.read_nonblock(4096, exception: false)
      if chunk.nil?
        flush_pending(io, pending, flush: true)
        open.delete(io)
        io.close unless io.closed?
        next
      end
      next if chunk == :wait_readable

      pending[io] << chunk.b
      # Nothing new can be emitted before a newline, so a long line is not
      # rescanned on every read.
      flush_pending(io, pending, flush: false) if chunk.include?("\n")
    end
  end
  open.each { |io| flush_pending(io, pending, flush: true) }
rescue StandardError
  nil
end

#drain_ready(open, pending) ⇒ void (private)

This method returns an undefined value.

Read what is already buffered, plus one quiet poll, then stop. Used after uninstall closes this process's write ends.

Parameters:

  • open (Array<IO>)
  • pending (Hash{IO => String})


370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/mutineer/output_filter.rb', line 370

def drain_ready(open, pending)
  open.each do |io|
    loop do
      chunk = io.read_nonblock(4096, exception: false)
      if chunk == :wait_readable
        break unless io.wait_readable(QUIET_POLL)

        next
      end
      break if chunk.nil?

      pending[io] << chunk.b
    end
    flush_pending(io, pending, flush: true)
  end
end

#emit(stream, chunk) ⇒ void (private)

This method returns an undefined value.

Write chunk to the original stream, redacted. The original bytes are kept when redaction changes nothing, so a report with no password stays byte for byte. An error writes Redaction::FAILED, never the raw chunk.

Parameters:

  • stream (Symbol, nil)
  • chunk (String) —

    raw bytes. May contain newlines.



405
406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/mutineer/output_filter.rb', line 405

def emit(stream, chunk)
  return if stream.nil? || chunk.nil? || chunk.empty?

  text = chunk.dup.force_encoding(Encoding::UTF_8)
  clean = text.dup
  clean.scrub! unless clean.valid_encoding?
  redacted = Redaction.text(clean)
  # Unchanged text keeps the original bytes, including invalid ones.
  # A replaced secret is the redacted UTF-8 string.
  payload = redacted == clean ? chunk : redacted.b
  write_out(stream, payload)
rescue StandardError
  write_out(stream, Redaction::FAILED.b)
end

#flush_pending(io, pending, flush:) ⇒ void (private)

This method returns an undefined value.

Redact and write the part of pending[io] that is safe to emit.

Parameters:

  • io (IO)
  • pending (Hash{IO => String})
  • flush (Boolean)


393
394
395
396
# File 'lib/mutineer/output_filter.rb', line 393

def flush_pending(io, pending, flush:)
  ready, pending[io] = Redaction.take_redactable(pending[io], flush: flush)
  emit(@readers[io], ready)
end

#hook_exit ⇒ void (private)

This method returns an undefined value.

Register the process-exit flush once. exit! skips at_exit; ExitHook covers that.



296
297
298
299
300
301
# File 'lib/mutineer/output_filter.rb', line 296

def hook_exit
  return if @hooked

  @hooked = true
  at_exit { uninstall }
end

#hook_exit! ⇒ void (private)

This method returns an undefined value.



320
321
322
323
324
325
# File 'lib/mutineer/output_filter.rb', line 320

def hook_exit!
  return if @exit_hooked

  @exit_hooked = true
  Kernel.prepend(ExitHook)
end

#hook_fork ⇒ void (private)

This method returns an undefined value.

Wrap fork, exec, spawn, and system once per process.



306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/mutineer/output_filter.rb', line 306

def hook_fork
  return if @fork_hooked

  @fork_hooked = true
  [Kernel, Kernel.singleton_class, Process.singleton_class].each do |target|
    target.prepend(ForkHook)
    target.prepend(ExecHook)
    target.prepend(SpawnHook)
  end
  Kernel.prepend(SystemHook)
  Kernel.singleton_class.prepend(SystemHook)
end

#install(streams: %i[stdout stderr])) ⇒ Symbol (private)

Point each named stream at a pipe and start the copier. A second call does nothing and returns false, so the caller that turned it on is the one that turns it off. streams is :stdout, :stderr, or both. Returns :failed without leaving the descriptors redirected when they cannot be moved (a closed stream). Returns :already when a copier is already running, so the caller that started it stays the one that stops it.

Parameters:

  • streams (Array<Symbol>) (defaults to: %i[stdout stderr]))

Returns:

  • (Symbol) —

    :started, :already, or :failed.



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/mutineer/output_filter.rb', line 104

def install(streams: %i[stdout stderr])
  return :already if installed?

  names = Array(streams)
  saved = {}
  stdio = {}
  readers = {}
  names.each do |name|
    io = stream_io(name)
    copy = io.dup
    copy.sync = true
    read, write = IO.pipe
    write.sync = true
    read.binmode
    read.close_on_exec = true
    io.reopen(write)
    io.sync = true
    write.close
    saved[name] = copy
    stdio[name] = io
    readers[read] = name
  end
  @streams = names
  @saved = saved
  @stdio = stdio
  @readers = readers
  @stopping = false
  @installed = true
  # What the process that reads this pipe knows, for {before_exec}.
  @install_url = ENV["DATABASE_URL"].to_s
  hook_fork
  hook_exit!
  @thread = Thread.new { drain } # rubocop:disable ThreadSafety/NewThread
  @thread.report_on_exception = false
  hook_exit
  :started
rescue StandardError
  restore(stdio || {}, saved || {})
  readers&.each_key { |io| io.close unless io.closed? }
  :failed
end

#installed? ⇒ Boolean (private)

True while the descriptors point at the pipe.

Returns:

  • (Boolean)


90
91
92
# File 'lib/mutineer/output_filter.rb', line 90

def installed?
  @installed == true
end

#known_url?(args, current) ⇒ Boolean (private)

True when the program args start would run with no DATABASE_URL, with current, or with a dotenv URL redaction already knows. The env hash wins; ENV counts only when unsetenv_others does not clear it.

Parameters:

  • args (Array) —

    exec, spawn, or system arguments.

  • current (String, nil) —

    the URL the redacting copier knows.

Returns:

  • (Boolean)


262
263
264
265
266
267
268
# File 'lib/mutineer/output_filter.rb', line 262

def known_url?(args, current)
  env = args.first.is_a?(Hash) ? args.first : {}
  options = args.size > 1 && args.last.is_a?(Hash) ? args.last : {}
  inherited = options[:unsetenv_others] ? nil : ENV.fetch("DATABASE_URL", nil)
  url = (env.key?("DATABASE_URL") ? env["DATABASE_URL"] : inherited).to_s
  url.empty? || url == current.to_s || Redaction.extra_urls.include?(url)
end

#restore(stdio, saved) ⇒ void (private)

This method returns an undefined value.

Put any streams this failed install already moved back where they were.

Parameters:

  • stdio (Hash{Symbol => IO})
  • saved (Hash{Symbol => IO})


441
442
443
444
445
446
447
448
449
# File 'lib/mutineer/output_filter.rb', line 441

def restore(stdio, saved)
  stdio.each do |name, io|
    copy = saved[name]
    io.reopen(copy) if copy && !copy.closed? && !io.closed?
  end
  saved.each_value { |io| io.close unless io.closed? }
rescue StandardError
  nil
end

#silence_stdio ⇒ void (private)

This method returns an undefined value.

Point stdout and stderr at the null device. Used when this fork cannot start its own copier: the parent's pipe would otherwise publish a password this process set and the parent does not know.



275
276
277
278
279
280
281
282
# File 'lib/mutineer/output_filter.rb', line 275

def silence_stdio
  File.open(File::NULL, "w") do |null|
    STDOUT.reopen(null) unless STDOUT.closed?
    STDERR.reopen(null) unless STDERR.closed?
  end
rescue StandardError
  nil
end

#spawn_args(args) ⇒ Array (private)

args for spawn or system, with stdout and stderr sent to the null device when the program's env hash sets a DATABASE_URL this process does not know. The caller's own redirects of stdout and stderr are dropped too: a target such as err: :out or err: STDOUT would still reach this pipe, and Ruby refuses a stream given twice.

Parameters:

  • args (Array) —

    the arguments given to spawn or system.

Returns:

  • (Array)


246
247
248
249
250
251
252
253
# File 'lib/mutineer/output_filter.rb', line 246

def spawn_args(args)
  return args if !installed? || known_url?(args, ENV.fetch("DATABASE_URL", nil))

  options = args.size > 1 && args.last.is_a?(Hash) ? args.last : {}
  kept = options.reject { |key, _| Array(key).intersect?([:out, :err, 1, 2, STDOUT, STDERR]) }
  command = options.empty? ? args : args[0...-1]
  command + [kept.merge(out: File::NULL, err: File::NULL)]
end

#stream_io(name) ⇒ IO (private)

The real stream for name.

Parameters:

  • name (Symbol) —

    :stdout or :stderr.

Returns:

  • (IO)


288
289
290
# File 'lib/mutineer/output_filter.rb', line 288

def stream_io(name)
  name == :stdout ? STDOUT : STDERR
end

#uninstall ⇒ void (private)

This method returns an undefined value.

Put the descriptors back and write every byte already queued. Does nothing when install is not on. Safe to call twice. Does not kill the copier: a slow stdout must still receive the report. A grandchild that holds the pipe does not add a wait past QUIET_POLL, because the copier stops reading once the pipe is empty.



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/mutineer/output_filter.rb', line 153

def uninstall
  return unless installed?

  @stopping = true
  saved = @saved || {}
  stdio = @stdio || {}
  stdio.each do |name, io|
    copy = saved[name]
    io.reopen(copy) if copy && !copy.closed? && !io.closed?
  end
  @thread&.join
  saved.each_value { |io| io.close unless io.closed? }
  (@readers || {}).each_key { |io| io.close unless io.closed? }
  @installed = false
  @thread = nil
  @stopping = false
  @saved = {}
  @stdio = {}
  @readers = {}
end

#write_out(stream, data) ⇒ void (private)

This method returns an undefined value.

Write to $stdout or $stderr when the caller replaced that variable (a test capture). Otherwise write to the descriptor saved before install, never back into the pipe.

Parameters:

  • stream (Symbol)
  • data (String)


427
428
429
430
431
432
433
434
# File 'lib/mutineer/output_filter.rb', line 427

def write_out(stream, data)
  current = stream == :stdout ? $stdout : $stderr
  pipe = @stdio[stream]
  target = current.equal?(pipe) ? @saved[stream] : current
  target&.write(data)
rescue Errno::EPIPE, IOError
  nil
end