asciidoctor-kroki 2.0.0.rc.4 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b0e774865edef5b92ddc71019b565498769cb6e4ba33c85b4cfdb5d15b2461a6
4
- data.tar.gz: 75adfc3948f2ebb93db82b3db7d1a66b46812e3a2df68dee131107b2c9690ec9
3
+ metadata.gz: f76765d8311aa663098b90be7247a5a5af3c923a8d43e429f61430d2f6142673
4
+ data.tar.gz: 602d5d12d63fc375a4f3f86df158e5aefdbf237123bc0fc560c3ab89d33ef9e0
5
5
  SHA512:
6
- metadata.gz: 6d11fe8173cb8cadb24dbd38aace93ffdee6d35b8f2685bddcda1e8ad416576d24b56a888be83b4866ab2bd7814a744d9b027d29d9bda8c412f285791b9ec526
7
- data.tar.gz: f274cb36c9ba674675c5c373faff3e7841780f727fc0f5a50d9e875ceb705f4ba865100727630e1cdf831d27fef35cabcdf6784867280420ca38e8b2b24ec1a0
6
+ metadata.gz: dccfbb46bae6bd057ec31b8f0a2799c517da693ccc1b8ffe8a96e3dbc792fc6031bd54db34649466558b6346c32ec2712d6b8925afdd9e45c9fd3f5aae320301
7
+ data.tar.gz: 69da6d005b7fc619080b880359b97de16685f05a8f30fb1aca32bc6d1e21963926f83405255ed172a9e4b6d0b8ff360cf8fa4ac3a1c6f7690e3d75bc4603ff5c
data/.rubocop.yml CHANGED
@@ -1,5 +1,5 @@
1
1
  AllCops:
2
- TargetRubyVersion: 2.7
2
+ TargetRubyVersion: 3.2
3
3
  SuggestExtensions: false
4
4
  NewCops: enable
5
5
 
data/Gemfile CHANGED
@@ -3,3 +3,6 @@
3
3
  source 'https://rubygems.org'
4
4
 
5
5
  gemspec
6
+
7
+ # required by testcontainers-core but not declared, and no longer a default gem since Ruby 3.4
8
+ gem 'base64', '~> 0.3.0'
data/Gemfile.lock CHANGED
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- asciidoctor-kroki (2.0.0.rc.4)
4
+ asciidoctor-kroki (2.0.0)
5
5
  asciidoctor (~> 2.0)
6
6
 
7
7
  GEM
@@ -9,10 +9,18 @@ GEM
9
9
  specs:
10
10
  asciidoctor (2.0.26)
11
11
  ast (2.4.3)
12
+ base64 (0.3.0)
12
13
  diff-lcs (1.6.2)
14
+ docker-api (2.4.0)
15
+ excon (>= 0.64.0)
16
+ multi_json
17
+ excon (1.2.5)
18
+ logger
13
19
  json (2.13.0)
14
20
  language_server-protocol (3.17.0.5)
15
21
  lint_roller (1.1.0)
22
+ logger (1.7.0)
23
+ multi_json (1.15.0)
16
24
  parallel (1.27.0)
17
25
  parser (3.3.8.0)
18
26
  ast (~> 2.4.1)
@@ -50,6 +58,8 @@ GEM
50
58
  parser (>= 3.3.7.2)
51
59
  prism (~> 1.4)
52
60
  ruby-progressbar (1.13.0)
61
+ testcontainers-core (0.2.0)
62
+ docker-api (~> 2.2)
53
63
  unicode-display_width (3.1.4)
54
64
  unicode-emoji (~> 4.0, >= 4.0.4)
55
65
  unicode-emoji (4.0.4)
@@ -59,9 +69,11 @@ PLATFORMS
59
69
 
60
70
  DEPENDENCIES
61
71
  asciidoctor-kroki!
72
+ base64 (~> 0.3.0)
62
73
  rake (~> 13.3.0)
63
74
  rspec (~> 3.13.1)
64
75
  rubocop (~> 1.78)
76
+ testcontainers-core (~> 0.2.0)
65
77
 
66
78
  BUNDLED WITH
67
79
  2.3.15
@@ -32,4 +32,5 @@ Gem::Specification.new do |s|
32
32
  s.add_development_dependency 'rake', '~> 13.3.0'
