mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-08-21 10:29:06 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b7a7e26bfe |
+63
-1
@@ -111,6 +111,12 @@ class RestoreOptions:
|
|||||||
"""Which sections of a backup should be restored."""
|
"""Which sections of a backup should be restored."""
|
||||||
|
|
||||||
restore_config: bool = True
|
restore_config: bool = True
|
||||||
|
#: Whether to take the backup's display.hardware block as well.
|
||||||
|
#: Off by default: that block describes the panel physically wired to
|
||||||
|
#: *this* device -- its size, chain length, mapping, multiplexing and
|
||||||
|
#: refresh cap. A backup carries the panel of the machine it was taken
|
||||||
|
#: on, and restoring one onto a different rig drives the wrong geometry.
|
||||||
|
restore_hardware: bool = False
|
||||||
restore_secrets: bool = True
|
restore_secrets: bool = True
|
||||||
restore_wifi: bool = True
|
restore_wifi: bool = True
|
||||||
restore_fonts: bool = True
|
restore_fonts: bool = True
|
||||||
@@ -549,6 +555,60 @@ def _copy_file(src: Path, dst: Path) -> None:
|
|||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
_HARDWARE_PATH = ("display", "hardware")
|
||||||
|
|
||||||
|
|
||||||
|
def _restore_config_preserving_hardware(src: Path, dst: Path, keep_hardware: bool) -> None:
|
||||||
|
"""Copy a backed-up config.json, optionally keeping the local panel block.
|
||||||
|
|
||||||
|
display.hardware describes the panel physically attached to this device:
|
||||||
|
cols, rows, chain_length, hardware_mapping, panel_type, multiplexing and
|
||||||
|
the refresh-rate cap. None of that travels with a configuration -- it is a
|
||||||
|
property of the machine. Restoring a backup taken on a 512x64 rig onto a
|
||||||
|
128x32 one used to overwrite the smaller panel's geometry with the larger
|
||||||
|
one's, which is not a setting the user can see going wrong; the display
|
||||||
|
simply stops being right.
|
||||||
|
|
||||||
|
Falls back to a plain copy when either file cannot be parsed, so a restore
|
||||||
|
never fails because of this.
|
||||||
|
"""
|
||||||
|
if not keep_hardware:
|
||||||
|
_copy_file(src, dst)
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
incoming = json.loads(src.read_text(encoding="utf-8"))
|
||||||
|
local = json.loads(dst.read_text(encoding="utf-8")) if dst.exists() else {}
|
||||||
|
except (OSError, ValueError) as exc:
|
||||||
|
logger.warning(
|
||||||
|
"[Backup] Could not merge local panel config (%s); restoring the "
|
||||||
|
"backup's config.json as-is", exc)
|
||||||
|
_copy_file(src, dst)
|
||||||
|
return
|
||||||
|
|
||||||
|
section, key = _HARDWARE_PATH
|
||||||
|
local_hw = (local.get(section) or {}).get(key)
|
||||||
|
if not isinstance(local_hw, dict) or not local_hw:
|
||||||
|
_copy_file(src, dst)
|
||||||
|
return
|
||||||
|
|
||||||
|
if not isinstance(incoming.get(section), dict):
|
||||||
|
incoming[section] = {}
|
||||||
|
incoming_hw = incoming[section].get(key)
|
||||||
|
incoming[section][key] = local_hw
|
||||||
|
if isinstance(incoming_hw, dict) and incoming_hw != local_hw:
|
||||||
|
logger.info(
|
||||||
|
"[Backup] Kept this device's display.hardware; the backup's panel "
|
||||||
|
"was %sx%s chain %s, this one is %sx%s chain %s",
|
||||||
|
incoming_hw.get("cols"), incoming_hw.get("rows"),
|
||||||
|
incoming_hw.get("chain_length"),
|
||||||
|
local_hw.get("cols"), local_hw.get("rows"),
|
||||||
|
local_hw.get("chain_length"))
|
||||||
|
|
||||||
|
tmp_path = dst.with_suffix(dst.suffix + ".restore-tmp")
|
||||||
|
tmp_path.write_text(json.dumps(incoming, indent=2) + "\n", encoding="utf-8")
|
||||||
|
os.replace(tmp_path, dst)
|
||||||
|
|
||||||
|
|
||||||
def restore_backup(
|
def restore_backup(
|
||||||
zip_path: Path,
|
zip_path: Path,
|
||||||
project_root: Path,
|
project_root: Path,
|
||||||
@@ -584,7 +644,9 @@ def restore_backup(
|
|||||||
# Main config.
|
# Main config.
|
||||||
if options.restore_config and (tmp_dir / _CONFIG_REL).exists():
|
if options.restore_config and (tmp_dir / _CONFIG_REL).exists():
|
||||||
try:
|
try:
|
||||||
_copy_file(tmp_dir / _CONFIG_REL, project_root / _CONFIG_REL)
|
_restore_config_preserving_hardware(
|
||||||
|
tmp_dir / _CONFIG_REL, project_root / _CONFIG_REL,
|
||||||
|
keep_hardware=not options.restore_hardware)
|
||||||
result.restored.append("config")
|
result.restored.append("config")
|
||||||
except OSError as e:
|
except OSError as e:
|
||||||
logger.error("[Backup] Failed to restore config.json: %s", e, exc_info=True)
|
logger.error("[Backup] Failed to restore config.json: %s", e, exc_info=True)
|
||||||
|
|||||||
@@ -1,143 +0,0 @@
|
|||||||
"""GET /config/main must not hand out credentials.
|
|
||||||
|
|
||||||
The endpoint returned the raw config to anyone who could reach the port, and
|
|
||||||
this web interface has no authentication of any kind. Measured against a live
|
|
||||||
rig, an unauthenticated request returned:
|
|
||||||
|
|
||||||
github.api_token 40 chars
|
|
||||||
incoming-packages.ha_token 183 chars
|
|
||||||
jellyfin-now-playing.api_key 32 chars
|
|
||||||
ledmatrix-weather.api_key 32 chars
|
|
||||||
on-air.mqtt_password 8 chars
|
|
||||||
youtube.api_key 20 chars
|
|
||||||
youtube-stats.api_key 39 chars
|
|
||||||
|
|
||||||
A GitHub token and a Home Assistant long-lived token among them.
|
|
||||||
|
|
||||||
The x-secret masking the plugin config endpoints use does not apply here: this
|
|
||||||
endpoint never consults a schema, and core keys such as github.api_token have
|
|
||||||
no schema to carry the marker. Several of those fields *are* tagged x-secret in
|
|
||||||
their plugin's schema and were still returned in full, which is what makes the
|
|
||||||
schema route the wrong one to rely on for this endpoint.
|
|
||||||
|
|
||||||
Matching on field name is blunt. For a whole-config dump it is the right
|
|
||||||
default: anything named like a credential should not leave the process, and a
|
|
||||||
new plugin that adds a differently-shaped secret is covered without anyone
|
|
||||||
remembering to tag it.
|
|
||||||
"""
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from web_interface.blueprints.api_v3 import (
|
|
||||||
_looks_like_a_credential,
|
|
||||||
_redact_credentials,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("name", [
|
|
||||||
"password", "mqtt_password", "opensky_password", "passwd",
|
|
||||||
"api_key", "apikey", "API_KEY", "flightaware_api_key",
|
|
||||||
"token", "ha_token", "api_token", "access_token",
|
|
||||||
"secret", "client_secret", "spotify_client_secret",
|
|
||||||
"access_key", "private_key",
|
|
||||||
])
|
|
||||||
def test_credential_names_are_recognised(name):
|
|
||||||
assert _looks_like_a_credential(name)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("name", [
|
|
||||||
"timezone", "city", "brightness", "enabled", "update_interval",
|
|
||||||
"favorite_teams", "display_duration", "keyword",
|
|
||||||
])
|
|
||||||
def test_ordinary_names_are_left_alone(name):
|
|
||||||
assert not _looks_like_a_credential(name)
|
|
||||||
|
|
||||||
|
|
||||||
def test_the_measured_leak_is_closed():
|
|
||||||
"""The exact shape taken off the rig."""
|
|
||||||
config = {
|
|
||||||
"github": {"api_token": "ghp_" + "x" * 36},
|
|
||||||
"incoming-packages": {"ha_token": "y" * 183, "enabled": True},
|
|
||||||
"jellyfin-now-playing": {"api_key": "z" * 32},
|
|
||||||
"on-air": {"mqtt_password": "hunter22"},
|
|
||||||
"youtube": {"api_key": "k" * 20},
|
|
||||||
"timezone": "America/New_York",
|
|
||||||
}
|
|
||||||
out = _redact_credentials(config)
|
|
||||||
assert out["github"]["api_token"] == ""
|
|
||||||
assert out["incoming-packages"]["ha_token"] == ""
|
|
||||||
assert out["jellyfin-now-playing"]["api_key"] == ""
|
|
||||||
assert out["on-air"]["mqtt_password"] == ""
|
|
||||||
assert out["youtube"]["api_key"] == ""
|
|
||||||
# Everything else survives, or the config editor breaks.
|
|
||||||
assert out["timezone"] == "America/New_York"
|
|
||||||
assert out["incoming-packages"]["enabled"] is True
|
|
||||||
|
|
||||||
|
|
||||||
def test_nested_and_listed_credentials_are_reached():
|
|
||||||
config = {"a": {"b": {"c": {"password": "p"}}},
|
|
||||||
"feeds": [{"name": "x", "api_key": "k"}, {"name": "y"}]}
|
|
||||||
out = _redact_credentials(config)
|
|
||||||
assert out["a"]["b"]["c"]["password"] == ""
|
|
||||||
assert out["feeds"][0]["api_key"] == ""
|
|
||||||
assert out["feeds"][0]["name"] == "x"
|
|
||||||
|
|
||||||
|
|
||||||
def test_the_original_is_not_mutated():
|
|
||||||
"""The caller holds the live config; redaction must not edit it in place."""
|
|
||||||
config = {"github": {"api_token": "keepme"}}
|
|
||||||
_redact_credentials(config)
|
|
||||||
assert config["github"]["api_token"] == "keepme"
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_credential_shaped_container_is_still_walked():
|
|
||||||
"""`secrets: {...}` is a section name, not a value to blank."""
|
|
||||||
config = {"secrets": {"api_key": "k", "note": "keep"}}
|
|
||||||
out = _redact_credentials(config)
|
|
||||||
assert out["secrets"]["api_key"] == ""
|
|
||||||
assert out["secrets"]["note"] == "keep"
|
|
||||||
|
|
||||||
|
|
||||||
def test_non_dict_input_passes_through():
|
|
||||||
assert _redact_credentials("plain") == "plain"
|
|
||||||
assert _redact_credentials(7) == 7
|
|
||||||
assert _redact_credentials(None) is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_the_endpoint_itself_redacts():
|
|
||||||
"""Through the view function, not the helper.
|
|
||||||
|
|
||||||
The helper tests above all passed with the route still returning
|
|
||||||
`config` -- reverting the one line that calls the redactor changed
|
|
||||||
nothing, because nothing exercised the route. A property asserted on a
|
|
||||||
helper is not a property asserted on the endpoint, and it is the endpoint
|
|
||||||
that is exposed to the network.
|
|
||||||
"""
|
|
||||||
import json as _json
|
|
||||||
from unittest.mock import MagicMock
|
|
||||||
|
|
||||||
import flask
|
|
||||||
|
|
||||||
from web_interface.blueprints import api_v3 as mod
|
|
||||||
|
|
||||||
raw = {"github": {"api_token": "ghp_secret_value"},
|
|
||||||
"timezone": "America/New_York"}
|
|
||||||
|
|
||||||
manager = MagicMock()
|
|
||||||
manager.load_config.return_value = raw
|
|
||||||
previous = getattr(mod.api_v3, "config_manager", None)
|
|
||||||
mod.api_v3.config_manager = manager
|
|
||||||
|
|
||||||
app = flask.Flask(__name__)
|
|
||||||
try:
|
|
||||||
with app.test_request_context("/config/main"):
|
|
||||||
response = mod.get_main_config()
|
|
||||||
payload = response.get_json() if hasattr(response, "get_json") else _json.loads(response[0].data)
|
|
||||||
finally:
|
|
||||||
mod.api_v3.config_manager = previous
|
|
||||||
|
|
||||||
data = payload["data"]
|
|
||||||
assert data["github"]["api_token"] == "", (
|
|
||||||
"the endpoint returned the token; the redactor is not wired in")
|
|
||||||
assert data["timezone"] == "America/New_York"
|
|
||||||
# And the config the manager handed over is untouched.
|
|
||||||
assert raw["github"]["api_token"] == "ghp_secret_value"
|
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""A restore must not repoint this device at another machine's panel.
|
||||||
|
|
||||||
|
display.hardware describes the panel physically wired to this device -- cols,
|
||||||
|
rows, chain_length, hardware_mapping, panel_type, multiplexing, the refresh
|
||||||
|
cap. A backup carries the panel of the machine it was taken on. Restoring a
|
||||||
|
512x64 rig's backup onto a 128x32 one used to overwrite the smaller panel's
|
||||||
|
geometry with the larger one's, and nothing on screen explains why: the
|
||||||
|
display just stops being right.
|
||||||
|
|
||||||
|
That is not hypothetical. It happened, and the rig it happened to had to be
|
||||||
|
reflashed.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
from src.backup_manager import _restore_config_preserving_hardware # noqa: E402
|
||||||
|
|
||||||
|
BIG = {"display": {"hardware": {"cols": 128, "rows": 64, "chain_length": 4,
|
||||||
|
"hardware_mapping": "adafruit-hat-pwm"},
|
||||||
|
"runtime": {"gpio_slowdown": 4}},
|
||||||
|
"timezone": "America/New_York", "some-plugin": {"enabled": True}}
|
||||||
|
SMALL = {"display": {"hardware": {"cols": 64, "rows": 32, "chain_length": 2,
|
||||||
|
"hardware_mapping": "regular"},
|
||||||
|
"runtime": {"gpio_slowdown": 2}},
|
||||||
|
"timezone": "UTC"}
|
||||||
|
|
||||||
|
|
||||||
|
def _run(tmp, keep):
|
||||||
|
src = tmp / "backup_config.json"; src.write_text(json.dumps(BIG))
|
||||||
|
dst = tmp / "config.json"; dst.write_text(json.dumps(SMALL))
|
||||||
|
_restore_config_preserving_hardware(src, dst, keep_hardware=keep)
|
||||||
|
return json.loads(dst.read_text())
|
||||||
|
|
||||||
|
|
||||||
|
def test_local_panel_survives(tmp_path):
|
||||||
|
out = _run(tmp_path, keep=True)
|
||||||
|
hw = out["display"]["hardware"]
|
||||||
|
assert (hw["cols"], hw["rows"], hw["chain_length"]) == (64, 32, 2), (
|
||||||
|
"the restore repointed this device at the backup's panel")
|
||||||
|
assert hw["hardware_mapping"] == "regular", "panel wiring came from the backup"
|
||||||
|
|
||||||
|
|
||||||
|
def test_everything_else_is_restored(tmp_path):
|
||||||
|
out = _run(tmp_path, keep=True)
|
||||||
|
assert out["timezone"] == "America/New_York", "config was not restored"
|
||||||
|
assert out["some-plugin"] == {"enabled": True}, "plugin config was not restored"
|
||||||
|
assert out["display"]["runtime"] == {"gpio_slowdown": 4}, (
|
||||||
|
"only display.hardware should be held back")
|
||||||
|
|
||||||
|
|
||||||
|
def test_opting_in_takes_the_backups_panel(tmp_path):
|
||||||
|
out = _run(tmp_path, keep=False)
|
||||||
|
hw = out["display"]["hardware"]
|
||||||
|
assert (hw["cols"], hw["rows"], hw["chain_length"]) == (128, 64, 4)
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_device_with_no_local_hardware_takes_the_backups(tmp_path):
|
||||||
|
src = tmp_path / "b.json"; src.write_text(json.dumps(BIG))
|
||||||
|
dst = tmp_path / "c.json"; dst.write_text(json.dumps({"timezone": "UTC"}))
|
||||||
|
_restore_config_preserving_hardware(src, dst, keep_hardware=True)
|
||||||
|
out = json.loads(dst.read_text())
|
||||||
|
assert out["display"]["hardware"]["cols"] == 128, (
|
||||||
|
"nothing local to preserve, so the backup's panel should be used")
|
||||||
|
|
||||||
|
|
||||||
|
def test_unparseable_local_config_still_restores(tmp_path):
|
||||||
|
src = tmp_path / "b.json"; src.write_text(json.dumps(BIG))
|
||||||
|
dst = tmp_path / "c.json"; dst.write_text("{ not json")
|
||||||
|
_restore_config_preserving_hardware(src, dst, keep_hardware=True)
|
||||||
|
assert json.loads(dst.read_text())["timezone"] == "America/New_York", (
|
||||||
|
"a restore must never fail because of this merge")
|
||||||
@@ -262,54 +262,15 @@ def _stop_display_service():
|
|||||||
result['status'] = status
|
result['status'] = status
|
||||||
return result
|
return result
|
||||||
|
|
||||||
#: Field names whose value is a credential. Matched by name because this
|
|
||||||
#: endpoint returns the whole config, core keys included, and core config has
|
|
||||||
#: no schema to carry x-secret markers.
|
|
||||||
_CREDENTIAL_NAME_PARTS = ("password", "passwd", "secret", "token", "api_key",
|
|
||||||
"apikey", "access_key", "private_key", "client_secret")
|
|
||||||
|
|
||||||
|
|
||||||
def _looks_like_a_credential(name: str) -> bool:
|
|
||||||
lowered = name.lower()
|
|
||||||
return any(part in lowered for part in _CREDENTIAL_NAME_PARTS)
|
|
||||||
|
|
||||||
|
|
||||||
def _redact_credentials(value):
|
|
||||||
"""A copy of `value` with credential-named fields blanked.
|
|
||||||
|
|
||||||
/config/main returned the raw config to anyone who could reach the port,
|
|
||||||
and this interface has no authentication. On one rig that meant a 40-char
|
|
||||||
GitHub token, a 183-char Home Assistant token and five API keys were
|
|
||||||
readable by anything on the LAN.
|
|
||||||
|
|
||||||
The x-secret masking used by the plugin config endpoints does not help
|
|
||||||
here: this endpoint never consults a schema, and core keys such as
|
|
||||||
github.api_token have no schema to mark. Matching on the field name is
|
|
||||||
blunt, but for a whole-config dump the right default is that anything
|
|
||||||
named like a credential does not leave the process.
|
|
||||||
|
|
||||||
Blanked rather than removed, and safe to blank: POST /config/main merges
|
|
||||||
into the loaded config and only writes the keys it was given, so a client
|
|
||||||
that round-trips this response cannot erase a secret it never saw.
|
|
||||||
"""
|
|
||||||
if isinstance(value, dict):
|
|
||||||
return {k: ("" if _looks_like_a_credential(k) and not isinstance(v, (dict, list))
|
|
||||||
else _redact_credentials(v))
|
|
||||||
for k, v in value.items()}
|
|
||||||
if isinstance(value, list):
|
|
||||||
return [_redact_credentials(item) for item in value]
|
|
||||||
return value
|
|
||||||
|
|
||||||
|
|
||||||
@api_v3.route('/config/main', methods=['GET'])
|
@api_v3.route('/config/main', methods=['GET'])
|
||||||
def get_main_config():
|
def get_main_config():
|
||||||
"""Get main configuration, with credentials redacted."""
|
"""Get main configuration"""
|
||||||
try:
|
try:
|
||||||
if not api_v3.config_manager:
|
if not api_v3.config_manager:
|
||||||
return jsonify({'status': 'error', 'message': 'Config manager not initialized'}), 500
|
return jsonify({'status': 'error', 'message': 'Config manager not initialized'}), 500
|
||||||
|
|
||||||
config = api_v3.config_manager.load_config()
|
config = api_v3.config_manager.load_config()
|
||||||
return jsonify({'status': 'success', 'data': _redact_credentials(config)})
|
return jsonify({'status': 'success', 'data': config})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error('Unhandled exception', exc_info=True)
|
logger.error('Unhandled exception', exc_info=True)
|
||||||
return jsonify({'status': 'error', 'message': 'An error occurred; see logs for details', 'details': describe_exception(e)}), 500
|
return jsonify({'status': 'error', 'message': 'An error occurred; see logs for details', 'details': describe_exception(e)}), 500
|
||||||
|
|||||||
Reference in New Issue
Block a user