Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .changeset/mqtt-read-requests.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
"ftw": minor
---

A read-only MQTT driver from the signed channel may now send the read
requests its signed policy declares, such as Victron's
`R/<portal ID>/keepalive`.

Venus OS on a Victron GX publishes its values only while a client sends that
keep-alive. FTW refused every publish from a signed read-only driver, so
`victron_mqtt` from the channel went stale on a GX with no other MQTT client.

Core now lets such a driver publish to a topic its signed manifest lists, and
to nothing else. The grant needs `mqtt.subscribe` and no write permission, so
an older Core runs the same signed driver read-only and refuses the request.
A listed topic must start with `R/`, Venus's read-request namespace; a `+`
stands for one whole level, and `#` is refused. Each request carries at most
1 KiB, and a driver may send six a minute. Setup measurement mode holds read
requests as it holds writes. Every other publish, Modbus write and POST from a
read-only driver is still refused. Bundled, local and control drivers behave
as before.
12 changes: 12 additions & 0 deletions docs/writing-a-driver.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,18 @@ A read-only driver may POST only to the sign-in paths its `DRIVER` block
declares: `auth_post_path` for one path, or `auth_post_paths` when the login
posts more than one form. The host matches each exactly.

A read-only MQTT driver installed from the signed channel may publish only to
the read-request topics its signed policy declares. These are for a device
that reports only while a client asks: Victron's Venus OS publishes while it
receives `R/<portal ID>/keepalive`. The channel takes the topics from the
driver's catalog manifest (`mqtt_read_request_topics`). They need
`mqtt.subscribe` and no write permission; `mqtt.publish` stays refused. A topic
must start with `R/`, Venus's read-request namespace; `+` stands for one whole
level, and `#` is refused. Each request carries at most 1 KiB, and a driver may
send six a minute. Setup measurement mode and fingerprint probes hold read
requests as they hold writes. A bundled or local driver runs without a policy
and publishes as before.

A driver with an opt-in write path names it in its `DRIVER` block —
`write_capabilities = { "solar_pv" }` for a driver that feeds a heat pump's
own solar-surplus input. The Settings UI offers a switch for a path it
Expand Down
123 changes: 123 additions & 0 deletions go/internal/driverrepo/mqtt_read_request_policy_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package driverrepo

import (
"context"
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"sync/atomic"
"testing"

"github.com/srcfl/ftw/go/internal/config"
"github.com/srcfl/ftw/go/internal/drivers"
"github.com/srcfl/ftw/go/internal/state"
)

// The read-request topics a read-only MQTT driver may publish to come from the
// signed manifest, as its sign-in paths do. Nothing outside the signed payload
// can add or widen one.
func TestSignedManifestCarriesMQTTReadRequestTopics(t *testing.T) {
public, private, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
fixture := &signedFixture{private: private}
var tamper atomic.Bool
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/manifest.json":
raw := fixture.envelope(t)
if tamper.Load() {
// Widen the topics after signing, leaving the signature.
var envelope ManifestEnvelope
if err := json.Unmarshal(raw, &envelope); err != nil {
t.Error(err)
}
envelope.Payload = json.RawMessage(strings.Replace(string(envelope.Payload),
`"R/+/keepalive"`, `"W/+/+"`, 1))
raw, _ = json.Marshal(envelope)
}
_, _ = w.Write(raw)
case "/demo.lua":
fixture.mu.Lock()
defer fixture.mu.Unlock()
_, _ = w.Write(fixture.driver)
default:
http.NotFound(w, r)
}
}))
defer server.Close()
fixture.setVersion(server.URL, "1.0.0")
fixture.mu.Lock()
fixture.manifest.Repository = "https://github.com/srcfl/device-drivers"
fixture.manifest.Drivers[0].ReadOnly = true
// The channel grants no write permission for read requests.
fixture.manifest.Drivers[0].Permissions = []string{"mqtt.subscribe"}
fixture.manifest.Drivers[0].Metadata.ReadOnly = true
fixture.manifest.Drivers[0].Metadata.MQTTReadRequestTopics = []string{"R/+/keepalive"}
fixture.mu.Unlock()

