xlsxrb 0.2.1 → 0.2.2

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 (45) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +51 -0
  3. data/README.md +24 -2
  4. data/lib/xlsxrb/dsl_helpers.rb +16 -0
  5. data/lib/xlsxrb/elements/styles.rb +15 -6
  6. data/lib/xlsxrb/number_formatter.rb +26 -8
  7. data/lib/xlsxrb/ooxml/cfb.rb +11 -3
  8. data/lib/xlsxrb/ooxml/crypto/agile.rb +48 -10
  9. data/lib/xlsxrb/ooxml/crypto/standard.rb +5 -1
  10. data/lib/xlsxrb/ooxml/crypto.rb +3 -0
  11. data/lib/xlsxrb/ooxml/shared_strings_parser.rb +26 -8
  12. data/lib/xlsxrb/ooxml/workbook_writer.rb +30 -19
  13. data/lib/xlsxrb/ooxml/worksheet_parser.rb +116 -12
  14. data/lib/xlsxrb/ooxml/worksheet_writer.rb +43 -38
  15. data/lib/xlsxrb/ooxml/writer/drawing_xml.rb +206 -201
  16. data/lib/xlsxrb/ooxml/writer/features_xml.rb +99 -99
  17. data/lib/xlsxrb/ooxml/writer/styles_xml.rb +46 -46
  18. data/lib/xlsxrb/ooxml/writer.rb +166 -159
  19. data/lib/xlsxrb/ooxml/xml_builder.rb +17 -7
  20. data/lib/xlsxrb/ooxml/xml_parser.rb +34 -1
  21. data/lib/xlsxrb/ooxml/zip_reader.rb +95 -68
  22. data/lib/xlsxrb/ooxml/zip_writer.rb +16 -0
  23. data/lib/xlsxrb/stream_sheet.rb +26 -11
  24. data/lib/xlsxrb/stream_writer.rb +9 -6
  25. data/lib/xlsxrb/version.rb +1 -1
  26. data/lib/xlsxrb/worksheet_builder.rb +6 -5
  27. data/lib/xlsxrb.rb +68 -21
  28. data/sig/generated/xlsxrb/dsl_helpers.rbs +9 -0
  29. data/sig/generated/xlsxrb/elements/styles.rbs +5 -0
  30. data/sig/generated/xlsxrb/number_formatter.rbs +7 -0
  31. data/sig/generated/xlsxrb/ooxml/cfb.rbs +2 -0
  32. data/sig/generated/xlsxrb/ooxml/crypto/agile.rbs +10 -0
  33. data/sig/generated/xlsxrb/ooxml/shared_strings_parser.rbs +7 -0
  34. data/sig/generated/xlsxrb/ooxml/workbook_writer.rbs +8 -0
  35. data/sig/generated/xlsxrb/ooxml/worksheet_parser.rbs +40 -0
  36. data/sig/generated/xlsxrb/ooxml/writer.rbs +4 -0
  37. data/sig/generated/xlsxrb/ooxml/xml_builder.rbs +7 -2
  38. data/sig/generated/xlsxrb/ooxml/xml_parser.rbs +10 -0
  39. data/sig/generated/xlsxrb/ooxml/zip_reader.rbs +12 -1
  40. data/sig/generated/xlsxrb/ooxml/zip_writer.rbs +8 -0
  41. data/sig/generated/xlsxrb/stream_sheet.rbs +9 -0
  42. data/sig/generated/xlsxrb/stream_writer.rbs +6 -2
  43. data/sig/generated/xlsxrb/worksheet_builder.rbs +3 -1
  44. data/sig/generated/xlsxrb.rbs +38 -8
  45. metadata +9 -3
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 6eed4936f201a7a8a3090b4d1ca8cb4609992b663565f94cb66e62137adc1def
4
- data.tar.gz: 733afe59d5c49dddcc508fb4fe8db66e2c41bec971c7a057debebd2b5f6c9dbd
3
+ metadata.gz: 126fcecf7b280d0b6b978cfb12151e67da9d54289718f71a0bdd91186cc810d7
4
+ data.tar.gz: da5c941c4a66c43c3ab7471d68784549ffcdaaf65ac865449b6d73b30aae0104
5
5
  SHA512:
