Take control over your live stream video by running it yourself. Streaming + chat out of the box.
HTML activitypubbroadcastingchatdecentralizedfederationfediversegolanghacktoberfesthlslivelivestreamowncastrtmpself-hostedstreaming-videovideo
Reject duplicate local plugin slugs (#5113)
Gabe Kangas130c2c0cdc1e
diff --git a/pluginhost/pluginhost.go b/pluginhost/pluginhost.goindex b52c5f59ab..0242a4aaa5 100644--- a/pluginhost/pluginhost.go+++ b/pluginhost/pluginhost.go@@ -1220,7 +1220,7 @@ func (p *Host) handlePluginUpload(w http.ResponseWriter, r *http.Request) {writeJSONResponse(w, http.StatusBadRequest, map[string]string{jsonErrorKey: "read upload: " + err.Error()})return}- entry, err := p.manager.Install(r.Context(), packageBytes)+ entry, err := p.manager.InstallUploaded(r.Context(), packageBytes)if err != nil {writeJSONResponse(w, http.StatusBadRequest, map[string]string{jsonErrorKey: err.Error()})returndiff --git a/services/plugins/manager.go b/services/plugins/manager.goindex ec289d0185..df58a9e584 100644--- a/services/plugins/manager.go+++ b/services/plugins/manager.go@@ -329,10 +329,13 @@ type Manager struct {env *HostEnvmu sync.RWMutex- discovered map[string]*DiscoveredEntry // keyed by manifest.name+ discovered map[string]*DiscoveredEntry // keyed by manifest slugloaded map[string]*Loaded // subset of discovered that's currently running- enabledSet map[string]bool // names the admin has enabled- approvedSet map[string][]string // plugin name -> sorted approved permission set+ enabledSet map[string]bool // slugs the admin has enabled+ approvedSet map[string][]string // plugin slug -> sorted approved permission set+ // duplicatePluginPaths records rejected package paths and their accepted+ // counterpart, preventing the periodic scan from logging the same conflict.+ duplicatePluginPaths map[string]string// packageFilesMu serializes scans with package replacement. Windows does// not allow an .ocpkg opened by a scan to be replaced by Install.packageFilesMu sync.Mutex@@ -493,15 +496,16 @@ func NewManager(pluginsDir string, env *HostEnv) *Manager {// datastore) instead of a JSON file in the plugins directory.func NewManagerWithStore(pluginsDir string, env *HostEnv, store EnabledStore) *Manager {return &Manager{- pluginsDir: pluginsDir,- enabledStore: store,- env: env,- discovered: make(map[string]*DiscoveredEntry),- loaded: make(map[string]*Loaded),- enabledSet: make(map[string]bool),- approvedSet: make(map[string][]string),- scanInterval: ScanInterval,- scanCh: make(chan struct{}, 1),+ pluginsDir: pluginsDir,+ enabledStore: store,+ env: env,+ discovered: make(map[string]*DiscoveredEntry),+ loaded: make(map[string]*Loaded),+ enabledSet: make(map[string]bool),+ approvedSet: make(map[string][]string),+ duplicatePluginPaths: make(map[string]string),+ scanInterval: ScanInterval,+ scanCh: make(chan struct{}, 1),}}@@ -856,29 +860,40 @@ func atomicWritePackage(pluginsDir, destPath string, packageBytes []byte) error// upload can't fill the plugins directory.const MaxUploadBytes = 50 * 1024 * 1024-// Install validates a .ocpkg's contents, writes it into the plugins-// directory, and forces a scan so the new (or updated) plugin shows up-// in the next List() without waiting for the scan tick. The destination-// filename is derived from the manifest's name, not from the uploaded-// name, so an admin can't drop a file outside the plugins directory by-// abusing the upload filename, and a plugin update from a differently-// named .ocpkg ends up replacing the right file.-//-// When the plugin is already enabled and the new manifest declares no-// permissions beyond the approved set, the running instance is reloaded in-// place so the update takes effect immediately. If the update expands-// permissions, the old instance keeps running (it holds only approved-// permissions) and the entry reports PendingPermissions so the admin UI can-// run the re-approval flow.-//-// Returns the discovered entry for the installed plugin, with Enabled and-// Loaded populated the same way List() reports them.+// Install validates a registry .ocpkg, writes it into the plugins directory,+// and updates an existing plugin with the same slug when necessary.func (m *Manager) Install(ctx context.Context, packageBytes []byte) (*DiscoveredEntry, error) {+ return m.install(ctx, packageBytes, true)+}++// InstallUploaded validates a manually uploaded .ocpkg and writes it into the+// plugins directory. Uploads must not replace an existing plugin: only the+// registry update path is allowed to do that.+func (m *Manager) InstallUploaded(ctx context.Context, packageBytes []byte) (*DiscoveredEntry, error) {+ return m.install(ctx, packageBytes, false)+}++// install writes a validated package. Registry installs may replace an existing+// slug, while manual uploads must be a new plugin.+func (m *Manager) install(ctx context.Context, packageBytes []byte, replaceExisting bool) (*DiscoveredEntry, error) {manifest, err := validateUploadedPackage(ctx, m.env, packageBytes)if err != nil {return nil, err}m.packageFilesMu.Lock()+ m.mu.RLock()+ existing, found := m.discovered[manifest.Slug]+ m.mu.RUnlock()+ if found && !replaceExisting {+ m.packageFilesMu.Unlock()+ return nil, fmt.Errorf("plugin upload rejected: slug %q is already used by %q at %s; uninstall it before uploading another plugin with the same slug",+ manifest.Slug, existing.DisplayName, existing.Path)+ }+ if found && !strings.HasSuffix(existing.Path, packageSuffix) {+ m.packageFilesMu.Unlock()+ return nil, fmt.Errorf("plugin install rejected: slug %q is already used by loose plugin %q at %s; uninstall it before installing another plugin with the same slug",+ manifest.Slug, existing.DisplayName, existing.Path)+ }destPath := m.destPathForInstall(manifest.Slug)installErr := atomicWritePackage(m.pluginsDir, destPath, packageBytes)if installErr == nil {@@ -1197,6 +1212,23 @@ func (m *Manager) scan(ctx context.Context) error {return m.scanLocked(ctx)}+// claimPluginPath records the first package for a slug and rejects later+// packages with that identity. scanLocked serializes calls, so these maps need+// no additional synchronization.+func (m *Manager) claimPluginPath(manifest *Manifest, path string, claimedPaths, duplicatePaths map[string]string) bool {+ firstPath, duplicate := claimedPaths[manifest.Slug]+ if !duplicate {+ claimedPaths[manifest.Slug] = path+ return true+ }+ duplicatePaths[path] = firstPath+ if m.duplicatePluginPaths[path] != firstPath {+ log.Errorf("plugin %q at %s disabled: duplicate slug %q is already provided by %s",+ manifest.DisplayName, path, manifest.Slug, firstPath)+ }+ return false+}+// scanLocked re-reads the plugins directory, updates the discovered map, and// unloads anything whose underlying file has gone away. packageFilesMu must be// held by the caller.@@ -1207,6 +1239,8 @@ func (m *Manager) scanLocked(ctx context.Context) error {}seen := make(map[string]bool)+ claimedPaths := make(map[string]string)+ duplicatePaths := make(map[string]string)for _, entry := range entries {if entry.IsDir() {continue@@ -1225,6 +1259,9 @@ func (m *Manager) scanLocked(ctx context.Context) error {fmt.Fprintf(os.Stderr, "discover %s: %v\n", name, err)continue}+ if !m.claimPluginPath(manifest, path, claimedPaths, duplicatePaths) {+ continue+ }seen[manifest.Slug] = truehasIcon := hasPluginIcon(path)@@ -1268,6 +1305,7 @@ func (m *Manager) scanLocked(ctx context.Context) error {}m.mu.Unlock()}+ m.duplicatePluginPaths = duplicatePaths// Anything we knew about but didn't see this scan: gone from disk.var removed []stringdiff --git a/services/plugins/manager_test.go b/services/plugins/manager_test.goindex ffab16dbc6..c25c6bac25 100644--- a/services/plugins/manager_test.go+++ b/services/plugins/manager_test.go@@ -10,6 +10,8 @@ import ("strings""testing""time"++ log "github.com/sirupsen/logrus")// TestSnapshot_OmitsStrikeDisabledPlugins is the C4 regression: a plugin the@@ -548,6 +550,115 @@ func TestManager_Install_WritesPackageAndDiscovers(t *testing.T) {}}+func TestManager_InstallUploaded_RejectsExistingSlug(t *testing.T) {+ wasmPath := findExampleWasm(t)+ wasmBytes, err := os.ReadFile(wasmPath)+ if err != nil {+ t.Fatalf("read example wasm: %v", err)+ }++ ctx := context.Background()+ mgr := NewManager(t.TempDir(), &HostEnv{})+ if err := mgr.Start(ctx); err != nil {+ t.Fatalf("start: %v", err)+ }+ defer mgr.Stop(ctx)++ pkg := buildPackageBytes(t, validManifestBytes(), wasmBytes, nil)+ if _, err := mgr.Install(ctx, pkg); err != nil {+ t.Fatalf("install first plugin: %v", err)+ }+ if _, err := mgr.InstallUploaded(ctx, pkg); err == nil || !strings.Contains(err.Error(), `slug "hello-world"`) {+ t.Fatalf("duplicate upload error = %v, want slug-specific rejection", err)+ }+}++func TestManager_Install_RejectsReplacingLoosePlugin(t *testing.T) {+ wasmPath := findExampleWasm(t)+ wasmBytes, err := os.ReadFile(wasmPath)+ if err != nil {+ t.Fatalf("read example wasm: %v", err)+ }++ dir := t.TempDir()+ loosePath := filepath.Join(dir, "local-copy.wasm")+ if err := os.WriteFile(loosePath, wasmBytes, 0o600); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(dir, "local-copy.manifest.json"), validManifestBytes(), 0o600); err != nil {+ t.Fatal(err)+ }++ ctx := context.Background()+ mgr := NewManager(dir, &HostEnv{})+ if err := mgr.Start(ctx); err != nil {+ t.Fatalf("start: %v", err)+ }+ defer mgr.Stop(ctx)++ pkg := buildPackageBytes(t, validManifestBytes(), wasmBytes, nil)+ _, err = mgr.Install(ctx, pkg)+ if err == nil || !strings.Contains(err.Error(), `slug "hello-world"`) ||+ !strings.Contains(err.Error(), "loose plugin") ||+ !strings.Contains(err.Error(), loosePath) {+ t.Fatalf("install error = %v, want loose-plugin conflict", err)+ }+ if _, err := os.Stat(filepath.Join(dir, "hello-world.ocpkg")); !os.IsNotExist(err) {+ t.Fatalf("conflicting package was written, stat error = %v", err)+ }+ entries := mgr.List()+ if len(entries) != 1 || entries[0].Path != loosePath {+ t.Fatalf("discovered entries = %+v, want original loose plugin", entries)+ }+}++func TestManager_ScanDisablesLaterPluginWithDuplicateSlug(t *testing.T) {+ dir := t.TempDir()+ manifest := func(name string) []byte {+ t.Helper()+ data, err := json.Marshal(map[string]any{+ "api": "1",+ "name": name,+ "slug": "shared-slug",+ "version": "0.1.0",+ })+ if err != nil {+ t.Fatal(err)+ }+ return data+ }+ if err := os.WriteFile(filepath.Join(dir, "first.ocpkg"), buildPackageBytes(t, manifest("First plugin"), nil, nil), 0o600); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(dir, "second.ocpkg"), buildPackageBytes(t, manifest("Second plugin"), nil, nil), 0o600); err != nil {+ t.Fatal(err)+ }++ previousLogOutput := log.StandardLogger().Out+ var logOutput bytes.Buffer+ log.SetOutput(&logOutput)+ t.Cleanup(func() { log.SetOutput(previousLogOutput) })++ mgr := NewManager(dir, &HostEnv{})+ if err := mgr.Start(context.Background()); err != nil {+ t.Fatalf("start: %v", err)+ }+ defer mgr.Stop(context.Background())++ entries := mgr.List()+ if len(entries) != 1 {+ t.Fatalf("discovered plugins = %d, want 1", len(entries))+ }+ if entries[0].DisplayName != "First plugin" || entries[0].Path != filepath.Join(dir, "first.ocpkg") {+ t.Errorf("duplicate scan kept %+v, want first package", entries[0])+ }+ if output := logOutput.String(); !strings.Contains(output, "Second plugin") ||+ !strings.Contains(output, "shared-slug") ||+ !strings.Contains(output, "first.ocpkg") {+ t.Errorf("duplicate plugin log = %q", output)+ }+}+func TestManager_Install_RejectsEmptyUpload(t *testing.T) {mgr := NewManager(t.TempDir(), &HostEnv{})_, err := mgr.Install(context.Background(), nil)diff --git a/web/pages/admin/plugins.tsx b/web/pages/admin/plugins.tsxindex 877d45fba0..df38761fdd 100644--- a/web/pages/admin/plugins.tsx+++ b/web/pages/admin/plugins.tsx@@ -180,6 +180,7 @@ const Plugins = () => {} catch (e) {const msg = e instanceof Error ? e.message : String(e);setError(msg);+ message.error(msg);onError?.(e as Error);}},diff --git a/web/tests/plugins-page.test.tsx b/web/tests/plugins-page.test.tsxindex a83da968f5..9cf49ddee8 100644--- a/web/tests/plugins-page.test.tsx+++ b/web/tests/plugins-page.test.tsx@@ -7,6 +7,7 @@ import {PLUGINS_LIST,PLUGIN_REGISTRY_INSTALL,PLUGIN_REGISTRY_LIST,+ PLUGIN_UPLOAD,} from '../utils/apis';jest.mock('../pages/admin/plugins.module.scss', () => ({@@ -34,6 +35,24 @@ jest.mock('antd', () => {error: jest.fn(),success: jest.fn(),},+ Upload: ({+ children,+ customRequest,+ }: {+ children: React.ReactNode;+ customRequest: (options: { file: File; onError: (error: Error) => void }) => void;+ }) => (+ <>+ {children}+ <input+ data-testid="plugin-upload"+ type="file"+ onChange={() =>+ customRequest({ file: new File(['plugin'], 'duplicate.ocpkg'), onError: jest.fn() })+ }+ />+ </>+ ),};});@@ -79,11 +98,16 @@ jest.mock('../utils/apis', () => {const mockedFetchData = fetchData as jest.MockedFunction<typeof fetchData>;+const originalFetch = global.fetch;+describe('Plugins admin page', () => {beforeEach(() => {mockedFetchData.mockReset();jest.clearAllMocks();});+ afterEach(() => {+ global.fetch = originalFetch;+ });test('surfaces registry install errors to the admin page', async () => {mockedFetchData.mockImplementation(async url => {@@ -113,4 +137,38 @@ describe('Plugins admin page', () => {'invalid manifest: manifest.scripts requires the "http.serve" permission',);});++ test('shows a duplicate slug upload rejection in the admin alert', async () => {+ global.fetch = jest.fn().mockResolvedValue({+ ok: false,+ status: 400,+ text: async () =>+ JSON.stringify({ error: 'plugin upload rejected: slug "hello-world" is already used' }),+ } as Response);++ mockedFetchData.mockImplementation(async url => {+ if (url === PLUGINS_LIST || url === PLUGIN_REGISTRY_LIST) {+ return [];+ }+ throw new Error(`unexpected fetchData call: ${url}`);+ });++ render(<Plugins />);+ fireEvent.change(await screen.findByTestId('plugin-upload'), {+ target: { files: [new File(['plugin'], 'duplicate.ocpkg')] },+ });++ await waitFor(() => {+ expect(+ screen.getByText('plugin upload rejected: slug "hello-world" is already used'),+ ).toBeInTheDocument();+ });+ expect(global.fetch).toHaveBeenCalledWith(+ PLUGIN_UPLOAD,+ expect.objectContaining({ method: 'POST' }),+ );+ expect(message.error).toHaveBeenCalledWith(+ 'plugin upload rejected: slug "hello-world" is already used',+ );+ });});