33
33
  s.add_development_dependency 'rspec', '~> 3.13.1'
34
34
  s.add_development_dependency 'rubocop', '~> 1.78'
35
+ s.add_development_dependency 'testcontainers-core', '~> 0.2.0'
35
36
  end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AsciidoctorExtensions
4
+ # Reads attribute values, the same way as src/attributes.js in the JavaScript/Node.js extension.
5
+ module KrokiAttributes
6
+ # Returns the value of an attribute as a stripped string, or nil if it has none (unset, empty,
7
+ # blank, or `true` for a flag set through the API), so that the caller's default applies.
8
+ def self.value(value)
9
+ return if value == true
10
+
11
+ value = value.to_s.strip
12
+ value unless value.empty?
13
+ end
14
+ end
15
+ end
@@ -4,6 +4,8 @@ require 'digest'
4
4
  require 'fileutils'
5
5
  require 'json'
6
6
  require 'securerandom'
7
+ require_relative 'attributes'
8
+ require_relative 'path_policy'
7
9
 
8
10
  module AsciidoctorExtensions
9
11
  # Persistent, content-addressed cache for fetched diagrams, independent of the output
@@ -17,11 +19,15 @@ module AsciidoctorExtensions
17
19
 
18
20
  class << self
19
21
  # Resolves the persistent cache directory.
20
- # Uses the `kroki-cache-dir` attribute when set; otherwise defaults to the XDG cache
21
- # directory (`$XDG_CACHE_HOME/kroki` or `~/.cache/kroki`).
22
- def resolve_cache_dir(doc)
23
- configured = doc.attr('kroki-cache-dir')
24
- return configured if configured && !configured.empty?
22
+ # Uses the `kroki-cache-dir` attribute when set and allowed by the safe mode; otherwise
23
+ # defaults to the XDG cache directory (`$XDG_CACHE_HOME/kroki` or `~/.cache/kroki`).
24
+ def resolve_cache_dir(doc, logger = ::Asciidoctor::LoggerManager.logger)
25
+ configured = KrokiAttributes.value(doc.attr('kroki-cache-dir'))
26
+ if configured
27
+ return configured if KrokiPathPolicy.cache_dir_allowed?(doc, configured)
28
+
29
+ warn_ignored_cache_dir(doc, configured, logger)
30
+ end
25
31
 
26
32
  xdg_cache_home = ENV['XDG_CACHE_HOME'] || File.join(Dir.home, '.cache')
27
33
  File.join(xdg_cache_home, 'kroki')
@@ -54,7 +60,7 @@ module AsciidoctorExtensions
54
60
  # unwritable home directory), so failures are only reported, once per document rather
55
61
  # than once per diagram.
56
62
  def options(doc, logger)
57
- cache_dir = resolve_cache_dir(doc)
63
+ cache_dir = resolve_cache_dir(doc, logger)
58
64
  on_cache_error = lambda do |error|
59
65
  next if doc.instance_variable_get(:@kroki_cache_warned)
60
66
 
@@ -110,6 +116,13 @@ module AsciidoctorExtensions
110
116
 
111
117
  private
112
118
 
119
+ def warn_ignored_cache_dir(doc, cache_dir, logger)
120
+ return if doc.instance_variable_get(:@kroki_cache_dir_ignored)
121
+
122
+ doc.instance_variable_set(:@kroki_cache_dir_ignored, true)
123
+ logger.warn "kroki: ignoring the kroki-cache-dir attribute '#{cache_dir}', because it is outside of the base directory."
124
+ end
125
+
113
126
  def cache_file_path(cache_dir, key, format)
114
127
  File.join(cache_dir, "#{key}.#{format}")
115
128
  end
@@ -3,6 +3,8 @@
3
3
  require 'cgi'
4
4
  require 'pathname'
5
5
  require 'asciidoctor/extensions' unless RUBY_ENGINE == 'opal'
6
+ require_relative 'attributes'
7
+ require_relative 'http_limits'
6
8
  require_relative 'preprocess'
7
9
  require_relative 'cache'
8
10
 
@@ -78,21 +80,22 @@ module AsciidoctorExtensions
78
80
  role = attrs['role']
79
81
  target = parent.apply_subs(target, [:attributes])
80
82
 