6
- metadata.gz: 31a5bc6068cf43cc0d878cc3232cecfcab8e4669e2a36435752ec212ba70a204813f0e1b216817e81397f5ed5f56973f9a1ea8e2a91c5b6bcbcb61141bf11482
7
- data.tar.gz: 9e1614094509557f10679da61b2fc58b2abf21f2853472479ce424adc35da304e509a1094144cb1b8c28d8ca40b3e1da031a290fa594bd04042120c9cf59e9e9
6
+ metadata.gz: d00259b8db777c33f123b8c9bcc5a3a34121c99c780171aca78c557e08d796fc016d6340cb4ffa551af21447be0bb69dc86a067bc3469422429d65e213441d47
7
+ data.tar.gz: a962faf4eb6892ed08135dc0de71451a77661c70c6da688b606eff8ab090ab948362b671277033d0e3f45266f85d4accbe6d3d2bd3f9b191035529c1054118c5
data/CHANGELOG.md CHANGED
@@ -1,3 +1,54 @@
1
+ ## [0.2.2] - 2026-11-23
2
+
3
+ ### Added
4
+ - Add `Xlsxrb.truncate_cell_text`, which cuts text to what a cell holds: 32,767 characters counted in UTF-16 code units, as Excel counts them ([ADR 0011](docs/adr/0011-count-excel-text-limits-as-excel-does.md)). A character is never split, so 20,000 emoji become 16,383. `strict_excel_mode` raises `ArgumentError` for longer text; callers that want to keep the start of the text instead can call this for every cell. Text of 32,767 bytes or fewer is returned as is without being counted.
5
+
6
+ ### Deprecated
7
+ - `encryption_mode: :standard` in `Xlsxrb.write` is deprecated and warns; pass `encryption_mode: :agile` ([ADR 0013](docs/adr/0013-write-agile-encryption-read-both.md)). Standard encryption is AES-128 in ECB mode with no check that the file is unchanged, and Agile encryption, which Excel 2010 and later open, is AES-256 with one. In version 0.3.0 `:standard` raises `ArgumentError`, and a password without `encryption_mode:` writes Agile encryption instead of Standard; that change of default gives no warning. Files with either scheme are still read.
8
+ - Passing xlsx data as a String to `Xlsxrb.load` and `Xlsxrb.read` is deprecated and warns; pass a stream, as in `Xlsxrb.load(StringIO.new(data))` ([ADR 0012](docs/adr/0012-the-argument-fixes-what-a-string-means.md)). A String is read as data when it looks like xlsx data and as a file path otherwise, so a program that passes on an uploaded workbook as a String can be made to open a file on the server. In version 0.3.0 a String is always a file path.
9
+
10
+ ### Security
11
+ - Check the HMAC of a file encrypted with Agile encryption when reading it, and raise `Xlsxrb::DecryptionError` if the encrypted package does not match it or the file has none. The HMAC was not read at all, so a file changed after it was encrypted could be read without an error. Files written by xlsxrb 0.2.1 and earlier, whose HMAC was computed differently (see Fixed), are still read and checked against that HMAC.
12
+ - Raise `Xlsxrb::ZipError` for a ZIP entry whose declared size runs past the end of the archive, in `Xlsxrb.load`, `Xlsxrb.read`, and `Ooxml::ZipReader`. The size was passed to `IO#read` as the length to read: a 150-byte file declaring 4 GB made Ruby allocate over 1 GB before failing with `Errno::EINVAL`, and a ZIP64 size of 2**62 raised `NoMemoryError`, which `rescue StandardError` does not catch.
13
+ - Stop holding the inflated data of every entry in memory when reading an archive that has no central directory and uses data descriptors. Each entry is inflated to find where it ends, and the output was kept until the reader was closed, so `max_uncompressed_size` (500 MB by default) bounded one entry but not their total: a 2 MB file could hold 2 GB. Such an entry is now inflated once to measure it, without keeping the output, and again when it is read. Its `Entry#compressed_size` and `Entry#crc32` now hold the compressed size and the CRC-32 from the data descriptor instead of the uncompressed size and 0.
14
+ - Raise `Xlsxrb::Error` for an encrypted file (CFB) whose DIFAT lists the same FAT sector more than once. Every listing loaded the sector again, so a 529 KB file given to `Xlsxrb.load` with a password used 1.2 GB, and the use grew in proportion to the file.
15
+ - Raise `Xlsxrb::DecryptionError` for Agile encryption whose `hashSize` differs from the digest length. The password check compared only `hashSize` bytes, so `hashSize="0"` accepted any password; the package was then decrypted with the wrong key into unusable bytes rather than reported as a wrong password.
16
+ - Stop reading a String given to `background_image=` as a file path ([ADR 0012](docs/adr/0012-the-argument-fixes-what-a-string-means.md)). A String that named an existing file was replaced by that file's bytes, which were written into the workbook as the background image without being checked to be an image. A program that passed on an uploaded image as a String could be given text such as `/srv/app/config/secret.txt` and would put that file into the workbook it returned. A String is now always the image itself. To use a file, pass its bytes: `sheet.background_image = { data: File.binread(path), ext: "jpg" }`. This changes a documented behavior in a patch release, as the deprecation policy allows for severe harm; callers that passed a path get a background that is not an image until they change the call.
17
+ - Raise `ArgumentError` when writing an image or background image whose `ext` is not 1 to 10 letters and digits. The extension was written as given into the ZIP entry name, the relationship target, and `[Content_Types].xml`, so an extension taken from an uploaded file name, such as `png/../../../evil`, produced the entry `xl/media/image1.png/../../../evil`, and one containing `"/>` added relationships to the drawing's relationship part.
18
+ - Raise `Xlsxrb::ZipError` from `Ooxml::ZipWriter` for entry names that are empty, start with `/`, contain a `..` segment, a backslash, or a control character. A program that extracts the archive could write such an entry outside its target directory.
19
+ - Escape the `ref` and shared index of array and shared formulas, a row's `outline_level`, the `tint` of rich text colors, and the `id`, `parent_id`, and `timestamp` of threaded comments when writing them as XML attributes. A value containing `"` ended the attribute, so the rest of the value was written as further attributes or elements. A threaded comment `id` read from a file was written back the same way.
20
+ - Escape every option value written as an XML attribute by the workbook, styles, drawing, chart, table, and pivot table writers, and the font options of rich text. More than 500 values were written as given, among them a chart data point `idx`, a pivot table source range, `ref`, and `subtotal`, and a rich text font `size`, `underline`, `vert_align`, and color `theme`. A value containing `"` ended the attribute, so the rest of it was written as further attributes or elements, and one containing `<` or `&` made the part not well-formed. Custom document properties of type `:number`, `:float`, and `:date` are escaped as text in the same way. Values without these characters are written as before.
21
+ - Escape the `ref` and `type` of a cell given to `Ooxml::WorksheetWriter#write_row` as a Hash. They were written into the `r` and `t` attributes of the cell as given, so a value containing `"` could add attributes or elements to the worksheet. The builder and the stream writer do not pass these keys, so only a caller of the private writer was affected.
22
+ - Write a style id into the `s` attribute of a row or cell only when it is an Integer. `Ooxml::WorksheetWriter` wrote the value it found in the style map as given, so a map holding a String containing `"` could add attributes or elements to the worksheet. The builder and the stream writer fill the map with Integers, so only a caller of the private writer was affected.
23
+ - Remove characters that XML 1.0 cannot hold, such as U+0001 and U+FFFE, from attribute values and text written through `Ooxml::XmlBuilder`: hyperlink targets and tooltips, table and column names, defined names, headers and footers, data validation messages, number formats, and document properties. One such character made the part not well-formed, so the file could not be opened. Cell text is unchanged; it keeps these characters as `_xHHHH_`.
24
+ - Fix `Xlsxrb.load`, `StreamSheet#hyperlinks`, and `StreamSheet#load` never returning for a sheet in which the word `hyperlink` appears outside a tag after `<hyperlinks>`, as in `<hyperlinks>hyperlink</hyperlinks>`. The scan returned to the same position forever, and with a `ref` attribute on the enclosing tag it also added an entry on every pass until memory ran out.
25
+ - Read date format codes that contain `%` as literal text in `Cell#formatted_value`, `Row#formatted_values`, and `Xlsxrb.format_value`. The `%` reached `Time#strftime` as a directive, so a format code such as `yyyy%999999d` produced 1 MB of text per cell, and a 3.5 KB file could ask for 1 GB from one call.
26
+ - Raise `Xlsxrb::ParseError` for XML parts whose elements nest more than 256 levels deep. REXML's SAX2 parser takes time proportional to the depth for every tag: 20,000 nested elements (a 2.5 KB file) took 15 seconds in `Xlsxrb.read` and `Xlsxrb.load`, and 40,000 took 58 seconds.
27
+ - Raise `Xlsxrb::ParseError` for a row whose last `<c>` or `<is>` start tag has no end tag. The cell pattern searched to the end of the row once for each such tag, so a row of 40,000 unclosed `<c>` tags (a 3 KB file) took over 100 seconds to read. A `<c>` start tag without an end tag was read as an empty cell before.
28
+ - Read shared strings in time proportional to the part. An `<si>` without `<t>`, and a `<t>` in a string table that has `<rPh>` elements, each searched the rest of the part, so 100,000 empty `<si>` elements (a 4 KB file) took over 60 seconds before the first sheet was read.
29
+ - Find streamed rows in time proportional to the sheet when a row, or markup between rows, spans many chunks. Each 64 KB chunk searched the whole buffer again: 16 MB of elements whose names start with `row` (a 27 KB file) took over 60 seconds, and that buffer had no size limit. Rows and tags over 50 MB now raise `Xlsxrb::ParseError` on every path (it was `ArgumentError`, for unclosed rows only).
30
+ - Raise `Xlsxrb::ParseError` for a row number above 1,048,576, Excel's last row. The number was built digit by digit into an Integer of any size (400,000 digits took over 20 seconds), and `pad_empty_rows: true` yielded one empty row for every number below it.
31
+ - Read cell values of more than 400 characters as text, or raise `Xlsxrb::ParseError` when the cell is typed as a number, instead of converting them to a number. Converting 16 million digits (an 18 KB file) to an Integer took over 20 seconds. Shorter values are read as before. A shared string index that is negative or longer than 10 digits reads as an empty string instead of the last string or `RangeError`.
32
+ - Stop `StreamSheet#dimension`, `#row_range`, and `#column_range` after the first 1 MB of a sheet that has neither `<dimension>` nor `<sheetData>`. They searched everything read so far again for each chunk, so a 16 MB sheet (a 19 KB file) took 19 seconds.
33
+ - Format numbers as General for format codes longer than 1,024 characters (Excel accepts 255). The time to format grows with the code for every cell that uses it.
34
+ - Require rexml 3.4.2 or later (was `~> 3.0`), the first version without the denial of service in parsing XML that has multiple XML declarations (CVE-2025-58767). Earlier 3.x versions have further known denial-of-service advisories.
35
+ - Raise `ArgumentError` for a chart series `type` that is not a known chart type and for a shape color transform whose `type` is not a DrawingML color transform. Both are written as element names: a series type was written as given, so one containing `>` added elements to the chart part, and a transform type was only escaped as text. The `val` of a transform and the alpha of a color are escaped as attribute values.
36
+
37
+ ### Fixed
38
+ - Write the HMAC that the specification describes ([MS-OFFCRYPTO] 2.3.4.14) for `encryption_mode: :agile`: over the encrypted package, with its key and value encrypted under the package key. It was computed over the package before encryption and encrypted under keys derived from the password, so a reader that checks the HMAC found every such file changed. Excel 16.115 for Mac and Apache POI 5.2.5 open files written either way.
39
+ - Read an encrypted file whose last sector is shorter than a sector. Excel 2007 ends some files where the last stream ends, without padding; the short sector was dropped, so the encrypted package came out truncated and decryption failed with `Xlsxrb::DecryptionError`.
40
+ - Read a file with Standard encryption that has bytes after the encrypted package. Only the blocks that hold the package are decrypted now; trailing bytes that were not a whole AES block made decryption fail. A package shorter than its declared size raises `Xlsxrb::DecryptionError` instead of being returned truncated.
41
+ - Raise `Xlsxrb::ZipError` for corrupt deflate data and for compression methods other than stored and deflate. These raised `Zlib::DataError` or `Zlib::BufError`, which code that rescues `Xlsxrb::Error` does not catch, and reading an entry with an unsupported compression method through `ZipReader#open_entry_io` returned no data without an error. An archive that ends inside a local file header no longer raises `NoMethodError`.
42
+ - Replace invalid UTF-16 in a part with U+FFFD instead of raising `Encoding::InvalidByteSequenceError`.
43
+ - Raise `Xlsxrb::DecryptionError` for encrypted packages with salts, keys, or ciphertext of the wrong length or invalid Base64. These raised `OpenSSL::Cipher::CipherError` or `ArgumentError`, which code that rescues `Xlsxrb::Error` does not catch.
44
+ - Raise `Xlsxrb::ParseError` for malformed XML and exceeded entity expansion limits in a part, instead of `REXML::ParseException` and `RuntimeError`. Code that rescues `RuntimeError` for these no longer catches them.
45
+ - Return the General form when formatting Infinity or NaN, or a date serial number outside Excel's range, with a format code, instead of raising `FloatDomainError` or `ArgumentError`.
46
+ - Decode each XML entity once in cell text, formulas, and attribute values. The predefined entities were decoded before the numeric ones, so `&amp;#60;`, which is the text `&#60;`, was read as `<`, and `&amp;lt;` written as `&#38;lt;` was read as `<` as well.
47
+ - Read encrypted files stored as version 4 compound files, which have 4,096-byte sectors. The first sector was taken to start 512 bytes into the file, as in version 3, instead of 4,096, so no stream was found and decryption failed.
48
+ - Read bytes that are not UTF-8 in an XML part as U+FFFD. `Xlsxrb.load`, `StreamSheet#dimension`, and reading relationships raised `ArgumentError`, and `Xlsxrb.read` returned cell text that was not valid UTF-8, which raised when it was written or matched. A part that is not well-formed because of such bytes raises `Xlsxrb::ParseError`.
49
+ - Read a cell style index or a parent style (`xfId`) outside the style table as no style. One too large for a machine word raised `RangeError` in `Cell#formatted_value` and `Row#formatted_values`, and a negative `xfId` took the parent counted from the end of the table.
50
+ - Raise the decryption error for an encrypted workbook given as a stream. An error while decrypting, such as `Xlsxrb::InvalidPasswordError` for a wrong password, was discarded, and reading went on to raise `Xlsxrb::ZipError` for the encrypted bytes. A String source was not affected.
51
+
1
52
  ## [0.2.1] - 2026-11-16
