mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-10-04 14:25:08 +00:00
* feat(starlark,on-demand): the third-party fixes worth taking, plus an MQTT bridge Analysis of ant456/ledmatrix-fixes-repo, a third-party collection of patches and services built while running this project on Starlark apps under MQTT control. Its patches are whole-file copies taken against an older tree, so applying them as written would revert #523's frame pacing, #534's display() bool returns and the GitHub token masking in plugins_manager.js. Three of its claimed fixes are already in main, and its api_v3 Starlark routes are #535's. What follows is the rest -- verified against current code, and reimplemented where the patch's approach did not hold up. **On-demand display.** `pinned` reached the controller from the API, was stored on it and republished in the status payload, but never narrowed the rotation -- a pinned request still cycled every mode its plugin owns. Right for a sports plugin, whose modes are views of one subject; wrong for a plugin whose modes are unrelated, which is every Starlark app. Now honoured, and it survives a restart. Restarting while on-demand was active loaded *only* the on-demand plugin, so normal rotation had nothing to return to for the life of the process -- and a restart mid-session is routine, since that is how an update is applied. The panel came back cycling one plugin's modes with no way out but clearing the cache by hand. Every enabled plugin loads now; on-demand still resumes on its saved mode. Stop requests are exempt from the duplicate guards on purpose, so that a second click stops a mode a race left running -- which means consuming the mailbox is the only thing that ends one. It was never consumed, so the same stop was re-read and re-processed on every poll, forever. Both paths now share one compare-before-delete helper. **Starlark rendering.** `extract_schema` parsed the source with a regex, which can only see option lists written out literally: an app whose dropdown is filled from a live API call inside `get_schema()` came back empty, and the config form offered nothing to pick. Now runs `pixlet schema`, which executes the app, and falls back to the parser when Pixlet is absent, too old for the subcommand, or the app fails to run. The third-party patch replaced the parser outright and hardcoded /usr/local/bin/pixlet; this keeps the fallback and the binary search. A `|` in a config value was dropped by a shell-metacharacter filter, though the command is a list with no shell involved -- and apps do use it as a separator inside one value. The key went missing silently and the app rendered its own "not configured" screen with nothing to say why. And a 0-byte render was reported as success: Pixlet exits 0 and writes nothing when an app has no content, which read downstream as a working app drawing a black panel. **Starlark display.** `display()` ignored the mode it was called with, so a specific app could not be addressed. It now accepts `display_mode` -- which is the whole mechanism, since the controller inspects the signature before passing it. Found while there: `_select_next_app` ran only while `current_app` was unset, so with several apps installed the first was picked once and shown forever while the rest were rendered on schedule and never displayed. And `enable_scrolling` was missing, so multi-frame apps were called once per rotation slot and never advanced past frame one. **GET /api/v3/display/modes.** Every mode that can be requested on-demand, with the plugin that owns it. Nothing exposed this, so anything driving the display from outside the web UI read each plugin's manifest.json off disk and reimplemented PluginManager's fallbacks. It also triggers discovery, which is otherwise lazy and normally happens because a person opened the dashboard. **integrations/mqtt_bridge.** Home Assistant control over MQTT Discovery: a mode select, a stop button, power, brightness. Rewritten against the API rather than the filesystem, so it needs no read access to config.json and cannot drift from the web UI. paho-mqtt 2.x VERSION2, TLS, an availability topic that is also the last will, and secrets from the environment. **Two opt-in extras.** A DNS single-request unit, for glibc's parallel A/AAAA lookup stalling ~5s per name on routers that answer only the A query -- which makes any plugin calling an external API slow and Starlark apps, which have a render timeout, fail outright. And a Pixlet config editor: a script you run and Ctrl+C rather than the third-party version's always-on unauthenticated Flask service, since it stops the display for the length of a session. Neither is installed by default. Long Starlark app names now wrap instead of overflowing their card. 115 new tests across 5 files. Also unblocked test_starlark_display_contract.py, which was silently skipping wherever fcntl is absent. Whole suite: no new failures against main. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(mqtt_bridge): the five issues Codacy flagged on this branch All in the new bridge, all real: * requests floor was 2.31.0, which carries CVE-2024-35195, CVE-2024-47081 and CVE-2026-25645. Raised to >=2.33.0,<3.0.0, which is what the project's own requirements.txt already pins. * `import time` was never used. * `"mqtt_password": None` in DEFAULTS read as a hardcoded credential. It is the "no password configured" default; marked nosec B105, the convention used elsewhere in the repo. Also dropped an unused `build_app` from the display-modes test imports. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix: the review findings on this PR Nine of CodeRabbit's ten, plus the CodeQL alert. The tenth is wrong and is answered below. **One bad config section blanked the whole mode list.** `/display/modes` read `full_config.get(plugin_id, {}).get('enabled')`, so a non-dict under a plugin id -- a shape DisplayController already guards, so it happens -- raised AttributeError mid-loop and answered 500 with no modes at all. Every MQTT bridge entity is built from that list. Now skipped with a warning. **The DNS scripts reported success they had not earned.** Three separate paths: `resolvconf -u` failing was swallowed by `|| true`; the systemd-resolved branch exited 0 without applying anything, so the oneshot unit recorded success while the workaround was inactive; and the installer's `|| echo` turned a failed start into "installation complete." with exit 0. All three now fail loudly. `single-request` is a glibc resolv.conf option with no resolved.conf equivalent, so on those hosts the honest answer is that it cannot be applied. A NetworkManager-generated resolv.conf is regenerated on connection changes, not only at boot, and the unit is oneshot with RemainAfterExit -- so the option can vanish mid-boot with nothing to put it back. Now detected and stated plainly rather than implied to be permanent. **`Before=` does not order a manual restart.** It only orders units already in the same transaction, so `systemctl restart ledmatrix` could bypass the fix. install_dns_fix.sh now writes a ledmatrix.service drop-in with Wants= and After=. Wants=, not Requires=: a DNS workaround failing should not stop the display. **The Pixlet editor's `--lan` is gone.** `pixlet serve` has no authentication, and a printed warning is not access control. Loopback only, with the SSH port-forward in the header where the flag used to be documented -- SSH does the authenticating and nothing is left listening. **The MQTT example config now defaults to TLS** on 8883. The installer copies it verbatim, and without TLS the broker password and every command cross the network in cleartext. A plaintext broker is still supported and documented, and the bridge warns once at startup when a password is configured without TLS. **Not taken: "the upstream Pixlet CLI has no `schema` subcommand."** Upstream tidbyt/pixlet has none, but `scripts/download_pixlet.sh` installs `tronbyt/pixlet`, whose `cmd/schema.go` is `schema [PATH]` -> JSON on stdout, built on `runtime.NewAppletFromPath`, so it does execute `get_schema()`. That is exactly what extract_schema_via_pixlet calls. A binary without the subcommand exits non-zero and falls back to the source parser, which is already covered by a test. **CodeQL stack-trace exposure: not taken either.** I removed `details` first and that broke test_web_error_detail.py::test_no_api_v3_handler_discards_its_exception, which enforces `describe_exception` across all ~75 handlers -- written because a device with failing storage answered "see logs for details" from the log viewer itself. describe_exception redacts credentials; the trade-off is the project's and is already made. Restored, with the reasoning in a comment. 11 new tests. Whole suite: no new failures against main, 4127 passed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
211 lines
8.7 KiB
Python
211 lines
8.7 KiB
Python
"""starlark-apps PixletRenderer: what reaches Pixlet, and what counts as a render.
|
|
|
|
Three things a Starlark app can do that the renderer got wrong:
|
|
|
|
* put a "|" in a config value -- a shell metacharacter filter dropped the
|
|
whole key, though the command is a list and no shell is involved;
|
|
* render nothing -- Pixlet exits 0 and writes a 0-byte file, which was
|
|
reported as a successful render;
|
|
* compute its schema at runtime -- the source parser can only read option
|
|
lists that are written out literally, so a dropdown fed by a live API call
|
|
came back empty.
|
|
"""
|
|
|
|
import importlib.util
|
|
import json
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
from unittest.mock import patch
|
|
|
|
import pytest
|
|
|
|
PLUGIN_DIR = Path(__file__).resolve().parent.parent / "plugin-repos" / "starlark-apps"
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def renderer_module():
|
|
if not PLUGIN_DIR.exists():
|
|
pytest.skip("starlark-apps plugin is not checked out")
|
|
sys.path.insert(0, str(PLUGIN_DIR))
|
|
try:
|
|
spec = importlib.util.spec_from_file_location(
|
|
"pixlet_renderer_under_test", PLUGIN_DIR / "pixlet_renderer.py")
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
return module
|
|
except Exception as e: # noqa: BLE001 - optional deps may be absent
|
|
pytest.skip(f"pixlet_renderer is not importable here: {e}")
|
|
finally:
|
|
sys.path.remove(str(PLUGIN_DIR))
|
|
|
|
|
|
@pytest.fixture
|
|
def renderer(renderer_module):
|
|
"""A renderer with a known binary and __init__'s binary search bypassed."""
|
|
r = renderer_module.PixletRenderer.__new__(renderer_module.PixletRenderer)
|
|
r.timeout = 30
|
|
r.pixlet_binary = "/usr/local/bin/pixlet"
|
|
return r
|
|
|
|
|
|
def _completed(returncode=0, stdout="", stderr=""):
|
|
return subprocess.CompletedProcess(args=[], returncode=returncode,
|
|
stdout=stdout, stderr=stderr)
|
|
|
|
|
|
class TestConfigValuesReachPixlet:
|
|
"""cmd is a list and there is no shell=True, so nothing here is ever
|
|
interpreted by a shell -- the filter is defence in depth, not a boundary."""
|
|
|
|
def _args_for(self, renderer, tmp_path, config):
|
|
star = tmp_path / "app.star"
|
|
star.write_text("# app", encoding="utf-8")
|
|
out = tmp_path / "out.webp"
|
|
|
|
def fake_run(cmd, **kw):
|
|
out.write_bytes(b"webp-bytes")
|
|
fake_run.cmd = cmd
|
|
return _completed()
|
|
|
|
with patch.object(subprocess, "run", side_effect=fake_run):
|
|
renderer.render(str(tmp_path / "app.star"), str(out), config=config)
|
|
return fake_run.cmd
|
|
|
|
def test_a_pipe_in_a_value_is_passed_through(self, renderer, tmp_path):
|
|
"""Real apps use "|" as a separator inside one config value."""
|
|
args = self._args_for(renderer, tmp_path, {"sign_id": "I-476 North|175659"})
|
|
assert "sign_id=I-476 North|175659" in args
|
|
|
|
def test_a_dropped_value_does_not_take_the_key_with_it(self, renderer, tmp_path):
|
|
args = self._args_for(renderer, tmp_path, {"sign_id": "I-476 North|175659"})
|
|
assert any(a.startswith("sign_id=") for a in args)
|
|
|
|
@pytest.mark.parametrize("value", [
|
|
"$(rm -rf /)",
|
|
"`whoami`",
|
|
"a;b",
|
|
"a&b",
|
|
"a>b",
|
|
"a<b",
|
|
])
|
|
def test_actual_shell_metacharacters_are_still_dropped(self, renderer, tmp_path, value):
|
|
args = self._args_for(renderer, tmp_path, {"k": value})
|
|
assert not any(a.startswith("k=") for a in args)
|
|
|
|
def test_an_invalid_key_is_still_dropped(self, renderer, tmp_path):
|
|
args = self._args_for(renderer, tmp_path, {"bad key!": "x"})
|
|
assert not any("bad key!" in a for a in args)
|
|
|
|
|
|
class TestAnEmptyRenderIsNotASuccess:
|
|
"""Pixlet exits 0 and writes 0 bytes when an app renders no content."""
|
|
|
|
def _render(self, renderer, tmp_path, write_bytes):
|
|
star = tmp_path / "app.star"
|
|
star.write_text("# app", encoding="utf-8")
|
|
out = tmp_path / "out.webp"
|
|
|
|
def fake_run(cmd, **kw):
|
|
out.write_bytes(write_bytes)
|
|
return _completed()
|
|
|
|
with patch.object(subprocess, "run", side_effect=fake_run):
|
|
return renderer.render(str(tmp_path / "app.star"), str(out))
|
|
|
|
def test_a_zero_byte_output_is_reported_as_a_failure(self, renderer, tmp_path):
|
|
ok, error = self._render(renderer, tmp_path, b"")
|
|
assert ok is False
|
|
assert "empty" in (error or "").lower()
|
|
|
|
def test_a_real_output_still_succeeds(self, renderer, tmp_path):
|
|
ok, error = self._render(renderer, tmp_path, b"RIFF....WEBP")
|
|
assert (ok, error) == (True, None)
|
|
|
|
def test_a_missing_output_still_fails(self, renderer, tmp_path):
|
|
star = tmp_path / "app.star"
|
|
star.write_text("# app", encoding="utf-8")
|
|
out = tmp_path / "out.webp"
|
|
with patch.object(subprocess, "run", return_value=_completed()):
|
|
ok, error = renderer.render(str(tmp_path / "app.star"), str(out))
|
|
assert ok is False
|
|
assert "not found" in (error or "").lower()
|
|
|
|
|
|
class TestSchemaComesFromPixletWhenItCan:
|
|
"""`pixlet schema` runs get_schema(); the source parser only reads it.
|
|
|
|
An app whose dropdown options come from a live API call has no option list
|
|
anywhere in its source, so the parser reports an empty dropdown and the
|
|
config form offers nothing to choose.
|
|
"""
|
|
|
|
PIXLET_OUTPUT = json.dumps({
|
|
"version": "1",
|
|
"schema": [
|
|
{"id": "roadway", "name": "Roadway", "type": "dropdown",
|
|
"description": "Pick a road", "options": [{"display": "I-476", "value": "476"}]},
|
|
],
|
|
})
|
|
|
|
def test_the_pixlet_output_is_used(self, renderer, tmp_path):
|
|
star = tmp_path / "app.star"
|
|
star.write_text("# no schema literal anywhere\n", encoding="utf-8")
|
|
with patch.object(subprocess, "run",
|
|
return_value=_completed(stdout=self.PIXLET_OUTPUT)):
|
|
ok, schema, error = renderer.extract_schema(str(star))
|
|
assert ok is True and error is None
|
|
assert schema["schema"][0]["options"][0]["value"] == "476"
|
|
|
|
def test_pixlet_field_keys_are_remapped_for_the_config_form(self, renderer, tmp_path):
|
|
"""The UI reads typeOf/desc; Pixlet emits type/description."""
|
|
star = tmp_path / "app.star"
|
|
star.write_text("#\n", encoding="utf-8")
|
|
with patch.object(subprocess, "run",
|
|
return_value=_completed(stdout=self.PIXLET_OUTPUT)):
|
|
_, schema, _ = renderer.extract_schema(str(star))
|
|
field = schema["schema"][0]
|
|
assert field["typeOf"] == "dropdown"
|
|
assert field["desc"] == "Pick a road"
|
|
assert "type" not in field and "description" not in field
|
|
|
|
@pytest.mark.parametrize("outcome", [
|
|
{"return_value": _completed(returncode=1, stderr="unknown command \"schema\"")},
|
|
{"return_value": _completed(stdout="not json at all")},
|
|
{"side_effect": subprocess.TimeoutExpired(cmd="pixlet", timeout=20)},
|
|
{"side_effect": OSError("no such binary")},
|
|
])
|
|
def test_it_falls_back_to_the_source_parser(self, renderer, tmp_path, outcome):
|
|
"""Older Pixlet has no `schema` subcommand, and an app can fail to run.
|
|
Neither should cost the schema an app does state literally."""
|
|
star = tmp_path / "app.star"
|
|
star.write_text(
|
|
'def get_schema():\n'
|
|
' return schema.Schema(version = "1", fields = [\n'
|
|
' schema.Text(id = "city", name = "City", desc = "Your city",'
|
|
' icon = "gear"),\n'
|
|
' ])\n',
|
|
encoding="utf-8")
|
|
with patch.object(subprocess, "run", **outcome):
|
|
ok, parsed, error = renderer.extract_schema(str(star))
|
|
assert ok is True and error is None
|
|
assert [f["id"] for f in parsed["schema"]] == ["city"]
|
|
|
|
def test_no_pixlet_binary_skips_straight_to_the_parser(self, renderer, tmp_path):
|
|
renderer.pixlet_binary = None
|
|
star = tmp_path / "app.star"
|
|
star.write_text("#\n", encoding="utf-8")
|
|
assert renderer.extract_schema_via_pixlet(str(star)) is None
|
|
|
|
def test_a_missing_star_file_is_still_an_error(self, renderer, tmp_path):
|
|
ok, schema, error = renderer.extract_schema(str(tmp_path / "gone.star"))
|
|
assert ok is False and schema is None and "not found" in error
|
|
|
|
def test_an_unexpected_pixlet_shape_is_not_trusted(self, renderer, tmp_path):
|
|
"""A bare list, or a dict with no schema array, must not reach the UI."""
|
|
star = tmp_path / "app.star"
|
|
star.write_text("#\n", encoding="utf-8")
|
|
with patch.object(subprocess, "run",
|
|
return_value=_completed(stdout='["not", "a", "schema"]')):
|
|
assert renderer.extract_schema_via_pixlet(str(star)) is None
|