diff --git a/.changeset/mqtt-read-requests.md b/.changeset/mqtt-read-requests.md new file mode 100644 index 000000000..b0066afbf --- /dev/null +++ b/.changeset/mqtt-read-requests.md @@ -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//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. diff --git a/docs/writing-a-driver.md b/docs/writing-a-driver.md index a91d6e0e2..9d58c3de7 100644 --- a/docs/writing-a-driver.md +++ b/docs/writing-a-driver.md @@ -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//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 diff --git a/go/internal/driverrepo/mqtt_read_request_policy_test.go b/go/internal/driverrepo/mqtt_read_request_policy_test.go new file mode 100644 index 000000000..3467bea13 --- /dev/null +++ b/go/internal/driverrepo/mqtt_read_request_policy_test.go @@ -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") + } +} diff --git a/go/internal/driverrepo/runtime_policy.go b/go/internal/driverrepo/runtime_policy.go index e64622ac7..cba06512d 100644 --- a/go/internal/driverrepo/runtime_policy.go +++ b/go/internal/driverrepo/runtime_policy.go @@ -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 } diff --git a/go/internal/drivers/catalog.go b/go/internal/drivers/catalog.go index 4bfbedf7b..7bc8c4da8 100644 --- a/go/internal/drivers/catalog.go +++ b/go/internal/drivers/catalog.go @@ -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"` diff --git a/go/internal/drivers/host.go b/go/internal/drivers/host.go index ee5609a55..1802e75bc 100644 --- a/go/internal/drivers/host.go +++ b/go/internal/drivers/host.go @@ -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. diff --git a/go/internal/drivers/lua.go b/go/internal/drivers/lua.go index c629d8ad0..66057ea95 100644 --- a/go/internal/drivers/lua.go +++ b/go/internal/drivers/lua.go @@ -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 } diff --git a/go/internal/drivers/mqtt_read_request.go b/go/internal/drivers/mqtt_read_request.go new file mode 100644 index 000000000..5ec280e66 --- /dev/null +++ b/go/internal/drivers/mqtt_read_request.go @@ -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//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//... 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 +} diff --git a/go/internal/drivers/read_only_mqtt_read_request_test.go b/go/internal/drivers/read_only_mqtt_read_request_test.go new file mode 100644 index 000000000..33c32079b --- /dev/null +++ b/go/internal/drivers/read_only_mqtt_read_request_test.go @@ -0,0 +1,339 @@ +package drivers + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + lua "github.com/yuin/gopher-lua" + + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// Victron's Venus OS publishes its values only while a client sends a read +// request to R//keepalive. A signed read-only driver that may +// subscribe may send the read requests its signed policy declares, and nothing +// else. It needs no write permission, so a Core that predates the field runs +// the same policy and refuses the request. + +func readRequestPolicy() *RuntimePolicy { + return &RuntimePolicy{ + PackageID: "com.sourceful.driver.victron_mqtt", Version: "1.2.0", + ArtifactSHA256: strings.Repeat("c", 64), RuntimeABI: "gopher-lua-source-v1", + HostAPIProfile: "sourceful.host/ftw-core/v1", ReadOnly: true, + Permissions: map[string]bool{"mqtt.subscribe": true}, + MQTTReadRequestTopics: []string{"R/+/keepalive"}, + } +} + +func TestReadOnlyPolicyValidatesMQTTReadRequests(t *testing.T) { + for _, tc := range []struct { + name string + change func(*RuntimePolicy) + ok bool + }{ + {"keepalive", func(*RuntimePolicy) {}, true}, + {"several_topics", func(p *RuntimePolicy) { + p.MQTTReadRequestTopics = []string{"R/+/keepalive", "R/+/system/0/Serial"} + }, true}, + {"literal_topic", func(p *RuntimePolicy) { p.MQTTReadRequestTopics = []string{"R/c0619ab1234/keepalive"} }, true}, + // Declared topics without mqtt.subscribe open nothing. + {"topics_without_subscribe", func(p *RuntimePolicy) { delete(p.Permissions, "mqtt.subscribe") }, true}, + // A read request needs no write permission, and mqtt.publish stays a + // write: refused with or without declared topics. + {"publish_with_topics", func(p *RuntimePolicy) { p.Permissions["mqtt.publish"] = true }, false}, + {"publish_without_topics", func(p *RuntimePolicy) { + p.Permissions["mqtt.publish"] = true + p.MQTTReadRequestTopics = nil + }, false}, + {"multi_level_wildcard", func(p *RuntimePolicy) { p.MQTTReadRequestTopics = []string{"R/#"} }, false}, + {"bare_hash", func(p *RuntimePolicy) { p.MQTTReadRequestTopics = []string{"#"} }, false}, + {"hash_inside_segment", func(p *RuntimePolicy) { p.MQTTReadRequestTopics = []string{"R/+/keep#alive"} }, false}, + {"partial_plus", func(p *RuntimePolicy) { p.MQTTReadRequestTopics = []string{"R/+x/keepalive"} }, false}, + {"wildcard_first_segment", func(p *RuntimePolicy) { p.MQTTReadRequestTopics = []string{"+/+/keepalive"} }, false}, + {"empty_segment", func(p *RuntimePolicy) { p.MQTTReadRequestTopics = []string{"R//keepalive"} }, false}, + {"trailing_slash", func(p *RuntimePolicy) { p.MQTTReadRequestTopics = []string{"R/+/"} }, false}, + {"leading_slash", func(p *RuntimePolicy) { p.MQTTReadRequestTopics = []string{"/R/keepalive"} }, false}, + {"broker_system_topic", func(p *RuntimePolicy) { p.MQTTReadRequestTopics = []string{"$SYS/+/keepalive"} }, false}, + // The first level must be R, Venus's read-request namespace. A literal + // first level is not enough: W/ is Venus's write namespace. + {"venus_write", func(p *RuntimePolicy) { + p.MQTTReadRequestTopics = []string{"W/+/settings/0/Settings/CGwacs/AcPowerSetPoint"} + }, false}, + {"write_namespace", func(p *RuntimePolicy) { p.MQTTReadRequestTopics = []string{"W/+/x"} }, false}, + {"other_namespace", func(p *RuntimePolicy) { p.MQTTReadRequestTopics = []string{"X/+/keepalive"} }, false}, + {"lowercase_namespace", func(p *RuntimePolicy) { p.MQTTReadRequestTopics = []string{"r/+/keepalive"} }, false}, + {"namespace_only", func(p *RuntimePolicy) { p.MQTTReadRequestTopics = []string{"R"} }, false}, + {"single_level", func(p *RuntimePolicy) { p.MQTTReadRequestTopics = []string{"keepalive"} }, false}, + {"space", func(p *RuntimePolicy) { p.MQTTReadRequestTopics = []string{"R/+/keep alive"} }, false}, + {"control_character", func(p *RuntimePolicy) { p.MQTTReadRequestTopics = []string{"R/\x00/keepalive"} }, false}, + {"empty_topic", func(p *RuntimePolicy) { p.MQTTReadRequestTopics = []string{"R/+/keepalive", ""} }, false}, + {"too_long", func(p *RuntimePolicy) { p.MQTTReadRequestTopics = []string{"R/+/" + strings.Repeat("a", 253)} }, false}, + // An invalid pattern is refused even where it could not be used, so a + // malformed signed entry fails at start instead of lying dormant. + {"invalid_topic_without_subscribe", func(p *RuntimePolicy) { + delete(p.Permissions, "mqtt.subscribe") + p.MQTTReadRequestTopics = []string{"R/#"} + }, false}, + {"not_read_only", func(p *RuntimePolicy) { p.ReadOnly = false }, false}, + } { + t.Run(tc.name, func(t *testing.T) { + policy := readRequestPolicy() + tc.change(policy) + err := policy.validate() + if tc.ok && err != nil { + t.Fatalf("validate refused %+v: %v", policy, err) + } + if !tc.ok && err == nil { + t.Fatalf("validate accepted %+v", policy) + } + }) + } + // The limit is exactly 256 bytes, the same as the published topic's. + policy := readRequestPolicy() + policy.MQTTReadRequestTopics = []string{"R/+/" + strings.Repeat("a", 252)} + if err := policy.validate(); err != nil { + t.Fatalf("a 256-byte pattern was refused: %v", err) + } +} + +func TestMQTTReadRequestMatchesSegmentBySegment(t *testing.T) { + for _, tc := range []struct { + topic string + ok bool + }{ + {"R/abc123/keepalive", true}, + {"R/c0619ab1234/keepalive", true}, + {"W/abc123/keepalive", false}, + {"R/abc123/keepalive/x", false}, + {"R/abc123", false}, + {"R/abc123/keepalivex", false}, + {"r/abc123/keepalive", false}, + {"R//keepalive", false}, + {"R/+/keepalive", false}, + {"R/#/keepalive", false}, + {"R/ab#c/keepalive", false}, + {"R/a b/keepalive", false}, + {"R/abc123/keepalive\x00", false}, + {"/R/abc123/keepalive", false}, + {"R/" + strings.Repeat("a", 244) + "/keepalive", true}, // 256 bytes + {"R/" + strings.Repeat("a", 245) + "/keepalive", false}, // 257 bytes + {"", false}, + } { + if got := matchMQTTReadRequest("R/+/keepalive", tc.topic); got != tc.ok { + t.Errorf("match(R/+/keepalive, %q) = %v, want %v", tc.topic, got, tc.ok) + } + } + if !matchMQTTReadRequest("R/c0619ab1234/keepalive", "R/c0619ab1234/keepalive") || + matchMQTTReadRequest("R/c0619ab1234/keepalive", "R/other/keepalive") { + t.Error("a literal pattern must match only itself") + } + // A pattern that validate would refuse matches nothing, so a policy that + // skipped validation still cannot open a wider path. + for _, pattern := range []string{"#", "R/#", "+/+/keepalive", "+/abc123/keepalive", "W/+/keepalive", "R/+x/keepalive", ""} { + if matchMQTTReadRequest(pattern, "R/abc123/keepalive") { + t.Errorf("invalid pattern %q matched", pattern) + } + } +} + +type readRequestClock struct{ now time.Time } + +func (c *readRequestClock) Now() time.Time { return c.now } + +// loadPublishingDriver runs a driver whose init sends each publish in order +// and keeps what host.mqtt_publish returned, "sent" when it returned nothing. +func loadPublishingDriver(t *testing.T, env *HostEnv, policy *RuntimePolicy, publishes ...string) *LuaDriver { + t.Helper() + source := `results = {} +function send(topic, payload) + results[#results + 1] = host.mqtt_publish(topic, payload) or "sent" +end +function driver_init(config) +` + strings.Join(publishes, "\n") + ` +end +function driver_poll() + send("R/abc123/keepalive", "") + return 1000 +end +` + path := filepath.Join(t.TempDir(), "publisher.lua") + if err := os.WriteFile(path, []byte(source), 0o600); err != nil { + t.Fatal(err) + } + driver, err := NewLuaDriverWithPolicy(path, env, policy) + if err != nil { + t.Fatal(err) + } + t.Cleanup(driver.Cleanup) + if err := driver.Init(context.Background(), map[string]interface{}{}); err != nil { + t.Fatal(err) + } + return driver +} + +func publishResults(driver *LuaDriver) []string { + results, ok := driver.L.GetGlobal("results").(*lua.LTable) + if !ok { + return nil + } + var out []string + for i := 1; i <= results.Len(); i++ { + out = append(out, results.RawGetInt(i).String()) + } + return out +} + +func TestManagedReadOnlyDriverSendsOnlyDeclaredReadRequests(t *testing.T) { + for _, tc := range []struct { + name string + send string + policy func(*RuntimePolicy) + env func(*HostEnv) + sent bool + refusal string + }{ + {name: "keepalive_suppress_republish", send: `send("R/abc123/keepalive", '{"keepalive-options":["suppress-republish"]}')`, sent: true}, + {name: "keepalive_full_republish", send: `send("R/abc123/keepalive", "")`, sent: true}, + {name: "payload_at_limit", send: `send("R/abc123/keepalive", string.rep("x", 1024))`, sent: true}, + {name: "write_request", send: `send("W/abc123/settings/0/Settings/CGwacs/AcPowerSetPoint", '{"value":-5000}')`, refusal: "read-only driver cannot write"}, + {name: "another_read_topic", send: `send("R/abc123/system/0/Serial", "")`, refusal: "read-only driver cannot write"}, + {name: "deeper_topic", send: `send("R/abc123/keepalive/x", "")`, refusal: "read-only driver cannot write"}, + {name: "multi_level_wildcard", send: `send("R/#", "")`, refusal: "read-only driver cannot write"}, + {name: "wildcard_in_segment", send: `send("R/#/keepalive", "")`, refusal: "read-only driver cannot write"}, + {name: "plus_in_topic", send: `send("R/+/keepalive", "")`, refusal: "read-only driver cannot write"}, + {name: "empty_portal_id", send: `send("R//keepalive", "")`, refusal: "read-only driver cannot write"}, + {name: "oversized_payload", send: `send("R/abc123/keepalive", string.rep("x", 1025))`, refusal: "1024 bytes"}, + {name: "no_subscribe_permission", send: `send("R/abc123/keepalive", "")`, + policy: func(p *RuntimePolicy) { delete(p.Permissions, "mqtt.subscribe") }, refusal: "read-only driver cannot write"}, + {name: "no_declared_topics", send: `send("R/abc123/keepalive", "")`, + policy: func(p *RuntimePolicy) { p.MQTTReadRequestTopics = nil }, refusal: "read-only driver cannot write"}, + // A read request still meets the gates every write meets: setup + // measurement mode holds it, and a fingerprint probe never sends one. + {name: "setup_measurement_mode", send: `send("R/abc123/keepalive", "")`, + env: func(env *HostEnv) { env.ControlBlocked = func() bool { return true } }, refusal: "setup measurement mode"}, + {name: "fingerprint_probe", send: `send("R/abc123/keepalive", "")`, + env: func(env *HostEnv) { env.ProbeReadOnly = true }, refusal: "fingerprint probe"}, + {name: "setup_measurement_mode_write", send: `send("W/abc123/settings/0/Settings/CGwacs/AcPowerSetPoint", "{}")`, + env: func(env *HostEnv) { env.ControlBlocked = func() bool { return true } }, refusal: "setup measurement mode"}, + } { + t.Run(tc.name, func(t *testing.T) { + mqtt := &fakeMQTT{} + env := NewHostEnv("victron_mqtt", telemetry.NewStore()).WithMQTT(mqtt) + if tc.env != nil { + tc.env(env) + } + policy := readRequestPolicy() + if tc.policy != nil { + tc.policy(policy) + } + driver := loadPublishingDriver(t, env, policy, tc.send) + got := publishResults(driver) + if len(got) != 1 { + t.Fatalf("results = %q", got) + } + published := mqtt.Published() + if tc.sent { + if got[0] != "sent" || len(published) != 1 { + t.Fatalf("read request refused: %q, published %d", got[0], len(published)) + } + return + } + if len(published) != 0 { + t.Fatalf("refused publish reached the broker: %+v", published) + } + if !strings.Contains(got[0], tc.refusal) { + t.Fatalf("refusal = %q, want it to mention %q", got[0], tc.refusal) + } + }) + } +} + +// A declared topic must not become a write channel by volume: six read +// requests a minute, counted per driver over the last 60 s. +func TestManagedReadRequestsAreRateLimited(t *testing.T) { + mqtt := &fakeMQTT{} + clock := &readRequestClock{now: time.Unix(1_800_000_000, 0)} + env := NewHostEnv("victron_mqtt", telemetry.NewStore()).WithMQTT(mqtt) + env.readRequests.now = clock.Now + sends := make([]string, 7) + for i := range sends { + sends[i] = `send("R/abc123/keepalive", "")` + } + driver := loadPublishingDriver(t, env, readRequestPolicy(), sends...) + got := publishResults(driver) + for i := 0; i < 6; i++ { + if got[i] != "sent" { + t.Fatalf("read request %d refused within the limit: %q", i+1, got[i]) + } + } + if !strings.Contains(got[6], "6 per minute") { + t.Fatalf("seventh read request in a minute = %q, want the rate refusal", got[6]) + } + if n := len(mqtt.Published()); n != 6 { + t.Fatalf("broker received %d read requests, want 6", n) + } + + // Still inside the window: refused, and a refusal does not count. + clock.now = clock.now.Add(59 * time.Second) + if _, err := driver.Poll(context.Background()); err != nil { + t.Fatal(err) + } + if got := publishResults(driver); !strings.Contains(got[7], "6 per minute") { + t.Fatalf("read request 59 s later = %q, want refused", got[7]) + } + // Once the oldest leaves the window, one more may go. + clock.now = clock.now.Add(1 * time.Second) + if _, err := driver.Poll(context.Background()); err != nil { + t.Fatal(err) + } + if got := publishResults(driver); got[8] != "sent" { + t.Fatalf("read request after the window = %q, want sent", got[8]) + } + // Victron's own cadence, one every 30 s, never meets the limit. + for i := 0; i < 20; i++ { + clock.now = clock.now.Add(30 * time.Second) + if _, err := driver.Poll(context.Background()); err != nil { + t.Fatal(err) + } + results := publishResults(driver) + if last := results[len(results)-1]; last != "sent" { + t.Fatalf("keep-alive every 30 s refused at %d: %q", i, last) + } + } +} + +// Bundled, local and control-capable signed drivers run without a policy and +// publish as before: any topic, any size, no rate limit. Setup measurement +// mode still blocks them. +func TestDriversWithoutPolicyPublishAsBefore(t *testing.T) { + mqtt := &fakeMQTT{} + env := NewHostEnv("bundled", telemetry.NewStore()).WithMQTT(mqtt) + sends := []string{ + `send("W/abc123/settings/0/Settings/CGwacs/AcPowerSetPoint", '{"value":-5000}')`, + `send("R/abc123/keepalive", string.rep("x", 2048))`, + } + for i := 0; i < 10; i++ { + sends = append(sends, `send("R/abc123/keepalive", "")`) + } + driver := loadPublishingDriver(t, env, nil, sends...) + for i, got := range publishResults(driver) { + if got != "sent" { + t.Fatalf("publish %d without a policy refused: %q", i+1, got) + } + } + if n := len(mqtt.Published()); n != len(sends) { + t.Fatalf("broker received %d publishes, want %d", n, len(sends)) + } + + blocked := &fakeMQTT{} + env = NewHostEnv("bundled", telemetry.NewStore()).WithMQTT(blocked) + env.ControlBlocked = func() bool { return true } + driver = loadPublishingDriver(t, env, nil, `send("R/abc123/keepalive", "")`) + if got := publishResults(driver); !strings.Contains(got[0], "setup measurement mode") || len(blocked.Published()) != 0 { + t.Fatalf("setup measurement mode no longer blocks a driver without a policy: %q", got) + } +} diff --git a/go/internal/drivers/runtime_policy.go b/go/internal/drivers/runtime_policy.go index b5f699022..2c8d9dc1f 100644 --- a/go/internal/drivers/runtime_policy.go +++ b/go/internal/drivers/runtime_policy.go @@ -32,6 +32,14 @@ type RuntimePolicy struct { // AuthPostPaths adds further exact sign-in paths, for a login that posts // more than one form (an OIDC identifier step, then a password step). AuthPostPaths []string + // MQTTReadRequestTopics are the MQTT topics a read-only driver with + // mqtt.subscribe may publish read requests to, because the device + // publishes its values only while a client asks (Victron's Venus OS wants + // R//keepalive). They grant no write permission: mqtt.publish + // stays refused. Each is a pattern whose "+" stands for one whole topic + // level; see mqtt_read_request.go. Empty unless the signed metadata + // declares them. + MQTTReadRequestTopics []string // ConfigSecrets comes from verified signed metadata. A read-only OAuth // driver may persist only these keys in its own secret namespace. ConfigSecrets []string @@ -111,6 +119,14 @@ func (p *RuntimePolicy) validate() error { return fmt.Errorf("read-only runtime has write-capable permission %q", permission) } } + // Declared read requests need no write permission; mqtt.publish stays + // refused above. Refuse a bad pattern here, so a malformed signed entry + // fails at start. + for _, pattern := range p.MQTTReadRequestTopics { + if err := validMQTTReadRequestPattern(pattern); err != nil { + return err + } + } return nil }