iostreams 2.0.0 → 2.2.0

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 (85) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +5 -22
  3. data/Rakefile +45 -0
  4. data/docs/CLAUDE.md +9 -0
  5. data/docs/config.md +161 -0
  6. data/docs/copy_files.md +93 -0
  7. data/docs/extensions.md +125 -0
  8. data/docs/formats.md +816 -0
  9. data/docs/index.md +388 -0
  10. data/docs/path.md +668 -0
  11. data/docs/pgp.md +436 -0
  12. data/docs/streams.md +382 -0
  13. data/docs/tutorial.md +495 -0
  14. data/docs/upgrading.md +664 -0
  15. data/lib/io_streams/builder/deprecations.rb +250 -0
  16. data/lib/io_streams/builder.rb +316 -39
  17. data/lib/io_streams/bzip2/reader.rb +41 -2
  18. data/lib/io_streams/bzip2/writer.rb +35 -2
  19. data/lib/io_streams/deprecation/methods.rb +51 -0
  20. data/lib/io_streams/deprecation/once.rb +27 -0
  21. data/lib/io_streams/deprecation/option_names.rb +26 -0
  22. data/lib/io_streams/deprecation/words.rb +42 -0
  23. data/lib/io_streams/deprecation.rb +259 -0
  24. data/lib/io_streams/encode/reader.rb +58 -3
  25. data/lib/io_streams/encode/writer.rb +23 -2
  26. data/lib/io_streams/encode.rb +99 -0
  27. data/lib/io_streams/errors.rb +55 -0
  28. data/lib/io_streams/gzip/reader.rb +15 -0
  29. data/lib/io_streams/gzip/writer.rb +11 -2
  30. data/lib/io_streams/io_streams.rb +468 -28
  31. data/lib/io_streams/line/reader.rb +9 -3
  32. data/lib/io_streams/line/utf8_reader.rb +23 -0
  33. data/lib/io_streams/path.rb +227 -28
  34. data/lib/io_streams/paths/file.rb +115 -6
  35. data/lib/io_streams/paths/http.rb +92 -5
  36. data/lib/io_streams/paths/matcher.rb +6 -3
  37. data/lib/io_streams/paths/s3.rb +242 -20
  38. data/lib/io_streams/paths/sftp/net_ssh.rb +104 -0
  39. data/lib/io_streams/paths/sftp.rb +141 -57
  40. data/lib/io_streams/paths.rb +23 -0
  41. data/lib/io_streams/pgp/reader.rb +60 -2
  42. data/lib/io_streams/pgp/writer.rb +42 -6
  43. data/lib/io_streams/pgp.rb +92 -21
  44. data/lib/io_streams/reader.rb +54 -1
  45. data/lib/io_streams/record/reader.rb +71 -10
  46. data/lib/io_streams/record/writer.rb +17 -10
  47. data/lib/io_streams/row/header_row.rb +21 -0
  48. data/lib/io_streams/row/reader.rb +52 -15
  49. data/lib/io_streams/row/writer.rb +64 -13
  50. data/lib/io_streams/schema/columns.rb +456 -0
  51. data/lib/io_streams/schema/constraints.rb +99 -0
  52. data/lib/io_streams/schema/field.rb +967 -0
  53. data/lib/io_streams/schema/json_number.rb +56 -0
  54. data/lib/io_streams/schema/keys.rb +78 -0
  55. data/lib/io_streams/schema/pattern.rb +257 -0
  56. data/lib/io_streams/schema/source.rb +31 -0
  57. data/lib/io_streams/schema.rb +616 -0
  58. data/lib/io_streams/stream.rb +843 -69
  59. data/lib/io_streams/symmetric_encryption/reader.rb +12 -0
  60. data/lib/io_streams/symmetric_encryption/writer.rb +4 -0
  61. data/lib/io_streams/tabular/header.rb +60 -4
  62. data/lib/io_streams/tabular/header_mapping.rb +332 -0
  63. data/lib/io_streams/tabular/mapping.rb +165 -0
  64. data/lib/io_streams/tabular/parser/array.rb +5 -0
  65. data/lib/io_streams/tabular/parser/base.rb +34 -0
  66. data/lib/io_streams/tabular/parser/csv.rb +5 -0
  67. data/lib/io_streams/tabular/parser/fixed.rb +200 -1
  68. data/lib/io_streams/tabular/parser/fixed_fields.rb +160 -0
  69. data/lib/io_streams/tabular/parser/hash.rb +10 -0
  70. data/lib/io_streams/tabular/parser/json.rb +17 -0
  71. data/lib/io_streams/tabular/parser/json_fields.rb +132 -0
  72. data/lib/io_streams/tabular/parser/psv.rb +6 -2
  73. data/lib/io_streams/tabular/schema_mapping.rb +361 -0
  74. data/lib/io_streams/tabular.rb +344 -30
  75. data/lib/io_streams/utils.rb +467 -1
  76. data/lib/io_streams/version.rb +1 -1
  77. data/lib/io_streams/writer.rb +37 -1
  78. data/lib/io_streams/xlsx/cells.rb +127 -0
  79. data/lib/io_streams/xlsx/reader.rb +61 -1
  80. data/lib/io_streams/xlsx/schema_reader.rb +90 -0
  81. data/lib/io_streams/xlsx/v3_writer.rb +16 -0
  82. data/lib/io_streams/zip/reader.rb +11 -0
  83. data/lib/io_streams/zip/writer.rb +28 -2
  84. data/lib/iostreams.rb +21 -17
  85. metadata +50 -7
