- Issue created by @hartsak
Currently sanitization will happen when the svg file is rendered on page. However, SVG image field module allows uploading an SVG file even if it contains for example a script tag or an iframe tag. The original file will be preserved on the server filesystem and it can be directly loaded from there and the scripts will be executed in the user's browser.
It would be great if the sanitization could also be applied to the upload process as well. It could possibly be optional if needed?
I included a mock-up screenshot of some quickly made example how it could look like when an uploaded svg file does not validate because of suspicious tags.
Add new upload validator in svg_image_field/src/Plugin/Field/FieldWidget/SvgImageFieldWidget.php
For example something like this
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element = parent::formElement($items, $delta, $element, $form, $form_state);
$field_settings = $this->getFieldSettings();
$element['#upload_validators']['file_validate_extensions'][0] = 'svg';
$element['#upload_validators']['svg_image_field_validate_mime_type'] = [];
$element['#upload_validators']['svg_image_field_validate_sanitize'] = [];
After that, utilize the svg sanitizer in hook_file_validate() in a similar way as the mime type is validated
function svg_image_field_validate_sanitize(FileInterface $file) {
Something along these lines
...
$svgSanitizer = new Sanitizer();
$svg_data = $svgSanitizer->sanitize($svg_data);
if ($issues = $svgSanitizer->getXmlIssues()) {
foreach ($issues as $issue) {
$errors[] = $issue['message'];
}
}
...
In addition to this there could be settings for this, if someone doesn't want their svg files to be sanitized during upload. This could maybe be controlled in the field or form settings?
Active
2.3
Code