dir := t.TempDir()
store, err := state.Open(filepath.Join(dir, "state.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
cfg := &config.DeviceRepository{Enabled: true, Repositories: []config.DriverRepositorySource{{
ID: "ftw-official", ManifestURL: server.URL + "/manifest.json", Enabled: true,
AllowInsecure: true, TrustedKeys: map[string]string{"test": base64.StdEncoding.EncodeToString(public)},
}}}
manager := New(cfg, dir, store)
if err := manager.Refresh(context.Background(), "ftw-official"); err != nil {
t.Fatal(err)
}
if _, err := manager.Install(context.Background(), "ftw-official", "demo", "1.0.0"); err != nil {
t.Fatal(err)
}
driverCfg := config.Driver{Name: "demo", Lua: filepath.Join(manager.ActiveDir(), "demo.lua")}
checkPolicy := func(m *Manager) {
t.Helper()
policy, err := m.RuntimePolicy(driverCfg)
if err != nil || policy == nil || !policy.IsReadOnly() || policy.Permissions["mqtt.publish"] ||
!policy.Permissions["mqtt.subscribe"] ||
len(policy.MQTTReadRequestTopics) != 1 || policy.MQTTReadRequestTopics[0] != "R/+/keepalive" {
t.Fatalf("signed read-request policy = %+v, %v", policy, err)
}
// The Lua constructor validates the policy; the grant must pass it.
luaDriver, err := drivers.NewLuaDriverWithPolicy(driverCfg.Lua, drivers.NewHostEnv("demo", nil), policy)
if err != nil {
t.Fatal(err)
}
luaDriver.Cleanup()
}
checkPolicy(manager)

// A manifest altered after signing is refused, and the verified policy
// stays as it was.
tamper.Store(true)
if err := manager.Refresh(context.Background(), "ftw-official"); err == nil {
t.Fatal("a manifest whose topics changed after signing was accepted")
}
checkPolicy(manager)
tamper.Store(false)

// A signed entry with a topic Core refuses yields a policy the Lua
// constructor rejects, so the driver does not start.
manager.mu.Lock()
manifest := manager.manifests["ftw-official"]
manifest.Drivers[0].Metadata.MQTTReadRequestTopics = []string{"R/#"}
manager.manifests["ftw-official"] = manifest
manager.mu.Unlock()
policy, err := manager.RuntimePolicy(driverCfg)
if err != nil || policy == nil {
t.Fatalf("policy = %+v, %v", policy, err)
}
if _, err := drivers.NewLuaDriverWithPolicy(driverCfg.Lua, drivers.NewHostEnv("demo", nil), policy); err == nil {
t.Fatal("a policy with a multi-level wildcard read request was accepted")
}
}
7 changes: 5 additions & 2 deletions go/internal/driverrepo/runtime_policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,10 @@ func (m *Manager) directManifestRuntimePolicy(
// is the same as having no exemption at all.
AuthPostPath: matched.Metadata.AuthPostPath,
AuthPostPaths: append([]string(nil), matched.Metadata.AuthPostPaths...),
ConfigSecrets: append([]string(nil), matched.Metadata.ConfigSecrets...),
Capabilities: append([]string(nil), matched.Metadata.Capabilities...),
// The same holds for MQTT read requests: only the topics the signed
// manifest names, which validate checks before the driver starts.
MQTTReadRequestTopics: append([]string(nil), matched.Metadata.MQTTReadRequestTopics...),
ConfigSecrets: append([]string(nil), matched.Metadata.ConfigSecrets...),
Capabilities: append([]string(nil), matched.Metadata.Capabilities...),
}, nil
}
4 changes: 4 additions & 0 deletions go/internal/drivers/catalog.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ type CatalogEntry struct {
AuthPostPath string `json:"auth_post_path,omitempty"`
// AuthPostPaths lists further sign-in paths for a multi-step login.
AuthPostPaths []string `json:"auth_post_paths,omitempty"`
// MQTTReadRequestTopics are the topics a read-only MQTT driver may
// publish read requests to, such as Victron's R/+/keepalive. Only the
// signed channel's metadata sets them; see RuntimePolicy.
MQTTReadRequestTopics []string `json:"mqtt_read_request_topics,omitempty"`
// ReadOnly means the driver never accepts dispatch commands. The catalog
// UI uses it to avoid presenting battery capacity as a control opt-in.
ReadOnly bool `json:"read_only,omitempty"`
Expand Down
3 changes: 3 additions & 0 deletions go/internal/drivers/host.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,9 @@ type HostEnv struct {
// RuntimePolicy is nil for bundled, local and control-capable signed
// drivers. A signed read-only policy denies writes in every phase.
RuntimePolicy *RuntimePolicy
// readRequests counts the declared MQTT read requests this driver sent;
// see allowMQTTPublish.
readRequests mqttReadRequestLimiter
// ProbeReadOnly denies every mutating host verb. Fingerprint probes set
// this so a buggy driver_fingerprint cannot reconfigure hardware: bundled
// drivers otherwise have allowWrite as a no-op.
Expand Down
2 changes: 1 addition & 1 deletion go/internal/drivers/lua.go
Original file line number Diff line number Diff line change
Expand Up @@ -852,7 +852,7 @@ func registerHost(L *lua.LState, env *HostEnv) {
L.Push(lua.LString("no mqtt capability"))
return 1
}
if err := env.allowWrite("mqtt.publish"); err != nil {
if err := env.allowMQTTPublish(topic, len(payload)); err != nil {
L.Push(lua.LString(err.Error()))
return 1
}
Expand Down
170 changes: 170 additions & 0 deletions go/internal/drivers/mqtt_read_request.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
package drivers

import (
"errors"
"fmt"
"strings"
"sync"
"time"
)

// A read request asks a device to report and changes nothing on it. Venus OS
// on a Victron GX publishes its MQTT values only while some client sends one
// to R/<portal ID>/keepalive at least once a minute (victronenergy/dbus-flashmq
// README, "Keep-alive"). Without it the GX goes quiet and the driver goes
// stale, so a read-only driver that may subscribe may send the read requests
// its signed policy names. A read request needs no write permission, so a
// signed policy carries no mqtt.publish for it, and a Core that does not know
// this field runs the same driver read-only, refusing the request. The host
// holds each request to these bounds:
//
// - topic: a declared pattern, matched level by level, where "+" stands for
// one whole non-empty level and "#" is refused. The first level must be
// exactly "R", Venus's read-request namespace. A literal first level alone
// would not be enough: W/+/settings/0/Settings/CGwacs/AcPowerSetPoint is a
// valid pattern and a Venus write, and a third-party repository's key,
// not ours, may have signed the manifest. Topics are printable ASCII
// without spaces, at most 256 bytes.
// - payload: at most 1 KiB. A Venus keep-alive is empty or a JSON option
// list of about 45 bytes.
// - rate: six per driver in any 60 s. Venus needs one a minute and its own
// example sends one every 30 s.
//
// That caps a declared topic at about 130 bytes a second, too little to carry
// anything but the request.
//
// A read request still waits out setup measurement mode and is never sent
// from a fingerprint probe, as every write does; see allowMQTTPublish.
const (
// mqttReadRequestNamespace is the first level every read-request topic
// has: Venus OS reads R/<portal ID>/... as a request to report.
mqttReadRequestNamespace = "R"
maxMQTTReadRequestTopicBytes = 256
maxMQTTReadRequestPayloadBytes = 1024
mqttReadRequestsPerWindow = 6
mqttReadRequestWindow = time.Minute
)

// validMQTTReadRequestPattern reports why pattern cannot be a declared read
// request, or nil when it can.
func validMQTTReadRequestPattern(pattern string) error {
if pattern == "" || len(pattern) > maxMQTTReadRequestTopicBytes {
return fmt.Errorf("MQTT read-request topic %q must be 1 to %d bytes", pattern, maxMQTTReadRequestTopicBytes)
}
levels := strings.Split(pattern, "/")
if levels[0] != mqttReadRequestNamespace || len(levels) < 2 {
return fmt.Errorf("MQTT read-request topic %q must start with %s/, Venus's read-request namespace", pattern, mqttReadRequestNamespace)
}
for _, level := range levels[1:] {
if level != "+" && !validMQTTTopicLevel(level) {
return fmt.Errorf("MQTT read-request topic %q has level %q; a level is printable ASCII without spaces, and a wildcard is a whole \"+\" level", pattern, level)
}
}
return nil
}

// validMQTTTopicLevel reports whether level is non-empty printable ASCII with
// no space and no wildcard character.
func validMQTTTopicLevel(level string) bool {
if level == "" {
return false
}
for i := 0; i < len(level); i++ {
if c := level[i]; c <= ' ' || c > '~' || c == '+' || c == '#' {
return false
}
}
return true
}

// matchMQTTReadRequest reports whether topic is one the pattern declares. An
// invalid pattern matches nothing.
func matchMQTTReadRequest(pattern, topic string) bool {
if validMQTTReadRequestPattern(pattern) != nil || len(topic) > maxMQTTReadRequestTopicBytes {
return false
}
want := strings.Split(pattern, "/")
got := strings.Split(topic, "/")
if len(want) != len(got) {
return false
}
for i := range want {
if !validMQTTTopicLevel(got[i]) || want[i] != "+" && want[i] != got[i] {
return false
}
}
return true
}

// allowsMQTTReadRequest reports whether this read-only policy grants a read
// request to topic: it may subscribe and declares a pattern topic matches. It
// checks each pattern as validate does, so a policy that reached a host
// without validation grants nothing more.
func (p *RuntimePolicy) allowsMQTTReadRequest(topic string) bool {
if !p.IsReadOnly() || !p.Permissions["mqtt.subscribe"] {
return false
}
for _, pattern := range p.MQTTReadRequestTopics {
if matchMQTTReadRequest(pattern, topic) {
return true
}
}
return false
}

// allowMQTTPublish gates host.mqtt_publish. A publish from a signed read-only
// driver to a topic its policy declares is a read request, not a write, so it
// passes although the driver may not write; the payload and rate bounds above
// hold it instead. Every other publish, and every publish from a driver
// without a policy, goes through allowWrite unchanged.
//
// A read request still meets allowWrite's other gates. Setup measurement mode
// holds it, so a GX with no other MQTT client goes quiet until setup ends, and
// a fingerprint probe never sends one. DeviceReadOnly is left out: it means
// another client owns the driver's Modbus endpoint, and a read request goes to
// the MQTT broker, not to that endpoint.
func (h *HostEnv) allowMQTTPublish(topic string, payloadBytes int) error {
if !h.RuntimePolicy.allowsMQTTReadRequest(topic) {
return h.allowWrite("mqtt.publish")
}
if h.ControlBlocked != nil && h.ControlBlocked() {
return errors.New("mqtt.publish: setup measurement mode blocks device writes")
}
if h.ProbeReadOnly {
return errors.New("mqtt.publish: fingerprint probe cannot write")
}
if payloadBytes > maxMQTTReadRequestPayloadBytes {
return fmt.Errorf("mqtt.publish: read request payload is %d bytes; the limit is %d bytes",
payloadBytes, maxMQTTReadRequestPayloadBytes)
}
return h.readRequests.take()
}

// mqttReadRequestLimiter counts the read requests one driver sent in the last
// window. A refused request does not count.
type mqttReadRequestLimiter struct {
mu sync.Mutex
sent []time.Time
now func() time.Time // nil means time.Now; tests set it
}

func (l *mqttReadRequestLimiter) take() error {
l.mu.Lock()
defer l.mu.Unlock()
now := time.Now()
if l.now != nil {
now = l.now()
}
kept := l.sent[:0]
for _, at := range l.sent {
if now.Sub(at) < mqttReadRequestWindow {
kept = append(kept, at)
}
}
l.sent = kept
if len(l.sent) >= mqttReadRequestsPerWindow {
return fmt.Errorf("mqtt.publish: read requests are limited to %d per minute", mqttReadRequestsPerWindow)
}
l.sent = append(l.sent, now)
return nil
}
Loading
Loading