@@ -32,13 +32,35 @@ module IOStreams
32
32
  @before_password_wait_seconds = 2
33
33
  @sshpass_wait_seconds = 5
34
34
 
35
+ autoload :NetSSH, "io_streams/paths/sftp/net_ssh"
36
+
35
37
  attr_reader :hostname, :username, :ssh_options, :url, :port
36
38
 
39
+ # The password, and the private key supplied as the ssh option `IdentityKey`, see IOStreams::Path.redact_options.
40
+ def self.sensitive_option_names = %i[password identity_key]
41
+
42
+ # Returns [String|nil] the deprecation warning for an SFTP url without a path, such as `sftp://host`, which
43
+ # IOStreams v3.0 reads as `sftp://host/`, the root directory, see `IOStreams::Path.name_deprecation`, while this
44
+ # version lists the login directory for it, see #each_child.
45
+ def self.name_deprecation(url)
46
+ return unless url_without_path?(url)
47
+
48
+ "an SFTP url without a path, such as sftp://host, is deprecated, since v3.0 reads it as sftp://host/, the " \
49
+ "root directory, which changes its #to_s and #path, and what #each_child lists: supply the url with the /, " \
50
+ "which v2.2 reads the same way"
51
+ end
52
+
37
53
  # Stream to a remote file over sftp.
38
54
  #
39
55
  # url: [String]
40
56
  # "sftp://<host_name>/<file_name>"
41
57
  #
58
+ # SECURITY WARNING:
59
+ # A username and password supplied in the url remain part of it, so `#to_s` and `#url`
60
+ # return them, as does any log or error message that includes the path.
61
+ # Supply them with the `username:` and `password:` arguments instead,
62
+ # and log `#display_name`, which never includes them.
63
+ #
42
64
  # username: [String]
43
65
  # Name of user to login with.
44
66
  #
@@ -63,6 +85,11 @@ module IOStreams
63
85
  # - Any other options supported by ssh_config.
64
86
  # `man ssh_config` to see all available options.
65
87
  #
88
+ # `#each_child` lists files with the net-sftp gem instead of the sftp executable, so it only supports
89
+ # these ssh options: HostKey, IdentityKey, IdentityFile, UserKnownHostsFile, StrictHostKeyChecking,
90
+ # ConnectTimeout, ServerAliveInterval, ServerAliveCountMax and LogLevel. Any other option raises
91
+ # ArgumentError.
92
+ #
66
93
  # Examples:
67
94
  #
68
95
  # # Display the contents of a remote file
@@ -102,9 +129,10 @@ module IOStreams
102
129
  # Not Ruby 2.5 yet: transform_keys(&:to_s)
103
130
  @ssh_options = {}
104
131
  ssh_options.each_pair { |key, value| @ssh_options[key.to_s] = value }