2
53
 
3
54
  ### Changed
data/README.md CHANGED
@@ -92,6 +92,26 @@ Xlsxrb.read("large_file.xlsx") do |sheet|
92
92
  end
93
93
  ```
94
94
 
95
+ ### Reading from a File or from Memory
96
+
97
+ `Xlsxrb.read` and `Xlsxrb.load` take the workbook from a file path or from a stream:
98
+
99
+ | Source | Pass | Example |
100
+ | :--- | :--- | :--- |
101
+ | A file | Its path, as a String | `Xlsxrb.load("workbook.xlsx")` |
102
+ | xlsx data in memory, such as an upload | A stream (an IO) | `Xlsxrb.load(StringIO.new(data))` |
103
+ | An open file | The IO | `File.open("workbook.xlsx", "rb") { \|file\| Xlsxrb.load(file) }` |
104
+
105
+ ```ruby
106
+ require "xlsxrb"
107
+ require "stringio"
108
+
109
+ # In a web application: read the uploaded workbook, not a file named by the upload.
110
+ workbook = Xlsxrb.load(StringIO.new(params[:file].read))
111
+ ```
112
+
113
+ A String is a file path. Passing xlsx data as a String still works in 0.2 and warns: xlsxrb tells the two apart by the content of the String, so data that someone else supplied can be made to name a file on the machine instead ([ADR 0012](docs/adr/0012-the-argument-fixes-what-a-string-means.md)). From 0.3.0 a String is always a path. A path that comes from someone you do not trust opens whatever it names; check it before passing it, as with `File.open`.
114
+
95
115
  ### Streaming Write (Low Memory)
96
116
 
97
117
  Pipes row and cell XML directly to the archive without buffering rows in memory:
@@ -192,13 +212,13 @@ puts "Formulas: #{sheet.rows.flat_map(&:cells).select(&:formula?).map { |c| [c.r
192
212
 
193
213
  ### Password Protection & Encryption ([MS-OFFCRYPTO])
194
214
 
195
- Natively supports reading and writing encrypted XLSX files (Standard & Agile Encryption) with zero external C-extensions:
215
+ Reads files encrypted with Standard or Agile encryption and writes encrypted files, without external C extensions:
196
216
 
197
217
  ```ruby
