strong_csv 0.9.0 → 0.10.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: dd735e06083068bf676047a6ac4f2a0441bc3b36cb3455e04ac7ae2c0206acb6
4
- data.tar.gz: 77be5288dbd7854f82385367b62352c4ac98e41f108046c99fc68dadc8611890
3
+ metadata.gz: d4776ffdd035476e38fc689b3778f0027a03146d1b0725b413df27fa275f5cb3
4
+ data.tar.gz: 9e1fc7f5344f56b90b464d55fbb4f9f18d7b74c23c0d1baa13332fd335944416
5
5
  SHA512:
6
- metadata.gz: 3d2bbc51b2006f8769ce112c3a4280f6ca0000e5503680716cd218eb06db1011805ab7ff6113ad9804f58e26af03921f9a1f188f1626a7e6a2715663df9fa082
7
- data.tar.gz: 2e531d2ecbe4e9b035a882701a1eedd342ccf6bacea712964517d68b56f73ecf0654afb26229e6e1596bfb7d77805cf09c6c5d6d1e67ba337eecc94f57fedb22
6
+ metadata.gz: 135d368823a788fbad389f4cc9652321dbc05ac71e2312d512eab2f8c4d381bc9852291a96107c7ec3b7e972b3b0a8546c5f57d8343e88c0aa59400d90cad1b5
7
+ data.tar.gz: 2194bd4b8f26dafb8cc09eeea018b5ff3752b10375c64302a00a79d5e39cd5f2375ff952473c179a0e4ed49f48c266a0061875a111c0791dbdd7d63d5abd51c8
data/README.md CHANGED
@@ -43,11 +43,11 @@ The most important APIs of strong_csv are `StrongCSV.new` and `StrongCSV#parse`.
43
43
  Inside the block, you will mainly use `let` and declare types for a column.
44
44
 
45
45
  After defining types, you can parse CSV content with `StrongCSV#parse`.
