From 5a58808f20af14e754c6b402c4aec4cfbefcd4a2 Mon Sep 17 00:00:00 2001 From: Sebastian Norling <1932208+Bazze@users.noreply.github.com> Date: Thu, 21 May 2026 15:22:25 +0200 Subject: [PATCH 1/7] feat(machinery/config): add ONVIFMotion capture flag Adds Capture.ONVIFMotion and the matching AGENT_CAPTURE_ONVIF_MOTION environment override. When set to 'true', the agent will open an ONVIF event stream against the configured camera and route Motion events into the existing HandleMotion channel (wired up in the next commit). Defaults to empty (disabled), so existing deployments using the pixel-diff motion detector see no behaviour change. --- machinery/src/config/main.go | 3 +++ machinery/src/models/config.go | 8 ++++++++ 2 files changed, 11 insertions(+) diff --git a/machinery/src/config/main.go b/machinery/src/config/main.go index 3b93828..b5fad8b 100644 --- a/machinery/src/config/main.go +++ b/machinery/src/config/main.go @@ -377,6 +377,9 @@ func applyAgentEnvVars(configuration *models.Configuration, prefix string, apply case "AGENT_CAPTURE_MOTION": configuration.Config.Capture.Motion = value break + case "AGENT_CAPTURE_ONVIF_MOTION": + configuration.Config.Capture.ONVIFMotion = value + break case "AGENT_CAPTURE_SNAPSHOTS": configuration.Config.Capture.Snapshots = value break diff --git a/machinery/src/models/config.go b/machinery/src/models/config.go index 152c535..7c70862 100644 --- a/machinery/src/models/config.go +++ b/machinery/src/models/config.go @@ -75,6 +75,14 @@ type Capture struct { Fragmented string `json:"fragmented,omitempty" bson:"fragmented,omitempty"` FragmentedDuration int64 `json:"fragmentedduration,omitempty" bson:"fragmentedduration,omitempty"` PixelChangeThreshold *int `json:"pixelChangeThreshold,omitempty"` + // ONVIFMotion routes the camera's ONVIF motion events into the + // agent's motion-triggered recording pipeline. When "true" the + // agent opens an event/stream against the configured ONVIF + // endpoint and forwards Motion+Active events to HandleMotion. + // Requires Capture.IPCamera.ONVIFXAddr / ONVIFUsername / + // ONVIFPassword to be set. Default empty (disabled) keeps the + // existing pixel-diff motion detection as the only source. + ONVIFMotion string `json:"onvif_motion,omitempty" bson:"onvif_motion,omitempty"` } // IPCamera configuration, such as the RTSP url of the IPCamera and the FPS. From ed85261c8e162b2251a9fc78db84026efd29bfb4 Mon Sep 17 00:00:00 2001 From: Sebastian Norling <1932208+Bazze@users.noreply.github.com> Date: Thu, 21 May 2026 15:24:15 +0200 Subject: [PATCH 2/7] feat(machinery/onvif): consume ONVIF events via stream package MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Resolves kerberos-io/agent#173. When Capture.ONVIFMotion='true' the agent opens a stream.NewStream against the configured ONVIF endpoint and forwards Motion+Active events to HandleMotion, so AXIS cameras (and any other ONVIF-conformant device) can drive motion-triggered recording without relying on the pixel-diff detector. Why this shape -------------- Maintainer @cedricve's direction on #194 was 'extend the ONVIF library first to expose a go channel and hide the protocol complexity'. That work landed in kerberos-io/onvif (event/stream sub-package); the agent integration is now a thin consumer: connect to the device, wrap it in NewStream, range over Events, push Motion events at the existing HandleMotion channel. Design choices -------------- * New file machinery/src/onvif/events.go keeps the new code separate from the existing PTZ/IO-focused onvif/main.go so reviewers can read it without scrolling. * Opt-in via Capture.ONVIFMotion. Defaults preserve the current pixel-diff behaviour so nothing changes for existing users. * DispatchEvent only fires on StateActive — the leading edge. Motion STOP requires the recorder state machine to accept an explicit stop signal which today does not exist; tracked as a follow-up so this first PR stays small. * Non-blocking send to HandleMotion: drop ONVIF motion events when the channel is full rather than block the stream goroutine and starve subscription renewal. * Error logging routes by typed-error category from the library: ErrRecreateFailed is loud (camera may be offline), ErrPullFailed and ErrRenewFailed are debug-level (auto-recovers). * Goroutine lifetime tied to *communication.Context, the same cancellable context the agent uses to restart on config change. Not in this commit (intentionally deferred to follow-ups) --------------------------------------------------------- * Motion STOP wiring into capture/main.go's recorder state machine. * Replacing the ad-hoc CreatePullPointSubscription / GetEventMessages polling in cloud/Cloud.go with a stream consumer for DigitalInput and DigitalOutput events. The current code keeps working; the stream is purely additive. * Removing the temporary 'replace' directive on github.com/kerberos-io/onvif once the event/stream changes are tagged upstream. --- machinery/src/components/kerberos.go | 5 ++ machinery/src/onvif/events.go | 124 +++++++++++++++++++++++++++ 2 files changed, 129 insertions(+) create mode 100644 machinery/src/onvif/events.go diff --git a/machinery/src/components/kerberos.go b/machinery/src/components/kerberos.go index 350966b..5637824 100644 --- a/machinery/src/components/kerberos.go +++ b/machinery/src/components/kerberos.go @@ -341,6 +341,11 @@ func RunAgent(configDirectory string, configuration *models.Configuration, commu communication.HandleONVIF = make(chan models.OnvifAction, 10) go onvif.HandleONVIFActions(configuration, communication) + // Handle ONVIF event stream — opt-in via Capture.ONVIFMotion="true". + // Stops when the agent's shared context is cancelled. The function + // is a no-op if ONVIFMotion is not enabled. + go onvif.HandleONVIFEventStream(*communication.Context, configuration, communication) + communication.HandleAudio = make(chan models.AudioDataPartial, 10) if rtspBackChannelClient.HasBackChannel { communication.HasBackChannel = true diff --git a/machinery/src/onvif/events.go b/machinery/src/onvif/events.go new file mode 100644 index 0000000..bcd5fb3 --- /dev/null +++ b/machinery/src/onvif/events.go @@ -0,0 +1,124 @@ +package onvif + +import ( + "context" + "errors" + "time" + + "github.com/kerberos-io/agent/machinery/src/log" + "github.com/kerberos-io/agent/machinery/src/models" + "github.com/kerberos-io/onvif/event/stream" +) + +// HandleONVIFEventStream opens an event/stream against the configured +// ONVIF camera and routes Motion events into communication.HandleMotion +// so they trigger the existing recording pipeline. +// +// The goroutine returns when the stream's context is cancelled (the +// caller closes ctx when shutting the agent down) or when the camera +// is not configured for ONVIF. +// +// This is a feature behind Capture.ONVIFMotion. When the flag is empty +// or "false" the goroutine returns immediately, preserving the +// pixel-diff motion detector as the only source. +func HandleONVIFEventStream(ctx context.Context, configuration *models.Configuration, communication *models.Communication) { + log.Log.Debug("onvif.HandleONVIFEventStream(): started") + defer log.Log.Debug("onvif.HandleONVIFEventStream(): finished") + + cfg := configuration.Config.Capture + if cfg.ONVIFMotion != "true" { + return + } + camera := cfg.IPCamera + if camera.ONVIFXAddr == "" { + log.Log.Info("onvif.HandleONVIFEventStream(): ONVIFMotion enabled but ONVIFXAddr is empty; nothing to do") + return + } + + device, _, err := ConnectToOnvifDevice(&camera) + if err != nil { + log.Log.Error("onvif.HandleONVIFEventStream(): connect: " + err.Error()) + return + } + + s, err := stream.NewStream(ctx, device, stream.Options{ + DeviceID: configuration.Name, + }) + if err != nil { + log.Log.Error("onvif.HandleONVIFEventStream(): open stream: " + err.Error()) + return + } + defer func() { + if err := s.Close(); err != nil { + log.Log.Debug("onvif.HandleONVIFEventStream(): close: " + err.Error()) + } + }() + + log.Log.Info("onvif.HandleONVIFEventStream(): consuming events for " + configuration.Name) + + for { + select { + case <-ctx.Done(): + return + case ev, ok := <-s.Events(): + if !ok { + return + } + dispatchEvent(ev, configuration, communication) + case e, ok := <-s.Errors(): + if !ok { + return + } + logStreamError(e) + } + } +} + +// dispatchEvent routes a single decoded ONVIF Event into the agent's +// existing channels. Motion-active events become MotionDataPartial on +// HandleMotion, matching what the pixel-diff detector emits. Other +// event kinds are logged at debug for now; a follow-up will wire +// DigitalInput/Output into the existing inputOutputDeviceMap. +func dispatchEvent(ev stream.Event, configuration *models.Configuration, communication *models.Communication) { + if ev.Kind != stream.KindMotion { + log.Log.Debug("onvif.dispatchEvent(): non-motion event " + ev.Kind.String() + " topic=" + ev.Topic) + return + } + // We only fire on the leading edge — StateActive. Motion-stop + // handling is a follow-up that needs the recorder state machine + // to accept an explicit stop signal; today the recorder uses a + // fixed PostRecording timeout. + if ev.State != stream.StateActive { + return + } + if configuration.Config.Capture.Recording == "false" { + return + } + dataToPass := models.MotionDataPartial{ + Timestamp: time.Now().Unix(), + NumberOfChanges: 0, // ONVIF doesn't quantify motion area. + } + select { + case communication.HandleMotion <- dataToPass: + default: + log.Log.Debug("onvif.dispatchEvent(): HandleMotion full, dropping ONVIF motion event") + } +} + +// logStreamError logs at a level matching the severity. Recreate +// failures are louder because they usually mean the camera is offline. +func logStreamError(e error) { + var recreate stream.ErrRecreateFailed + var pull stream.ErrPullFailed + var renew stream.ErrRenewFailed + switch { + case errors.As(e, &recreate): + log.Log.Error("onvif.HandleONVIFEventStream(): subscription recreate failed (camera may be offline): " + recreate.Err.Error()) + case errors.As(e, &renew): + log.Log.Debug("onvif.HandleONVIFEventStream(): renew failed (will recover via pull/recreate): " + renew.Err.Error()) + case errors.As(e, &pull): + log.Log.Debug("onvif.HandleONVIFEventStream(): pull failed (will retry): " + pull.Err.Error()) + default: + log.Log.Info("onvif.HandleONVIFEventStream(): stream error: " + e.Error()) + } +} From 4f2a96b5e12aa82d61253dcca4f6e18b9876fc49 Mon Sep 17 00:00:00 2001 From: Sebastian Norling <1932208+Bazze@users.noreply.github.com> Date: Thu, 21 May 2026 17:40:24 +0200 Subject: [PATCH 3/7] fix(machinery/onvif): harden event-stream dispatch and add TDD coverage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses the critical and important findings from the second review of the agent integration. TDD followed locally: tests were written first and confirmed RED against the previous implementation before the fix turned them GREEN. Critical fixes -------------- * Shutdown-race panic (concurrency P0): the 3s gap between the agent's ctx cancel and close(HandleMotion) was reachable by a buffered event delivered after cancel, where dispatchEvent's send-with-default select would panic on the closed channel. dispatchEvent now takes ctx, has a pre-check after the kind/state/recording filters, and the send select includes a <-ctx.Done() arm. Pinned by TestDispatchEvent_CtxCancelledAndHandleMotionClosed_DoesNotPanic (asserts NotPanics; current code without the fix panics). * No retry on initial connect (Go P0 + ops P1): previously the goroutine exited permanently if ConnectToOnvifDevice or stream.NewStream failed at agent start — a brief boot-time DNS or network blip silently disabled ONVIF until restart. Construction is now wrapped in a retry loop with exponential backoff (1s -> 5min), matching what cloud.HandleHeartBeat does for its ONVIF connection attempts. The library handles in-stream recovery already; this covers the gap the library cannot see. * Strict 'true' match (Go P0): isONVIFMotionEnabled now normalises case and trims whitespace, so 'True', 'TRUE', ' true ' all enable the feature. Pinned by TestIsONVIFMotionEnabled_CaseAndWhitespace. Important fixes --------------- * Empty DeviceID fallback (Go P1): resolveDeviceID falls back from configuration.Name to camera.ONVIFXAddr to 'unknown' so log lines and metrics always have a useful identifier. Pinned by TestResolveDeviceID_FallbackChain. * Recovery log (ops P1): the run loop tracks a 'recovering' flag set when an ErrPullFailed/ErrRecreateFailed lands on Errors and cleared on the first successful Event. Logs an Info 'event stream recovered' line so on-call operators can see error streaks clear, instead of waking up to ERROR with no closure. * Misconfig log bumped Info -> Warning so the 'ONVIFXAddr is empty' line stands out from the heartbeat noise. Tests ----- events_test.go covers the dispatch contract end-to-end: * Motion+Active -> HandleMotion (happy path). * Motion+Inactive ignored (motion-stop is a documented follow-up). * Non-motion kinds ignored. * Recording='false' gates the send. * Full HandleMotion drops rather than blocks. * Ctx-cancelled + closed HandleMotion does not panic. * isONVIFMotionEnabled handles case and whitespace. * resolveDeviceID fallback chain. go.mod / go.sum: testify moved from indirect to direct dependency. Deferred (out of scope for this commit, tracked as follow-ups): * Heartbeat surface for ONVIF state ('disabled|running|failed') — requires a Cloud.go change beyond this integration's scope. * OTel span/metric for stream lifecycle. * Runtime toggle without restart (config-reload). * Replace-directive layout documentation — separate docs commit. --- machinery/go.mod | 3 + machinery/src/onvif/events.go | 158 +++++++++++++++++++----- machinery/src/onvif/events_test.go | 186 +++++++++++++++++++++++++++++ 3 files changed, 317 insertions(+), 30 deletions(-) create mode 100644 machinery/src/onvif/events_test.go diff --git a/machinery/go.mod b/machinery/go.mod index 353bf3d..2630af7 100644 --- a/machinery/go.mod +++ b/machinery/go.mod @@ -32,6 +32,7 @@ require ( github.com/pion/rtp v1.8.19 github.com/pion/webrtc/v4 v4.1.2 github.com/sirupsen/logrus v1.9.3 + github.com/stretchr/testify v1.10.0 github.com/swaggo/files v1.0.1 github.com/swaggo/gin-swagger v1.6.0 github.com/swaggo/swag v1.16.4 @@ -58,6 +59,7 @@ require ( github.com/clbanning/mxj v1.8.4 // indirect github.com/clbanning/mxj/v2 v2.7.0 // indirect github.com/cloudwego/base64x v0.1.5 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect github.com/elastic/go-windows v1.0.2 // indirect github.com/elgs/gostrgen v0.0.0-20161222160715-9d61ae07eeae // indirect github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 // indirect @@ -108,6 +110,7 @@ require ( github.com/pion/stun/v3 v3.0.0 // indirect github.com/pion/transport/v3 v3.0.7 // indirect github.com/pion/turn/v4 v4.0.0 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect github.com/prometheus/procfs v0.15.1 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.12 // indirect diff --git a/machinery/src/onvif/events.go b/machinery/src/onvif/events.go index bcd5fb3..6c2434c 100644 --- a/machinery/src/onvif/events.go +++ b/machinery/src/onvif/events.go @@ -3,6 +3,7 @@ package onvif import ( "context" "errors" + "strings" "time" "github.com/kerberos-io/agent/machinery/src/log" @@ -10,43 +11,78 @@ import ( "github.com/kerberos-io/onvif/event/stream" ) +// initialBackoff and maxBackoff bound the wait between successive +// attempts to (re)open the event stream after a transient construction +// failure (camera reachable but ONVIF not yet ready, brief network blip +// at agent boot, etc.). The library itself handles in-stream reconnect; +// these guards cover the initial-connect path the library cannot see. +const ( + initialBackoff = time.Second + maxBackoff = 5 * time.Minute +) + // HandleONVIFEventStream opens an event/stream against the configured // ONVIF camera and routes Motion events into communication.HandleMotion // so they trigger the existing recording pipeline. // -// The goroutine returns when the stream's context is cancelled (the -// caller closes ctx when shutting the agent down) or when the camera -// is not configured for ONVIF. +// The goroutine retries construction with exponential backoff on +// transient failure (camera reachable later, credentials reloaded, +// network restored). It exits cleanly when ctx is cancelled. // -// This is a feature behind Capture.ONVIFMotion. When the flag is empty -// or "false" the goroutine returns immediately, preserving the -// pixel-diff motion detector as the only source. +// This is a feature behind Capture.ONVIFMotion. When the flag is not +// enabled the goroutine returns immediately, preserving the pixel-diff +// motion detector as the only source. Toggling the flag at runtime +// requires an agent restart (Capture.ONVIFMotion is read once at +// goroutine start). func HandleONVIFEventStream(ctx context.Context, configuration *models.Configuration, communication *models.Communication) { log.Log.Debug("onvif.HandleONVIFEventStream(): started") defer log.Log.Debug("onvif.HandleONVIFEventStream(): finished") - cfg := configuration.Config.Capture - if cfg.ONVIFMotion != "true" { + if !isONVIFMotionEnabled(configuration.Config.Capture.ONVIFMotion) { return } - camera := cfg.IPCamera - if camera.ONVIFXAddr == "" { - log.Log.Info("onvif.HandleONVIFEventStream(): ONVIFMotion enabled but ONVIFXAddr is empty; nothing to do") + if configuration.Config.Capture.IPCamera.ONVIFXAddr == "" { + log.Log.Warning("onvif.HandleONVIFEventStream(): ONVIFMotion enabled but ONVIFXAddr is empty; nothing to do") return } + backoff := initialBackoff + for { + if ctx.Err() != nil { + return + } + recoverable := runStreamOnce(ctx, configuration, communication) + if !recoverable { + return + } + if !sleepCtx(ctx, backoff) { + return + } + backoff *= 2 + if backoff > maxBackoff { + backoff = maxBackoff + } + } +} + +// runStreamOnce opens one event stream and consumes from it until ctx +// is cancelled or the stream exits. Returns true when the caller +// should retry construction (transient failure), false on clean +// ctx-driven shutdown. +func runStreamOnce(ctx context.Context, configuration *models.Configuration, communication *models.Communication) (retry bool) { + camera := configuration.Config.Capture.IPCamera + device, _, err := ConnectToOnvifDevice(&camera) if err != nil { log.Log.Error("onvif.HandleONVIFEventStream(): connect: " + err.Error()) - return + return true } - s, err := stream.NewStream(ctx, device, stream.Options{ - DeviceID: configuration.Name, - }) + deviceID := resolveDeviceID(configuration.Name, camera.ONVIFXAddr) + s, err := stream.NewStream(ctx, device, stream.Options{DeviceID: deviceID}) if err != nil { log.Log.Error("onvif.HandleONVIFEventStream(): open stream: " + err.Error()) - return + return true } defer func() { if err := s.Close(); err != nil { @@ -54,21 +90,33 @@ func HandleONVIFEventStream(ctx context.Context, configuration *models.Configura } }() - log.Log.Info("onvif.HandleONVIFEventStream(): consuming events for " + configuration.Name) + log.Log.Info("onvif.HandleONVIFEventStream(): consuming events for " + deviceID) + // recovering tracks whether we're in a degraded period so the + // first successful event after an error streak can log a recovery + // line for on-call operators. + var recovering bool for { select { case <-ctx.Done(): - return + return false case ev, ok := <-s.Events(): if !ok { - return + // Lib's run goroutine exited — happens only on ctx + // cancel today (library handles its own reconnect), + // so treat as clean shutdown. + return false } - dispatchEvent(ev, configuration, communication) + if recovering { + log.Log.Info("onvif.HandleONVIFEventStream(): event stream recovered for " + deviceID) + recovering = false + } + dispatchEvent(ctx, ev, configuration, communication) case e, ok := <-s.Errors(): if !ok { - return + return false } + recovering = true logStreamError(e) } } @@ -76,17 +124,20 @@ func HandleONVIFEventStream(ctx context.Context, configuration *models.Configura // dispatchEvent routes a single decoded ONVIF Event into the agent's // existing channels. Motion-active events become MotionDataPartial on -// HandleMotion, matching what the pixel-diff detector emits. Other -// event kinds are logged at debug for now; a follow-up will wire -// DigitalInput/Output into the existing inputOutputDeviceMap. -func dispatchEvent(ev stream.Event, configuration *models.Configuration, communication *models.Communication) { +// HandleMotion, matching what the pixel-diff detector emits. +// +// The ctx pre-check is the shutdown-race guard: between cancel() and +// close(communication.HandleMotion) the agent leaves a ~3s window in +// which a stale event could otherwise attempt to send on a closed +// channel and panic. If ctx is done we drop the event silently — the +// recording pipeline is already winding down. +func dispatchEvent(ctx context.Context, ev stream.Event, configuration *models.Configuration, communication *models.Communication) { if ev.Kind != stream.KindMotion { log.Log.Debug("onvif.dispatchEvent(): non-motion event " + ev.Kind.String() + " topic=" + ev.Topic) return } - // We only fire on the leading edge — StateActive. Motion-stop - // handling is a follow-up that needs the recorder state machine - // to accept an explicit stop signal; today the recorder uses a + // Leading-edge only. Motion-stop wiring into the recorder state + // machine is tracked as a follow-up; today the recorder uses a // fixed PostRecording timeout. if ev.State != stream.StateActive { return @@ -94,11 +145,20 @@ func dispatchEvent(ev stream.Event, configuration *models.Configuration, communi if configuration.Config.Capture.Recording == "false" { return } + if ctx.Err() != nil { + return + } + // Timestamp in seconds matches what computervision/main.go emits; + // downstream consumers (capture/main.go) tolerate either second- + // or millisecond-precision. dataToPass := models.MotionDataPartial{ Timestamp: time.Now().Unix(), - NumberOfChanges: 0, // ONVIF doesn't quantify motion area. + NumberOfChanges: 0, // ONVIF does not quantify motion area. } select { + case <-ctx.Done(): + // Closes the residual race: ctx cancelled between the + // pre-check above and reaching this select. case communication.HandleMotion <- dataToPass: default: log.Log.Debug("onvif.dispatchEvent(): HandleMotion full, dropping ONVIF motion event") @@ -106,7 +166,9 @@ func dispatchEvent(ev stream.Event, configuration *models.Configuration, communi } // logStreamError logs at a level matching the severity. Recreate -// failures are louder because they usually mean the camera is offline. +// failures are loud because they usually mean the camera is offline; +// pull/renew failures are debug because the library recovers from them +// automatically. func logStreamError(e error) { var recreate stream.ErrRecreateFailed var pull stream.ErrPullFailed @@ -122,3 +184,39 @@ func logStreamError(e error) { log.Log.Info("onvif.HandleONVIFEventStream(): stream error: " + e.Error()) } } + +// isONVIFMotionEnabled returns true when the Capture.ONVIFMotion flag +// is set to "true" with case and whitespace tolerance. The rest of the +// Capture struct uses string flags so we keep the same shape; the +// difference is that ONVIFMotion defaults to disabled (opt-in), unlike +// Recording / Motion / Snapshots which default to enabled. +func isONVIFMotionEnabled(v string) bool { + return strings.EqualFold(strings.TrimSpace(v), "true") +} + +// resolveDeviceID returns the most useful identifier for the camera +// in stream events, logs and metrics. Falls back from configuration +// name (the operator-supplied label) to the ONVIF endpoint to a +// constant placeholder so log lines always have something to grep. +func resolveDeviceID(configName, xaddr string) string { + if n := strings.TrimSpace(configName); n != "" { + return n + } + if x := strings.TrimSpace(xaddr); x != "" { + return x + } + return "unknown" +} + +// sleepCtx blocks for d or until ctx is cancelled. Returns false if +// ctx was cancelled, true if the full duration elapsed. +func sleepCtx(ctx context.Context, d time.Duration) bool { + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + return false + case <-t.C: + return true + } +} diff --git a/machinery/src/onvif/events_test.go b/machinery/src/onvif/events_test.go new file mode 100644 index 0000000..3d86174 --- /dev/null +++ b/machinery/src/onvif/events_test.go @@ -0,0 +1,186 @@ +package onvif + +import ( + "context" + "testing" + "time" + + "github.com/kerberos-io/agent/machinery/src/models" + "github.com/kerberos-io/onvif/event/stream" + "github.com/stretchr/testify/assert" +) + +func makeConfig(recording, onvifMotion, name string) *models.Configuration { + return &models.Configuration{ + Name: name, + Config: models.Config{ + Capture: models.Capture{ + Recording: recording, + ONVIFMotion: onvifMotion, + }, + }, + } +} + +func makeCommunication(buffer int) *models.Communication { + return &models.Communication{ + HandleMotion: make(chan models.MotionDataPartial, buffer), + } +} + +// --- dispatchEvent --------------------------------------------------- + +func TestDispatchEvent_MotionActive_SendsToHandleMotion(t *testing.T) { + cfg := makeConfig("true", "true", "cam-1") + comm := makeCommunication(1) + ev := stream.Event{Kind: stream.KindMotion, State: stream.StateActive} + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + dispatchEvent(ctx, ev, cfg, comm) + + select { + case m := <-comm.HandleMotion: + assert.NotZero(t, m.Timestamp) + case <-time.After(time.Second): + t.Fatal("expected motion data on HandleMotion") + } +} + +func TestDispatchEvent_MotionInactive_DoesNotSend(t *testing.T) { + cfg := makeConfig("true", "true", "cam-1") + comm := makeCommunication(1) + ev := stream.Event{Kind: stream.KindMotion, State: stream.StateInactive} + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + dispatchEvent(ctx, ev, cfg, comm) + + select { + case <-comm.HandleMotion: + t.Fatal("inactive motion must not reach HandleMotion (motion-stop is a follow-up)") + case <-time.After(100 * time.Millisecond): + } +} + +func TestDispatchEvent_NonMotionKindIgnored(t *testing.T) { + cfg := makeConfig("true", "true", "cam-1") + comm := makeCommunication(1) + ev := stream.Event{Kind: stream.KindDigitalInput, State: stream.StateActive} + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + dispatchEvent(ctx, ev, cfg, comm) + + select { + case <-comm.HandleMotion: + t.Fatal("non-motion kinds must not reach HandleMotion") + case <-time.After(100 * time.Millisecond): + } +} + +func TestDispatchEvent_RecordingDisabled_DoesNotSend(t *testing.T) { + cfg := makeConfig("false", "true", "cam-1") + comm := makeCommunication(1) + ev := stream.Event{Kind: stream.KindMotion, State: stream.StateActive} + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + dispatchEvent(ctx, ev, cfg, comm) + + select { + case <-comm.HandleMotion: + t.Fatal("Recording=false must gate the send (matches computervision behaviour)") + case <-time.After(100 * time.Millisecond): + } +} + +func TestDispatchEvent_HandleMotionFull_DropsRatherThanBlocks(t *testing.T) { + cfg := makeConfig("true", "true", "cam-1") + // Pre-fill the buffer so the next send would block. + comm := &models.Communication{HandleMotion: make(chan models.MotionDataPartial, 1)} + comm.HandleMotion <- models.MotionDataPartial{} + ev := stream.Event{Kind: stream.KindMotion, State: stream.StateActive} + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + done := make(chan struct{}) + go func() { + dispatchEvent(ctx, ev, cfg, comm) + close(done) + }() + + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("dispatchEvent must drop when HandleMotion is full, not block") + } +} + +func TestDispatchEvent_CtxCancelledAndHandleMotionClosed_DoesNotPanic(t *testing.T) { + // Regression for the shutdown race: between cancel() and + // close(HandleMotion) the agent leaves a 3s window. If dispatchEvent + // runs in that window AFTER the channel is closed, a non-protected + // send would panic. The ctx pre-check must short-circuit before the + // send is attempted. + cfg := makeConfig("true", "true", "cam-1") + comm := &models.Communication{HandleMotion: make(chan models.MotionDataPartial, 1)} + close(comm.HandleMotion) + ev := stream.Event{Kind: stream.KindMotion, State: stream.StateActive} + + ctx, cancel := context.WithCancel(context.Background()) + cancel() // already cancelled, matching the shutdown sequence + + assert.NotPanics(t, func() { + dispatchEvent(ctx, ev, cfg, comm) + }) +} + +// --- isONVIFMotionEnabled -------------------------------------------- + +func TestIsONVIFMotionEnabled_CaseAndWhitespace(t *testing.T) { + tests := []struct { + in string + want bool + }{ + {"true", true}, + {"True", true}, + {"TRUE", true}, + {" true", true}, + {"true ", true}, + {" true ", true}, + {"false", false}, + {"False", false}, + {"", false}, + {"yes", false}, + {"1", false}, + } + for _, tc := range tests { + t.Run(tc.in, func(t *testing.T) { + assert.Equal(t, tc.want, isONVIFMotionEnabled(tc.in)) + }) + } +} + +// --- resolveDeviceID ------------------------------------------------- + +func TestResolveDeviceID_FallbackChain(t *testing.T) { + tests := []struct { + name string + cfgName string + xaddr string + want string + }{ + {"name_set", "front-door", "192.168.1.10", "front-door"}, + {"name_empty_xaddr_set", "", "192.168.1.10", "192.168.1.10"}, + {"name_whitespace_only_xaddr_set", " ", "192.168.1.10", "192.168.1.10"}, + {"both_empty", "", "", "unknown"}, + {"name_with_trailing_whitespace", "cam-2 ", "192.168.1.10", "cam-2"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, resolveDeviceID(tc.cfgName, tc.xaddr)) + }) + } +} From 357cc719a5fdf70e5f1a7889a4663b90da17d323 Mon Sep 17 00:00:00 2001 From: Sebastian Norling <1932208+Bazze@users.noreply.github.com> Date: Thu, 21 May 2026 18:44:01 +0200 Subject: [PATCH 4/7] docs(machinery/onvif): trim event-stream comments to WHY MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Audit against CLAUDE.md's 'default to no comments; only when WHY is non-obvious'. Net ~30 lines removed. Dropped (rot-prone or redundant) -------------------------------- * 'matching what the pixel-diff detector emits' — references a sibling file's behaviour. * 'Timestamp in seconds matches what computervision/main.go emits; downstream consumers (capture/main.go) tolerate...' — both cross-file references; classic 'will rot when the sibling changes'. * 'Motion-stop wiring into the recorder state machine is tracked as a follow-up; today the recorder uses a fixed PostRecording timeout' — PR-description content masquerading as a code comment. * 'happens only on ctx cancel today (library handles its own reconnect)' — 'today' is a red flag; either drop or assert via test, not narrate. * dispatchEvent's first paragraph restating what the function does. * runStreamOnce's first sentence (WHAT). * isONVIFMotionEnabled's reference to sibling Capture fields ('unlike Recording / Motion / Snapshots which default to enabled'). Kept (real WHYs) ---------------- * The shutdown-race rationale on dispatchEvent's ctx guards. * logStreamError's severity-mapping rationale. * The library-handles-reconnect-but-not-initial-connect rationale for the backoff constants. * The recovering-flag rationale (on-call ops use case). * The flag-read-once invariant on HandleONVIFEventStream. --- machinery/src/onvif/events.go | 82 +++++++++++------------------------ 1 file changed, 25 insertions(+), 57 deletions(-) diff --git a/machinery/src/onvif/events.go b/machinery/src/onvif/events.go index 6c2434c..c2c8e74 100644 --- a/machinery/src/onvif/events.go +++ b/machinery/src/onvif/events.go @@ -11,29 +11,22 @@ import ( "github.com/kerberos-io/onvif/event/stream" ) -// initialBackoff and maxBackoff bound the wait between successive -// attempts to (re)open the event stream after a transient construction -// failure (camera reachable but ONVIF not yet ready, brief network blip -// at agent boot, etc.). The library itself handles in-stream reconnect; -// these guards cover the initial-connect path the library cannot see. +// The library handles in-stream reconnect; these guards cover the +// initial-connect path the library cannot see. const ( initialBackoff = time.Second maxBackoff = 5 * time.Minute ) // HandleONVIFEventStream opens an event/stream against the configured -// ONVIF camera and routes Motion events into communication.HandleMotion -// so they trigger the existing recording pipeline. +// ONVIF camera and routes Motion events into communication.HandleMotion. // -// The goroutine retries construction with exponential backoff on -// transient failure (camera reachable later, credentials reloaded, -// network restored). It exits cleanly when ctx is cancelled. -// -// This is a feature behind Capture.ONVIFMotion. When the flag is not -// enabled the goroutine returns immediately, preserving the pixel-diff -// motion detector as the only source. Toggling the flag at runtime -// requires an agent restart (Capture.ONVIFMotion is read once at -// goroutine start). +// Behind the Capture.ONVIFMotion flag; the goroutine returns +// immediately when not enabled. The flag is read once at start, so +// toggling at runtime requires an agent restart. On transient +// construction failure (camera not yet ready at boot, brief network +// blip, credential reload) the goroutine retries with exponential +// backoff. Exits when ctx is cancelled. func HandleONVIFEventStream(ctx context.Context, configuration *models.Configuration, communication *models.Communication) { log.Log.Debug("onvif.HandleONVIFEventStream(): started") defer log.Log.Debug("onvif.HandleONVIFEventStream(): finished") @@ -65,10 +58,8 @@ func HandleONVIFEventStream(ctx context.Context, configuration *models.Configura } } -// runStreamOnce opens one event stream and consumes from it until ctx -// is cancelled or the stream exits. Returns true when the caller -// should retry construction (transient failure), false on clean -// ctx-driven shutdown. +// runStreamOnce returns true when the caller should retry construction +// (transient failure), false on clean ctx-driven shutdown. func runStreamOnce(ctx context.Context, configuration *models.Configuration, communication *models.Communication) (retry bool) { camera := configuration.Config.Capture.IPCamera @@ -92,9 +83,9 @@ func runStreamOnce(ctx context.Context, configuration *models.Configuration, com log.Log.Info("onvif.HandleONVIFEventStream(): consuming events for " + deviceID) - // recovering tracks whether we're in a degraded period so the - // first successful event after an error streak can log a recovery - // line for on-call operators. + // recovering = the first successful event after an error streak + // logs a recovery line so on-call operators see the clear-of- + // condition for the ERROR they were paged on. var recovering bool for { select { @@ -102,9 +93,6 @@ func runStreamOnce(ctx context.Context, configuration *models.Configuration, com return false case ev, ok := <-s.Events(): if !ok { - // Lib's run goroutine exited — happens only on ctx - // cancel today (library handles its own reconnect), - // so treat as clean shutdown. return false } if recovering { @@ -122,23 +110,16 @@ func runStreamOnce(ctx context.Context, configuration *models.Configuration, com } } -// dispatchEvent routes a single decoded ONVIF Event into the agent's -// existing channels. Motion-active events become MotionDataPartial on -// HandleMotion, matching what the pixel-diff detector emits. +// dispatchEvent routes motion-active events to HandleMotion. // -// The ctx pre-check is the shutdown-race guard: between cancel() and -// close(communication.HandleMotion) the agent leaves a ~3s window in -// which a stale event could otherwise attempt to send on a closed -// channel and panic. If ctx is done we drop the event silently — the -// recording pipeline is already winding down. +// The ctx pre-check + ctx-in-select guards a shutdown race: the agent +// closes HandleMotion shortly after cancelling ctx, and a stale event +// reaching the send would otherwise panic on a closed channel. func dispatchEvent(ctx context.Context, ev stream.Event, configuration *models.Configuration, communication *models.Communication) { if ev.Kind != stream.KindMotion { log.Log.Debug("onvif.dispatchEvent(): non-motion event " + ev.Kind.String() + " topic=" + ev.Topic) return } - // Leading-edge only. Motion-stop wiring into the recorder state - // machine is tracked as a follow-up; today the recorder uses a - // fixed PostRecording timeout. if ev.State != stream.StateActive { return } @@ -148,27 +129,21 @@ func dispatchEvent(ctx context.Context, ev stream.Event, configuration *models.C if ctx.Err() != nil { return } - // Timestamp in seconds matches what computervision/main.go emits; - // downstream consumers (capture/main.go) tolerate either second- - // or millisecond-precision. dataToPass := models.MotionDataPartial{ Timestamp: time.Now().Unix(), NumberOfChanges: 0, // ONVIF does not quantify motion area. } select { case <-ctx.Done(): - // Closes the residual race: ctx cancelled between the - // pre-check above and reaching this select. case communication.HandleMotion <- dataToPass: default: log.Log.Debug("onvif.dispatchEvent(): HandleMotion full, dropping ONVIF motion event") } } -// logStreamError logs at a level matching the severity. Recreate -// failures are loud because they usually mean the camera is offline; -// pull/renew failures are debug because the library recovers from them -// automatically. +// logStreamError logs at a level matching severity: recreate is loud +// because it usually means the camera is offline; pull and renew are +// debug because the library recovers from them automatically. func logStreamError(e error) { var recreate stream.ErrRecreateFailed var pull stream.ErrPullFailed @@ -185,19 +160,13 @@ func logStreamError(e error) { } } -// isONVIFMotionEnabled returns true when the Capture.ONVIFMotion flag -// is set to "true" with case and whitespace tolerance. The rest of the -// Capture struct uses string flags so we keep the same shape; the -// difference is that ONVIFMotion defaults to disabled (opt-in), unlike -// Recording / Motion / Snapshots which default to enabled. func isONVIFMotionEnabled(v string) bool { return strings.EqualFold(strings.TrimSpace(v), "true") } -// resolveDeviceID returns the most useful identifier for the camera -// in stream events, logs and metrics. Falls back from configuration -// name (the operator-supplied label) to the ONVIF endpoint to a -// constant placeholder so log lines always have something to grep. +// resolveDeviceID falls back from operator-supplied name to ONVIF +// endpoint to a constant placeholder so log lines always have +// something to grep. func resolveDeviceID(configName, xaddr string) string { if n := strings.TrimSpace(configName); n != "" { return n @@ -208,8 +177,7 @@ func resolveDeviceID(configName, xaddr string) string { return "unknown" } -// sleepCtx blocks for d or until ctx is cancelled. Returns false if -// ctx was cancelled, true if the full duration elapsed. +// sleepCtx returns false if ctx was cancelled, true if d elapsed. func sleepCtx(ctx context.Context, d time.Duration) bool { t := time.NewTimer(d) defer t.Stop() From 57cfc90c4b80a5c6551d8c07e3d1b6c21517e138 Mon Sep 17 00:00:00 2001 From: "T. Tradesman" <184814242+ttradesman@users.noreply.github.com> Date: Thu, 23 Jul 2026 11:52:51 +0200 Subject: [PATCH 5/7] feat(onvif): log the topic that triggered a recording MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit dispatchEvent logged only rejected events, so the topic that actually started a recording was invisible — the only way to identify it was to enumerate every rejected topic and reason about what was left. On a camera emitting 18 distinct topics that is not a diagnosis. Log the Kind and topic on the dispatch path too, at debug, matching the reject line's shape so both sides of the decision grep the same way. --- machinery/src/onvif/events.go | 4 +++ machinery/src/onvif/events_test.go | 44 ++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/machinery/src/onvif/events.go b/machinery/src/onvif/events.go index c2c8e74..5761614 100644 --- a/machinery/src/onvif/events.go +++ b/machinery/src/onvif/events.go @@ -129,6 +129,10 @@ func dispatchEvent(ctx context.Context, ev stream.Event, configuration *models.C if ctx.Err() != nil { return } + // The topic that actually started a recording is the one on-call + // needs; the reject path below already names the ones that didn't. + log.Log.Debug("onvif.dispatchEvent(): recording trigger " + ev.Kind.String() + " topic=" + ev.Topic) + dataToPass := models.MotionDataPartial{ Timestamp: time.Now().Unix(), NumberOfChanges: 0, // ONVIF does not quantify motion area. diff --git a/machinery/src/onvif/events_test.go b/machinery/src/onvif/events_test.go index 3d86174..2fd0682 100644 --- a/machinery/src/onvif/events_test.go +++ b/machinery/src/onvif/events_test.go @@ -1,12 +1,14 @@ package onvif import ( + "bytes" "context" "testing" "time" "github.com/kerberos-io/agent/machinery/src/models" "github.com/kerberos-io/onvif/event/stream" + "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" ) @@ -79,6 +81,48 @@ func TestDispatchEvent_NonMotionKindIgnored(t *testing.T) { } } +// captureDebugLog redirects logrus to a buffer at debug level for the +// duration of a test and returns what was written. It mutates package +// globals, so callers must not run in parallel. +func captureDebugLog(t *testing.T) *bytes.Buffer { + t.Helper() + var buf bytes.Buffer + prevOut, prevLevel := logrus.StandardLogger().Out, logrus.GetLevel() + logrus.SetOutput(&buf) + logrus.SetLevel(logrus.DebugLevel) + t.Cleanup(func() { + logrus.SetOutput(prevOut) + logrus.SetLevel(prevLevel) + }) + return &buf +} + +// TestDispatchEvent_LogsTheTriggeringTopic — a dispatched event is what +// actually starts a recording, so its topic is the one an operator needs +// when a camera records for the wrong reason (or the right reason and +// nobody can prove which). Rejected events were already logged; without +// this the triggering topic is only knowable by elimination. +func TestDispatchEvent_LogsTheTriggeringTopic(t *testing.T) { + buf := captureDebugLog(t) + + cfg := makeConfig("true", "true", "cam-1") + comm := makeCommunication(1) + ev := stream.Event{ + Kind: stream.KindMotion, + State: stream.StateActive, + Topic: "tns1:RuleEngine/tnsaxis:VMD3/vmd3_video_1", + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + dispatchEvent(ctx, ev, cfg, comm) + + assert.Contains(t, buf.String(), "tns1:RuleEngine/tnsaxis:VMD3/vmd3_video_1", + "the dispatched event's topic must appear in the log") + assert.Contains(t, buf.String(), "Motion", + "the dispatched event's Kind must appear in the log") +} + func TestDispatchEvent_RecordingDisabled_DoesNotSend(t *testing.T) { cfg := makeConfig("false", "true", "cam-1") comm := makeCommunication(1) From 91194f5c1a85da199d0ec640bf43aacc137ba2ca Mon Sep 17 00:00:00 2001 From: "T. Tradesman" <184814242+ttradesman@users.noreply.github.com> Date: Thu, 23 Jul 2026 13:05:24 +0200 Subject: [PATCH 6/7] fix(onvif): ignore subscription state replays as recording triggers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A camera replays the current state of every property topic as PropertyOperation=Initialized whenever a pull-point subscription is created. dispatchEvent looked only at Kind and State, so any motion property that happened to be active at that moment counted as a fresh trigger — meaning every reconnect restarts a recording, and a flapping subscription manufactures motion with no motion. Observed on a camera whose pull-point was being recreated every ~18s: each recreate replayed ~90 property events, and once real motion made the VMD property active the replays kept re-triggering it. Rejects Initialized specifically rather than accepting only Changed. PropertyOperation is optional per WS-Notification and absent on many non-property events, which decode reports as PropertyUnknown; those are real events and must still trigger. --- machinery/src/onvif/events.go | 7 +++++ machinery/src/onvif/events_test.go | 48 ++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/machinery/src/onvif/events.go b/machinery/src/onvif/events.go index 5761614..aff71d1 100644 --- a/machinery/src/onvif/events.go +++ b/machinery/src/onvif/events.go @@ -123,6 +123,13 @@ func dispatchEvent(ctx context.Context, ev stream.Event, configuration *models.C if ev.State != stream.StateActive { return } + // A camera replays every property topic's current state as + // Initialized on each new subscription, so treating that as a + // trigger lets a flapping pull-point manufacture motion. + if ev.Operation == stream.PropertyInitialized { + log.Log.Debug("onvif.dispatchEvent(): subscription state replay, not a trigger: topic=" + ev.Topic) + return + } if configuration.Config.Capture.Recording == "false" { return } diff --git a/machinery/src/onvif/events_test.go b/machinery/src/onvif/events_test.go index 2fd0682..597cc5b 100644 --- a/machinery/src/onvif/events_test.go +++ b/machinery/src/onvif/events_test.go @@ -123,6 +123,54 @@ func TestDispatchEvent_LogsTheTriggeringTopic(t *testing.T) { "the dispatched event's Kind must appear in the log") } +// TestDispatchEvent_PropertyOperation — a camera replays the current +// state of every property topic as Initialized whenever a pull-point +// subscription is created. If that counts as a trigger, every +// reconnect restarts a recording for any motion property that happens +// to be active, and a flapping subscription manufactures motion out of +// nothing. Only reject Initialized specifically: PropertyOperation is +// optional per WS-Notification and absent on many non-property events, +// which decode reports as PropertyUnknown. +func TestDispatchEvent_PropertyOperation(t *testing.T) { + tests := []struct { + name string + op stream.PropertyOperation + wantSend bool + }{ + {"changed is a real transition", stream.PropertyChanged, true}, + {"absent attribute still counts", stream.PropertyUnknown, true}, + {"initialized is a subscription state replay", stream.PropertyInitialized, false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cfg := makeConfig("true", "true", "cam-1") + comm := makeCommunication(1) + ev := stream.Event{ + Kind: stream.KindMotion, + State: stream.StateActive, + Operation: tt.op, + Topic: "tns1:RuleEngine/tnsaxis:VMD3/vmd3_video_1", + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + dispatchEvent(ctx, ev, cfg, comm) + + select { + case <-comm.HandleMotion: + if !tt.wantSend { + t.Fatalf("%v must not trigger a recording", tt.op) + } + case <-time.After(100 * time.Millisecond): + if tt.wantSend { + t.Fatalf("%v must trigger a recording", tt.op) + } + } + }) + } +} + func TestDispatchEvent_RecordingDisabled_DoesNotSend(t *testing.T) { cfg := makeConfig("false", "true", "cam-1") comm := makeCommunication(1) From b26f0190c62deb8be9a41c66b40102f2d758a782 Mon Sep 17 00:00:00 2001 From: "T. Tradesman" <184814242+ttradesman@users.noreply.github.com> Date: Thu, 23 Jul 2026 14:30:08 +0200 Subject: [PATCH 7/7] fix(onvif): only real transitions trigger, and sanitise logged topics MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three defects in the dispatch path. Deleted was still a trigger. The Initialized guard was a denylist of one value, so a property removal with an active-looking payload passed straight through. Both Initialized and Deleted are announcements about a property, not motion starting, so accept the transitions instead: Changed, and Unknown for the events that omit the optional attribute. ev.Topic reached the log unmodified. It is camera-controlled, unbounded and unfiltered, and logrus's coloured text formatter — the default — writes the message without quoting, so an embedded newline forges whole log entries. A compromised camera could fabricate ERROR lines or spoof another device's id in the logs an operator is reading to diagnose that camera. Escape control characters and bound the length; the reject path logs every event received, so an oversized topic was also a cheap way to evict a container's retained history. The trigger line was logged before the send, so an event dropped on a full channel or at shutdown left a line claiming a recording that never started. Log it in the send case. --- machinery/src/onvif/events.go | 42 ++++++++++--- machinery/src/onvif/events_test.go | 97 ++++++++++++++++++++++++++++++ 2 files changed, 130 insertions(+), 9 deletions(-) diff --git a/machinery/src/onvif/events.go b/machinery/src/onvif/events.go index aff71d1..005694e 100644 --- a/machinery/src/onvif/events.go +++ b/machinery/src/onvif/events.go @@ -3,6 +3,7 @@ package onvif import ( "context" "errors" + "strconv" "strings" "time" @@ -116,18 +117,16 @@ func runStreamOnce(ctx context.Context, configuration *models.Configuration, com // closes HandleMotion shortly after cancelling ctx, and a stale event // reaching the send would otherwise panic on a closed channel. func dispatchEvent(ctx context.Context, ev stream.Event, configuration *models.Configuration, communication *models.Communication) { + topic := sanitiseTopic(ev.Topic) if ev.Kind != stream.KindMotion { - log.Log.Debug("onvif.dispatchEvent(): non-motion event " + ev.Kind.String() + " topic=" + ev.Topic) + log.Log.Debug("onvif.dispatchEvent(): non-motion event " + ev.Kind.String() + " topic=" + topic) return } if ev.State != stream.StateActive { return } - // A camera replays every property topic's current state as - // Initialized on each new subscription, so treating that as a - // trigger lets a flapping pull-point manufacture motion. - if ev.Operation == stream.PropertyInitialized { - log.Log.Debug("onvif.dispatchEvent(): subscription state replay, not a trigger: topic=" + ev.Topic) + if !isTransition(ev.Operation) { + log.Log.Debug("onvif.dispatchEvent(): " + ev.Operation.String() + " is not a transition, not a trigger: topic=" + topic) return } if configuration.Config.Capture.Recording == "false" { @@ -136,9 +135,6 @@ func dispatchEvent(ctx context.Context, ev stream.Event, configuration *models.C if ctx.Err() != nil { return } - // The topic that actually started a recording is the one on-call - // needs; the reject path below already names the ones that didn't. - log.Log.Debug("onvif.dispatchEvent(): recording trigger " + ev.Kind.String() + " topic=" + ev.Topic) dataToPass := models.MotionDataPartial{ Timestamp: time.Now().Unix(), @@ -147,11 +143,39 @@ func dispatchEvent(ctx context.Context, ev stream.Event, configuration *models.C select { case <-ctx.Done(): case communication.HandleMotion <- dataToPass: + // Logged on the send, not before it: this line records that a + // recording started, so a dropped event must not leave one. + log.Log.Debug("onvif.dispatchEvent(): recording trigger " + ev.Kind.String() + " topic=" + topic) default: log.Log.Debug("onvif.dispatchEvent(): HandleMotion full, dropping ONVIF motion event") } } +// isTransition reports whether an operation represents a state change. +// A camera replays every property's current state as Initialized on +// each new subscription and announces removals as Deleted; neither is +// motion starting. Absent (Unknown) counts — PropertyOperation is +// optional per WS-Notification and many non-property events omit it. +func isTransition(op stream.PropertyOperation) bool { + return op == stream.PropertyChanged || op == stream.PropertyUnknown +} + +// maxLoggedTopic bounds a topic in the log; the wire imposes no limit, +// and the reject path logs every event received. +const maxLoggedTopic = 256 + +// sanitiseTopic makes a camera-controlled topic safe to concatenate +// into a log line. logrus's coloured text formatter writes the message +// unquoted, so a raw newline would let a camera forge entries in the +// log being used to diagnose it. +func sanitiseTopic(topic string) string { + if len(topic) > maxLoggedTopic { + topic = topic[:maxLoggedTopic] + "…(truncated)" + } + quoted := strconv.Quote(topic) + return quoted[1 : len(quoted)-1] +} + // logStreamError logs at a level matching severity: recreate is loud // because it usually means the camera is offline; pull and renew are // debug because the library recovers from them automatically. diff --git a/machinery/src/onvif/events_test.go b/machinery/src/onvif/events_test.go index 597cc5b..2dba9b6 100644 --- a/machinery/src/onvif/events_test.go +++ b/machinery/src/onvif/events_test.go @@ -3,6 +3,7 @@ package onvif import ( "bytes" "context" + "strings" "testing" "time" @@ -10,6 +11,7 @@ import ( "github.com/kerberos-io/onvif/event/stream" "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func makeConfig(recording, onvifMotion, name string) *models.Configuration { @@ -276,3 +278,98 @@ func TestResolveDeviceID_FallbackChain(t *testing.T) { }) } } + +// TestDispatchEvent_OnlyRealTransitionsTrigger — a camera replays every +// property topic's state on each new subscription (Initialized) and +// announces removals (Deleted). Neither is a motion transition, and a +// flapping pull-point would otherwise manufacture recordings out of +// replayed state. PropertyOperation is optional per WS-Notification, so +// absent (Unknown) still counts — many non-property events omit it. +func TestDispatchEvent_OnlyRealTransitionsTrigger(t *testing.T) { + tests := []struct { + op stream.PropertyOperation + wantSend bool + }{ + {stream.PropertyChanged, true}, + {stream.PropertyUnknown, true}, + {stream.PropertyInitialized, false}, + {stream.PropertyDeleted, false}, + } + + for _, tt := range tests { + t.Run(tt.op.String(), func(t *testing.T) { + cfg := makeConfig("true", "true", "cam-1") + comm := makeCommunication(1) + ev := stream.Event{Kind: stream.KindMotion, State: stream.StateActive, Operation: tt.op} + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + dispatchEvent(ctx, ev, cfg, comm) + + if tt.wantSend { + require.Len(t, comm.HandleMotion, 1, "%v must trigger a recording", tt.op) + return + } + require.Empty(t, comm.HandleMotion, "%v must not trigger a recording", tt.op) + }) + } +} + +// TestSanitiseTopic — ev.Topic is camera-controlled and reaches the log +// unmodified. logrus's coloured text formatter (the default) writes the +// message without quoting, so an embedded newline forges whole log +// lines: a compromised camera can fabricate ERROR entries or spoof +// another device's id, in the logs an operator is reading to diagnose +// that very camera. Length is also unbounded on the wire, and the +// reject path logs every event, so an oversized topic is a cheap way to +// evict a container's whole retained history. +func TestSanitiseTopic(t *testing.T) { + tests := []struct { + name string + in string + want string + }{ + {"ordinary topic passes through", "tns1:RuleEngine/tnsaxis:VMD3/vmd3_video_1", "tns1:RuleEngine/tnsaxis:VMD3/vmd3_video_1"}, + {"newline cannot forge a line", "a\nERRO[fake] boom", `a\nERRO[fake] boom`}, + {"carriage return", "a\rb", `a\rb`}, + {"tab", "a\tb", `a\tb`}, + {"NUL", "a\x00b", `a\x00b`}, + {"empty", "", ""}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := sanitiseTopic(tt.in) + assert.Equal(t, tt.want, got) + assert.NotContains(t, got, "\n", "no raw newline may survive") + assert.NotContains(t, got, "\r", "no raw carriage return may survive") + }) + } +} + +func TestSanitiseTopic_Truncates(t *testing.T) { + got := sanitiseTopic(strings.Repeat("x", maxLoggedTopic*2)) + assert.LessOrEqual(t, len(got), maxLoggedTopic+len("…(truncated)")) + assert.Contains(t, got, "truncated") +} + +// TestDispatchEvent_LogsTriggerOnlyWhenSent — the trigger line is the +// record that a recording started. Logging it before the send means a +// dropped event (full channel, or shutdown) leaves a line claiming a +// recording that never began. +func TestDispatchEvent_LogsTriggerOnlyWhenSent(t *testing.T) { + buf := captureDebugLog(t) + + cfg := makeConfig("true", "true", "cam-1") + comm := &models.Communication{HandleMotion: make(chan models.MotionDataPartial, 1)} + comm.HandleMotion <- models.MotionDataPartial{} // full + ev := stream.Event{Kind: stream.KindMotion, State: stream.StateActive, Topic: "tns1:VideoSource/MotionAlarm"} + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + dispatchEvent(ctx, ev, cfg, comm) + + assert.NotContains(t, buf.String(), "recording trigger", + "a dropped event must not be logged as a trigger") + assert.Contains(t, buf.String(), "dropping", "the drop itself must still be logged") +}