gamba 2.0.0 → 2.0.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 025fac5d0c63d47973bd1c28e56c62ccb56ffe6610cdde36f75ce8b927180303
4
- data.tar.gz: d1e45ff6c48a371d1252e67c6dead3cb428ae506c96a614c1632050f3c7eee41
3
+ metadata.gz: 6909a10a173cb8d39f9f93432f7b47495e2bf18ca5d56559b263ac8292235ba7
4
+ data.tar.gz: 1a54fa9a6878a7eab8ed06e4d9b57fde344ad3c3edd850c93de2fb5b2bd099fd
5
5
  SHA512:
6
- metadata.gz: 5c29d5bdb557f2437e3ec9ce9502aa744fe389d7a16f77afced77837af6aab21219bc2ea61564a0e0b7aa7c41ac1ca9a4d59057360db9a88c382d166ab97d7c0
7
- data.tar.gz: 9c82755b0e28d2273c3b32e882ace7c11228fe3ad5356d63a921687b0e0dd68e91eda71dd097915b5160047f532493fe8e7721dbabcf5472e252da739e06c233
6
+ metadata.gz: f8eb03f65d8d6e26264a0fbea81cb38bf68968b171bb84b41aeafd3b11360024c2ad6cfa2ce171a321861a6bfc2756ec8cd445168d20d345724358eb10604b3c
7
+ data.tar.gz: bf668afa09665f836ed62ff0b8d2a593baabaa062353c1b46b9297439bdc6c9cd3e0c977b937a397fa3a3e03dd53dd4cf8478133d49b0aadd7602b20c2cfbc18
data/CHANGELOG.md CHANGED
@@ -2,6 +2,37 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [2.0.2] — 2026-11-07
6
+
7
+ SVGs that users send can no longer crash or stall a server through `<use>`, `<image>` or `<tref>`.
8
+
9
+ **Fixed**
10
+ - An SVG loaded through `<use>` or `<image>` is checked like the document, attributes included: a `data:` URL nested
11
+ thousands of levels deep overflowed the stack, and entities in an attribute raised `RuntimeError`.
12
+ - `<tref>` draws through the `<use>` path: a tref inside its own text no longer overflows the stack, one to a missing
13
+ id no longer raises `NoMethodError`, and trefs doubling at each level stop at the 20,000-element budget.
14
+ - Embedded SVG images share the budget of the SVG that embeds them and stop at 16 levels, and `data:` URLs are
15
+ decoded once per document.
16
+ - An `@font-face` that is not a font becomes a warning, and a table with no cells draws nothing instead of raising
17
+ `NoMethodError`.
18
+ - addressable 2.9.1 or later is required: before it, an `@import` path took quadratic time to resolve
19
+ (GHSA-qq38-m9mg-xjj5).
20
+
21
+ ## [2.0.1] — 2026-11-06
22
+
23
+ Fonts, images, SVGs and PDFs that users send can no longer hang a server, exhaust its memory or crash it.
24
+
25
+ **Faster**
26
+ - Packed indexed transparency in PNGs goes through a byte table: 4 seconds instead of 48 on an 8 KB file.
27
+ - Inline formatting tokenizes in linear time and dedupes repeated styles: `"<a" * 40_000` took 5.8 seconds, and `"<b>x" * 8000` used 401 MB.
28
+
29
+ **Fixed**
30
+ - SVG ids are read once instead of through XPath built from the id, which could be injected and scanned the whole document for each missing id. `<use>` cycles are skipped, `<use>` draws at most 20,000 elements, gradient cycles paint nothing, nesting stops at 256 levels, and an SVG's `@font-face` faces no longer replace the application's fonts once it is drawn.
31
+ - Composite glyph cycles end, overlapping cmap ranges raise `TrueType::Error`, and malformed name tables or `.otf`/`.ttf` outline mismatches no longer crash. The parsed font cache keeps 64 files.
32
+ - Truncated or zero-sized JPEGs raise `FormatError`, and a PNG without a full row is still written.
33
+ - An encrypted PDF's `/ID` mixes in the passwords, so it can no longer be used to check guesses at the content, and `owner_password: :random` uses SecureRandom.
34
+ - PDF/A metadata with control characters raises `PdfAViolation`, `Gamba.combine` no longer writes NaN for huge reals, and SVG never writes NaN or Infinity.
35
+
5
36
  ## [2.0.0] — 2026-11-05
6
37
 
7
38
  PrawnX is now Gamba, at levups/gamba, and text that overflows onto a page that already exists keeps the state it was drawn with.
@@ -73,7 +104,9 @@ speed. Same API and same pages as Prawn, pixel for pixel, in lighter files.
73
104
  place of combine_pdf.
74
105
  - `Gamba::VERSION` is the gem's; `Prawn::VERSION` stays 2.5.0, the API reproduced.
75
106
 
