gamba 2.0.2 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +47 -1
  3. data/README.md +174 -31
  4. data/lib/gamba/annotations.rb +5 -0
  5. data/lib/gamba/barcodes/data_matrix.rb +204 -0
  6. data/lib/gamba/barcodes/linear.rb +182 -0
  7. data/lib/gamba/barcodes/qr_code.rb +339 -0
  8. data/lib/gamba/barcodes.rb +136 -0
  9. data/lib/gamba/combine.rb +13 -135
  10. data/lib/gamba/copier.rb +107 -0
  11. data/lib/gamba/document/internals.rb +5 -1
  12. data/lib/gamba/document.rb +36 -4
  13. data/lib/gamba/font.rb +7 -3
  14. data/lib/gamba/fonts/afm.rb +3 -2
  15. data/lib/gamba/fonts/ttf.rb +26 -20
  16. data/lib/gamba/images.rb +23 -1
  17. data/lib/gamba/imported_page.rb +137 -0
  18. data/lib/gamba/invoice/cross_industry_invoice.rb +255 -0
  19. data/lib/gamba/invoice/rules.rb +183 -0
  20. data/lib/gamba/invoice.rb +272 -0
  21. data/lib/gamba/minitest.rb +35 -0
  22. data/lib/gamba/native/band.rb +56 -0
  23. data/lib/gamba/native/document.rb +128 -0
  24. data/lib/gamba/native/layout.rb +1063 -0
  25. data/lib/gamba/native/table.rb +189 -0
  26. data/lib/gamba/page_boxes.rb +68 -0
  27. data/lib/gamba/pdf/decryption.rb +1 -20
  28. data/lib/gamba/pdf/reader.rb +8 -2
  29. data/lib/gamba/pdf/writer.rb +34 -5
  30. data/lib/gamba/pdf.rb +15 -1
  31. data/lib/gamba/pdf_a.rb +65 -21
  32. data/lib/gamba/pdf_check.rb +220 -0
  33. data/lib/gamba/railtie.rb +52 -0
  34. data/lib/gamba/rspec.rb +58 -0
  35. data/lib/gamba/security.rb +133 -5
  36. data/lib/gamba/table/cell/kinds.rb +45 -5
  37. data/lib/gamba/table/cell.rb +37 -0
  38. data/lib/gamba/table.rb +7 -0
  39. data/lib/gamba/tagging.rb +302 -0
  40. data/lib/gamba/testing.rb +79 -0
  41. data/lib/gamba/text/formatted/box.rb +5 -0
  42. data/lib/gamba/text/formatted/wrap.rb +1 -1
  43. data/lib/gamba/true_type/open_type_layout.rb +44 -17
  44. data/lib/gamba/true_type/simple_subsets.rb +11 -7
  45. data/lib/gamba/version.rb +1 -1
  46. data/lib/gamba/watermark.rb +108 -0
  47. data/lib/gamba.rb +22 -1
  48. metadata +294 -260
