From 0188a22ee3b869629844fb1a0d8525bec1c47b58 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Sun, 22 Nov 2026 13:48:04 +0100 Subject: [PATCH 1/2] feat(channel): let a read-only MQTT driver declare its read requests Venus OS on a Victron GX publishes its MQTT values only while a client sends R//keepalive. A driver from the signed channel cannot send one: the generated guard turns host.mqtt_publish into an error for every read-only driver, and FTW Core refuses the publish too. A catalog manifest may now list mqtt_read_request_topics. The channel build checks each topic, refuses the list on a driver that is not MQTT or that controls, carries it into the signed metadata, and generates a guard that lets host.mqtt_publish and host.mqtt_pub through only to a matching topic with at most 1 KiB of payload. A topic must start with R/, Venus's read-request namespace: a literal first level alone would admit W/+/settings/..., a Venus write. "+" is a whole level, "#" is refused, levels are printable ASCII without spaces, at most 256 bytes. The guard checks the R/ level itself as well. A read request is not a write, so the driver gets no write permission: the signed permissions stay read-only and verification still refuses mqtt.publish on a read-only driver. An FTW Core that does not know the field runs the driver as before and refuses the request. Verification and make check hold the topics to the same rule, and verification wants mqtt.subscribe beside them. Every other artifact is byte for byte the same. Refs srcfl/device-drivers#256 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Fredrik Ahlgren --- docs/WRITING-A-DRIVER.md | 28 ++++ spec/host-api.md | 3 + spec/manifest-v2.md | 4 + tests/test_ftw_repository.py | 267 +++++++++++++++++++++++++++++++++++ tools/ftw_repository.py | 110 ++++++++++++++- tools/manifest_parser.py | 38 +++++ tools/validate_manifest.py | 21 ++- 7 files changed, 466 insertions(+), 5 deletions(-) diff --git a/docs/WRITING-A-DRIVER.md b/docs/WRITING-A-DRIVER.md index 2c415a74..b357afbc 100644 --- a/docs/WRITING-A-DRIVER.md +++ b/docs/WRITING-A-DRIVER.md @@ -176,6 +176,34 @@ make refused-write-report ID=example `refused-write-baseline.json` recording what already shipped. `sungrow` is the worked example, and the only one clean when this was first measured. +## A read-only driver that has to ask + +A read-only driver from the signed channel cannot write, in any phase. Two +kinds of request only ask to read, and a driver may declare them: + +- A cloud driver that has to sign in before it can read names its sign-in + paths in its `DRIVER` table: `auth_post_path`, and `auth_post_paths` for a + login that posts more than one form. It may POST to those paths and no + others. +- An MQTT driver whose device reports only while a client asks names its + read-request topics in its catalog manifest. Venus OS on a Victron GX + publishes only while it receives `R//keepalive`: + + ```yaml + mqtt_read_request_topics: ["R/+/keepalive"] + ``` + + A topic must start with `R/`, Venus's read-request namespace; `+` stands + for one whole level and `#` is refused. The driver may publish only to a + matching topic, with at most 1 KiB of payload, and FTW Core allows six such + requests a minute. Setup measurement mode and fingerprint probes hold them + as they hold writes. A read request + needs no write permission, so the signed channel grants none: an FTW Core + that does not know the field runs the driver read-only and refuses it. The generated + guard raises an error for any other publish; Core returns its refusal as a + string, so log it and try again later. Declare only a topic that asks the + device to report, never one that changes a setting. + ## Sign convention **Positive watts flow into the site.** Every driver, every device, no diff --git a/spec/host-api.md b/spec/host-api.md index 49f53933..48cdabec 100644 --- a/spec/host-api.md +++ b/spec/host-api.md @@ -192,6 +192,9 @@ Drain all buffered messages since last call. Returns a table of `{topic=string, ### `host.mqtt_publish(topic, payload)` Publish a message. Returns `true`/`false`. +A read-only driver from the signed channel may publish only to the +`mqtt_read_request_topics` its manifest declares (`docs/WRITING-A-DRIVER.md`). + ## HTTP Available when `PROTOCOL = "http"`. diff --git a/spec/manifest-v2.md b/spec/manifest-v2.md index ab097b61..0c928447 100644 --- a/spec/manifest-v2.md +++ b/spec/manifest-v2.md @@ -17,6 +17,7 @@ Each driver has a YAML manifest in `manifests/` that describes its metadata, cap | `control` | bool | Yes | Whether FTW can command the device through this driver: `driver_command` writes to it and the `DRIVER` table does not declare `read_only = true`. A stub that only refuses is `false` and declares `read_only` | | `tested_devices` | list | No | Devices tested against (see below) | | `upstream_docs` | list | No | Vendor reference documents to watch for register/protocol changes (see below) | +| `mqtt_read_request_topics` | list | No | For a read-only MQTT driver: the topics it may publish read requests to, such as `R/+/keepalive`. FTW lets the driver publish to these topics only; they grant no write permission (see `docs/WRITING-A-DRIVER.md`) | | `min_host_version` | string | No | Minimum gateway firmware version required | | `size_bytes` | int | Yes | Size of the `.lua` file in bytes | | `dkb_id` | string | No | Corresponding Hugin DKB device profile ID | @@ -208,6 +209,7 @@ Version changes must be accompanied by a `CHANGELOG.md` entry under `[Unreleased 10. Every manifest must have a corresponding `.lua` file in `drivers/` 11. `tested_devices` entries must have `manufacturer` and `model_family` 12. `upstream_docs` entries must have an `http(s)` `url`; `kind` and `url_stability`, when present, must be known values +13. `mqtt_read_request_topics`, when present, must be a non-empty list on an `mqtt` driver with `control: false`. Each topic starts with `R/`, Venus's read-request namespace, and is at most 256 bytes of printable ASCII without spaces; `+` is a whole level; `#` is refused ## Migration from V1 @@ -221,6 +223,8 @@ V2.2 adds bytecode fields: `bytecode_sha256`, `bytecode_signature`, `bytecode_si V2.3 adds `upstream_docs`: an optional list of vendor reference documents (`url`, `title`, `kind`, `url_stability`) to watch for register/protocol changes. +V2.5 adds the optional `mqtt_read_request_topics`: the read requests a read-only MQTT driver may publish. + V2.4 adds `connectivity` (`local`/`cloud`) and the optional `setup` list: where a driver talks while it is running, and what a human must obtain once before it can connect at all. `connectivity` is required, so every manifest carries it. Use `tools/migrate_manifests.py` to convert V1 JSON → V2 YAML. diff --git a/tests/test_ftw_repository.py b/tests/test_ftw_repository.py index de041dca..f9b686ec 100644 --- a/tests/test_ftw_repository.py +++ b/tests/test_ftw_repository.py @@ -34,6 +34,8 @@ verify_manifest, verify_stable_promotion, ) +from manifest_parser import mqtt_read_request_topic_error # noqa: E402 +from validate_manifest import validate_manifest # noqa: E402 COMMIT = "a" * 40 @@ -287,6 +289,31 @@ def test_manifest_requires_exact_canonical_envelope_bytes( ), "read-only driver has a write-capable permission", ), + # Declared read requests grant no write permission. mqtt.publish is + # refused on a read-only driver with or without them, and they need + # mqtt.subscribe. + ( + lambda driver: driver.update(permissions=["mqtt.subscribe", "mqtt.publish"]), + "read-only driver has a write-capable permission", + ), + ( + lambda driver: ( + driver.update(permissions=["mqtt.subscribe", "mqtt.publish"]), + driver["metadata"].update(mqtt_read_request_topics=["R/+/keepalive"]), + ), + "read-only driver has a write-capable permission", + ), + ( + lambda driver: driver["metadata"].update(mqtt_read_request_topics=["R/+/keepalive"]), + "declared MQTT read requests need mqtt.subscribe", + ), + ( + lambda driver: ( + driver.update(permissions=["mqtt.subscribe"]), + driver["metadata"].update(mqtt_read_request_topics=["R/#"]), + ), + "has level '#'", + ), ( lambda driver: driver["metadata"].update(read_only=False), "Lua metadata read_only must match the manifest", @@ -1132,3 +1159,243 @@ def test_auth_post_path_must_be_a_path_and_must_mean_something( _load_channel(config_path, repo) source.write_text(original, encoding="utf-8") + + +# ---- MQTT read requests --------------------------------------------------- +# +# Venus OS on a Victron GX publishes its MQTT values only while a client sends +# R//keepalive. A read-only MQTT driver may declare such read +# requests in its catalog manifest; the generated guard and FTW Core both hold +# its publishes to exactly those topics. + +KEEPALIVE = 'mqtt_read_request_topics: ["R/+/keepalive"]\n' + + +def declare_read_requests(repo: Path, driver_id: str, line: str = KEEPALIVE) -> None: + """Set a driver's mqtt_read_request_topics line, replacing any it has.""" + path = repo / "manifests" / f"{driver_id}.yaml" + text = re.sub(r"^mqtt_read_request_topics:.*\n", "", path.read_text(encoding="utf-8"), + flags=re.M) + text = re.sub(r"^(ders:.*\n)", lambda match: match.group(1) + line, text, + count=1, flags=re.M) + path.write_text(text, encoding="utf-8") + + +@pytest.mark.parametrize( + "topic", + [ + "R/+/keepalive", + "R/c0619ab1234/keepalive", + "R/+/system/0/Serial", + "R/+/" + "a" * 252, # 256 bytes, the limit Core uses + ], +) +def test_read_request_topic_rule_accepts(topic: str) -> None: + assert mqtt_read_request_topic_error(topic) == "" + + +@pytest.mark.parametrize( + "topic", + [ + "", + "#", + "R/#", + "R/+/keep#alive", + "R/+x/keepalive", + "+/+/keepalive", + "R//keepalive", + "R/+/", + "/R/keepalive", + "$SYS/+/keepalive", + # The first level must be R, Venus's read-request namespace. A literal + # first level is not enough: W/ is Venus's write namespace. + "W/+/settings/0/Settings/CGwacs/AcPowerSetPoint", + "W/+/x", + "X/+/keepalive", + "r/+/keepalive", + "+/abc123/keepalive", + "R", + "keepalive", + # Core refuses a trailing newline; so must this. + "R/+/keepalive\n", + "R/+/keep alive", + "R/\x00/keepalive", + "R/é/keepalive", + "R/+/" + "a" * 253, + None, + 7, + ], +) +def test_read_request_topic_rule_refuses(topic: object) -> None: + assert mqtt_read_request_topic_error(topic) + + +def test_a_declared_read_request_reaches_the_policy_and_the_guard( + tmp_path: Path, keypair: tuple[str, str] +) -> None: + repo, config_path = single_driver_repo(tmp_path, "victron_mqtt") + declare_read_requests(repo, "victron_mqtt") + entry = _load_channel(config_path, repo)[0] + artifact = entry["raw"].decode("utf-8") + + assert entry["controls"] is False + assert entry["metadata"]["read_only"] is True + assert entry["metadata"]["mqtt_read_request_topics"] == ["R/+/keepalive"] + # A read request is not a write: no write permission, so an FTW Core that + # does not know the field runs the driver read-only, as before. + assert entry["permissions"] == ["mqtt.subscribe"] + assert 'local __sourceful_ftw_read_requests = { "R/+/keepalive" }' in artifact + assert "host.mqtt_publish = __sourceful_ftw_write_denied" not in artifact + assert "host.mqtt_pub = __sourceful_ftw_write_denied" not in artifact + for denied in ("http_post", "modbus_write", "modbus_write_multi", + "modbus_write_multiple", "serial_write"): + assert f"host.{denied} = __sourceful_ftw_write_denied" in artifact, denied + + # The signed manifest carries it, and verifies. + _, output = build(tmp_path / "signed", keypair, repo_root=repo, config_path=config_path) + manifest = verify_manifest(output / "manifest.json", key_id=KEY_ID, + public_key_base64=keypair[1]) + driver = manifest["drivers"][0] + assert driver["metadata"]["mqtt_read_request_topics"] == ["R/+/keepalive"] + assert driver["permissions"] == ["mqtt.subscribe"] + + +@pytest.mark.skipif(not (ROOT / "lua55").exists(), reason="run make check to build ./lua55") +def test_the_read_request_guard_passes_only_declared_topics(tmp_path: Path) -> None: + repo, config_path = single_driver_repo(tmp_path, "victron_mqtt") + declare_read_requests(repo, "victron_mqtt") + artifact_path = tmp_path / "victron_mqtt.lua" + artifact_path.write_bytes(_load_channel(config_path, repo)[0]["raw"]) + script = "\n".join( + ( + "sent = {}", + "host = { log = function() end }", + "host.mqtt_publish = function(topic, payload) sent[#sent + 1] = topic end", + "host.mqtt_pub = host.mqtt_publish", + f"dofile({json.dumps(str(artifact_path))})", + "local function sends(publish, topic, payload)", + " local ok, err = pcall(publish, topic, payload)", + " assert(ok or tostring(err):find('declared read request', 1, true), err)", + " return ok", + "end", + "assert(sends(host.mqtt_publish, 'R/abc123/keepalive', ''))", + "assert(sends(host.mqtt_publish, 'R/abc123/keepalive'," + " '{\"keepalive-options\":[\"suppress-republish\"]}'))", + "assert(sends(host.mqtt_pub, 'R/abc123/keepalive', ''))", + "assert(sends(host.mqtt_publish, 'R/abc123/keepalive', string.rep('x', 1024)))", + "for _, topic in ipairs({", + " 'W/abc123/settings/0/Settings/CGwacs/AcPowerSetPoint',", + " 'R/abc123/system/0/Serial', 'R/abc123/keepalive/x', 'R/abc123',", + " 'R/#', 'R/#/keepalive', 'R/+/keepalive', 'R//keepalive', 'R/a b/keepalive', '',", + "}) do", + " assert(not sends(host.mqtt_publish, topic, ''), topic)", + " assert(not sends(host.mqtt_pub, topic, ''), topic)", + "end", + "assert(not sends(host.mqtt_publish, 'R/abc123/keepalive', string.rep('x', 1025)))", + "assert(not sends(host.mqtt_publish, nil, ''))", + "assert(#sent == 4, #sent)", + ) + ) + runtime = subprocess.run( + [str(ROOT / "lua55"), "-e", script], + check=False, + capture_output=True, + text=True, + ) + assert runtime.returncode == 0, runtime.stderr + + +@pytest.mark.skipif(not (ROOT / "lua55").exists(), reason="run make check to build ./lua55") +def test_the_read_request_guard_holds_to_the_read_namespace(tmp_path: Path) -> None: + """The guard refuses a topic outside R/ even if a W/ pattern reached it. + + The build refuses such a pattern first; this checks the guard does not + depend on that. + """ + metadata = {"id": "victron_mqtt", "name": "Victron", "version": "9.9.9", + "protocols": ["mqtt"], "capabilities": ["meter"]} + artifact = _ftw_artifact( + b"function driver_init(config) end\nfunction driver_poll() return 1000 end\n", + metadata, read_only=True, mqtt_read_request_topics=["W/+/x", "R/+/keepalive"]) + artifact_path = tmp_path / "guard.lua" + artifact_path.write_bytes(artifact) + script = "\n".join( + ( + "sent = {}", + "host = { log = function() end }", + "host.mqtt_publish = function(topic, payload) sent[#sent + 1] = topic end", + f"dofile({json.dumps(str(artifact_path))})", + "assert(not pcall(host.mqtt_publish, 'W/abc123/x', ''))", + "assert(pcall(host.mqtt_publish, 'R/abc123/keepalive', ''))", + "assert(#sent == 1 and sent[1] == 'R/abc123/keepalive', #sent)", + ) + ) + runtime = subprocess.run( + [str(ROOT / "lua55"), "-e", script], check=False, capture_output=True, text=True + ) + assert runtime.returncode == 0, runtime.stderr + + +@pytest.mark.parametrize( + ("driver_id", "line", "message"), + [ + ("victron_mqtt", 'mqtt_read_request_topics: ["R/#"]\n', "has level '#'"), + ("victron_mqtt", 'mqtt_read_request_topics: ["+/+/keepalive"]\n', + "must start with R/"), + ("victron_mqtt", + 'mqtt_read_request_topics: ["W/+/settings/0/Settings/CGwacs/AcPowerSetPoint"]\n', + "must start with R/"), + ("victron_mqtt", 'mqtt_read_request_topics: ["R/+x/keepalive"]\n', + "a wildcard is a whole '+' level"), + ("victron_mqtt", 'mqtt_read_request_topics: "R/+/keepalive"\n', "must be a list"), + # Declared where it cannot mean a read request: a Modbus meter, and an + # MQTT driver that controls and so already holds mqtt.publish. + ("sdm630", KEEPALIVE, "only for an MQTT driver"), + ("ferroamp", KEEPALIVE, "only means anything for a read-only driver"), + ], +) +def test_read_request_topics_must_be_valid_and_mean_something( + tmp_path: Path, driver_id: str, line: str, message: str +) -> None: + repo, config_path = single_driver_repo(tmp_path, driver_id) + declare_read_requests(repo, driver_id, line) + with pytest.raises(RepositoryError, match=re.escape(message)): + _load_channel(config_path, repo) + + +def test_publishing_is_declared_or_it_does_not_happen( + tmp_path: Path, keypair: tuple[str, str] +) -> None: + """A read-only driver that declares no read request keeps the blanket denial.""" + manifest, output = build(tmp_path, keypair) + exempt = [] + for driver in manifest["drivers"]: + if not driver["read_only"]: + continue + artifact = (output / Path(driver["url"]).name).read_text() + # No read-only driver holds the write permission, declared or not. + assert "mqtt.publish" not in driver["permissions"], driver["id"] + if "host.mqtt_publish = __sourceful_ftw_write_denied" not in artifact: + exempt.append(driver["id"]) + else: + assert "mqtt_read_request_topics" not in driver["metadata"], driver["id"] + assert exempt == [], f"unexpected drivers allowed to publish: {exempt}" + + +def test_manifest_check_holds_read_request_topics_to_the_rule(tmp_path: Path) -> None: + def errors(driver_id: str, line: str) -> list[str]: + repo = tmp_path / driver_id + (repo / "manifests").mkdir(parents=True, exist_ok=True) + (repo / "manifests" / f"{driver_id}.yaml").write_bytes( + (ROOT / "manifests" / f"{driver_id}.yaml").read_bytes()) + declare_read_requests(repo, driver_id, line) + return validate_manifest(repo / "manifests" / f"{driver_id}.yaml", + ROOT / "drivers" / "lua") + + assert errors("victron_mqtt", KEEPALIVE) == [] + assert any("has level '#'" in e for e in errors( + "victron_mqtt", 'mqtt_read_request_topics: ["R/#"]\n')) + assert any("non-empty list" in e for e in errors( + "victron_mqtt", "mqtt_read_request_topics: []\n")) + assert any("only for an MQTT driver" in e for e in errors("sdm630", KEEPALIVE)) + assert any("only for a read-only driver" in e for e in errors("ferroamp", KEEPALIVE)) diff --git a/tools/ftw_repository.py b/tools/ftw_repository.py index 05330d5c..78dff46f 100644 --- a/tools/ftw_repository.py +++ b/tools/ftw_repository.py @@ -29,7 +29,14 @@ "ftw_repository.py requires the package extra: uv run --extra package ..." ) from exc -from manifest_parser import parse_tested_devices, parse_yaml_simple +from manifest_parser import ( + MQTT_READ_REQUEST_NAMESPACE, + MQTT_READ_REQUEST_PAYLOAD_MAX_BYTES, + MQTT_READ_REQUEST_TOPIC_MAX_BYTES, + mqtt_read_request_topic_error, + parse_tested_devices, + parse_yaml_simple, +) ROOT = Path(__file__).resolve().parents[1] @@ -430,6 +437,7 @@ def _ftw_artifact( read_only: bool, auth_post_paths: list[str] | None = None, preserve_controls: bool = False, + mqtt_read_request_topics: list[str] | None = None, ) -> bytes: """Add FTW metadata and the host-call polyfills older hosts lack. @@ -453,6 +461,15 @@ def _ftw_artifact( a site pointing the driver at its own base URL. A web login posts more than one form, so a driver may declare several paths. The same rule holds for a POST through host.http_request. + + `mqtt_read_request_topics` is for a read-only MQTT driver whose device + publishes only while a client asks, as Venus OS does for + R//keepalive. The guard lets host.mqtt_publish through only to + a topic under R/, Venus's read-request namespace, that matches a declared + pattern level by level ("+" is one whole level), with at most 1 KiB of + payload, and raises for anything else. FTW + Core checks the same and also bounds the rate; the guard keeps an older + host to the topics. """ protocols = metadata.get("protocols", []) capabilities = metadata.get("capabilities", []) @@ -546,6 +563,55 @@ def _ftw_artifact( " end\n" "end\n" ) + # Only a driver that declares read requests gets this guard, so every + # other published artifact stays byte-identical. + mqtt_guard = ( + "host.mqtt_pub = __sourceful_ftw_write_denied\n" + "host.mqtt_publish = __sourceful_ftw_write_denied\n" + ) + if mqtt_read_request_topics: + mqtt_guard = ( + "local __sourceful_ftw_mqtt_publish = host.mqtt_publish or host.mqtt_pub\n" + "local __sourceful_ftw_read_requests = " + f"{_lua_string_list(mqtt_read_request_topics)}\n" + "local function __sourceful_ftw_levels(topic)\n" + " local levels = {}\n" + " for level in string.gmatch(topic .. \"/\", \"([^/]*)/\") do\n" + " levels[#levels + 1] = level\n" + " end\n" + " return levels\n" + "end\n" + "local function __sourceful_ftw_is_read_request(topic)\n" + " if type(topic) ~= \"string\" or " + f"#topic > {MQTT_READ_REQUEST_TOPIC_MAX_BYTES} then return false end\n" + " local got = __sourceful_ftw_levels(topic)\n" + f" if got[1] ~= {_lua_string(MQTT_READ_REQUEST_NAMESPACE)} then return false end\n" + " for _, pattern in ipairs(__sourceful_ftw_read_requests) do\n" + " local want = __sourceful_ftw_levels(pattern)\n" + " local match = #want == #got\n" + " for i = 1, #want do\n" + " local level = got[i]\n" + " if not match then break end\n" + " if not level:find(\"^[!-~]+$\") or level:find(\"[+#]\") then\n" + " match = false\n" + " elseif want[i] ~= \"+\" and want[i] ~= level then\n" + " match = false\n" + " end\n" + " end\n" + " if match then return true end\n" + " end\n" + " return false\n" + "end\n" + "host.mqtt_publish = function(topic, payload)\n" + " if __sourceful_ftw_is_read_request(topic) and type(payload) == \"string\"\n" + f" and #payload <= {MQTT_READ_REQUEST_PAYLOAD_MAX_BYTES} then\n" + " return __sourceful_ftw_mqtt_publish(topic, payload)\n" + " end\n" + " error(\"this driver declares itself read-only: " + "MQTT publish is allowed only for a declared read request\")\n" + "end\n" + "host.mqtt_pub = host.mqtt_publish\n" + ) write_guards = ( "local function __sourceful_ftw_write_denied()\n" " error(\"this driver declares itself read-only\")\n" @@ -554,9 +620,8 @@ def _ftw_artifact( "host.modbus_write = __sourceful_ftw_write_denied\n" "host.modbus_write_multi = __sourceful_ftw_write_denied\n" "host.modbus_write_multiple = __sourceful_ftw_write_denied\n" - "host.mqtt_pub = __sourceful_ftw_write_denied\n" - "host.mqtt_publish = __sourceful_ftw_write_denied\n" - "host.serial_write = __sourceful_ftw_write_denied\n" + + mqtt_guard + + "host.serial_write = __sourceful_ftw_write_denied\n" ) builtin_type_capture = ( "local __sourceful_ftw_builtin_type = type\n" if preserve_controls else "" @@ -745,6 +810,22 @@ def _load_channel(config_path: Path, repo_root: Path) -> list[dict[str, Any]]: # still an error -- that is a manifest someone forgot to fill in. if not isinstance(capabilities, list): raise RepositoryError(f"{driver_id}: catalog must declare its DERs, even if none") + # A read-only MQTT driver whose device reports only while a client asks + # (Venus OS and R//keepalive). The catalog manifest names the + # topics; the generated guard and FTW Core hold publishes to exactly + # those -- see _ftw_artifact. A read request is not a write, so the + # driver gets no write permission for it: an FTW Core that does not + # know the field still runs the driver, read-only, as before. + read_request_topics = catalog.get("mqtt_read_request_topics", []) + if not isinstance(read_request_topics, list): + raise RepositoryError(f"{driver_id}: mqtt_read_request_topics must be a list") + for topic in read_request_topics: + problem = mqtt_read_request_topic_error(topic) + if problem: + raise RepositoryError(f"{driver_id}: {problem}") + if read_request_topics and protocol != "mqtt": + raise RepositoryError( + f"{driver_id}: mqtt_read_request_topics is only for an MQTT driver") if body is not None: metadata_id = _string_field(body, "id") @@ -775,6 +856,10 @@ def _load_channel(config_path: Path, repo_root: Path) -> list[dict[str, Any]]: if isinstance(model, str) and model and model not in tested_models: tested_models.append(model) controls = driver_controls(source) + if read_request_topics and controls: + raise RepositoryError( + f"{driver_id}: mqtt_read_request_topics only means anything for a " + "read-only driver; one that controls already publishes") # The DRIVER block's verification claim reaches the artifact only # when it is one the review actually gated: a driver declaring # production or beta made a checkable statement that a reviewer @@ -840,6 +925,8 @@ def _load_channel(config_path: Path, repo_root: Path) -> list[dict[str, Any]]: metadata["auth_post_path"] = auth_post_path if extra_auth_paths and not controls: metadata["auth_post_paths"] = extra_auth_paths + if read_request_topics: + metadata["mqtt_read_request_topics"] = read_request_topics artifact = _ftw_artifact( raw, @@ -847,6 +934,7 @@ def _load_channel(config_path: Path, repo_root: Path) -> list[dict[str, Any]]: read_only=not controls, auth_post_paths=auth_post_paths if not controls else [], preserve_controls=controls and declares_controls, + mqtt_read_request_topics=read_request_topics, ) if len(artifact) > MAX_DRIVER_BYTES: raise RepositoryError(f"{driver_id}: generated FTW artifact is too large") @@ -962,6 +1050,20 @@ def _validate_manifest(manifest: dict[str, Any]) -> None: allowed_write = set() if metadata.get("auth_post_path") or metadata.get("auth_post_paths"): allowed_write = {"http.post"} + # Declared read requests grant no write permission: mqtt.publish stays + # refused below, so an FTW Core that does not know the field runs the + # driver read-only. The guard and a Core that knows the field confine + # publishes to these topics. + read_request_topics = metadata.get("mqtt_read_request_topics", []) + if not isinstance(read_request_topics, list): + raise RepositoryError(f"{driver_id}: mqtt_read_request_topics must be a list") + for topic in read_request_topics: + problem = mqtt_read_request_topic_error(topic) + if problem: + raise RepositoryError(f"{driver_id}: {problem}") + if read_request_topics and "mqtt.subscribe" not in permissions: + raise RepositoryError( + f"{driver_id}: declared MQTT read requests need mqtt.subscribe") if read_only and write_permissions.intersection(permissions) - allowed_write: raise RepositoryError(f"{driver_id}: read-only driver has a write-capable permission") if driver.get("channel") not in {"beta", "stable"}: diff --git a/tools/manifest_parser.py b/tools/manifest_parser.py index 9eeafb5f..0c63515e 100644 --- a/tools/manifest_parser.py +++ b/tools/manifest_parser.py @@ -178,3 +178,41 @@ def _parse_device_field(device: dict, field_str: str) -> None: key = m.group(1) val = m.group(2).strip().strip('"').strip("'") device[key] = val + + +# A read request asks a device to report and changes nothing on it. Victron's +# Venus OS publishes its MQTT values only while a client sends one to +# R//keepalive. A read-only MQTT driver may declare such topics in +# `mqtt_read_request_topics`, and FTW Core then lets it publish to them and to +# nothing else. Core applies this same rule (go/internal/drivers/ +# mqtt_read_request.go in srcfl/ftw); change the two together. +MQTT_READ_REQUEST_NAMESPACE = "R" +MQTT_READ_REQUEST_TOPIC_MAX_BYTES = 256 +MQTT_READ_REQUEST_PAYLOAD_MAX_BYTES = 1024 +_MQTT_TOPIC_LEVEL_RE = re.compile(r"[!-~]+") + + +def mqtt_read_request_topic_error(topic: object) -> str: + """Why `topic` cannot be a declared read request, or "" when it can. + + The first level must be exactly "R", Venus's read-request namespace. A + literal first level alone is not enough: W/+/settings/... is a valid + pattern and a Venus write. "+" stands for one whole level and "#" is + refused. A level is printable ASCII without spaces. + """ + if not isinstance(topic, str) or not topic: + return f"MQTT read-request topic {topic!r} must be a non-empty string" + if len(topic.encode("utf-8")) > MQTT_READ_REQUEST_TOPIC_MAX_BYTES: + return (f"MQTT read-request topic {topic!r} is longer than " + f"{MQTT_READ_REQUEST_TOPIC_MAX_BYTES} bytes") + levels = topic.split("/") + if levels[0] != MQTT_READ_REQUEST_NAMESPACE or len(levels) < 2: + return (f"MQTT read-request topic {topic!r} must start with " + f"{MQTT_READ_REQUEST_NAMESPACE}/, Venus's read-request namespace") + for level in levels[1:]: + if level == "+": + continue + if not _MQTT_TOPIC_LEVEL_RE.fullmatch(level) or "+" in level or "#" in level: + return (f"MQTT read-request topic {topic!r} has level {level!r}; a level is " + "printable ASCII without spaces, and a wildcard is a whole '+' level") + return "" diff --git a/tools/validate_manifest.py b/tools/validate_manifest.py index fdc64d2b..a7f0e30e 100644 --- a/tools/validate_manifest.py +++ b/tools/validate_manifest.py @@ -11,7 +11,8 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) -from manifest_parser import parse_yaml_simple, parse_tested_devices, parse_upstream_docs +from manifest_parser import (mqtt_read_request_topic_error, parse_tested_devices, + parse_upstream_docs, parse_yaml_simple) REQUIRED_FIELDS = ["name", "version", "tier", "protocol", "ders", "size_bytes", "connectivity"] @@ -126,6 +127,24 @@ def validate_manifest(yaml_path: Path, drivers_dir: Path) -> list[str]: if "none" in setup and len(setup) > 1: errors.append("setup 'none' cannot be combined with another requirement") + # Validate mqtt_read_request_topics: the read requests a read-only MQTT + # driver may publish, such as Victron's R/+/keepalive. The signed channel + # grants mqtt.publish for exactly these topics. + if "mqtt_read_request_topics" in data: + topics = data["mqtt_read_request_topics"] + if not isinstance(topics, list) or not topics: + errors.append("mqtt_read_request_topics must be a non-empty list: " + "omit the field, or list the topics") + else: + for topic in topics: + problem = mqtt_read_request_topic_error(topic) + if problem: + errors.append(problem) + if protocol != "mqtt": + errors.append("mqtt_read_request_topics is only for an MQTT driver") + if data.get("control") is not False: + errors.append("mqtt_read_request_topics is only for a read-only driver (control: false)") + # Validate size_bytes size = data.get("size_bytes", 0) if isinstance(size, int) and size < 0: From 02d0325ba8b82158e3b4aadb7587297ba37d5027 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Sun, 22 Nov 2026 13:52:40 +0100 Subject: [PATCH 2/2] feat(victron_mqtt): declare the Venus keep-alive as a read request (1.2.1) 1.2.0 sends R//keepalive every 30 s, but the signed channel's guard and FTW refuse every publish from this read-only driver, so the keep-alive never reached a GX from the channel. The manifest now lists R/+/keepalive in mqtt_read_request_topics. The channel's guard lets the driver publish to that topic alone, with at most 1 KiB of payload; an FTW Core with srcfl/ftw#2071 also limits it to six a minute. The driver still holds only mqtt.subscribe, so a Core without srcfl/ftw#2071 runs it as it runs 1.2.0 and refuses the request. The Lua source is unchanged. A changed artifact needs a new version, so 1.2.1. Refs srcfl/device-drivers#256 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Fredrik Ahlgren --- CHANGELOG.md | 18 ++++++++++++++++++ SUPPORT_STATUS.md | 4 ++-- devices.yaml | 10 +++++----- index.yaml | 2 +- manifests/victron_mqtt.yaml | 5 +++-- support-status.json | 2 +- tests/test_ftw_repository.py | 5 ++++- 7 files changed, 34 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ba3afd05..065e945b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,24 @@ ## [Unreleased] +### victron_mqtt 1.2.1 + +The manifest declares `R/+/keepalive` in `mqtt_read_request_topics`, so the +keep-alive 1.2.0 sends can reach a GX from the signed channel. Before, the +channel's guard and FTW refused every publish from this read-only driver, +and the GX went quiet 60 s after the last keep-alive from anyone. + +The channel's guard now lets the driver publish to that topic alone, with at +most 1 KiB of payload, and an FTW Core with srcfl/ftw#2071 allows six such +requests a minute. Every other publish is still refused. A read request is +not a write, so the driver still holds only `mqtt.subscribe`. The Lua source +is unchanged. + +A Core without srcfl/ftw#2071 runs this version as it runs 1.2.0: it refuses +the keep-alive, the driver logs one warning and keeps reading, and the GX +publishes only while another client keeps it awake. Not yet checked on a +real GX. + ### alphaess 1.3.0, kstar 1.3.0 Both drivers read the registers their vendor's own Modbus map gives diff --git a/SUPPORT_STATUS.md b/SUPPORT_STATUS.md index 13ea60fb..1d9daaba 100644 --- a/SUPPORT_STATUS.md +++ b/SUPPORT_STATUS.md @@ -176,8 +176,8 @@ Catalog source is not proof that a target can install or run a driver. | varta | 1.1.2 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | victron | 2.2.1 | ftw-core | not_assessed | — | not_recorded | not_assessed | | victron | 2.2.1 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | -| victron_mqtt | 1.2.0 | ftw-core | not_assessed | — | not_recorded | not_assessed | -| victron_mqtt | 1.2.0 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | +| victron_mqtt | 1.2.1 | ftw-core | not_assessed | — | not_recorded | not_assessed | +| victron_mqtt | 1.2.1 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | wallbox | 1.1.0 | ftw-core | not_assessed | — | not_recorded | not_assessed | | wallbox | 1.1.0 | blixt-l1 | not_assessed | — | not_recorded | not_assessed | | zap | 3.2.0 | ftw-core | not_assessed | — | not_recorded | not_assessed | diff --git a/devices.yaml b/devices.yaml index 1ffad574..94fc788a 100644 --- a/devices.yaml +++ b/devices.yaml @@ -2011,7 +2011,7 @@ manufacturers: control: false - protocol: mqtt driver: "victron_mqtt" - version: "1.2.0" + version: "1.2.1" ders: [pv, battery, meter] control: false firmware_versions: "" @@ -2027,7 +2027,7 @@ manufacturers: control: false - protocol: mqtt driver: "victron_mqtt" - version: "1.2.0" + version: "1.2.1" ders: [pv, battery, meter] control: false firmware_versions: "" @@ -2043,7 +2043,7 @@ manufacturers: control: false - protocol: mqtt driver: "victron_mqtt" - version: "1.2.0" + version: "1.2.1" ders: [pv, battery, meter] control: false firmware_versions: "" @@ -2059,7 +2059,7 @@ manufacturers: control: false - protocol: mqtt driver: "victron_mqtt" - version: "1.2.0" + version: "1.2.1" ders: [pv, battery, meter] control: false firmware_versions: "" @@ -2075,7 +2075,7 @@ manufacturers: control: false - protocol: mqtt driver: "victron_mqtt" - version: "1.2.0" + version: "1.2.1" ders: [pv, battery, meter] control: false firmware_versions: "" diff --git a/index.yaml b/index.yaml index 6facac32..4af9e0a8 100644 --- a/index.yaml +++ b/index.yaml @@ -806,7 +806,7 @@ drivers: size_bytes: 9392 sha256: "246369f9a66d9b667ea423cdc6c972d6a93e57828b1e8518e1a118ecb4b7c10a" - name: "victron_mqtt" - version: "1.2.0" + version: "1.2.1" tier: community protocol: mqtt connectivity: local diff --git a/manifests/victron_mqtt.yaml b/manifests/victron_mqtt.yaml index 9a8921df..1adc3b53 100644 --- a/manifests/victron_mqtt.yaml +++ b/manifests/victron_mqtt.yaml @@ -1,11 +1,12 @@ name: "victron_mqtt" -version: "1.2.0" +version: "1.2.1" tier: community author: "Sourceful Labs AB" protocol: mqtt connectivity: local ders: [pv, battery, meter] control: false +mqtt_read_request_topics: ["R/+/keepalive"] tested_devices: - manufacturer: "Victron Energy" model_family: "GX Devices" @@ -51,7 +52,7 @@ signature: "" bytecode_sha256: "" bytecode_signature: "" bytecode_size: 0 -changelog: "Send the Venus keep-alive every 30 s and ask for a full republish every 120 s; drop a system battery value a full republish leaves out." +changelog: "Declare the Venus keep-alive topic R/+/keepalive as a read request, so FTW lets the driver send it from the signed channel." upstream_docs: - url: "https://raw.githubusercontent.com/victronenergy/dbus-flashmq/master/README.md" diff --git a/support-status.json b/support-status.json index a7d14b07..d90e0b30 100644 --- a/support-status.json +++ b/support-status.json @@ -1808,7 +1808,7 @@ }, { "catalog_source": true, - "catalog_version": "1.2.0", + "catalog_version": "1.2.1", "driver_id": "victron_mqtt", "targets": { "blixt-l1": { diff --git a/tests/test_ftw_repository.py b/tests/test_ftw_repository.py index f9b686ec..0a8f2b11 100644 --- a/tests/test_ftw_repository.py +++ b/tests/test_ftw_repository.py @@ -1379,7 +1379,10 @@ def test_publishing_is_declared_or_it_does_not_happen( exempt.append(driver["id"]) else: assert "mqtt_read_request_topics" not in driver["metadata"], driver["id"] - assert exempt == [], f"unexpected drivers allowed to publish: {exempt}" + assert exempt == ["victron_mqtt"], f"unexpected drivers allowed to publish: {exempt}" + victron = next(d for d in manifest["drivers"] if d["id"] == "victron_mqtt") + assert victron["metadata"]["mqtt_read_request_topics"] == ["R/+/keepalive"] + assert victron["permissions"] == ["mqtt.subscribe"] def test_manifest_check_holds_read_request_topics_to_the_rule(tmp_path: Path) -> None: