decidim-core 0.32.2 → 0.32.3

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 (82) hide show
  1. checksums.yaml +4 -4
  2. data/app/cells/decidim/address_cell.rb +7 -3
  3. data/app/cells/decidim/card_metadata_cell.rb +3 -1
  4. data/app/cells/decidim/date_range/show.erb +6 -6
  5. data/app/cells/decidim/date_range_cell.rb +7 -2
  6. data/app/commands/decidim/create_follow.rb +2 -3
  7. data/app/commands/decidim/create_omniauth_registration.rb +2 -5
  8. data/app/commands/decidim/create_user_report.rb +1 -1
  9. data/app/commands/decidim/destroy_account.rb +6 -6
  10. data/app/commands/decidim/destroy_ephemeral_user.rb +2 -0
  11. data/app/commands/decidim/invite_user.rb +1 -1
  12. data/app/commands/decidim/multiple_attachments_methods.rb +17 -3
  13. data/app/commands/decidim/update_resources_taxonomies.rb +2 -1
  14. data/app/controllers/concerns/decidim/direct_upload.rb +12 -6
  15. data/app/controllers/concerns/decidim/impersonate_users.rb +2 -2
  16. data/app/controllers/concerns/decidim/needs_organization.rb +15 -0
  17. data/app/controllers/decidim/amendments_controller.rb +34 -6
  18. data/app/controllers/decidim/application_controller.rb +2 -0
  19. data/app/controllers/decidim/authorization_modals_controller.rb +1 -1
  20. data/app/controllers/decidim/doorkeeper/authorizations_controller.rb +10 -4
  21. data/app/controllers/decidim/doorkeeper/credentials_controller.rb +6 -1
  22. data/app/controllers/decidim/messaging/conversations_controller.rb +1 -1
  23. data/app/controllers/decidim/profiles_controller.rb +1 -1
  24. data/app/helpers/decidim/cells_paginate_helper.rb +0 -5
  25. data/app/helpers/decidim/layout_helper.rb +1 -0
  26. data/app/helpers/decidim/orders_helper.rb +8 -6
  27. data/app/helpers/decidim/paginate_helper.rb +15 -3
  28. data/app/helpers/decidim/url_helper.rb +35 -0
  29. data/app/jobs/decidim/open_data_job.rb +21 -5
  30. data/app/models/decidim/action_log.rb +7 -1
  31. data/app/models/decidim/component.rb +10 -0
  32. data/app/models/decidim/like.rb +1 -1
  33. data/app/packs/src/decidim/datepicker/datepicker_functions.js +20 -7
  34. data/app/packs/src/decidim/datepicker/form_datepicker.js +18 -2
  35. data/app/packs/src/decidim/datepicker/generate_datepicker.js +12 -4
  36. data/app/packs/src/decidim/datepicker/generate_timepicker.js +5 -3
  37. data/app/packs/src/decidim/datepicker/test/date.test.js +8 -0
  38. data/app/packs/stylesheets/decidim/_datepicker.scss +3 -3
  39. data/app/packs/stylesheets/decidim/_spinner.scss +16 -0
  40. data/app/packs/stylesheets/decidim/_tom_select.scss +1 -1
  41. data/app/presenters/decidim/log/base_presenter.rb +10 -1
  42. data/app/services/decidim/action_logger.rb +97 -29
  43. data/app/services/decidim/svg_content_validator.rb +419 -84
  44. data/app/validators/uploader_image_content_validator.rb +6 -2
  45. data/app/views/decidim/manifests/show.json.erb +25 -22
  46. data/app/views/decidim/shared/_results_per_page.html.erb +1 -1
  47. data/config/locales/bg.yml +1 -3
  48. data/config/locales/ca-IT.yml +7 -3
  49. data/config/locales/ca.yml +7 -5
  50. data/config/locales/cs.yml +9 -3
  51. data/config/locales/de.yml +1 -3
  52. data/config/locales/en.yml +5 -3
  53. data/config/locales/es-MX.yml +5 -3
  54. data/config/locales/es-PY.yml +5 -3
  55. data/config/locales/es.yml +7 -5
  56. data/config/locales/eu.yml +10 -8
  57. data/config/locales/fi-plain.yml +2 -2
  58. data/config/locales/fi.yml +2 -2
  59. data/config/locales/fr-CA.yml +5 -3
  60. data/config/locales/fr.yml +5 -3
  61. data/config/locales/gl.yml +0 -1
  62. data/config/locales/it.yml +0 -2
  63. data/config/locales/ja.yml +3 -3
  64. data/config/locales/pl.yml +1 -3
  65. data/config/locales/pt-BR.yml +1 -3
  66. data/config/locales/ro-RO.yml +0 -2
  67. data/config/locales/sk.yml +68 -3
  68. data/config/locales/sv.yml +3 -3
  69. data/config/locales/tr-TR.yml +1 -1
  70. data/db/migrate/20250523104311_move_cta_to_hero_content_block.rb +1 -1
  71. data/db/migrate/20250527122040_move_highlighted_content_banner_settings_to_content_block.rb +3 -0
  72. data/db/migrate/20261007090000_make_user_optional_in_action_logs.rb +12 -0
  73. data/decidim-core.gemspec +1 -1
  74. data/lib/decidim/content_renderers/mention_resource_renderer.rb +1 -1
  75. data/lib/decidim/core/version.rb +1 -1
  76. data/lib/decidim/core.rb +1 -1
  77. data/lib/decidim/maintenance/import_models/scope.rb +2 -1
  78. data/lib/decidim/maintenance/taxonomy_importer.rb +4 -1
  79. data/lib/decidim/seeds.rb +1 -1
  80. data/lib/decidim/view_model.rb +1 -0
  81. data/lib/tasks/decidim_open_data_tasks.rake +7 -0
  82. metadata +7 -5