@@ -0,0 +1,220 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "open3"
4
+ require "pathname"
5
+ require "tempfile"
6
+ require "tmpdir"
7
+
8
+ module Gamba
9
+ # What tells two PDFs apart, or a PDF from a valid one, through tools that share no code with Gamba: MuPDF for the
10
+ # text and its positions, MuPDF and Poppler for pixels, qpdf and Poppler for validity, veraPDF for PDF/A. Gamba's
11
+ # own oracle compares it with Prawn this way; Gamba::Minitest and Gamba::RSpec put it in an application's tests.
12
+ # A PDF is given as its bytes or as the path of a file.
13
+ module PdfCheck
14
+ # Each glyph: [character, font without its subset tag, size, x, y], positions in points from the top left.
15
+ Page = Data.define(:size, :glyphs)
16
+
17
+ RESOLUTION_DPI = 150
18
+ POSITION_PRECISION_DIGITS = 2
19
+ # Same character, font and size, at most this far apart: positions round to 0.01 on either side of a boundary.
20
+ POSITION_TOLERANCE = 0.0101
21
+ RENDERERS = {"MuPDF" => :rasterize, "Poppler" => :rasterize_with_poppler}.freeze
22
+ QPDF_WARNINGS_EXIT_STATUS = 3
23
+ TOOLS = {
24
+ "mutool" => "brew install mupdf-tools, or apt-get install mupdf-tools",
25
+ "pdftoppm" => "brew install poppler, or apt-get install poppler-utils",
26
+ "pdftotext" => "brew install poppler, or apt-get install poppler-utils",
27
+ "qpdf" => "brew install qpdf, or apt-get install qpdf",
28
+ "verapdf" => "brew install verapdf, or https://verapdf.org/software/"
29
+ }.freeze
30
+
31
+ # Raised when a check needs a tool that is not installed: the message names the install command.
32
+ class ToolMissing < StandardError; end
33
+
34
+ class << self
35
+ # A password encrypted PDFs open with: the tools are given it when they cannot open one without.
36
+ attr_accessor :password
37
+
38
+ # The pages of the PDF, their text read by MuPDF.
39
+ def text_layout(pdf)
40
+ with_path(pdf) { |path| parse_text(mutool("draw", "-F", "stext", "-o", "-", path)) }
41
+ end
42
+
43
+ # The text of each page by line, top to bottom: what a reader sees, words joined.
44
+ def text_lines(pdf)
45
+ text_layout(pdf).map { |page| page.glyphs.group_by(&:last).sort.map! { |_y, glyphs| glyphs.map(&:first).join } }
46
+ end
47
+
48
+ # What makes qpdf or Poppler find the PDF broken, nil when nothing does. qpdf exits 3 for warnings: a PDF readers
49
+ # have to repair is not a valid one. Poppler checks the operands of content stream operators, which qpdf does not.
50
+ def invalidity(pdf)
51
+ with_path(pdf) do |path|
52
+ output, status = run("qpdf", "--check", path)
53
+ output, status = run("qpdf", "--check", "--password=#{password}", path) if password && output.include?("invalid password")
54
+ next output.lines.grep(/WARNING|ERROR|error/).first(3).join.strip.then { |problem| problem.empty? ? "qpdf exit #{status.exitstatus}" : problem } unless status.success?
55
+
56
+ errors, _status = run("pdftotext", *(password ? ["-upw", password] : []), path, File::NULL)
57
+ errors.lines.grep(/Syntax Error/).first(3).join.strip.then { |problem| problem unless problem.empty? }
58
+ end
59
+ end
60
+
61
+ # What veraPDF finds against the PDF/A flavour, nil when it passes.
62
+ def pdf_a_failure(pdf, flavour: "3b")
63
+ with_path(pdf) do |path|
64
+ report, _status = run("verapdf", "--flavour", flavour, "--format", "text", path)
65
+ report.start_with?("PASS") ? nil : report.strip
66
+ end
67
+ end
68
+
69
+ # Every difference between the pages of two PDFs: their number and sizes, each glyph with its font and position,
70
+ # then pixel rows in MuPDF and in Poppler. Empty when a reader could not tell them apart.
71
+ def page_differences(expected, actual)
72
+ with_path(expected) do |expected_path|
73
+ with_path(actual) do |actual_path|
74
+ text_differences(expected_path, actual_path) + pixel_differences(expected_path, actual_path)
75
+ end
76
+ end
77
+ end
78
+
79
+ def text_differences(expected, actual)
80
+ expected_pages = text_layout(expected)
81
+ actual_pages = text_layout(actual)
82
+ return ["#{actual_pages.size} pages instead of #{expected_pages.size}"] if expected_pages.size != actual_pages.size
83
+
84
+ expected_pages.zip(actual_pages).each_with_index.filter_map do |(expected_page, actual_page), index|
85
+ next if expected_page.size == actual_page.size && expected_page.glyphs.size == actual_page.glyphs.size &&
86
+ expected_page.glyphs.zip(actual_page.glyphs).all? { |expected_glyph, actual_glyph| same_glyph?(expected_glyph, actual_glyph) }
87
+ next "page #{index + 1}: size #{actual_page.size} instead of #{expected_page.size}" if expected_page.size != actual_page.size
88
+
89
+ position = expected_page.glyphs.zip(actual_page.glyphs).index { |expected_glyph, actual_glyph| !same_glyph?(expected_glyph, actual_glyph) }
90
+ next "page #{index + 1}: #{actual_page.glyphs.size} glyphs instead of #{expected_page.glyphs.size}" unless position
91
+
92
+ "page #{index + 1}: glyph #{position} is #{actual_page.glyphs[position].inspect} instead of #{expected_page.glyphs[position].inspect}"
93
+ end
94
+ end
95
+
96
+ def same_glyph?(expected_glyph, actual_glyph)
97
+ return false if actual_glyph.nil? || expected_glyph.first(3) != actual_glyph.first(3)
98
+
99
+ expected_glyph.last(2).zip(actual_glyph.last(2)).all? { |expected, actual| (expected - actual).abs <= POSITION_TOLERANCE }
100
+ end
101
+
102
+ # Two renderers that share no code, MuPDF and Poppler, must each draw both documents identically. Subset tags
103
+ # are made the same first: MuPDF hints glyphs differently whether a tag is valid or not.
104
+ def pixel_differences(expected, actual)
105
+ with_path(expected) do |expected_path|
106
+ with_path(actual) do |actual_path|
107
+ Dir.mktmpdir do |directory|
108
+ expected_path = with_neutral_subset_tags(expected_path, File.join(directory, "expected.pdf"))
109
+ actual_path = with_neutral_subset_tags(actual_path, File.join(directory, "actual.pdf"))
110
+ rendered_pixel_differences(expected_path, actual_path)
111
+ end
112
+ end
113
+ end
114
+ end
115
+
116
+ def rendered_pixel_differences(expected, actual)
117
+ RENDERERS.flat_map do |renderer, rasterizer|
118
+ Dir.mktmpdir do |directory|
119
+ expected_images = send(rasterizer, expected, File.join(directory, "expected"))
120
+ actual_images = send(rasterizer, actual, File.join(directory, "actual"))
121
+ expected_images.zip(actual_images).each_with_index.filter_map do |(expected_image, actual_image), index|
122
+ next if actual_image.nil? || File.binread(expected_image) == File.binread(actual_image)
123
+
124
+ "page #{index + 1}: #{differing_rows(expected_image, actual_image)} pixel rows differ at #{RESOLUTION_DPI} dpi#{" in #{renderer}" unless renderer == "MuPDF"}"
125
+ end
126
+ end
127
+ end
128
+ end
129
+
130
+ # Each page as an image file, by MuPDF.
131
+ def rasterize(pdf, prefix)
132
+ mutool("draw", "-r", RESOLUTION_DPI.to_s, "-o", "#{prefix}-%04d.pnm", pdf)
133
+ Dir["#{prefix}-*.pnm"].sort
134
+ end
135
+
136
+ def rasterize_with_poppler(pdf, prefix)
137
+ _output, status = run("pdftoppm", "-r", RESOLUTION_DPI.to_s, pdf, prefix)
138
+ run("pdftoppm", "-r", RESOLUTION_DPI.to_s, "-upw", password, pdf, prefix) if password && !status.success?
139
+ Dir["#{prefix}-*.ppm"].sort
140
+ end
141
+
142
+ def mutool(*arguments, path)
143
+ output, errors, status = Open3.capture3(tool("mutool"), arguments.first, "-q", *password_arguments("-p"), *arguments.drop(1), path, binmode: true)
144
+ raise "mutool #{arguments.first} failed on #{path}: #{errors}" unless status.success?
145
+
146
+ output
147
+ end
148
+
149
+ # The bytes of a PDF written to a file for the tools, or the path given (a String or a Pathname).
150
+ def with_path(pdf)
151
+ return yield pdf.to_s if pdf.is_a?(Pathname) || (!pdf.b.start_with?("%PDF") && !pdf.include?("\0") && File.file?(pdf))
152
+
153
+ Tempfile.create(["gamba-check", ".pdf"]) do |file|
154
+ file.binmode
155
+ file.write(pdf)
156
+ file.flush
157
+ yield file.path
158
+ end
159
+ end
160
+
161
+ # The PDF written to path with every subset tag the same. Only names after /BaseFont or /FontName change: compressed stream data can hold a tag's bytes by chance.
162
+ def with_neutral_subset_tags(pdf, path)
163
+ _output, status = run("qpdf", "--qdf", "--object-streams=disable", "--stream-data=preserve", pdf, path)
164
+ return pdf unless status.success? || status.exitstatus == QPDF_WARNINGS_EXIT_STATUS
165
+
166
+ File.binwrite(path, File.binread(path).gsub(%r{(/(?:BaseFont|FontName)\s*)/[0-9A-Za-z]{6}\+}n, '\1/AAAAAA+'))
167
+ path
168
+ end
169
+
170
+ private
171
+
172
+ def parse_text(xml)
173
+ xml.split("<page ").drop(1).map! do |page|
174
+ font = nil
175
+ glyphs = []
176
+ page.scan(/<(font|char) ([^>]*)>/) do |element, attributes|
177
+ value_by_name = attributes.scan(/(\w+)="([^"]*)"/).to_h
178
+ if element == "font"
179
+ font = [value_by_name.fetch("name").sub(/\A[A-Z]{6}\+/, ""), value_by_name.fetch("size").to_f.round(POSITION_PRECISION_DIGITS)]
180
+ else
181
+ position = value_by_name.fetch_values("x", "y").map { _1.to_f.round(POSITION_PRECISION_DIGITS) }
182
+ glyphs << [value_by_name.fetch("c"), *font, *position]
183
+ end
184
+ end
185
+ Page.new(size: page[/width="[^"]*" height="[^"]*"/], glyphs:)
186
+ end
187
+ end
188
+
189
+ def differing_rows(expected_image, actual_image)
190
+ expected_rows = pnm_rows(expected_image)
191
+ actual_rows = pnm_rows(actual_image)
192
+ return "all" if expected_rows.size != actual_rows.size
193
+
194
+ expected_rows.zip(actual_rows).count { |expected_row, actual_row| expected_row != actual_row }
195
+ end
196
+
197
+ def pnm_rows(image)
198
+ content = File.binread(image)
199
+ header = content[/\AP\d\s+\d+\s+\d+\s+\d+\s/]
200
+ _format, width, height = header.split.map { Integer(_1[/\d+/]) }
201
+ row_bytes = width * (content.start_with?("P5") ? 1 : 3)
202
+ Array.new(height) { |row| content.byteslice(header.bytesize + (row * row_bytes), row_bytes) }
203
+ end
204
+
205
+ def password_arguments(flag)
206
+ password ? [flag, password] : []
207
+ end
208
+
209
+ def run(name, *arguments)
210
+ Open3.capture2e(tool(name), *arguments)
211
+ end
212
+
213
+ def tool(name)
214
+ @found ||= {}
215
+ @found[name] ||= ENV.fetch("PATH", "").split(File::PATH_SEPARATOR).map { File.join(_1, name) }.find { File.executable?(_1) } ||
216
+ raise(ToolMissing, "#{name} is not installed: #{TOOLS.fetch(name)}")
217
+ end
218
+ end
219
+ end
220
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gamba
4
+ # What a Rails application gets once Gamba is in its bundle: `render pdf:` in controllers, `.pdf.rb` templates,
5
+ # and Gamba loaded before the server forks. Defined only when Rails is.
6
+ class Railtie < ::Rails::Railtie
7
+ # The bytes of what a controller renders or a template ends with: a Gamba::Document, a Prawn::Document, an
8
+ # object answering to_pdf (a document class of the application), or the bytes themselves.
9
+ def self.pdf(document)
10
+ if document.respond_to?(:to_pdf) then document.to_pdf
11
+ elsif document.is_a?(Gamba::Document) then document.to_s
12
+ elsif document.respond_to?(:render) then document.render
13
+ elsif document.is_a?(String) then document
14
+ else raise ArgumentError, "render pdf: takes a Gamba::Document, a Prawn::Document, an object answering to_pdf or a PDF's bytes, not #{document.class}"
15
+ end.b
16
+ end
17
+
18
+ # A `.pdf.rb` template: its code runs in the view, helpers and translations at hand, with `document`, a
19
+ # Gamba::Document; Prawn's API is at document.prawn. A template that ends with a document of its own (Gamba's
20
+ # or Prawn's) renders that one instead. A PDF is bytes, not text: the response loses the charset Rails adds.
21
+ module TemplateHandler
22
+ def self.call(template, source)
23
+ <<~RUBY
24
+ document = ::Gamba::Document.new
25
+ result = begin
26
+ #{source}
27
+ end
28
+ if respond_to?(:response) && response
29
+ response.content_type = Mime[:pdf].to_s
30
+ response.charset = false
31
+ end
32
+ ::Gamba::Railtie.pdf(result.is_a?(::Gamba::Document) || result.is_a?(::Prawn::Document) ? result : document)
33
+ RUBY
34
+ end
35
+ end
36
+
37
+ # Before the server forks its workers, so they share what Gamba loads instead of each loading its own.
38
+ config.before_eager_load { Gamba.eager_load! }
39
+
40
+ initializer "gamba.renderer" do
41
+ ActiveSupport.on_load(:action_controller) do
42
+ ActionController::Renderers.add(:pdf) do |document, options|
43
+ send_data Gamba::Railtie.pdf(document), {type: Mime[:pdf], disposition: "inline"}.merge(options.slice(:filename, :disposition, :status))
44
+ end
45
+ end
46
+ end
47
+
48
+ initializer "gamba.template_handler" do
49
+ ActiveSupport.on_load(:action_view) { ActionView::Template.register_template_handler(:rb, Gamba::Railtie::TemplateHandler) }
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "gamba/testing"
4
+
5
+ module Gamba
6
+ # require "gamba/rspec": matchers on PDFs, as bytes or a file's path, in every example group.
7
+ module RSpec
8
+ # A matcher whose check returns nil when it passes, or the failure's words.
9
+ class Matcher
10
+ def initialize(description, &check)
11
+ @description = description
12
+ @check = check
13
+ end
14
+
15
+ def matches?(pdf)
16
+ @failure = @check.call(pdf)
17
+ @failure.nil?
18
+ rescue Gamba::PdfCheck::ToolMissing => error
19
+ raise if Gamba::Testing.missing_tools == :fail
20
+
21
+ ::RSpec::Core::Pending.mark_skipped!(::RSpec.current_example, error.message) if defined?(::RSpec::Core::Pending)
22
+ raise ::RSpec::Core::Pending::SkipDeclaredInExample, error.message
23
+ end
24
+
25
+ def does_not_match?(pdf)
26
+ !matches?(pdf)
27
+ end
28
+
29
+ def failure_message
30
+ @failure
31
+ end
32
+
33
+ def failure_message_when_negated
34
+ "expected the PDF not to #{@description}"
35
+ end
36
+
37
+ attr_reader :description
38
+ end
39
+
40
+ def have_pdf_text(text, page: nil, at: nil)
41
+ Matcher.new("have the text #{text.inspect}") { |pdf| Gamba::Testing.text_failure(pdf, text, page:, at:) }
42
+ end
43
+
44
+ def have_same_pages_as(expected)
45
+ Matcher.new("have the same pages") { |actual| Gamba::Testing.pages_failure(expected, actual) }
46
+ end
47
+
48
+ def be_a_valid_pdf
49
+ Matcher.new("be a valid PDF") { |pdf| Gamba::Testing.validity_failure(pdf) }
50
+ end
51
+
52
+ def be_pdf_a(flavour: "3b")
53
+ Matcher.new("be PDF/A-#{flavour}") { |pdf| Gamba::Testing.pdf_a_failure(pdf, flavour:) }
54
+ end
55
+ end
56
+ end
57
+
58
+ RSpec.configure { |config| config.include(Gamba::RSpec) } if defined?(RSpec.configure)
@@ -1,11 +1,13 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "digest/md5"
4
+ require "openssl"
4
5
  require "securerandom"