81
- unless read_allowed?(target)
83
+ # like include::, reading a remote target requires allow-uri-read and is disabled in secure mode
84
+ unless read_allowed?(target) && (!remote_target?(target) || (parent.document.attr?('allow-uri-read') && parent.document.safe < ::Asciidoctor::SafeMode::SECURE))
82
85
  link = create_inline(parent, :anchor, target, type: :link, target: target)
83
86
  return create_block(parent, :paragraph, link.convert, {}, content_model: :raw)
84
87
  end
85
88
 
86
89
  unless (path = resolve_target_path(parent, target))
87
- logger.error message_with_context "#{diagram_type} block macro not found: #{target}.", source_location: parent.document.reader.cursor_at_mark
88
- return create_block(parent, 'paragraph', unresolved_block_macro_message(diagram_type, target), {})
90
+ logger.warn message_with_context "Skipping #{diagram_type} block: block macro not found: #{target}.", source_location: parent.document.reader.cursor_at_mark
91
+ return create_error_block(parent, unresolved_block_macro_message(diagram_type, target), attrs, role)
89
92
  end
90
93
 
91
94
  begin
92
95
  diagram_text = read(path)
93
96
  rescue => e # rubocop:disable Style/RescueStandardError
94
- logger.error message_with_context "Failed to read #{diagram_type} file: #{path}. #{e}.", source_location: parent.document.reader.cursor_at_mark
95
- return create_block(parent, 'paragraph', unresolved_block_macro_message(diagram_type, path), {})
97
+ logger.warn message_with_context "Skipping #{diagram_type} block: failed to read #{path}. #{e}.", source_location: parent.document.reader.cursor_at_mark
98
+ return create_error_block(parent, unresolved_block_macro_message(diagram_type, target), attrs, role)
96
99
  end
97
100
  begin
98
101
  KrokiProcessor.process(self, parent, attrs, diagram_type, diagram_text, @logger, resource_path: path)
@@ -100,8 +103,7 @@ module AsciidoctorExtensions
100
103
  # Matches the JavaScript/Node.js extension: a failure talking to the Kroki server
101
104
  # shouldn't abort the whole document conversion, so it's degraded to a warning instead.
102
105
  logger.warn message_with_context "Skipping #{diagram_type} block: #{e.message}", source_location: parent.document.reader.cursor_at_mark
103
- attrs['role'] = role ? "#{role} kroki-error" : 'kroki-error'
104
- create_block(parent, 'paragraph', "#{e.message} - #{diagram_type}::#{target}[]", attrs)
106
+ create_error_block(parent, "#{e.message} - #{diagram_type}::#{target}[]", attrs, role)
105
107
  end
106
108
  end
107
109
  # rubocop:enable Metrics/AbcSize
@@ -113,6 +115,8 @@ module AsciidoctorExtensions
113
115
  # @param parent [Asciidoctor::AbstractBlock] the parent asciidoc block of the block or block macro being processed
114
116
  # @param target [String] the target value of a block macro
115
117
  def resolve_target_path(parent, target)
118
+ return target if remote_target?(target)
119
+
116
120
  parent.normalize_system_path(target)
117
121
  end
118
122
 
@@ -120,15 +124,23 @@ module AsciidoctorExtensions
120
124
  true
121
125
  end
122
126
 
127
+ def create_error_block(parent, message, attrs, role)
128
+ attrs['role'] = role.nil_or_empty? ? 'kroki-error' : "#{role} kroki-error"
129
+ create_block(parent, 'paragraph', message, attrs)
130
+ end
131
+
123
132
  def read(target)
124
- if target.start_with?('http://') || target.start_with?('https://')
125
- require 'open-uri'
126
- ::OpenURI.open_uri(target, &:read)
133
+ if remote_target?(target)
134
+ KrokiHttpLimits.read_uri(target)
127
135
  else
128
136
  File.read(target, mode: 'rb:utf-8:utf-8')
129
137
  end
130
138
  end
131
139
 
140
+ def remote_target?(target)
141
+ target.start_with?('http://', 'https://')
142
+ end
143
+
132
144
  def unresolved_block_macro_message(name, target)
133
145
  "Unresolved block macro - #{name}::#{target}[]"
134
146
  end
@@ -150,6 +162,7 @@ module AsciidoctorExtensions
150
162
  excalidraw
151
163
  goat
152
164
  graphviz
165
+ lini
153
166
  mermaid
154
167
  nomnoml