105
- @ssh_options.merge(uri.query) if uri.query
132
+ validate_username!
106
133
 
107
134
  super(uri.path)
135
+ warn_unusable_url(uri)
108
136
  end
109
137
 
110
138
  # Does not support relative file names since there is no concept of current working directory
@@ -116,6 +144,11 @@ module IOStreams
116
144
  url
117
145
  end
118
146
 
147
+ # Returns [String] the url without the user name, password, query or fragment, which can hold credentials.
148
+ def display_name
149
+ url.sub(%r{\A([^:/]+://)[^/?#]*@}, "\\1").sub(/[?#].*\z/m, "")
150
+ end
151
+
119
152
  # Note that mkdir is delayed and only executed when the file write is performed.
120
153
  def mkdir
121
154
  @mkdir = true
@@ -124,7 +157,9 @@ module IOStreams
124
157
 
125
158
  # TODO: Add #copy_from shortcut to detect when a file is supplied that does not require conversion.
126
159
 
127
- # Search for files on the remote sftp server that match the provided pattern.
160
+ # Search for files on the remote sftp server that match the provided pattern, within this path.
161
+ # When the url does not include a path, for example `sftp://sftp.example.org`, it searches
162
+ # the login directory.
128
163
  #
129
164
  # The pattern matching works like Net::SFTP::Operations::Dir.glob and Dir.glob
130
165
  # Each child also returns attributes that contain the file size, ownership, file dates and other details.
@@ -137,7 +172,7 @@ module IOStreams
137
172
  # end
138
173
  #
139
174
  # Example Output:
140
- # sftp://sftp.example.org/a/b/c/test.txt {:type=>1, :size=>37, :owner=>"test_owner", :group=>"test_group",
175
+ # sftp://sftp.example.org/my_files/a/b/c/test.txt {:type=>1, :size=>37, :owner=>"test_owner", :group=>"test_group",
141
176
  # :permissions=>420, :atime=>1572378136, :mtime=>1572378136, :link_count=>1, :extended=>{}}
142
177
  def each_child(pattern = "*", case_sensitive: true, directories: false, hidden: false)
143
178
  unless block_given?
@@ -145,64 +180,118 @@ module IOStreams
145
180
  case_sensitive: case_sensitive, directories: directories, hidden: hidden)
146
181
  end
147
182
 
183
+ authorize!
148
184
  Utils.load_soft_dependency("net-sftp", "SFTP glob capability", "net/sftp") unless defined?(Net::SFTP)
149
185
 
150
186
  flags = ::File::FNM_EXTGLOB
151
187
  flags |= ::File::FNM_CASEFOLD unless case_sensitive
152
188
  flags |= ::File::FNM_DOTMATCH if hidden
153
189
 
154
- Net::SFTP.start(hostname, username, build_ssh_options) do |sftp|
155
- sftp.dir.glob(".", pattern, flags) do |path|
156
- next if !directories && !path.file?
190
+ NetSSH.options(ssh_options, port: port, password: password) do |options|
191
+ Net::SFTP.start(hostname, username, options) do |sftp|
192
+ # Without a path in the url, list the login directory.
193
+ sftp.dir.glob(path.empty? ? "." : path, pattern, flags) do |entry|
194
+ next if !directories && !entry.file?
157
195
 
158
- new_path = self.class.new("sftp://#{hostname}/#{path.name}", username: username, password: password, **ssh_options)
159
- yield(new_path, path.attributes.attributes)
196
+ child = child_path(entry.name)
197
+ yield(child, entry.attributes.attributes) if allowed_child?(child)
198
+ end
160
199
  end
161
200
  end
162
201
  nil
163
202
  end
164
203
 
204
+ protected
205
+
206
+ attr_writer :url
207
+
165
208
  private
166
209
 
167
210
  attr_reader :password
168
211
 
212
+ # Returns [String] the host, port and path, which is compared against the allowed paths.
213
+ # `.` and `..` are resolved the way the sftp server resolves them.
214
+ def allowed_location
215
+ "sftp://#{hostname.to_s.downcase}:#{port}#{normalize_path(path)}".chomp("/")
216
+ end
217
+
218
+ # Reports a deprecation warning for each part of the url that this path cannot use, which IOStreams 3.0 raises
219
+ # ArgumentError for when the path is created, so that a mistake in a configured url is reported wherever the
220
+ # code runs: a url without a host, a query, whose ssh options are ignored, and a fragment, which an unencoded `#`
221
+ # starts, and which is not part of the name. Each warning names the url without its user name, password, query or
222
+ # fragment, see #display_name.
223
+ def warn_unusable_url(uri)
224
+ warn_url("it names no host, name one, such as 'sftp://example.org#{path}'") if uri.hostname.to_s.empty?
225
+ if uri.query
226
+ warn_url("its query is ignored, supply ssh options with ssh_options:, and percent-encode a '?' in a name as " \
227
+ "'%3F'")
228
+ end
229
+ return unless uri.fragment
230
+
231
+ warn_url("it has a fragment, which a '#' starts, and which is not part of the name, percent-encode a '#' in a " \
232
+ "name as '%23'")
233
+ end
234
+
235
+ # Reports that the url of this path is deprecated, since IOStreams 3.0 raises ArgumentError for it, for the
236
+ # supplied reason.
237
+ def warn_url(reason)
238
+ Deprecation.warn("the SFTP url #{display_name.inspect} is deprecated, since #{reason}")
239
+ end
240
+
241
+ # Usernames are passed to the `sftp` executable, so reject values that it could treat as options.
242
+ def validate_username!
243
+ return if username.nil?
244
+ return unless username.to_s.start_with?("-") || username.to_s.match?(/[[:cntrl:]]/)
245
+
246
+ raise(ArgumentError, "Invalid SFTP username: it cannot start with '-' or contain control characters")
247
+ end
248
+
249
+ # Set the path directly rather than parsing it as part of a URL, since a file name can contain
250
+ # characters such as `?`, `#`, `+` or `%` that a URL parser would treat as a query or as escapes.
251
+ #
252
+ # The supplied name is relative to this path, or to the login directory when this url has no path.
253
+ def child_path(name)
254
+ server = port == 22 ? "sftp://#{hostname}" : "sftp://#{hostname}:#{port}"
255
+ child = self.class.new(server, username: username, password: password, ssh_options: ssh_options)
256
+ child.replace_path((path.empty? ? "/#{name}" : Utils::PathName.join(path, name)).freeze)
257
+ child.url = "#{server}#{child.path}"
258
+ child
259
+ end
260
+
169
261
  def stream_reader(&block)
170
- IOStreams.temp_file("iostreams-sftp-reader") do |temp_file|
171
- sftp_download(path, temp_file.to_s)
172
- ::File.open(temp_file.to_s, "rb") { |io| builder.reader(io, &block) }
262
+ Utils.private_temp_file("iostreams-sftp-reader") do |file_name|
263
+ sftp_download(path, file_name)
264
+ ::File.open(file_name, "rb") { |io| builder.reader(io, &block) }
173
265
  end
174
266
  end
175
267
 
176
268
  def stream_writer(&block)
177
- IOStreams.temp_file("iostreams-sftp-writer") do |temp_file|
178
- ::File.open(temp_file.to_s, "wb") { |io| builder.writer(io, &block) }
179
- sftp_upload(temp_file.to_s, path)
180
- temp_file.size
269
+ Utils.private_temp_file("iostreams-sftp-writer") do |file_name|
270
+ ::File.open(file_name, "wb") { |io| builder.writer(io, &block) }
271
+ sftp_upload(file_name, path)
272
+ ::File.size(file_name)
181
273
  end
182
274
  end
183
275
 
184
- # Use sftp and sshpass executables to download to a local file
276
+ # Use the sftp executable to download to a local file, via sshpass when a password is supplied
185
277
  def sftp_download(remote_file_name, local_file_name)
186
278
  with_sftp_args do |args|
187
279
  Open3.popen2e(*args) do |writer, reader, waith_thr|
188
- # Give time for remote sftp server to get ready to accept the password.
189
- sleep self.class.before_password_wait_seconds
280
+ if password
281
+ # Give time for remote sftp server to get ready to accept the password.
282
+ sleep self.class.before_password_wait_seconds
190
283
 
191
- writer.puts password
284
+ writer.puts password
192
285
 
193
- # Give time for password to be processed and stdin to be passed to sftp process.
194
- sleep self.class.sshpass_wait_seconds
286
+ # Give time for password to be processed and stdin to be passed to sftp process.
287
+ sleep self.class.sshpass_wait_seconds
288
+ end
195
289
 
196
290
  writer.puts "get #{remote_file_name.inspect} #{local_file_name.inspect}"
197
291
  writer.puts "bye"
198
292
  writer.close
199
293
  out = reader.read.chomp
200
- unless waith_thr.value.success?
201
- raise(
202
- Errors::CommunicationsFailure,
203
- "Download failed calling #{self.class.sftp_bin} via #{self.class.sshpass_bin}: #{out}"
204
- )
205
- end
294
+ raise_failure("Download", out) unless waith_thr.value.success?
206
295
 
207
296
  out
208
297
  rescue Errno::EPIPE
@@ -211,10 +300,7 @@ module IOStreams
211
300
  rescue StandardError
212
301
  nil
213
302
  end
214
- raise(
215
- Errors::CommunicationsFailure,
216
- "Download failed calling #{self.class.sftp_bin} via #{self.class.sshpass_bin}: #{out}"
217
- )
303
+ raise_failure("Download", out)
218
304
  end
219
305
  end
220
306
  end
@@ -222,19 +308,16 @@ module IOStreams
222
308
  def sftp_upload(local_file_name, remote_file_name)
223
309
  with_sftp_args do |args|
224
310
  Open3.popen2e(*args) do |writer, reader, waith_thr|
225
- writer.puts(password) if password
226
- # Give time for password to be processed and stdin to be passed to sftp process.
227
- sleep self.class.sshpass_wait_seconds
311
+ if password
312
+ writer.puts(password)
313
+ # Give time for password to be processed and stdin to be passed to sftp process.
314
+ sleep self.class.sshpass_wait_seconds
315
+ end
228
316
  writer.puts "put #{local_file_name.inspect} #{remote_file_name.inspect}"
229
317
  writer.puts "bye"
230
318
  writer.close
231
319
  out = reader.read.chomp
232
- unless waith_thr.value.success?
233
- raise(
234
- Errors::CommunicationsFailure,
235
- "Upload failed calling #{self.class.sftp_bin} via #{self.class.sshpass_bin}: #{out}"
236
- )
237
- end
320
+ raise_failure("Upload", out) unless waith_thr.value.success?
238
321
 
239
322
  out
240
323
  rescue Errno::EPIPE
@@ -243,14 +326,21 @@ module IOStreams
243
326
  rescue StandardError
244
327
  nil
245
328
  end
246
- raise(
247
- Errors::CommunicationsFailure,
248
- "Upload failed calling #{self.class.sftp_bin} via #{self.class.sshpass_bin}: #{out}"
249
- )
329
+ raise_failure("Upload", out)
250
330
  end
251
331
  end
252
332
  end
253
333
 
334
+ # When the server does not prompt for a password, sftp reads the password line as a command
335
+ # and echoes it in its output, so remove it before the output is included in the error.
336
+ def raise_failure(action, out)
337
+ out = out.gsub(password.to_s, "[FILTERED]") if out && !password.to_s.empty?
338
+ raise(
339
+ Errors::CommunicationsFailure,
340
+ "#{action} failed calling #{self.class.sftp_bin}#{" via #{self.class.sshpass_bin}" if password}: #{out}"
341
+ )
342
+ end
343
+
254
344
  def with_sftp_args
255
345
  return yield sftp_args(ssh_options) if !ssh_options.key?("IdentityKey") && !ssh_options.key?("HostKey")
256
346
 
@@ -274,9 +364,9 @@ module IOStreams
274
364
  end
275
365
 
276
366
  def with_temp_file(options, option, value)
277
- Utils.temp_file_name("iostreams-sftp-args", "key") do |file_name|
278
- # sftp requires that private key is only readable by the current user
279
- ::File.open(file_name, "wb", 0o600) { |io| io.write(value) }
367
+ # sftp requires that private key is only readable by the current user
368
+ Utils.private_temp_file("iostreams-sftp-args", "key") do |file_name|
369
+ ::File.binwrite(file_name, value)
280
370
 
281
371
  options[option] = file_name
282
372
  yield options
@@ -284,7 +374,8 @@ module IOStreams
284
374
  end
285
375
 
286
376
  def sftp_args(ssh_options)
287
- args = [self.class.sshpass_bin, self.class.sftp_bin]
377
+ # sshpass is only needed to supply the password to sftp.
378
+ args = password ? [self.class.sshpass_bin, self.class.sftp_bin] : [self.class.sftp_bin]
288
379
  # Force sftp to use the password when supplied,
289
380
  # and stop sftp from prompting for a password when none was supplied.
290
381
  if password
@@ -303,19 +394,12 @@ module IOStreams
303
394
  ssh_options.each_pair { |key, value| args << "-o#{key}=#{value}" }
304
395
  args << "-b"
305
396
  args << "-"
397
+ # Stop sftp from treating the destination as an option.
398
+ args << "--"
306
399
  args << "#{username}@#{hostname}"
307
400
  args
308
401
  end
309
402
 
310
- def build_ssh_options
311
- options = ssh_options.dup
312
- options[:logger] ||= IOStreams.logger if IOStreams.logger
313
- options[:port] ||= port
314
- options[:max_pkt_size] ||= 65_536
315
- options[:password] ||= @password
316
- options
317
- end
318
-
319
403
  def map_log_level
320
404
  level = IOStreams.logger&.level
321
405
  case level
@@ -0,0 +1,23 @@
1
+ module IOStreams
2
+ # The path classes of the schemes of urls, such as `IOStreams::Paths::S3` for `s3://`, see `IOStreams.register_scheme`.
3
+ module Paths
4
+ # Returns [IOStreams::Path] the path of the supplied name or url, created with the supplied arguments by the path
5
+ # class of its scheme, see .path_class.
6
+ #
7
+ # It reports no deprecation warning for the name, which `IOStreams.path` reports for a name that the application
8
+ # supplies, see `IOStreams::Path.name_deprecation`, so that IOStreams can create the path of a name that it derives
9
+ # from one, such as the directory that a pattern is matched within, see `IOStreams::Paths::Matcher`.
10
+ def self.build(name, **args)
11
+ klass = path_class(name)
12
+ args.empty? ? klass.new(name) : klass.new(name, **args)
13
+ end
14
+
15
+ # Returns [Class] the path class of the scheme of the supplied name or url, such as `IOStreams::Paths::SFTP`, or the
16
+ # one registered for a name without a scheme, such as `IOStreams::Paths::File`, see `IOStreams.scheme`.
17
+ #
18
+ # Raises ArgumentError when the scheme is not registered, and `URI::Error` when the url is not valid.
19
+ def self.path_class(name)
20
+ IOStreams.scheme(name.include?("://") ? Utils::URI.new(name).scheme : nil)
21
+ end
22
+ end
23
+ end
@@ -3,6 +3,28 @@ require "open3"
3
3
  module IOStreams
4
4
  module Pgp
5
5
  class Reader < IOStreams::Reader
6
+ def self.option_names
7
+ %i[passphrase ignore_mdc_error verify_first]
8
+ end
9
+
10
+ def self.sensitive_option_names
11
+ %i[passphrase]
12
+ end
13
+
14
+ # The methods that the stream that v3.0 supplies to a reader block for PGP answers, when gpg does not read a regular
15
+ # local file, see .v3_stream_methods: those of an IO that read, and #binmode and #binmode?.
16
+ V3_METHODS = [*V3_READ_METHODS, :binmode, :binmode?].freeze
17
+ private_constant :V3_METHODS
18
+
19
+ # Returns [Array<Symbol>|nil] the methods that the stream that v3.0 supplies to a reader block, in place of the IO
20
+ # of gpg's output that this reader yields, answers, see `IOStreams::Reader.v3_stream_methods`: nil with
21
+ # `verify_first: true`, since both versions then yield the File that gpg decrypts the data into, or when it reads
22
+ # a regular local file, which gpg reads itself in v3.0, so that the block receives gpg's output in both versions,
23
+ # otherwise those of the stream that v3.0 supplies, which feeds gpg the data that it reads.
24
+ def self.v3_stream_methods(options)
25
+ V3_METHODS unless options[:verify_first] || yield
26
+ end
27
+
6
28
  # Passphrase to use to open the private key to decrypt the received file
7
29
  class << self
8
30
  attr_writer :default_passphrase
@@ -16,6 +38,15 @@ module IOStreams
16
38
 
17
39
  # Read from a PGP / GPG file , decompressing the contents as it is read.
18
40
  #
41
+ # SECURITY WARNING:
42
+ # By default the decrypted contents are passed to the block as gpg decrypts them,
43
+ # before gpg has checked the file's integrity (MDC) and any signature, since those are
44
+ # only known once the whole file has been read. When either check fails,
45
+ # `IOStreams::Pgp::Failure` is raised after the block has processed the data.
46
+ # Do not commit any side effects, such as database updates, until the block returns
47
+ # without raising, for example by processing the file within a database transaction.
48
+ # Otherwise supply `verify_first: true`.
49
+ #
19
50
  # file_name: [String]
20
51
  # Name of file to read from
21
52
  #
@@ -30,7 +61,15 @@ module IOStreams
30
61
  # Only enable this for files from a trusted source: without MDC the decrypted
31
62
  # contents are not protected against tampering.
32
63
  # Default: false
33
- def self.file(file_name, passphrase: nil, ignore_mdc_error: false)
64
+ #
65
+ # verify_first: [true|false]
66
+ # Decrypt the whole file into a temporary file, only readable by the current user,
67
+ # and only pass its contents to the block once gpg has checked the file's integrity
68
+ # and any signature.
69
+ # Requires local disk space for the decrypted contents, which are deleted afterwards,
70
+ # and an extra pass over the data.
71
+ # Default: false
72
+ def self.file(file_name, passphrase: nil, ignore_mdc_error: false, verify_first: false, &)
34
73
  # Cannot use `passphrase: self.default_passphrase` since it is considered private
35
74
  passphrase ||= default_passphrase
36
75
 
@@ -43,11 +82,13 @@ module IOStreams
43
82
  args += ["--batch", "--no-tty", "--yes", "--decrypt"]
44
83
  # Only feed a passphrase when one is supplied; sign-only files need none.
45
84
  args += ["--passphrase-fd", "0"] if passphrase
46
- args << file_name.to_s
85
+ args += ["--", file_name.to_s]
47
86
 
48
87
  command = IOStreams::Pgp.gpg_command(*args)
49
88
  IOStreams.logger&.debug { "IOStreams::Pgp::Reader.open: #{command.shelljoin}" }
50
89
 
90
+ return decrypt_then_read(command, file_name, passphrase, &) if verify_first
91
+
51
92
  # Read decrypted contents from stdout
52
93
  Open3.popen3(*command) do |stdin, stdout, stderr, waith_thr|
53
94
  stdin.puts(passphrase) if passphrase
@@ -65,6 +106,23 @@ module IOStreams
65
106
  result
66
107
  end
67
108
  end
109
+
110
+ # Decrypts the file into a temporary file, and only yields it once gpg has succeeded.
111
+ def self.decrypt_then_read(command, file_name, passphrase, &block)
112
+ Utils.private_temp_file("iostreams_pgp") do |temp_file_name|
113
+ Open3.popen3(*command) do |stdin, stdout, stderr, waith_thr|
114
+ stdin.puts(passphrase) if passphrase
115
+ stdin.close
116
+ ::File.open(temp_file_name, "wb") { |io| ::IO.copy_stream(stdout, io) }
117
+ unless waith_thr.value.success?
118
+ raise(Pgp::Failure, "GPG Failed to decrypt file: #{file_name}: #{stderr.read.chomp}")
119
+ end
120
+ end
121
+
122
+ ::File.open(temp_file_name, "rb", &block)
123
+ end
124
+ end
125
+ private_class_method :decrypt_then_read
68
126
  end
69
127
  end
70
128
  end
@@ -3,6 +3,30 @@ require "open3"
3
3
  module IOStreams
4
4
  module Pgp
5
5
  class Writer < IOStreams::Writer
6
+ # File descriptor in the gpg process that the signer passphrase is read from.
7
+ PASSPHRASE_FD = 3
8
+
9
+ def self.option_names
10
+ %i[encrypt recipient import_and_trust_key import_and_trust_level signer signer_passphrase
11
+ compress compress_level]
12
+ end
13
+
14
+ def self.sensitive_option_names
15
+ %i[signer_passphrase]
16
+ end
17
+
18
+ # The methods that the stream that v3.0 supplies to a writer block for PGP answers: those of an IO that write,
19
+ # #flush, #binmode and #binmode?, see .v3_stream_methods.
20
+ V3_METHODS = [*V3_WRITE_METHODS, :flush, :binmode, :binmode?].freeze
21
+ private_constant :V3_METHODS
22
+
23
+ # Returns [Array<Symbol>] the methods that the stream that v3.0 supplies to a writer block, in place of the IO of
24
+ # gpg's input that this writer yields, answers, which writes to gpg, whatever it writes to, see
25
+ # `IOStreams::Writer.v3_stream_methods`.
26
+ def self.v3_stream_methods(_options)
27
+ V3_METHODS
28
+ end
29
+
6
30
  class << self
7
31
  # Sign all encrypted files with this users key.
8
32
  # Default: Do not sign encrypted files.
@@ -122,13 +146,22 @@ module IOStreams
122
146
  recipients: recipients
123
147
  )
124
148
  command = IOStreams::Pgp.gpg_command(*args)
149
+ IOStreams.logger&.debug { "IOStreams::Pgp::Writer.open: #{command.shelljoin}" }
125
150
 
126
- # Do not log the command, it may contain the signer passphrase.
127
- action = encrypt ? "encrypt" : "sign"
128
- IOStreams.logger&.debug { "IOStreams::Pgp::Writer.open: #{action} -o #{file_name}" }
151
+ # Since stdin carries the data, supply the signer passphrase on file descriptor 3
152
+ # so that it is not visible in the process list.
153
+ spawn_options = {}
154
+ if signer_passphrase
155
+ passphrase_reader, passphrase_writer = IO.pipe
156
+ passphrase_writer.puts(signer_passphrase.to_s)
157
+ passphrase_writer.close
158
+ spawn_options[PASSPHRASE_FD] = passphrase_reader
159
+ end
129
160
 
130
161
  result = nil
131
- Open3.popen2e(*command) do |stdin, out, waith_thr|
162
+ Open3.popen2e(*command, spawn_options) do |stdin, out, waith_thr|
163
+ # Only the gpg process needs the passphrase.
164
+ passphrase_reader&.close
132
165
  begin
133
166
  stdin.binmode
134
167
  result = yield(stdin)
@@ -144,6 +177,8 @@ module IOStreams
144
177
  end
145
178
  end
146
179
  result
180
+ ensure
181
+ passphrase_reader&.close
147
182
  end
148
183
 
149
184
  def self.build_args(file_name:, encrypt:, signer:, signer_passphrase:, compress:, compress_level:, recipients:)
@@ -153,7 +188,7 @@ module IOStreams
153
188
  if signer_passphrase
154
189
  args += ["--pinentry-mode", "loopback"] if IOStreams::Pgp.pgp_version.to_f >= 2.1
155
190
  args << "--no-symkey-cache" if IOStreams::Pgp.pgp_version.to_f >= 2.4
156
- args += ["--passphrase", signer_passphrase.to_s]
191
+ args += ["--passphrase-fd", PASSPHRASE_FD.to_s]
157
192
  end
158
193
  args += ["-z", compress_level.to_s] if compress_level != 6
159
194
  args += ["--compress-algo", compress.to_s] unless compress == :none
@@ -168,7 +203,8 @@ module IOStreams
168
203
  recipients << audit_recipient if audit_recipient
169
204
 
170
205
  Array(import_and_trust_key).each do |key|
171
- recipients << IOStreams::Pgp.import_and_trust(key: key, trust_level: import_and_trust_level)
206
+ # Encrypt to the imported key's fingerprint, since its email address could match another key in the keyring.
207
+ recipients << IOStreams::Pgp.import_and_trust_recipient(key: key, trust_level: import_and_trust_level)
172
208
  end
173
209
  recipients
174
210
  end