Take control over your live stream video by running it yourself. Streaming + chat out of the box.
HTML activitypubbroadcastingchatdecentralizedfederationfediversegolanghacktoberfesthlslivelivestreamowncastrtmpself-hostedstreaming-videovideo
fix(plugins): load enabled but unloaded plugins on baseline-conforming updates (#5059)
Gabe Kangas98b4357dfb5a
diff --git a/pluginhost/registry_test.go b/pluginhost/registry_test.goindex ce027a1bac..75aea3c99c 100644--- a/pluginhost/registry_test.go+++ b/pluginhost/registry_test.go@@ -495,3 +495,147 @@ func TestHandleRegistryInstall_PersistsHomepageSidecar(t *testing.T) {t.Errorf("sidecar homepage = %q, want %q", meta.Homepage, stubRegistryHomepage)}}++// TestHandleRegistryInstall_SamePermissionUpdateNeedsNoReEnable is the+// regression test for the admin-facing re-enable prompt: updating an+// installed, enabled, loaded plugin to a version that declares the SAME+// permission set must come back from the install endpoint with+// enabled=true and no pendingPermissions — the exact JSON fields the+// admin frontend checks to decide whether to pop the enable/approve+// modal (web/pages/admin/plugins.tsx installFromRegistry).+func TestHandleRegistryInstall_SamePermissionUpdateNeedsNoReEnable(t *testing.T) {+ manifest := func(version string) []byte {+ // Permissions deliberately not in sorted order: Enable stores the+ // approved baseline sorted, so an order-sensitive comparison would+ // misreport these as pending.+ return fmt.Appendf(nil, `{+ "api": "1",+ "name": "Perm Bot",+ "slug": "perm-bot",+ "version": %q,+ "description": "same-permission update test",+ "permissions": ["storage.kv", "chat.send"]+ }`, version)+ }+ install := func(host *Host, version string) map[string]any {+ t.Helper()+ pkg := buildJSPackageBytes(t, manifest(version))+ sum := sha256.Sum256(pkg)+ upstream := newRegistryStub(t, "perm-bot", version, pkg, hex.EncodeToString(sum[:]))+ withRegistryEnv(t, upstream.URL)+ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodPost, "/api/admin/plugin-registry/install",+ strings.NewReader(fmt.Sprintf(`{"slug":"perm-bot","version":%q}`, version)))+ host.handleRegistryInstall(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("install %s: status = %d, want 200 (body=%s)", version, rec.Code, rec.Body.String())+ }+ var body map[string]any+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {+ t.Fatalf("decode install %s response: %v", version, err)+ }+ return body+ }++ host := newTestHost(t)++ // Fresh install is not enabled: the modal SHOULD show here.+ body := install(host, "0.1.0")+ if enabled, _ := body["enabled"].(bool); enabled {+ t.Fatalf("fresh install must not be enabled, body=%v", body)+ }+ // Admin clicks Enable in the modal (same Manager op the enable+ // action endpoint dispatches).+ if err := host.manager.Enable(context.Background(), "perm-bot"); err != nil {+ t.Fatalf("enable: %v", err)+ }++ // Update to v2 with an identical permission set: no prompt.+ body = install(host, "0.2.0")+ if enabled, _ := body["enabled"].(bool); !enabled {+ t.Errorf("same-permission update must report enabled=true, body=%v", body)+ }+ if pending, ok := body["pendingPermissions"]; ok && pending != nil {+ if list, isList := pending.([]any); !isList || len(list) > 0 {+ t.Errorf("same-permission update must report no pendingPermissions, got %v", pending)+ }+ }+ if loaded, _ := body["loaded"].(bool); !loaded {+ t.Errorf("same-permission update must stay loaded, body=%v", body)+ }+ if v, _ := body["version"].(string); v != "0.2.0" {+ t.Errorf("version after update = %q, want 0.2.0", v)+ }+}++// TestHandleRegistryInstall_SamePermUpdateSurvivesRestart is the same+// scenario across an Owncast restart, with the production+// configEnabledStore persisting the enabled set and approved-permission+// baseline in the datastore. If the baseline is lost in the+// Save/Load round trip, the update reports every permission as pending+// and the admin gets re-prompted to approve an unchanged set.+func TestHandleRegistryInstall_SamePermUpdateSurvivesRestart(t *testing.T) {+ ctx := context.Background()+ dir := t.TempDir()+ store := &configEnabledStore{datastore: newTestDatastore(t)}++ manifest := func(version string) []byte {+ return fmt.Appendf(nil, `{+ "api": "1",+ "name": "Perm Bot",+ "slug": "perm-bot",+ "version": %q,+ "description": "restart persistence test",+ "permissions": ["storage.kv", "chat.send"]+ }`, version)+ }+ install := func(host *Host, version string) map[string]any {+ t.Helper()+ pkg := buildJSPackageBytes(t, manifest(version))+ sum := sha256.Sum256(pkg)+ upstream := newRegistryStub(t, "perm-bot", version, pkg, hex.EncodeToString(sum[:]))+ withRegistryEnv(t, upstream.URL)+ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodPost, "/api/admin/plugin-registry/install",+ strings.NewReader(fmt.Sprintf(`{"slug":"perm-bot","version":%q}`, version)))+ host.handleRegistryInstall(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("install %s: status = %d, want 200 (body=%s)", version, rec.Code, rec.Body.String())+ }+ var body map[string]any+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {+ t.Fatalf("decode install %s response: %v", version, err)+ }+ return body+ }++ mgr1 := plugins.NewManagerWithStore(dir, &plugins.HostEnv{}, store)+ if err := mgr1.Start(ctx); err != nil {+ t.Fatalf("manager 1 start: %v", err)+ }+ install(&Host{manager: mgr1}, "0.1.0")+ if err := mgr1.Enable(ctx, "perm-bot"); err != nil {+ t.Fatalf("enable: %v", err)+ }+ mgr1.Stop(ctx)++ // "Restart": a fresh manager over the same plugins dir + datastore.+ mgr2 := plugins.NewManagerWithStore(dir, &plugins.HostEnv{}, store)+ if err := mgr2.Start(ctx); err != nil {+ t.Fatalf("manager 2 start: %v", err)+ }+ t.Cleanup(func() { mgr2.Stop(ctx) })++ body := install(&Host{manager: mgr2}, "0.2.0")+ if enabled, _ := body["enabled"].(bool); !enabled {+ t.Errorf("post-restart same-permission update must report enabled=true, body=%v", body)+ }+ if pending, ok := body["pendingPermissions"]; ok && pending != nil {+ if list, isList := pending.([]any); !isList || len(list) > 0 {+ t.Errorf("post-restart same-permission update must report no pendingPermissions, got %v", pending)+ }+ }+ if loaded, _ := body["loaded"].(bool); !loaded {+ t.Errorf("post-restart same-permission update must stay loaded, body=%v", body)+ }+}diff --git a/services/plugins/engine_lifecycle_test.go b/services/plugins/engine_lifecycle_test.goindex eaf47f4f44..68cedd93c6 100644--- a/services/plugins/engine_lifecycle_test.go+++ b/services/plugins/engine_lifecycle_test.go@@ -6,6 +6,8 @@ import ("context""encoding/json""fmt"+ "os"+ "path/filepath""testing")@@ -335,3 +337,77 @@ module.exports = definePlugin({ onChatMessage(msg) {} });`)t.Fatalf("engine cache after no-op Enable: %d engines with %d refs, want unchanged 1/1", n, refs)}}++// TestManager_Install_LoadsEnabledButUnloadedPluginOnUpdate defends the last+// corner of the Install update contract: a plugin can be enabled but not+// running (an on-disk update expanded its permissions, so the host held it+// unloaded across a restart). Installing a version whose permissions are+// covered by the approved baseline must bring it back up — the admin already+// consented to everything this package asks for.+func TestManager_Install_LoadsEnabledButUnloadedPluginOnUpdate(t *testing.T) {+ ctx := context.Background()+ compiledEngines.resetForTest(ctx)+ t.Cleanup(func() { compiledEngines.resetForTest(ctx) })++ env, _, _ := captureEnv()+ dir := t.TempDir()+ mgr := NewManager(dir, env)+ if err := mgr.Start(ctx); err != nil {+ t.Fatalf("start: %v", err)+ }++ script := []byte(`+const { definePlugin } = require("@owncast/plugin-sdk");+module.exports = definePlugin({ onChatMessage(msg) {} });`)+ perms := []string{PermChatSend}++ if _, err := mgr.Install(ctx, buildJSPackageBytes(t, lifecycleManifest(t, "0.1.0", perms), script)); err != nil {+ t.Fatalf("install v1: %v", err)+ }+ if err := mgr.Enable(ctx, "lifecycle-bot"); err != nil {+ t.Fatalf("enable: %v", err)+ }+ mgr.Stop(ctx)++ // The author drops a permission-expanding v2 on disk while the host is+ // down; the restarted manager discovers it, sees an unapproved+ // permission, and keeps the plugin unloaded.+ v2 := buildJSPackageBytes(t, lifecycleManifest(t, "0.2.0", []string{PermChatSend, PermStorageKV}), script)+ if err := os.WriteFile(filepath.Join(dir, "lifecycle-bot.ocpkg"), v2, 0o600); err != nil {+ t.Fatalf("drop v2 on disk: %v", err)+ }+ mgr = NewManager(dir, env)+ if err := mgr.Start(ctx); err != nil {+ t.Fatalf("restart: %v", err)+ }+ defer mgr.Stop(ctx)+ if len(mgr.Snapshot()) != 0 {+ t.Fatal("precondition: the expanded-permission v2 must be held unloaded")+ }++ // The admin installs v3, back inside the approved baseline. The plugin+ // is enabled and everything v3 asks for is approved, so the update must+ // leave it running — not stranded at "enabled, not loaded" until the+ // next restart.+ entry, err := mgr.Install(ctx, buildJSPackageBytes(t, lifecycleManifest(t, "0.3.0", perms), script))+ if err != nil {+ t.Fatalf("install v3: %v", err)+ }+ if !entry.Enabled || !entry.Loaded {+ t.Fatalf("baseline-conforming update of an enabled plugin must end up loaded: Enabled=%v Loaded=%v LastError=%q",+ entry.Enabled, entry.Loaded, entry.LastError)+ }+ if len(entry.PendingPermissions) != 0 {+ t.Errorf("pending permissions after conforming update: got %v, want none", entry.PendingPermissions)+ }+ snap := mgr.Snapshot()+ if len(snap) != 1 || snap[0].Manifest.Version != "0.3.0" {+ t.Fatalf("running instance after conforming update: got %d loaded (want 1) with version %q (want 0.3.0)",+ len(snap), func() string {+ if len(snap) > 0 {+ return snap[0].Manifest.Version+ }+ return ""+ }())+ }+}diff --git a/services/plugins/manager.go b/services/plugins/manager.goindex e9b51f2ab8..169e68099c 100644--- a/services/plugins/manager.go+++ b/services/plugins/manager.go@@ -851,7 +851,6 @@ func (m *Manager) Install(ctx context.Context, packageBytes []byte) (*Discoveredm.mu.RLock()entry, ok := m.discovered[manifest.Slug]enabled := m.enabledSet[manifest.Slug]- _, isLoaded := m.loaded[manifest.Slug]pending := 0if ok {pending = len(entry.PendingPermissions)@@ -863,10 +862,14 @@ func (m *Manager) Install(ctx context.Context, packageBytes []byte) (*Discovered// An update of an enabled plugin whose permissions are still covered by// the admin's approval takes effect now: swap the running instance for- // one built from the new package. A failure surfaces via LastError (set- // by loadInternal) rather than failing the install — the file on disk is- // already the new version either way.- if enabled && isLoaded && pending == 0 {+ // one built from the new package. The plugin need not be running — a+ // previous version may have been held unloaded because it declared+ // unapproved permissions; a conforming update clears that hold (and the+ // stale "needs approval" LastError) instead of stranding the plugin at+ // "enabled, not loaded" until the next restart. A failure surfaces via+ // LastError (set by loadInternal) rather than failing the install — the+ // file on disk is already the new version either way.+ if enabled && pending == 0 {if err := m.Reload(ctx, manifest.Slug); err != nil {fmt.Fprintf(os.Stderr, "plugin %s: reload after update failed: %v\n", manifest.Slug, err)}