155
168
  nwdiag
@@ -173,6 +186,7 @@ module AsciidoctorExtensions
173
186
 
174
187
  # Internal processor
175
188
  #
189
+ # rubocop:disable Metrics/ClassLength
176
190
  class KrokiProcessor
177
191
  include Asciidoctor::Logging
178
192
 
@@ -183,14 +197,17 @@ module AsciidoctorExtensions
183
197
  class << self
184
198
  # rubocop:disable Metrics/AbcSize, Metrics/PerceivedComplexity
185
199
  def process(processor, parent, attrs, diagram_type, diagram_text, logger, resource_path: nil)
200
+ # Work on a copy, like the JavaScript extension, so that the kroki-error block that
201
+ # the caller creates on failure keeps the original attributes, such as the title.
202
+ attrs = attrs.dup
186
203
  doc = parent.document
187
- diagram_text = prepend_plantuml_config(diagram_text, diagram_type, doc, logger)
188
- diagram_text = preprocess_plantuml_includes(diagram_text, diagram_type, doc, resource_path, logger)
189
204
  # If "subs" attribute is specified, substitute accordingly.
190
205
  # Be careful not to specify "specialcharacters" or your diagram code won't be valid anymore!
191
206
  if (subs = attrs['subs'])
192
207
  diagram_text = parent.apply_subs(diagram_text, parent.resolve_subs(subs))
193
208
  end
209
+ diagram_text = prepend_plantuml_config(diagram_text, diagram_type, doc, logger)
210
+ diagram_text = preprocess_plantuml_includes(diagram_text, diagram_type, doc, resource_path, logger)
194
211
  attrs.delete('opts')
195
212
  # Apply the option defined on the block/macro or, as a fallback, the document-wide kroki-default-options.
196
213
  if (option = get_option(attrs, doc)) && option != 'none'
@@ -201,7 +218,7 @@ module AsciidoctorExtensions
201
218
  attrs['format'] = format
202
219
  opts = attrs.filter { |key, _| key.is_a?(String) && BUILTIN_ATTRIBUTES.none? { |k| key == k } && !key.end_with?('-option') }
203
220
  normalize_diagram_options(diagram_type, opts)