46
- `StrongCSV#parse` won't raise errors as possible and just store error messages in its rows.
47
- The reason why it won't raise errors is CSV content may contain _invalid_ rows,
48
- but sometimes, it makes sense to ignore them and process something for _valid_ rows.
49
- If you want to stop all processes with invalid rows,
50
- check whether all rows are valid before proceeding with computation.
46
+ `StrongCSV#parse` stores invalid cell values as error messages in the row
47
+ instead of raising, so an application can skip invalid rows and process the
48
+ valid ones. To stop on any invalid row, check whether all rows are valid
49
+ before proceeding. Structural CSV errors, such as malformed quoting or an
50
+ invalid byte sequence, still raise; see [Security](#security).
51
51
 
52
52
  Here is an example usage of this gem:
53
53
 
@@ -113,6 +113,15 @@ because the block receives the complete array. For very large CSV files, this ca
113
113
  a large amount of memory; the streaming form of `StrongCSV#parse` does not remove this
114
114
  buffering for picked columns.
115
115
 
116
+ `pick` also requires a seekable input. A request body or socket cannot be
117
+ rewound; buffer it before parsing. Picked values are scoped to a single
118
+ `parse` call, so a `StrongCSV` instance can be shared across concurrent
119
+ requests once its declarations are complete.
120
+
121
+ When you declare columns by name, every declared column must appear exactly
122
+ once in the CSV header; otherwise `StrongCSV#parse` raises
123
+ `StrongCSV::HeaderError`. Extra columns are ignored.
124
+
116
125
  You can also define types without CSV headers by specifying column numbers.
117
126
 
118
127
  > [!NOTE]
@@ -194,6 +203,8 @@ This declaration expects a CSV has the contents like this:
194
203
 
195
204
  The value must be casted to Integer. `integer?` allows the value to be `nil`, so you can declare optional integer type
196
205
  for columns. It also lets you allow values that satisfy the specified limitation through `:constraint`.
206
+ The conversion follows Ruby's `Integer()` rules; see [Security](#security)
207
+ for accepted forms such as `010` (octal) and `1_0`.
197
208
 
198
209
  _Example_
199
210
 
@@ -225,6 +236,8 @@ result[2].errors.slice(:stock, :user_id) # => {:stock=>["`\"non-integer\"` can't
225
236
 
226
237
  The value must be casted to Float. `float?` allows the value to be `nil`, so you can declare optional float type for
227
238
  columns. It also lets you allow values that satisfy the specified limitation through `:constraint`.
239
+ The conversion follows Ruby's `Float()` rules; see [Security](#security)
240
+ for accepted forms such as `1_0.5` and `1e400` (`Infinity`).
228
241
 
229
242
  _Example_
230
243
 
@@ -401,8 +414,9 @@ result[2].slice(0, 1, 2, 3, 4) # => {0=>123, 1=>"Hey", 2=>2.5, 3=>10, 4=>"!"} ("
401
414
  > default. A match that exceeds the timeout is treated as a non-match. On Ruby 3.2 and later,
402
415
  > pass a Regexp with an explicit timeout to change the limit, e.g.
403
416
  > `let :id, Regexp.new("\\A[a-z]+\\z", timeout: 5.0)`. A per-Regexp timeout or the global
404
- > `Regexp.timeout` takes precedence over the default. Ruby 3.1 and earlier have no regexp
405
- > timeout, and the `timeout:` keyword must not be used there because it is not supported.
417
+ > `Regexp.timeout` takes precedence over the default. Ruby 2.5–3.1 has no regexp timeout.
418
+ > When parsing untrusted input on those versions, keep `field_size_limit` small or avoid
419
+ > Regexp literals; see [Security](#security).
406
420
 
407
421
  ### Union
408
422
 
@@ -430,6 +444,67 @@ result[1].slice(:priority, :size) # => {:priority=>30, :size=>"A"} ("A" is not o
430
444
  result[2].slice(:priority, :size) # => {:priority=>"11", :size=>"S"} (11 is not one of 10, 20, and 30)
431
445
  ```
432
446
 
447
+ ## Security
448
+
449
+ strong_csv validates cell values; it does not sandbox the CSV parser or
450
+ enforce resource limits. Treat CSV content as untrusted and apply limits at
451
+ the application boundary.
452
+
453
+ ### Resource limits
454
+
455
+ - Set `field_size_limit`; the CSV default is unlimited.
456
+ `strong_csv.parse(data, field_size_limit: 2048)` forwards it to `CSV.new`.
457
+ - Limit the number of rows and the total time or bytes at the application
458
+ boundary. `parse` without a block materializes every row.
459
+ - `pick` buffers all values of the picked columns for the whole CSV, even
460
+ when parsing with a block.
461
+
462
+ ### Exceptions
463
+
464
+ Invalid cell values are stored in `row.errors` and do not raise. Structurally
465
+ invalid CSV raises `CSV::MalformedCSVError` or `CSV::InvalidEncodingError`;
466
+ rescue these at the boundary. `pick` requires a seekable input and raises
467
+ `StrongCSV::NotSeekableError` when a stream cannot be rewound. Declared
468
+ symbol columns must appear exactly once in the header; otherwise `parse`
469
+ raises `StrongCSV::HeaderError`.
470
+
471
+ ### Regular expressions
472
+
473
+ On Ruby 3.2 and later, a Regexp literal match has a one-second default
474
+ timeout; a timed-out match is an invalid cell. Set a per-Regexp timeout when
475
+ one second is too long for your request budget. Ruby 2.5–3.1 has no regexp
476
+ timeout, so keep `field_size_limit` small or avoid Regexp literals for
477
+ untrusted input on those versions.
478
+
479
+ ### Numeric conversion
480
+
481
+ `integer` and `float` use Ruby's `Integer()` and `Float()` rules. For
482
+ example, `Integer("010")` is octal (`8`), `Integer("0x10")` is `16`,
483
+ `Integer("1_0")` is `10`, surrounding whitespace is ignored, and
484
+ `Float("1e400")` is `Infinity`. Reject non-finite floats with a
485
+ `constraint:` when it matters. If exact decimal syntax matters, validate the
486
+ raw cell with a custom type before casting.
487
+
488
+ ### CSV options
489
+
490
+ `headers` and `header_converters` are set by strong_csv. Other options are
491
+ forwarded to `CSV.new`; `converters`, `strip`, and `liberal_parsing` change
492
+ the values or parsing semantics and can bypass the type declarations. Only
493
+ pass options you control.
494
+
495
+ ### Reading values
496
+
497
+ `row[]` returns the original String when a cell is invalid. Check `valid?`
498
+ before using values from a row.
499
+
500
+ ### Error messages
501
+
502
+ Built-in error messages include the cell value truncated to 256 characters
503
+ and escape invisible control and format characters, so `row.errors` is
504
+ safer to log. Custom `error_message:` values are used as given.
505
+
506
+ To report a vulnerability, follow [SECURITY.md](SECURITY.md).
507
+
433
508
  ## Contributing
434
509
 
435
510
  Bug reports and pull requests are welcome on the [GitHub repository](https://github.com/yykamei/strong_csv).
data/SECURITY.md ADDED
@@ -0,0 +1,34 @@
1
+ # Security Policy
2
+
3
+ ## Supported Versions
4
+
5
+ Security fixes are provided in the latest released version of strong_csv.
6
+
7
+ The gem runs on Ruby 2.5 and later, but the Ruby project only maintains
8
+ Ruby 3.3 and later. Use a Ruby version that still receives security fixes,
9
+ especially when parsing untrusted input.
10
+
11
+ | Version | Supported |
12
+ | -------------- | --------- |
13
+ | Latest release | Yes |
14
+ | Older releases | No |
15
+
16
+ ## Reporting a Vulnerability
17
+
18
+ Please report vulnerabilities privately through GitHub's private
19
+ vulnerability reporting:
20
+
21
+ [GitHub private vulnerability reporting](https://github.com/yykamei/strong_csv/security/advisories/new)
22
+
23
+ Do not open a public issue for a security problem.
24
+
25
+ Include:
26
+
27
+ - the strong_csv version,
28
+ - the Ruby and csv versions,
29
+ - a minimal CSV input and type declaration that reproduces the issue,
30
+ - the impact you expect, such as a denial of service or a validation bypass.
31
+
32
+ We aim to acknowledge a report within 7 days and to publish a fix or
33
+ mitigation as soon as practical. We will credit reporters unless they
34
+ prefer to remain anonymous.
@@ -16,8 +16,8 @@ class StrongCSV
16
16
  @types = []
17
17
  @headers = false
18
18
  @pickers = {}
19
- @picked = {}
20
19
  @picker_columns = {}
20
+ @picked_key = :"strong_csv_picked_#{object_id}"
21
21
  end
22
22
 
23
23
  # @param name [String, Symbol, Integer]
@@ -52,12 +52,14 @@ class StrongCSV
52
52
  # @param as [Symbol]
53
53
  # @yieldparam values [Array<String>] The values for the column. NOTE: This is an array of String, not casted values.
54
54
  def pick(column, as:, &block)
55
+ raise TypeError, "`column` must be Symbol or Integer: #{column.inspect}" unless column.is_a?(::Symbol) || column.is_a?(::Integer)
56
+ raise TypeError, "`as` must be a Symbol: #{as.inspect}" unless as.is_a?(::Symbol)
57
+ raise ArgumentError, "`as` conflicts with an existing method: #{as.inspect}" if respond_to?(as, true)
58
+
55
59
  define_singleton_method(as) do
56
- @picked[as]
57
- end
58
- @pickers[as] = lambda do |values|
59
- @picked[as] = block.call(values)
60
+ picked[as]
60
61
  end
62
+ @pickers[as] = block
61
63
  @picker_columns[as] = column
62
64
  end
63
65
 
@@ -66,13 +68,78 @@ class StrongCSV
66
68
  # The collected values are held in memory until the picker blocks return.
67
69
  # The CSV stream is rewound before returning so the caller can continue
68
70
  # reading from the beginning.
71
+ #
72
+ # @return [Hash{Symbol => Object}] The picked values by picker name.
69
73
  def pick_all(csv)
70
- return if @pickers.empty?
74
+ picked_values = {}
75
+ return picked_values if @pickers.empty?
71
76
 
72
77
  buffers = Hash.new { |hash, key| hash[key] = [] }
73
- csv.each { |row| @pickers.each_key { |as| buffers[as] << row[@picker_columns[as]] } }
74
- csv.rewind
75
- @pickers.each { |as, picker| picker.call(buffers[as]) }
78
+ header_checked = false
79
+ csv.each do |row|
80
+ unless header_checked
81
+ validate_headers(csv.headers)
82
+ header_checked = true
83
+ end
84
+ @pickers.each_key { |as| buffers[as] << row[@picker_columns[as]] }
85
+ end
86
+ # Report a schema mismatch before the seekability requirement.
87
+ validate_headers(csv.headers) unless header_checked
88
+ rewind!(csv)
89
+ with_picked(picked_values) do
90
+ @pickers.each { |as, block| picked_values[as] = block.call(buffers[as]) }
91
+ end
92
+ picked_values
93
+ end
94
+
95
+ # Runs the block with the picked values for the current parse.
96
+ #
97
+ # The constraint and block closures created by the DSL call picker methods
98
+ # on this instance, so the per-parse values must be reachable without
99
+ # changing those closures. Fiber-local storage keeps concurrent threads and
100
+ # fibers isolated and is restored when the block returns. Picker methods
101
+ # raise outside this scope instead of silently returning nil.
102
+ #
103
+ # @param picked [Hash{Symbol => Object}]
104
+ # @return [Object] The block's return value.
105
+ def with_picked(picked)
106
+ previous = Thread.current[@picked_key]
107
+ Thread.current[@picked_key] = picked
108
+ yield
109
+ ensure
110
+ Thread.current[@picked_key] = previous
111
+ end
112
+
113
+ # Finalizes the header mode after all declarations are known.
114
+ #
115
+ # Index-based `let` declarations cannot be combined with a Symbol picker
116
+ # column because the picker would index a row by Symbol.
117
+ #
118
+ # @raise [ArgumentError] when Symbol pick columns are combined with
119
+ # index-based `let` declarations.
120
+ def validate_declarations
121
+ if @types.empty?
122
+ @headers = @picker_columns.values.any?(::Symbol)
123
+ return
124
+ end
125
+
126
+ return if @headers
127
+ return unless @picker_columns.values.any?(::Symbol)
128
+
129
+ raise ArgumentError, "Symbol pick columns require header-based `let` declarations"
130
+ end
131
+
132
+ # Verifies that every declared symbol column appears exactly once in the
133
+ # CSV header. Extra columns are ignored, and index-based declarations are
134
+ # not checked.
135
+ #
136
+ # @param headers [Array<Symbol>, true, false, nil]
137
+ # @raise [HeaderError] when a declared column is missing or duplicated.
138
+ def validate_headers(headers)
139
+ return unless @headers
140
+
141
+ errors = header_errors(headers)
142
+ raise HeaderError, "invalid CSV headers (#{errors.join(", ")})" unless errors.empty?
76
143
  end
77
144
 
78
145
  # @param options [Hash] See `Types::Integer#initialize` for more details.
@@ -130,6 +197,39 @@ class StrongCSV
130
197
 
131
198
  private
132
199
 
200
+ def picked
201
+ context = Thread.current[@picked_key]
202
+ raise Error, "picked values are only available during parse" if context.nil?
203
+
204
+ context
205
+ end
206
+
207
+ def rewind!(csv)
208
+ csv.rewind
209
+ rescue IOError, NoMethodError, SystemCallError => e
210
+ raise NotSeekableError, "pick requires a seekable input; buffer the CSV before parsing", cause: e
211
+ end
212
+
213
+ def header_errors(headers)
214
+ required = required_columns
215
+ return ["missing: #{required.inspect}"] unless headers.is_a?(::Array)
216
+
217
+ missing = required - headers
218
+ duplicated = required.select { |name| headers.count(name) > 1 }
219
+ error_messages(missing, duplicated)
220
+ end
221
+
222
+ def required_columns
223
+ (@types.map(&:name) + @picker_columns.values.grep(::Symbol)).uniq
224
+ end
225
+
226
+ def error_messages(missing, duplicated)
227
+ messages = []
228
+ messages << "missing: #{missing.inspect}" unless missing.empty?
229
+ messages << "duplicated: #{duplicated.inspect}" unless duplicated.empty?
230
+ messages
231
+ end
232
+
133
233
  def validate_columns
134
234
  if @types.all? { |t| t.name.is_a?(Integer) }
135
235
  @headers = false
@@ -17,7 +17,7 @@ class StrongCSV
17
17
  boolean = FALSE_VALUES.include?(value) ? false : nil
18
18
  return ValueResult.new(value: boolean, original_value: value) unless boolean.nil?
19
19
 
20
- ValueResult.new(original_value: value, error_messages: ["`#{value.inspect}` can't be casted to Boolean"])
20
+ ValueResult.new(original_value: value, error_messages: ["`#{SafeInspect.render(value)}` can't be casted to Boolean"])
21
21
  end
22
22
  end
23
23
  end
@@ -21,10 +21,10 @@ class StrongCSV
21
21
  if @constraint.call(float)
22
22
  ValueResult.new(value: float, original_value: value)
23
23
  else
24
- ValueResult.new(original_value: value, error_messages: ["`#{value.inspect}` does not satisfy the specified constraint"])
24
+ ValueResult.new(original_value: value, error_messages: ["`#{SafeInspect.render(value)}` does not satisfy the specified constraint"])
25
25
  end
26
26
  rescue ArgumentError, TypeError
27
- ValueResult.new(original_value: value, error_messages: ["`#{value.inspect}` can't be casted to Float"])
27
+ ValueResult.new(original_value: value, error_messages: ["`#{SafeInspect.render(value)}` can't be casted to Float"])
28
28
  end
29
29
  end
30
30
  end
@@ -21,10 +21,10 @@ class StrongCSV
21
21
  if @constraint.call(int)
22
22
  ValueResult.new(value: int, original_value: value)
23
23
  else
24
- ValueResult.new(original_value: value, error_messages: ["`#{value.inspect}` does not satisfy the specified constraint"])
24
+ ValueResult.new(original_value: value, error_messages: ["`#{SafeInspect.render(value)}` does not satisfy the specified constraint"])
25
25
  end
26
26
  rescue ArgumentError, TypeError
27
- ValueResult.new(original_value: value, error_messages: ["`#{value.inspect}` can't be casted to Integer"])
27
+ ValueResult.new(original_value: value, error_messages: ["`#{SafeInspect.render(value)}` can't be casted to Integer"])
28
28
  end
29
29
  end
30
30
  end
@@ -4,10 +4,14 @@ class StrongCSV
4
4
  module Types
5
5
  # Literal is a module to collect all the literal types for CSV parsing.
6
6
  # This module is intended for refining built-in classes and provide `#cast` like `Base` class.
7
- module Literal
7
+ module Literal # rubocop:disable Metrics/ModuleLength
8
8
  # The default time limit, in seconds, for matching a Regexp literal on Ruby 3.2 and later.
9
9
  REGEXP_TIMEOUT = 1.0
10
- private_constant :REGEXP_TIMEOUT
10
+
11
+ # Internal error for a range begin type that cannot be casted.
12
+ class UnsupportedBeginType < TypeError; end
13
+
14
+ private_constant :REGEXP_TIMEOUT, :UnsupportedBeginType
11
15
 
12
16
  class << self
13
17
  # Returns a Regexp that enforces the default match timeout.
@@ -27,8 +31,10 @@ class StrongCSV
27
31
  # Matches the value against the Regexp with the default timeout.
28
32
  #
29
33
  # @param regexp [Regexp]
30
- # @param value [Object]
31
- # @return [Integer, nil, :timeout] The match position, nil, or :timeout when the match exceeded the limit
34
+ # @param value [String]
35
+ # @return [Integer, nil, :timeout, :incompatible_encoding] The match
36
+ # position, nil, :timeout when the match exceeded the limit, or
37
+ # :incompatible_encoding when the value cannot be matched.
32
38
  def regexp_match(regexp, value)
33
39
  matcher = regexp_with_timeout(regexp)
34
40
 
@@ -37,9 +43,15 @@ class StrongCSV
37
43
  matcher =~ value
38
44
  rescue ::Regexp::TimeoutError
39
45
  :timeout
46
+ rescue ::Encoding::CompatibilityError, ::ArgumentError
47
+ :incompatible_encoding
40
48
  end
41
49
  else
42
- matcher =~ value
50
+ begin
51
+ matcher =~ value
52
+ rescue ::Encoding::CompatibilityError, ::ArgumentError
53
+ :incompatible_encoding
54
+ end
43
55
  end
44
56
  end
45
57
  end
@@ -52,10 +64,10 @@ class StrongCSV
52
64
  if int == self
53
65
  ValueResult.new(value: int, original_value: value)
54
66
  else
55
- ValueResult.new(original_value: value, error_messages: ["`#{inspect}` is expected, but `#{int.inspect}` was given"])
67
+ ValueResult.new(original_value: value, error_messages: ["`#{inspect}` is expected, but `#{SafeInspect.render(int)}` was given"])
56
68
  end
57
69
  rescue ArgumentError, TypeError
58
- ValueResult.new(original_value: value, error_messages: ["`#{value.inspect}` can't be casted to Integer"])
70
+ ValueResult.new(original_value: value, error_messages: ["`#{SafeInspect.render(value)}` can't be casted to Integer"])
59
71
  end
60
72
  end
61
73
 
@@ -67,10 +79,10 @@ class StrongCSV
67
79
  if float == self
68
80
  ValueResult.new(value: float, original_value: value)
69
81
  else
70
- ValueResult.new(original_value: value, error_messages: ["`#{inspect}` is expected, but `#{float.inspect}` was given"])
82
+ ValueResult.new(original_value: value, error_messages: ["`#{inspect}` is expected, but `#{SafeInspect.render(float)}` was given"])
71
83
  end
72
84
  rescue ArgumentError, TypeError
73
- ValueResult.new(original_value: value, error_messages: ["`#{value.inspect}` can't be casted to Float"])
85
+ ValueResult.new(original_value: value, error_messages: ["`#{SafeInspect.render(value)}` can't be casted to Float"])
74
86
  end
75
87
  end
76
88
 
@@ -78,25 +90,33 @@ class StrongCSV
78
90
  # @param value [Object] Value to be casted to Range
79
91
  # @return [ValueResult]
80
92
  def cast(value)
81
- return ValueResult.new(original_value: value, error_messages: ["`#{value.inspect}` can't be casted to the beginning of `#{inspect}`"]) if value.nil?
82
-
83
- casted = case self.begin
84
- when ::Float
85
- Float(value)
86
- when ::Integer
87
- Integer(value)
88
- when ::String
89
- value
90
- else
91
- raise TypeError, "#{self.begin.class} is not supported"
92
- end
93
- if cover?(casted)
93
+ return failure(value) if value.nil?
94
+
95
+ begin
96
+ casted = case self.begin
97
+ when ::Float then Float(value)
98
+ when ::Integer then Integer(value)
99
+ when ::String then value
100
+ else raise UnsupportedBeginType, "#{self.begin.class} is not supported"
101
+ end
102
+ within = cover?(casted)
103
+ rescue UnsupportedBeginType
104
+ raise
105
+ rescue ArgumentError, Encoding::CompatibilityError, RangeError, TypeError
106
+ return failure(value)
107
+ end
108
+
109
+ if within
94
110
  ValueResult.new(value: casted, original_value: value)
95
111
  else
96
- ValueResult.new(original_value: value, error_messages: ["`#{casted.inspect}` is not within `#{inspect}`"])
112
+ ValueResult.new(original_value: value, error_messages: ["`#{SafeInspect.render(casted)}` is not within `#{inspect}`"])
97
113
  end
98
- rescue ArgumentError
99
- ValueResult.new(original_value: value, error_messages: ["`#{value.inspect}` can't be casted to the beginning of `#{inspect}`"])
114
+ end
115
+
116
+ private
117
+
118
+ def failure(value)
119
+ ValueResult.new(original_value: value, error_messages: ["`#{SafeInspect.render(value)}` can't be casted to the beginning of `#{inspect}`"])
100
120
  end
101
121
  end
102
122
 
@@ -107,7 +127,7 @@ class StrongCSV
107
127
  if self == value
108
128
  ValueResult.new(value: self, original_value: value)
109
129
  else
110
- ValueResult.new(original_value: value, error_messages: ["`#{inspect}` is expected, but `#{value.inspect}` was given"])
130
+ ValueResult.new(original_value: value, error_messages: ["`#{inspect}` is expected, but `#{SafeInspect.render(value)}` was given"])
111
131
  end
112
132
  end
113
133
  end
@@ -116,13 +136,15 @@ class StrongCSV
116
136
  # @param value [Object] Value to be casted to String
117
137
  # @return [ValueResult]
118
138
  def cast(value)
119
- return ValueResult.new(original_value: value, error_messages: ["`#{value.inspect}` can't be casted to String"]) if value.nil?
139
+ return ValueResult.new(original_value: value, error_messages: ["`#{SafeInspect.render(value)}` can't be casted to String"]) unless value.is_a?(::String)
120
140
 
121
141
  case Literal.regexp_match(self, value)
122
142
  when :timeout
123
143
  ValueResult.new(original_value: value, error_messages: ["`#{inspect}` matching timed out"])
144
+ when :incompatible_encoding
145
+ ValueResult.new(original_value: value, error_messages: ["`#{SafeInspect.render(value)}` can't be matched against `#{inspect}` because of incompatible encodings"])
124
146
  when nil
125
- ValueResult.new(original_value: value, error_messages: ["`#{value.inspect}` did not match `#{inspect}`"])
147
+ ValueResult.new(original_value: value, error_messages: ["`#{SafeInspect.render(value)}` did not match `#{inspect}`"])
126
148
  else
127
149
  ValueResult.new(value: value, original_value: value)
128
150
  end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ class StrongCSV
4
+ module Types
5
+ # Builds bounded, log-safe representations of untrusted values for error messages.
6
+ #
7
+ # Use it whenever a cell value is interpolated into an error message.
8
+ #
9
+ # ```ruby
10
+ # SafeInspect.render("\u202Eevil") # => "\"\\u202Eevil\""
11
+ # ```
12
+ module SafeInspect
13
+ MAX_LENGTH = 256
14
+ INVISIBLE_PATTERN = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\u034F\u115F\u1160\u17B4\u17B5\u180B-\u180E\u3164\u{13430}-\u{1343F}\uFE00-\uFE0F\uFFA0\u{E0100}-\u{E01EF}]/.freeze
15
+ private_constant :INVISIBLE_PATTERN
16
+
17
+ class << self
18
+ # @param value [Object]
19
+ # @return [String] A bounded, escaped representation of the value.
20
+ def render(value)
21
+ text, truncated = inspect_value(value)
22
+ text = "#{text}..." if truncated
23
+ text.gsub(INVISIBLE_PATTERN) { |char| escape(char) }
24
+ end
25
+
26
+ private
27
+
28
+ def inspect_value(value)
29
+ if value.is_a?(::String)
30
+ [normalize(value[0, MAX_LENGTH].inspect), value.length > MAX_LENGTH]
31
+ else
32
+ normalized = normalize(value.inspect)
33
+ [normalized[0, MAX_LENGTH], normalized.length > MAX_LENGTH]
34
+ end
35
+ end
36
+
37
+ def normalize(string)
38
+ string.encode(::Encoding::UTF_8, invalid: :replace, undef: :replace)
39
+ end
40
+
41
+ def escape(char)
42
+ codepoint = char.ord
43
+ codepoint > 0xFFFF ? format("\\u{%X}", codepoint) : format("\\u%04X", codepoint)
44
+ end
45
+ end
46
+ end
47
+ end
48
+ end
@@ -15,11 +15,11 @@ class StrongCSV
15
15
  # @param value [Object] Value to be casted to Boolean
16
16
  # @return [ValueResult]
17
17
  def cast(value)
18
- return ValueResult.new(original_value: value, error_messages: ["`#{value.inspect}` can't be casted to String"]) if value.nil?
18
+ return ValueResult.new(original_value: value, error_messages: ["`#{SafeInspect.render(value)}` can't be casted to String"]) if value.nil?
19
19
 
20
20
  casted = String(value)
21
21
  if @within && !@within.cover?(casted.size)
22
- ValueResult.new(original_value: value, error_messages: ["The length of `#{value.inspect}` is out of range `#{@within.inspect}`"])
22
+ ValueResult.new(original_value: value, error_messages: ["The length of `#{SafeInspect.render(value)}` is out of range `#{@within.inspect}`"])
23
23
  else
24
24
  ValueResult.new(value: casted, original_value: value)
25
25
  end
@@ -40,7 +40,7 @@ class StrongCSV
40
40
  private
41
41
 
42
42
  def failure(value)
43
- ValueResult.new(original_value: value, error_messages: ["`#{value.inspect}` can't be casted to Time with the format `#{@format.inspect}`"])
43
+ ValueResult.new(original_value: value, error_messages: ["`#{SafeInspect.render(value)}` can't be casted to Time with the format `#{@format.inspect}`"])
44
44
  end
45
45
 
46
46
  def parsed_valid?(parsed)
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  class StrongCSV
4
- VERSION = "0.9.0"
4
+ VERSION = "0.10.0"
5
5
  end
data/lib/strong_csv.rb CHANGED
@@ -7,6 +7,7 @@ require "time"
7
7
 
8
8
  require_relative "strong_csv/version"
9
9
  require_relative "strong_csv/value_result"
10
+ require_relative "strong_csv/types/safe_inspect"
10
11
  require_relative "strong_csv/types/base"
11
12
  require_relative "strong_csv/types/boolean"
12
13
  require_relative "strong_csv/types/float"
@@ -39,9 +40,16 @@ require_relative "strong_csv/row"
39
40
  class StrongCSV
40
41
  class Error < StandardError; end
41
42
 
43
+ # Raised when the CSV header does not contain every declared column exactly once.
44
+ class HeaderError < Error; end
45
+
46
+ # Raised when `pick` is used with an input that cannot be rewound.
47
+ class NotSeekableError < Error; end
48
+
42
49
  def initialize(&block)
43
50
  @let = Let.new
44
51
  @let.instance_eval(&block) if block_given?
52
+ @let.validate_declarations
45
53
  end
46
54
 
47
55
  # @param csv [String, IO]
@@ -52,14 +60,26 @@ class StrongCSV
52
60
  options = options.merge(headers: @let.headers, header_converters: :symbol)
53
61
  csv = CSV.new(csv, **options)
54
62
 
55
- @let.pick_all(csv)
63
+ picked = @let.pick_all(csv)
64
+
65
+ header_checked = false
66
+ each_row = lambda do |row|
67
+ unless header_checked
68
+ @let.validate_headers(csv.headers)
69
+ header_checked = true
70
+ end
71
+ Row.new(row: row, types: @let.types, lineno: csv.lineno)
72
+ end
56
73
 
57
- if block_given?
58
- csv.each do |row|
59
- yield Row.new(row: row, types: @let.types, lineno: csv.lineno)
74
+ result = @let.with_picked(picked) do
75
+ if block_given?
76
+ csv.each { |row| yield each_row.call(row) }
77
+ else
78
+ csv.map { |row| each_row.call(row) }
60
79
  end
61
- else
62
- csv.map { |row| Row.new(row: row, types: @let.types, lineno: csv.lineno) }
63
80
  end
81
+
82
+ @let.validate_headers(csv.headers) unless header_checked
83
+ result
64
84
  end
65
85
  end
data/sig/strong_csv.rbs CHANGED
@@ -24,7 +24,7 @@ class StrongCSV
24
24
 
25
25
  attr_reader error_messages: Array[::String]?
26
26
 
27
- def initialize: (original_value: ::String | nil, ?value: (casted | ::Object)?, ?error_messages: Array[::String]?) -> void
27
+ def initialize: (original_value: untyped, ?value: (casted | ::Object)?, ?error_messages: Array[::String]?) -> void
28
28
 
29
29
  def value: -> ((casted | ::Object | nil)?)
30
30
 
@@ -32,6 +32,12 @@ class StrongCSV
32
32
  end
33
33
 
34
34
  module Types
35
+ module SafeInspect
36
+ MAX_LENGTH: Integer
37
+
38
+ def self.render: (untyped) -> ::String
39
+ end
40
+
35
41
  class Base
36
42
  def cast: (untyped _value) -> bot
37
43
  end
@@ -68,7 +74,7 @@ class StrongCSV
68
74
 
69
75
  def self.regexp_with_timeout: (::Regexp) -> ::Regexp
70
76
 
71
- def self.regexp_match: (::Regexp, untyped) -> (::Integer | nil | :timeout)
77
+ def self.regexp_match: (::Regexp, ::String) -> (::Integer | nil | :timeout | :incompatible_encoding)
72
78
 
73
79
  def cast: (untyped value) -> ValueResult
74
80
  | (untyped value) -> ValueResult
@@ -111,7 +117,7 @@ class StrongCSV
111
117
  end
112
118
 
113
119
  class Let
114
- @picked: Hash[untyped, untyped]
120
+ @picked_key: Symbol
115
121
  @picker_columns: Hash[untyped, column]
116
122
 
117
123
  attr_reader types: Array[TypeWrapper]
@@ -124,7 +130,13 @@ class StrongCSV
124
130
 
125
131
  def pick: (column, as: ::Symbol) { (Array[::String]) -> untyped } -> void
126
132
 
127
- def pick_all: (untyped) -> void
133
+ def pick_all: (untyped) -> Hash[untyped, untyped]
134
+
135
+ def with_picked: [T] (Hash[untyped, untyped]) { () -> T } -> T
136
+
137
+ def validate_declarations: -> void
138
+
139
+ def validate_headers: (untyped) -> void
128
140
 
129
141
  def integer: (**untyped) -> Types::Integer
130
142
 
@@ -150,6 +162,16 @@ class StrongCSV
150
162
 
151
163
  private
152
164
 
165
+ def picked: -> Hash[untyped, untyped]
166
+
167
+ def rewind!: (untyped) -> void
168
+
169
+ def header_errors: (untyped) -> Array[::String]
170
+
171
+ def required_columns: -> Array[::Symbol]
172
+
173
+ def error_messages: (Array[::Symbol], Array[::Symbol]) -> Array[::String]
174
+
153
175
  def validate_columns: -> bool
154
176
  end
155
177
 
@@ -177,4 +199,10 @@ class StrongCSV
177
199
 
178
200
  class Error < StandardError
179
201
  end
202
+
203
+ class HeaderError < Error
204
+ end
205
+
206
+ class NotSeekableError < Error
207
+ end
180
208
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: strong_csv
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.9.0
4
+ version: 0.10.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Yutaka Kamei
@@ -47,6 +47,7 @@ extra_rdoc_files: []
47
47
  files:
48
48
  - LICENSE
49
49
  - README.md
50
+ - SECURITY.md
50
51
  - lib/strong_csv.rb
51
52
  - lib/strong_csv/let.rb
52
53
  - lib/strong_csv/row.rb
@@ -57,6 +58,7 @@ files:
57
58
  - lib/strong_csv/types/integer.rb
58
59
  - lib/strong_csv/types/literal.rb
59
60
  - lib/strong_csv/types/optional.rb
61
+ - lib/strong_csv/types/safe_inspect.rb
60
62
  - lib/strong_csv/types/string.rb
61
63
  - lib/strong_csv/types/time.rb
62
64
  - lib/strong_csv/types/union.rb
@@ -83,7 +85,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
83
85
  - !ruby/object:Gem::Version
84
86
  version: '0'
85
87
  requirements: []
86
- rubygems_version: 3.6.9
88
+ rubygems_version: 4.0.20
87
89
  specification_version: 4
88
90
  summary: Type check CSV objects
89
91
  test_files: []