@@ -11,25 +11,73 @@ module Decidim
11
11
  # validation, so that documents which could execute scripts or read external
12
12
  # resources are rejected instead of being stored as they are.
13
13
  #
14
- # The document must be parseable as XML with an "svg" root element and must
15
- # not declare entities nor contain any other content which could execute
16
- # scripts or read external resources when the document is rendered.
14
+ # The document must be parseable as XML with an "svg" root element in the SVG
15
+ # namespace and must not declare entities nor contain any other content which
16
+ # could execute scripts or read external resources when the document is rendered.
17
17
  #
18
- # The references which load resources into the document (the "href" of
19
- # "image", "use", "feImage" and "cursor", the URL references of the
20
- # presentation attributes, the style sheets and the "xml-stylesheet"
21
- # instruction) are restricted to the document itself and to inline data, so
22
- # that documents cannot make the browser of the reader fetch third-party
23
- # resources. The contents of the inline data references declaring
18
+ # The namespace of the root is checked because the files are stored and served as
19
+ # images, so the engines read them as XML, where the namespace declaration is what
20
+ # makes a document an SVG document. The namespace is provided automatically only by
21
+ # the HTML parser, which is not the way these files are read, so a root in another
22
+ # namespace is not an SVG element and the document is not rendered as an SVG.
23
+ #
24
+ # The other checks are applied to the names, independently of the namespace, as a
25
+ # document can declare another namespace for its descendants. The elements which are
26
+ # not in the SVG namespace are not SVG elements and are not rendered, but they are
27
+ # rejected as well, so that a document cannot pass the checks by moving its content
28
+ # to another namespace.
29
+ #
30
+ # The documents which the parser reports as not well formed, such as the ones using a
31
+ # prefix which is not bound to a namespace, are rejected as invalid, as the engines do
32
+ # not render them either (see #parse).
33
+ #
34
+ # The references which load resources into the document (the "href" of the
35
+ # elements which resolve a reference when the document is rendered, the URL
36
+ # references of the presentation attributes, the style sheets and the
37
+ # "xml-stylesheet" instruction) are restricted to the document itself and to
38
+ # inline data, so that documents cannot make the browser of the reader fetch
39
+ # third-party resources. The contents of the inline data references declaring
24
40
  # an SVG document are validated as nested documents, as they are parsed when
25
- # the reference is rendered. Links ("a") are not restricted, as they do not
26
- # load any resource when the document is rendered; they can still reference
27
- # any host, so they are a phishing surface which is accepted on purpose.
41
+ # the reference is rendered.
42
+ #
43
+ # The references resolved against the document (the fragments and the paths
44
+ # relative to it, including the ones starting at the root) cannot reach another
45
+ # host, but they are still requested to the origin which serves the document when
46
+ # it is rendered as a document, with the credentials of the reader; the browsers of
47
+ # the readers do not resolve the references of a document used as an image. The
48
+ # response is not readable by the document, so the consequence which is accepted on
49
+ # purpose is the request itself.
50
+ #
51
+ # Links ("a") are not restricted, as they do not load any resource when the
52
+ # document is rendered; they are only followed when the reader activates them, so
53
+ # they are a phishing surface which is accepted on purpose. The schemes which
54
+ # execute scripts when navigated and the data documents declaring an HTML content
55
+ # type are still rejected (see SVG_FORBIDDEN_URI_PREFIXES). The other data
56
+ # references accepted in a link cannot be opened as a top-level document by the
57
+ # browsers of the readers, and the documents they open have an opaque origin, so
58
+ # their contents cannot read the page which contains the link.
59
+ #
60
+ # The base URI which the relative references are resolved against ("xml:base")
61
+ # is restricted to the document itself as well, as an external base makes the
62
+ # references which are relative to the document resolve against another host
63
+ # when it is rendered.
64
+ #
65
+ # The contents are limited in size, and the parser limits the depth of the tree
66
+ # and the length of the names while it reads them, so the documents which could
67
+ # exhaust the memory of the process while they are parsed are rejected before the
68
+ # checks below are applied. The documents nested inside inline data references are
69
+ # limited in depth as well, as they are parsed with the same rules. The parser
70
+ # options which lift these limits are not enabled.
28
71
  #
29
72
  # This is used by UploaderImageContentValidator, which delegates the SVG
30
73
  # specific validation to this class, so callers of that validator only need
31
74
  # to call a single validator for all the image formats.
32
75
  class SvgContentValidator
76
+ # The namespace the elements of an SVG document belong to, which is what the
77
+ # engines use to recognize an SVG document when the file is read as XML (see
78
+ # #parse).
79
+ SVG_NAMESPACE = "http://www.w3.org/2000/svg"
80
+
33
81
  # The elements which are not allowed in SVG documents, because they either
34
82
  # execute scripts themselves (e.g. "script" and the SVG Tiny "handler") or
35
83
  # allow embedding foreign content which can execute them (e.g.
@@ -51,18 +99,30 @@ module Decidim
51
99
  # attributes are validated as element/attribute names. The names are kept
52
100
  # in lowercase and compared case insensitively, as the HTML parser resolves
53
101
  # the names written in lowercase (e.g. "attributename") to the camel case
54
- # ones when the document is parsed as HTML.
102
+ # ones when the document is parsed as HTML. The value of "attributenames" is
103
+ # a list of names separated by whitespace, so each name of the list is
104
+ # checked separately (see #name_list).
55
105
  SVG_ANIMATION_TARGET_NAMES = %w(attribute attributename attributenames).freeze
56
106
 