198
218
  require "xlsxrb"
199
219
 
200
220
  # Write password-protected file
201
- Xlsxrb.write("confidential.xlsx", password: "SecretPassword123") do |writer|
221
+ Xlsxrb.write("confidential.xlsx", password: "SecretPassword123", encryption_mode: :agile) do |writer|
202
222
  writer.sheet("Financials") { |sheet| sheet.row(["Assets", 5_000_000]) }
203
223
  end
204
224
 
@@ -208,6 +228,8 @@ Xlsxrb.read("confidential.xlsx", password: "SecretPassword123") do |sheet|
208
228
  end
209
229
  ```
210
230
 
231
+ `encryption_mode: :agile` writes AES-256 with a check that the file is unchanged, which Excel 2010 and later open. Without it, 0.2 writes Standard encryption (AES-128, no such check); from 0.3.0 a password always writes Agile encryption, and `encryption_mode: :standard` warns in 0.2 and is an error from 0.3.0 ([ADR 0013](docs/adr/0013-write-agile-encryption-read-both.md)). Files with either scheme are read.
232
+
211
233
  ### Date and Time Handling
212
234
 
213
235
  Excel stores dates and times as serial numbers (days since 1900, with the time of day as the fraction) and marks them as dates only through the cell's number format. `cell.value` returns that serial number as an Integer or Float. To get dates back:
@@ -818,6 +818,22 @@ module Xlsxrb
818
818
  raise ArgumentError, "Cell text length #{length} exceeds Excel limit of 32,767 characters, counted in UTF-16 code units as Excel does"
819
819
  end
820
820
 
821
+ # Cuts +text+ to the whole characters that fit in a cell: 32,767 UTF-16 code units, as
822
+ # Excel counts them (ADR 0011). Text of 32,767 bytes or fewer always fits and is returned
823
+ # as is, so most text is not counted. Longer text is returned as a new UTF-8 String.
824
+ #
825
+ # @param text [String]
826
+ # @return [String]
827
+ #: (String text) -> String
828
+ def self.truncate_cell_text(text)
829
+ return text if text.bytesize <= MAX_CELL_TEXT_LENGTH
830
+
831
+ units = text.encode(Encoding::UTF_16LE).byteslice(0, MAX_CELL_TEXT_LENGTH * 2) #: String
832
+ # A cut between the two code units of a character leaves a lone high surrogate.
833
+ units = units.byteslice(0, units.bytesize - 2) unless units.valid_encoding? #: String
834
+ units.encode(Encoding::UTF_8)
835
+ end
836
+
821
837
  # Sanitizes a worksheet name to ensure it conforms to Excel constraints within 31 characters.
822
838
  # Replaces forbidden characters (\ / ? * [ ] : and control characters),
823
839
  # replaces leading/trailing apostrophes, and replaces reserved 'History' with 'History_'.
@@ -469,7 +469,7 @@ module Xlsxrb
469
469
  # @api public
470
470
  #: (Integer? style_index) -> String?
471
471
  def number_format(style_index)
472
- return nil unless style_index.is_a?(Integer) && style_index >= 0
472
+ return nil unless style_index?(style_index)
473
473
 
474
474
  precompute! unless @format_codes
475
475
  @format_codes[style_index]
@@ -482,7 +482,7 @@ module Xlsxrb
482
482
  # @api public
483
483
  #: (Integer? style_index) -> Symbol?
484
484
  def format_type(style_index)
485
- return nil unless style_index.is_a?(Integer) && style_index >= 0
485
+ return nil unless style_index?(style_index)
486
486
 
487
487
  precompute! unless @format_types
488
488
  @format_types[style_index]
@@ -495,7 +495,7 @@ module Xlsxrb
495
495
  # @api public
496
496
  #: (Integer? style_index) -> bool
497
497
  def date_format?(style_index)
498
- return false unless style_index.is_a?(Integer) && style_index >= 0
498
+ return false unless style_index?(style_index)
499
499
 
500
500
  precompute! unless @date_flags
501
501
  @date_flags[style_index] || false
@@ -508,7 +508,7 @@ module Xlsxrb
508
508
  # @api public
509
509
  #: (Integer? style_index) -> bool
510
510
  def datetime_format?(style_index)
511
- return false unless style_index.is_a?(Integer) && style_index >= 0
511
+ return false unless style_index?(style_index)
512
512
 
513
513
  precompute! unless @datetime_flags
514
514
  @datetime_flags[style_index] || false
@@ -521,7 +521,7 @@ module Xlsxrb
521
521
  # @api public
522
522
  #: (Integer? style_index) -> bool
523
523
  def time_format?(style_index)
524
- return false unless style_index.is_a?(Integer) && style_index >= 0
524
+ return false unless style_index?(style_index)
525
525
 
526
526
  precompute! unless @time_flags
527
527
  @time_flags[style_index] || false
@@ -563,7 +563,9 @@ module Xlsxrb
563
563
  num_fmt_id = xf.is_a?(Elements::CellXf) ? xf.num_fmt_id : xf[:num_fmt_id]
564
564
  xf_id = xf.is_a?(Elements::CellXf) ? xf.xf_id : xf[:xf_id]
565
565
  if (num_fmt_id.nil? || num_fmt_id.zero?) && xf_id && cs_xfs.is_a?(Array)
566
- parent_xf = cs_xfs[xf_id]
566
+ # An xfId outside the array names no parent. Array#[] would count a negative
567
+ # one from the end and raise RangeError for one that does not fit in a word.
568
+ parent_xf = xf_id.is_a?(Integer) && xf_id.between?(0, cs_xfs.size - 1) ? cs_xfs[xf_id] : nil
567
569
  if parent_xf.is_a?(Elements::CellXf)
568
570
  num_fmt_id = parent_xf.num_fmt_id
569
571
  elsif parent_xf.is_a?(Hash)
@@ -592,6 +594,13 @@ module Xlsxrb
592
594
 
593
595
  private
594
596
 
597
+ # Whether +value+ can be an index into cellXfs. A larger Integer is not one, and
598
+ # Array#[] raises RangeError for an Integer that does not fit in a machine word.
599
+ #: (untyped value) -> bool
600
+ def style_index?(value)
601
+ value.is_a?(Integer) && value.between?(0, 0x7FFFFFFF)
602
+ end
603
+
595
604
  def next_num_fmt_id
596
605
  max_id = [163, *number_formats.keys].max
597
606
  max_id + 1
@@ -17,6 +17,14 @@ module Xlsxrb
17
17
  "mm-dd-yy", "d-mmm-yy", "d-mmm", "mmm-yy", "h:mm AM/PM", "h:mm:ss AM/PM", "h:mm", "h:mm:ss", "m/d/yy h:mm", "mm:ss", "[h]:mm:ss", "mmss.0"
18
18
  ].freeze
19
19
 
20
+ # Excel accepts format codes of up to 255 characters. Longer codes are not applied: the
21
+ # cost of formatting grows with the code, for every cell that uses it.
22
+ MAX_FORMAT_CODE_LENGTH = 1024
23
+
24
+ # Stands for a literal "%" while a date format code is converted to a strftime pattern.
25
+ LITERAL_PERCENT = "\x01"
26
+ private_constant :LITERAL_PERCENT
27
+
20
28
  class << self
21
29
  # Formats a cell value according to an Excel format code string.
22
30
  #
@@ -32,17 +40,24 @@ module Xlsxrb
32
40
  return value ? "TRUE" : "FALSE" if [true, false].include?(value)
33
41
 
34
42
  code = format_code.to_s.strip
35
- return default_format(value) if code.empty? || code.casecmp("general").zero?
43
+ return default_format(value) if code.empty? || code.casecmp("general").zero? || code.length > MAX_FORMAT_CODE_LENGTH
44
+ # Infinity and NaN, from values such as 1e999, have no date or digits to format.
45
+ return value.to_s if value.is_a?(Float) && !value.finite?
36
46
 
37
47
  return format_datetime(value, code) if value.is_a?(Date) || value.is_a?(DateTime) || value.is_a?(Time)
38
48
 
39
49
  if value.is_a?(Numeric) && date_format?(code)
40
- dt = if value.is_a?(Float) && (value % 1).positive?
41
- Ooxml::Utils.serial_to_datetime(value, date1904: date1904)
42
- else
43
- Ooxml::Utils.serial_to_date(value.to_i, date1904: date1904)
44
- end
45
- return format_datetime(dt, code)
50
+ dt = begin
51
+ if value.is_a?(Float) && (value % 1).positive?
52
+ Ooxml::Utils.serial_to_datetime(value, date1904: date1904)
53
+ else
54
+ Ooxml::Utils.serial_to_date(value.to_i, date1904: date1904)
55
+ end
56
+ rescue ArgumentError, RangeError
57
+ # A serial number outside the dates Excel supports.
58
+ nil
59
+ end
60
+ return dt ? format_datetime(dt, code) : default_format(value)
46
61
  end
47
62
 
48
63
  return format_number(value, code) if value.is_a?(Numeric)
@@ -380,7 +395,9 @@ module Xlsxrb
380
395
  end
381
396
 
382
397
  def excel_to_strftime(format_code)
383
- code = format_code.dup
398
+ # A "%" in the format code is literal text. Left as is, it would be read by strftime
399
+ # as a directive, and "%999999d" asks for a field of 999,999 characters.
400
+ code = format_code.delete(LITERAL_PERCENT).gsub("%", LITERAL_PERCENT)
384
401
 
385
402
  code.gsub!(%r{am/pm}i, "%p")
386
403
  code.gsub!(%r{a/p}i, "%p")
@@ -421,6 +438,7 @@ module Xlsxrb
421
438
  code.gsub!(/yy/i, "%y")
422
439
 
423
440
  code.gsub!(/\\(.)/, "\\1")
441
+ code.gsub!(LITERAL_PERCENT, "%%")
424
442
 
425
443
  code
426
444
  end
@@ -125,12 +125,16 @@ module Xlsxrb
125
125
  @header_difat = @data[0x4C, 436].unpack("V109").reject { |s| [FREESECT, ENDOFCHAIN].include?(s) }
126
126
  end
127
127
 
128
+ # The header takes the first sector: 512 bytes in version 3, and 4,096 in version 4,
129
+ # where it is padded with zeros. Sector 0 follows it.
128
130
  def sector_offset(sector_id)
129
- 512 + (sector_id * @sector_size)
131
+ (sector_id + 1) * @sector_size
130
132
  end
131
133
 
132
134
  def read_sector(sector_id)
133
- max_sectors = (@data.bytesize - 512) / @sector_size
135
+ # The last sector may be shorter than a sector: Excel 2007 ends some files where
136
+ # the last stream ends, without padding.
137
+ max_sectors = ((@data.bytesize + @sector_size - 1) / @sector_size) - 1
134
138
  return "".b if sector_id.negative? || sector_id >= max_sectors
135
139
 
136
140
  offset = sector_offset(sector_id)
@@ -158,11 +162,15 @@ module Xlsxrb
158
162
  end
159
163
  end
160
164
 
161
- # Read all FAT sectors
165
+ # Read all FAT sectors. Each may be listed once: a DIFAT that repeats a sector
166
+ # would otherwise grow the FAT far beyond the size of the file.
162
167
  @fat = []
168
+ loaded = {}
163
169
  @difat_sectors.each do |fat_sec_id|
164
170
  break if [ENDOFCHAIN, FREESECT].include?(fat_sec_id)
171
+ raise Xlsxrb::Error, "Invalid CFB file: FAT sector #{fat_sec_id} is listed more than once" if loaded[fat_sec_id]
165
172
 
173
+ loaded[fat_sec_id] = true
166
174
  sec_data = read_sector(fat_sec_id)
167
175
  @fat.concat(sec_data.unpack("V*"))
168
176
  end
@@ -41,7 +41,10 @@ module Xlsxrb
41
41
  k_ver_val = derive_key(digest, h_final, BLOCK_KEY_VERIFIER_VALUE, key_bytes)
42
42
  decrypted_hash = aes_decrypt(cipher_name, k_ver_val, info[:encryptor_salt], info[:encrypted_verifier_hash_value])
43
43
 
44
+ # A hashSize shorter than the digest would compare fewer bytes, and 0 would accept
45
+ # any password.
44
46
  hash_size = info[:hash_size]
47
+ raise Xlsxrb::DecryptionError, "Invalid hashSize in EncryptionInfo: #{hash_size}" unless hash_size == digest.digest_length
45
48
  raise Xlsxrb::InvalidPasswordError, "Password verification failed" unless OpenSSL.secure_compare(decrypted_hash[0, hash_size], expected_hash[0, hash_size])
46
49
 
47
50
  # 3. Decrypt package master key
@@ -60,6 +63,9 @@ module Xlsxrb
60
63
  pkg_digest = digest_for(info[:key_data_hash_algorithm])
61
64
  pkg_salt = info[:key_data_salt]
62
65
 
66
+ # 5. Check the HMAC of the stream before decrypting it
67
+ intact = integrity_verified?(info, pkg_cipher_name, pkg_digest, package_key, encrypted_package_bytes)
68
+
63
69
  decrypted = +""
64
70
  num_blocks = (encrypted_data.bytesize + SEGMENT_SIZE - 1) / SEGMENT_SIZE
65
71
  num_blocks.times do |i|
@@ -70,7 +76,10 @@ module Xlsxrb
70
76
  decrypted << aes_decrypt_block(pkg_cipher_name, package_key, iv, chunk)
71
77
  end
72
78
 
73
- decrypted[0, total_size] || "".b
79
+ plain = decrypted[0, total_size] || "".b
80
+ raise Xlsxrb::DecryptionError, "Data integrity check failed: the encrypted package does not match its HMAC" unless intact || legacy_integrity_verified?(info, cipher_name, digest, h_final, plain)
81
+
82
+ plain
74
83
  end
75
84
 
76
85
  # Encrypts a plain zip payload with the given password into EncryptionInfo and EncryptedPackage streams.
@@ -126,15 +135,13 @@ module Xlsxrb
126
135
  encrypted_package_stream << aes_encrypt_block(cipher_name, package_key, iv, chunk)
127
136
  end
128
137
 
129
- # Data integrity HMAC
130
- hmac_key = SecureRandom.random_bytes(64)
131
- hmac_value = OpenSSL::HMAC.digest(hash_algorithm, hmac_key, plain_bytes)
132
-
133
- k_integ_key = derive_key(digest, h_final, BLOCK_KEY_INTEGRITY_KEY, key_bytes)
134
- encrypted_hmac_key = aes_encrypt(cipher_name, k_integ_key, encryptor_salt, hmac_key)
135
-
136
- k_integ_val = derive_key(digest, h_final, BLOCK_KEY_INTEGRITY_VALUE, key_bytes)
137
- encrypted_hmac_val = aes_encrypt(cipher_name, k_integ_val, encryptor_salt, hmac_value)
138
+ # Data integrity ([MS-OFFCRYPTO] 2.3.4.14): an HMAC of the whole EncryptedPackage
139
+ # stream, its size prefix included. The HMAC key and value are encrypted with the
140
+ # package key, each with an IV derived from the keyData salt.
141
+ hmac_key = SecureRandom.random_bytes(hash_size)
142
+ hmac_value = OpenSSL::HMAC.digest(hash_algorithm, hmac_key, encrypted_package_stream)
143
+ encrypted_hmac_key = aes_encrypt(cipher_name, package_key, digest.digest(key_data_salt + BLOCK_KEY_INTEGRITY_KEY), hmac_key)
144
+ encrypted_hmac_val = aes_encrypt(cipher_name, package_key, digest.digest(key_data_salt + BLOCK_KEY_INTEGRITY_VALUE), hmac_value)
138
145
 
139
146
  # Build EncryptionInfo XML
140
147
  xml = <<~XML
@@ -185,12 +192,15 @@ module Xlsxrb
185
192
  raise Xlsxrb::DecryptionError, "spinCount out of allowed bounds: #{spin_count}" if spin_count.negative? || spin_count > 10_000_000
186
193
 
187
194
  key_attrs = key_data&.attributes
195
+ integrity_attrs = root.elements["dataIntegrity"]&.attributes
188
196
  {
189
197
  key_data_salt: key_attrs&.[]("saltValue").to_s.unpack1("m0") || "".b,
190
198
  key_data_hash_algorithm: key_attrs&.[]("hashAlgorithm") || "SHA512",
191
199
  key_data_cipher_algorithm: key_attrs&.[]("cipherAlgorithm") || "AES",
192
200
  key_data_key_bits: key_attrs&.[]("keyBits")&.to_i || 256,
193
201
  key_data_block_size: key_attrs&.[]("blockSize")&.to_i || 16,
202
+ encrypted_hmac_key: integrity_attrs&.[]("encryptedHmacKey")&.unpack1("m0"),
203
+ encrypted_hmac_value: integrity_attrs&.[]("encryptedHmacValue")&.unpack1("m0"),
194
204
 
195
205
  spin_count: spin_count,
196
206
  encryptor_salt: key_encryptor.attributes["saltValue"].to_s.unpack1("m0") || "".b,
@@ -204,6 +214,32 @@ module Xlsxrb
204
214
  }
205
215
  end
206
216
 
217
+ # Data integrity ([MS-OFFCRYPTO] 2.3.4.14): the HMAC of the whole EncryptedPackage
218
+ # stream. The HMAC key and value are encrypted with the package key, each with an
219
+ # IV derived from the keyData salt.
220
+ def integrity_verified?(info, cipher_name, digest, package_key, encrypted_package_bytes)
221
+ encrypted_key = info[:encrypted_hmac_key]
222
+ encrypted_value = info[:encrypted_hmac_value]
223
+ raise Xlsxrb::DecryptionError, "Missing dataIntegrity in EncryptionInfo" if encrypted_key.nil? || encrypted_value.nil?
224
+
225
+ salt = info[:key_data_salt]
226
+ size = digest.digest_length
227
+ hmac_key = aes_decrypt(cipher_name, package_key, digest.digest(salt + BLOCK_KEY_INTEGRITY_KEY), encrypted_key)[0, size]
228
+ hmac_value = aes_decrypt(cipher_name, package_key, digest.digest(salt + BLOCK_KEY_INTEGRITY_VALUE), encrypted_value)[0, size]
229
+ OpenSSL.secure_compare(OpenSSL::HMAC.digest(digest.name, hmac_key, encrypted_package_bytes), hmac_value)
230
+ end
231
+
232
+ # xlsxrb 0.2.1 and earlier wrote an HMAC of the package before encryption, with the HMAC
233
+ # key and value encrypted under keys derived from the password. Files it wrote are
234
+ # still read; this HMAC also fails for a package that was changed.
235
+ def legacy_integrity_verified?(info, cipher_name, digest, h_final, plain)
236
+ key_bytes = info[:key_bits] / 8
237
+ salt = info[:encryptor_salt]
238
+ hmac_key = aes_decrypt(cipher_name, derive_key(digest, h_final, BLOCK_KEY_INTEGRITY_KEY, key_bytes), salt, info[:encrypted_hmac_key])
239
+ hmac_value = aes_decrypt(cipher_name, derive_key(digest, h_final, BLOCK_KEY_INTEGRITY_VALUE, key_bytes), salt, info[:encrypted_hmac_value])
240
+ OpenSSL.secure_compare(OpenSSL::HMAC.digest(digest.name, hmac_key, plain), hmac_value)
241
+ end
242
+
207
243
  def digest_for(name)
208
244
  case name.to_s.upcase.gsub(/[^A-Z0-9]/, "")
209
245
  when "SHA512" then OpenSSL::Digest.new("SHA512")
@@ -218,6 +254,8 @@ module Xlsxrb
218
254
  def cipher_name_for(algo, key_bits)
219
255
  case algo.to_s.upcase
220
256
  when "AES"
257
+ raise Xlsxrb::DecryptionError, "Unsupported AES key size: #{key_bits}" unless [128, 192, 256].include?(key_bits)
258
+
221
259
  "aes-#{key_bits}-cbc"
222
260
  else
223
261
  raise Xlsxrb::DecryptionError, "Unsupported cipher algorithm: #{algo}"
@@ -35,7 +35,11 @@ module Xlsxrb
35
35
  total_size = encrypted_package_bytes[0, 8].unpack1("Q<")
36
36
  raise Xlsxrb::DecryptionError, "Encrypted package size is invalid or exceeds limits" if total_size.negative? || total_size > 0x400_000_000
37
37
 
38
- encrypted_data = encrypted_package_bytes[8..] || "".b
38
+ # Only the blocks that hold the package are decrypted. Some writers leave bytes
39
+ # after them that are not a whole block.
40
+ encrypted_size = (total_size + 15) / 16 * 16
41
+ encrypted_data = encrypted_package_bytes[8, encrypted_size] || "".b
42
+ raise Xlsxrb::DecryptionError, "Encrypted package is shorter than its declared size" if encrypted_data.bytesize < encrypted_size
39
43
 
40
44
  decrypted = aes_ecb_decrypt(k, encrypted_data)
41
45
  decrypted[0, total_size] || "".b
@@ -41,6 +41,9 @@ module Xlsxrb
41
41
  else
42
42
  raise Xlsxrb::DecryptionError, "Unsupported encryption version #{major}.#{minor}"
43
43
  end
44
+ rescue OpenSSL::OpenSSLError, ArgumentError => e
45
+ # Salts, keys, and ciphertext of the wrong length, and invalid Base64.
46
+ raise Xlsxrb::DecryptionError, "Malformed encrypted package: #{e.message}"
44
47
  end
45
48
 
46
49
  # Encrypts a plain ZIP payload with the given password into an encrypted CFB package.
@@ -78,6 +78,10 @@ module Xlsxrb
78
78
  rph_end_len = rph_end_tag.bytesize
79
79
  has_rph = xml.include?(rph_start_pattern)
80
80
 
81
+ # Position of the next <t at or after the last position searched from. Searching
82
+ # again from every <si> that has no <t> would scan the rest of the part each time.
83
+ t_hint = nil
84
+
81
85
  pos = sst_open_end + 1
82
86
  while pos < sst_end
83
87
  si_start = xml.index(si_start_pattern, pos)
@@ -97,15 +101,15 @@ module Xlsxrb
97
101
  break unless si_end
98
102
 
99
103
  # Fast path: check for simple single <t>...</t> inside <si>
100
- first_t = xml.index(t_start_pattern, si_open_end + 1)
101
- if first_t && first_t < si_end
104
+ first_t = t_hint = next_index(xml, t_start_pattern, si_open_end + 1, t_hint)
105
+ if first_t < si_end
102
106
  tb = xml.getbyte(first_t + t_start_len)
103
107
  if TAG_DELIM_BYTES.include?(tb)
104
108
  t_open_end = xml.index(">", first_t + t_start_len)
105
109
  if t_open_end && t_open_end < si_end
106
110
  if xml.getbyte(t_open_end - 1) == 47 # <t/>
107
- next_t = xml.index(t_start_pattern, t_open_end + 1)
108
- str = if next_t && next_t < si_end
111
+ next_t = t_hint = next_index(xml, t_start_pattern, t_open_end + 1, t_hint)
112
+ str = if next_t < si_end
109
113
  extract_multi_t(xml, si_open_end + 1, si_end, t_start_pattern, t_start_len, t_end_tag, t_end_len, rph_start_pattern, rph_end_tag, rph_end_len, has_rph: has_rph)
110
114
  else
111
115
  ""
@@ -113,8 +117,8 @@ module Xlsxrb
113
117
  else
114
118
  t_end = xml.index(t_end_tag, t_open_end + 1)
115
119
  if t_end && t_end <= si_end
116
- next_t = xml.index(t_start_pattern, t_end + t_end_len)
117
- if next_t && next_t < si_end
120
+ next_t = t_hint = next_index(xml, t_start_pattern, t_end + t_end_len, t_hint)
121
+ if next_t < si_end
118
122
  # Multiple <t> tags (rich text runs)
119
123
  str = extract_multi_t(xml, si_open_end + 1, si_end, t_start_pattern, t_start_len, t_end_tag, t_end_len, rph_start_pattern, rph_end_tag, rph_end_len, has_rph: has_rph)
120
124
  else
@@ -142,9 +146,23 @@ module Xlsxrb
142
146
 
143
147
  private_class_method :fast_scan
144
148
 
149
+ # Returns the index of the first +pattern+ at or after +from+, or the size of +xml+ when
150
+ # there is none. +cached+ is the result of the previous call for the same pattern with a
151
+ # smaller +from+; while it is not behind +from+ it is still the answer, so a caller that
152
+ # moves forward searches each stretch of +xml+ once.
153
+ #: (String xml, String pattern, Integer from, Integer? cached) -> Integer
154
+ def self.next_index(xml, pattern, from, cached)
155
+ return cached if cached && cached >= from
156
+
157
+ xml.index(pattern, from) || xml.bytesize
158
+ end
159
+
160
+ private_class_method :next_index
161
+
145
162
  def self.extract_multi_t(xml, from, to, t_start_pattern, t_start_len, t_end_tag, t_end_len, rph_start_pattern, rph_end_tag, rph_end_len, has_rph: false)
146
163
  buf = +""
147
164
  pos = from
165
+ rph_hint = nil
148
166
  while pos < to
149
167
  t_start = xml.index(t_start_pattern, pos)
150
168
  break unless t_start && t_start < to
@@ -160,8 +178,8 @@ module Xlsxrb
160
178
 
161
179
  if has_rph
162
180
  # Phonetic runs (<rPh>) hold furigana readings and are not part of the string
163
- rph_start = xml.index(rph_start_pattern, pos)
164
- if rph_start && rph_start < t_start
181
+ rph_start = rph_hint = next_index(xml, rph_start_pattern, pos, rph_hint)
182
+ if rph_start < t_start
165
183
  rph_end = xml.index(rph_end_tag, rph_start)
166
184
  break unless rph_end && rph_end < to
167
185