204
- kroki_diagram = KrokiDiagram.new(diagram_type, format, diagram_text, attrs['target'], opts)
221
+ kroki_diagram = KrokiDiagram.new(diagram_type, format, diagram_text, output_name(doc, attrs['target'], logger), opts)
205
222
  kroki_client = KrokiClient.new({
206
223
  server_url: server_url(doc),
207
224
  http_method: http_method(doc),
@@ -239,15 +256,15 @@ module AsciidoctorExtensions
239
256
  opts.delete('separation')
240
257
  end
241
258
 
242
- # Prepends the kroki-plantuml-include file content to the diagram text. Unlike the
243
- # !include directives resolved by preprocess_plantuml_includes below, this path is jailed
244
- # to the document's safe-mode boundaries via normalize_system_path, since the attribute
245
- # value (unlike an !include target written by the diagram's author) may come from outside
246
- # the diagram itself (e.g. a document-wide default set by a build script).
259
+ # Prepends the kroki-plantuml-include file content to the diagram text. A local path is
260
+ # jailed to the document's safe-mode boundaries via normalize_system_path, and a URL
261
+ # follows the same rules as an !include directive.
247
262
  def prepend_plantuml_config(diagram_text, diagram_type, doc, logger)
248
- if PLANTUML_TYPES.include?(diagram_type) && doc.safe < ::Asciidoctor::SafeMode::SECURE && doc.attr?('kroki-plantuml-include')
249
- plantuml_include_path = doc.normalize_system_path(doc.attr('kroki-plantuml-include'))
250
- if ::File.readable? plantuml_include_path
263
+ if PLANTUML_TYPES.include?(diagram_type) && doc.safe < ::Asciidoctor::SafeMode::SECURE && (plantuml_include = KrokiAttributes.value(doc.attr('kroki-plantuml-include')))
264
+ return prepend_remote_plantuml_config(diagram_text, plantuml_include, doc, logger) if plantuml_include.start_with?('http://', 'https://')
265
+
266
+ plantuml_include_path = doc.normalize_system_path(plantuml_include)
267
+ if ::File.file?(plantuml_include_path) && ::File.readable?(plantuml_include_path)
251
268
  config = File.read(plantuml_include_path)
252
269
  diagram_text = "#{config}\n#{diagram_text}"
253
270
  else
@@ -258,16 +275,34 @@ module AsciidoctorExtensions
258
275
  diagram_text
259
276
  end
260
277
 
278
+ def prepend_remote_plantuml_config(diagram_text, url, doc, logger)
279
+ policy = read_policy(doc)
280
+ raise policy.denial_reason(url) if policy.denial_reason(url)
281
+
282
+ config = PlantUmlPreprocessor.preprocess(KrokiHttpLimits.read_uri(url), url, plantuml_include_paths(doc), logger, policy)
283
+ "#{config}\n#{diagram_text}"
284
+ rescue StandardError
285
+ logger.warn message_with_context "Unable to read plantuml-include. File not found or not readable: #{url}.", source_location: doc.reader.cursor_at_mark
286
+ diagram_text
287
+ end
288
+
261
289
  # Resolves !include/!include_once/!include_many/!includeurl/!includesub directives found in
262
290
  # PlantUML/C4-PlantUML diagram text (including text prepended above), searching resource_path's
263
- # own directory and then each directory in kroki-plantuml-include-paths, in order. Unlike
264
- # kroki-plantuml-include above, this mirrors the JavaScript extension's preprocessor and is
265
- # not jailed to the safe-mode boundary (see src/preprocess.js) — only gated by safe mode itself.
291
+ # own directory, then each directory in kroki-plantuml-include-paths, in order, and finally the
292
+ # base directory. Like the JavaScript extension's preprocessor, reads follow the rules of include::.
266
293
  def preprocess_plantuml_includes(diagram_text, diagram_type, doc, resource_path, logger)
267
294
  return diagram_text unless PLANTUML_TYPES.include?(diagram_type) && doc.safe < ::Asciidoctor::SafeMode::SECURE
268
295
 
269
- include_paths = doc.attr('kroki-plantuml-include-paths')
270
- PlantUmlPreprocessor.preprocess(diagram_text, resource_path, include_paths, logger)
296
+ PlantUmlPreprocessor.preprocess(diagram_text, resource_path, plantuml_include_paths(doc), logger, read_policy(doc))
297
+ end
298
+
299
+ def plantuml_include_paths(doc)
300
+ KrokiAttributes.value(doc.attr('kroki-plantuml-include-paths'))
301
+ end
302
+
303
+ def read_policy(doc)
304
+ base_dir = ::File.expand_path(doc.base_dir)
305
+ PlantUmlPreprocessor::ReadPolicy.new(doc.attr?('allow-uri-read'), doc.safe >= ::Asciidoctor::SafeMode::SAFE ? base_dir : nil, base_dir)
271
306
  end
272
307
 
273
308
  def get_alt(attrs)
@@ -281,15 +316,7 @@ module AsciidoctorExtensions
281
316
  end
282
317
 
283
318
  def get_role(format, role)
284
- if role
285
- if format
286
- "#{role} kroki-format-#{format} kroki"
287
- else
288
- "#{role} kroki"
289
- end
290
- else
291
- 'kroki'
292
- end
319
+ role.nil_or_empty? ? 'kroki' : "#{role} kroki-format-#{format} kroki"
293
320
  end
294
321
 
295
322
  # Get the option defined on the block or macro.
@@ -307,17 +334,27 @@ module AsciidoctorExtensions
307
334
  end
308
335
 
309
336
  def get_format(doc, attrs, diagram_type)
310
- format = attrs['format'] || doc.attr('kroki-default-format') || 'svg'
337
+ format = KrokiAttributes.value(attrs['format']) || KrokiAttributes.value(doc.attr('kroki-default-format')) || 'svg'
311
338
  if format == 'png'
312
339
  # redirect PNG format to SVG if the diagram library only supports SVG as output format.
313
340
  # this is useful when the default format has been set to PNG
314
- # Currently, goat, nomnoml, svgbob, wavedrom only support SVG as output format.
315
- svg_only_diagram_types = %i[goat nomnoml svgbob wavedrom]
341
+ # Currently, bpmn, bytefield, d2, dbml, excalidraw, goat, lini, nomnoml, pikchr, svgbob, wavedrom only support SVG as output format.
342
+ svg_only_diagram_types = %i[bpmn bytefield d2 dbml excalidraw goat lini nomnoml pikchr svgbob wavedrom]
316
343
  format = 'svg' if svg_only_diagram_types.include?(diagram_type)
317
344
  end
318
345
  format
319
346
  end
320
347
 
348
+ # Checks a diagram file name that comes from the document before it is written to the output
349
+ # directory, like Asciidoctor does for the paths it resolves when the safe mode is `safe` or higher.
350
+ def output_name(doc, target, logger)
351
+ return target unless target.is_a?(::String) && doc.attr('kroki-fetch-diagram') && doc.safe.between?(::Asciidoctor::SafeMode::SAFE, ::Asciidoctor::SafeMode::SERVER)
352
+ return target unless target.split(%r{[\\/]}).include?('..')
353
+
354
+ logger.warn "kroki: ignoring the diagram file name '#{target}', because it is outside of the output directory."
355
+ nil
356
+ end
357
+
321
358
  def apply_image_src(attrs, image_src)
322
359
  attrs['target'] = image_src[:target]
323
360
  attrs['imagesdir'] = image_src[:imagesdir] if image_src[:imagesdir]
@@ -325,10 +362,13 @@ module AsciidoctorExtensions
325
362
 
326
363
  def create_image_src(doc, kroki_diagram, kroki_client, logger, inline: false)
327
364
  if doc.attr('kroki-fetch-diagram') && doc.safe < ::Asciidoctor::SafeMode::SECURE
328
- # Embedded images use the same persistent cache, but never write an output image.
329
- return { target: kroki_diagram.to_data_uri(kroki_client, **KrokiCache.options(doc, logger)) } if doc.attr?('data-uri') || doc.attr?('kroki-data-uri')
365
+ # The format is part of the name of the output file and of the cache entry.
366
+ raise "Invalid diagram format '#{kroki_diagram.format}'" if kroki_diagram.format.match?(%r{[\\/]})
330
367
 
331
368
  images_output_dir = output_dir_path(doc)
369
+ # Embedded images use the same persistent cache, but never write an output image.
370
+ return { target: kroki_diagram.to_data_uri(kroki_client, **KrokiCache.options(doc, logger)) } if embed_image?(doc, images_output_dir, logger)
371
+
332
372
  diagram_name = kroki_diagram.save(images_output_dir, kroki_client, generated_files(doc), logger, **KrokiCache.options(doc, logger))
333
373
  # The converter resolves the image target against the document's `imagesdir`
334
374
  # attribute, which only matches where we actually wrote the file when
@@ -350,17 +390,27 @@ module AsciidoctorExtensions
350
390
  # NOTE: as of this writing, Asciidoctor core's HTML5 converter treats a `data:` URI target
351
391
  # the same as any other remote URI and still refuses to read it without `allow-uri-read`
352
392
  # (https://github.com/asciidoctor/asciidoctor/issues/3791) — so today this still renders a
353
- # blank placeholder, only later than before. A fix decoding `data:` targets directly is
354
- # proposed upstream (https://github.com/asciidoctor/asciidoctor/pull/4865, not yet merged);
355
- # this branch is aligned with it ahead of time, matching the JavaScript/Node.js extension
356
- # (already correct against Asciidoctor.js >= 4.0.2, which carries the equivalent fix), so
357
- # it starts working here too as soon as a released gem picks it up — no code change needed.
393
+ # blank placeholder, only later than before. The fix is merged upstream but not yet in a
394
+ # released gem (still absent from 2.0.26); this branch is aligned with it ahead of time,
395
+ # matching the JavaScript/Node.js extension (already correct against Asciidoctor.js >= 4.0.2,
396
+ # which carries the equivalent fix), so it starts working here too as soon as a released gem
397
+ # picks it up — no code change needed.
358
398
  { target: kroki_diagram.to_data_uri(kroki_client) }
359
399
  else
360
400
  { target: kroki_diagram.get_diagram_uri(server_url(doc)) }
361
401
  end
362
402
  end
363
403
 
404
+ # A document cannot write outside of the directories allowed by the safe mode, so the
405
+ # diagram is embedded instead.
406
+ def embed_image?(doc, images_output_dir, logger)
407
+ return true if doc.attr?('data-uri') || doc.attr?('kroki-data-uri')
408
+ return false if KrokiPathPolicy.images_dir_allowed?(doc, images_output_dir)
409
+
410
+ logger.warn "kroki: embedding the diagram as a data URI, because the directory '#{images_output_dir}' is outside of the base directory."
411
+ true
412
+ end
413
+
364
414
  # Returns the per-document registry of generated file names, mapping each name
365
415
  # to the diagram URI it was generated from. Used to detect name clashes within
366
416
  # a single conversion.
@@ -370,7 +420,7 @@ module AsciidoctorExtensions
370
420
  end
371
421
 
372
422
  def server_url(doc)
373
- doc.attr('kroki-server-url', 'https://kroki.io')
423
+ KrokiAttributes.value(doc.attr('kroki-server-url')) || 'https://kroki.io'
374
424
  end
375
425
 
376
426
  def http_method(doc)
@@ -401,6 +451,8 @@ module AsciidoctorExtensions
401
451
  end
402
452
  end
403
453
 
454
+ # rubocop:enable Metrics/ClassLength
455
+
404
456
  # Kroki diagram
405
457
  #
406
458
  class KrokiDiagram
@@ -571,7 +623,8 @@ module AsciidoctorExtensions
571
623
  }.freeze
572
624
 
573
625
  def initialize(opts, logger = ::Asciidoctor::LoggerManager.logger)
574
- @server_url = opts[:server_url]
626
+ # remove trailing slashes
627
+ @server_url = opts[:server_url]&.gsub(%r{/+$}, '')
575
628
  @max_uri_length = opts.fetch(:max_uri_length, 4000)
576
629
  @http_client = opts[:http_client]
577
630
  @source_location = opts[:source_location]
@@ -628,21 +681,12 @@ module AsciidoctorExtensions
628
681
  require 'json'
629
682
 
630
683
  class << self
631
- REFERER = "asciidoctor/kroki.rb/#{Asciidoctor::AsciidoctorKroki::VERSION}"
684
+ REFERER = "asciidoctor/kroki.rb/#{Asciidoctor::AsciidoctorKroki::VERSION}".freeze
632
685
 
633
686
  def get(uri, opts, _encoding, expected_content_type = nil)
634
- parsed_uri = URI(uri)
635
687
  headers = opts.transform_keys { |key| "Kroki-Diagram-Options-#{key}" }
636
688
  .merge({ 'referer' => REFERER })
637
- request = ::Net::HTTP::Get.new(parsed_uri, headers)
638
- response = ::Net::HTTP.start(
639
- parsed_uri.hostname,
640
- parsed_uri.port,
641
- use_ssl: (parsed_uri.scheme == 'https')
642
- ) do |http|
643
- http.request(request)
644
- end
645
- handle_response(response, 'GET', uri, expected_content_type)
689
+ send_request('GET', uri, ::Net::HTTP::Get.new(URI(uri), headers), expected_content_type)
646
690
  end
647
691
 
648
692
  def post(uri, data, opts, _encoding, expected_content_type = nil)
@@ -651,16 +695,35 @@ module AsciidoctorExtensions
651
695
  'Content-Type' => 'text/plain',
652
696
  'referer' => REFERER
653
697
  })
