decidim-core 0.31.7 → 0.31.9

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 (164) 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/content_blocks/participatory_space_main_data/title.erb +1 -14
  5. data/app/cells/decidim/date_range/show.erb +6 -6
  6. data/app/cells/decidim/date_range_cell.rb +7 -2
  7. data/app/cells/decidim/following_cell.rb +1 -1
  8. data/app/cells/decidim/nav_links/show.erb +3 -1
  9. data/app/cells/decidim/participatory_space_private_user/show.erb +1 -1
  10. data/app/cells/decidim/share_text_widget/modal.erb +1 -0
  11. data/app/cells/decidim/share_widget/modal.erb +1 -0
  12. data/app/cells/decidim/share_widget/qr_code_modal.erb +2 -4
  13. data/app/commands/decidim/create_follow.rb +3 -7
  14. data/app/commands/decidim/create_omniauth_registration.rb +19 -7
  15. data/app/commands/decidim/create_user_report.rb +1 -1
  16. data/app/commands/decidim/destroy_account.rb +6 -6
  17. data/app/commands/decidim/destroy_ephemeral_user.rb +2 -0
  18. data/app/commands/decidim/invite_user.rb +1 -1
  19. data/app/commands/decidim/multiple_attachments_methods.rb +17 -3
  20. data/app/commands/decidim/update_resources_taxonomies.rb +2 -1
  21. data/app/controllers/concerns/decidim/devise_authentication_methods.rb +4 -0
  22. data/app/controllers/concerns/decidim/devise_controllers.rb +4 -0
  23. data/app/controllers/concerns/decidim/direct_upload.rb +12 -6
  24. data/app/controllers/concerns/decidim/disable_redirection_to_external_host.rb +2 -0
  25. data/app/controllers/concerns/decidim/filter_resource.rb +2 -0
  26. data/app/controllers/concerns/decidim/impersonate_users.rb +4 -4
  27. data/app/controllers/concerns/decidim/locale_switcher.rb +62 -11
  28. data/app/controllers/concerns/decidim/needs_organization.rb +15 -0
  29. data/app/controllers/concerns/decidim/needs_permission.rb +22 -10
  30. data/app/controllers/concerns/decidim/onboarding_action_methods.rb +2 -0
  31. data/app/controllers/concerns/decidim/paginable.rb +7 -3
  32. data/app/controllers/concerns/decidim/payload_info.rb +2 -0
  33. data/app/controllers/concerns/decidim/resource_versions_concern.rb +14 -0
  34. data/app/controllers/decidim/amendments_controller.rb +34 -6
  35. data/app/controllers/decidim/application_controller.rb +2 -6
  36. data/app/controllers/decidim/authorization_modals_controller.rb +3 -1
  37. data/app/controllers/decidim/components/base_controller.rb +2 -0
  38. data/app/controllers/decidim/devise/passwords_controller.rb +8 -0
  39. data/app/controllers/decidim/doorkeeper/authorizations_controller.rb +10 -4
  40. data/app/controllers/decidim/doorkeeper/credentials_controller.rb +6 -1
  41. data/app/controllers/decidim/favicon_controller.rb +9 -0
  42. data/app/controllers/decidim/free_resource_authorization_modals_controller.rb +2 -0
  43. data/app/controllers/decidim/gamification/badges_controller.rb +2 -0
  44. data/app/controllers/decidim/homepage_controller.rb +4 -1
  45. data/app/controllers/decidim/likes_controller.rb +1 -1
  46. data/app/controllers/decidim/links_controller.rb +2 -0
  47. data/app/controllers/decidim/manifests_controller.rb +2 -0
  48. data/app/controllers/decidim/messaging/conversations_controller.rb +11 -5
  49. data/app/controllers/decidim/newsletters_controller.rb +4 -0
  50. data/app/controllers/decidim/notifications_subscriptions_controller.rb +4 -0
  51. data/app/controllers/decidim/offline_controller.rb +5 -1
  52. data/app/controllers/decidim/open_data_controller.rb +5 -1
  53. data/app/controllers/decidim/pages_controller.rb +31 -3
  54. data/app/controllers/decidim/private_downloads_controller.rb +2 -0
  55. data/app/controllers/decidim/profiles_controller.rb +11 -1
  56. data/app/controllers/decidim/qr_controller.rb +3 -1
  57. data/app/controllers/decidim/resource_autocomplete_controller.rb +2 -0
  58. data/app/controllers/decidim/searches_controller.rb +2 -0
  59. data/app/controllers/decidim/short_links_controller.rb +4 -0
  60. data/app/controllers/decidim/static_map_controller.rb +2 -0
  61. data/app/controllers/decidim/timeouts_controller.rb +4 -0
  62. data/app/controllers/decidim/tos_controller.rb +2 -0
  63. data/app/controllers/decidim/upload_validations_controller.rb +4 -2
  64. data/app/controllers/decidim/user_activities_controller.rb +2 -0
  65. data/app/forms/decidim/upload_validation_form.rb +16 -10
  66. data/app/helpers/concerns/decidim/user_role_checker.rb +35 -10
  67. data/app/helpers/decidim/cells_paginate_helper.rb +0 -5
  68. data/app/helpers/decidim/layout_helper.rb +1 -0
  69. data/app/helpers/decidim/orders_helper.rb +8 -6
  70. data/app/helpers/decidim/paginate_helper.rb +27 -2
  71. data/app/helpers/decidim/sanitize_helper.rb +11 -1
  72. data/app/helpers/decidim/url_helper.rb +35 -0
  73. data/app/jobs/decidim/application_job.rb +4 -0
  74. data/app/jobs/decidim/open_data_job.rb +21 -5
  75. data/app/models/decidim/action_log.rb +7 -1
  76. data/app/models/decidim/authorization.rb +24 -0
  77. data/app/models/decidim/component.rb +10 -0
  78. data/app/models/decidim/like.rb +1 -1
  79. data/app/models/decidim/oauth_application.rb +1 -0
  80. data/app/models/decidim/user.rb +1 -0
  81. data/app/models/decidim/user_base_entity.rb +1 -1
  82. data/app/packs/src/decidim/callout.js +10 -0
  83. data/app/packs/src/decidim/callout.test.js +32 -0
  84. data/app/packs/src/decidim/controllers/accordion/accordion.test.js +64 -0
  85. data/app/packs/src/decidim/controllers/accordion/controller.js +43 -0
  86. data/app/packs/src/decidim/datepicker/datepicker_functions.js +54 -30
  87. data/app/packs/src/decidim/datepicker/form_datepicker.js +18 -2
  88. data/app/packs/src/decidim/datepicker/generate_datepicker.js +16 -8
  89. data/app/packs/src/decidim/datepicker/generate_timepicker.js +5 -3
  90. data/app/packs/src/decidim/datepicker/test/date.test.js +8 -0
  91. data/app/packs/src/decidim/datepicker/test/time.test.js +39 -24
  92. data/app/packs/src/decidim/utilities/dom.js +2 -2
  93. data/app/packs/stylesheets/decidim/_content_blocks.scss +4 -10
  94. data/app/packs/stylesheets/decidim/_conversations.scss +0 -8
  95. data/app/packs/stylesheets/decidim/_datepicker.scss +3 -3
  96. data/app/packs/stylesheets/decidim/_modal.scss +16 -8
  97. data/app/packs/stylesheets/decidim/_modal_share.scss +0 -22
  98. data/app/packs/stylesheets/decidim/_participatory_spaces.scss +11 -1
  99. data/app/packs/stylesheets/decidim/_rich_text.scss +12 -9
  100. data/app/packs/stylesheets/decidim/_spinner.scss +16 -0
  101. data/app/packs/stylesheets/decidim/_tom_select.scss +1 -1
  102. data/app/packs/stylesheets/decidim/_typography.scss +5 -2
  103. data/app/packs/stylesheets/decidim/legacy/email.scss +0 -5
  104. data/app/permissions/decidim/permissions.rb +20 -0
  105. data/app/presenters/decidim/admin_log/component_presenter.rb +1 -1
  106. data/app/presenters/decidim/log/base_presenter.rb +20 -2
  107. data/app/presenters/decidim/log/user_presenter.rb +2 -2
  108. data/app/serializers/decidim/exporters/open_data_blocked_user_serializer.rb +11 -2
  109. data/app/serializers/decidim/exporters/open_data_moderation_serializer.rb +25 -1
  110. data/app/services/decidim/action_logger.rb +97 -29
  111. data/app/services/decidim/svg_content_validator.rb +889 -0
  112. data/app/uploaders/decidim/application_uploader.rb +2 -2
  113. data/app/validators/uploader_image_content_validator.rb +282 -0
  114. data/app/views/decidim/application/_radio_accordion.html.erb +1 -5
  115. data/app/views/decidim/manifests/show.json.erb +25 -22
  116. data/app/views/decidim/messaging/conversations/create.js.erb +1 -3
  117. data/app/views/decidim/shared/_login_modal.html.erb +12 -14
  118. data/app/views/decidim/shared/_results_per_page.html.erb +1 -1
  119. data/app/views/layouts/decidim/_mailer_logo.html.erb +1 -1
  120. data/config/initializers/rack_attack.rb +10 -0
  121. data/config/locales/bg.yml +1 -4
  122. data/config/locales/ca-IT.yml +8 -4
  123. data/config/locales/ca.yml +10 -6
  124. data/config/locales/cs.yml +16 -4
  125. data/config/locales/de.yml +62 -6
  126. data/config/locales/en.yml +8 -4
  127. data/config/locales/es-MX.yml +8 -4
  128. data/config/locales/es-PY.yml +8 -4
  129. data/config/locales/es.yml +14 -10
  130. data/config/locales/eu.yml +165 -164
  131. data/config/locales/fi-plain.yml +3 -3
  132. data/config/locales/fi.yml +3 -3
  133. data/config/locales/fr-CA.yml +8 -4
  134. data/config/locales/fr.yml +8 -4
  135. data/config/locales/gl.yml +1440 -33
  136. data/config/locales/hu.yml +0 -1
  137. data/config/locales/it.yml +0 -2
  138. data/config/locales/ja.yml +4 -4
  139. data/config/locales/pl.yml +1 -4
  140. data/config/locales/pt-BR.yml +1 -4
  141. data/config/locales/ro-RO.yml +0 -3
  142. data/config/locales/sk.yml +51 -4
  143. data/config/locales/sv.yml +50 -13
  144. data/config/locales/tr-TR.yml +1 -3
  145. data/db/migrate/20250523104311_move_cta_to_hero_content_block.rb +1 -1
  146. data/db/migrate/20250527122040_move_highlighted_content_banner_settings_to_content_block.rb +3 -0
  147. data/db/migrate/20260909000000_add_failed_attempts_and_locked_at_to_decidim_authorizations.rb +8 -0
  148. data/db/migrate/20261007090000_make_user_optional_in_action_logs.rb +12 -0
  149. data/decidim-core.gemspec +1 -1
  150. data/lib/decidim/content_renderers/mention_resource_renderer.rb +6 -3
  151. data/lib/decidim/core/test/factories.rb +2 -2
  152. data/lib/decidim/core/test/shared_examples/participatory_space_members_page_examples.rb +77 -0
  153. data/lib/decidim/core/test/shared_examples/participatory_space_members_shared_examples.rb +85 -6
  154. data/lib/decidim/core/test/shared_examples/versions_controller_examples.rb +23 -1
  155. data/lib/decidim/core/version.rb +1 -1
  156. data/lib/decidim/core.rb +10 -1
  157. data/lib/decidim/has_upload_validations.rb +1 -0
  158. data/lib/decidim/legacy_form_builder.rb +4 -0
  159. data/lib/decidim/maintenance/import_models/scope.rb +2 -1
  160. data/lib/decidim/maintenance/taxonomy_importer.rb +4 -1
  161. data/lib/decidim/query_extensions.rb +2 -0
  162. data/lib/decidim/view_model.rb +1 -0
  163. data/lib/tasks/decidim_open_data_tasks.rake +7 -0
  164. metadata +22 -10