57
- # The elements which load the resource referenced by their "href" (or
58
- # legacy "xlink:href") attribute into the document when it is rendered.
59
- # The references of these elements are restricted to the document itself
60
- # and to inline data, as absolute references make the browser of the
61
- # reader fetch resources from third-party hosts, which can be used for
62
- # tracking or for probing internal networks. Links ("a") are not
63
- # included, as they do not load any resource; they can still reference
64
- # any host, so they are a phishing surface which is accepted on purpose.
65
- SVG_RESOURCE_ELEMENTS = %w(image use feimage cursor).freeze
107
+ # The elements which resolve the reference of their "href" (or legacy
108
+ # "xlink:href") attribute when the document is rendered, either by loading
109
+ # the referenced resource (e.g. the "image", the icon of a "cursor" or the
110
+ # font of a "font-face-uri") or by resolving it to an element which may
111
+ # belong to another document, which is fetched to find it (e.g. the
112
+ # gradient a "linearGradient" inherits from, the "path" of a "textPath", or
113
+ # the elements referenced by "use", "tref" and "altGlyph"). The references
114
+ # of these elements are restricted to the document itself and to inline
115
+ # data, as absolute references make the browser of the reader fetch
116
+ # resources from third-party hosts, which can be used for tracking or for
117
+ # probing internal networks. Links ("a") are not included, as they do not
118
+ # load any resource; they can still reference any host, so they are a
119
+ # phishing surface which is accepted on purpose. The animation elements are
120
+ # not included either, as their reference identifies the target element,
121
+ # which the specification requires to be part of the same document.
122
+ SVG_RESOURCE_ELEMENTS = %w(
123
+ image use feimage cursor font-face-uri tref altglyph color-profile
124
+ lineargradient radialgradient pattern filter textpath mpath
125
+ ).freeze
66
126
 
67
127
  # The presentation attributes whose value defines a reference resolved when
68
128
  # the document is rendered. The image references (e.g. "cursor" and "mask")
@@ -72,25 +132,48 @@ module Decidim
72
132
  # mode. Their values are validated as style sheet content, as they are
73
133
  # parsed as the CSS properties they define.
74
134
  SVG_URL_PRESENTATION_ATTRIBUTES = %w(
75
- cursor mask fill stroke filter clip-path marker marker-start marker-mid marker-end
135
+ cursor mask fill stroke filter clip-path marker marker-start marker-mid marker-end color-profile
76
136
  ).freeze
77
137
 
78
138
  # The name of the attribute which references the resource loaded by an
79
- # element, either "href" or the legacy "xlink:href", which is also
80
- # matched with an undeclared prefix, as browsers resolve it as the XLink
81
- # reference.
82
- SVG_REFERENCE_NAME = /\A(?:[\w.-]+:)?href\z/i
139
+ # element, either "href" or the legacy "xlink:href". The parser reports the
140
+ # attributes which are bound to a namespace without their prefix, so any prefix
141
+ # bound to the XLink namespace is matched; the prefix is kept in the pattern to
142
+ # also cover the documents which use it without binding it, which are rejected as
143
+ # not well formed by #parse. The "src" attribute is matched as well, as it defines
144
+ # the location of the profile referenced by the "color-profile" element.
145
+ SVG_REFERENCE_NAME = /\A(?:[\w.-]+:)?(?:href|src)\z/i
146
+
147
+ # The name of the attribute which defines the base URI that the relative
148
+ # references of the document are resolved against (XML Base). The parser
149
+ # reports it without its reserved "xml" prefix, so it is matched with any
150
+ # prefix, which also covers the documents binding the XML namespace to another
151
+ # prefix (rejected as not well formed by #parse) and the ones using a "base"
152
+ # attribute in another namespace, which the engines do not interpret as XML Base
153
+ # but are rejected as well (see #forbidden_base_value?).
154
+ SVG_BASE_NAME = /\A(?:[\w.-]+:)?base\z/i
83
155
 
84
156
  # The references which load a resource from another host: URIs with a
85
157
  # scheme (e.g. "https:") and references resolving to an authority, which
86
158
  # browsers also detect from two separators at the beginning of the
87
159
  # reference (e.g. "//example.org", "/\example.org" or "\\example.org"), as
88
160
  # backslashes are treated as separators of the authority for the schemes of
89
- # the web. A single backslash only starts a path, so it is not matched.
161
+ # the web. A single backslash only starts a path, so it is not matched. The
162
+ # separators are not decoded before resolving the reference, so a reference
163
+ # whose separators are percent encoded (e.g. "/%2F%2Fexample.org") is a path
164
+ # and not an authority.
90
165
  # Fragment ("#") and relative references are resolved against the document
91
166
  # itself, and "data:" references are inline, so they are accepted (see
92
- # #forbidden_reference_value?).
93
- SVG_EXTERNAL_REFERENCE = %r{\A(?!data:)(?:[a-z][a-z0-9+.-]*:|[\\/]{2})}i
167
+ # #forbidden_reference_value?). The relative references, including the ones
168
+ # starting at the root, are requested to the origin which serves the document
169
+ # when it is rendered, as the class documentation says.
170
+ #
171
+ # The two forms are matched separately, as a quantifier inside an alternation
172
+ # makes the engine of the regular expressions allocate memory proportional to
173
+ # the length of the value, which a document with a single long value can use to
174
+ # exhaust the memory of the process (see #external_reference_value?).
175
+ SVG_EXTERNAL_SCHEME = /\A[a-z][a-z0-9+.-]*:/i
176
+ SVG_EXTERNAL_AUTHORITY = %r{\A[\\/]{2}}i
94
177
 
95
178
  # The inline data references whose contents are parsed when the document is