76
- [Unreleased]: https://github.com/levups/gamba/compare/v2.0.0...HEAD
107
+ [Unreleased]: https://github.com/levups/gamba/compare/v2.0.2...HEAD
108
+ [2.0.2]: https://github.com/levups/gamba/compare/v2.0.1...v2.0.2
109
+ [2.0.1]: https://github.com/levups/gamba/compare/v2.0.0...v2.0.1
77
110
  [2.0.0]: https://github.com/levups/gamba/compare/v1.1.0...v2.0.0
78
111
  [1.1.0]: https://github.com/levups/gamba/compare/v1.0.1...v1.1.0
79
112
  [1.0.1]: https://github.com/levups/gamba/compare/v1.0.0...v1.0.1
data/README.md CHANGED
@@ -1,86 +1,143 @@
1
1
  # Gamba
2
2
 
3
- Prawn's API, rewritten for speed: the same pages, pixel for pixel, in lighter files, faster.
3
+ Gamba is a Ruby library that writes PDF files: invoices, reports, labels, anything you can lay out as text, tables,
4
+ images and shapes. It is a faster rewrite of [Prawn](https://github.com/prawnpdf/prawn), the most widely used PDF
5
+ library for Ruby, together with its two companion gems, prawn-table and prawn-svg.
4
6
 
5
- https://levups.github.io/gamba/
7
+ Code written for Prawn 2.5 runs on Gamba unchanged and draws the same pages, down to the pixel. The difference is
8
+ speed and size: a one-page invoice renders about five times faster and the file is a quarter lighter (see
9
+ [Performance](#performance)).
10
+
11
+ Website and guide: https://levups.github.io/gamba/
6
12
 
7
13
  ## Installation
8
14
 
15
+ Gamba needs Ruby 3.3 or later. In your Gemfile, replace `prawn`, `prawn-table` and `prawn-svg` with one line:
16
+
9
17
  ```ruby
10
- # Gemfile
11
- gem "gamba" # instead of prawn, prawn-table and prawn-svg
18
+ gem "gamba"
12
19
  ```
13
20
 
14
- `pdf.table` and `pdf.svg` work without any other gem; `require "prawn/table"` and `require "prawn-svg"` keep
15
- working.
16
-
17
- Gamba needs Ruby 3.3 or later, and refuses to load when the prawn gem is in the bundle too.
18
-
19
- The gem has its own version, `Gamba::VERSION`. `Prawn::VERSION` is the version of the Prawn API it reproduces,
20
- 2.5.0, so code that checks Prawn's version keeps working.
21
+ Gamba refuses to load if the prawn gem is in the same bundle, so remove it. Your existing `require "prawn"`,
22
+ `require "prawn/table"` and `require "prawn-svg"` lines keep working, and `pdf.table` and `pdf.svg` are available
23
+ without them.
21
24
 
22
- ## Usage
23
-
24
- Code written for Prawn runs unchanged:
25
+ ## A first document
25
26
 
26
27
  ```ruby
28
+ require "prawn"
29
+
27
30
  Prawn::Document.generate("hello.pdf") do
28
31
  text "Hello, World!"
29
32
  table [%w[SKU Qty], %w[A-1 2]]
30
33
  end
31
34
  ```
32
35
 
33
- ## Beyond Prawn
36
+ This writes `hello.pdf` with a line of text and a two-row table. Everything else Prawn documents works the same
37
+ way: fonts, colors, images, columns, page numbers, links, encryption. Prawn's manual applies as it is, and
38
+ [the guide](https://levups.github.io/gamba/guide.html) covers what Gamba adds.
39
+
40
+ The constant is still `Prawn`, so you don't have to rename anything. `Prawn::VERSION` reports `2.5.0`, the
41
+ version of the API Gamba reproduces, for code that checks it. Gamba's own version is `Gamba::VERSION`.
42
+
43
+ ## What Gamba adds
34
44
 
35
- What would move pixels away from Prawn's stays off unless asked for.
45
+ Anything that would change how a page looks compared with Prawn is off until you ask for it.
46
+
47
+ Ligatures and kerning from OpenType fonts, per font:
36
48
 
37
49
  ```ruby
38
- # OpenType ligatures and GPOS pair kerning, per font
39
50
  font "Inter.ttf", features: %i[liga kern]
51
+ ```
40
52
 
41
- # PDF/A-3b: XMP metadata, sRGB output intent, file identifier; standard fonts and encryption raise
53
+ PDF/A-3b archival files, and Factur-X electronic invoices (the French and German standard that embeds the invoice
54
+ data as XML inside the PDF). Gamba embeds the XML your invoicing system produced; it does not build it.
55
+
56
+ ```ruby
42
57
  Prawn::Document.new(pdf_a: true, info: {Title: "Invoice INV-2026-0001"}) do
43
- font "Inter.ttf"
44
- # …
45
- factur_x File.read("factur-x.xml"), profile: :en16931 # Factur-X: minimum, basic_wl, basic, en16931, extended
58
+ font "Inter.ttf" # PDF/A needs embedded fonts: the 14 standard ones raise, and so does encryption
59
+ # ...
60
+ factur_x File.read("factur-x.xml"), profile: :en16931 # or minimum, basic_wl, basic, extended
46
61
  end
62
+ ```
47
63
 
48
- # Before a server forks: load TrueType and SVG support once, shared by every worker
49
- Gamba.eager_load!
64
+ Merging existing PDFs, such as carrier labels or supplier invoices, one page after another. This replaces the
65
+ combine_pdf gem for that use:
50
66
 
51
- # Pages of PDFs written elsewhere, one after the other: carrier labels, supplier invoices (instead of combine_pdf)
67
+ ```ruby
52
68
  Gamba.combine([label, other_label], page_size: [288, 432], orientation: :portrait)
53
69
  ```
54
70
 
55
- OpenType fonts with CFF outlines (`.otf`) embed like TrueType ones, and render like the font itself. Gamba does
56
- not build the Factur-X XML: it embeds the one the invoicing system produced.
57
-
58
- SVG images do not fetch anything from the web unless asked to (`svg data, enable_web_requests: true`): prawn-svg
59
- 0.40 fetches by default, which lets a submitted SVG make the server request any URL. prawn-svg 1.0 plans the same
60
- default.
71
+ Loading font and SVG support once, before a server such as Puma or Unicorn forks its workers, so they share it in
72
+ memory:
61
73
 
62
- `Gamba.combine` reads xref tables, cross-reference and object streams, incremental updates, and files encrypted
63
- with an owner password only (RC4, AES-128, AES-256); a file that needs a user password raises
64
- `Prawn::Errors::EncryptedPDF`, a damaged one it cannot repair `Prawn::Errors::MalformedPDF`. Content streams are
65
- copied as they were encoded, and what several sources share (a carrier's fonts and logo) is written once. With
66
- `page_size`, each page is scaled from its lower left corner to fit, keeping its proportions; with `orientation`, a
67
- page the other way round turns a quarter counterclockwise, as combine_pdf does. A `/Rotate` is applied to the
68
- content first, where combine_pdf left it to the viewer. Outlines, forms and tagged structure are not carried over.
69
-
70
- ## Comparing an app's PDFs
74
+ ```ruby
75
+ Gamba.eager_load!
76
+ ```
71
77
 
72
- `script/capture_pdfs.rb` writes every PDF an app's test suite renders, named after its test. Run the suite under
73
- Prawn, then under Gamba, and compare both directories with `Oracle.pdf_differences`:
78
+ ### More on combining PDFs
79
+
80
+ `Gamba.combine` takes the bytes of each PDF and returns the bytes of the merged one. It reads the cross-reference
81
+ formats PDF writers use, including incremental updates, and files encrypted with an owner password only (RC4,
82
+ AES-128 and AES-256). A file that needs a password to open raises `Prawn::Errors::EncryptedPDF`, and a damaged one
83
+ it cannot repair raises `Prawn::Errors::MalformedPDF`.
84
+
85
+ Pages are copied as they were encoded, and resources several files share, like a carrier's fonts and logo, are
86
+ written once. With `page_size`, each page is scaled from its lower left corner to fit, keeping its proportions.
87
+ With `orientation`, a page the other way round turns a quarter counterclockwise, as combine_pdf does. A page's
88
+ `/Rotate` is applied to its content, where combine_pdf left it to the viewer. Outlines, forms and tagged structure
89
+ are not carried over.
90
+
91
+ ## Files your users send
92
+
93
+ Applications often put user content into PDFs: an uploaded logo, a font, a name typed in a form, a PDF to attach.
94
+ Any of it can be built to attack the server that renders it.
95
+
96
+ - SVG images fetch nothing from the web unless you pass `enable_web_requests: true`. prawn-svg 0.40 fetched by
97
+ default, so a submitted SVG could make your server request any URL. prawn-svg 1.0 plans the same default as
98
+ Gamba.
99
+ - An SVG reads only what you allow. Base64 `data:` URLs of PNG, JPEG and SVG images always load; `http` and
100
+ `https` URLs need `enable_web_requests: true`; files need `enable_file_requests_with_root`, and only regular
101
+ files inside that directory load, symbolic links in it followed. Any other URL, path or scheme is skipped with a
102
+ warning, and an entity the SVG declares from a file or URL is never read.
103
+ - An SVG can't make Gamba loop or run out of stack through references (`<use>`, `<tref>`, gradients) or deep
104
+ nesting. An SVG it loads with `<use>` or `<image>` is checked the same way, SVG images stop 16 levels inside
105
+ one another, and they draw within the budget of the SVG that embeds them.
106
+ - Fonts an SVG declares with `@font-face` disappear once it is drawn, and one that is not a font is left out. In
107
+ prawn-svg, an uploaded SVG declaring a "Helvetica" font changed the font of the application's own text.
108
+ - A damaged or malicious PNG, JPEG, TrueType or OpenType file either renders or raises an error Gamba names
109
+ (`Prawn::Errors::UnsupportedImageType`, `Prawn::Images::JPG::FormatError`, `Gamba::TrueType::Error`, or
110
+ `Prawn::Errors::CannotFit` when a damaged font makes a glyph wider than the page). A PNG
111
+ inflates no further than the size its header gives. CI corrupts sample files on every run to check this.
112
+ - `Gamba.combine` stops at 64 levels of nested arrays and dictionaries and at 256 MB of decompressed data, and
113
+ ignores references that lead back to themselves, so a crafted PDF can't send it into a loop or fill
114
+ memory.
115
+ - Text with inline formatting (`inline_format: true`) is parsed in linear time, whatever the markup.
116
+ - The `/ID` of an encrypted PDF depends on its passwords, so it reveals nothing about the content to someone
117
+ without them.
118
+
119
+ Inline formatting still turns `<link href="...">` into a clickable link. Escape user text before you put it inside
120
+ markup. A word with no space to break at, thousands of characters long, takes time that grows with the square of its
121
+ length, as in Prawn: limit the length of what users type.
122
+
123
+ To report a vulnerability, see [SECURITY.md](SECURITY.md).
124
+
125
+ ## Checking your app's PDFs
126
+
127
+ Before switching, you can compare what your app produces under both libraries. `script/capture_pdfs.rb` saves
128
+ every PDF your test suite renders, named after the test. Run the suite once with Prawn and once with Gamba:
74
129
 
75
130
  ```sh
76
131
  GAMBA_CAPTURE_DIRECTORY=tmp/prawn RUBYOPT=-r/path/to/gamba/script/capture_pdfs.rb bin/rails test
77
132
  ```
78
133
 
134
+ Then compare the two directories with `Oracle.pdf_differences`, from Gamba's test support.
135
+
79
136
  ## Performance
80
137
 
81
- `bundle exec rake bench` renders each document of `bench/documents` with Prawn 2.5 and with Gamba in 7 fresh YJIT
82
- processes each, taking turns, and writes `docs/benchmarks.json`. Each process times 20 renders; the table shows the
83
- median of the 7 processes, on Ruby 4.0.9:
138
+ `bundle exec rake bench` renders each document in `bench/documents` with Prawn 2.5 and with Gamba, in 7 fresh
139
+ YJIT processes each, taking turns. Each process times 20 renders, and the table shows the median of the 7, on
140
+ Ruby 4.0.9:
84
141
 
85
142
  | Document | Prawn | Gamba | Allocations, Prawn → Gamba | Weight, Prawn → Gamba |
86
143
  |---|---:|---:|---:|---:|
@@ -88,58 +145,71 @@ median of the 7 processes, on Ruby 4.0.9:
88
145
  | Report, 101 pages | 559.4 ms | 216.0 ms | 3,350,853 → 2,089,008 | 207,815 → 164,924 bytes |
89
146
  | Catalog, 1,000 table rows | 544.9 ms | 265.6 ms | 3,979,977 → 2,078,343 | 147,731 → 134,082 bytes |
90
147
 
91
- Charts and peak memory: https://levups.github.io/gamba/benchmarks.html
148
+ Files are lighter because Gamba compresses streams and packs objects together, which PDF 1.5 allows and Prawn
149
+ doesn't do. Charts and peak memory are on the [benchmarks page](https://levups.github.io/gamba/benchmarks.html).
150
+
151
+ ## How we know the pages are the same
152
+
153
+ The test suite renders every example of Prawn's and prawn-table's manuals, and every sample SVG of prawn-svg, once
154
+ with the original gems and once with Gamba. For each pair it compares the text and its position to 0.01 pt, the
155
+ pixels at 150 dpi in two unrelated renderers (MuPDF and Poppler), whether `qpdf --check` accepts the file, and its
156
+ size. We call this the oracle.
157
+
158
+ Gamba does not copy Prawn's bugs. When Prawn crashes, writes an invalid PDF or contradicts its own documentation,
159
+ Gamba fixes it, and the [compatibility page](https://levups.github.io/gamba/compatibility.html) lists each fix with
160
+ its proof.
92
161
 
93
162
  ## Development
94
163
 
95
- - An oracle renders every example of Prawn's and prawn-table's manuals and every sample SVG of prawn-svg, with
96
- Prawn 2.5, prawn-table 0.2.2 and prawn-svg 0.40.4 and with Gamba, each in its own process, and
97
- compares their pages, their text and its positions to 0.01 pt, their pixels at 150 dpi in two renderers that
98
- share no code (MuPDF and Poppler), their validity
99
- (`qpdf --check`) and their weight. Examples listed in `test/oracle_passing.txt` must stay identical; one that
100
- becomes identical must join the list.
101
- - A seeded fuzzer writes random documents (text in all its options, boxes, columns, tables, shapes, pages) and
102
- compares them the same way: `FUZZ_SEED=42 FUZZ_CASES=500 bundle exec ruby -Itest test/fuzz_test.rb`, and
103
- `ruby -Itest script/fuzz_minimize.rb tmp/fuzz/documents/fuzz_0042.rb` shrinks a failing one. CI adds 300 from a
104
- fresh seed on every run.
105
- - An input fuzzer corrupts sample PNGs, JPEGs and fonts (flipped bytes, truncations, forged lengths): each must
106
- render or raise an error Gamba names, never crash inside a parser, hang or exhaust memory. PNG data inflates
107
- no further than its header announces.
108
- - `test/divergences.yml` lists Prawn's bugs Gamba fixes, each with the specification that proves it and the exact
109
- differences the oracle must report. `test/oracle_examples` holds documents of our own for what the manual
110
- does not show.
111
- - PDF/A documents are checked by veraPDF when it is installed (`brew install verapdf`).
112
- - `test/contract/prawn-2.5.0.yml`, generated by `script/contract_extract.rb`, lists Prawn's public methods; Gamba
113
- must accept every call Prawn accepts on those of its contract, settled in `test/contract/decisions.yml`.
114
-
115
- Prawn runs from its own bundle, `oracle/Gemfile`. The oracle needs `mutool`, `pdftoppm` and `qpdf` (`brew install
116
- mupdf-tools poppler qpdf`), and Prawn's manual and data, which `rake corpus:fetch` downloads into the ignored `corpus/cache`.
164
+ Prawn runs from its own bundle, `oracle/Gemfile`, so the oracle can compare the two. The tests need `mutool`,
165
+ `pdftoppm` and `qpdf` (`brew install mupdf-tools poppler qpdf`), and Prawn's manual and sample data, which
166
+ `rake corpus:fetch` downloads into `corpus/cache`. Without that cache, the comparison tests are skipped.
117
167
 
118
168
  ```sh
119
169
  bundle install && BUNDLE_GEMFILE=oracle/Gemfile bundle install
120
170
  bundle exec rake corpus:fetch
121
171
  bundle exec rake test
122
- ORACLE_CANDIDATE=prawn bundle exec rake test # Prawn against itself: proves the oracle
123
- bundle exec rake bench
124
172
  bundle exec rubocop
125
173
  ```
126
174
 
175
+ Other commands:
176
+
177
+ ```sh
178
+ ORACLE_CANDIDATE=prawn bundle exec rake test # Prawn against itself, to check the oracle
179
+ FUZZ_SEED=42 FUZZ_CASES=500 bundle exec ruby -Itest test/fuzz_test.rb # random documents, compared with Prawn
180
+ INPUT_FUZZ_SEED=42 INPUT_FUZZ_CASES=400 bundle exec ruby -Itest test/input_fuzz_test.rb # corrupted images and fonts
181
+ bundle exec rake bench # writes docs/benchmarks.json
182
+ ```
183
+
184
+ `ruby -Itest script/fuzz_minimize.rb tmp/fuzz/documents/fuzz_0042.rb` shrinks a failing fuzz document. PDF/A
185
+ files are also checked by veraPDF when it is installed (`brew install verapdf`).
186
+
187
+ The files that define what "compatible" means:
188
+
189
+ - `test/oracle_passing.txt`: examples that must stay identical to Prawn's. One that becomes identical joins it.
190
+ - `test/divergences.yml`: Prawn bugs Gamba fixes, with the specification that proves each one and the exact
191
+ differences the oracle must find.
192
+ - `test/oracle_examples`: documents of our own, for cases the manuals don't show.
193
+ - `test/contract/prawn-2.5.0.yml`: Prawn's public methods, generated by `script/contract_extract.rb`. Every call
194
+ Prawn accepts must keep working; exceptions are settled in `test/contract/decisions.yml`.
195
+
196
+ See [CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request.
197
+
127
198
  ### Releasing
128
199
 
129
- Pull requests leave `CHANGELOG.md` alone: a release starts by writing its notes under `## [Unreleased]`, from the
130
- pull requests merged since the last tag, without committing them. Then, from an up-to-date `main` whose CI is
131
- green:
200
+ Pull requests leave `CHANGELOG.md` alone. A release starts by writing its notes under `## [Unreleased]`, from the
201
+ pull requests merged since the last tag, without committing them. Then, from an up-to-date `main` with green CI:
132
202
 
133
203
  ```sh
134
- bin/release minor --dry-run # the notes and the changes, nothing written
204
+ bin/release minor --dry-run # shows the notes and the changes, writes nothing
135
205
  bin/release minor # or patch, major, or an exact version such as 1.2.0
136
206
  ```
137
207
 
138
- `main` takes no direct push, so `bin/release` dates the Unreleased section and bumps the version on a branch
139
- `release/vX.Y.Z`, opens its pull request, which merges itself once CI is green, and waits for it. It then pushes a
140
- signed tag `vX.Y.Z` on the merge commit (`bin/release --tag X.Y.Z` does it if you stopped waiting). The tag starts
141
- the Release workflow, which publishes the gem to RubyGems through trusted publishing and creates the GitHub release
142
- with the version's notes and the `.gem`.
208
+ `main` takes no direct push, so `bin/release` dates the notes and bumps the version on a `release/vX.Y.Z` branch,
209
+ opens a pull request that merges itself once CI is green, and waits for it. It then pushes a signed `vX.Y.Z` tag on
210
+ the merge commit (`bin/release --tag X.Y.Z` does it if you stopped waiting). The tag starts the Release workflow,
211
+ which publishes the gem to RubyGems through trusted publishing and creates the GitHub release with the notes and
212
+ the `.gem`.
143
213
 
144
214
  ## License
145
215
 
data/lib/gamba/combine.rb CHANGED
@@ -283,8 +283,10 @@ module Gamba
283
283
  numeric(@reader.resolve(value))
284
284
  end
285
285
 
286
+ # A real too large for a Float reads as infinite, and would write NaN into the page's matrix: no number then.
286
287
  def numeric(value)
287
- (value.is_a?(PDF::Core::Real) || value.is_a?(Numeric)) ? value.to_f : nil
288
+ number = (value.is_a?(PDF::Core::Real) || value.is_a?(Numeric)) ? value.to_f : nil
289
+ number if number&.finite?
288
290
  end
289
291
 
290
292
  def intersection(crop, media)
data/lib/gamba/font.rb CHANGED
@@ -104,14 +104,23 @@ module Prawn
104
104
 
105
105
  def self.load(document, source, options = {})
106
106
  case font_format(source, options)
107
- when "ttf" then Fonts::TTF.new(document, source, options)
108
- when "otf" then Fonts::OTF.new(document, source, options)
107
+ when "ttf" then outline_class(source, Fonts::TTF).new(document, source, options)
108
+ when "otf" then outline_class(source, Fonts::OTF).new(document, source, options)
109
109
  when "dfont" then Fonts::DFont.new(document, source, options)
110
110
  when "ttc" then Fonts::TTC.new(document, source, options)
111
111
  else Fonts::AFM.new(document, source, options)
112
112
  end
113
113
  end
114
114
 
115
+ # Outlines decide, not the extension: a .otf may hold TrueType outlines, and a .ttf CFF ones.
116
+ def self.outline_class(source, by_extension)
117
+ case (source.respond_to?(:read) ? :unknown : Gamba::TrueType::File.open(source).outline_format)
118
+ when :true_type then Fonts::TTF
119
+ when :open_type then Fonts::OTF
120
+ else by_extension
121
+ end
122
+ end
123
+
115
124
  def self.font_format(source, options)
116
125
  return options.fetch(:format, "ttf") if source.respond_to?(:read)
117
126
 
@@ -58,9 +58,14 @@ module Prawn
58
58
  loop do
59
59
  marker, code, length = data.byteslice(position, 4)&.unpack("CCn")
60
60
  raise FormatError, "JPEG marker not found!" if marker != MARKER_PREFIX
61
+ raise FormatError, "Truncated JPEG" if length.nil?
61
62
 
62
63
  if START_OF_FRAME_MARKERS.include?(code)
64
+ raise FormatError, "Truncated JPEG frame header" if position + 10 > data.bytesize
65
+
63
66
  @bits, @height, @width, @channels = data.unpack("@#{position + 4} CnnC")
67
+ raise FormatError, "JPEG of #{@width}x#{@height} pixels at #{@bits} bits" unless @bits.positive? && @height.positive? && @width.positive?
68
+
64
69
  break
65
70
  end
66
71
  position += 2 + length
@@ -121,8 +126,9 @@ module Prawn
121
126
  @transparency =
122
127
  case @color_type
123
128
  when INDEXED then {palette: chunk.unpack("C*")}
124
- when GRAYSCALE then {grayscale: chunk.unpack1("n")}
125
- when TRUE_COLOR then {rgb: chunk.unpack("nnn")}
129
+ # Shorter than the samples they need, they would write a /Mask of nulls: ignored, as viewers do.
130
+ when GRAYSCALE then (chunk.bytesize >= 2) ? {grayscale: chunk.unpack1("n")} : {}
131
+ when TRUE_COLOR then (chunk.bytesize >= 6) ? {rgb: chunk.unpack("nnn")} : {}
126
132
  else {}
127
133
  end
128
134
  when "IEND" then break
@@ -185,6 +191,7 @@ module Prawn
185
191
  raise Errors::UnsupportedImageType, "PNG uses an unsupported filter method" if filter_method != 0
186
192
  raise Errors::UnsupportedImageType, "PNG uses unsupported interlace method" if interlace_method != 0
187
193
  raise Errors::UnsupportedImageType, "PNG uses an invalid bit depth" if BIT_DEPTHS[color_type]&.include?(bits) == false
194
+ raise Errors::UnsupportedImageType, "PNG has a palette of #{palette.bytesize / 3} colors" if color_type == INDEXED && !(3..768).cover?(palette.bytesize)
188
195
 
189
196
  dictionary = {Type: :XObject, Subtype: :Image, Height: height, Width: width, BitsPerComponent: bits}
190
197
  if color_type == INDEXED && alpha_channel?
@@ -203,6 +210,9 @@ module Prawn
203
210
  else
204
211
  [:Indexed, :DeviceRGB, (palette.bytesize / 3) - 1, document.ref!({}, palette)]
205
212
  end
213
+ # Data too short for one row still makes an image XObject, which must be a stream: viewers pad it.
214
+ image.empty_stream = true
215
+ image.data[:SMask]&.empty_stream = true
206
216
  if transparency[:grayscale]
207
217
  image.data[:Mask] = [transparency[:grayscale]] * 2
208
218
  elsif transparency[:rgb]
@@ -256,14 +266,18 @@ module Prawn
256
266
  img_data.unpack(alpha_layout, offset:).pack("C*", buffer: alpha)
257
267
  end
258
268
 
259
- # Palette indices and their opacity: indices only mean something once the rows are unfiltered.
269
+ # Palette indices and their opacity: indices only mean something once the rows are unfiltered. Each byte of
270
+ # a row maps to the opacity of the 8 / bits pixels it packs, through a table of its 256 values.
260
271
  def split_palette_transparency
261
272
  rows = PngDecoder.unfilter(img_data, ((width * bits) + 7) / 8, 1)
262
273
  alpha_by_index = Array.new(256) { |index| transparency[:palette][index] || 0xFF }
263
- alpha = rows.map do |row|
264
- indices = (bits == 8) ? row.bytes : row.unpack1("B*").scan(/.{#{bits}}/).first(width).map! { _1.to_i(2) }
265
- indices.map { alpha_by_index[_1] }.pack("C*")
266
- end
274
+ pixels_per_byte = 8 / bits
275
+ mask = (1 << bits) - 1
276
+ alpha_by_byte = Array.new(256) do |byte|
277
+ indices = Array.new(pixels_per_byte) { |pixel| (byte >> (8 - (bits * (pixel + 1)))) & mask }
278
+ [byte.chr, indices.map { alpha_by_index[_1] }.pack("C*")]
279
+ end.to_h
280
+ alpha = rows.map { |row| row.gsub(/./mn, alpha_by_byte).byteslice(0, width) }
267
281
  [rows.join, alpha.join]
268
282
  end
269
283
  end
@@ -6,12 +6,14 @@ module PDF
6
6
  class Reference
7
7
  attr_reader :identifier
8
8
  attr_accessor :data, :uncompressed
9
- attr_writer :stream
9
+ # Written as a stream even without bytes, as image XObjects must be.
10
+ attr_writer :stream, :empty_stream
10
11
 
11
12
  def initialize(identifier, data, stream = nil)
12
13
  @identifier = identifier
13
14
  @data = data
14
15
  @stream = stream
16
+ @empty_stream = false
15
17
  end
16
18
 
17
19
  def to_s
@@ -24,7 +26,7 @@ module PDF
24
26
  end
25
27
 
26
28
  def stream?
27
- !@stream.nil? && !@stream.empty?
29
+ !@stream.nil? && (@empty_stream || !@stream.empty?)
28
30
  end
29
31
  end
30
32
  end
@@ -23,7 +23,7 @@ module PDF
23
23
  @trailer = trailer
24
24
  return unless encryption || identified
25
25
 
26
- file_identifier = PDF::Core::ByteString.new(document_digest)
26
+ file_identifier = PDF::Core::ByteString.new(document_digest(encryption&.identifier_secret))
27
27
  @trailer = trailer.merge(ID: [file_identifier, file_identifier])
28
28
  return unless encryption
29
29
 
@@ -56,9 +56,11 @@ module PDF
56
56
 
57
57
  attr_reader :objects, :root, :info, :version, :trailer
58
58
 
59
- # A file identifier derived from the document's content, so the same document always gets the same one.
60
- def document_digest
59
+ # A file identifier derived from the document's content, so the same document always gets the same one; an
60
+ # encrypted document's mixes in its passwords.
61
+ def document_digest(secret)
61
62
  digest = Digest::MD5.new
63
+ digest << secret if secret
62
64
  objects.each do |reference|
63
65
  digest << PDF::Core.serialize(reference.data)
64
66
  digest << reference.stream if reference.stream?
data/lib/gamba/pdf_a.rb CHANGED
@@ -28,6 +28,8 @@ module Gamba
28
28
  Title: "dc:title", Author: "dc:creator", Subject: "dc:description", Keywords: "pdf:Keywords",
29
29
  Creator: "xmp:CreatorTool", Producer: "pdf:Producer", CreationDate: "xmp:CreateDate", ModDate: "xmp:ModifyDate"
30
30
  }.freeze
31
+ # XML 1.0 has no way to write these, not even as references: the XMP would not parse.
32
+ XML_FORBIDDEN_CHARACTERS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]/
31
33
 
32
34
  def pdf_a?
33
35
  @pdf_a == true
@@ -126,7 +128,12 @@ module Gamba
126
128
  end
127
129
 
128
130
  def escape_xml(text)
131
+ text = text.encode(::Encoding::UTF_8)
132
+ raise Prawn::Errors::PdfAViolation, "PDF/A metadata cannot hold control characters: #{text.inspect}" if text.match?(XML_FORBIDDEN_CHARACTERS)
133
+
129
134
  text.encode(xml: :text)
135
+ rescue EncodingError => error
136
+ raise Prawn::Errors::PdfAViolation, "PDF/A metadata must be text: #{error.message}"
130
137
  end
131
138
  end
132
139
  end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "digest/md5"
4
+ require "securerandom"
4
5
 
5
6
  module Prawn
6
7
  class Document
@@ -18,7 +19,7 @@ module Prawn
18
19
  Prawn.verify_options(%i[user_password owner_password permissions], options)
19
20
  @user_password = options.delete(:user_password) || ""
20
21
  @owner_password = options.delete(:owner_password) || @user_password
21
- @owner_password = Random.bytes(32) if @owner_password == :random
22
+ @owner_password = SecureRandom.bytes(32) if @owner_password == :random
22
23
  self.permissions = options.delete(:permissions) || {}
23
24
  @encryption = Encryption.new(user_password: @user_password, owner_password: @owner_password, permissions: permissions_value)
24
25
  end
@@ -72,6 +73,13 @@ module Prawn
72
73
  end
73
74
  end
74
75
 
76
+ # Mixed into the file identifier, which is written in clear: without it, anyone holding the template could
77
+ # check guesses at the encrypted content against the identifier. The /U and /O entries already let a password
78
+ # guess be checked, so this tells nothing more about the passwords.
79
+ def identifier_secret
80
+ Security.pad_password(@user_password) + Security.pad_password(@owner_password)
81
+ end
82
+
75
83
  def key(file_identifier)
76
84
  Digest::MD5.digest(Security.pad_password(@user_password) + owner_password_hash + [@permissions].pack("V") + file_identifier)[0, Security::KEY_LENGTH_BYTES]
77
85
  end
data/lib/gamba/table.rb CHANGED
@@ -77,6 +77,9 @@ module Prawn
77
77
  alias_method :column, :columns
78
78
 
79
79
  def draw
80
+ # Gamba: rows without a single cell, such as [[]], draw nothing, where prawn-table raised NoMethodError.
81
+ return if @cells.empty?
82
+
80
83
  with_position do
81
84
  reference_bounds = @pdf.reference_bounds
82
85
  started_new_page_at_row = initial_row_on_initial_page
@@ -11,6 +11,8 @@ module Prawn
11
11
  "<color[^>]*>|</color>|<font[^>]*>|</font>|<strong>|</strong>|<em>|</em>|<a[^>]*>|</a>|[^<\n]+",
12
12
  Regexp::MULTILINE
13
13
  )
14
+ # Past the last ">", no tag can end: only text and newlines are left.
15
+ TEXT_REGEX = /\n|[^<\n]+/
14
16
  ESCAPE_CHARS = {"&" => "&amp;", ">" => "&gt;", "<" => "&lt;"}.freeze
15
17
  UNESCAPE_CHARS = ESCAPE_CHARS.invert.freeze
16
18
  CMYK_ATTRIBUTES = %w[c m y k].freeze
@@ -25,7 +27,18 @@ module Prawn
25
27
  SUFFIX_BY_STYLE = PREFIX_BY_STYLE.transform_values { _1.sub("<", "</") }.freeze
26
28
 
27
29
  def self.format(string, *_arguments)
28
- array_from_tokens(string.gsub(%r{<br\s*/?>}, "\n").scan(PARSER_REGEX))
30
+ array_from_tokens(tokens(string.gsub(%r{<br\s*/?>}, "\n")))
31
+ end
32
+
33
+ # The same tokens as string.scan(PARSER_REGEX), in linear time: a tag with attributes that never closes
34
+ # scans to the end of the string from each "<" after the last ">", which made "<a" * n quadratic. From the
35
+ # first "<" past the last ">", only TEXT_REGEX can match.
36
+ def self.tokens(string)
37
+ last_tag_end = string.rindex(">")
38
+ cut = last_tag_end ? string.index("<", last_tag_end) : string.index("<")
39
+ return string.scan(PARSER_REGEX) unless cut
40
+
41
+ string[0, cut].scan(PARSER_REGEX).concat(string[cut..].scan(TEXT_REGEX))
29
42
  end
30
43
 
31
44
  def self.to_string(array)
@@ -95,7 +108,9 @@ module Prawn
95
108
  character_spacings = []
96
109
  tokens.each do |token|
97
110
  if (style = STYLE_BY_OPENING_TAG[token])
98
- styles << style
111
+ # A style opened twice is still one: a closing tag removes it whole, and copies would grow every
112
+ # following fragment's styles.
113
+ styles << style unless styles.include?(style)
99
114
  elsif (style = STYLE_BY_CLOSING_TAG[token])
100
115
  styles.delete(style)
101
116
  else