mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-10-04 14:25:08 +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:
+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")
|
||||
Reference in New Issue
Block a user