From 101426ca1e78a773e96e7c0716f0acb4fa64ced5 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 8 Nov 2026 18:20:25 -0800 Subject: [PATCH 1/8] refactor(editor): render dynamic option lists through an escaping helper Add wm_editor_attributes() and wm_editor_option() so every attribute value and option label on the editor page is escaped by construction. Attribute names must match a plain HTML name; true renders a boolean attribute and false or null omits it. Values use plugin_weathermap_escape_attr(), which double-encodes, so names such as "A&B.png" round-trip instead of collapsing to "A&B.png". Convert the icon, background, graph template, background sizing and key style lists, and get_fontlist(). The key style labels were previously printed unescaped, and the "Special Icon (AICON)" placeholder lost a stray ">". Signed-off-by: Thomas Vincent --- lib/editor.inc.php | 65 +++++++++++-- tests/Unit/EditorAttributesTest.php | 142 ++++++++++++++++++++++++++++ weathermap-cacti-plugin-editor.php | 36 +++---- 3 files changed, 213 insertions(+), 30 deletions(-) create mode 100644 tests/Unit/EditorAttributesTest.php diff --git a/lib/editor.inc.php b/lib/editor.inc.php index d2b351a8..6331ea7b 100644 --- a/lib/editor.inc.php +++ b/lib/editor.inc.php @@ -40,6 +40,7 @@ +-------------------------------------------------------------------------+ */ +require_once __DIR__ . '/../setup.php'; require_once __DIR__ . '/editor.comment-style.php'; require_once __DIR__ . '/editor.notes.php'; @@ -265,6 +266,58 @@ function wm_editor_sanitize_url($str) { return str_replace(['&', "\r", "\n"], ['&', '', ''], wm_editor_sanitize_string($str)); } +/** + * Build an HTML attribute list in which every value is escaped. + * + * Names must come from the caller, never from request or map data. A true + * value renders a boolean attribute; false and null omit the attribute. + * Values use plugin_weathermap_escape_attr() rather than html_escape(), + * which does not double-encode, so a value such as "&" round-trips. + * + * @param array $attributes Attribute names and values, in output order. + * + * @throws InvalidArgumentException When a name is not a plain attribute name or a value is not scalar. + * + * @return string The attributes, each with a leading space. + */ +function wm_editor_attributes(array $attributes) { + $out = ''; + + foreach ($attributes as $name => $value) { + if (!is_string($name) || !preg_match('/^[a-z][a-z0-9:-]*$/iD', $name)) { + throw new InvalidArgumentException('Invalid HTML attribute name'); + } + + if ($value === false || $value === null) { + continue; + } + + if ($value === true) { + $out .= ' ' . $name; + } elseif (is_scalar($value)) { + $out .= ' ' . $name . '="' . plugin_weathermap_escape_attr((string) $value) . '"'; + } else { + throw new InvalidArgumentException('Invalid value for HTML attribute ' . $name); + } + } + + return $out; +} + +/** + * Build an '; +} + /** * @param mixed $bw * @return bool @@ -732,10 +785,12 @@ function handle_inheritance(&$map, &$inheritables) { } /** + * Render a font selector listing the map's registered fonts. + * * @param WeatherMap $map * @param string $name * @param mixed $current - * @return mixed + * @return string */ function get_fontlist(&$map,$name,$current) { $output = ''; diff --git a/tests/Unit/EditorAttributesTest.php b/tests/Unit/EditorAttributesTest.php new file mode 100644 index 00000000..7a4e657b --- /dev/null +++ b/tests/Unit/EditorAttributesTest.php @@ -0,0 +1,142 @@ +, text: string, count: int} + */ +function wm_attributes_test_parse($html) { + $doc = new DOMDocument(); + libxml_use_internal_errors(true); + $doc->loadHTML(''); + libxml_clear_errors(); + $select = $doc->getElementsByTagName('select')->item(0); + $element = $select->firstChild; + $attributes = []; + + foreach ($element->attributes as $attribute) { + $attributes[$attribute->name] = $attribute->value; + } + + return ['tag' => $element->nodeName, 'attributes' => $attributes, 'text' => $element->textContent, 'count' => $select->childNodes->length]; +} + +it('EscapesEverySpecialCharacterInAttributeValues', function (string $char, string $encoded) { + expect(wm_editor_attributes(['value' => 'a' . $char . 'b']))->toBe(' value="a' . $encoded . 'b"'); +})->with([ + 'double quote' => ['"', '"'], + 'single quote' => ["'", '''], + 'less than' => ['<', '<'], + 'greater than' => ['>', '>'], + 'ampersand' => ['&', '&'], + 'backtick' => ['`', '`'], +]); + +it('DoubleEncodesExistingEntitiesSoValuesRoundTrip', function () { + expect(wm_editor_attributes(['value' => '& " '']))->toBe(' value="&amp; &quot; &#39;"'); +}); + +it('RoundTripsHostileAndUnicodeValuesThroughAnHtmlParser', function (string $value) { + $parsed = wm_attributes_test_parse(wm_editor_option($value, ['data-description' => $value, 'value' => $value])); + expect($parsed['count'])->toBe(1) + ->and($parsed['tag'])->toBe('option') + ->and($parsed['attributes'])->toBe(['data-description' => $value, 'value' => $value]) + ->and($parsed['text'])->toBe($value); +})->with([ + 'attribute breakout' => ['x" onmouseover="alert(1)'], + 'single breakout' => ["x' onmouseover='alert(1)"], + 'element injection' => ['">'], + 'entity text' => ['A&B <tag>'], + 'unicode' => ['Ünïcødé — 東京 🚀'], + 'whitespace' => ["tab\tand space"], +]); + +it('RendersEmptyStringsAsEmptyAttributesAndLabels', function () { + expect(wm_editor_attributes(['data-imagesrc' => '']))->toBe(' data-imagesrc=""') + ->and(wm_editor_option('', ['value' => '']))->toBe(''); +}); + +it('RendersTrueAsABooleanAttributeAndOmitsFalseAndNull', function () { + expect(wm_editor_attributes(['selected' => true]))->toBe(' selected') + ->and(wm_editor_attributes(['selected' => false]))->toBe('') + ->and(wm_editor_attributes(['hidden' => null]))->toBe('') + ->and(wm_editor_attributes(['value' => 'x', 'disabled' => true, 'hidden' => false, 'selected' => null]))->toBe(' value="x" disabled'); +}); + +it('RendersIntegerAndFloatValuesAsStrings', function () { + expect(wm_editor_attributes(['value' => 0]))->toBe(' value="0"') + ->and(wm_editor_attributes(['value' => -1]))->toBe(' value="-1"') + ->and(wm_editor_attributes(['value' => 42]))->toBe(' value="42"') + ->and(wm_editor_attributes(['value' => 1.5]))->toBe(' value="1.5"'); +}); + +it('KeepsTheCallerAttributeOrder', function () { + expect(wm_editor_attributes(['selected' => true, 'data-description' => 'd', 'data-imagesrc' => 'i', 'value' => 'v'])) + ->toBe(' selected data-description="d" data-imagesrc="i" value="v"') + ->and(wm_editor_attributes(['value' => 'v', 'selected' => true]))->toBe(' value="v" selected'); +}); + +it('ReturnsAnEmptyStringForNoAttributes', function () { + expect(wm_editor_attributes([]))->toBe('') + ->and(wm_editor_option('Label'))->toBe(''); +}); + +it('AcceptsNamespacedAndMixedCaseNames', function () { + expect(wm_editor_attributes(['xlink:href' => 'a', 'Data-X1' => 'b']))->toBe(' xlink:href="a" Data-X1="b"'); +}); + +it('RejectsInvalidAttributeNames', function (mixed $name) { + expect(fn () => wm_editor_attributes([$name => 'x']))->toThrow(InvalidArgumentException::class); +})->with([ + 'empty' => [''], + 'leading digit' => ['1value'], + 'leading dash' => ['-value'], + 'space' => ['value onclick'], + 'equals' => ['value='], + 'quote' => ['value"'], + 'angle bracket' => ['value>'], + 'slash' => ['data/x'], + 'underscore' => ['data_x'], + 'non-ascii' => ['dätä'], + 'trailing newline' => ["value\n"], + 'integer key' => [0], +]); + +it('RejectsNonScalarValues', function (mixed $value) { + expect(fn () => wm_editor_attributes(['value' => $value]))->toThrow(InvalidArgumentException::class); +})->with([ + 'array' => [[1]], + 'object' => [new stdClass()], +]); + +it('RejectsInvalidNamesInOptions', function () { + expect(fn () => wm_editor_option('x', ['on click' => 'x']))->toThrow(InvalidArgumentException::class); +}); diff --git a/weathermap-cacti-plugin-editor.php b/weathermap-cacti-plugin-editor.php index a87fcd1f..a256ac7c 100644 --- a/weathermap-cacti-plugin-editor.php +++ b/weathermap-cacti-plugin-editor.php @@ -459,19 +459,16 @@ ' . __('All', 'weathermap') . ''; + print wm_editor_option(__('All', 'weathermap'), ['value' => '-1', 'selected' => get_request_var('node_template') == -1]); $graph_templates = db_fetch_assoc('SELECT DISTINCT gt.id, gt.name FROM graph_templates AS gt INNER JOIN graph_local AS gl @@ -503,8 +500,7 @@ ORDER BY gt.name'); foreach ($graph_templates as $gt) { - print ''; + print wm_editor_option($gt['name'], ['selected' => get_request_var('node_template') == $gt['id'], 'value' => $gt['id']]); } ?> @@ -602,7 +598,7 @@ ' . __esc('(no images are available)', 'weathermap') . ''; + print wm_editor_option(__('(no images are available)', 'weathermap'), ['data-value' => '--NONE--']); } else { - print ''; + print wm_editor_option(__('--NO BACKGROUND--', 'weathermap'), ['data-description' => __('Use Map Background Colour', 'weathermap'), 'data-imagesrc' => '', 'value' => '--NONE--']); foreach ($backgd_list as $im) { $display = ucfirst(str_replace(['.png', '.gif', '.jpg'], '', basename($im))); - print ''; + print wm_editor_option($display, ['selected' => $im == $map->background, 'data-description' => $display, 'data-imagesrc' => $im, 'value' => $im]); } } ?> @@ -733,7 +725,7 @@ $background_sizing = $map->get_hint('background_sizing', 'image'); if (!in_array($background_sizing, ['fit', 'stretch', 'image'], true)) { $background_sizing = 'image'; } foreach (['fit' => __('Fit to map', 'weathermap'), 'stretch' => __('Stretch to map', 'weathermap'), 'image' => __('Use image size', 'weathermap')] as $value => $label) { - print ''; + print wm_editor_option($label, ['value' => $value, 'selected' => $background_sizing === $value]); } ?> @@ -801,7 +793,7 @@ ]; foreach ($styles as $id => $name) { - print "'; + print wm_editor_option($name, ['value' => $id, 'selected' => $map->keystyle['DEFAULT'] == $id]); } ?> From 5096eccc33d504e8b21f5a6a27b3d9e8f2d5197f Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 8 Nov 2026 18:20:26 -0800 Subject: [PATCH 2/8] test(editor): enforce escaped editor attributes and parse hostile image lists Fail when the editor page concatenates or interpolates an unescaped value into an HTML attribute, or prints an .png']; + [$image_list] = wm_option_lists_build($files, [], $used); + expect($image_list)->toHaveCount(count($files) + count($used)); + + $options = wm_option_lists_render('node_iconfilename', ['image_list' => $image_list]); + expect($options)->toHaveCount(count($image_list) + 2) + ->and($options[0])->toBe(['attributes' => ['data-description' => 'Label Only Icon', 'data-imagesrc' => '', 'value' => '--NONE--'], 'text' => 'Label Only']) + ->and($options[1])->toBe(['attributes' => ['data-description' => 'Special Purpose Icon', 'data-imagesrc' => '', 'value' => '--AICON--'], 'text' => 'Special Icon (AICON)']); + + foreach ($image_list as $index => $im) { + $label = wm_option_lists_label($im); + expect($options[$index + 2])->toBe(['attributes' => ['data-description' => $label, 'data-imagesrc' => $im, 'value' => $im], 'text' => $label]); + } + + foreach ($files as $file) { + expect($image_list)->toContain('images/objects/' . $file); + } +})->with('hostile image names'); + +it('RendersHostileBackgroundFilenamesAndSelectsOnlyTheCurrentOne', function (array $files) { + [, $backgd_list] = wm_option_lists_build([], $files, []); + expect($backgd_list)->toHaveCount(count($files)); + $current = 'images/backgrounds/' . $files[1]; + $map = (object) ['background' => $current]; + + $options = wm_option_lists_render('map_bgfile', ['backgd_list' => $backgd_list, 'map' => $map]); + expect($options)->toHaveCount(count($backgd_list) + 1) + ->and($options[0])->toBe(['attributes' => ['data-description' => 'Use Map Background Colour', 'data-imagesrc' => '', 'value' => '--NONE--'], 'text' => '--NO BACKGROUND--']); + + foreach ($backgd_list as $index => $im) { + $label = wm_option_lists_label($im); + $expected = ['data-description' => $label, 'data-imagesrc' => $im, 'value' => $im]; + + if ($im === $current) { + $expected = ['selected' => 'selected'] + $expected; + } + expect($options[$index + 1])->toBe(['attributes' => $expected, 'text' => $label]); + } + + expect(array_filter($options, fn ($option) => isset($option['attributes']['selected'])))->toHaveCount(1); +})->with('hostile image names'); + +it('RendersThePlaceholderOptionsWhenNoImagesExist', function () { + [$image_list, $backgd_list] = wm_option_lists_build([], [], []); + + expect(wm_option_lists_render('node_iconfilename', ['image_list' => $image_list]))->toBe([ + ['attributes' => ['data-value' => '--NONE--'], 'text' => 'Label Only'], + ['attributes' => ['data-value' => '--AICON--'], 'text' => 'Special Icon (AICON)'], + ])->and(wm_option_lists_render('map_bgfile', ['backgd_list' => $backgd_list, 'map' => (object) ['background' => '']]))->toBe([ + ['attributes' => ['data-value' => '--NONE--'], 'text' => '(no images are available)'], + ]); +}); diff --git a/tests/Security/EditorAttributeEscapingTest.php b/tests/Security/EditorAttributeEscapingTest.php new file mode 100644 index 00000000..3c7eb141 --- /dev/null +++ b/tests/Security/EditorAttributeEscapingTest.php @@ -0,0 +1,86 @@ + The offending lines, prefixed with line numbers. + */ +function wm_editor_unescaped_attributes($source) { + $attribute = '(?:value|data-[a-z-]+|title|alt|placeholder|href|src|id|name|class|label)'; + $escaped = '(?:html_escape|__esc|plugin_weathermap_escape_attr|htmlspecialchars|wm_editor_attributes)\s*\('; + $patterns = [ + // value="' . $var or data-x=\'' . $var + '/\b' . $attribute . '\s*=\s*(?:"\'|\\\\\'\')\s*\.(?!\s*' . $escaped . ')/i', + // "