@@ -0,0 +1,889 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "strscan"
4
+
5
+ module Decidim
6
+ # Validates the contents of SVG documents.
7
+ #
8
+ # SVG documents are XML-based and can contain scripts and other active
9
+ # content, which is executed when the document is rendered by the browser.
10
+ # Because of that, the contents of files detected as SVG need an additional
11
+ # validation, so that documents which could execute scripts or read external
12
+ # resources are rejected instead of being stored as they are.
13
+ #
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
+ #
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
40
+ # an SVG document are validated as nested documents, as they are parsed when
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.
71
+ #
72
+ # This is used by UploaderImageContentValidator, which delegates the SVG
73
+ # specific validation to this class, so callers of that validator only need
74
+ # to call a single validator for all the image formats.
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
+
81
+ # The elements which are not allowed in SVG documents, because they either
82
+ # execute scripts themselves (e.g. "script" and the SVG Tiny "handler") or
83
+ # allow embedding foreign content which can execute them (e.g.
84
+ # "foreignObject"). The names are kept in lowercase, as the names found in
85
+ # the documents are compared case insensitively.
86
+ SVG_FORBIDDEN_ELEMENTS = %w(script handler foreignobject iframe embed object applet).freeze
87
+
88
+ # The names of the attributes which are not allowed in SVG documents, as
89
+ # event handlers execute scripts when the document is rendered.
90
+ SVG_EVENT_HANDLER_NAME = /\Aon[a-z]/i
91
+
92
+ # The URI prefixes which are not allowed in the attribute values of SVG
93
+ # documents, as they execute scripts.
94
+ SVG_FORBIDDEN_URI_PREFIXES = %w(javascript: livescript: vbscript: data:text/html).freeze
95
+
96
+ # The attributes of the SVG animation elements which define the attribute
97
+ # modified by the animation. Through them an animation can set an event
98
+ # handler or another forbidden value at runtime, so the values of these
99
+ # attributes are validated as element/attribute names. The names are kept
100
+ # in lowercase and compared case insensitively, as the HTML parser resolves
101
+ # the names written in lowercase (e.g. "attributename") to the camel case
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).
105
+ SVG_ANIMATION_TARGET_NAMES = %w(attribute attributename attributenames).freeze
106
+
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
126
+
127
+ # The presentation attributes whose value defines a reference resolved when
128
+ # the document is rendered. The image references (e.g. "cursor" and "mask")
129
+ # are fetched as resources, and the references to paint servers, filters,
130
+ # clipping paths and markers can also resolve to an element of another
131
+ # document, which is fetched unless the document is processed in a secure
132
+ # mode. Their values are validated as style sheet content, as they are
133
+ # parsed as the CSS properties they define.
134
+ SVG_URL_PRESENTATION_ATTRIBUTES = %w(
135
+ cursor mask fill stroke filter clip-path marker marker-start marker-mid marker-end color-profile
136
+ ).freeze
137
+
138
+ # The name of the attribute which references the resource loaded by an
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
155
+
156
+ # The references which load a resource from another host: URIs with a
157
+ # scheme (e.g. "https:") and references resolving to an authority, which
158
+ # browsers also detect from two separators at the beginning of the
159
+ # reference (e.g. "//example.org", "/\example.org" or "\\example.org"), as
160
+ # backslashes are treated as separators of the authority for the schemes of
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.
165
+ # Fragment ("#") and relative references are resolved against the document
166
+ # itself, and "data:" references are inline, so they are accepted (see
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
177
+
178
+ # The inline data references whose contents are parsed when the document is
179
+ # rendered. The SVG ones are validated as nested documents, as the rules
180
+ # above cannot be applied to a payload which is stored encoded (e.g. in
181
+ # base64), and the other ones are accepted when they do not declare a
182
+ # forbidden content type (see SVG_FORBIDDEN_URI_PREFIXES). The parameters of
183
+ # the MIME type (e.g. "image/svg+xml;charset=utf-8") are matched as well, as
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
202
+
203
+ # The CSS functions which load the resources they reference when the style
204
+ # sheet is rendered. The strings inside them are interpreted as URLs, so the
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
208
+
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
229
+
230
+ # The maximum depth of the documents nested inside inline data references,
231
+ # which are validated with the same rules as the document itself.
232
+ MAX_NESTED_DEPTH = 5
233
+
234
+ # The maximum size of the contents to validate, as a safety net for the
235
+ # documents which reach this validator without a size limit.
236
+ MAX_CONTENT_SIZE = 10 * 1024 * 1024
237
+
238
+ # The elements which modify the attributes of another element at runtime.
239
+ # When they target a reference attribute of an element which loads the
240
+ # referenced resource, the values assigned to it are validated as
241
+ # references, as the resource is loaded when the animation reaches it. When
242
+ # they target the "style" attribute or one of the presentation attributes
243
+ # which resolve a URL reference, the values are validated as style sheet
244
+ # content, as the URL references they declare are loaded when the animation
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
259
+
260
+ # The CSS at-rules which load external resources when the style sheets of
261
+ # an SVG document are rendered. Imports always fetch a resource, so
262
+ # documents containing them are rejected. The URL references are validated
263
+ # separately as references (see #scan_css_reference_value), as the same rules apply
264
+ # to them: references with a scheme or an authority fetch a resource from
265
+ # another host, fragment and relative references are resolved against the
266
+ # document itself, and "data:" references are inline but can contain a
267
+ # nested document which is parsed when rendered.
268
+ SVG_CSS_IMPORT = /@import/i
269
+
270
+ # Validates the contents of an SVG document. Returns :valid when the
271
+ # document can be stored, :invalid when the contents are not a well formed
272
+ # SVG document, and :unsafe when the document contains content which could
273
+ # execute scripts or read external resources when it is rendered.
274
+ def self.validate(content)
275
+ new(content).validate
276
+ end
277
+
278
+ def initialize(content, depth = 0)
279
+ @content = content
280
+ @depth = depth
281
+ end
282
+
283
+ def validate
284
+ return :invalid if content.nil?
285
+ # The contents which are not valid in their encoding cannot be checked by
286
+ # the expressions below, so they are rejected as unsafe.
287
+ return :unsafe unless content.valid_encoding?
288
+ return :invalid if content.blank?
289
+ return :invalid if content.bytesize > MAX_CONTENT_SIZE
290
+
291
+ document = parse
292
+ return :invalid if document.nil?
293
+ return :unsafe if entity_declaration?(document)
294
+ return :unsafe if forbidden_content?(document)
295
+
296
+ :valid
297
+ end
298
+
299
+ private
300
+
301
+ attr_reader :content, :depth
302
+
303
+ # Parses the SVG document in strict mode, so that malformed documents are
304
+ # rejected instead of being recovered with a partial tree, and without
305
+ # fetching any external resource (e.g. an external DTD) or substituting
306
+ # entities, so that a malicious document cannot make the server read external
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.
314
+ def parse
315
+ document = Nokogiri::XML.parse(content) { |options| options.strict.nonet }
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
320
+
321
+ document
322
+ rescue Nokogiri::XML::SyntaxError
323
+ nil
324
+ end
325
+
326
+ def forbidden_content?(document)
327
+ # The "xml-stylesheet" processing instruction loads an external style
328
+ # sheet when the document is rendered, so documents declaring one are
329
+ # rejected.
330
+ return true if document.xpath("//processing-instruction('xml-stylesheet')").any?
331
+
332
+ document.xpath("//*").any? { |node| forbidden_node?(node) }
333
+ end
334
+
335
+ def forbidden_node?(node)
336
+ return true if SVG_FORBIDDEN_ELEMENTS.include?(node.name.downcase)
337
+ return true if node.attribute_nodes.any? { |attribute| forbidden_attribute?(node, attribute) }
338
+ return true if forbidden_animation_reference?(node)
339
+
340
+ node.name.downcase == "style" && forbidden_css_content?(node.content.to_s)
341
+ end
342
+
343
+ def forbidden_attribute?(node, attribute)
344
+ return true if SVG_EVENT_HANDLER_NAME.match?(attribute.name)
345
+
346
+ return true if forbidden_uri_value?(attribute.value.to_s)
347
+ return true if css_content_name?(attribute.name) && forbidden_css_content?(attribute.value.to_s)
348
+ return true if animation_target_attribute?(attribute) && forbidden_name?(attribute.value.to_s)
349
+ return true if forbidden_base_value?(attribute)
350
+
351
+ forbidden_resource_reference?(node, attribute)
352
+ end
353
+
354
+ # Whether the name is parsed as the content of a style sheet, either because
355
+ # it declares the declarations of an element or because it is a presentation
356
+ # attribute whose CSS property resolves a URL reference (see
357
+ # SVG_URL_PRESENTATION_ATTRIBUTES).
358
+ def css_content_name?(name)
359
+ normalized = name.downcase
360
+ normalized == "style" || SVG_URL_PRESENTATION_ATTRIBUTES.include?(normalized)
361
+ end
362
+
363
+ # Whether the attribute references an external resource in an element
364
+ # which loads it when the document is rendered (e.g. the "href" of an
365
+ # "image").
366
+ def forbidden_resource_reference?(node, attribute)
367
+ return false unless resource_element?(node)
368
+ return false unless SVG_REFERENCE_NAME.match?(attribute.name)
369
+
370
+ forbidden_reference_value?(attribute.value.to_s)
371
+ end
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
+
383
+ # Whether an animation assigns an external resource to a reference
384
+ # attribute (e.g. "href") of an element which loads it, as the resource
385
+ # is loaded when the animation reaches the value. References which do not
386
+ # load a resource (e.g. the links of an "a") are not restricted, as they
387
+ # are never fetched when the document is rendered. The values assigned to
388
+ # the "style" attribute and to the presentation attributes which resolve a
389
+ # URL reference are validated as style sheet content, as the references they
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.
393
+ def forbidden_animation_reference?(node)
394
+ return false unless SVG_ANIMATION_ELEMENTS.include?(node.name.downcase)
395
+
396
+ targets = animation_targets(node)
397
+ values = animation_values(node)
398
+ return false if targets.empty? || values.empty?
399
+
400
+ targets.any? { |target| forbidden_animation_target?(node, target, values) }
401
+ end
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)
406
+ return true if css_content_name?(target) && forbidden_css_values?(values)
407
+ return false unless SVG_REFERENCE_NAME.match?(target) && animates_resource_element?(node)
408
+
409
+ forbidden_reference_values?(values)
410
+ end
411
+
412
+ def forbidden_css_values?(values)
413
+ values.any? { |value| forbidden_css_content?(value) }
414
+ end
415
+
416
+ def forbidden_reference_values?(values)
417
+ values.any? { |value| forbidden_reference_value?(value) }
418
+ end
419
+
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)
425
+ attribute = node.attribute_nodes.find { |a| animation_target_attribute?(a) }
426
+ return [] if attribute.nil?
427
+
428
+ name_list(attribute.value.to_s)
429
+ end
430
+
431
+ def animation_target_attribute?(attribute)
432
+ SVG_ANIMATION_TARGET_NAMES.any? { |name| attribute.name.casecmp?(name) }
433
+ end
434
+
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.
439
+ def animation_values(node)
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?)
443
+ end
444
+
445
+ # Whether the animation modifies the reference of an element which loads
446
+ # the referenced resource when the document is rendered. The animation
447
+ # modifies its parent element, unless it references another one with its
448
+ # own reference attribute (e.g. "xlink:href"), which browsers resolve to
449
+ # the element with that identifier. References which do not resolve to an
450
+ # element of the document are also considered as loading a resource, so
451
+ # that documents which could hide the modified element are rejected.
452
+ def animates_resource_element?(node)
453
+ references = node.attribute_nodes.select { |attribute| SVG_REFERENCE_NAME.match?(attribute.name) }
454
+ return resource_element?(node.parent) if references.empty?
455
+
456
+ references.any? do |attribute|
457
+ targets = referenced_elements(node.document, attribute.value.to_s)
458
+ targets.empty? || targets.any? { |element| resource_element?(element) }
459
+ end
460
+ end
461
+
462
+ # The elements of the document referenced by a target reference of an
463
+ # animation element, which browsers resolve to the element with the
464
+ # identifier of the fragment, after decoding its percent-encoded characters.
465
+ # The decoded identifier is encoded as UTF-8, as the identifiers of the
466
+ # document are read with that encoding. References to other documents or to
467
+ # missing identifiers do not resolve to any element.
468
+ def referenced_elements(document, reference)
469
+ id = reference[/\A#(.*)\z/m, 1]
470
+ return [] if id.nil?
471
+
472
+ elements_by_id(document).fetch(percent_decode(id).force_encoding(Encoding::UTF_8), [])
473
+ end
474
+
475
+ # The elements of the document which declare an identifier, grouped by it.
476
+ # The index is built once per document and reused for every reference, as
477
+ # searching the whole document for each of the animations would take a
478
+ # long time for documents with many elements and animations.
479
+ def elements_by_id(document)
480
+ @elements_by_id ||= {}
481
+ @elements_by_id[document] ||= document.xpath("//*[@id]").group_by { |element| element["id"] }
482
+ end
483
+
484
+ # Whether the element loads the resource referenced by its reference
485
+ # attribute when the document is rendered.
486
+ def resource_element?(element)
487
+ SVG_RESOURCE_ELEMENTS.include?(element.name.downcase)
488
+ end
489
+
490
+ # Whether the reference loads a resource from another host or contains a
491
+ # nested document which could execute scripts or read external resources
492
+ # when it is rendered. The whitespace and control characters which can be
493
+ # used to obfuscate the scheme are removed before checking.
494
+ def forbidden_reference_value?(value)
495
+ return true if external_reference_value?(normalize_uri_value(value))
496
+ return true if forbidden_uri_value?(value)
497
+
498
+ nested_document_unsafe?(value)
499
+ end
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
+
509
+ # Whether the contents of an inline data reference declaring an SVG
510
+ # document are rejected, as they are parsed as a document of their own when
511
+ # the reference is rendered. The nested documents are validated with the
512
+ # same rules, up to a maximum depth, so that a document referencing itself
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.
520
+ def nested_document_unsafe?(value)
521
+ data = SVG_DATA_URI.match(value.strip)
522
+ return false if data.nil?
523
+ return true if depth >= MAX_NESTED_DEPTH
524
+
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
534
+ end
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.
550
+ def decode_base64(value)
551
+ return nil unless BASE64_ALPHABET.match?(value)
552
+
553
+ value.unpack1("m")
554
+ end
555
+
556
+ # Decodes the percent-encoded characters of a data URI, which are otherwise
557
+ # invisible to the checks applied to the contents of the document. The
558
+ # substitutions are applied to the bytes of the value, as the decoded
559
+ # characters can be part of a multi-byte sequence which is not valid in the
560
+ # encoding of the value. The result is kept as bytes, so that the encoding
561
+ # declared by a nested document is still read by the parser (see #parse);
562
+ # the callers which compare the decoded value with the contents of the
563
+ # document encode it as UTF-8.
564
+ def percent_decode(value)
565
+ value.dup.force_encoding(Encoding::BINARY).gsub(/%([0-9A-Fa-f]{2})/) { [Regexp.last_match(1).hex].pack("C") }
566
+ end
567
+
568
+ # Whether the value is a script URI or contains one. The animation elements
569
+ # accept lists of values separated by semicolons (e.g. in the "values"
570
+ # attribute), which are assigned to the target attribute one after another
571
+ # at runtime, so each value of the list is checked separately.
572
+ def forbidden_uri_value?(value)
573
+ value.split(";").any? do |uri|
574
+ normalized = normalize_uri_value(uri)
575
+ SVG_FORBIDDEN_URI_PREFIXES.any? { |prefix| normalized.start_with?(prefix) }
576
+ end
577
+ end
578
+
579
+ # Whether the value targets an event handler or a forbidden element, as
580
+ # used by the animation elements to modify attributes at runtime. Lists of
581
+ # names are also accepted by some animation attributes, so each name of the
582
+ # list is checked separately.
583
+ def forbidden_name?(name)
584
+ name_list(name).any? do |normalized|
585
+ SVG_EVENT_HANDLER_NAME.match?(normalized) || SVG_FORBIDDEN_ELEMENTS.include?(normalized)
586
+ end
587
+ end
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
+
596
+ # Whether the document type definition declares an entity. Entities can be
597
+ # used to read external resources (XXE) or to expand content exponentially
598
+ # (billion laughs), so documents declaring one are rejected. Only the
599
+ # declarations of the internal subset are considered, as the external ones
600
+ # are never fetched (see #parse). Text which only looks like a declaration
601
+ # outside of the document type definition (e.g. inside a comment, a CDATA
602
+ # section or a processing instruction) is not a declaration, so it does not
603
+ # reject a legitimate document.
604
+ def entity_declaration?(document)
605
+ internal_subset = document.internal_subset
606
+ return false if internal_subset.nil?
607
+
608
+ internal_subset.children.any? { |node| node.type == Nokogiri::XML::Node::ENTITY_DECL }
609
+ end
610
+
611
+ # Whether the CSS of a "style" element or attribute loads external
612
+ # resources when the document is rendered. The comments and the strings
613
+ # which do not define a URL are removed, and the escape sequences decoded,
614
+ # before checking, as they can otherwise hide the references (e.g.
615
+ # "u\rl(https://example.org)") or be mistaken for them (e.g. 'content:
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.
635
+ def forbidden_css_content?(css)
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
646
+
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
748
+ end
749
+
750
+ # Removes the comments and the strings of a style sheet, which are not
751
+ # interpreted as directives when the style sheet is rendered, so that text
752
+ # which only looks like a reference (e.g. 'content: "See @import"') is not
753
+ # mistaken for one. The strings which define the URL of a function which
754
+ # loads its arguments are kept, as those URLs are loaded. Comments and
755
+ # strings are detected following the tokenization rules of CSS, in which
756
+ # comments are not recognized inside strings and escape sequences hide the
757
+ # character following them, so that neither can be used to hide a reference
758
+ # (e.g. 'content: "/*"; background: url(https://example.org)'). The reference
759
+ # of a function is kept after a comment as well, as some engines tokenize the
760
+ # comment inside the function instead of reading it as part of the URL.
761
+ def scrub_css(css)
762
+ scanner = StringScanner.new(css)
763
+ output = +""
764
+ url_functions = []
765
+ until scanner.eos?
766
+ if scanner.scan(%r{/\*})
767
+ scan_css_comment(scanner)
768
+ elsif (quote = scanner.scan(/["']/))
769
+ # The string token is always consumed, as its content is not
770
+ # interpreted as CSS. Only the strings of the functions which load
771
+ # their arguments define a loaded URL.
772
+ string = scan_css_string(scanner, quote)
773
+ output << string if url_functions.any?
774
+ elsif (ident = scan_css_ident(scanner))
775
+ url_function = css_url_function?(ident)
776
+ output << decoded_css_name(ident, url_function)
777
+ if scanner.match?(/\(/)
778
+ url_functions.push(url_function)
779
+ output << scanner.getch
780
+ end
781
+ else
782
+ char = scanner.getch
783
+ output << char
784
+ # The arguments of these functions are kept until the function ends,
785
+ # as "image-set()" can declare several URLs. The opening parentheses
786
+ # which do not follow an identifier are tracked as well, so that their
787
+ # closing ones do not end an enclosing function and drop its arguments.
788
+ url_functions.push(false) if char == "("
789
+ url_functions.pop if char == ")"
790
+ end
791
+ end
792
+ output
793
+ end
794
+
795
+ # Consumes the comment token of CSS which starts at the current position.
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.
801
+ def scan_css_comment(scanner)
802
+ scanner.scan_until(%r{\*/}) || scanner.terminate
803
+ end
804
+
805
+ # Consumes the string token of CSS which starts at the given quote, and
806
+ # returns it with its quotes. Escape sequences hide the following
807
+ # character, and an unescaped newline or the end of the input end the
808
+ # token, as in the tokenization rules of CSS.
809
+ def scan_css_string(scanner, quote)
810
+ token = quote.dup
811
+ until scanner.eos?
812
+ escape = scanner.scan(CSS_ESCAPE)
813
+ if escape
814
+ token << escape
815
+ elsif scanner.match?(quote)
816
+ token << scanner.getch
817
+ break
818
+ elsif scanner.match?(/[\n\r\f]/)
819
+ break
820
+ else
821
+ token << scanner.getch
822
+ end
823
+ end
824
+ token
825
+ end
826
+
827
+ # Consumes the identifier token of CSS which starts at the current
828
+ # position, including its escape sequences, and returns it as it is
829
+ # written. Returns nil when no identifier starts at the current position.
830
+ # An identifier starts with a letter, an underscore, a non-ASCII character,
831
+ # an escape sequence, or a hyphen followed by one of those, and continues
832
+ # with any of those or a digit: digits are only accepted after the first
833
+ # character, as "5url(" is a number followed by a function while "url5(" is
834
+ # another function.
835
+ def scan_css_ident(scanner)
836
+ prefix = scanner.scan(/-?(?:[a-zA-Z_]|[^\x00-\x7f])/) || (scanner.match?(CSS_ESCAPE) && "")
837
+ return nil if prefix.nil?
838
+
839
+ ident = prefix.dup
840
+ loop do
841
+ char = scanner.scan(CSS_ESCAPE) || scanner.scan(/[-\w]|[^\x00-\x7f]/)
842
+ break if char.nil?
843
+
844
+ ident << char
845
+ end
846
+ ident
847
+ end
848
+
849
+ # Whether the identifier is the name of a function which loads its arguments
850
+ # as resources. The name is matched after decoding its escape sequences, as
851
+ # they are processed before the name is interpreted, so that functions
852
+ # written with escapes (e.g. "u\72l(...)") are also recognized.
853
+ def css_url_function?(ident)
854
+ CSS_URL_FUNCTIONS.any? { |name| decode_css_escapes(ident).casecmp?(name) }
855
+ end
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
+
867
+ # Decodes the escape sequences of CSS. Invalid codepoints are replaced with
868
+ # the replacement character.
869
+ def decode_css_escapes(css)
870
+ css.gsub(CSS_ESCAPE) do
871
+ digits = Regexp.last_match(1)
872
+ next Regexp.last_match(2) if digits.nil?
873
+
874
+ codepoint = digits.to_i(16)
875
+ if codepoint.zero? || codepoint > 0x10FFFF || codepoint.between?(0xD800, 0xDFFF)
876
+ "\uFFFD"
877
+ else
878
+ [codepoint].pack("U")
879
+ end
880
+ end
881
+ end
882
+
883
+ # Removes the whitespace and control characters which can be used to
884
+ # obfuscate URI schemes (e.g. "java\tscript:") and normalizes the casing.
885
+ def normalize_uri_value(value)
886
+ value.gsub(/[[:space:][:cntrl:]]/, "").downcase
887
+ end
888
+ end
889
+ end