5
6
 
6
7
  module Prawn
7
8
  class Document
8
- # The standard security handler, revision 2: 40-bit RC4 (ISO 32000-1 §7.6.3).
9
+ # The standard security handler: 40-bit RC4 by default (revision 2, ISO 32000-1 §7.6.3), or AES-256
10
+ # (revision 6, ISO 32000-2 §7.6.4) with algorithm: :aes_256.
9
11
  module Security
10
12
  PERMISSIONS_BITS = {print_document: 3, modify_contents: 4, copy_contents: 5, modify_annotations: 6}.freeze
11
13
  FULL_PERMISSIONS = 0xFFFFFFFF
@@ -16,18 +18,48 @@ module Prawn
16
18
  def encrypt_document(options = {})
17
19
  raise Errors::PdfAViolation, "PDF/A forbids encryption" if pdf_a?
18
20
 
19
- Prawn.verify_options(%i[user_password owner_password permissions], options)
21
+ Prawn.verify_options(%i[user_password owner_password permissions algorithm], options)
22
+ options = options.dup
23
+ algorithm = options.delete(:algorithm) || :rc4_40
24
+ encryption_class = case algorithm
25
+ when :rc4_40 then Rc4Encryption
26
+ when :aes_256 then Aes256Encryption
27
+ else raise ArgumentError, "algorithm is #{algorithm.inspect}: encrypt_document takes :rc4_40 or :aes_256"
28
+ end
20
29
  @user_password = options.delete(:user_password) || ""