654
- response = ::Net::HTTP.post(
655
- URI(uri),
656
- data,
657
- headers
658
- )
659
- handle_response(response, 'POST', uri, expected_content_type)
698
+ request = ::Net::HTTP::Post.new(URI(uri), headers)
699
+ request.body = data
700
+ send_request('POST', uri, request, expected_content_type)
660
701
  end
661
702
 
662
703
  private
663
704
 
705
+ def send_request(method, uri, request, expected_content_type)
706
+ parsed_uri = URI(uri)
707
+ response = KrokiHttpLimits.with_timeout(method, uri) do
708
+ ::Net::HTTP.start(parsed_uri.hostname, parsed_uri.port, use_ssl: (parsed_uri.scheme == 'https')) do |http|
709
+ http.request(request) { |incoming| read_body(incoming, method, uri) }
710
+ end
711
+ end
712
+ handle_response(response, method, uri, expected_content_type)
713
+ end
714
+
715
+ # Reads the body incrementally, so that no more than the maximum size is ever accumulated,
716
+ # even when the server omits (or lies about) Content-Length.
717
+ def read_body(response, method, uri)
718
+ KrokiHttpLimits.check_size(response['content-length'].to_i, method, uri)
719
+ body = String.new
720
+ response.read_body do |chunk|
721
+ body << chunk
722
+ KrokiHttpLimits.check_size(body.bytesize, method, uri)
723
+ end
724
+ response.body = body
725
+ end
726
+
664
727
  # Mirrors the JavaScript/Node.js extension's http-client.js: unlike Net::HTTP, which