96
179
  # rendered. The SVG ones are validated as nested documents, as the rules
@@ -98,22 +181,51 @@ module Decidim
98
181
  # base64), and the other ones are accepted when they do not declare a
99
182
  # forbidden content type (see SVG_FORBIDDEN_URI_PREFIXES). The parameters of
100
183
  # the MIME type (e.g. "image/svg+xml;charset=utf-8") are matched as well, as
101
- # browsers still parse the payload as a document, and the "base64" one can
102
- # appear in any position of the list.
103
- SVG_DATA_URI = %r{\Adata:(?<mime>image/svg\+xml)(?<parameters>(?:;[^;,]*)*),(?<payload>.*)\z}im
184
+ # browsers still parse the payload as a document. The payload is the data of
185
+ # the reference (RFC 2397): the fragment of the URI is not part of it, so the
186
+ # text after the first hash is not decoded as contents, and the "base64"
187
+ # indicator is a parameter of the MIME type, which is distinguishable from a
188
+ # parameter with a value because it does not have an "=" sign (see
189
+ # #base64_parameter?). The payload is percent-decoded before it is read as
190
+ # Base64, as the browsers do, so that a payload written with its Base64
191
+ # characters percent-encoded is decoded as the document it declares.
192
+ SVG_DATA_URI = %r{\Adata:(?<mime>image/svg\+xml)(?<parameters>(?:;[^#;,]*)*),(?<payload>[^#]*)}im
193
+
194
+ # The characters the payload of a data reference can contain when its MIME
195
+ # type indicates it is Base64 encoded. The alphabet is checked on the payload
196
+ # after it is percent-decoded, as the browsers decode the percent-encoded
197
+ # characters before reading it as Base64 (see #nested_document_unsafe?). The
198
+ # whitespace is ignored, as the payload is decoded with the forgiving decoding
199
+ # applied by browsers; the other characters outside the alphabet make it fail
200
+ # to be decoded (see #decode_base64).
201
+ BASE64_ALPHABET = %r{\A[A-Za-z0-9+/=\s]*\z}i
104
202
 
105
203
  # The CSS functions which load the resources they reference when the style
106
204
  # sheet is rendered. The strings inside them are interpreted as URLs, so the
107
- # arguments of "image-set()" define a reference as the arguments of "url()"
108
- # do, and the vendor prefixed spelling is matched as well.
109
- CSS_URL_FUNCTIONS = %w(url image-set -webkit-image-set).freeze
205
+ # arguments of "image()" and "image-set()" define a reference as the arguments
206
+ # of "url()" do, and the vendor prefixed spelling is matched as well.
207
+ CSS_URL_FUNCTIONS = %w(url image image-set -webkit-image-set).freeze
110
208
 
111
- # The URL references of a style sheet, captured after the comments and the
112
- # strings which do not define a URL are removed, so that each of them can
113
- # be validated as a reference. Only the strings of the functions which load
114
- # their arguments survive the scrubbing, so the remaining strings are URL
115
- # values, and the unquoted value of a "url()" function is matched as well.
116
- SVG_CSS_URL_VALUE = /["']([^"')]+)["']?|(?:url|image-set)\(\s*([^"')]+)/im
209
+ # The escape sequences of CSS, which consist of a backslash followed by up
210
+ # to six hexadecimal digits, with an optional whitespace terminating the
211
+ # sequence, or by any other character. The groups are the codepoint and the
212
+ # escaped character, read by position in #decode_css_escapes, so they are
213
+ # kept unnamed.
214
+ CSS_ESCAPE = /\\(?:(\h{1,6})[ \t\n\r\f]?|(.))/m
215
+
216
+ # The call of a function which loads its arguments as a resource, which
217
+ # starts the value read as a reference (see #scan_css_reference_value). The
218
+ # value of a function is not taken as a reference when it is itself a function
219
+ # call, so that a function nested inside another one (e.g. "image(url(...))")
220
+ # is read on its own. The whitespace which can separate the nested call from
221
+ # the parenthesis is not part of the value, as the engines read the arguments
222
+ # as tokens, so it is skipped before the check (see #scan_css_reference_value).
223
+ #
224
+ # The expression has no quantified group, as the values are read token by
225
+ # token instead of with a quantified expression (see #scan_css_reference_value):
226
+ # the regexp engine keeps one entry per repetition in its match stack, which
227
+ # grows the memory proportionally to the length of a multi-megabyte value.
228
+ SVG_CSS_URL_FUNCTION_CALL = /(?:#{CSS_URL_FUNCTIONS.join("|")})\(/im
117
229
 
118
230
  # The maximum depth of the documents nested inside inline data references,
119
231
  # which are validated with the same rules as the document itself.
@@ -130,25 +242,31 @@ module Decidim
130
242
  # they target the "style" attribute or one of the presentation attributes
131
243
  # which resolve a URL reference, the values are validated as style sheet
132
244
  # content, as the URL references they declare are loaded when the animation
133
- # reaches them.
134
- SVG_ANIMATION_ELEMENTS = %w(animate set).freeze
135
- SVG_ANIMATION_VALUE_NAMES = %w(values from to by).freeze
245
+ # reaches them. "animateColor" is included although deprecated, as it is
246
+ # defined by SVG 1.1 and modifies the "fill" and "stroke" properties.
247
+ SVG_ANIMATION_ELEMENTS = %w(animate animatecolor set).freeze
248
+
249
+ # The attribute which defines the list of values assigned by an animation,
250
+ # separated by semicolons.
251
+ SVG_ANIMATION_LIST_NAMES = %w(values).freeze
252
+
253
+ # The attributes which define a single value assigned by an animation. A
254
+ # single value is not split, as a semicolon can be part of it when it belongs
255
+ # to the value of the attribute being modified (e.g. the parameters of the
256
+ # MIME type of a data reference), and splitting it would validate only the
257
+ # part before the first semicolon.
258
+ SVG_ANIMATION_SINGLE_VALUE_NAMES = %w(from to by).freeze
136
259
 
137
260
  # The CSS at-rules which load external resources when the style sheets of
138
261
  # an SVG document are rendered. Imports always fetch a resource, so
139
262
  # documents containing them are rejected. The URL references are validated
140
- # separately as references (see SVG_CSS_URL_VALUE), as the same rules apply
263
+ # separately as references (see #scan_css_reference_value), as the same rules apply
141
264
  # to them: references with a scheme or an authority fetch a resource from
142
265
  # another host, fragment and relative references are resolved against the
143
266
  # document itself, and "data:" references are inline but can contain a
144
267
  # nested document which is parsed when rendered.
145
268
  SVG_CSS_IMPORT = /@import/i
146
269
 
147
- # The escape sequences of CSS, which consist of a backslash followed by up
148
- # to six hexadecimal digits, with an optional whitespace terminating the
149
- # sequence, or by any other character.
150
- CSS_ESCAPE = /\\(?:(?<hex>\h{1,6})[ \t\n\r\f]?|(?<char>.))/m
151
-
152
270
  # Validates the contents of an SVG document. Returns :valid when the
153
271
  # document can be stored, :invalid when the contents are not a well formed
154
272
  # SVG document, and :unsafe when the document contains content which could
@@ -186,11 +304,19 @@ module Decidim
186
304
  # rejected instead of being recovered with a partial tree, and without
187
305
  # fetching any external resource (e.g. an external DTD) or substituting
188
306
  # entities, so that a malicious document cannot make the server read external
189
- # resources or expand entities while it is validated. Returns nil when the
190
- # contents are not a well formed XML document with an "svg" root element.
307
+ # resources or expand entities while it is validated. Strict mode does not
308
+ # recover, but it does not stop on the problems which are not fatal, such as a
309
+ # prefix which is not bound to a namespace (XML 1.0, 2.8); they are reported
310
+ # after the parse, so the documents which are not well formed are rejected as
311
+ # well, as the engines do not render them. Returns nil when the contents are
312
+ # not a well formed XML document with an "svg" root element in the SVG
313
+ # namespace.
191
314
  def parse
192
315
  document = Nokogiri::XML.parse(content) { |options| options.strict.nonet }
193
- return nil if document.root.nil? || document.root.name != "svg"
316
+ return nil if document.errors.any? { |error| error.error? || error.fatal? }
317
+
318
+ root = document.root
319
+ return nil if root.nil? || root.name != "svg" || root.namespace&.href != SVG_NAMESPACE
194
320
 
195
321
  document
196
322
  rescue Nokogiri::XML::SyntaxError
@@ -220,6 +346,7 @@ module Decidim
220
346
  return true if forbidden_uri_value?(attribute.value.to_s)
221
347
  return true if css_content_name?(attribute.name) && forbidden_css_content?(attribute.value.to_s)
222
348
  return true if animation_target_attribute?(attribute) && forbidden_name?(attribute.value.to_s)
349
+ return true if forbidden_base_value?(attribute)
223
350
 
224
351
  forbidden_resource_reference?(node, attribute)
225
352
  end
@@ -243,6 +370,16 @@ module Decidim
243
370
  forbidden_reference_value?(attribute.value.to_s)
244
371
  end
245
372
 
373
+ # Whether the attribute defines the base URI which the relative references of
374
+ # the document are resolved against (XML Base), when that base points to
375
+ # another host. The base applies to the element which declares it and to its
376
+ # descendants, so a reference which is relative to the document resolves
377
+ # against it when the document is rendered, and the base is restricted like
378
+ # the references which load a resource.
379
+ def forbidden_base_value?(attribute)
380
+ SVG_BASE_NAME.match?(attribute.name) && forbidden_reference_value?(attribute.value.to_s)
381
+ end
382
+
246
383
  # Whether an animation assigns an external resource to a reference
247
384
  # attribute (e.g. "href") of an element which loads it, as the resource
248
385
  # is loaded when the animation reaches the value. References which do not
@@ -250,14 +387,22 @@ module Decidim
250
387
  # are never fetched when the document is rendered. The values assigned to
251
388
  # the "style" attribute and to the presentation attributes which resolve a
252
389
  # URL reference are validated as style sheet content, as the references they
253
- # declare are loaded when the animation reaches them.
390
+ # declare are loaded when the animation reaches them. The values are checked
391
+ # when any name of the list of targets defines one of these attributes, as
392
+ # the value is assigned to each name of the list.
254
393
  def forbidden_animation_reference?(node)
255
394
  return false unless SVG_ANIMATION_ELEMENTS.include?(node.name.downcase)
256
395
 
257
- target = animation_target(node)
396
+ targets = animation_targets(node)
258
397
  values = animation_values(node)
259
- return false if target.nil? || values.empty?
398
+ return false if targets.empty? || values.empty?
399
+
400
+ targets.any? { |target| forbidden_animation_target?(node, target, values) }
401
+ end
260
402
 
403
+ # Whether one name of the list of targets receives a forbidden value, as the
404
+ # animation assigns the value to each name of the list.
405
+ def forbidden_animation_target?(node, target, values)
261
406
  return true if css_content_name?(target) && forbidden_css_values?(values)
262
407
  return false unless SVG_REFERENCE_NAME.match?(target) && animates_resource_element?(node)
263
408
 
@@ -272,21 +417,29 @@ module Decidim
272
417
  values.any? { |value| forbidden_reference_value?(value) }
273
418
  end
274
419
 
275
- # The attribute modified by an animation, normalized as the HTML parser
276
- # resolves it when the document is parsed as HTML.
277
- def animation_target(node)
420
+ # The attributes modified by an animation, normalized as the HTML parser
421
+ # resolves them when the document is parsed as HTML. "attributenames" accepts
422
+ # a list of names separated by whitespace, so each name of the list is
423
+ # checked separately.
424
+ def animation_targets(node)
278
425
  attribute = node.attribute_nodes.find { |a| animation_target_attribute?(a) }
279
- attribute&.value&.downcase
426
+ return [] if attribute.nil?
427
+
428
+ name_list(attribute.value.to_s)
280
429
  end
281
430
 
282
431
  def animation_target_attribute?(attribute)
283
432
  SVG_ANIMATION_TARGET_NAMES.any? { |name| attribute.name.casecmp?(name) }
284
433
  end
285
434
 
286
- # The values assigned by an animation, which are accepted as lists
287
- # separated by semicolons.
435
+ # The values assigned by an animation, which are the list of "values" and the
436
+ # single value of each of the other attributes. The white space which the
437
+ # specification ignores is stripped, and the values which are empty are
438
+ # ignored, as they do not assign anything.
288
439
  def animation_values(node)
289
- SVG_ANIMATION_VALUE_NAMES.flat_map { |name| node[name].to_s.split(";") }
440
+ values = SVG_ANIMATION_LIST_NAMES.flat_map { |name| node[name].to_s.split(";") }
441
+ values.concat(SVG_ANIMATION_SINGLE_VALUE_NAMES.map { |name| node[name].to_s })
442
+ values.map(&:strip).reject(&:empty?)
290
443
  end
291
444
 
292
445
  # Whether the animation modifies the reference of an element which loads
@@ -339,29 +492,64 @@ module Decidim
339
492
  # when it is rendered. The whitespace and control characters which can be
340
493
  # used to obfuscate the scheme are removed before checking.
341
494
  def forbidden_reference_value?(value)
342
- return true if SVG_EXTERNAL_REFERENCE.match?(normalize_uri_value(value))
495
+ return true if external_reference_value?(normalize_uri_value(value))
343
496
  return true if forbidden_uri_value?(value)
344
497
 
345
498
  nested_document_unsafe?(value)
346
499
  end
347
500
 
501
+ # Whether the normalized reference resolves to another host. The "data:"
502
+ # references are inline, so they are not external.
503
+ def external_reference_value?(normalized)
504
+ return false if normalized.start_with?("data:")
505
+
506
+ SVG_EXTERNAL_SCHEME.match?(normalized) || SVG_EXTERNAL_AUTHORITY.match?(normalized)
507
+ end
508
+
348
509
  # Whether the contents of an inline data reference declaring an SVG
349
- # document are unsafe, as they are parsed as a document of their own when
510
+ # document are rejected, as they are parsed as a document of their own when
350
511
  # the reference is rendered. The nested documents are validated with the
351
512
  # same rules, up to a maximum depth, so that a document referencing itself
352
- # cannot be used to recurse indefinitely. A nested document which cannot be
353
- # validated because the maximum depth is reached is rejected, as its contents
354
- # are still parsed when the reference is rendered.
513
+ # cannot be used to recurse indefinitely. Only the nested documents which are
514
+ # valid are accepted: the ones which are unsafe contain content which is
515
+ # executed when the reference is rendered, and the ones which cannot be
516
+ # validated (e.g. a payload which is not a well formed document, or which
517
+ # cannot be decoded) are rejected as well, as the rules above cannot be
518
+ # applied to them. Reaching the maximum depth rejects the reference, as its
519
+ # contents are still parsed when it is rendered.
355
520
  def nested_document_unsafe?(value)
356
- match = SVG_DATA_URI.match(value.strip)
357
- return false if match.nil?
521
+ data = SVG_DATA_URI.match(value.strip)
522
+ return false if data.nil?
358
523
  return true if depth >= MAX_NESTED_DEPTH
359
524
 
360
- payload = match[:parameters].downcase.include?(";base64") ? decode_base64(match[:payload]) : percent_decode(match[:payload])
361
- Decidim::SvgContentValidator.new(payload, depth + 1).validate == :unsafe
525
+ # The data of the reference is percent-decoded first, and the Base64
526
+ # indicator is applied to the decoded data (Fetch, data URL parser), so the
527
+ # Base64 characters written percent-encoded (e.g. the padding as "%3D") are
528
+ # decoded before the payload is read as Base64.
529
+ decoded = percent_decode(data[:payload])
530
+ payload = base64_parameter?(data[:parameters]) ? decode_base64(decoded) : decoded
531
+ return true if payload.nil?
532
+
533
+ Decidim::SvgContentValidator.new(payload, depth + 1).validate != :valid
362
534
  end
363
535
 
536
+ # Whether the parameters of the MIME type of a data reference indicate that
537
+ # its payload is Base64 encoded. The indicator is a parameter without a
538
+ # value, as a parameter whose value only looks like it (e.g.
539
+ # "charset=base64") is not one, and browsers only detect it as the last
540
+ # parameter of the MIME type.
541
+ def base64_parameter?(parameters)
542
+ parameters.split(";").last.to_s.strip.casecmp?("base64")
543
+ end
544
+
545
+ # Decodes the Base64 payload of a data reference with the forgiving decoding
546
+ # applied by browsers, which ignores the whitespace. The characters outside
547
+ # the Base64 alphabet make the payload fail to be decoded, as they do in the
548
+ # browsers, so the failure is reported to the caller instead of producing
549
+ # contents which are never rendered.
364
550
  def decode_base64(value)
551
+ return nil unless BASE64_ALPHABET.match?(value)
552
+
365
553
  value.unpack1("m")
366
554
  end
367
555
 
@@ -393,12 +581,18 @@ module Decidim
393
581
  # names are also accepted by some animation attributes, so each name of the
394
582
  # list is checked separately.
395
583
  def forbidden_name?(name)
396
- name.split(";").any? do |part|
397
- normalized = part.strip.downcase
584
+ name_list(name).any? do |normalized|
398
585
  SVG_EVENT_HANDLER_NAME.match?(normalized) || SVG_FORBIDDEN_ELEMENTS.include?(normalized)
399
586
  end
400
587
  end
401
588
 
589
+ # The normalized names of a list of attribute names, which are separated by
590
+ # semicolons or by whitespace, as "attributenames" accepts a list of names
591
+ # separated by whitespace.
592
+ def name_list(value)
593
+ value.split(/[;\s]+/).map(&:downcase)
594
+ end
595
+
402
596
  # Whether the document type definition declares an entity. Entities can be
403
597
  # used to read external resources (XXE) or to expand content exponentially
404
598
  # (billion laughs), so documents declaring one are rejected. Only the
@@ -420,11 +614,137 @@ module Decidim
420
614
  # before checking, as they can otherwise hide the references (e.g.
421
615
  # "u\rl(https://example.org)") or be mistaken for them (e.g. 'content:
422
616
  # "See @import instructions"').
617
+ #
618
+ # The input is normalized before the style sheet is tokenized, as the engines
619
+ # do (CSS Syntax Level 3, 5.1): CRLF, CR and FF are read as a single newline,
620
+ # so that a CRLF pair consumed by a hexadecimal escape does not cut the value
621
+ # short at the second character of the pair (see #normalize_css_newlines).
622
+ #
623
+ # The references are captured on the scrubbed style sheet, before the escape
624
+ # sequences are decoded, so that the boundaries of the string tokens are
625
+ # preserved: an escaped quote is part of the value and not the end of it, and
626
+ # an unescaped newline ends the value. The captured values are decoded
627
+ # afterwards, as the engines read them as URLs only after decoding. The names
628
+ # of the functions which load their arguments are decoded during the
629
+ # scrubbing, so that the escaped spellings are still recognized (see
630
+ # #scrub_css).
631
+ #
632
+ # The values are checked as they are found, so that a style sheet with many
633
+ # references does not keep all of them in memory before the first one is
634
+ # rejected.
423
635
  def forbidden_css_content?(css)
424
- normalized = decode_css_escapes(scrub_css(css))
425
- return true if SVG_CSS_IMPORT.match?(normalized)
636
+ scrubbed = scrub_css(normalize_css_newlines(css))
637
+ return true if SVG_CSS_IMPORT.match?(decode_css_escapes(scrubbed))
638
+
639
+ scanner = StringScanner.new(scrubbed)
640
+ until scanner.eos?
641
+ value = scan_css_reference_value(scanner)
642
+ next if value.nil?
643
+
644
+ return true if forbidden_reference_value?(decode_css_escapes(value))
645
+ end
426
646
 
427
- normalized.scan(SVG_CSS_URL_VALUE).any? { |groups| forbidden_reference_value?(groups.compact.first) }
647
+ false
648
+ end
649
+
650
+ # Normalizes the newlines of a style sheet as the engines do before
651
+ # tokenizing it (CSS Syntax Level 3, 5.1): CRLF, CR and FF are read as a
652
+ # single newline. A hexadecimal escape consumes the newline which terminates
653
+ # it, so without normalizing the CRLF pair the escape consumes only the CR
654
+ # and the value is cut short at the LF, hiding the URL which continues after
655
+ # the newline (e.g. "url(\"\\68&#13;&#10;ttps://example.org\")", which the
656
+ # engines resolve to an external address).
657
+ def normalize_css_newlines(css)
658
+ css.gsub(/\r\n?|[\r\f]/, "\n")
659
+ end
660
+
661
+ # Reads the next reference value of the scrubbed style sheet: a string token
662
+ # or the unquoted value of a function which loads its arguments. The values
663
+ # are read token by token instead of with a quantified expression, as the
664
+ # regexp engine keeps one entry per repetition in its match stack, which
665
+ # grows the memory proportionally to the length of a multi-megabyte value.
666
+ #
667
+ # The content of a string is delimited by the quote which opens it, so the
668
+ # other quote is part of the value and cannot be used to cut it short (e.g.
669
+ # the namespace of an inline document written with single quotes inside a
670
+ # double quoted URL). Taking only the part before the other quote would
671
+ # validate an incomplete reference instead of the one which is rendered.
672
+ #
673
+ # The closing parenthesis of a function is not a delimiter of a quoted value
674
+ # either, as it is part of the string token when the style sheet is
675
+ # tokenized (see #scrub_css). Cutting the value at it would read the text
676
+ # after the parenthesis as part of another value, which can hide an external
677
+ # URL following it (e.g. "image-set(\"a)b\" c, url(https://example.org))").
678
+ #
679
+ # The value is read as the string token which defines it, so the escape
680
+ # sequences and the newlines are kept as they are written and decoded after
681
+ # the capture (see #forbidden_css_content?): an escaped quote does not close
682
+ # the token, and an unescaped newline ends it. Capturing across them would
683
+ # read the text after the token as part of the value, hiding an external URL
684
+ # which follows it.
685
+ #
686
+ # A hexadecimal escape consumes the whitespace or newline which terminates it,
687
+ # so the whole sequence is part of the token and the value must be read as
688
+ # the complete escape (see CSS_ESCAPE). Stopping at the first character after
689
+ # the backslash would validate only the decoded character, and the rest of the
690
+ # URL after the newline would never be checked (e.g. "url(\"\\68\n" followed
691
+ # by "ttps://example.org\")", which the engines resolve to an external address).
692
+ #
693
+ # An empty string is a complete value which must be consumed as such.
694
+ # Requiring at least one character would leave the scan to start at its
695
+ # closing quote, reading the rest of the style sheet as a single value which
696
+ # hides the external URLs declared after it.
697
+ #
698
+ # The whitespace between the parenthesis of a function and its argument is not
699
+ # part of the value, as the engines read the arguments as tokens. When the
700
+ # argument is a nested function call, it is read on its own, so the whitespace
701
+ # which can separate it from the enclosing function is skipped before checking
702
+ # it (e.g. "image-set( url(https://example.org))"). Reading it as a value would
703
+ # consume the name of the nested function and leave its address without a
704
+ # function name before it, which is never checked as a reference.
705
+ #
706
+ # The delimiters of an unquoted value are only the delimiters which the
707
+ # tokenization rules read as such: an escape sequence hides the character
708
+ # following it, so a quote or a parenthesis written as an escape is part of the
709
+ # value and does not end it (e.g. "url(local\"); mask-image:
710
+ # url(https://example.org))"). Stopping at the escaped character would read the
711
+ # rest of the style sheet as a string starting at that character, which hides the
712
+ # external URL declared after it.
713
+ def scan_css_reference_value(scanner)
714
+ if (quote = scanner.scan(/["']/))
715
+ token = scan_css_string(scanner, quote)
716
+ value = token[1..-1]
717
+ value = value[0..-2] if value.end_with?(quote)
718
+ value
719
+ elsif scanner.scan(SVG_CSS_URL_FUNCTION_CALL)
720
+ scanner.getch while scanner.match?(/\s/)
721
+ return nil if scanner.match?(SVG_CSS_URL_FUNCTION_CALL)
722
+
723
+ scan_css_unquoted_value(scanner)
724
+ else
725
+ scanner.getch
726
+ nil
727
+ end
728
+ end
729
+
730
+ # Consumes the unquoted value of a function which loads its arguments, and
731
+ # returns it as it is written. The value ends at a quote or a parenthesis, but
732
+ # only when the tokenization rules read it as a delimiter: an escape sequence
733
+ # hides the character following it, so the whole escape is consumed as part of
734
+ # the value (see #scan_css_reference_value).
735
+ def scan_css_unquoted_value(scanner)
736
+ value = +""
737
+ until scanner.eos?
738
+ escape = scanner.scan(CSS_ESCAPE)
739
+ if escape
740
+ value << escape
741
+ elsif scanner.match?(/["')(]/)
742
+ break
743
+ else
744
+ value << scanner.getch
745
+ end
746
+ end
747
+ value
428
748
  end
429
749
 
430
750
  # Removes the comments and the strings of a style sheet, which are not
@@ -452,9 +772,10 @@ module Decidim
452
772
  string = scan_css_string(scanner, quote)
453
773
  output << string if url_functions.any?
454
774
  elsif (ident = scan_css_ident(scanner))
455
- output << ident
775
+ url_function = css_url_function?(ident)
776
+ output << decoded_css_name(ident, url_function)
456
777
  if scanner.match?(/\(/)
457
- url_functions.push(css_url_function?(ident))
778
+ url_functions.push(url_function)
458
779
  output << scanner.getch
459
780
  end
460
781
  else
@@ -472,9 +793,13 @@ module Decidim
472
793
  end
473
794
 
474
795
  # Consumes the comment token of CSS which starts at the current position.
475
- # Unterminated comments extend to the end of the style sheet.
796
+ # Unterminated comments extend to the end of the style sheet. The end is
797
+ # reached with #terminate, as the position of the scanner is counted in bytes
798
+ # while the length of the string counts characters: assigning the length moves
799
+ # the scanner back for a style sheet with multibyte characters, which then
800
+ # reads the same unclosed comment again in an endless loop.
476
801
  def scan_css_comment(scanner)
477
- scanner.scan_until(%r{\*/}) || (scanner.pos = scanner.string.length)
802
+ scanner.scan_until(%r{\*/}) || scanner.terminate
478
803
  end
479
804
 
480
805
  # Consumes the string token of CSS which starts at the given quote, and
@@ -529,12 +854,22 @@ module Decidim
529
854
  CSS_URL_FUNCTIONS.any? { |name| decode_css_escapes(ident).casecmp?(name) }
530
855
  end
531
856
 
857
+ # The name of an identifier as it is written, or decoded when it is the name
858
+ # of a function which loads its arguments, so that the escaped spellings are
859
+ # recognized when the references are captured on the scrubbed style sheet
860
+ # (see #forbidden_css_content?). The other identifiers are kept as they are
861
+ # written, as decoding them could turn an escaped character into one which
862
+ # the tokenization rules do not accept inside an identifier.
863
+ def decoded_css_name(ident, url_function)
864
+ url_function ? decode_css_escapes(ident) : ident
865
+ end
866
+
532
867
  # Decodes the escape sequences of CSS. Invalid codepoints are replaced with
533
868
  # the replacement character.
534
869
  def decode_css_escapes(css)
535
870
  css.gsub(CSS_ESCAPE) do
536
- digits = Regexp.last_match[:hex]
537
- next Regexp.last_match[:char] if digits.nil?
871
+ digits = Regexp.last_match(1)
872
+ next Regexp.last_match(2) if digits.nil?
538
873
 
539
874
  codepoint = digits.to_i(16)
540
875
  if codepoint.zero? || codepoint > 0x10FFFF || codepoint.between?(0xD800, 0xDFFF)