21
30
  @owner_password = options.delete(:owner_password) || @user_password
22
31
  @owner_password = SecureRandom.bytes(32) if @owner_password == :random
23
32
  self.permissions = options.delete(:permissions) || {}
24
- @encryption = Encryption.new(user_password: @user_password, owner_password: @owner_password, permissions: permissions_value)
33
+ @encryption = encryption_class.new(user_password: @user_password, owner_password: @owner_password, permissions: permissions_value)
34
+ declare_extension_level_8 if algorithm == :aes_256
25
35
  end
26
36
 
27
37
  def self.encrypt_string(string, key, identifier, generation)
28
38
  Arcfour.new(object_key(key, identifier, generation)).encrypt(string)
29
39
  end
30
40
 
41
+ # Algorithm 2.B (ISO 32000-2 §7.6.4.3.4): the hash of a password for revision 6, salted, and for the owner
42
+ # password also keyed by the user entry.
43
+ def self.hash_2b(password, salt, user_entry = "".b)
44
+ digest = Digest::SHA256.digest(password + salt + user_entry)
45
+ round = 0
46
+ loop do
47
+ cipher = OpenSSL::Cipher.new("aes-128-cbc").encrypt
48
+ cipher.key = digest.byteslice(0, 16)
49
+ cipher.iv = digest.byteslice(16, 16)
50
+ cipher.padding = 0
51
+ encrypted = cipher.update((password + digest + user_entry) * 64) + cipher.final
52
+ digest = case encrypted.byteslice(0, 16).bytes.sum % 3
53
+ when 0 then Digest::SHA256.digest(encrypted)
54
+ when 1 then Digest::SHA384.digest(encrypted)
55
+ else Digest::SHA512.digest(encrypted)
56
+ end
57
+ round += 1
58
+ break if round >= 64 && encrypted.getbyte(-1) <= round - 32
59
+ end
60
+ digest.byteslice(0, 32)
61
+ end
62
+
31
63
  # The key of one object: the document key extended with its number and generation (algorithm 1), and with
