Skip to content

Take control over your live stream video by running it yourself. Streaming + chat out of the box.

fix(plugins): prevent a host crash when a plugin is torn down mid-dispatch

Gabe Kangasbec04141e4f2
diff --git a/services/plugins/dispatcher.go b/services/plugins/dispatcher.go
index 3fe76a8940..719d96acd4 100644
--- a/services/plugins/dispatcher.go
+++ b/services/plugins/dispatcher.go
@@ -129,6 +129,11 @@ func (d *Dispatcher) Filter(ctx context.Context, eventType string, payload any)
}
result, err := callOnFilter(ctx, c.plugin, eventType, current)
if err != nil {
+ // A plugin torn down mid-chain (or one exporting no filter) is a
+ // benign no-op, not a fault: don't log it or count it as a strike.
+ if errors.Is(err, errPluginNotLoaded) || errors.Is(err, errPluginNoSuchExport) {
+ continue
+ }
fmt.Fprintf(os.Stderr, "plugin %s: on_filter(%s) failed (fail-open): %v\n", c.plugin.Manifest.Slug, eventType, err)
if c.plugin.recordFilterFailure() {
fmt.Fprintf(os.Stderr, "plugin %s: auto-disabled after %d consecutive filter failures\n",
@@ -152,9 +157,6 @@ func (d *Dispatcher) Filter(ctx context.Context, eventType string, payload any)
}
func callOnFilter(ctx context.Context, p *Loaded, eventType string, payload any) (*FilterResult, error) {
- if !p.plugin.FunctionExists("on_filter") {
- return nil, fmt.Errorf("plugin does not export on_filter")
- }
envelope, err := json.Marshal(Envelope{EventType: eventType, Payload: payload})
if err != nil {
return nil, fmt.Errorf("marshal envelope: %w", err)
@@ -172,7 +174,17 @@ func callOnFilter(ctx context.Context, p *Loaded, eventType string, payload any)
return nil, fmt.Errorf("on_filter timed out after %s waiting for plugin mutex", FilterTimeout)
}
defer p.mu.Unlock()
- _, out, err := p.plugin.CallWithContext(callCtx, "on_filter", envelope)
+ // Snapshot the instance under the lock: a concurrent Loaded.Close may have
+ // torn it down. Reading p.plugin before the lock raced with that write and
+ // could nil-deref.
+ pl := p.plugin
+ if pl == nil {
+ return nil, errPluginNotLoaded
+ }
+ if !pl.FunctionExists("on_filter") {
+ return nil, errPluginNoSuchExport
+ }
+ _, out, err := pl.CallWithContext(callCtx, "on_filter", envelope)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) || callCtx.Err() == context.DeadlineExceeded {
return nil, fmt.Errorf("on_filter timed out after %s", FilterTimeout)
@@ -208,7 +220,15 @@ func (d *Dispatcher) Notify(ctx context.Context, eventType string, payload any)
wg.Add(1)
go func(p *Loaded) {
defer wg.Done()
- if err := callOnEvent(ctx, p, encoded); err != nil {
+ // A plugin must never take down the host. A panic in this goroutine
+ // can't be recovered by the caller, so recover it here.
+ defer func() {
+ if rec := recover(); rec != nil {
+ fmt.Fprintf(os.Stderr, "plugin %s: on_event(%s) panicked: %v\n", p.Manifest.Slug, eventType, rec)
+ }
+ }()
+ if err := callOnEvent(ctx, p, encoded); err != nil &&
+ !errors.Is(err, errPluginNotLoaded) && !errors.Is(err, errPluginNoSuchExport) {
fmt.Fprintf(os.Stderr, "plugin %s: on_event(%s) failed: %v\n", p.Manifest.Slug, eventType, err)
}
}(p)
@@ -225,16 +245,32 @@ func subscribed(subs []Subscription, eventType string) bool {
return false
}
+// errPluginNotLoaded / errPluginNoSuchExport are benign "nothing to do"
+// sentinels from the per-plugin call helpers: the instance was torn down by a
+// concurrent Close, or the plugin doesn't export the requested function. Best-
+// effort callers (Notify, SSE connect/disconnect) skip logging them.
+var (
+ errPluginNotLoaded = errors.New("plugin is not loaded")
+ errPluginNoSuchExport = errors.New("plugin does not export the requested function")
+)
+
func callOnEvent(ctx context.Context, p *Loaded, input []byte) error {
- if !p.plugin.FunctionExists("on_event") {
- return fmt.Errorf("plugin does not export on_event")
- }
// Extism plugins are not safe for concurrent calls; serialize per-plugin.
p.mu.Lock()
defer p.mu.Unlock()
+ // Snapshot the instance under the lock: a concurrent Loaded.Close may have
+ // torn it down. Reading p.plugin before the lock raced with that write and
+ // could nil-deref.
+ pl := p.plugin
+ if pl == nil {
+ return errPluginNotLoaded
+ }
+ if !pl.FunctionExists("on_event") {
+ return errPluginNoSuchExport
+ }
callCtx, cancel := context.WithTimeout(ctx, NotifyTimeout)
defer cancel()
- _, _, err := p.plugin.CallWithContext(callCtx, "on_event", input)
+ _, _, err := pl.CallWithContext(callCtx, "on_event", input)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) || callCtx.Err() == context.DeadlineExceeded {
return fmt.Errorf("on_event timed out after %s", NotifyTimeout)
diff --git a/services/plugins/manager.go b/services/plugins/manager.go
index 95ca2691dc..b1631afb62 100644
--- a/services/plugins/manager.go
+++ b/services/plugins/manager.go
@@ -267,12 +267,20 @@ func (p *Loaded) callVoidExport(ctx context.Context, export string) (string, err
// Close releases the underlying wasm instance and any retained file handles
// (the .ocpkg zip reader for packaged plugins). Safe to call multiple times.
func (l *Loaded) Close(ctx context.Context) {
- if l.plugin != nil {
+ // Clear the instance pointer under the lock so concurrent dispatch
+ // goroutines (which read p.plugin under the same lock) never observe a torn
+ // instance. Close the wasm instance OUTSIDE the lock: l.plugin.Close can
+ // block on an in-flight call that itself holds l.mu, so closing under the
+ // lock would deadlock.
+ l.mu.Lock()
+ pl := l.plugin
+ l.plugin = nil
+ l.mu.Unlock()
+ if pl != nil {
// Closes this instance only. For shared-engine plugins the underlying
// CompiledPlugin (the engine) is process-global and is never closed
// here; for legacy wasm plugins this closes their own runtime.
- _ = l.plugin.Close(ctx)
- l.plugin = nil
+ _ = pl.Close(ctx)
}
// Drop the call-time identity so any in-flight or stale host call from this
// plugin resolves to "not found" and fails cleanly rather than acting on a
diff --git a/services/plugins/server.go b/services/plugins/server.go
index ef251095f0..47615664f5 100644
--- a/services/plugins/server.go
+++ b/services/plugins/server.go
@@ -368,16 +368,16 @@ func sseConnectionEnvelope(eventType, channel string, connID uint64, user *HostU
// logged but never affects the stream. A fresh context is used because the
// disconnect path fires after the request context has already been cancelled.
func (s *Server) notifySSEConnection(p *Loaded, eventType, channel string, connID uint64, user *HostUser) {
- if p.plugin == nil || !p.plugin.FunctionExists("on_event") {
- return
- }
envelope, err := sseConnectionEnvelope(eventType, channel, connID, user)
if err != nil {
return
}
ctx, cancel := context.WithTimeout(context.Background(), NotifyTimeout)
defer cancel()
- if err := callOnEvent(ctx, p, envelope); err != nil {
+ // callOnEvent guards the instance under the lock; a not-loaded or
+ // non-exporting plugin is a silent no-op on this best-effort path.
+ if err := callOnEvent(ctx, p, envelope); err != nil &&
+ !errors.Is(err, errPluginNotLoaded) && !errors.Is(err, errPluginNoSuchExport) {
fmt.Fprintf(os.Stderr, "plugin %s: %s notify failed: %v\n", p.Manifest.Slug, eventType, err)
}
}
@@ -484,10 +484,13 @@ func isHTMLName(name string) bool {
}
func (s *Server) serveDynamic(w http.ResponseWriter, r *http.Request, p *Loaded, requestPath string, authenticated bool, injectStyles bool) {
- // p.plugin can be nil during shutdown (Loaded.Close clears it) or in
- // tests that only exercise the static path. Either way, no plugin
- // instance means no dynamic handler.
- if p.plugin == nil || !p.plugin.FunctionExists("on_http_request") {
+ // Snapshot the instance under the lock: Loaded.Close may clear it during
+ // shutdown (and tests may exercise only the static path). Reading p.plugin
+ // unlocked raced with that write. No instance means no dynamic handler.
+ p.mu.Lock()
+ pl := p.plugin
+ p.mu.Unlock()
+ if pl == nil || !pl.FunctionExists("on_http_request") {
http.NotFound(w, r)
return
}
@@ -515,7 +518,7 @@ func (s *Server) serveDynamic(w http.ResponseWriter, r *http.Request, p *Loaded,
// response after the call returns.
callCtx, sink := withAuthSink(callCtx)
p.mu.Lock()
- _, out, err := p.plugin.CallWithContext(callCtx, "on_http_request", envelopeJSON)
+ _, out, err := pl.CallWithContext(callCtx, "on_http_request", envelopeJSON)
p.mu.Unlock()
if err != nil {
if errors.Is(err, context.DeadlineExceeded) || callCtx.Err() == context.DeadlineExceeded {
@@ -544,13 +547,19 @@ func (s *Server) serveDynamic(w http.ResponseWriter, r *http.Request, p *Loaded,
// fails closed on error).
func (s *Server) CallAuthCheck(ctx context.Context, slug string, input []byte) ([]byte, error) {
p := s.lookup(slug)
- if p == nil || p.plugin == nil || !p.plugin.FunctionExists("on_auth_check") {
+ if p == nil {
+ return nil, fmt.Errorf("auth check unavailable for plugin %q", slug)
+ }
+ p.mu.Lock()
+ pl := p.plugin
+ p.mu.Unlock()
+ if pl == nil || !pl.FunctionExists("on_auth_check") {
return nil, fmt.Errorf("auth check unavailable for plugin %q", slug)
}
callCtx, cancel := context.WithTimeout(ctx, HTTPHandlerTimeout)
defer cancel()
p.mu.Lock()
- _, out, err := p.plugin.CallWithContext(callCtx, "on_auth_check", input)
+ _, out, err := pl.CallWithContext(callCtx, "on_auth_check", input)
p.mu.Unlock()
return out, err
}
diff --git a/services/plugins/shared_engine_test.go b/services/plugins/shared_engine_test.go
index 1547596789..460a682543 100644
--- a/services/plugins/shared_engine_test.go
+++ b/services/plugins/shared_engine_test.go
@@ -119,6 +119,44 @@ module.exports = definePlugin({
}
}
+// TestDispatchCloseRace exercises the C1 lifecycle race: tearing a plugin down
+// (Loaded.Close) while events are concurrently dispatched to it must neither
+// data-race on the instance pointer nor nil-deref. Run under -race to catch the
+// field race; before the snapshot-under-lock fix this also panicked (an
+// unrecovered panic on the dispatch goroutine crashed the whole host).
+func TestDispatchCloseRace(t *testing.T) {
+ ctx := context.Background()
+ compiledEngines.resetForTest(ctx)
+ t.Cleanup(func() { compiledEngines.resetForTest(ctx) })
+
+ env, _, _ := captureEnv()
+ script := `
+const { definePlugin, owncast } = require("@owncast/plugin-sdk");
+module.exports = definePlugin({
+ onChatMessage(msg) { owncast.chat.send("ok"); }
+});`
+ loaded := loadShared(t, ctx, env, RuntimeJavaScript, "racer", script, []string{PermChatSend})
+ d := NewLiveDispatcher(func() []*Loaded { return []*Loaded{loaded} })
+
+ var wg sync.WaitGroup
+ // Many dispatchers fanning on_event out to the plugin...
+ for i := 0; i < 50; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ d.Dispatch(ctx, EventChatMessageReceived, chatPayload("alice", "hi"))
+ }()
+ }
+ // ...while it is torn down underneath them. The dispatches that land after
+ // Close must safely no-op rather than crash.
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ loaded.Close(ctx)
+ }()
+ wg.Wait()
+}
+
// TestManifestParse covers the R4 reserved-config-key guard and confirms the
// manifest no longer requires (or validates) a "type" field — the runtime is
// inferred from the code artifact at load time.
diff --git a/services/plugins/timer.go b/services/plugins/timer.go
index 81402a1728..9d2bb20138 100644
--- a/services/plugins/timer.go
+++ b/services/plugins/timer.go
@@ -3,6 +3,7 @@ package plugins
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"os"
"sync"
@@ -165,7 +166,8 @@ func (h *TimerHub) fire(e *timerEntry) {
Payload: TimerFireEvent{ID: e.id},
})
if err == nil {
- if err := callOnEvent(context.Background(), loaded, envelope); err != nil {
+ if err := callOnEvent(context.Background(), loaded, envelope); err != nil &&
+ !errors.Is(err, errPluginNotLoaded) && !errors.Is(err, errPluginNoSuchExport) {
fmt.Fprintf(os.Stderr, "plugin %s: timer %d fire failed: %v\n", e.slug, e.id, err)
}
}