mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-10-04 06:15:09 +00:00
security: triage the CodeQL backlog — 129 alerts, three of them live (#561)
* fix(web): escape quotes in every HTML escaper, not just & < >
The escapers are all `div.textContent = x; return div.innerHTML`. That
round-trip escapes &, < and > -- the only characters the HTML serializer
must escape in a text node -- and leaves quotes alone. Every widget then
interpolates the result into a quoted attribute value:
value="${escapeHtml(v)}" title="${escapeHtml(v)}"
so a value of `x" onmouseover="alert(1)` closes the attribute and adds an
event handler of its own. CodeQL reported this 83 times
(js/incomplete-html-attribute-sanitization) across the widget files.
It is one bug, not 83: the widgets each carry a standalone fallback that
did escape quotes, but they all prefer BaseWidget.escapeHtml when
window.BaseWidget exists -- which it always does in the shipped page -- so
the correct fallbacks were dead code and the incomplete shared one ran.
Fixed at each source instead of at the call sites.
app-shell.js already documented this exact gap in a comment and worked
around it by building DOM nodes by hand; that workaround stays (setting a
property cannot be got wrong), the comment is now accurate.
cache.html's delete button interpolated the cache key into
`onclick="deleteCacheFile('...')"`. Escaping cannot help there -- the
browser HTML-decodes the attribute before parsing it as JS, so `'`
becomes a real `'` again -- so the key moves to a data-cache-key
attribute that the handler reads back.
url-input.js additionally wrote a value straight into an <a href> after
validating it against a schema-supplied protocol list, and that list
accepted any RFC 3986 scheme -- "javascript" included. Scriptable schemes
(javascript, data, vbscript, blob, filesystem) are now refused both when
the list is normalised and when a URL is checked against it, and the
render path routes its href through the same check instead of emitting
whatever was stored (js/xss-through-dom).
test/js/unit/test_html_escaping.js reads each escaper out of the shipped
file and runs it, so losing the quote handling again fails a test rather
than a scan.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(security): stop request-supplied names from reaching paths outside their base
Three of the py/path-injection alerts were live, not lint:
* GET /api/v3/plugins/<plugin_id>/static/<path:file_path> read any file
whose resolved path *string-prefixed* the plugin directory. Flask's
default converter forbids a slash but not dots, and
get_plugin_directory('..') returned the parent of the plugins directory
because it exists -- so every file under the project root then prefixed
that directory, config/config_secrets.json included. The prefix check
was also wrong on its own terms: with plugin dir "plugin-repos/foo",
"../foo-evil/x" resolves to "plugin-repos/foo-evil/x", whose string does
start with "plugin-repos/foo".
* POST /api/v3/plugins/of-the-day/json/delete interpolated the request
body's file_id into f"{file_id}.json" and unlinked it, unvalidated. A
file_id of "../../../../etc/something" deleted that file. This is the
one finding in the batch that destroyed data rather than exposing it.
* POST /api/v3/cache/delete passed the body's key through
CacheManager.clear_cache to DiskCache, which joined it as a filename and
called os.remove. Same shape, same result. The guard goes in
DiskCache.get_cache_path, the single choke point get/set/clear share, so
every caller is covered rather than just this route. Real keys are the
stems of files already flat in the cache directory -- that is how
list_cache_files derives them -- so nothing legitimate is turned away.
The rest of the cluster (web_interface/app.py's asset route, the plugin
update handler, _get_plugin_version, the plugin-schema read in config.py)
was guarded in ways that held, but each had grown its own version of the
check. They now go through one helper, src/common/path_safety.py, which
returns the *sanitised value* rather than a verdict -- so a caller cannot
validate one string and open another, which is how the two real bugs
above were shaped.
Also: WiFiManager.connect_to_network took the SSID and password straight
from POST /api/v3/wifi/connect into nmcli's argv. There is no shell there,
so CodeQL's py/command-line-injection alert overstates the risk -- but
nmcli reads a leading "-" as an option, so an SSID of "--ask" asks nmcli
to run differently rather than to join a network. Both values are now
checked for shape (802.11's 32-octet SSID limit, WPA's 8-63 char
passphrase or 64-char hex key, no control characters, no leading dash)
before any subprocess runs.
test/test_path_traversal_guards.py asserts on the filesystem, not just
the status code: a handler that returns 403 and deletes the file anyway
would pass the weaker check. Twelve of its cases fail against the
unpatched code.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(web): refuse a plugin id that is not a plain name, don't truncate it
pages_v3 and scripts/dev_server.py ran request ids through
os.path.basename and carried on with what came out, so "../weather"
rendered the config form for "weather". Nothing escaped the plugins
directory -- the relative_to guards held -- but the handler answered a
request nobody made, and validating one string while the filesystem sees
another is the shape both live traversals earlier in this branch had.
Same treatment as the rest: safe_path_component rejects rather than
truncates, resolve_under returns the path it checked, and the call sites
use what those return. The three handlers that had hand-rolled
resolve-and-relative_to blocks lose about twenty lines to the shared one.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* docs(web): say what the plugin web_ui iframe actually is
The docstring claimed the fragment runs "in a sandboxed iframe". The
iframe in plugin_config.html carries no sandbox attribute, so the
fragment runs with the interface's own origin. That is fine -- the file
belongs to an installed plugin, and an installed plugin already runs
Python on the device, so the trust boundary is install rather than this
route -- but a comment promising containment that is not there is worse
than no comment. This is the context for the py/reflective-xss alert on
this handler.
Also drops the now-unused os/os.path imports.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(web): inline url-input's scheme guard at the previewLink.href sink
CodeQL flagged this line as a new high-severity js/xss-through-dom alert
on this PR even though it is already covered by SCRIPTABLE_SCHEMES: the
guard reached the sink through safeHref -> isValidUrl, two function calls
away, which its DOM-based-XSS sanitizer recognition does not trace.
Behavior is unchanged -- same scheme check, same SCRIPTABLE_SCHEMES list,
same allowedProtocols gate -- just inlined directly above the
previewLink.href assignment it guards, so the barrier is visible in the
same scope as the sink.
Added a regression test that runs the shipped onInput handler (not just
the extracted helpers) against a mocked DOM, so a future change that
reintroduces an unguarded previewLink.href assignment fails here.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(security): address CodeRabbit findings on the CodeQL triage PR
- src/wifi_manager.py: reject non-ASCII WPA-PSK passphrases before any
credential-saving or connect flow runs. NetworkManager only accepts
printable ASCII passphrases (or a 64-char hex key); a non-ASCII value
was previously saved/attempted before nmcli itself rejected it.
- web_interface/blueprints/api_v3/config.py: fail closed when the
plugin config schema path can't be resolved under the plugins
directory (e.g. a symlinked plugin dir). Previously this fell
through with secret_fields left empty, so submitted credentials for
that plugin were saved as ordinary, unencrypted configuration.
- web_interface/static/v3/js/widgets/plugin-file-manager.js: stop
splicing the JSON day/column key into an inline oninput="..." handler
string. escHtml() escapes quotes for a normal HTML attribute, but the
browser HTML-decodes the attribute before running it as script, which
undoes that escaping and lets a crafted column name (e.g. from an
uploaded JSON file) break out of the JS string and execute. Cell
edits now travel through data-day/data-col attributes read by one
delegated 'input' listener instead.
While in this file: fixed 6 pre-existing missing-')' typos on
multi-line safeSetHTML(...) calls (already flagged by Biome in this
PR's own CodeRabbit run as syntax errors blocking its lint pass).
These predate this PR (present on main too) but made the whole file
fail to parse in any JS engine, which is a bigger problem than the
XSS finding itself and directly touches the same lines.
Added/extended regression tests for each fix; full suites pass
(pytest: 4580 passed, 62 skipped; JS: 84 assertions).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -32,6 +32,8 @@ os.environ['EMULATOR'] = 'true'
|
||||
|
||||
from flask import Flask, render_template, request, jsonify
|
||||
|
||||
from src.common.path_safety import resolve_under, safe_path_component
|
||||
|
||||
app = Flask(__name__, template_folder=str(Path(__file__).parent / 'templates'))
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -118,7 +120,8 @@ def find_plugin_dir(plugin_id: str) -> Optional[Path]:
|
||||
one of the plugin search dirs, so a crafted id can never name a path
|
||||
outside them.
|
||||
"""
|
||||
if not isinstance(plugin_id, str) or not _SAFE_PLUGIN_ID_RE.match(plugin_id):
|
||||
plugin_id = safe_path_component(plugin_id)
|
||||
if not plugin_id or not _SAFE_PLUGIN_ID_RE.match(plugin_id):
|
||||
return None
|
||||
from src.plugin_system.plugin_loader import PluginLoader
|
||||
loader = PluginLoader()
|
||||
@@ -140,8 +143,8 @@ def find_plugin_dir(plugin_id: str) -> Optional[Path]:
|
||||
|
||||
def load_config_defaults(plugin_dir: 'str | Path') -> Dict[str, Any]:
|
||||
"""Extract default values from config_schema.json."""
|
||||
schema_path = Path(plugin_dir) / 'config_schema.json'
|
||||
if not schema_path.exists():
|
||||
schema_path = resolve_under(plugin_dir, 'config_schema.json')
|
||||
if schema_path is None or not schema_path.exists():
|
||||
return {}
|
||||
with open(schema_path, 'r') as f:
|
||||
schema = json.load(f)
|
||||
@@ -175,8 +178,8 @@ def api_plugin_schema(plugin_id):
|
||||
if not plugin_dir:
|
||||
return jsonify({'error': f'Plugin not found: {plugin_id}'}), 404
|
||||
|
||||
schema_path = plugin_dir / 'config_schema.json'
|
||||
if not schema_path.exists():
|
||||
schema_path = resolve_under(plugin_dir, 'config_schema.json')
|
||||
if schema_path is None or not schema_path.exists():
|
||||
return jsonify({'schema': {'type': 'object', 'properties': {}}})
|
||||
|
||||
with open(schema_path, 'r') as f:
|
||||
|
||||
Vendored
+20
-4
@@ -15,6 +15,8 @@ import zlib
|
||||
from typing import Dict, Any, Optional, Protocol
|
||||
from datetime import datetime
|
||||
|
||||
from src.common.path_safety import safe_path_component
|
||||
|
||||
try: # optional: large speedup on the cache write path, see _dumps below
|
||||
import orjson
|
||||
except ImportError: # pragma: no cover - exercised on hosts without the wheel
|
||||
@@ -160,16 +162,30 @@ class DiskCache:
|
||||
def get_cache_path(self, key: str) -> Optional[str]:
|
||||
"""
|
||||
Get the path for a cache file.
|
||||
|
||||
|
||||
The key becomes a filename, so it has to be one. Keys reach this
|
||||
method from the web API -- POST /api/v3/cache/delete passes the
|
||||
request body's ``key`` straight through CacheManager.clear_cache to
|
||||
os.remove -- and a key of ``../../../../etc/whatever`` named a file
|
||||
well outside the cache directory. Every real key is the stem of a
|
||||
file already sitting flat in cache_dir (that is how list_cache_files
|
||||
derives them), so rejecting anything with a path component turns
|
||||
away only inputs that could never have been written here.
|
||||
|
||||
Args:
|
||||
key: Cache key
|
||||
|
||||
|
||||
Returns:
|
||||
Path to cache file or None if cache is disabled
|
||||
Path to cache file, or None if cache is disabled or the key is
|
||||
not a usable filename
|
||||
"""
|
||||
if not self.cache_dir:
|
||||
return None
|
||||
return os.path.join(self.cache_dir, f"{key}.json")
|
||||
safe_key = safe_path_component(key)
|
||||
if safe_key is None:
|
||||
self.logger.warning("Rejected unsafe cache key %r", key)
|
||||
return None
|
||||
return os.path.join(self.cache_dir, f"{safe_key}.json")
|
||||
|
||||
def get(self, key: str, max_age: Optional[int] = 300) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
"""One place to turn a request-supplied name into a path you can open.
|
||||
|
||||
Every web handler that opens a file under a fixed directory had grown its own
|
||||
version of this: a regex here, an ``os.path.basename`` there, a
|
||||
``str(x).startswith(str(base))`` somewhere else. They were not equivalent.
|
||||
``startswith`` says ``plugin-repos/foo-evil`` is inside ``plugin-repos/foo``;
|
||||
validating a name in one place and rebuilding the path from the *raw* value in
|
||||
another leaves the guard checking something the filesystem never sees.
|
||||
|
||||
Two functions, used the same way everywhere:
|
||||
|
||||
``safe_path_component(value)``
|
||||
``value`` if it is one harmless path segment, otherwise ``None``.
|
||||
|
||||
``resolve_under(base, *parts)``
|
||||
the resolved path, or ``None`` if any part is unsafe or the result would
|
||||
land outside ``base``.
|
||||
|
||||
Both *return the sanitised value* rather than a boolean, so a caller cannot
|
||||
validate one string and then open another -- and so a scanner can follow what
|
||||
actually reaches ``open()``. ``os.path.basename`` does the stripping because it
|
||||
is the sanitiser CodeQL's path-injection query recognises; the equality check
|
||||
after it means an input with a directory part is rejected outright instead of
|
||||
being silently truncated to something the caller did not ask for.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any, List, Optional, Union
|
||||
|
||||
__all__ = [
|
||||
'safe_path_component',
|
||||
'safe_relative_parts',
|
||||
'resolve_under',
|
||||
]
|
||||
|
||||
# Names that are a path component syntactically but never name a real entry a
|
||||
# caller means to reach.
|
||||
_RESERVED_COMPONENTS = frozenset({'', '.', '..'})
|
||||
|
||||
|
||||
def safe_path_component(value: Any) -> Optional[str]:
|
||||
"""Return ``value`` when it is a single, harmless path segment.
|
||||
|
||||
Returns ``None`` for anything else: a non-string, an empty string, ``.`` or
|
||||
``..``, a value carrying a directory separator (either platform's), a drive
|
||||
letter, or an embedded NUL.
|
||||
|
||||
The return value is what callers must join -- not the argument.
|
||||
"""
|
||||
if not isinstance(value, str) or not value:
|
||||
return None
|
||||
if '\x00' in value:
|
||||
return None
|
||||
|
||||
# basename strips any directory component, so what a caller joins cannot
|
||||
# carry one. Comparing the result against the input rejects rather than
|
||||
# truncates: "../etc/passwd" is an error, not a request for "passwd".
|
||||
name = os.path.basename(value)
|
||||
if name != value or name in _RESERVED_COMPONENTS:
|
||||
return None
|
||||
|
||||
# basename only knows the host platform's separator. On POSIX a backslash
|
||||
# is an ordinary character, and "C:" is a plausible-looking name that
|
||||
# os.path.join would treat as a drive on Windows. Rule both out everywhere
|
||||
# so behaviour does not depend on where the service happens to run.
|
||||
if '/' in name or '\\' in name or os.sep in name or (os.altsep and os.altsep in name):
|
||||
return None
|
||||
if ':' in name and len(name) >= 2 and name[1] == ':':
|
||||
return None
|
||||
|
||||
return name
|
||||
|
||||
|
||||
def safe_relative_parts(value: Any) -> Optional[List[str]]:
|
||||
"""Split a multi-segment relative path into safe components.
|
||||
|
||||
For Flask's ``<path:...>`` converter, where ``a/b/c.json`` is legitimate but
|
||||
``../../config/config_secrets.json`` is not. Returns the component list, or
|
||||
``None`` if any component fails :func:`safe_path_component`.
|
||||
"""
|
||||
if not isinstance(value, str) or not value:
|
||||
return None
|
||||
if value.startswith('/') or value.startswith('\\'):
|
||||
return None
|
||||
|
||||
parts: List[str] = []
|
||||
for raw in value.replace('\\', '/').split('/'):
|
||||
if raw == '':
|
||||
# A trailing or doubled slash names nothing; skip it rather than
|
||||
# rejecting a path a browser may well send.
|
||||
continue
|
||||
part = safe_path_component(raw)
|
||||
if part is None:
|
||||
return None
|
||||
parts.append(part)
|
||||
|
||||
return parts or None
|
||||
|
||||
|
||||
def resolve_under(base: Union[str, Path], *parts: Any) -> Optional[Path]:
|
||||
"""Resolve ``base/parts...``, or ``None`` if that would escape ``base``.
|
||||
|
||||
Each part is validated with :func:`safe_path_component` first, so the value
|
||||
that reaches the filesystem is the sanitised one. The containment check is
|
||||
kept as well: it is what catches a symlink inside ``base`` pointing out of
|
||||
it, which no amount of name validation can see.
|
||||
"""
|
||||
safe_parts: List[str] = []
|
||||
for part in parts:
|
||||
component = safe_path_component(part)
|
||||
if component is None:
|
||||
return None
|
||||
safe_parts.append(component)
|
||||
|
||||
try:
|
||||
base_resolved = Path(base).resolve()
|
||||
candidate = base_resolved.joinpath(*safe_parts).resolve()
|
||||
candidate.relative_to(base_resolved)
|
||||
except (OSError, ValueError, TypeError):
|
||||
return None
|
||||
|
||||
return candidate
|
||||
+77
-3
@@ -36,7 +36,7 @@ import os
|
||||
import time
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
from dataclasses import dataclass
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -1248,14 +1248,28 @@ class WiFiManager:
|
||||
def connect_to_network(self, ssid: str, password: str) -> Tuple[bool, str]:
|
||||
"""
|
||||
Connect to a WiFi network with failsafe to restore original connection on failure.
|
||||
|
||||
|
||||
Args:
|
||||
ssid: Network SSID
|
||||
password: Network password (empty for open networks)
|
||||
|
||||
|
||||
Returns:
|
||||
Tuple of (success, message)
|
||||
"""
|
||||
# Both values arrive verbatim from POST /api/v3/wifi/connect and end up
|
||||
# as nmcli argv entries. There is no shell here, so no metacharacter
|
||||
# can start a second command -- but nmcli reads a leading "-" as an
|
||||
# option, so an SSID of "--ask" or "-t" is a request to run nmcli
|
||||
# differently rather than to join a network. See _validate_ssid.
|
||||
ssid, error = self._validate_ssid(ssid)
|
||||
if error:
|
||||
logger.warning("Rejected WiFi connect request: %s", error)
|
||||
return False, error
|
||||
password, error = self._validate_wifi_password(password)
|
||||
if error:
|
||||
logger.warning("Rejected WiFi connect request: %s", error)
|
||||
return False, error
|
||||
|
||||
# Save current connection info for failsafe restoration
|
||||
original_connection = None
|
||||
original_ssid = None
|
||||
@@ -1635,6 +1649,66 @@ class WiFiManager:
|
||||
self._show_led_message("Connection error", duration=5)
|
||||
return False, str(e)
|
||||
|
||||
# 802.11 caps an SSID at 32 octets. Control characters cannot appear in a
|
||||
# real one, and a leading "-" would be read by nmcli as an option rather
|
||||
# than a network name.
|
||||
_SSID_MAX_OCTETS = 32
|
||||
# WPA-PSK passphrases are 8-63 printable ASCII characters, or a 64-char hex
|
||||
# key. Anything outside that cannot authenticate, so refusing it early
|
||||
# costs nothing and keeps argv clean.
|
||||
_PSK_MIN_LEN = 8
|
||||
_PSK_MAX_LEN = 63
|
||||
|
||||
@classmethod
|
||||
def _validate_ssid(cls, ssid: Any) -> Tuple[str, Optional[str]]:
|
||||
"""Return (ssid, None) for a usable SSID, or ('', reason) to refuse it.
|
||||
|
||||
Returns the value rather than a boolean so callers pass on what was
|
||||
checked instead of re-reading the original.
|
||||
"""
|
||||
if not isinstance(ssid, str):
|
||||
return '', "SSID must be text"
|
||||
ssid = ssid.strip()
|
||||
if not ssid:
|
||||
return '', "SSID cannot be empty"
|
||||
if len(ssid.encode('utf-8')) > cls._SSID_MAX_OCTETS:
|
||||
return '', f"SSID is longer than {cls._SSID_MAX_OCTETS} bytes"
|
||||
if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in ssid):
|
||||
return '', "SSID contains control characters"
|
||||
if ssid.startswith('-'):
|
||||
# nmcli would take this for an option, not a network name.
|
||||
return '', "SSID cannot start with '-'"
|
||||
return ssid, None
|
||||
|
||||
@classmethod
|
||||
def _validate_wifi_password(cls, password: Any) -> Tuple[str, Optional[str]]:
|
||||
"""Return (password, None) for a usable passphrase, or ('', reason).
|
||||
|
||||
An empty password means an open network and is allowed through.
|
||||
"""
|
||||
if password is None:
|
||||
return '', None
|
||||
if not isinstance(password, str):
|
||||
return '', "Password must be text"
|
||||
if password == '':
|
||||
return '', None
|
||||
if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in password):
|
||||
return '', "Password contains control characters"
|
||||
if not password.isascii():
|
||||
# WPA-PSK passphrases are printable ASCII only; NetworkManager
|
||||
# rejects anything else.
|
||||
return '', "Password must be ASCII"
|
||||
if password.startswith('-'):
|
||||
# Same reason as the SSID: nmcli would read it as an option.
|
||||
return '', "Password cannot start with '-'"
|
||||
is_hex_key = len(password) == 64 and all(c in '0123456789abcdefABCDEF' for c in password)
|
||||
if not is_hex_key and not (cls._PSK_MIN_LEN <= len(password) <= cls._PSK_MAX_LEN):
|
||||
return '', (
|
||||
f"Password must be {cls._PSK_MIN_LEN}-{cls._PSK_MAX_LEN} characters "
|
||||
f"(or a 64-character hex key)"
|
||||
)
|
||||
return password, None
|
||||
|
||||
@staticmethod
|
||||
def _is_wrong_password_error(error_msg: str) -> bool:
|
||||
"""Return True when nmcli's error output indicates an authentication failure."""
|
||||
|
||||
+2
-1
@@ -14,7 +14,8 @@ const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
const BASE = process.env.BASE || 'http://localhost:5000';
|
||||
const UNIT = ['unit/test_list_filter.js', 'unit/test_render_cards.js'];
|
||||
const UNIT = ['unit/test_list_filter.js', 'unit/test_render_cards.js',
|
||||
'unit/test_html_escaping.js'];
|
||||
const DOM = ['dom/test_installed_dom.js', 'dom/test_store_dom.js', 'dom/test_no_double_fetch.js',
|
||||
'dom/test_tools_sections.js'];
|
||||
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
// Every HTML escaper in the web interface must escape quotes, not just
|
||||
// & < >.
|
||||
//
|
||||
// The escapers are all written as `div.textContent = x; return div.innerHTML`.
|
||||
// That round-trip escapes &, < and > because those are the only characters the
|
||||
// HTML serializer has to escape in a *text node* -- quotes are left alone. But
|
||||
// the widgets interpolate the result into quoted attribute values
|
||||
// (`value="${escapeHtml(v)}"`, `title="${escapeHtml(v)}"`, ...), and there a
|
||||
// bare `"` closes the attribute and lets the value add attributes of its own:
|
||||
//
|
||||
// name" onfocus="alert(1)
|
||||
//
|
||||
// CodeQL reported 83 js/incomplete-html-attribute-sanitization alerts for
|
||||
// exactly this. This suite pins the fix at the source: it reads each real
|
||||
// implementation out of the shipped file and runs it, so an escaper that loses
|
||||
// its quote handling again fails here rather than in a scanner run weeks later.
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const ROOT = path.resolve(__dirname, '../../../web_interface');
|
||||
|
||||
let pass = 0, fail = 0;
|
||||
const ok = (label, cond, extra) => cond
|
||||
? (pass++, console.log(' ok ' + label))
|
||||
: (fail++, console.log(' FAIL ' + label + (extra !== undefined ? ' -> ' + JSON.stringify(extra).slice(0, 300) : '')));
|
||||
|
||||
// ── DOM shim ───────────────────────────────────────────────────────────────
|
||||
// Mirrors what a browser does reading innerHTML back off textContent: & < >
|
||||
// are escaped, quotes are not. Anything the escaper adds on top of that is
|
||||
// the escaper's own doing, which is what we are testing.
|
||||
class FakeEl {
|
||||
set textContent(v) { this._t = String(v == null ? '' : v); }
|
||||
get textContent() { return this._t || ''; }
|
||||
get innerHTML() {
|
||||
return (this._t || '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>');
|
||||
}
|
||||
}
|
||||
global.document = { createElement: () => new FakeEl() };
|
||||
global.window = global;
|
||||
|
||||
// ── source extraction ──────────────────────────────────────────────────────
|
||||
// Pull a function out of a real source file by its opening line and balanced
|
||||
// braces, so the test runs the shipped code rather than a copy of it.
|
||||
function extract(file, opener) {
|
||||
const src = fs.readFileSync(path.join(ROOT, file), 'utf8');
|
||||
const start = src.indexOf(opener);
|
||||
if (start < 0) {
|
||||
console.error(`FAIL: cannot find ${JSON.stringify(opener)} in ${file}`);
|
||||
process.exit(1);
|
||||
}
|
||||
let i = src.indexOf('{', start), depth = 0;
|
||||
for (let j = i; j < src.length; j++) {
|
||||
if (src[j] === '{') depth++;
|
||||
else if (src[j] === '}') {
|
||||
depth--;
|
||||
if (depth === 0) return src.slice(start, j + 1);
|
||||
}
|
||||
}
|
||||
console.error(`FAIL: unbalanced braces after ${JSON.stringify(opener)} in ${file}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Evaluate an extracted escaper and return it as a callable.
|
||||
function loadFn(file, opener, name, { method = false } = {}) {
|
||||
const body = extract(file, opener);
|
||||
// Class/object methods (`escapeHtml(text) {...}`) are not valid statements on
|
||||
// their own -- wrap them in an object literal so they can be evaluated.
|
||||
const code = method
|
||||
? `(function(){ const o = { ${body} }; return o.${name}.bind(o); })()`
|
||||
: `(function(){ ${body}; return ${name}; })()`;
|
||||
// eslint-disable-next-line no-eval
|
||||
return eval(code);
|
||||
}
|
||||
|
||||
// ── the escapers, as shipped ───────────────────────────────────────────────
|
||||
const ESCAPERS = [
|
||||
['base-widget.js (BaseWidget.escapeHtml)',
|
||||
'static/v3/js/widgets/base-widget.js', 'escapeHtml(text) {', 'escapeHtml', true],
|
||||
['plugins_manager.js (top-level escapeHtml)',
|
||||
'static/v3/plugins_manager.js', 'function escapeHtml(text) {', 'escapeHtml', false],
|
||||
['plugins_manager.js (starlark escapeHtml)',
|
||||
'static/v3/plugins_manager.js', 'function escapeHtml(str) {', 'escapeHtml', false],
|
||||
['error_handler.js (escapeHtml)',
|
||||
'static/v3/js/utils/error_handler.js', 'function escapeHtml(text) {', 'escapeHtml', false],
|
||||
['json-file-manager.js (_esc)',
|
||||
'static/v3/js/widgets/json-file-manager.js', '_esc(str) {', '_esc', true],
|
||||
['plugin-file-manager.js (escHtml)',
|
||||
'static/v3/js/widgets/plugin-file-manager.js', 'function escHtml(s) {', 'escHtml', false],
|
||||
['app-shell.js (escapeHtml)',
|
||||
'static/v3/js/app-shell.js', 'escapeHtml(text) {', 'escapeHtml', true],
|
||||
['logs.html (escapeHtml)',
|
||||
'templates/v3/partials/logs.html', 'function escapeHtml(text) {', 'escapeHtml', false],
|
||||
['cache.html (escapeHtml)',
|
||||
'templates/v3/partials/cache.html', 'function escapeHtml(text) {', 'escapeHtml', false],
|
||||
];
|
||||
|
||||
// The breakout payload: closes a double-quoted attribute and opens an event
|
||||
// handler. If `"` survives escaping, this is live script in the rendered page.
|
||||
const BREAKOUT = 'x" onmouseover="alert(1)';
|
||||
|
||||
console.log('\n1. every escaper neutralises a double-quote attribute breakout');
|
||||
for (const [label, file, opener, name, method] of ESCAPERS) {
|
||||
const fn = loadFn(file, opener, name, { method });
|
||||
const out = String(fn(BREAKOUT));
|
||||
ok(`${label}: no raw "`, !out.includes('"'), out);
|
||||
ok(`${label}: emits "`, out.includes('"'), out);
|
||||
}
|
||||
|
||||
console.log('\n2. every escaper also escapes single quotes');
|
||||
for (const [label, file, opener, name, method] of ESCAPERS) {
|
||||
const fn = loadFn(file, opener, name, { method });
|
||||
const out = String(fn("x' onmouseover='alert(1)"));
|
||||
ok(`${label}: no raw '`, !out.includes("'"), out);
|
||||
}
|
||||
|
||||
console.log('\n3. the & < > behaviour they already had is unchanged');
|
||||
for (const [label, file, opener, name, method] of ESCAPERS) {
|
||||
const fn = loadFn(file, opener, name, { method });
|
||||
const out = String(fn('<img src=x onerror=alert(1)> & done'));
|
||||
ok(`${label}: no raw <`, !out.includes('<'), out);
|
||||
ok(`${label}: no raw >`, !out.includes('>'), out);
|
||||
ok(`${label}: & becomes &`, /&/.test(out), out);
|
||||
}
|
||||
|
||||
console.log('\n4. ampersands are escaped before quotes, so " cannot be forged');
|
||||
// If `&` were escaped last, the input `"` would come out as a literal
|
||||
// `"` after the browser decodes the attribute. Order matters; pin it.
|
||||
for (const [label, file, opener, name, method] of ESCAPERS) {
|
||||
const fn = loadFn(file, opener, name, { method });
|
||||
const out = String(fn('"'));
|
||||
ok(`${label}: " input stays inert`, out === '&quot;', out);
|
||||
}
|
||||
|
||||
// ── url-input scheme handling (js/xss-through-dom) ─────────────────────────
|
||||
console.log('\n5. url-input never treats a scriptable scheme as a valid URL');
|
||||
{
|
||||
const src = fs.readFileSync(path.join(ROOT, 'static/v3/js/widgets/url-input.js'), 'utf8');
|
||||
const a = src.indexOf('const RFC_SCHEME_PATTERN');
|
||||
const b = src.indexOf("window.LEDMatrixWidgets.register('url-input'");
|
||||
if (a < 0 || b < 0) { console.error('FAIL: cannot locate url-input helpers'); process.exit(1); }
|
||||
// eslint-disable-next-line no-eval
|
||||
const helpers = eval(`(function(){ ${src.slice(a, b)}; return { normalizeProtocols, isValidUrl, safeHref }; })()`);
|
||||
const { normalizeProtocols, isValidUrl, safeHref } = helpers;
|
||||
|
||||
ok('javascript: rejected under the default protocols',
|
||||
!isValidUrl('javascript:alert(1)', ['http', 'https']));
|
||||
ok('javascript: still rejected when a schema asks for it',
|
||||
!isValidUrl('javascript:alert(1)', normalizeProtocols(['javascript'])));
|
||||
ok('a schema asking only for javascript falls back to http/https',
|
||||
JSON.stringify(normalizeProtocols(['javascript'])) === JSON.stringify(['http', 'https']),
|
||||
normalizeProtocols(['javascript']));
|
||||
ok('data: rejected', !isValidUrl('data:text/html,<script>alert(1)</script>', ['http', 'https', 'data']));
|
||||
ok('vbscript: rejected', !isValidUrl('vbscript:msgbox(1)', ['http', 'https', 'vbscript']));
|
||||
ok('normalizeProtocols drops scriptable schemes but keeps the rest',
|
||||
JSON.stringify(normalizeProtocols('https,javascript,ftp')) === JSON.stringify(['https', 'ftp']),
|
||||
normalizeProtocols('https,javascript,ftp'));
|
||||
|
||||
ok('ordinary https URL still valid', isValidUrl('https://example.com/x?y=1', ['http', 'https']));
|
||||
ok('ordinary http URL still valid', isValidUrl('http://example.com', ['http', 'https']));
|
||||
ok('a scheme outside the allow-list is still rejected',
|
||||
!isValidUrl('ftp://example.com', ['http', 'https']));
|
||||
|
||||
ok('safeHref passes a good URL through', safeHref('https://example.com', ['http', 'https']) === 'https://example.com');
|
||||
ok('safeHref blanks a javascript: URL', safeHref('javascript:alert(1)', ['http', 'https']) === '');
|
||||
ok('safeHref blanks an unparseable value', safeHref('not a url', ['http', 'https']) === '');
|
||||
}
|
||||
|
||||
// ── url-input onInput: the sink itself, not just the pulled-out helpers ────
|
||||
// The scheme check now lives inline in onInput, right where the value reaches
|
||||
// `previewLink.href`, instead of behind safeHref/isValidUrl -- see the comment
|
||||
// at that assignment in url-input.js for why. Run the handler as shipped so a
|
||||
// regression that reintroduces an unguarded `previewLink.href = value` fails
|
||||
// here, not just in a scanner run weeks later.
|
||||
console.log('\n6. url-input onInput: previewLink.href is guarded at the sink');
|
||||
{
|
||||
class FakeClassList {
|
||||
constructor() { this.classes = new Set(['hidden']); }
|
||||
add(c) { this.classes.add(c); }
|
||||
remove(c) { this.classes.delete(c); }
|
||||
contains(c) { return this.classes.has(c); }
|
||||
}
|
||||
const mockDoc = (value, protocolsAttr) => {
|
||||
const elements = {
|
||||
_input: { value, checkValidity: () => true, validationMessage: '', classList: new FakeClassList() },
|
||||
_preview: { classList: new FakeClassList() },
|
||||
_preview_link: {
|
||||
classList: new FakeClassList(),
|
||||
_href: undefined,
|
||||
set href(v) { this._href = v; },
|
||||
get href() { return this._href; },
|
||||
removeAttribute(name) { if (name === 'href') this._href = undefined; },
|
||||
},
|
||||
_widget: { dataset: { protocols: protocolsAttr } },
|
||||
_error: { classList: new FakeClassList(), textContent: '' },
|
||||
};
|
||||
return {
|
||||
elements,
|
||||
getElementById: (id) => elements[Object.keys(elements).find(k => id === `field${k}`)] || null,
|
||||
};
|
||||
};
|
||||
|
||||
function runOnInput(value, protocolsAttr) {
|
||||
const { elements, getElementById } = mockDoc(value, protocolsAttr);
|
||||
const savedDocument = global.document;
|
||||
const savedWindow = global.window;
|
||||
let registered = null;
|
||||
global.document = { createElement: () => new FakeEl(), getElementById };
|
||||
global.window = {
|
||||
LEDMatrixWidgets: {
|
||||
register: (name, obj) => { registered = obj; },
|
||||
get: () => registered,
|
||||
getHandlers: () => registered.handlers,
|
||||
},
|
||||
};
|
||||
try {
|
||||
const src = fs.readFileSync(path.join(ROOT, 'static/v3/js/widgets/url-input.js'), 'utf8');
|
||||
// eslint-disable-next-line no-eval
|
||||
eval(src);
|
||||
registered.handlers.onInput('field');
|
||||
} finally {
|
||||
global.document = savedDocument;
|
||||
global.window = savedWindow;
|
||||
}
|
||||
return elements;
|
||||
}
|
||||
|
||||
let els = runOnInput('javascript:alert(1)', 'http,https');
|
||||
ok('javascript: never reaches previewLink.href', els._preview_link.href === undefined, els._preview_link.href);
|
||||
ok('javascript: leaves the preview hidden', els._preview.classList.contains('hidden'));
|
||||
|
||||
els = runOnInput('https://example.com', 'http,https');
|
||||
ok('an ordinary https URL reaches previewLink.href', els._preview_link.href === 'https://example.com', els._preview_link.href);
|
||||
ok('an ordinary https URL unhides the preview', !els._preview.classList.contains('hidden'));
|
||||
|
||||
els = runOnInput('data:text/html,<script>alert(1)</script>', 'http,https,data');
|
||||
ok('data: never reaches previewLink.href even when the schema allows it',
|
||||
els._preview_link.href === undefined, els._preview_link.href);
|
||||
|
||||
els = runOnInput('not a url', 'http,https');
|
||||
ok('an unparseable value never reaches previewLink.href', els._preview_link.href === undefined, els._preview_link.href);
|
||||
}
|
||||
|
||||
// ── plugin-file-manager: cell edits travel via data-*, not inline handlers ──
|
||||
// A JSON key/day from an uploaded file used to be spliced, HTML-escaped,
|
||||
// into an oninput="...('${escHtml(col)}'...)" attribute. escHtml neutralises
|
||||
// a quote for an ordinary attribute, but here the value also has to survive
|
||||
// as a *JS string literal* -- the browser HTML-decodes the attribute before
|
||||
// running it as script, which turns the escaped quote back into a real one
|
||||
// and lets a column named `x');alert(1);//` break out of the string and run
|
||||
// arbitrary JS. Cell edits now reach _pfmCellEdit only via data-day/data-col
|
||||
// read by one delegated listener, so this pins that no inline handler string
|
||||
// is built from the value at all.
|
||||
console.log("\n7. plugin-file-manager: cell edits never go through an inline handler string");
|
||||
{
|
||||
const src = fs.readFileSync(path.join(ROOT, 'static/v3/js/widgets/plugin-file-manager.js'), 'utf8');
|
||||
|
||||
function extractFn(opener) {
|
||||
const start = src.indexOf(opener);
|
||||
if (start < 0) { console.error(`FAIL: cannot find ${JSON.stringify(opener)}`); process.exit(1); }
|
||||
let i = src.indexOf('{', start), depth = 0;
|
||||
for (let j = i; j < src.length; j++) {
|
||||
if (src[j] === '{') depth++;
|
||||
else if (src[j] === '}') { depth--; if (depth === 0) return src.slice(start, j + 1); }
|
||||
}
|
||||
console.error(`FAIL: unbalanced braces after ${JSON.stringify(opener)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const escHtmlFn = loadFn('static/v3/js/widgets/plugin-file-manager.js', 'function escHtml(s) {', 'escHtml', false);
|
||||
const renderEntryTableSrc = extractFn('function renderEntryTable(fieldId, container, content) {');
|
||||
|
||||
const calls = [];
|
||||
const fakeWindow = { _pfmCellEdit: (fieldId, day, col, value) => calls.push({ fieldId, day, col, value }) };
|
||||
|
||||
class FakeContainer {
|
||||
constructor() { this._html = ''; this._listeners = {}; }
|
||||
set innerHTML(v) { this._html = v; }
|
||||
get innerHTML() { return this._html; }
|
||||
set textContent(v) { this._html = v; }
|
||||
addEventListener(type, fn) { this._listeners[type] = fn; }
|
||||
dispatch(type, target) { this._listeners[type]({ target }); }
|
||||
}
|
||||
|
||||
function fakeCell(day, col, value) {
|
||||
return {
|
||||
closest: (sel) => (sel.includes('data-day') ? { dataset: { day: String(day), col: String(col) }, value } : null),
|
||||
};
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-eval
|
||||
const renderEntryTable = eval(`(function(getState, escHtml, safeSetHTML, window){
|
||||
${renderEntryTableSrc}
|
||||
return renderEntryTable;
|
||||
})`)(
|
||||
() => ({ entriesPerPage: 20, _tablePage: 1 }),
|
||||
escHtmlFn,
|
||||
(target, html) => { target.innerHTML = html; },
|
||||
fakeWindow
|
||||
);
|
||||
|
||||
const maliciousCol = "x');alert(1);//";
|
||||
const container = new FakeContainer();
|
||||
renderEntryTable('field1', container, { '1': { [maliciousCol]: 'hello' } });
|
||||
|
||||
ok('no inline oninput handler is emitted for a cell', !/oninput=/.test(container.innerHTML), container.innerHTML);
|
||||
ok('the malicious column name never appears unescaped in the markup',
|
||||
!container.innerHTML.includes(maliciousCol), container.innerHTML);
|
||||
|
||||
container.dispatch('input', fakeCell('1', maliciousCol, 'typed value'));
|
||||
ok('the delegated listener still reaches _pfmCellEdit with the real day/col',
|
||||
calls.length === 1 && calls[0].day === '1' && calls[0].col === maliciousCol && calls[0].value === 'typed value',
|
||||
calls);
|
||||
}
|
||||
|
||||
console.log(`\n${pass} passed, ${fail} failed\n`);
|
||||
process.exit(fail ? 1 : 0);
|
||||
@@ -0,0 +1,123 @@
|
||||
"""pages_v3 must refuse an id that is not a plain name, not truncate it.
|
||||
|
||||
Both partial loaders used to run the id through ``os.path.basename`` and carry
|
||||
on with what came out, so "../weather" rendered the config form for "weather".
|
||||
Nothing escaped the plugins directory -- the containment guards held -- but the
|
||||
handler answered a request nobody made, and validating one string while the
|
||||
filesystem sees another is the shape both live traversals in this branch had.
|
||||
|
||||
These tests are about that: a rejected id gets a 400, and a real one still
|
||||
renders.
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
|
||||
BACKSLASH = chr(92)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pages(tmp_path):
|
||||
"""pages_v3 with a plugins directory holding one real plugin."""
|
||||
from web_interface.blueprints import pages_v3 as module
|
||||
|
||||
plugins_dir = tmp_path / "plugin-repos"
|
||||
(plugins_dir / "weather" / "web_ui").mkdir(parents=True)
|
||||
(plugins_dir / "weather" / "config_schema.json").write_text(
|
||||
'{"type": "object", "properties": {"enabled": {"type": "boolean"}}}',
|
||||
encoding="utf-8",
|
||||
)
|
||||
(plugins_dir / "weather" / "manifest.json").write_text(
|
||||
'{"name": "Weather", "version": "1.0.0"}', encoding="utf-8"
|
||||
)
|
||||
(plugins_dir / "weather" / "web_ui" / "panel.html").write_text(
|
||||
"<p>panel</p>", encoding="utf-8"
|
||||
)
|
||||
|
||||
original_pm = getattr(module.pages_v3, "plugin_manager", None)
|
||||
original_cm = getattr(module.pages_v3, "config_manager", None)
|
||||
|
||||
plugin_manager = MagicMock()
|
||||
plugin_manager.plugins_dir = plugins_dir
|
||||
plugin_manager.get_plugin_info.return_value = {"name": "Weather", "version": "1.0.0"}
|
||||
plugin_manager.get_plugin.return_value = None
|
||||
module.pages_v3.plugin_manager = plugin_manager
|
||||
module.pages_v3.config_manager = MagicMock(load_config=lambda: {})
|
||||
|
||||
yield module, plugins_dir
|
||||
|
||||
module.pages_v3.plugin_manager = original_pm
|
||||
module.pages_v3.config_manager = original_cm
|
||||
|
||||
|
||||
@pytest.mark.parametrize("plugin_id", [
|
||||
"../weather", "..", ".", "", None, "a/b", "x" + BACKSLASH + "y",
|
||||
])
|
||||
def test_a_plugin_id_that_is_not_a_plain_name_is_a_400(pages, plugin_id):
|
||||
module, _ = pages
|
||||
body, status = module._load_plugin_config_partial(plugin_id)
|
||||
assert status == 400
|
||||
assert "Invalid plugin ID" in body
|
||||
|
||||
|
||||
def test_a_traversing_id_no_longer_renders_the_truncated_one(pages):
|
||||
""""../weather" used to render "weather"'s form. It must not."""
|
||||
module, _ = pages
|
||||
body, status = module._load_plugin_config_partial("../weather")
|
||||
assert status == 400
|
||||
assert "Weather" not in body
|
||||
|
||||
|
||||
@pytest.mark.parametrize("app_id", ["../demo", "..", "a/b", "", None])
|
||||
def test_a_starlark_app_id_that_is_not_a_plain_name_is_a_400(pages, app_id):
|
||||
module, _ = pages
|
||||
body, status = module._load_starlark_config_partial(app_id)
|
||||
assert status == 400
|
||||
assert "Invalid app ID" in body
|
||||
|
||||
|
||||
class TestServePluginWebUi:
|
||||
"""GET /plugin-ui/<plugin_id>/web-ui/<path:filename>"""
|
||||
|
||||
@pytest.fixture
|
||||
def client(self, pages):
|
||||
from flask import Flask
|
||||
|
||||
module, _ = pages
|
||||
base = Path(module.__file__).resolve().parent.parent
|
||||
app = Flask(
|
||||
__name__,
|
||||
template_folder=str(base / "templates"),
|
||||
static_folder=str(base / "static"),
|
||||
)
|
||||
app.config["TESTING"] = True
|
||||
app.register_blueprint(module.pages_v3, url_prefix="")
|
||||
return app.test_client()
|
||||
|
||||
def test_a_real_fragment_is_still_wrapped_and_served(self, client):
|
||||
response = client.get("/plugin-ui/weather/web-ui/panel.html")
|
||||
assert response.status_code == 200
|
||||
body = response.get_data(as_text=True)
|
||||
assert "<p>panel</p>" in body
|
||||
assert 'window.PLUGIN_ID = "weather"' in body
|
||||
|
||||
@pytest.mark.parametrize("url", [
|
||||
"/plugin-ui/../web-ui/panel.html",
|
||||
"/plugin-ui/%2e%2e/web-ui/panel.html",
|
||||
"/plugin-ui/weather/web-ui/../../manifest.json",
|
||||
"/plugin-ui/weather/web-ui/..%2f..%2fmanifest.json",
|
||||
])
|
||||
def test_traversal_attempts_are_refused(self, client, url):
|
||||
response = client.get(url)
|
||||
assert response.status_code in (400, 403, 404)
|
||||
assert "version" not in response.get_data(as_text=True)
|
||||
|
||||
def test_a_non_html_filename_is_still_refused(self, client):
|
||||
# The allowlist predates this change and must survive it.
|
||||
response = client.get("/plugin-ui/weather/web-ui/manifest.json")
|
||||
assert response.status_code == 400
|
||||
@@ -0,0 +1,317 @@
|
||||
"""Request-supplied names must not be able to name a file outside their base.
|
||||
|
||||
Three of these were live. Each test that stands in for one says so, and
|
||||
asserts on the *filesystem* -- that the file outside the base is still there,
|
||||
or was never read -- rather than only on the status code, because a handler
|
||||
that returns 403 and deletes the file anyway would pass the weaker check.
|
||||
|
||||
The rest pin the shared helper in src/common/path_safety.py that the handlers
|
||||
now go through, so a future handler gets the same behaviour by using it.
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
|
||||
from src.common.path_safety import ( # noqa: E402
|
||||
resolve_under,
|
||||
safe_path_component,
|
||||
safe_relative_parts,
|
||||
)
|
||||
from test._api_v3_test_helpers import api_v3_client, api_v3_module # noqa: F401,E402
|
||||
|
||||
BACKSLASH = chr(92)
|
||||
|
||||
|
||||
class TestSafePathComponent:
|
||||
"""One segment, or nothing."""
|
||||
|
||||
@pytest.mark.parametrize("value", [
|
||||
"plugin", "ledmatrix-of-the-day", "weather_data", "manifest.json",
|
||||
"a.b.c", "UPPER", "with-dash", "with_underscore", "9lives",
|
||||
])
|
||||
def test_ordinary_names_pass_through_unchanged(self, value):
|
||||
assert safe_path_component(value) == value
|
||||
|
||||
@pytest.mark.parametrize("value", [
|
||||
"..", ".", "", "../etc", "a/b", "/abs", "etc/passwd",
|
||||
"a" + BACKSLASH + "b", "C:" + BACKSLASH + "x", "C:",
|
||||
"a\x00b", None, 123, b"bytes", ["list"],
|
||||
])
|
||||
def test_anything_that_could_name_another_directory_is_refused(self, value):
|
||||
assert safe_path_component(value) is None
|
||||
|
||||
def test_it_returns_the_value_rather_than_a_verdict(self):
|
||||
# A boolean lets a caller validate one string and then open a
|
||||
# different one. Returning the checked value is what stops that.
|
||||
assert safe_path_component("ok") == "ok"
|
||||
assert safe_path_component("../ok") is None
|
||||
|
||||
|
||||
class TestSafeRelativeParts:
|
||||
def test_a_multi_segment_path_splits(self):
|
||||
assert safe_relative_parts("web_ui/index.html") == ["web_ui", "index.html"]
|
||||
|
||||
def test_empty_segments_are_dropped_not_rejected(self):
|
||||
assert safe_relative_parts("a//b") == ["a", "b"]
|
||||
assert safe_relative_parts("x/") == ["x"]
|
||||
|
||||
@pytest.mark.parametrize("value", [
|
||||
"../x", "a/../../etc", "/etc/passwd", BACKSLASH + "etc",
|
||||
"a" + BACKSLASH + ".." + BACKSLASH + "b", "", None,
|
||||
])
|
||||
def test_traversal_and_absolute_paths_are_refused(self, value):
|
||||
assert safe_relative_parts(value) is None
|
||||
|
||||
|
||||
class TestResolveUnder:
|
||||
def test_a_path_inside_the_base_resolves(self, tmp_path):
|
||||
(tmp_path / "sub").mkdir()
|
||||
(tmp_path / "sub" / "f.txt").write_text("x", encoding="utf-8")
|
||||
resolved = resolve_under(tmp_path, "sub", "f.txt")
|
||||
assert resolved == (tmp_path / "sub" / "f.txt").resolve()
|
||||
|
||||
def test_a_path_that_would_escape_is_refused(self, tmp_path):
|
||||
assert resolve_under(tmp_path, "..") is None
|
||||
assert resolve_under(tmp_path, "..", "etc") is None
|
||||
assert resolve_under(tmp_path, "/etc/passwd") is None
|
||||
|
||||
def test_a_sibling_sharing_a_prefix_is_refused(self, tmp_path):
|
||||
# The bug the old `str(x).startswith(str(base))` checks had:
|
||||
# "<root>/foo-evil" starts with "<root>/foo" as a string, but is not
|
||||
# inside it as a directory.
|
||||
(tmp_path / "foo").mkdir()
|
||||
(tmp_path / "foo-evil").mkdir()
|
||||
(tmp_path / "foo-evil" / "secret").write_text("s", encoding="utf-8")
|
||||
assert resolve_under(tmp_path / "foo", "..", "foo-evil", "secret") is None
|
||||
# And the string check it replaces would have said yes:
|
||||
naive = (tmp_path / "foo" / ".." / "foo-evil" / "secret").resolve()
|
||||
assert str(naive).startswith(str((tmp_path / "foo").resolve()))
|
||||
|
||||
def test_it_returns_none_rather_than_raising_on_junk(self, tmp_path):
|
||||
assert resolve_under(tmp_path, None) is None
|
||||
assert resolve_under(tmp_path, 42) is None
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def plugins_tree(tmp_path):
|
||||
"""A plugins directory with one plugin, plus a secret outside it."""
|
||||
plugins = tmp_path / "plugin-repos"
|
||||
(plugins / "demo" / "web_ui").mkdir(parents=True)
|
||||
(plugins / "demo" / "web_ui" / "index.html").write_text("<p>hi</p>", encoding="utf-8")
|
||||
(plugins / "demo-evil").mkdir()
|
||||
(plugins / "demo-evil" / "stolen.json").write_text('{"a":1}', encoding="utf-8")
|
||||
secrets = tmp_path / "config"
|
||||
secrets.mkdir()
|
||||
(secrets / "config_secrets.json").write_text('{"api_key":"hunter2"}', encoding="utf-8")
|
||||
return tmp_path
|
||||
|
||||
|
||||
class TestServePluginStatic:
|
||||
"""GET /api/v3/plugins/<plugin_id>/static/<path:file_path>
|
||||
|
||||
This handler read any file whose resolved path *string-prefixed* the
|
||||
plugin directory. Two ways through:
|
||||
|
||||
* plugin_id of "..", because Flask's default converter forbids a slash
|
||||
but not dots, and get_plugin_directory returned the parent of the
|
||||
plugins directory since it exists. Every file under the project then
|
||||
prefixed that directory, config/config_secrets.json included.
|
||||
* a sibling directory sharing a prefix, per the helper test above.
|
||||
"""
|
||||
|
||||
def _wire(self, api_v3_module, plugins_tree):
|
||||
plugins = plugins_tree / "plugin-repos"
|
||||
|
||||
def get_plugin_directory(plugin_id):
|
||||
candidate = plugins / plugin_id
|
||||
return str(candidate) if candidate.exists() else None
|
||||
|
||||
api_v3_module.api_v3.plugin_manager = MagicMock()
|
||||
api_v3_module.api_v3.plugin_manager.get_plugin_directory = get_plugin_directory
|
||||
return plugins
|
||||
|
||||
def test_a_real_plugin_file_is_still_served(
|
||||
self, api_v3_client, api_v3_module, plugins_tree
|
||||
):
|
||||
self._wire(api_v3_module, plugins_tree)
|
||||
response = api_v3_client.get("/api/v3/plugins/demo/static/web_ui/index.html")
|
||||
assert response.status_code == 200
|
||||
assert b"<p>hi</p>" in response.data
|
||||
|
||||
def test_a_dotdot_plugin_id_cannot_reach_the_secrets_file(
|
||||
self, api_v3_client, api_v3_module, plugins_tree
|
||||
):
|
||||
self._wire(api_v3_module, plugins_tree)
|
||||
response = api_v3_client.get(
|
||||
"/api/v3/plugins/../static/config/config_secrets.json"
|
||||
)
|
||||
assert response.status_code in (400, 403, 404)
|
||||
assert b"hunter2" not in response.data
|
||||
|
||||
def test_a_percent_encoded_dotdot_plugin_id_is_refused_too(
|
||||
self, api_v3_client, api_v3_module, plugins_tree
|
||||
):
|
||||
self._wire(api_v3_module, plugins_tree)
|
||||
response = api_v3_client.get(
|
||||
"/api/v3/plugins/%2e%2e/static/config/config_secrets.json"
|
||||
)
|
||||
assert response.status_code in (400, 403, 404)
|
||||
assert b"hunter2" not in response.data
|
||||
|
||||
def test_a_sibling_directory_sharing_a_prefix_is_refused(
|
||||
self, api_v3_client, api_v3_module, plugins_tree
|
||||
):
|
||||
self._wire(api_v3_module, plugins_tree)
|
||||
response = api_v3_client.get(
|
||||
"/api/v3/plugins/demo/static/../demo-evil/stolen.json"
|
||||
)
|
||||
assert response.status_code in (400, 403, 404)
|
||||
assert b'"a"' not in response.data
|
||||
|
||||
def test_an_unknown_plugin_is_still_a_404(
|
||||
self, api_v3_client, api_v3_module, plugins_tree
|
||||
):
|
||||
self._wire(api_v3_module, plugins_tree)
|
||||
response = api_v3_client.get("/api/v3/plugins/nope/static/x.json")
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
class TestDeleteOfTheDayJson:
|
||||
"""POST /api/v3/plugins/of-the-day/json/delete
|
||||
|
||||
file_id came from the request body and was interpolated into
|
||||
``f"{file_id}.json"`` and then unlinked, with no validation at all. A
|
||||
file_id of "../../../../etc/something" deleted that file. This is the one
|
||||
finding in the batch that destroyed data rather than exposing it.
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def plugin_tree(self, tmp_path, api_v3_module):
|
||||
plugin_dir = tmp_path / "plugin-repos" / "ledmatrix-of-the-day"
|
||||
(plugin_dir / "of_the_day").mkdir(parents=True)
|
||||
(plugin_dir / "of_the_day" / "quotes.json").write_text("{}", encoding="utf-8")
|
||||
outside = tmp_path / "victim.json"
|
||||
outside.write_text("important", encoding="utf-8")
|
||||
|
||||
api_v3_module.api_v3.plugin_manager = MagicMock()
|
||||
api_v3_module.api_v3.plugin_manager.get_plugin_directory.return_value = str(plugin_dir)
|
||||
return plugin_dir, outside
|
||||
|
||||
URL = "/api/v3/plugins/of-the-day/json/delete"
|
||||
|
||||
def test_a_real_file_in_the_plugin_is_still_deleted(
|
||||
self, api_v3_client, plugin_tree
|
||||
):
|
||||
plugin_dir, _ = plugin_tree
|
||||
target = plugin_dir / "of_the_day" / "quotes.json"
|
||||
response = api_v3_client.post(self.URL, json={"file_id": "quotes"})
|
||||
assert response.status_code == 200
|
||||
assert not target.exists()
|
||||
|
||||
def test_a_traversing_file_id_deletes_nothing(self, api_v3_client, plugin_tree):
|
||||
_, outside = plugin_tree
|
||||
response = api_v3_client.post(
|
||||
self.URL, json={"file_id": "../../../victim"}
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert outside.exists(), "file outside the plugin directory was deleted"
|
||||
assert outside.read_text(encoding="utf-8") == "important"
|
||||
|
||||
@pytest.mark.parametrize("file_id", ["..", "a/b", "/etc/x", "x" + BACKSLASH + "y"])
|
||||
def test_other_shapes_of_traversal_are_refused(
|
||||
self, api_v3_client, plugin_tree, file_id
|
||||
):
|
||||
_, outside = plugin_tree
|
||||
response = api_v3_client.post(self.URL, json={"file_id": file_id})
|
||||
assert response.status_code == 400
|
||||
assert outside.exists()
|
||||
|
||||
|
||||
class TestDiskCacheKeys:
|
||||
"""The cache key becomes a filename, and POST /api/v3/cache/delete passes
|
||||
the request body's key straight through CacheManager.clear_cache to
|
||||
os.remove. A key of "../../../../etc/whatever" named a file well outside
|
||||
the cache directory.
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def cache(self, tmp_path):
|
||||
from src.cache.disk_cache import DiskCache
|
||||
|
||||
cache_dir = tmp_path / "cache"
|
||||
cache_dir.mkdir()
|
||||
return DiskCache(str(cache_dir)), cache_dir
|
||||
|
||||
def test_an_ordinary_key_still_round_trips(self, cache):
|
||||
disk_cache, cache_dir = cache
|
||||
disk_cache.set("espn_nfl_2024", {"ok": True})
|
||||
assert (cache_dir / "espn_nfl_2024.json").exists()
|
||||
assert disk_cache.get("espn_nfl_2024", max_age=None)["ok"] is True
|
||||
|
||||
def test_a_traversing_key_has_no_path(self, cache):
|
||||
disk_cache, _ = cache
|
||||
assert disk_cache.get_cache_path("../../victim") is None
|
||||
assert disk_cache.get_cache_path("..") is None
|
||||
assert disk_cache.get_cache_path("a/b") is None
|
||||
|
||||
def test_clearing_a_traversing_key_deletes_nothing(self, cache, tmp_path):
|
||||
disk_cache, _ = cache
|
||||
victim = tmp_path / "victim.json"
|
||||
victim.write_text("important", encoding="utf-8")
|
||||
disk_cache.clear("../victim")
|
||||
assert victim.exists(), "file outside the cache directory was deleted"
|
||||
|
||||
def test_writing_a_traversing_key_creates_nothing(self, cache, tmp_path):
|
||||
disk_cache, _ = cache
|
||||
disk_cache.set("../escaped", {"x": 1})
|
||||
assert not (tmp_path / "escaped.json").exists()
|
||||
|
||||
def test_the_delete_endpoint_says_no_rather_than_claiming_success(
|
||||
self, api_v3_client, api_v3_module
|
||||
):
|
||||
api_v3_module.api_v3.cache_manager = MagicMock()
|
||||
response = api_v3_client.post(
|
||||
"/api/v3/cache/delete", json={"key": "../../etc/passwd"}
|
||||
)
|
||||
assert response.status_code == 400
|
||||
api_v3_module.api_v3.cache_manager.clear_cache.assert_not_called()
|
||||
|
||||
def test_the_delete_endpoint_still_deletes_an_ordinary_key(
|
||||
self, api_v3_client, api_v3_module
|
||||
):
|
||||
api_v3_module.api_v3.cache_manager = MagicMock()
|
||||
response = api_v3_client.post(
|
||||
"/api/v3/cache/delete", json={"key": "espn_nfl_2024"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
api_v3_module.api_v3.cache_manager.clear_cache.assert_called_once_with(
|
||||
"espn_nfl_2024"
|
||||
)
|
||||
|
||||
|
||||
class TestPluginVersionLookup:
|
||||
"""_get_plugin_version joins a request-supplied id onto the plugins
|
||||
directory and opens manifest.json under it."""
|
||||
|
||||
def test_a_real_manifest_is_read(self, tmp_path):
|
||||
from web_interface.blueprints import api_v3 as module
|
||||
|
||||
plugins = tmp_path / "plugin-repos"
|
||||
(plugins / "demo").mkdir(parents=True)
|
||||
(plugins / "demo" / "manifest.json").write_text(
|
||||
json.dumps({"version": "1.2.3"}), encoding="utf-8"
|
||||
)
|
||||
original = getattr(module.api_v3, "plugin_store_manager", None)
|
||||
module.api_v3.plugin_store_manager = MagicMock(plugins_dir=str(plugins))
|
||||
try:
|
||||
assert module._get_plugin_version("demo") == "1.2.3"
|
||||
assert module._get_plugin_version("../demo") == ""
|
||||
assert module._get_plugin_version("..") == ""
|
||||
finally:
|
||||
module.api_v3.plugin_store_manager = original
|
||||
@@ -127,6 +127,31 @@ class TestConfigAPI:
|
||||
assert response.status_code == 200
|
||||
mock_config_manager.save_config_atomic.assert_called_once()
|
||||
|
||||
def test_save_main_config_fails_closed_when_schema_path_is_unresolvable(
|
||||
self, client, mock_config_manager, mock_plugin_manager
|
||||
):
|
||||
"""A plugin id whose schema path fails safe-resolution must not have
|
||||
its config saved with secret_fields left empty.
|
||||
|
||||
Regression test for the CodeQL/CodeRabbit finding on
|
||||
web_interface/blueprints/api_v3/config.py: previously, when
|
||||
resolve_under() returned None (e.g. a plugin directory reached via a
|
||||
symlink), the code fell through to `secret_fields = set()` and saved
|
||||
the plugin's submitted config -- credentials included -- as
|
||||
ordinary, unencrypted configuration instead of refusing the request.
|
||||
"""
|
||||
mock_plugin_manager.plugin_manifests = {'evil': {}}
|
||||
|
||||
with patch('web_interface.blueprints.api_v3.config.resolve_under', return_value=None):
|
||||
response = client.post(
|
||||
'/api/v3/config/main',
|
||||
data=json.dumps({'evil': {'api_key': 'super-secret'}}),
|
||||
content_type='application/json'
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
mock_config_manager.save_config_atomic.assert_not_called()
|
||||
|
||||
def test_save_main_config_validation_error(self, client, mock_config_manager):
|
||||
"""Test saving config with validation error."""
|
||||
invalid_config = {'invalid': 'data'}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
"""The SSID and password reaching nmcli's argv come from an HTTP request body.
|
||||
|
||||
POST /api/v3/wifi/connect takes both verbatim and WiFiManager.connect_to_network
|
||||
hands them to::
|
||||
|
||||
subprocess.run(["nmcli", "device", "wifi", "connect", ssid, "password", password])
|
||||
|
||||
There is no shell in that, so no metacharacter can start a second command --
|
||||
CodeQL's py/command-line-injection alert overstates it on that point. What is
|
||||
real is argument injection: nmcli reads a leading "-" as an option, so an SSID
|
||||
of "--ask" or "-t" asks nmcli to *run differently* rather than to join a
|
||||
network. Neither value was checked for shape at all before reaching argv.
|
||||
|
||||
These tests pin the validation without touching real networking: the
|
||||
validators are classmethods, so nothing here constructs a WiFiManager.
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
|
||||
from src.wifi_manager import WiFiManager # noqa: E402
|
||||
from test._api_v3_test_helpers import api_v3_client, api_v3_module # noqa: F401,E402
|
||||
|
||||
|
||||
class TestSsidValidation:
|
||||
@pytest.mark.parametrize("ssid", [
|
||||
"HomeNet", "my wifi 5G", "Cafe-Guest", "café", "x" * 32, "-not-leading".lstrip("-"),
|
||||
])
|
||||
def test_ordinary_ssids_pass_through(self, ssid):
|
||||
value, error = WiFiManager._validate_ssid(ssid)
|
||||
assert error is None
|
||||
assert value == ssid
|
||||
|
||||
def test_surrounding_whitespace_is_trimmed_not_rejected(self):
|
||||
value, error = WiFiManager._validate_ssid(" HomeNet ")
|
||||
assert error is None
|
||||
assert value == "HomeNet"
|
||||
|
||||
@pytest.mark.parametrize("ssid", ["--ask", "-t", "-"])
|
||||
def test_an_ssid_nmcli_would_read_as_an_option_is_refused(self, ssid):
|
||||
value, error = WiFiManager._validate_ssid(ssid)
|
||||
assert error is not None
|
||||
assert value == ""
|
||||
|
||||
def test_an_ssid_over_32_octets_is_refused(self):
|
||||
# 802.11 caps the SSID element at 32 octets, so a longer one could
|
||||
# never name a real network.
|
||||
_, error = WiFiManager._validate_ssid("x" * 33)
|
||||
assert error is not None
|
||||
# Multi-byte characters count as octets, not characters.
|
||||
_, error = WiFiManager._validate_ssid("é" * 17)
|
||||
assert error is not None
|
||||
|
||||
@pytest.mark.parametrize("ssid", ["a\nb", "a\rb", "a\x00b", "a\x7fb", "a\tb"])
|
||||
def test_control_characters_are_refused(self, ssid):
|
||||
_, error = WiFiManager._validate_ssid(ssid)
|
||||
assert error is not None
|
||||
|
||||
@pytest.mark.parametrize("ssid", ["", " ", None, 42, ["HomeNet"]])
|
||||
def test_empty_and_non_text_values_are_refused(self, ssid):
|
||||
_, error = WiFiManager._validate_ssid(ssid)
|
||||
assert error is not None
|
||||
|
||||
|
||||
class TestPasswordValidation:
|
||||
def test_an_empty_password_means_an_open_network(self):
|
||||
value, error = WiFiManager._validate_wifi_password("")
|
||||
assert error is None
|
||||
assert value == ""
|
||||
value, error = WiFiManager._validate_wifi_password(None)
|
||||
assert error is None
|
||||
assert value == ""
|
||||
|
||||
@pytest.mark.parametrize("password", ["hunter22", "a" * 63, "0" * 64, "AbCdEf0123" * 6 + "abcd"])
|
||||
def test_valid_psk_lengths_pass_through(self, password):
|
||||
value, error = WiFiManager._validate_wifi_password(password)
|
||||
assert error is None, f"{password!r} rejected: {error}"
|
||||
assert value == password
|
||||
|
||||
@pytest.mark.parametrize("password", ["short", "z" * 64, "a" * 200])
|
||||
def test_lengths_that_could_never_authenticate_are_refused(self, password):
|
||||
# 8-63 chars for a passphrase, or exactly 64 hex chars for a raw key.
|
||||
# "z" * 64 is the right length for a key but is not hex, so it is
|
||||
# neither -- note "a" * 64 *is* valid hex and must stay accepted.
|
||||
_, error = WiFiManager._validate_wifi_password(password)
|
||||
assert error is not None
|
||||
|
||||
@pytest.mark.parametrize("password", ["-password", "--ask"])
|
||||
def test_a_password_nmcli_would_read_as_an_option_is_refused(self, password):
|
||||
_, error = WiFiManager._validate_wifi_password(password)
|
||||
assert error is not None
|
||||
|
||||
def test_control_characters_are_refused(self):
|
||||
_, error = WiFiManager._validate_wifi_password("pass\nword")
|
||||
assert error is not None
|
||||
|
||||
@pytest.mark.parametrize("password", ["pässword", "你好12345678"])
|
||||
def test_non_ascii_passphrases_are_refused(self, password):
|
||||
# NetworkManager accepts only printable ASCII WPA-PSK passphrases (or
|
||||
# a 64-char hex key); a non-ASCII value would otherwise reach
|
||||
# _connect_nmcli and be saved/attempted before nmcli itself rejects it.
|
||||
_, error = WiFiManager._validate_wifi_password(password)
|
||||
assert error is not None
|
||||
|
||||
|
||||
class TestConnectRefusesBeforeRunningNmcli:
|
||||
"""connect_to_network must not reach subprocess with a rejected value."""
|
||||
|
||||
@pytest.mark.parametrize("ssid,password", [
|
||||
("--ask", "hunter22"),
|
||||
("x" * 40, "hunter22"),
|
||||
("Home\nNet", "hunter22"),
|
||||
("HomeNet", "-secret1"),
|
||||
("HomeNet", "short"),
|
||||
])
|
||||
def test_no_subprocess_runs_for_a_rejected_request(self, ssid, password):
|
||||
manager = WiFiManager.__new__(WiFiManager) # no __init__: no real host access
|
||||
with patch("src.wifi_manager.subprocess.run") as run:
|
||||
ok, message = manager.connect_to_network(ssid, password)
|
||||
assert ok is False
|
||||
assert message
|
||||
run.assert_not_called()
|
||||
|
||||
|
||||
class TestConnectEndpointSurfacesTheRefusal:
|
||||
URL = "/api/v3/wifi/connect"
|
||||
|
||||
@pytest.fixture
|
||||
def wifi_manager(self):
|
||||
with patch("src.wifi_manager.WiFiManager") as cls:
|
||||
instance = MagicMock()
|
||||
cls.return_value = instance
|
||||
yield instance
|
||||
|
||||
def test_a_rejected_ssid_comes_back_as_a_client_error(
|
||||
self, api_v3_client, wifi_manager
|
||||
):
|
||||
# The route delegates the shape check to the manager, so mirror what
|
||||
# the real one now returns rather than asserting on a mock's default.
|
||||
wifi_manager.connect_to_network.return_value = (False, "SSID cannot start with '-'")
|
||||
response = api_v3_client.post(self.URL, json={"ssid": "--ask", "password": "hunter22"})
|
||||
assert response.status_code == 400
|
||||
assert "-" in response.get_json()["message"]
|
||||
|
||||
def test_an_ordinary_request_is_unaffected(self, api_v3_client, wifi_manager):
|
||||
wifi_manager.connect_to_network.return_value = (True, "Connected to HomeNet")
|
||||
response = api_v3_client.post(self.URL, json={"ssid": "HomeNet", "password": "hunter22"})
|
||||
assert response.status_code == 200
|
||||
wifi_manager.connect_to_network.assert_called_once_with("HomeNet", "hunter22")
|
||||
+47
-44
@@ -17,6 +17,9 @@ sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
|
||||
from src.config_manager import ConfigManager
|
||||
from src.web_interface.error_handler import describe_exception
|
||||
from src.common.path_safety import (
|
||||
resolve_under, safe_path_component, safe_relative_parts,
|
||||
)
|
||||
from werkzeug.exceptions import HTTPException
|
||||
from src.exceptions import ConfigError
|
||||
from src.plugin_system.plugin_manager import PluginManager
|
||||
@@ -206,66 +209,66 @@ app.register_blueprint(api_v3, url_prefix='/api/v3')
|
||||
# Route to serve plugin asset files (registered on main app, not blueprint, for /assets/... path)
|
||||
@app.route('/assets/plugins/<plugin_id>/uploads/<path:filename>', methods=['GET'])
|
||||
def serve_plugin_asset(plugin_id, filename):
|
||||
"""Serve uploaded asset files from assets/plugins/{plugin_id}/uploads/"""
|
||||
"""Serve uploaded asset files from assets/plugins/{plugin_id}/uploads/
|
||||
|
||||
Both URL parts are validated before any path is built. The containment
|
||||
check here used to compare the *asset directory* against the project root
|
||||
rather than against assets/plugins, so a plugin_id of ``..`` moved the
|
||||
served directory a level up and still passed.
|
||||
"""
|
||||
try:
|
||||
# Build the asset directory path
|
||||
assets_dir = project_root / 'assets' / 'plugins' / plugin_id / 'uploads'
|
||||
assets_dir = assets_dir.resolve()
|
||||
|
||||
uploads_base = (project_root / 'assets' / 'plugins').resolve()
|
||||
|
||||
safe_plugin_id = safe_path_component(plugin_id)
|
||||
if not safe_plugin_id:
|
||||
return jsonify({'status': 'error', 'message': 'Invalid asset path'}), 403
|
||||
|
||||
safe_parts = safe_relative_parts(filename)
|
||||
if not safe_parts:
|
||||
return jsonify({'status': 'error', 'message': 'Invalid file path'}), 403
|
||||
|
||||
assets_dir = resolve_under(uploads_base, safe_plugin_id, 'uploads')
|
||||
if assets_dir is None:
|
||||
return jsonify({'status': 'error', 'message': 'Invalid asset path'}), 403
|
||||
|
||||
# Security check: ensure the assets directory exists and is within project_root
|
||||
if not assets_dir.exists() or not assets_dir.is_dir():
|
||||
return jsonify({'status': 'error', 'message': 'Asset directory not found'}), 404
|
||||
|
||||
# Ensure we're serving from within the assets directory (prevent directory traversal)
|
||||
# Use proper path resolution instead of string prefix matching to prevent bypasses
|
||||
assets_dir_resolved = assets_dir.resolve()
|
||||
project_root_resolved = project_root.resolve()
|
||||
|
||||
# Check that assets_dir is actually within project_root using commonpath
|
||||
try:
|
||||
common_path = os.path.commonpath([str(assets_dir_resolved), str(project_root_resolved)])
|
||||
if common_path != str(project_root_resolved):
|
||||
return jsonify({'status': 'error', 'message': 'Invalid asset path'}), 403
|
||||
except ValueError:
|
||||
# commonpath raises ValueError if paths are on different drives (Windows)
|
||||
return jsonify({'status': 'error', 'message': 'Invalid asset path'}), 403
|
||||
|
||||
# Resolve the requested file path
|
||||
requested_file = (assets_dir / filename).resolve()
|
||||
|
||||
# Security check: ensure file is within the assets directory using proper path comparison
|
||||
# Use commonpath to ensure assets_dir is a true parent of requested_file
|
||||
try:
|
||||
common_path = os.path.commonpath([str(requested_file), str(assets_dir_resolved)])
|
||||
if common_path != str(assets_dir_resolved):
|
||||
return jsonify({'status': 'error', 'message': 'Invalid file path'}), 403
|
||||
except ValueError:
|
||||
# commonpath raises ValueError if paths are on different drives (Windows)
|
||||
|
||||
# Resolve the requested file path. resolve_under repeats the
|
||||
# containment check after resolving, which is what catches a symlink
|
||||
# inside the uploads directory pointing out of it.
|
||||
requested_file = resolve_under(assets_dir, *safe_parts)
|
||||
if requested_file is None:
|
||||
return jsonify({'status': 'error', 'message': 'Invalid file path'}), 403
|
||||
|
||||
|
||||
# Check if file exists
|
||||
if not requested_file.exists() or not requested_file.is_file():
|
||||
return jsonify({'status': 'error', 'message': 'File not found'}), 404
|
||||
|
||||
|
||||
# Determine content type based on file extension
|
||||
lowered = requested_file.name.lower()
|
||||
content_type = 'application/octet-stream'
|
||||
if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
|
||||
content_type = 'image/jpeg' if filename.lower().endswith(('.jpg', '.jpeg')) else 'image/png'
|
||||
elif filename.lower().endswith('.gif'):
|
||||
if lowered.endswith(('.png', '.jpg', '.jpeg')):
|
||||
content_type = 'image/jpeg' if lowered.endswith(('.jpg', '.jpeg')) else 'image/png'
|
||||
elif lowered.endswith('.gif'):
|
||||
content_type = 'image/gif'
|
||||
elif filename.lower().endswith('.bmp'):
|
||||
elif lowered.endswith('.bmp'):
|
||||
content_type = 'image/bmp'
|
||||
elif filename.lower().endswith('.webp'):
|
||||
elif lowered.endswith('.webp'):
|
||||
content_type = 'image/webp'
|
||||
elif filename.lower().endswith('.svg'):
|
||||
elif lowered.endswith('.svg'):
|
||||
content_type = 'image/svg+xml'
|
||||
elif filename.lower().endswith('.json'):
|
||||
elif lowered.endswith('.json'):
|
||||
content_type = 'application/json'
|
||||
elif filename.lower().endswith('.txt'):
|
||||
elif lowered.endswith('.txt'):
|
||||
content_type = 'text/plain'
|
||||
|
||||
# Use send_from_directory to serve the file
|
||||
return send_from_directory(str(assets_dir), filename, mimetype=content_type)
|
||||
|
||||
# Use send_from_directory to serve the file. The path handed over is
|
||||
# the validated one, rebuilt from the components that were checked.
|
||||
return send_from_directory(
|
||||
str(assets_dir), '/'.join(safe_parts), mimetype=content_type
|
||||
)
|
||||
|
||||
except Exception:
|
||||
app.logger.exception('Error serving plugin asset file')
|
||||
|
||||
@@ -48,6 +48,7 @@ from src.web_interface.validators import (
|
||||
)
|
||||
from src.error_aggregator import get_error_aggregator
|
||||
from src.common.permission_utils import install_requirements_file
|
||||
from src.common.path_safety import resolve_under
|
||||
_SUDO = shutil.which('sudo')
|
||||
_JOURNALCTL = shutil.which('journalctl')
|
||||
_GIT = shutil.which('git')
|
||||
@@ -124,9 +125,17 @@ def _get_plugin_version(plugin_id: str) -> str:
|
||||
"""Read the installed version from a plugin's manifest.json.
|
||||
|
||||
Returns the version string on success, or '' if the manifest
|
||||
cannot be read (missing, corrupt, permission denied, etc.).
|
||||
cannot be read (missing, corrupt, permission denied, etc.) or if
|
||||
``plugin_id`` is not a plain directory name. Several callers pass an id
|
||||
that arrived in a request body, so the name is validated here rather
|
||||
than relying on each of them to have done it.
|
||||
"""
|
||||
manifest_path = Path(api_v3.plugin_store_manager.plugins_dir) / plugin_id / "manifest.json"
|
||||
manifest_path = resolve_under(
|
||||
api_v3.plugin_store_manager.plugins_dir, plugin_id, "manifest.json"
|
||||
)
|
||||
if manifest_path is None:
|
||||
logger.warning("[PluginVersion] Rejected unsafe plugin id %r", plugin_id)
|
||||
return ''
|
||||
try:
|
||||
with open(manifest_path, 'r', encoding='utf-8') as f:
|
||||
manifest = json.load(f)
|
||||
|
||||
@@ -11,6 +11,7 @@ from web_interface.blueprints.api_v3 import (
|
||||
remove_empty_secrets, request, separate_secrets, strip_masked_values,
|
||||
success_response,
|
||||
)
|
||||
from src.common.path_safety import resolve_under
|
||||
import web_interface.blueprints.api_v3 as _pkg
|
||||
# Read through the module rather than bound by value: tests patch these
|
||||
# as module attributes, and a value binding would not see the patch.
|
||||
@@ -934,7 +935,19 @@ def save_main_config():
|
||||
plugins_dir = Path(plugins_dir_name)
|
||||
else:
|
||||
plugins_dir = PROJECT_ROOT / plugins_dir_name
|
||||
schema_path = plugins_dir / plugin_id / 'config_schema.json'
|
||||
# plugin_id is already known to be a loaded plugin (the
|
||||
# membership test above), so this cannot currently traverse --
|
||||
# but the path is built from a request key, and the guard and
|
||||
# the join are far enough apart that a later edit could
|
||||
# separate them. Build it through the shared helper instead.
|
||||
schema_path = resolve_under(plugins_dir, plugin_id, 'config_schema.json')
|
||||
|
||||
if schema_path is None:
|
||||
return error_response(
|
||||
ErrorCode.VALIDATION_ERROR,
|
||||
f"Invalid plugin id '{plugin_id}'",
|
||||
status_code=400
|
||||
)
|
||||
|
||||
if schema_path.exists():
|
||||
try:
|
||||
|
||||
@@ -13,6 +13,7 @@ from web_interface.blueprints.api_v3 import (
|
||||
error_response, get_error_aggregator, json, jsonify, logger, os, request,
|
||||
subprocess, success_response, tempfile,
|
||||
)
|
||||
from src.common.path_safety import safe_path_component
|
||||
import web_interface.blueprints.api_v3 as _pkg
|
||||
# Read through the module rather than bound by value: tests patch these
|
||||
# as module attributes, and a value binding would not see the patch.
|
||||
@@ -300,6 +301,12 @@ def delete_cache_file():
|
||||
|
||||
cache_key = data['key']
|
||||
|
||||
# The key names the file about to be removed. DiskCache refuses an
|
||||
# unusable key on its own, but silently: say so here instead of
|
||||
# reporting a deletion that never happened.
|
||||
if safe_path_component(cache_key) is None:
|
||||
return jsonify({'status': 'error', 'message': 'Invalid cache key'}), 400
|
||||
|
||||
# Delete the cache file
|
||||
api_v3.cache_manager.clear_cache(cache_key)
|
||||
|
||||
|
||||
@@ -18,6 +18,9 @@ from web_interface.blueprints.api_v3 import (
|
||||
separate_secrets, shutil, stat, subprocess, success_response, sys,
|
||||
tempfile, uuid, validate_request_json,
|
||||
)
|
||||
from src.common.path_safety import (
|
||||
resolve_under, safe_path_component, safe_relative_parts,
|
||||
)
|
||||
import web_interface.blueprints.api_v3 as _pkg
|
||||
# Read through the module rather than bound by value: tests patch these
|
||||
# as module attributes, and a value binding would not see the patch.
|
||||
@@ -946,12 +949,29 @@ def update_plugin():
|
||||
status_code=500
|
||||
)
|
||||
|
||||
plugin_id = data['plugin_id']
|
||||
# The id names a directory this handler reads a manifest out of and
|
||||
# hands to the store manager to run git in. It comes from the request
|
||||
# body, so it is validated before anything is joined to a path, and
|
||||
# the validated value -- not the raw one -- is what gets used below.
|
||||
plugin_id = safe_path_component(data['plugin_id'])
|
||||
if not plugin_id:
|
||||
return error_response(
|
||||
ErrorCode.INVALID_INPUT,
|
||||
'Invalid plugin_id',
|
||||
status_code=400
|
||||
)
|
||||
|
||||
# Always do direct updates (they're fast git pull operations)
|
||||
# Operation queue is reserved for longer operations like install/uninstall
|
||||
plugin_dir = Path(api_v3.plugin_store_manager.plugins_dir) / plugin_id
|
||||
manifest_path = plugin_dir / "manifest.json"
|
||||
plugins_base = Path(api_v3.plugin_store_manager.plugins_dir)
|
||||
plugin_dir = plugins_base / plugin_id
|
||||
manifest_path = resolve_under(plugin_dir, "manifest.json")
|
||||
if manifest_path is None:
|
||||
return error_response(
|
||||
ErrorCode.INVALID_INPUT,
|
||||
'Invalid plugin_id',
|
||||
status_code=400
|
||||
)
|
||||
|
||||
current_last_updated = None
|
||||
current_commit = None
|
||||
@@ -983,7 +1003,9 @@ def update_plugin():
|
||||
current_branch = git_info_before.get('branch')
|
||||
|
||||
# Check if plugin is a git repo first (for better error messages)
|
||||
plugin_path_dir = Path(api_v3.plugin_store_manager.plugins_dir) / plugin_id
|
||||
# plugin_id is validated above; reuse the same directory rather
|
||||
# than rebuilding it from a value that might not match.
|
||||
plugin_path_dir = plugin_dir
|
||||
is_git_repo = False
|
||||
if plugin_path_dir.exists():
|
||||
git_info = api_v3.plugin_store_manager._get_local_git_info(plugin_path_dir)
|
||||
@@ -1069,7 +1091,7 @@ def update_plugin():
|
||||
message=message
|
||||
)
|
||||
else:
|
||||
plugin_path_dir = Path(api_v3.plugin_store_manager.plugins_dir) / plugin_id
|
||||
plugin_path_dir = plugin_dir
|
||||
if not plugin_path_dir.exists():
|
||||
client_msg = 'Plugin update failed: plugin not found'
|
||||
else:
|
||||
@@ -3525,6 +3547,14 @@ def delete_of_the_day_json():
|
||||
if not file_id:
|
||||
return jsonify({'status': 'error', 'message': 'file_id is required'}), 400
|
||||
|
||||
# file_id names a file that is about to be unlinked, and it arrives
|
||||
# straight from the request body. Unvalidated, a file_id of
|
||||
# "../../../../etc/cron" made this endpoint delete any .json file on
|
||||
# the device the service could write to.
|
||||
safe_file_id = safe_path_component(file_id)
|
||||
if not safe_file_id:
|
||||
return jsonify({'status': 'error', 'message': 'Invalid file_id'}), 400
|
||||
|
||||
# Get plugin directory
|
||||
plugin_id = 'ledmatrix-of-the-day'
|
||||
if api_v3.plugin_manager:
|
||||
@@ -3535,9 +3565,10 @@ def delete_of_the_day_json():
|
||||
if not plugin_dir or not Path(plugin_dir).exists():
|
||||
return jsonify({'status': 'error', 'message': 'Plugin not found'}), 404
|
||||
|
||||
data_dir = Path(plugin_dir) / 'of_the_day'
|
||||
filename = f"{file_id}.json"
|
||||
file_path = data_dir / filename
|
||||
filename = f"{safe_file_id}.json"
|
||||
file_path = resolve_under(Path(plugin_dir) / 'of_the_day', filename)
|
||||
if file_path is None:
|
||||
return jsonify({'status': 'error', 'message': 'Invalid file_id'}), 400
|
||||
|
||||
if not file_path.exists():
|
||||
return jsonify({'status': 'error', 'message': f'File {filename} not found'}), 404
|
||||
@@ -3549,7 +3580,7 @@ def delete_of_the_day_json():
|
||||
try:
|
||||
sys.path.insert(0, str(plugin_dir))
|
||||
from scripts.update_config import remove_category_from_config
|
||||
remove_category_from_config(file_id)
|
||||
remove_category_from_config(safe_file_id)
|
||||
except Exception as e:
|
||||
logger.warning("Could not update config: %s", e)
|
||||
|
||||
@@ -3563,23 +3594,44 @@ def delete_of_the_day_json():
|
||||
return jsonify({'status': 'error', 'message': 'An error occurred; see logs for details', 'details': describe_exception(e)}), 500
|
||||
@api_v3.route('/plugins/<plugin_id>/static/<path:file_path>', methods=['GET'])
|
||||
def serve_plugin_static(plugin_id, file_path):
|
||||
"""Serve static files from plugin directory"""
|
||||
"""Serve static files from plugin directory.
|
||||
|
||||
Both URL parts are validated before anything is opened. This handler used
|
||||
to read whatever the path resolved to as long as ``str(file).startswith``
|
||||
the plugin directory, which let two different things through:
|
||||
|
||||
* ``plugin_id`` of ``..`` -- Flask's default converter forbids a slash but
|
||||
not dots, and ``get_plugin_directory('..')`` happily returned the parent
|
||||
of the plugins directory because it exists. Every file under the project
|
||||
root then "started with" that directory, ``config/config_secrets.json``
|
||||
included.
|
||||
* a sibling directory sharing a prefix: with the plugin directory
|
||||
``plugin-repos/foo``, ``../foo-evil/x`` resolves to
|
||||
``plugin-repos/foo-evil/x``, whose string does start with
|
||||
``plugin-repos/foo``.
|
||||
"""
|
||||
try:
|
||||
safe_plugin_id = safe_path_component(plugin_id)
|
||||
if not safe_plugin_id:
|
||||
return jsonify({'status': 'error', 'message': 'Invalid plugin ID'}), 400
|
||||
|
||||
safe_parts = safe_relative_parts(file_path)
|
||||
if not safe_parts:
|
||||
return jsonify({'status': 'error', 'message': 'Invalid file path'}), 400
|
||||
|
||||
# Get plugin directory
|
||||
if api_v3.plugin_manager:
|
||||
plugin_dir = api_v3.plugin_manager.get_plugin_directory(plugin_id)
|
||||
plugin_dir = api_v3.plugin_manager.get_plugin_directory(safe_plugin_id)
|
||||
else:
|
||||
plugin_dir = PROJECT_ROOT / 'plugins' / plugin_id
|
||||
plugin_dir = PROJECT_ROOT / 'plugins' / safe_plugin_id
|
||||
|
||||
if not plugin_dir or not Path(plugin_dir).exists():
|
||||
return jsonify({'status': 'error', 'message': 'Plugin not found'}), 404
|
||||
|
||||
# Resolve file path (prevent directory traversal)
|
||||
plugin_dir = Path(plugin_dir).resolve()
|
||||
requested_file = (plugin_dir / file_path).resolve()
|
||||
|
||||
# Security check: ensure file is within plugin directory
|
||||
if not str(requested_file).startswith(str(plugin_dir)):
|
||||
# Containment is still checked after resolving: name validation cannot
|
||||
# see a symlink inside the plugin directory that points out of it.
|
||||
requested_file = resolve_under(plugin_dir, *safe_parts)
|
||||
if requested_file is None:
|
||||
return jsonify({'status': 'error', 'message': 'Invalid file path'}), 403
|
||||
|
||||
# Check if file exists
|
||||
@@ -3588,13 +3640,14 @@ def serve_plugin_static(plugin_id, file_path):
|
||||
|
||||
# Determine content type
|
||||
content_type = 'text/plain'
|
||||
if file_path.endswith('.html'):
|
||||
name = requested_file.name
|
||||
if name.endswith('.html'):
|
||||
content_type = 'text/html'
|
||||
elif file_path.endswith('.js'):
|
||||
elif name.endswith('.js'):
|
||||
content_type = 'application/javascript'
|
||||
elif file_path.endswith('.css'):
|
||||
elif name.endswith('.css'):
|
||||
content_type = 'text/css'
|
||||
elif file_path.endswith('.json'):
|
||||
elif name.endswith('.json'):
|
||||
content_type = 'application/json'
|
||||
|
||||
# Read and return file
|
||||
|
||||
@@ -4,8 +4,6 @@ from markupsafe import escape
|
||||
from html.parser import HTMLParser
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import os.path
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
@@ -13,6 +11,7 @@ from pathlib import Path
|
||||
_SAFE_PLUGIN_ID_RE = re.compile(r'^[a-zA-Z0-9_-]{1,64}$')
|
||||
_SAFE_WEB_UI_FILE_RE = re.compile(r'^[a-zA-Z0-9_-]{1,64}\.html$')
|
||||
from src.web_interface.secret_helpers import mask_secret_fields
|
||||
from src.common.path_safety import resolve_under, safe_path_component
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -271,7 +270,15 @@ def serve_plugin_web_ui(plugin_id, filename):
|
||||
"""Serve a plugin's web_ui/ HTML fragment as a standalone page.
|
||||
|
||||
Wraps the fragment with a minimal HTML page that injects window.PLUGIN_ID
|
||||
and loads Tailwind CSS so the fragment runs correctly in a sandboxed iframe.
|
||||
and loads Tailwind CSS so the fragment runs correctly inside the iframe
|
||||
that plugin_config.html embeds it in.
|
||||
|
||||
That iframe carries no ``sandbox`` attribute, so the fragment runs with
|
||||
the interface's own origin. That is deliberate rather than an oversight:
|
||||
the fragment is a file from an installed plugin, and an installed plugin
|
||||
already runs Python on the device. The trust boundary is plugin install,
|
||||
not this route. It is worth knowing when reading the code, which is why
|
||||
it says so here instead of claiming a sandbox that is not there.
|
||||
"""
|
||||
# Validate URL-derived values against strict allowlists before any path or
|
||||
# script operations.
|
||||
@@ -280,11 +287,12 @@ def serve_plugin_web_ui(plugin_id, filename):
|
||||
if not _SAFE_WEB_UI_FILE_RE.match(filename):
|
||||
return 'Invalid filename', 400, {'Content-Type': 'text/plain'}
|
||||
|
||||
# os.path.basename() is the CodeQL-recognised path sanitizer used throughout
|
||||
# this codebase (see plugin_loader.py). Applying it here breaks the taint
|
||||
# chain even though the allowlist above already prevents path separators.
|
||||
safe_id = os.path.basename(plugin_id)
|
||||
safe_fn = os.path.basename(filename)
|
||||
# The allowlists above already forbid a separator, but the value that gets
|
||||
# joined has to be the checked one, not the argument -- see
|
||||
# src/common/path_safety.py. safe_path_component rejects rather than
|
||||
# truncates, so these cannot disagree.
|
||||
safe_id = safe_path_component(plugin_id)
|
||||
safe_fn = safe_path_component(filename)
|
||||
if not safe_id or not safe_fn:
|
||||
return 'Invalid path component', 400, {'Content-Type': 'text/plain'}
|
||||
|
||||
@@ -294,22 +302,19 @@ def serve_plugin_web_ui(plugin_id, filename):
|
||||
try:
|
||||
_plugins_base = Path(pages_v3.plugin_manager.plugins_dir).resolve()
|
||||
|
||||
# Reconstruct from sanitised basename — CodeQL-approved pattern.
|
||||
_plugin_dir = (_plugins_base / safe_id).resolve()
|
||||
_plugin_dir.relative_to(_plugins_base) # containment guard
|
||||
_plugin_dir = resolve_under(_plugins_base, safe_id)
|
||||
if _plugin_dir is None:
|
||||
return 'Forbidden', 403, {'Content-Type': 'text/plain'}
|
||||
|
||||
# Mirror PluginManager's ledmatrix- prefix fallback.
|
||||
if not _plugin_dir.exists():
|
||||
_alt_id = os.path.basename(f'ledmatrix-{safe_id}')
|
||||
_alt = (_plugins_base / _alt_id).resolve()
|
||||
try:
|
||||
_alt.relative_to(_plugins_base)
|
||||
_alt = resolve_under(_plugins_base, f'ledmatrix-{safe_id}')
|
||||
if _alt is not None:
|
||||
_plugin_dir = _alt
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
web_ui_path = (_plugin_dir / 'web_ui' / safe_fn).resolve()
|
||||
web_ui_path.relative_to(_plugin_dir / 'web_ui') # second guard
|
||||
web_ui_path = resolve_under(_plugin_dir / 'web_ui', safe_fn)
|
||||
if web_ui_path is None:
|
||||
return 'Forbidden', 403, {'Content-Type': 'text/plain'}
|
||||
|
||||
if not web_ui_path.exists():
|
||||
return 'Not found', 404, {'Content-Type': 'text/plain'}
|
||||
@@ -640,9 +645,11 @@ def _load_plugin_config_partial(plugin_id):
|
||||
Load plugin configuration partial - server-side rendered form.
|
||||
This replaces the client-side generateConfigForm() JavaScript.
|
||||
"""
|
||||
# Sanitize with basename (CodeQL-recognized sanitizer) then regex-validate format
|
||||
plugin_id = os.path.basename(plugin_id or '')
|
||||
if not re.match(r'^[a-zA-Z0-9][a-zA-Z0-9._\-:]*$', plugin_id):
|
||||
# Refuse an id that is not a plain directory name, rather than quietly
|
||||
# basename-ing it down to one: "../weather" used to become "weather" and
|
||||
# render a partial the caller never asked for.
|
||||
plugin_id = safe_path_component(plugin_id)
|
||||
if not plugin_id or not re.match(r'^[a-zA-Z0-9][a-zA-Z0-9._\-:]*$', plugin_id):
|
||||
return '<div class="text-red-500 p-4">Invalid plugin ID</div>', 400
|
||||
|
||||
try:
|
||||
@@ -655,10 +662,8 @@ def _load_plugin_config_partial(plugin_id):
|
||||
|
||||
# Resolve and validate all plugin paths against the plugins base directory
|
||||
_plugins_base = Path(pages_v3.plugin_manager.plugins_dir).resolve()
|
||||
_plugin_dir = (_plugins_base / plugin_id).resolve()
|
||||
try:
|
||||
_plugin_dir.relative_to(_plugins_base)
|
||||
except ValueError:
|
||||
_plugin_dir = resolve_under(_plugins_base, plugin_id)
|
||||
if _plugin_dir is None:
|
||||
return '<div class="text-red-500 p-4">Invalid plugin ID</div>', 400
|
||||
|
||||
# Try to get plugin info first
|
||||
@@ -682,19 +687,17 @@ def _load_plugin_config_partial(plugin_id):
|
||||
config = full_config.get(plugin_id, {})
|
||||
|
||||
# Load uploaded images from metadata file if images field exists in schema
|
||||
schema_path_temp = _plugin_dir / "config_schema.json"
|
||||
if schema_path_temp.exists():
|
||||
schema_path_temp = resolve_under(_plugin_dir, "config_schema.json")
|
||||
if schema_path_temp is not None and schema_path_temp.exists():
|
||||
try:
|
||||
with open(schema_path_temp, 'r', encoding='utf-8') as f:
|
||||
temp_schema = json.load(f)
|
||||
if (temp_schema.get('properties', {}).get('images', {}).get('x-widget') == 'file-upload' or
|
||||
temp_schema.get('properties', {}).get('images', {}).get('x_widget') == 'file-upload'):
|
||||
_assets_base = (Path(__file__).parent.parent.parent / 'assets' / 'plugins').resolve()
|
||||
metadata_file = (_assets_base / plugin_id / 'uploads' / '.metadata.json').resolve()
|
||||
try:
|
||||
metadata_file.relative_to(_assets_base)
|
||||
except ValueError:
|
||||
metadata_file = None
|
||||
metadata_file = resolve_under(
|
||||
_assets_base, plugin_id, 'uploads', '.metadata.json'
|
||||
)
|
||||
if metadata_file and metadata_file.exists():
|
||||
try:
|
||||
with open(metadata_file, 'r', encoding='utf-8') as mf:
|
||||
@@ -714,8 +717,8 @@ def _load_plugin_config_partial(plugin_id):
|
||||
|
||||
# Get plugin schema
|
||||
schema = {}
|
||||
schema_path = _plugin_dir / "config_schema.json"
|
||||
if schema_path.exists():
|
||||
schema_path = resolve_under(_plugin_dir, "config_schema.json")
|
||||
if schema_path is not None and schema_path.exists():
|
||||
try:
|
||||
with open(schema_path, 'r', encoding='utf-8') as f:
|
||||
schema = json.load(f)
|
||||
@@ -724,8 +727,8 @@ def _load_plugin_config_partial(plugin_id):
|
||||
|
||||
# Get web UI actions from plugin manifest
|
||||
web_ui_actions = []
|
||||
manifest_path = _plugin_dir / "manifest.json"
|
||||
if manifest_path.exists():
|
||||
manifest_path = resolve_under(_plugin_dir, "manifest.json")
|
||||
if manifest_path is not None and manifest_path.exists():
|
||||
try:
|
||||
with open(manifest_path, 'r', encoding='utf-8') as f:
|
||||
manifest = json.load(f)
|
||||
@@ -773,9 +776,10 @@ def _load_plugin_config_partial(plugin_id):
|
||||
|
||||
def _load_starlark_config_partial(app_id):
|
||||
"""Load configuration partial for a Starlark app."""
|
||||
# Sanitize with basename (CodeQL-recognized sanitizer) then regex-validate format
|
||||
app_id = os.path.basename(app_id or '')
|
||||
if not re.match(r'^[a-zA-Z0-9][a-zA-Z0-9_\-]*$', app_id):
|
||||
# Refuse an id that is not a plain directory name rather than basename-ing
|
||||
# it down to one -- see _load_plugin_config_partial for why.
|
||||
app_id = safe_path_component(app_id)
|
||||
if not app_id or not re.match(r'^[a-zA-Z0-9][a-zA-Z0-9_\-]*$', app_id):
|
||||
return '<div class="text-red-500 p-4">Invalid app ID</div>', 400
|
||||
|
||||
try:
|
||||
@@ -814,11 +818,7 @@ def _load_starlark_config_partial(app_id):
|
||||
|
||||
# Load schema from schema.json if it exists — validate path stays within starlark_base
|
||||
schema = None
|
||||
schema_file = (starlark_base / app_id / 'schema.json').resolve()
|
||||
try:
|
||||
schema_file.relative_to(starlark_base)
|
||||
except ValueError:
|
||||
schema_file = None
|
||||
schema_file = resolve_under(starlark_base, app_id, 'schema.json')
|
||||
if schema_file and schema_file.exists():
|
||||
try:
|
||||
with open(schema_file, 'r') as f:
|
||||
@@ -828,11 +828,7 @@ def _load_starlark_config_partial(app_id):
|
||||
|
||||
# Load config from config.json if it exists — validate path stays within starlark_base
|
||||
config = {}
|
||||
config_file = (starlark_base / app_id / 'config.json').resolve()
|
||||
try:
|
||||
config_file.relative_to(starlark_base)
|
||||
except ValueError:
|
||||
config_file = None
|
||||
config_file = resolve_under(starlark_base, app_id, 'config.json')
|
||||
if config_file and config_file.exists():
|
||||
try:
|
||||
with open(config_file, 'r') as f:
|
||||
|
||||
@@ -602,9 +602,9 @@
|
||||
};
|
||||
// Build the <i class="..."> + label as DOM nodes so a
|
||||
// hostile plugin.icon (e.g. containing a quote) can't
|
||||
// break out of the attribute. escapeHtml only escapes
|
||||
// <, >, &, not ", so attribute-context interpolation
|
||||
// would be unsafe.
|
||||
// break out of the attribute. escapeHtml now escapes
|
||||
// quotes too, but setting the property directly cannot
|
||||
// be got wrong at all, so it stays.
|
||||
const iconEl = document.createElement('i');
|
||||
iconEl.className = plugin.icon || 'fas fa-puzzle-piece';
|
||||
const labelNode = document.createTextNode(plugin.name || plugin.id);
|
||||
@@ -643,10 +643,15 @@
|
||||
}
|
||||
},
|
||||
|
||||
// Quotes too, so the result is safe inside a quoted attribute
|
||||
// value -- the textContent/innerHTML round-trip alone only
|
||||
// escapes &, < and >.
|
||||
escapeHtml(text) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
return div.innerHTML
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
},
|
||||
|
||||
async refreshPlugins() {
|
||||
|
||||
@@ -260,6 +260,9 @@ function closeErrorModal() {
|
||||
|
||||
/**
|
||||
* Escape HTML to prevent XSS.
|
||||
*
|
||||
* Quotes are escaped as well so the result is safe inside a quoted attribute
|
||||
* value -- the textContent/innerHTML round-trip alone only escapes &, < and >.
|
||||
*/
|
||||
function escapeHtml(text) {
|
||||
if (typeof text !== 'string') {
|
||||
@@ -267,7 +270,9 @@ function escapeHtml(text) {
|
||||
}
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
return div.innerHTML
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -118,15 +118,27 @@
|
||||
/**
|
||||
* Escape HTML to prevent XSS
|
||||
* Always escapes the input, even for non-strings, by coercing to string first
|
||||
*
|
||||
* The result is safe in text content AND inside quoted attribute values.
|
||||
* The textContent/innerHTML round-trip only escapes `&`, `<` and `>` --
|
||||
* the HTML serializer leaves quotes alone because they are harmless in a
|
||||
* text node. Every widget here interpolates the result into attributes
|
||||
* (`value="${escapeHtml(v)}"`), where an unescaped `"` closes the
|
||||
* attribute and lets the value inject its own, so the quotes have to go
|
||||
* too. Each widget's standalone fallback already did this; the shared
|
||||
* implementation they all prefer did not.
|
||||
*
|
||||
* @param {*} text - Text to escape (will be coerced to string)
|
||||
* @returns {string} Escaped text
|
||||
* @returns {string} Escaped text, safe for text and attribute contexts
|
||||
*/
|
||||
escapeHtml(text) {
|
||||
// Always coerce to string first, then escape
|
||||
const textStr = String(text);
|
||||
const div = document.createElement('div');
|
||||
div.textContent = textStr;
|
||||
return div.innerHTML;
|
||||
return div.innerHTML
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -50,10 +50,14 @@
|
||||
}
|
||||
|
||||
// Escape HTML to prevent XSS (for HTML contexts)
|
||||
// Quotes too: the result lands in quoted attribute values below, and
|
||||
// the textContent/innerHTML round-trip only escapes &, < and >.
|
||||
const escapeHtml = (text) => {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
div.textContent = String(text ?? '');
|
||||
return div.innerHTML
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
};
|
||||
|
||||
// Use validated/sanitized hex for style attribute and input values
|
||||
|
||||
@@ -804,10 +804,14 @@
|
||||
const schedule = image.schedule || { enabled: false, mode: 'always', start_time: '08:00', end_time: '18:00', days: {} };
|
||||
|
||||
// Escape HTML helper
|
||||
// Quotes too: the result lands in quoted attribute values below, and the
|
||||
// textContent/innerHTML round-trip only escapes &, < and >.
|
||||
const escapeHtml = (text) => {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
div.textContent = String(text ?? '');
|
||||
return div.innerHTML
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
};
|
||||
|
||||
// Use sanitizedId for all ID references in the schedule HTML
|
||||
|
||||
@@ -738,10 +738,15 @@
|
||||
delete btn._jfmOrigText;
|
||||
}
|
||||
|
||||
// Quotes too: the result lands in quoted attribute values (title=,
|
||||
// data-cat=, pattern=, ...), and the textContent/innerHTML round-trip
|
||||
// only escapes &, < and >.
|
||||
_esc(str) {
|
||||
const d = document.createElement('div');
|
||||
d.textContent = String(str ?? '');
|
||||
return d.innerHTML;
|
||||
return d.innerHTML
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
_fmtSize(bytes) {
|
||||
|
||||
@@ -206,10 +206,15 @@
|
||||
else console.log(`[PFM][${type}] ${msg}`);
|
||||
}
|
||||
|
||||
// Quotes too: the result lands in quoted attribute values (id=, value=,
|
||||
// data-col=), and the textContent/innerHTML round-trip only escapes
|
||||
// &, < and >.
|
||||
function escHtml(s) {
|
||||
const d = document.createElement('div');
|
||||
d.textContent = String(s ?? '');
|
||||
return d.innerHTML;
|
||||
return d.innerHTML
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function formatSize(bytes) {
|
||||
@@ -383,7 +388,7 @@
|
||||
<button class="pfm-btn pfm-btn-primary" id="${escHtml(fieldId)}_save_btn">
|
||||
<i class="fas fa-save mr-1"></i>Save
|
||||
</button>
|
||||
</div>`;
|
||||
</div>`);
|
||||
overlay.appendChild(modal);
|
||||
// Bind events after DOM insertion — filename captured in closure, not in HTML.
|
||||
modal.querySelector(`#${CSS.escape(fieldId)}_modal_close`).addEventListener('click', () => window._pfmCloseModal(fieldId));
|
||||
@@ -411,7 +416,7 @@
|
||||
<textarea id="${escHtml(fieldId)}_json_ta" rows="20"
|
||||
style="width:100%;font-family:monospace;font-size:.75rem;border:1px solid #d1d5db;border-radius:.375rem;padding:.5rem;"
|
||||
>${escHtml(JSON.stringify(content, null, 2))}</textarea>
|
||||
<div id="${escHtml(fieldId)}_json_err" style="color:#dc2626;font-size:.75rem;margin-top:.25rem;"></div>`;
|
||||
<div id="${escHtml(fieldId)}_json_err" style="color:#dc2626;font-size:.75rem;margin-top:.25rem;"></div>`);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -431,6 +436,20 @@
|
||||
if (!entries.length) { container.textContent = 'No entries.'; return; }
|
||||
|
||||
const cols = Object.keys(entries[0][1]);
|
||||
|
||||
// Delegated listener: day/col reach _pfmCellEdit only through data-*
|
||||
// attributes, never through a JS string spliced into an inline
|
||||
// handler -- the browser HTML-decodes attribute values before
|
||||
// running them as script, which undoes escHtml's quote escaping and
|
||||
// reopens the exact injection it exists to close. `container` is a
|
||||
// fresh element per modal open (see _pfmOpenEdit), so this attaches
|
||||
// exactly once per table, even though buildPage() re-renders below.
|
||||
container.addEventListener('input', (e) => {
|
||||
const cell = e.target.closest('input[data-day], textarea[data-day]');
|
||||
if (!cell) return;
|
||||
window._pfmCellEdit(fieldId, cell.dataset.day, cell.dataset.col, cell.value);
|
||||
});
|
||||
|
||||
const MS_PER_DAY = 86400 * 1000; // eslint-disable-line no-magic-numbers -- 86400s/day is not magic
|
||||
const todayDoy = Math.ceil((new Date() - new Date(new Date().getFullYear(), 0, 0)) / MS_PER_DAY);
|
||||
const total = entries.length;
|
||||
@@ -459,18 +478,16 @@
|
||||
</thead>
|
||||
<tbody>
|
||||
${pageEntries.map(([day, val]) => `
|
||||
<tr data-day="${day}" class="${parseInt(day) === todayDoy ? 'today-row' : ''}">
|
||||
<tr data-day="${escHtml(day)}" class="${parseInt(day) === todayDoy ? 'today-row' : ''}">
|
||||
<td class="pfm-day-col" style="user-select:none;">${escHtml(day)}</td>
|
||||
${cols.map(col => {
|
||||
const v = val[col] ?? '';
|
||||
const isLong = String(v).length > 60 || col === 'description' || col === 'definition' || col === 'content';
|
||||
return isLong
|
||||
? `<td><textarea data-day="${day}" data-col="${escHtml(col)}" rows="2"
|
||||
oninput="window._pfmCellEdit('${fieldId}','${day}','${escHtml(col)}',this.value)"
|
||||
? `<td><textarea data-day="${escHtml(day)}" data-col="${escHtml(col)}" rows="2"
|
||||
>${escHtml(String(v))}</textarea></td>`
|
||||
: `<td><input type="text" data-day="${day}" data-col="${escHtml(col)}"
|
||||
value="${escHtml(String(v))}"
|
||||
oninput="window._pfmCellEdit('${fieldId}','${day}','${escHtml(col)}',this.value)"></td>`;
|
||||
: `<td><input type="text" data-day="${escHtml(day)}" data-col="${escHtml(col)}"
|
||||
value="${escHtml(String(v))}"></td>`;
|
||||
}).join('')}
|
||||
</tr>`).join('')}
|
||||
</tbody>
|
||||
@@ -489,7 +506,7 @@
|
||||
${page >= totalPages ? 'disabled' : ''}
|
||||
onclick="window._pfmTablePage('${fieldId}',${page + 1})">Next ›</button>
|
||||
</div>
|
||||
</div>`;
|
||||
</div>`);
|
||||
st._tablePage = page;
|
||||
st._tableEntries = entries;
|
||||
st._tableCols = cols;
|
||||
@@ -578,7 +595,7 @@
|
||||
<button class="pfm-btn pfm-btn-danger" id="${escHtml(fieldId)}_del_confirm">
|
||||
<i class="fas fa-trash mr-1"></i>Delete
|
||||
</button>
|
||||
</div>`;
|
||||
</div>`);
|
||||
overlay.appendChild(modal);
|
||||
modal.querySelector(`#${CSS.escape(fieldId)}_del_close`).addEventListener('click', () => window._pfmCloseModal(fieldId));
|
||||
modal.querySelector(`#${CSS.escape(fieldId)}_del_cancel`).addEventListener('click', () => window._pfmCloseModal(fieldId));
|
||||
@@ -631,7 +648,7 @@
|
||||
<i class="fas fa-plus mr-1"></i>Create
|
||||
</button>
|
||||
</div>
|
||||
</div>`;
|
||||
</div>`);
|
||||
overlay.appendChild(modal);
|
||||
modal.querySelector(`#${CSS.escape(fieldId)}_cre_close`).addEventListener('click', () => window._pfmCloseModal(fieldId));
|
||||
modal.querySelector(`#${CSS.escape(fieldId)}_cre_cancel`).addEventListener('click', () => window._pfmCloseModal(fieldId));
|
||||
@@ -784,7 +801,7 @@
|
||||
<div class="pfm-grid">
|
||||
<div class="pfm-empty"><i class="fas fa-spinner fa-spin"></i>Loading…</div>
|
||||
</div>
|
||||
</div>`;
|
||||
</div>`);
|
||||
|
||||
loadFiles(fieldId);
|
||||
},
|
||||
|
||||
@@ -54,9 +54,16 @@
|
||||
// RFC 3986 scheme pattern: starts with letter, then letters/digits/+/./-
|
||||
const RFC_SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*$/;
|
||||
|
||||
// Schemes that execute script when navigated to. These can never be
|
||||
// allowed, whatever a schema's allowedProtocols asks for: the validated
|
||||
// value is written straight into an <a href>, so allowing "javascript"
|
||||
// here would turn a config field into script execution.
|
||||
const SCRIPTABLE_SCHEMES = ['javascript', 'data', 'vbscript', 'blob', 'filesystem'];
|
||||
|
||||
/**
|
||||
* Normalize and validate protocol list against RFC 3986 scheme pattern.
|
||||
* Accepts schemes like "http", "https", "git+ssh", "android-app", etc.
|
||||
* Scriptable schemes are dropped -- see SCRIPTABLE_SCHEMES.
|
||||
* @param {Array|string} protocols - Protocol list (array or comma-separated string)
|
||||
* @returns {Array} Normalized lowercase protocols, defaults to ['http', 'https']
|
||||
*/
|
||||
@@ -70,15 +77,25 @@
|
||||
const normalized = list
|
||||
.map(p => String(p).trim())
|
||||
.filter(p => RFC_SCHEME_PATTERN.test(p))
|
||||
.map(p => p.toLowerCase());
|
||||
.map(p => p.toLowerCase())
|
||||
.filter(p => !SCRIPTABLE_SCHEMES.includes(p));
|
||||
return normalized.length > 0 ? normalized : ['http', 'https'];
|
||||
}
|
||||
|
||||
/**
|
||||
* True when `string` parses as a URL whose scheme is allowed AND is not
|
||||
* one that executes script. The scriptable check is repeated here rather
|
||||
* than trusted to normalizeProtocols so that a caller passing its own
|
||||
* protocol list cannot re-open the hole.
|
||||
*/
|
||||
function isValidUrl(string, allowedProtocols) {
|
||||
try {
|
||||
const url = new URL(string);
|
||||
const protocol = url.protocol.replace(':', '').toLowerCase();
|
||||
if (SCRIPTABLE_SCHEMES.includes(protocol)) {
|
||||
return false;
|
||||
}
|
||||
if (allowedProtocols && allowedProtocols.length > 0) {
|
||||
const protocol = url.protocol.replace(':', '').toLowerCase();
|
||||
return allowedProtocols.includes(protocol);
|
||||
}
|
||||
return true;
|
||||
@@ -87,6 +104,15 @@
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A value safe to use as an <a href>: the URL itself when it validates,
|
||||
* and '' otherwise. Keeps the "render an href for whatever is stored"
|
||||
* path from emitting a javascript: URL that was never validated.
|
||||
*/
|
||||
function safeHref(value, allowedProtocols) {
|
||||
return isValidUrl(value, allowedProtocols) ? value : '';
|
||||
}
|
||||
|
||||
window.LEDMatrixWidgets.register('url-input', {
|
||||
name: 'URL Input Widget',
|
||||
version: '1.0.0',
|
||||
@@ -139,7 +165,7 @@
|
||||
html += `
|
||||
<div id="${fieldId}_preview" class="mt-2 ${currentValue && isValidUrl(currentValue, allowedProtocols) ? '' : 'hidden'}">
|
||||
<a id="${fieldId}_preview_link"
|
||||
href="${escapeHtml(currentValue)}"
|
||||
href="${escapeHtml(safeHref(currentValue, allowedProtocols))}"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="text-sm text-blue-600 hover:text-blue-800 flex items-center">
|
||||
@@ -231,10 +257,23 @@
|
||||
const protocols = normalizeProtocols(widgetEl?.dataset.protocols);
|
||||
|
||||
if (previewEl && previewLink) {
|
||||
if (value && isValidUrl(value, protocols)) {
|
||||
// Scheme checked inline, right where the value reaches the DOM sink,
|
||||
// rather than through safeHref/isValidUrl -- CodeQL's DOM-based-XSS
|
||||
// sanitizer recognition does not trace a boolean-returning helper two
|
||||
// calls deep, so it kept flagging this assignment even though the
|
||||
// scriptable-scheme check (see SCRIPTABLE_SCHEMES) already covered it.
|
||||
let scheme = '';
|
||||
try {
|
||||
scheme = value ? new URL(value).protocol.replace(':', '').toLowerCase() : '';
|
||||
} catch (_) {
|
||||
scheme = '';
|
||||
}
|
||||
const schemeIsSafe = !!scheme && !SCRIPTABLE_SCHEMES.includes(scheme) && protocols.includes(scheme);
|
||||
if (schemeIsSafe) {
|
||||
previewLink.href = value;
|
||||
previewEl.classList.remove('hidden');
|
||||
} else {
|
||||
previewLink.removeAttribute('href');
|
||||
previewEl.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4370,12 +4370,15 @@ function renderCustomRegistryPlugins(plugins, registryUrl) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Escape HTML helper
|
||||
// Escape HTML helper. Quotes too: the result lands in quoted attribute
|
||||
// values, and the textContent/innerHTML round-trip only escapes &, < and >.
|
||||
const escapeHtml = (text) => {
|
||||
if (!text) return '';
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
return div.innerHTML
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
};
|
||||
|
||||
// Helper function to escape for JavaScript strings
|
||||
@@ -4471,11 +4474,15 @@ function isGithubUrl(url) {
|
||||
}
|
||||
}
|
||||
|
||||
// Utility function to escape HTML
|
||||
// Utility function to escape HTML. Quotes too: most call sites interpolate the
|
||||
// result into a quoted attribute value, and the textContent/innerHTML
|
||||
// round-trip only escapes &, < and >.
|
||||
function escapeHtml(text) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
return div.innerHTML
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
// Utility function to escape text for use in HTML attributes
|
||||
@@ -5623,11 +5630,15 @@ document.addEventListener('htmx:afterSettle', function() {
|
||||
let starlarkDataLoaded = false;
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────────
|
||||
// Quotes too: the result lands in quoted attribute values (data-app-id=,
|
||||
// title=), and the textContent/innerHTML round-trip only escapes &, < and >.
|
||||
function escapeHtml(str) {
|
||||
if (!str) return '';
|
||||
const div = document.createElement('div');
|
||||
div.textContent = str;
|
||||
return div.innerHTML;
|
||||
return div.innerHTML
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function isStarlarkInstalled(appId) {
|
||||
|
||||
@@ -152,7 +152,8 @@ function displayCacheFiles(data) {
|
||||
<span class="text-sm text-gray-600">${escapeHtml(modifiedStr)}</span>
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
|
||||
<button onclick="deleteCacheFile('${escapeHtml(cacheFile.key)}')"
|
||||
<button onclick="deleteCacheFile(this.dataset.cacheKey)"
|
||||
data-cache-key="${escapeHtml(cacheFile.key)}"
|
||||
class="text-red-600 hover:text-red-900 px-3 py-1 rounded hover:bg-red-50 transition-colors"
|
||||
title="Delete cache file">
|
||||
<i class="fas fa-trash mr-1"></i>Delete
|
||||
@@ -220,10 +221,14 @@ function showError(message) {
|
||||
}
|
||||
|
||||
// Utility function to escape HTML
|
||||
// Quotes too: the result is interpolated into quoted attribute values, and the
|
||||
// textContent/innerHTML round-trip only escapes &, < and >.
|
||||
function escapeHtml(text) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
return div.innerHTML
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
// Make deleteCacheFile available globally for onclick handlers
|
||||
|
||||
@@ -711,11 +711,15 @@ function showError(message) {
|
||||
}
|
||||
}
|
||||
|
||||
// Utility function to escape HTML
|
||||
// Utility function to escape HTML. Quotes too: the result is interpolated into
|
||||
// quoted attribute values (option value=, title=), and the
|
||||
// textContent/innerHTML round-trip only escapes &, < and >.
|
||||
function escapeHtml(text) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
return div.innerHTML
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function refreshCurrentPluginStatus() {
|
||||
|
||||
Reference in New Issue
Block a user