32
64
  # "sAlT" for AES-128, which only PDF::Core::Decryption reads.
33
65
  def self.object_key(key, identifier, generation, salt = nil)
@@ -43,6 +75,12 @@ module Prawn
43
75
 
44
76
  private
45
77
 
78
+ # Revision 6 came as Adobe's extension level 8 to PDF 1.7, before ISO 32000-2 made it part of PDF 2.0.
79
+ def declare_extension_level_8
80
+ min_version(1.7)
81
+ (@root.data[:Extensions] ||= {})[:ADBE] = {BaseVersion: :"1.7", ExtensionLevel: 8}
82
+ end
83
+
46
84
  def permissions=(permissions = {})
47
85
  @permissions ||= FULL_PERMISSIONS
48
86
  permissions.each do |key, value|
@@ -58,8 +96,8 @@ module Prawn
58
96
  end
59
97
  end
60
98
 
61
- # The keys and dictionary of an encrypted document, which depend on its file identifier.
62
- class Encryption
99
+ # Revision 2, 40-bit RC4: the keys and dictionary of an encrypted document, which depend on its file identifier.
100
+ class Rc4Encryption
63
101
  def initialize(user_password:, owner_password:, permissions:)
64
102
  @user_password = user_password
65
103
  @owner_password = owner_password