665
728
  # returns whatever body the server sent regardless of status code, this raises a clear
666
729
  # error for a non-2xx response, an unexpected content-type (e.g. the Kroki server
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'timeout'
4
+
5
+ module AsciidoctorExtensions
6
+ # Limits of the HTTP requests sent to Kroki and of the remote resources read by the extension,
7
+ # the same way as src/http-client.js in the JavaScript/Node.js extension.
8
+ module KrokiHttpLimits
9
+ # Maximum time in seconds for a request, including the time needed to receive the complete response body.
10
+ TIMEOUT = 60
11
+ # Maximum size in bytes of a response body.
12
+ MAX_RESPONSE_SIZE = 25 * 1024 * 1024
13
+
14
+ class TimedOut < StandardError; end
15
+ private_constant :TimedOut
16
+
17
+ class << self
18
+ def with_timeout(method, uri, &)
19
+ ::Timeout.timeout(self::TIMEOUT, TimedOut, &)
20
+ rescue TimedOut
21
+ raise "#{method} #{uri} - timed out after #{self::TIMEOUT}s"
22
+ end
23
+
24
+ def check_size(size, method, uri)
25
+ raise "#{method} #{uri} - response exceeds maximum size of #{self::MAX_RESPONSE_SIZE} bytes" if size > self::MAX_RESPONSE_SIZE
26
+ end
27
+
28
+ def read_uri(uri)
29
+ require 'open-uri'
30
+ with_timeout('GET', uri) do
31
+ check = ->(size) { check_size(size.to_i, 'GET', uri) }
32
+ ::OpenURI.open_uri(uri, { content_length_proc: check, progress_proc: check }, &:read)
33
+ end
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AsciidoctorExtensions
4
+ # Checks the paths used by the extension against the safe mode, the same way as
5
+ # src/read-policy.js in the JavaScript/Node.js extension.
6
+ module KrokiPathPolicy
7
+ class << self
8
+ # A lexical check, like Asciidoctor
9
+ def inside?(path, dir)
10
+ resolved = normalize(path)
11
+ dir = normalize(dir)
12
+ resolved == dir || resolved.start_with?(dir.end_with?('/') ? dir : "#{dir}/")
13
+ end
14
+
15
+ # Checks the directory of the generated images when the safe mode is `safe` or higher. A
16
+ # value set from the API or the CLI is locked, so it cannot come from the document.
17
+ def images_dir_allowed?(doc, dir)
18
+ return true if doc.safe < ::Asciidoctor::SafeMode::SAFE
19
+
20
+ locked = if doc.attr('imagesoutdir')
21
+ doc.attribute_locked?('imagesoutdir')
22
+ else
23
+ doc.attribute_locked?('imagesdir') && (!doc.attr('outdir') || doc.attribute_locked?('outdir'))
24
+ end
25
+ locked || inside_write_root?(doc, dir)
26
+ end
27
+
28
+ # Checks the kroki-cache-dir attribute when the safe mode is `safe` or higher.
29
+ def cache_dir_allowed?(doc, dir)
30
+ doc.safe < ::Asciidoctor::SafeMode::SAFE || doc.attribute_locked?('kroki-cache-dir') || inside_write_root?(doc, dir)
31
+ end
32
+
33
+ private
34
+
35
+ # The base directory, and the output directory given to the converter.
36
+ def inside_write_root?(doc, dir)
37
+ roots = [doc.base_dir, (doc.nested? ? doc.parent_document : doc).options[:to_dir]]
38
+ roots << doc.attr('outdir') if doc.attribute_locked?('outdir')
39
+ roots.compact.any? { |root| inside?(dir, root) }
40
+ end
41
+
42
+ # The case of the drive letter varies on Windows.
43
+ def normalize(path)
44
+ expanded = ::File.expand_path(path)
45
+ ::File::ALT_SEPARATOR ? expanded.downcase : expanded
46
+ end
47
+ end
48
+ end
49
+ end