@@ -89,6 +127,96 @@ module Prawn
89
127
  {Filter: :Standard, V: 1, R: 2, O: PDF::Core::ByteString.new(owner_password_hash), U: PDF::Core::ByteString.new(user_password_hash),
90
128
  P: [@permissions].pack("L").unpack1("l")}
91
129
  end
130
+
131
+ def encrypt(bytes, key, identifier)
132
+ Security.encrypt_string(bytes, key, identifier, 0)
133
+ end
134
+ end
135
+
136
+ # Revision 6 of the standard security handler: AES-256 with the file key itself (ISO 32000-2 §7.6.4). The key,
137
+ # salts and initialization vectors are random, as the standard asks: derived from the passwords, the public salts
138
+ # would let anyone test a guess far faster than algorithm 2.B allows. Two renders give different bytes.
139
+ class Aes256Encryption
140
+ # Bits 1 and 2 are reserved and must be 0 (ISO 32000-2 table 22).
141
+ RESERVED_PERMISSIONS = 0b11
142
+ # Revision 3 on, bit 11 (assemble) and bit 9 (fill forms) grant on their own what bit 4 (modify) and bit 6
143
+ # (annotate) cover in revision 2: refused with them, as Prawn's permissions mean.
144
+ IMPLIED_PERMISSION_BY_BIT = {1 << 3 => 1 << 10, 1 << 5 => 1 << 8}.freeze
145
+ ZERO_IV = ("\x00" * 16).b.freeze
146
+
147
+ attr_reader :identifier_secret
148
+
149
+ def initialize(user_password:, owner_password:, permissions:)
150
+ @user_password = password_bytes(user_password)
151
+ @owner_password = password_bytes(owner_password)
152
+ @permissions = IMPLIED_PERMISSION_BY_BIT.reduce(permissions & ~RESERVED_PERMISSIONS) do |value, (bit, implied)|
153
+ value.anybits?(bit) ? value : value & ~implied
154
+ end
155
+ @file_key = SecureRandom.bytes(32)
156
+ @identifier_secret = SecureRandom.bytes(32)
157
+ end
158
+
159
+ def key(_file_identifier)
160
+ @file_key
161
+ end
162
+
163
+ def dictionary(_file_identifier)
164
+ user_entry = password_entry(@user_password)
165
+ owner_entry = password_entry(@owner_password, user_entry)
166
+ {Filter: :Standard, V: 5, R: 6, Length: 256, CF: {StdCF: {AuthEvent: :DocOpen, CFM: :AESV3, Length: 32}}, StmF: :StdCF, StrF: :StdCF,
167
+ U: byte_string(user_entry), UE: byte_string(wrapped_key(@user_password, user_entry)),
168
+ O: byte_string(owner_entry), OE: byte_string(wrapped_key(@owner_password, owner_entry, user_entry)),
169
+ P: [@permissions].pack("L").unpack1("l"), Perms: byte_string(permissions_entry), EncryptMetadata: true}
170
+ end
171
+
172
+ # Each string and stream: its initialization vector, then its bytes in AES-256-CBC with PKCS#7 padding.
173
+ def encrypt(bytes, key, _identifier)
174
+ iv = SecureRandom.bytes(16)
175
+ cipher = OpenSSL::Cipher.new("aes-256-cbc").encrypt
176
+ cipher.key = key
177
+ cipher.iv = iv
178
+ iv << cipher.update(bytes) << cipher.final
179
+ end
180
+
181
+ private
182
+
183
+ # Without SASLprep, as qpdf, Poppler and MuPDF take a typed password: normalized, "fi" would no longer open in
184
+ # them. 127 bytes is the limit revision 6 hashes.
185
+ def password_bytes(password)
186
+ password.to_s.encode(::Encoding::UTF_8).b.byteslice(0, 127)
187
+ rescue ::EncodingError # bytes that are no text, owner_password: :random's among them
188
+ password.to_s.b.byteslice(0, 127)
189
+ end
190
+
191
+ # Algorithm 8 (user) or 9 (owner): the password's hash, its validation salt and its key salt.
192
+ def password_entry(password, user_entry = "".b)
193
+ validation_salt = SecureRandom.bytes(8)
194
+ Security.hash_2b(password, validation_salt, user_entry) + validation_salt + SecureRandom.bytes(8)
195
+ end
196
+
197
+ # The file key encrypted with the hash of the password and its key salt, /UE or /OE.
198
+ def wrapped_key(password, entry, user_entry = "".b)
199
+ cipher = OpenSSL::Cipher.new("aes-256-cbc").encrypt
200
+ cipher.key = Security.hash_2b(password, entry.byteslice(40, 8), user_entry)
201
+ cipher.iv = ZERO_IV
202
+ cipher.padding = 0
203
+ cipher.update(@file_key) + cipher.final
204
+ end
205
+
206
+ # Algorithm 10: the permissions, encrypted so that a reader can check nobody changed /P. It asks for ECB on one
207
+ # block, which CBC with a zero IV gives byte for byte.
208
+ def permissions_entry
209
+ block = [@permissions].pack("l<") + "\xFF\xFF\xFF\xFFTadb".b + SecureRandom.bytes(4)
210
+ cipher = OpenSSL::Cipher.new("aes-256-cbc").encrypt
211
+ cipher.key = @file_key
212
+ cipher.iv = ZERO_IV
213
+ cipher.padding = 0
214
+ cipher.update(block) + cipher.final
215
+ end
216
+
217
+ def byte_string(bytes)
218
+ PDF::Core::ByteString.new(bytes)
219
+ end
92
220
  end
93
221
 
94
222
  # RC4, the stream cipher of the standard security handler's first revisions.
@@ -26,6 +26,15 @@ module Prawn
26
26
  @text_options[:style] = style
27
27
  end
28
28
 
29
+ # What the cell was given, before the document's font fills in: Gamba's own tables check the faces with them.
30
+ def font_style
31
+ @text_options[:style]
32
+ end
33
+
34
+ def font_name
35
+ @font
36
+ end
37
+
29
38
  def natural_content_width
30
39
  @natural_content_width ||= [styled_width_of(@content), @pdf.bounds.width].min
31
40
  end
@@ -64,8 +73,8 @@ module Prawn
64
73
  def with_font
65
74
  @pdf.save_font do
66
75
  options = {}
67
- options[:style] = @text_options[:style] if @text_options[:style]
68
- options[:style] ||= @pdf.font.options[:style] if @pdf.font.options[:style]
76
+ options[:style] = drawn_style if drawn_style
77
+ options[:style] ||= @pdf.font.options[:style] if @pdf.font.options[:style] && !in_its_regular?
69
78
  @pdf.font(@font || @pdf.font.family, options)
70
79
  yield
71
80
  end
@@ -86,20 +95,46 @@ module Prawn
86
95
  def text_box(extra_options = {})
87
96
  inline_format = @text_options[:inline_format]
88
97
  if inline_format
89
- options = @text_options.except(:inline_format).merge(extra_options).merge(document: @pdf)
98
+ options = drawn_text_options.except(:inline_format).merge(extra_options).merge(document: @pdf)
90
99
  array = @pdf.text_formatter.format(@content, *(inline_format.is_a?(Array) ? inline_format : []))
91
100
  Prawn::Text::Formatted::Box.new(array, options)
92
101
  else
93
- Prawn::Text::Box.new(@content, @text_options.merge(extra_options).merge(document: @pdf))
102
+ Prawn::Text::Box.new(@content, drawn_text_options.merge(extra_options).merge(document: @pdf))
94
103
  end
95
104
  end
96
105
 
97
106
  def styled_width_of(text)
98
- @pdf.width_of(text, @text_options)
107
+ return @pdf.width_of(text, @text_options) unless @sized_in_its_font
108
+
109
+ with_font { @pdf.width_of(text, drawn_text_options) }
99
110
  end
100
111
 
101
112
  private
102
113
 
114
+ # A font of one face, given by its file or by a standard face's name, its own or the document's, is its own
115
+ # regular: asked by name, Prawn would look it up in a family it does not have.
116
+ def drawn_style
117
+ style = @text_options[:style]
118
+ (style == :normal && @sized_in_its_font && one_face?) ? nil : style
119
+ end
120
+
121
+ def one_face?
122
+ @font ? !@pdf.font_families.key?(@font.to_s) : @pdf.font.family.nil?
123
+ end
124
+
125
+ def drawn_text_options
126
+ (drawn_style == @text_options[:style]) ? @text_options : @text_options.except(:style)
127
+ end
128
+
129
+ # A cell of Gamba's own tables in a font of its own is in its regular unless it names a style, as a text is:
130
+ # the style of the document around is not its own. A family without a regular takes it still, as in Prawn.
131
+ def in_its_regular?
132
+ return false unless @sized_in_its_font && @font
133
+
134
+ faces = @pdf.font_families[@font.to_s]
135
+ faces.nil? || faces.key?(:normal)
136
+ end
137
+
103
138
  # A cell is laid out while the table is sized, then drawn: the layout is drawn again unless
104
139
  # before_rendering_page, the document or a truncating height changed what the cell would wrap.
105
140
  def laid_out_box_reusable?
@@ -203,6 +238,11 @@ module Prawn
203
238
  def draw_bounded_content(_point)
204
239
  end
205
240
 
241
+ # The spanning cell is the table cell element; its stand-ins make none.
242
+ def tag_content
243
+ yield
244
+ end
245
+
206
246
  def padding_right=(value)
207
247
  @master_cell.padding_right = value if rightmost?
208
248
  end
@@ -31,6 +31,11 @@ module Prawn
31
31
  attr_reader :padding, :colspan, :rowspan, :dummy_cells, :border_widths, :border_colors, :border_lines
32
32
  attr_writer :height
33
33
  attr_accessor :borders, :content, :background_color
34
+ # In a tagged document, :header for a cell of the table header, :repeated for its copy atop a later page.
35
+ attr_writer :tag_role
36
+ # Set by Gamba's own tables: a text cell is measured in the font it is drawn in. prawn-table measures it in the
37
+ # document's, and Prawn's tables keep that.
38
+ attr_writer :sized_in_its_font
34
39
 
35
40
  def self.make(pdf, content, options = {})
36
41
  at = options.delete(:at) || [0, pdf.cursor]
@@ -55,6 +60,8 @@ module Prawn
55
60
  end
56
61
 
57
62
  def self.draw_cells(cells)
63
+ return draw_tagged_cells(cells) if cells.first&.first&.tagged?
64
+
58
65
  cells.each do |cell, point|
59
66
  cell.set_width_constraints
60
67
  cell.draw_background(point)
@@ -65,6 +72,36 @@ module Prawn
65
72
  end
66
73
  end
67
74
 
75
+ # Backgrounds and borders only decorate; the content of each cell goes into its own table cell element.
76
+ def self.draw_tagged_cells(cells)
77
+ cells.each do |cell, point|
78
+ cell.set_width_constraints
79
+ cell.tag_decoration { cell.draw_background(point) }
80
+ end
81
+ cells.each do |cell, point|
82
+ cell.tag_decoration { cell.draw_borders(point) }
83
+ cell.tag_content { cell.draw_bounded_content(point) }
84
+ end
85
+ end
86
+ private_class_method :draw_tagged_cells
87
+
88
+ def tagged?
89
+ @pdf.tagged?
90
+ end
91
+
92
+ def tag_decoration(&)
93
+ @pdf.tag_decoration(&)
94
+ end
95
+
96
+ # A copy of the header atop a later page is an artifact: the table has its header once. A cell drawn outside
97
+ # a table has no row, and no table cell element.
98
+ def tag_content(&)
99
+ return @pdf.tag_artifact(&) if @tag_role == :repeated
100
+ return yield unless respond_to?(:row)
101
+
102
+ @pdf.tag_table_cell(row, header: @tag_role == :header, colspan:, rowspan:, &)
103
+ end
104
+
68
105
  def initialize(pdf, point, options = {})
69
106
  @pdf = pdf
70
107
  @point = point
data/lib/gamba/table.rb CHANGED
@@ -85,6 +85,7 @@ module Prawn
85
85
  started_new_page_at_row = initial_row_on_initial_page
86
86
  offset = @pdf.y
87
87
  @header_row = header_rows if @header
88
+ mark_header_cells if @header && @pdf.tagged?
88
89
  cells_this_page = []
89
90
  @cells.each do |cell|
90
91
  if start_new_page?(cell, offset, reference_bounds)
@@ -149,6 +150,12 @@ module Prawn
149
150
  cell
150
151
  end
151
152
 
153
+ # Tagged, the header is made of header cells, and its copies atop later pages are artifacts.
154
+ def mark_header_cells
155
+ row(0..(number_of_header_rows - 1)).each { _1.tag_role = :header }
156
+ @header_row.each { _1.tag_role = :repeated }
157
+ end
158
+
152
159
  def number_of_header_rows
153
160
  return @header if @header.is_a?(Integer)
154
161