From 5802229fdcbcd329cf092fd9cbf7cee5543ee4c4 Mon Sep 17 00:00:00 2001 From: Ayush7614 Date: Sat, 17 Oct 2026 17:12:16 +0530 Subject: [PATCH 1/7] feat(plugins): add CLI enable/disable for plugin.json Add zero plugins enable|disable so installed plugins can be toggled without removing them, matching hooks/MCP parity and EXTENDING docs. --- docs/EXTENDING.md | 4 +- internal/cli/extensions.go | 98 ++++++++++++++++++++ internal/cli/extensions_test.go | 121 ++++++++++++++++++++++++ internal/plugins/enabled.go | 114 +++++++++++++++++++++++ internal/plugins/enabled_test.go | 152 +++++++++++++++++++++++++++++++ 5 files changed, 488 insertions(+), 1 deletion(-) create mode 100644 internal/plugins/enabled.go create mode 100644 internal/plugins/enabled_test.go diff --git a/docs/EXTENDING.md b/docs/EXTENDING.md index a2906f39ec..38b49303b2 100644 --- a/docs/EXTENDING.md +++ b/docs/EXTENDING.md @@ -347,10 +347,12 @@ Install and manage: zero plugins add ./github-pr-review # copy into ~/.config/zero/plugins/ or ./.zero/plugins/ zero plugins list zero plugins info github-pr-review # show manifest path, enabled state, lock metadata +zero plugins disable github-pr-review # sets "enabled": false in plugin.json +zero plugins enable github-pr-review # sets "enabled": true in plugin.json zero plugins remove github-pr-review # alias: rm ``` -A plugin is enabled by being present in the plugins directory and disabled by removing it (or by the user setting `"enabled": false` in its `plugin.json`). Plugins are not enabled or disabled by a CLI subcommand today. +A plugin is active when it is present under a plugins directory and its `plugin.json` has `"enabled": true` (the default when the field is omitted). Use `zero plugins disable ` / `zero plugins enable ` to toggle that field without removing the plugin. Pass `--user` to target only user plugins and ignore `./.zero/plugins`. Plugin commands run with the plugin directory as their working directory. Use relative paths; the loader resolves them at activation time. diff --git a/internal/cli/extensions.go b/internal/cli/extensions.go index c3bb81a4ef..c50f55c6fb 100644 --- a/internal/cli/extensions.go +++ b/internal/cli/extensions.go @@ -2,6 +2,7 @@ package cli import ( "context" + "errors" "fmt" "io" "strings" @@ -82,11 +83,94 @@ func runPlugins(args []string, stdout io.Writer, stderr io.Writer, deps appDeps) return runPluginInfo(args[1:], stdout, stderr, deps) case "remove", "rm": return runPluginRemove(args[1:], deps.pluginsDir(), stdout, stderr) + case "enable": + return runPluginsToggle(args[1:], stdout, stderr, deps, false) + case "disable": + return runPluginsToggle(args[1:], stdout, stderr, deps, true) default: return writeExecUsageError(stderr, fmt.Sprintf("unknown plugins subcommand %q", args[0])) } } +type pluginToggleOptions struct { + json bool + user bool +} + +func runPluginsToggle(args []string, stdout io.Writer, stderr io.Writer, deps appDeps, disabled bool) int { + commandName := "enable" + if disabled { + commandName = "disable" + } + options, positional, help, err := parsePluginToggleArgs(args, commandName) + if err != nil { + return writeExecUsageError(stderr, err.Error()) + } + if help { + if err := writePluginsToggleHelp(stdout, commandName); err != nil { + return exitCrash + } + return exitSuccess + } + if len(positional) != 1 { + return writeExecUsageError(stderr, fmt.Sprintf("usage: zero plugins %s [--user] [--json]", commandName)) + } + pluginID := positional[0] + + cwd, err := deps.getwd() + if err != nil { + return writeAppError(stderr, "failed to resolve workspace: "+err.Error(), exitCrash) + } + loadOptions := plugins.LoadOptions{Cwd: cwd, ExcludeProject: options.user} + result, err := plugins.SetEnabledByID(loadOptions, pluginID, !disabled) + if err != nil { + if errors.Is(err, plugins.ErrNotInstalled) { + return writeExecUsageError(stderr, err.Error()) + } + return writeAppError(stderr, redaction.ErrorMessage(err, redaction.Options{}), exitCrash) + } + + state := "enabled" + if disabled { + state = "disabled" + } + if options.json { + if err := writePrettyJSON(stdout, redaction.RedactValue(result, redaction.Options{})); err != nil { + return exitCrash + } + return exitSuccess + } + if result.Changed { + if _, err := fmt.Fprintf(stdout, "Plugin %s is now %s in %s.\n", result.ID, state, result.ManifestPath); err != nil { + return exitCrash + } + } else if _, err := fmt.Fprintf(stdout, "Plugin %s was already %s in %s.\n", result.ID, state, result.ManifestPath); err != nil { + return exitCrash + } + return exitSuccess +} + +func parsePluginToggleArgs(args []string, command string) (pluginToggleOptions, []string, bool, error) { + options := pluginToggleOptions{} + positional := []string{} + for _, arg := range args { + switch arg { + case "-h", "--help", "help": + return options, positional, true, nil + case "--json": + options.json = true + case "--user": + options.user = true + default: + if strings.HasPrefix(arg, "-") { + return options, positional, false, execUsageError{fmt.Sprintf("unknown plugins %s flag %q", command, arg)} + } + positional = append(positional, arg) + } + } + return options, positional, false, nil +} + func runHooks(args []string, stdout io.Writer, stderr io.Writer, deps appDeps) int { if len(args) == 0 { return writeExecUsageError(stderr, "hooks subcommand required. Use `zero hooks list`.") @@ -566,10 +650,24 @@ Commands: info Show plugin details and lockfile metadata add Install a plugin (manifest-validated, pinned in plugins.lock) remove Remove an installed plugin and its lockfile entry + enable Enable a plugin via its plugin.json + disable Disable a plugin via its plugin.json `) return err } +func writePluginsToggleHelp(w io.Writer, command string) error { + _, err := fmt.Fprintf(w, `Usage: + zero plugins %s [flags] + +Flags: + --user Target only user plugins (ignore ./.zero/plugins) + --json Print command result as JSON + -h, --help Show this help +`, command) + return err +} + func writePluginsListHelp(w io.Writer) error { _, err := fmt.Fprint(w, `Usage: zero plugins list [flags] diff --git a/internal/cli/extensions_test.go b/internal/cli/extensions_test.go index 8b613fd3e0..e6e531b93b 100644 --- a/internal/cli/extensions_test.go +++ b/internal/cli/extensions_test.go @@ -5,6 +5,7 @@ import ( "context" "encoding/json" "errors" + "os" "path/filepath" "strings" "testing" @@ -333,3 +334,123 @@ func TestRunMCPPermissionsHelpDoesNotOpenStore(t *testing.T) { }) } } + +func TestRunPluginsEnableDisable(t *testing.T) { + cwd := t.TempDir() + pluginDir := filepath.Join(cwd, ".zero", "plugins", "demo") + if err := os.MkdirAll(pluginDir, 0o700); err != nil { + t.Fatal(err) + } + manifestPath := filepath.Join(pluginDir, "plugin.json") + if err := os.WriteFile(manifestPath, []byte(`{ + "schemaVersion": 1, + "id": "zero.demo", + "name": "Demo", + "version": "1.0.0" +} +`), 0o600); err != nil { + t.Fatal(err) + } + + deps := appDeps{getwd: func() (string, error) { return cwd, nil }} + + var stdout bytes.Buffer + var stderr bytes.Buffer + exitCode := runWithDeps([]string{"plugins", "disable", "zero.demo", "--json"}, &stdout, &stderr, deps) + if exitCode != exitSuccess { + t.Fatalf("disable exit=%d stderr=%s", exitCode, stderr.String()) + } + var disablePayload plugins.SetEnabledResult + if err := json.Unmarshal(stdout.Bytes(), &disablePayload); err != nil { + t.Fatalf("decode disable JSON: %v\n%s", err, stdout.String()) + } + if disablePayload.ID != "zero.demo" || disablePayload.Enabled || !disablePayload.Changed { + t.Fatalf("unexpected disable payload: %#v", disablePayload) + } + + raw, err := os.ReadFile(manifestPath) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(raw), `"enabled": false`) { + t.Fatalf("manifest not disabled: %s", raw) + } + + stdout.Reset() + stderr.Reset() + exitCode = runWithDeps([]string{"plugins", "disable", "zero.demo"}, &stdout, &stderr, deps) + if exitCode != exitSuccess { + t.Fatalf("noop disable exit=%d stderr=%s", exitCode, stderr.String()) + } + if !strings.Contains(stdout.String(), "was already disabled") { + t.Fatalf("noop disable output: %s", stdout.String()) + } + + stdout.Reset() + stderr.Reset() + exitCode = runWithDeps([]string{"plugins", "enable", "zero.demo"}, &stdout, &stderr, deps) + if exitCode != exitSuccess { + t.Fatalf("enable exit=%d stderr=%s", exitCode, stderr.String()) + } + if !strings.Contains(stdout.String(), "is now enabled") { + t.Fatalf("enable output: %s", stdout.String()) + } + + stdout.Reset() + stderr.Reset() + exitCode = runWithDeps([]string{"plugins", "enable", "missing-plugin"}, &stdout, &stderr, deps) + if exitCode != exitUsage { + t.Fatalf("missing plugin exit=%d want %d stderr=%s", exitCode, exitUsage, stderr.String()) + } +} + +func TestRunPluginsDisableUserIgnoresProject(t *testing.T) { + home := t.TempDir() + cwd := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", home) + t.Setenv("HOME", home) + + userManifest := filepath.Join(home, "zero", "plugins", "demo", "plugin.json") + projectManifest := filepath.Join(cwd, ".zero", "plugins", "demo", "plugin.json") + for _, path := range []string{userManifest, projectManifest} { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(`{ + "schemaVersion": 1, + "id": "zero.demo", + "name": "Demo", + "version": "1.0.0", + "enabled": true +} +`), 0o600); err != nil { + t.Fatal(err) + } + } + + deps := appDeps{getwd: func() (string, error) { return cwd, nil }} + var stdout bytes.Buffer + var stderr bytes.Buffer + exitCode := runWithDeps([]string{"plugins", "disable", "zero.demo", "--user"}, &stdout, &stderr, deps) + if exitCode != exitSuccess { + t.Fatalf("disable --user exit=%d stderr=%s", exitCode, stderr.String()) + } + if !strings.Contains(stdout.String(), "is now disabled") { + t.Fatalf("disable --user output: %s", stdout.String()) + } + + userRaw, err := os.ReadFile(userManifest) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(userRaw), `"enabled": false`) { + t.Fatalf("user manifest not disabled: %s", userRaw) + } + projectRaw, err := os.ReadFile(projectManifest) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(projectRaw), `"enabled": false`) { + t.Fatalf("project manifest should stay enabled: %s", projectRaw) + } +} diff --git a/internal/plugins/enabled.go b/internal/plugins/enabled.go new file mode 100644 index 0000000000..f3b4b357b9 --- /dev/null +++ b/internal/plugins/enabled.go @@ -0,0 +1,114 @@ +package plugins + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "time" +) + +// SetEnabledResult describes a successful enable/disable of one plugin manifest. +type SetEnabledResult struct { + ID string `json:"id"` + Enabled bool `json:"enabled"` + Changed bool `json:"changed"` + Source Source `json:"source"` + ManifestPath string `json:"manifestPath"` +} + +// FindByID returns the loaded plugin with the given id after normal discovery +// and precedence (project overrides user). A missing id returns ok=false. +func FindByID(options LoadOptions, id string) (LoadedPlugin, bool, error) { + id = strings.TrimSpace(id) + if id == "" { + return LoadedPlugin{}, false, errors.New("plugin id is required") + } + result, err := Load(options) + if err != nil { + return LoadedPlugin{}, false, err + } + for _, plugin := range result.Plugins { + if plugin.ID == id { + return plugin, true, nil + } + } + return LoadedPlugin{}, false, nil +} + +// SetEnabled updates the "enabled" field in plugin.json, preserving the rest of +// the manifest. It returns whether the file actually changed. +func SetEnabled(manifestPath string, enabled bool) (changed bool, err error) { + manifestPath = strings.TrimSpace(manifestPath) + if manifestPath == "" { + return false, errors.New("plugin manifest path is required") + } + resolved, err := filepath.Abs(manifestPath) + if err != nil { + return false, err + } + + raw, err := os.ReadFile(resolved) + if err != nil { + return false, err + } + var obj map[string]any + if err := json.Unmarshal(raw, &obj); err != nil { + return false, fmt.Errorf("parse plugin manifest: %w", err) + } + if obj == nil { + return false, errors.New("plugin manifest must be a JSON object") + } + + previous, err := optionalBool(obj, "enabled", true) + if err != nil { + return false, err + } + if previous == enabled { + return false, nil + } + obj["enabled"] = enabled + + data, err := json.MarshalIndent(obj, "", " ") + if err != nil { + return false, err + } + mode := os.FileMode(0o644) + if info, statErr := os.Stat(resolved); statErr == nil { + mode = info.Mode().Perm() + } + tempPath := fmt.Sprintf("%s.tmp-%d-%d", resolved, os.Getpid(), time.Now().UnixNano()) + if err := os.WriteFile(tempPath, append(data, '\n'), mode); err != nil { + return false, err + } + if err := os.Rename(tempPath, resolved); err != nil { + _ = os.Remove(tempPath) + return false, err + } + return true, nil +} + +// SetEnabledByID finds a plugin by id (respecting LoadOptions) and toggles its +// manifest enabled field. +func SetEnabledByID(options LoadOptions, id string, enabled bool) (SetEnabledResult, error) { + plugin, ok, err := FindByID(options, id) + if err != nil { + return SetEnabledResult{}, err + } + if !ok { + return SetEnabledResult{}, fmt.Errorf("%w: %q", ErrNotInstalled, id) + } + changed, err := SetEnabled(plugin.ManifestPath, enabled) + if err != nil { + return SetEnabledResult{}, err + } + return SetEnabledResult{ + ID: plugin.ID, + Enabled: enabled, + Changed: changed, + Source: plugin.Source, + ManifestPath: plugin.ManifestPath, + }, nil +} diff --git a/internal/plugins/enabled_test.go b/internal/plugins/enabled_test.go new file mode 100644 index 0000000000..340cd549b2 --- /dev/null +++ b/internal/plugins/enabled_test.go @@ -0,0 +1,152 @@ +package plugins + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "runtime" + "testing" +) + +func TestSetEnabledTogglesManifestAndIsIdempotent(t *testing.T) { + root := t.TempDir() + pluginDir := filepath.Join(root, "demo") + writePluginManifest(t, pluginDir, map[string]any{ + "schemaVersion": 1, + "id": "zero.demo", + "name": "Demo", + "version": "1.0.0", + "description": "keep me", + "tools": []any{}, + }) + manifestPath := filepath.Join(pluginDir, "plugin.json") + + changed, err := SetEnabled(manifestPath, false) + if err != nil { + t.Fatalf("SetEnabled(false): %v", err) + } + if !changed { + t.Fatal("expected first disable to change the manifest") + } + + raw, err := os.ReadFile(manifestPath) + if err != nil { + t.Fatal(err) + } + var obj map[string]any + if err := json.Unmarshal(raw, &obj); err != nil { + t.Fatalf("re-read manifest: %v", err) + } + if obj["enabled"] != false { + t.Fatalf("enabled = %#v, want false", obj["enabled"]) + } + if obj["description"] != "keep me" { + t.Fatalf("description was not preserved: %#v", obj["description"]) + } + + changed, err = SetEnabled(manifestPath, false) + if err != nil { + t.Fatalf("SetEnabled(false) again: %v", err) + } + if changed { + t.Fatal("expected second disable to be a no-op") + } + + changed, err = SetEnabled(manifestPath, true) + if err != nil { + t.Fatalf("SetEnabled(true): %v", err) + } + if !changed { + t.Fatal("expected enable to change the manifest") + } +} + +func TestSetEnabledByIDRespectsUserOnlyFilter(t *testing.T) { + dir := t.TempDir() + userRoot := filepath.Join(dir, "user") + projectRoot := filepath.Join(dir, "project") + writePluginManifest(t, filepath.Join(userRoot, "demo"), map[string]any{ + "schemaVersion": 1, + "id": "zero.demo", + "name": "User Demo", + "version": "0.1.0", + "enabled": true, + }) + writePluginManifest(t, filepath.Join(projectRoot, "demo"), map[string]any{ + "schemaVersion": 1, + "id": "zero.demo", + "name": "Project Demo", + "version": "0.2.0", + "enabled": true, + }) + + result, err := SetEnabledByID(LoadOptions{ + Roots: []Root{ + {Source: SourceUser, Path: userRoot}, + {Source: SourceProject, Path: projectRoot}, + }, + }, "zero.demo", false) + if err != nil { + t.Fatalf("SetEnabledByID: %v", err) + } + if result.Source != SourceProject { + t.Fatalf("source = %s, want project (precedence)", result.Source) + } + if !result.Changed || result.Enabled { + t.Fatalf("unexpected result: %#v", result) + } + + userOnly, err := SetEnabledByID(LoadOptions{ + Roots: []Root{ + {Source: SourceUser, Path: userRoot}, + {Source: SourceProject, Path: projectRoot}, + }, + ExcludeProject: true, + }, "zero.demo", false) + if err != nil { + t.Fatalf("SetEnabledByID user-only: %v", err) + } + if userOnly.Source != SourceUser { + t.Fatalf("user-only source = %s, want user", userOnly.Source) + } +} + +func TestSetEnabledPreservesManifestMode(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Windows does not preserve chmod bits in os.Stat mode") + } + root := t.TempDir() + pluginDir := filepath.Join(root, "demo") + writePluginManifest(t, pluginDir, map[string]any{ + "schemaVersion": 1, + "id": "zero.demo", + "name": "Demo", + "version": "1.0.0", + }) + manifestPath := filepath.Join(pluginDir, "plugin.json") + if err := os.Chmod(manifestPath, 0o644); err != nil { + t.Fatal(err) + } + + if _, err := SetEnabled(manifestPath, false); err != nil { + t.Fatalf("SetEnabled: %v", err) + } + info, err := os.Stat(manifestPath) + if err != nil { + t.Fatal(err) + } + if got := info.Mode().Perm(); got != 0o644 { + t.Fatalf("mode = %04o, want 0644", got) + } +} + +func TestSetEnabledByIDMissingPlugin(t *testing.T) { + _, err := SetEnabledByID(LoadOptions{Roots: []Root{{Source: SourceUser, Path: t.TempDir()}}}, "missing", false) + if err == nil { + t.Fatal("expected missing plugin error") + } + if !errors.Is(err, ErrNotInstalled) { + t.Fatalf("error = %v, want ErrNotInstalled", err) + } +} From c4cf774ef58384d0f239ed48f42e2d0269accba8 Mon Sep 17 00:00:00 2001 From: Ayush7614 Date: Sat, 17 Oct 2026 17:12:23 +0530 Subject: [PATCH 2/7] fix(plugins): serialize toggles with installs and preserve manifest bytes Address review findings on the enable/disable CLI: - Take the same cross-process installtxn lock plugins add/remove take on the plugin's install root before the final lookup and read, and publish plugin.json with installtxn.WriteFileAtomically while holding it. - Re-resolve the plugin under the lock so a concurrent install can never be overwritten with manifest bytes read before it committed, retrying when precedence moves to the other root; a plugin removed under the lock reports ErrNotInstalled instead of being recreated. - Edit the enabled value in place (a targeted token walk) so field order, formatting, and numeric literals survive; the old decode/re-encode dropped precision (9007199254740993 became 9007199254740992) and sorted the keys. - Fail closed on manifest stat errors, refresh a clean plugins.lock hash after a toggle, and leave pre-existing drift in place instead of absorbing it into the lockfile. - Redact the text-mode output, reject an empty plugin id as a usage error, and document project-over-user precedence in the help text. --- docs/EXTENDING.md | 2 +- internal/cli/extensions.go | 18 +- internal/cli/extensions_test.go | 73 ++++ internal/plugins/enabled.go | 355 ++++++++++++++++--- internal/plugins/enabled_test.go | 574 +++++++++++++++++++++++++++++-- internal/plugins/info.go | 3 +- 6 files changed, 939 insertions(+), 86 deletions(-) diff --git a/docs/EXTENDING.md b/docs/EXTENDING.md index 38b49303b2..fec923f453 100644 --- a/docs/EXTENDING.md +++ b/docs/EXTENDING.md @@ -352,7 +352,7 @@ zero plugins enable github-pr-review # sets "enabled": true in plugin.json zero plugins remove github-pr-review # alias: rm ``` -A plugin is active when it is present under a plugins directory and its `plugin.json` has `"enabled": true` (the default when the field is omitted). Use `zero plugins disable ` / `zero plugins enable ` to toggle that field without removing the plugin. Pass `--user` to target only user plugins and ignore `./.zero/plugins`. +A plugin is active when it is present under a plugins directory and its `plugin.json` has `"enabled": true` (the default when the field is omitted). Use `zero plugins disable ` / `zero plugins enable ` to toggle that field without removing the plugin. Pass `--user` to target only user plugins and ignore `./.zero/plugins`; without it, a project plugin with the same id takes precedence. The toggle edits the `enabled` value in place — the rest of the manifest keeps its formatting, field order, and numeric literals — and serializes with `plugins add` / `plugins remove` on the same plugins root. Plugin commands run with the plugin directory as their working directory. Use relative paths; the loader resolves them at activation time. diff --git a/internal/cli/extensions.go b/internal/cli/extensions.go index c50f55c6fb..fe8da1c533 100644 --- a/internal/cli/extensions.go +++ b/internal/cli/extensions.go @@ -115,7 +115,10 @@ func runPluginsToggle(args []string, stdout io.Writer, stderr io.Writer, deps ap if len(positional) != 1 { return writeExecUsageError(stderr, fmt.Sprintf("usage: zero plugins %s [--user] [--json]", commandName)) } - pluginID := positional[0] + pluginID := strings.TrimSpace(positional[0]) + if pluginID == "" { + return writeExecUsageError(stderr, fmt.Sprintf("usage: zero plugins %s [--user] [--json]", commandName)) + } cwd, err := deps.getwd() if err != nil { @@ -140,11 +143,11 @@ func runPluginsToggle(args []string, stdout io.Writer, stderr io.Writer, deps ap } return exitSuccess } - if result.Changed { - if _, err := fmt.Fprintf(stdout, "Plugin %s is now %s in %s.\n", result.ID, state, result.ManifestPath); err != nil { - return exitCrash - } - } else if _, err := fmt.Fprintf(stdout, "Plugin %s was already %s in %s.\n", result.ID, state, result.ManifestPath); err != nil { + message := fmt.Sprintf("Plugin %s is now %s in %s.\n", result.ID, state, result.ManifestPath) + if !result.Changed { + message = fmt.Sprintf("Plugin %s was already %s in %s.\n", result.ID, state, result.ManifestPath) + } + if _, err := fmt.Fprint(stdout, redaction.RedactString(message, redaction.Options{})); err != nil { return exitCrash } return exitSuccess @@ -664,6 +667,9 @@ Flags: --user Target only user plugins (ignore ./.zero/plugins) --json Print command result as JSON -h, --help Show this help + +Without --user, a project plugin with the same id takes precedence over a user +plugin, matching the loader's discovery order. `, command) return err } diff --git a/internal/cli/extensions_test.go b/internal/cli/extensions_test.go index e6e531b93b..b8b7e17038 100644 --- a/internal/cli/extensions_test.go +++ b/internal/cli/extensions_test.go @@ -337,6 +337,9 @@ func TestRunMCPPermissionsHelpDoesNotOpenStore(t *testing.T) { func TestRunPluginsEnableDisable(t *testing.T) { cwd := t.TempDir() + home := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", home) + t.Setenv("HOME", home) pluginDir := filepath.Join(cwd, ".zero", "plugins", "demo") if err := os.MkdirAll(pluginDir, 0o700); err != nil { t.Fatal(err) @@ -404,6 +407,76 @@ func TestRunPluginsEnableDisable(t *testing.T) { } } +// The text-mode toggle output runs through the redaction pipeline, so a +// manifest path that contains something secret-shaped is masked. +func TestRunPluginsToggleTextOutputIsRedacted(t *testing.T) { + cwd := t.TempDir() + home := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", home) + t.Setenv("HOME", home) + secretDir := "sk-proj-abcdefghijklmnopqrstuvwxyz" + pluginDir := filepath.Join(cwd, ".zero", "plugins", secretDir) + if err := os.MkdirAll(pluginDir, 0o700); err != nil { + t.Fatal(err) + } + manifestPath := filepath.Join(pluginDir, "plugin.json") + if err := os.WriteFile(manifestPath, []byte(`{ + "schemaVersion": 1, + "id": "zero.demo", + "name": "Demo", + "version": "1.0.0" +} +`), 0o600); err != nil { + t.Fatal(err) + } + + deps := appDeps{getwd: func() (string, error) { return cwd, nil }} + + var stdout bytes.Buffer + var stderr bytes.Buffer + exitCode := runWithDeps([]string{"plugins", "disable", "zero.demo"}, &stdout, &stderr, deps) + if exitCode != exitSuccess { + t.Fatalf("disable exit=%d stderr=%s", exitCode, stderr.String()) + } + if strings.Contains(stdout.String(), secretDir) { + t.Fatalf("toggle text leaked a secret-shaped manifest path: %q", stdout.String()) + } + if !strings.Contains(stdout.String(), "[REDACTED]") { + t.Fatalf("toggle text was not redacted: %q", stdout.String()) + } + + stdout.Reset() + stderr.Reset() + exitCode = runWithDeps([]string{"plugins", "disable", "zero.demo"}, &stdout, &stderr, deps) + if exitCode != exitSuccess { + t.Fatalf("noop disable exit=%d stderr=%s", exitCode, stderr.String()) + } + if !strings.Contains(stdout.String(), "was already disabled") { + t.Fatalf("noop toggle output: %q", stdout.String()) + } + if strings.Contains(stdout.String(), secretDir) { + t.Fatalf("noop toggle text leaked a secret-shaped manifest path: %q", stdout.String()) + } +} + +func TestRunPluginsToggleRejectsEmptyID(t *testing.T) { + deps := appDeps{getwd: func() (string, error) { return t.TempDir(), nil }} + + for _, subcommand := range []string{"enable", "disable"} { + t.Run(subcommand, func(t *testing.T) { + var stdout bytes.Buffer + var stderr bytes.Buffer + exitCode := runWithDeps([]string{"plugins", subcommand, ""}, &stdout, &stderr, deps) + if exitCode != exitUsage { + t.Fatalf("exit=%d want %d stderr=%s", exitCode, exitUsage, stderr.String()) + } + if !strings.Contains(stderr.String(), "usage: zero plugins "+subcommand) { + t.Fatalf("stderr = %q", stderr.String()) + } + }) + } +} + func TestRunPluginsDisableUserIgnoresProject(t *testing.T) { home := t.TempDir() cwd := t.TempDir() diff --git a/internal/plugins/enabled.go b/internal/plugins/enabled.go index f3b4b357b9..38ce5d8008 100644 --- a/internal/plugins/enabled.go +++ b/internal/plugins/enabled.go @@ -1,13 +1,15 @@ package plugins import ( + "bytes" "encoding/json" "errors" "fmt" + "io" "os" - "path/filepath" "strings" - "time" + + "github.com/Twigpine/zero/internal/installtxn" ) // SetEnabledResult describes a successful enable/disable of one plugin manifest. @@ -19,6 +21,10 @@ type SetEnabledResult struct { ManifestPath string `json:"manifestPath"` } +// maxEnabledRelockAttempts bounds how many times SetEnabledByID re-resolves the +// plugin after it moves to another install root while waiting for the lock. +const maxEnabledRelockAttempts = 4 + // FindByID returns the loaded plugin with the given id after normal discovery // and precedence (project overrides user). A missing id returns ok=false. func FindByID(options LoadOptions, id string) (LoadedPlugin, bool, error) { @@ -38,77 +44,326 @@ func FindByID(options LoadOptions, id string) (LoadedPlugin, bool, error) { return LoadedPlugin{}, false, nil } -// SetEnabled updates the "enabled" field in plugin.json, preserving the rest of -// the manifest. It returns whether the file actually changed. -func SetEnabled(manifestPath string, enabled bool) (changed bool, err error) { - manifestPath = strings.TrimSpace(manifestPath) - if manifestPath == "" { - return false, errors.New("plugin manifest path is required") - } - resolved, err := filepath.Abs(manifestPath) - if err != nil { - return false, err +// SetEnabledByID finds a plugin by id (respecting LoadOptions) and toggles the +// top-level "enabled" field of its plugin.json. +// +// The read-modify-write is serialized with plugin installs and removals: it +// takes the same cross-process installtxn lock they take on the plugin's +// install root, re-resolves the plugin under that lock, and publishes the +// manifest with an atomic rename while still holding it, so a concurrent +// install can never be interleaved between the read and the write. Only the +// bytes of the "enabled" value change, so field order, formatting, and numeric +// literals in the rest of the manifest survive the toggle. +func SetEnabledByID(options LoadOptions, id string, enabled bool) (SetEnabledResult, error) { + for attempt := 0; ; attempt++ { + plugin, ok, err := FindByID(options, id) + if err != nil { + return SetEnabledResult{}, err + } + if !ok { + return SetEnabledResult{}, fmt.Errorf("%w: %q", ErrNotInstalled, id) + } + // Take the install root lock before the final lookup and read so an + // install or remove cannot swap the tree between them. + unlock, err := installtxn.Lock(plugin.Root) + if err != nil { + return SetEnabledResult{}, err + } + final, ok, err := FindByID(options, id) + if err != nil { + unlock() + return SetEnabledResult{}, err + } + if !ok { + unlock() + return SetEnabledResult{}, fmt.Errorf("%w: %q", ErrNotInstalled, id) + } + if final.Root != plugin.Root { + // Precedence moved to another root while this lock was pending; + // retry against the root that wins now so the edit still serializes + // with that root's installs. + unlock() + if attempt >= maxEnabledRelockAttempts { + return SetEnabledResult{}, fmt.Errorf("plugin %q kept changing roots while waiting for the install lock", id) + } + continue + } + changed, err := setEnabledLocked(final, enabled) + unlock() + if err != nil { + return SetEnabledResult{}, err + } + return SetEnabledResult{ + ID: final.ID, + Enabled: enabled, + Changed: changed, + Source: final.Source, + ManifestPath: final.ManifestPath, + }, nil } +} - raw, err := os.ReadFile(resolved) +// setEnabledLocked performs the manifest read-modify-write while the caller +// holds the installtxn lock for the plugin's install root. +func setEnabledLocked(plugin LoadedPlugin, enabled bool) (bool, error) { + raw, err := os.ReadFile(plugin.ManifestPath) if err != nil { return false, err } - var obj map[string]any - if err := json.Unmarshal(raw, &obj); err != nil { - return false, fmt.Errorf("parse plugin manifest: %w", err) - } - if obj == nil { - return false, errors.New("plugin manifest must be a JSON object") - } - - previous, err := optionalBool(obj, "enabled", true) + data, changed, err := toggleEnabledManifest(raw, enabled) if err != nil { return false, err } - if previous == enabled { + if !changed { return false, nil } - obj["enabled"] = enabled - data, err := json.MarshalIndent(obj, "", " ") + // Read the lockfile before the edit so the refresh below only runs when the + // installed tree still matched its recorded hash; a toggle must never mask + // pre-existing drift. + lock, entry, hashClean := cleanLockEntry(plugin) + + // Fail closed on stat errors instead of widening the permissions. + info, err := os.Stat(plugin.ManifestPath) if err != nil { + return false, fmt.Errorf("inspect plugin manifest: %w", err) + } + if err := installtxn.WriteFileAtomically(plugin.ManifestPath, data, info.Mode().Perm()); err != nil { return false, err } - mode := os.FileMode(0o644) - if info, statErr := os.Stat(resolved); statErr == nil { - mode = info.Mode().Perm() + if !hashClean { + return true, nil } - tempPath := fmt.Sprintf("%s.tmp-%d-%d", resolved, os.Getpid(), time.Now().UnixNano()) - if err := os.WriteFile(tempPath, append(data, '\n'), mode); err != nil { - return false, err + after, err := hashTree(plugin.PluginDir) + if err != nil { + return true, fmt.Errorf("plugin manifest updated but %s hash refresh failed: %w", LockFileName, err) } - if err := os.Rename(tempPath, resolved); err != nil { - _ = os.Remove(tempPath) - return false, err + entry.Hash = after + lock[plugin.ID] = entry + if err := writeLock(plugin.Root, lock); err != nil { + return true, fmt.Errorf("plugin manifest updated but %s hash refresh failed: %w", LockFileName, err) } return true, nil } -// SetEnabledByID finds a plugin by id (respecting LoadOptions) and toggles its -// manifest enabled field. -func SetEnabledByID(options LoadOptions, id string, enabled bool) (SetEnabledResult, error) { - plugin, ok, err := FindByID(options, id) +// cleanLockEntry reports whether the tree on disk still matches the lockfile +// entry recorded for the plugin and returns both for a refresh. +func cleanLockEntry(plugin LoadedPlugin) (map[string]LockEntry, LockEntry, bool) { + lock, err := ReadLock(plugin.Root) if err != nil { - return SetEnabledResult{}, err + return nil, LockEntry{}, false } + entry, ok := lock[plugin.ID] if !ok { - return SetEnabledResult{}, fmt.Errorf("%w: %q", ErrNotInstalled, id) + return nil, LockEntry{}, false } - changed, err := SetEnabled(plugin.ManifestPath, enabled) + current, err := hashTree(plugin.PluginDir) + if err != nil || current != entry.Hash { + return nil, LockEntry{}, false + } + return lock, entry, true +} + +// toggleEnabledManifest returns raw with the top-level "enabled" member set to +// enabled. A missing or null value counts as enabled, matching the loader's +// optionalBool fallback. changed reports whether the result differs from raw. +func toggleEnabledManifest(raw []byte, enabled bool) (out []byte, changed bool, err error) { + dec := json.NewDecoder(bytes.NewReader(raw)) + openTok, err := dec.Token() if err != nil { - return SetEnabledResult{}, err - } - return SetEnabledResult{ - ID: plugin.ID, - Enabled: enabled, - Changed: changed, - Source: plugin.Source, - ManifestPath: plugin.ManifestPath, - }, nil + return nil, false, fmt.Errorf("parse plugin manifest: %w", err) + } + if delim, ok := openTok.(json.Delim); !ok || delim != '{' { + return nil, false, errors.New("plugin manifest must be a JSON object") + } + openEnd := dec.InputOffset() + + current := true + var valueStart, valueEnd int64 = -1, -1 + for dec.More() { + keyTok, err := dec.Token() + if err != nil { + return nil, false, fmt.Errorf("parse plugin manifest: %w", err) + } + key, ok := keyTok.(string) + if !ok { + return nil, false, errors.New("plugin manifest must be a JSON object") + } + keyEnd := dec.InputOffset() + if key != "enabled" { + if err := skipManifestValue(dec); err != nil { + return nil, false, fmt.Errorf("parse plugin manifest: %w", err) + } + continue + } + valueTok, err := dec.Token() + if err != nil { + return nil, false, fmt.Errorf("parse plugin manifest: %w", err) + } + var literal string + switch value := valueTok.(type) { + case bool: + current = value + literal = "false" + if value { + literal = "true" + } + case nil: + current = true + literal = "null" + default: + return nil, false, ManifestError{FieldPath: "enabled", Message: "Expected a boolean."} + } + start, err := enabledValueOffset(raw, keyEnd) + if err != nil { + return nil, false, err + } + if start+int64(len(literal)) > int64(len(raw)) || + !bytes.Equal(raw[start:start+int64(len(literal))], []byte(literal)) { + return nil, false, errors.New("parse plugin manifest: cannot locate the enabled value") + } + // A duplicate key keeps the last occurrence, matching json.Unmarshal. + valueStart, valueEnd = start, start+int64(len(literal)) + } + closingTok, err := dec.Token() + if err != nil { + return nil, false, fmt.Errorf("parse plugin manifest: %w", err) + } + if delim, ok := closingTok.(json.Delim); !ok || delim != '}' { + return nil, false, errors.New("plugin manifest must be a JSON object") + } + closingEnd := dec.InputOffset() + if _, err := dec.Token(); err != io.EOF { + return nil, false, errors.New("parse plugin manifest: unexpected data after the top-level object") + } + + if current == enabled { + return nil, false, nil + } + newLiteral := "false" + if enabled { + newLiteral = "true" + } + if valueStart >= 0 { + out := make([]byte, 0, len(raw)-int(valueEnd-valueStart)+len(newLiteral)) + out = append(out, raw[:valueStart]...) + out = append(out, newLiteral...) + out = append(out, raw[valueEnd:]...) + return out, true, nil + } + return insertEnabledMember(raw, openEnd, closingEnd-1, newLiteral), true, nil +} + +// enabledValueOffset returns the byte offset of the value that follows the +// colon after an "enabled" key token that ended at keyEnd. +func enabledValueOffset(raw []byte, keyEnd int64) (int64, error) { + i := keyEnd + for i < int64(len(raw)) && isJSONSpace(raw[i]) { + i++ + } + if i >= int64(len(raw)) || raw[i] != ':' { + return 0, errors.New("parse plugin manifest: missing colon after key") + } + i++ + for i < int64(len(raw)) && isJSONSpace(raw[i]) { + i++ + } + return i, nil +} + +// insertEnabledMember adds a top-level "enabled" member to a manifest that has +// none, mirroring the document's own whitespace style where it can. openEnd is +// the byte offset just after the opening brace and bracePos is the byte index +// of the closing brace. +func insertEnabledMember(raw []byte, openEnd, bracePos int64, literal string) []byte { + insertPos := bracePos + for insertPos > openEnd && isJSONSpace(raw[insertPos-1]) { + insertPos-- + } + + newline := "\n" + if bytes.Contains(raw, []byte("\r\n")) { + newline = "\r\n" + } + + first := openEnd + for first < bracePos && isJSONSpace(raw[first]) { + first++ + } + empty := first >= bracePos + multiline := bytes.IndexByte(raw[openEnd:bracePos], '\n') >= 0 + + member := `"enabled": ` + literal + var insert string + switch { + case empty && !multiline: + insert = member + case empty && multiline: + insert = newline + closingLineIndent(raw, openEnd, bracePos) + " " + member + case !empty && !multiline: + insert = "," + member + default: + insert = "," + newline + memberLineIndent(raw, openEnd, first) + member + } + + out := make([]byte, 0, len(raw)+len(insert)) + out = append(out, raw[:insertPos]...) + out = append(out, insert...) + out = append(out, raw[insertPos:]...) + return out +} + +// memberLineIndent returns the indentation of the line the first member of a +// JSON object starts on. first is the byte index of that member's first token. +func memberLineIndent(raw []byte, openEnd, first int64) string { + lineStart := first + for lineStart > openEnd && raw[lineStart-1] != '\n' { + lineStart-- + } + end := lineStart + for end < first && (raw[end] == ' ' || raw[end] == '\t') { + end++ + } + return string(raw[lineStart:end]) +} + +// closingLineIndent returns the indentation before an object's closing brace. +func closingLineIndent(raw []byte, openEnd, bracePos int64) string { + start := bracePos + for start > openEnd && (raw[start-1] == ' ' || raw[start-1] == '\t') { + start-- + } + return string(raw[start:bracePos]) +} + +// skipManifestValue consumes the next JSON value from dec. +func skipManifestValue(dec *json.Decoder) error { + tok, err := dec.Token() + if err != nil { + return err + } + delim, ok := tok.(json.Delim) + if !ok || (delim != '{' && delim != '[') { + return nil + } + depth := 1 + for depth > 0 { + tok, err := dec.Token() + if err != nil { + return err + } + if inner, ok := tok.(json.Delim); ok { + switch inner { + case '{', '[': + depth++ + case '}', ']': + depth-- + } + } + } + return nil +} + +func isJSONSpace(b byte) bool { + return b == ' ' || b == '\t' || b == '\n' || b == '\r' } diff --git a/internal/plugins/enabled_test.go b/internal/plugins/enabled_test.go index 340cd549b2..5e19a5b522 100644 --- a/internal/plugins/enabled_test.go +++ b/internal/plugins/enabled_test.go @@ -1,18 +1,113 @@ package plugins import ( - "encoding/json" "errors" "os" "path/filepath" "runtime" + "strings" "testing" + "time" + + "github.com/Twigpine/zero/internal/installtxn" ) -func TestSetEnabledTogglesManifestAndIsIdempotent(t *testing.T) { +func enableTestOptions(root string) LoadOptions { + return LoadOptions{Roots: []Root{{Source: SourceUser, Path: root}}} +} + +func writeRawManifest(t *testing.T, root, dir, raw string) string { + t.Helper() + pluginDir := filepath.Join(root, dir) + if err := os.MkdirAll(pluginDir, 0o700); err != nil { + t.Fatal(err) + } + manifestPath := filepath.Join(pluginDir, "plugin.json") + if err := os.WriteFile(manifestPath, []byte(raw), 0o600); err != nil { + t.Fatal(err) + } + return manifestPath +} + +func demoManifest(enabled bool) string { + state := "false" + if enabled { + state = "true" + } + return `{ + "schemaVersion": 1, + "id": "zero.demo", + "name": "Demo", + "version": "1.0.0", + "enabled": ` + state + ` +} +` +} + +func TestSetEnabledByIDPreservesManifestBytes(t *testing.T) { + root := t.TempDir() + raw := `{ + "schemaVersion": 1, + "id": "zero.demo", + "name": "Demo", + "version": "1.0.0", + "limits": { + "maxBytes": 9007199254740993 + }, + "description": "keep me", + "enabled": true, + "tools": [] +} +` + manifestPath := writeRawManifest(t, root, "demo", raw) + + result, err := SetEnabledByID(enableTestOptions(root), "zero.demo", false) + if err != nil { + t.Fatalf("SetEnabledByID(false): %v", err) + } + if !result.Changed || result.Enabled { + t.Fatalf("unexpected result: %#v", result) + } + + disabled, err := os.ReadFile(manifestPath) + if err != nil { + t.Fatal(err) + } + want := strings.Replace(raw, `"enabled": true`, `"enabled": false`, 1) + if string(disabled) != want { + t.Fatalf("toggle changed more than the enabled value:\n got %q\nwant %q", disabled, want) + } + if !strings.Contains(string(disabled), "9007199254740993") { + t.Fatal("large integer literal was rounded by the toggle") + } + + plugin, ok, err := FindByID(enableTestOptions(root), "zero.demo") + if err != nil || !ok { + t.Fatalf("FindByID after disable: ok=%v err=%v", ok, err) + } + if plugin.Enabled { + t.Fatal("loader still reports the plugin enabled after disable") + } + + result, err = SetEnabledByID(enableTestOptions(root), "zero.demo", true) + if err != nil { + t.Fatalf("SetEnabledByID(true): %v", err) + } + if !result.Changed || !result.Enabled { + t.Fatalf("unexpected enable result: %#v", result) + } + enabled, err := os.ReadFile(manifestPath) + if err != nil { + t.Fatal(err) + } + if string(enabled) != raw { + t.Fatalf("round trip did not restore the original bytes:\n got %q\nwant %q", enabled, raw) + } +} + +func TestSetEnabledByIDTogglesManifestAndIsIdempotent(t *testing.T) { root := t.TempDir() - pluginDir := filepath.Join(root, "demo") - writePluginManifest(t, pluginDir, map[string]any{ + writePluginManifest(t, filepath.Join(root, "demo"), map[string]any{ "schemaVersion": 1, "id": "zero.demo", "name": "Demo", @@ -20,48 +115,213 @@ func TestSetEnabledTogglesManifestAndIsIdempotent(t *testing.T) { "description": "keep me", "tools": []any{}, }) - manifestPath := filepath.Join(pluginDir, "plugin.json") + manifestPath := filepath.Join(root, "demo", "plugin.json") - changed, err := SetEnabled(manifestPath, false) + result, err := SetEnabledByID(enableTestOptions(root), "zero.demo", false) if err != nil { - t.Fatalf("SetEnabled(false): %v", err) + t.Fatalf("SetEnabledByID(false): %v", err) } - if !changed { + if !result.Changed { t.Fatal("expected first disable to change the manifest") } - raw, err := os.ReadFile(manifestPath) if err != nil { t.Fatal(err) } - var obj map[string]any - if err := json.Unmarshal(raw, &obj); err != nil { - t.Fatalf("re-read manifest: %v", err) - } - if obj["enabled"] != false { - t.Fatalf("enabled = %#v, want false", obj["enabled"]) + if !strings.Contains(string(raw), `"enabled": false`) { + t.Fatalf("manifest not disabled: %s", raw) } - if obj["description"] != "keep me" { - t.Fatalf("description was not preserved: %#v", obj["description"]) + if !strings.Contains(string(raw), `"keep me"`) { + t.Fatalf("description was not preserved: %s", raw) } - changed, err = SetEnabled(manifestPath, false) + result, err = SetEnabledByID(enableTestOptions(root), "zero.demo", false) if err != nil { - t.Fatalf("SetEnabled(false) again: %v", err) + t.Fatalf("SetEnabledByID(false) again: %v", err) } - if changed { + if result.Changed { t.Fatal("expected second disable to be a no-op") } - changed, err = SetEnabled(manifestPath, true) + result, err = SetEnabledByID(enableTestOptions(root), "zero.demo", true) if err != nil { - t.Fatalf("SetEnabled(true): %v", err) + t.Fatalf("SetEnabledByID(true): %v", err) } - if !changed { + if !result.Changed { t.Fatal("expected enable to change the manifest") } } +func TestSetEnabledByIDInsertsMissingField(t *testing.T) { + t.Run("pretty manifest", func(t *testing.T) { + root := t.TempDir() + raw := `{ + "schemaVersion": 1, + "id": "zero.demo", + "name": "Demo", + "version": "1.0.0" +} +` + manifestPath := writeRawManifest(t, root, "demo", raw) + + if _, err := SetEnabledByID(enableTestOptions(root), "zero.demo", false); err != nil { + t.Fatalf("SetEnabledByID(false): %v", err) + } + disabled, err := os.ReadFile(manifestPath) + if err != nil { + t.Fatal(err) + } + wantDisabled := `{ + "schemaVersion": 1, + "id": "zero.demo", + "name": "Demo", + "version": "1.0.0", + "enabled": false +} +` + if string(disabled) != wantDisabled { + t.Fatalf("after insert:\n got %q\nwant %q", disabled, wantDisabled) + } + + if _, err := SetEnabledByID(enableTestOptions(root), "zero.demo", true); err != nil { + t.Fatalf("SetEnabledByID(true): %v", err) + } + enabled, err := os.ReadFile(manifestPath) + if err != nil { + t.Fatal(err) + } + wantEnabled := strings.Replace(wantDisabled, `"enabled": false`, `"enabled": true`, 1) + if string(enabled) != wantEnabled { + t.Fatalf("after replace:\n got %q\nwant %q", enabled, wantEnabled) + } + }) + + t.Run("compact manifest", func(t *testing.T) { + root := t.TempDir() + raw := `{"schemaVersion":1,"id":"zero.demo","name":"Demo","version":"1.0.0"}` + manifestPath := writeRawManifest(t, root, "demo", raw) + + if _, err := SetEnabledByID(enableTestOptions(root), "zero.demo", false); err != nil { + t.Fatalf("SetEnabledByID(false): %v", err) + } + disabled, err := os.ReadFile(manifestPath) + if err != nil { + t.Fatal(err) + } + want := `{"schemaVersion":1,"id":"zero.demo","name":"Demo","version":"1.0.0","enabled": false}` + if string(disabled) != want { + t.Fatalf("compact insert:\n got %q\nwant %q", disabled, want) + } + }) + + t.Run("null value", func(t *testing.T) { + root := t.TempDir() + raw := `{ + "schemaVersion": 1, + "id": "zero.demo", + "name": "Demo", + "version": "1.0.0", + "enabled": null +} +` + manifestPath := writeRawManifest(t, root, "demo", raw) + + result, err := SetEnabledByID(enableTestOptions(root), "zero.demo", true) + if err != nil { + t.Fatalf("SetEnabledByID(true): %v", err) + } + if result.Changed { + t.Fatal("null counts as enabled, so enabling must be a no-op") + } + unchanged, err := os.ReadFile(manifestPath) + if err != nil { + t.Fatal(err) + } + if string(unchanged) != raw { + t.Fatalf("no-op toggle rewrote the manifest: %q", unchanged) + } + + if _, err := SetEnabledByID(enableTestOptions(root), "zero.demo", false); err != nil { + t.Fatalf("SetEnabledByID(false): %v", err) + } + disabled, err := os.ReadFile(manifestPath) + if err != nil { + t.Fatal(err) + } + want := strings.Replace(raw, `"enabled": null`, `"enabled": false`, 1) + if string(disabled) != want { + t.Fatalf("null replacement:\n got %q\nwant %q", disabled, want) + } + }) +} + +func TestToggleEnabledManifestFormattingEdges(t *testing.T) { + cases := []struct { + name string + in string + enabled bool + want string + changed bool + }{ + {"empty object", `{}`, false, `{"enabled": false}`, true}, + {"empty object with space", `{ }`, false, `{"enabled": false }`, true}, + {"empty multiline", "{\n}", false, "{\n \"enabled\": false\n}", true}, + {"compact members", `{"a":1}`, false, `{"a":1,"enabled": false}`, true}, + {"crlf members", "{\r\n \"a\": 1\r\n}", false, "{\r\n \"a\": 1,\r\n \"enabled\": false\r\n}", true}, + {"nested enabled untouched", `{"nested":{"enabled":true},"a":2}`, false, `{"nested":{"enabled":true},"a":2,"enabled": false}`, true}, + {"replace with true", `{"enabled": false}`, true, `{"enabled": true}`, true}, + {"replace with false", `{"enabled":true}`, false, `{"enabled":false}`, true}, + {"null to false", `{"enabled": null}`, false, `{"enabled": false}`, true}, + {"null to true is a no-op", `{"enabled": null}`, true, `{"enabled": null}`, false}, + {"already enabled is a no-op", `{"enabled": true}`, true, `{"enabled": true}`, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + out, changed, err := toggleEnabledManifest([]byte(tc.in), tc.enabled) + if err != nil { + t.Fatalf("toggleEnabledManifest: %v", err) + } + if changed != tc.changed { + t.Fatalf("changed = %v, want %v", changed, tc.changed) + } + if !tc.changed { + if out != nil { + t.Fatalf("no-op returned bytes: %q", out) + } + return + } + if string(out) != tc.want { + t.Fatalf("got %q, want %q", out, tc.want) + } + }) + } +} + +func TestToggleEnabledManifestRejectsMalformedInput(t *testing.T) { + for _, raw := range []string{`{"enabled": "yes"}`, `{"enabled": 1}`, `{"enabled": []}`, `{"enabled": {}}`} { + t.Run("value "+raw, func(t *testing.T) { + _, _, err := toggleEnabledManifest([]byte(raw), false) + if err == nil { + t.Fatal("expected error") + } + var manifestErr ManifestError + if !errors.As(err, &manifestErr) { + t.Fatalf("error = %v, want ManifestError", err) + } + if !strings.Contains(err.Error(), "enabled") { + t.Fatalf("error = %v, want it to name the enabled field", err) + } + }) + } + for _, raw := range []string{``, `{`, `[]`, `null`, `"str"`, `{} {}`, `{}{}`} { + t.Run("document "+raw, func(t *testing.T) { + if _, _, err := toggleEnabledManifest([]byte(raw), false); err == nil { + t.Fatalf("toggleEnabledManifest(%q) succeeded, want error", raw) + } + }) + } +} + func TestSetEnabledByIDRespectsUserOnlyFilter(t *testing.T) { dir := t.TempDir() userRoot := filepath.Join(dir, "user") @@ -117,20 +377,19 @@ func TestSetEnabledPreservesManifestMode(t *testing.T) { t.Skip("Windows does not preserve chmod bits in os.Stat mode") } root := t.TempDir() - pluginDir := filepath.Join(root, "demo") - writePluginManifest(t, pluginDir, map[string]any{ + writePluginManifest(t, filepath.Join(root, "demo"), map[string]any{ "schemaVersion": 1, "id": "zero.demo", "name": "Demo", "version": "1.0.0", }) - manifestPath := filepath.Join(pluginDir, "plugin.json") + manifestPath := filepath.Join(root, "demo", "plugin.json") if err := os.Chmod(manifestPath, 0o644); err != nil { t.Fatal(err) } - if _, err := SetEnabled(manifestPath, false); err != nil { - t.Fatalf("SetEnabled: %v", err) + if _, err := SetEnabledByID(enableTestOptions(root), "zero.demo", false); err != nil { + t.Fatalf("SetEnabledByID: %v", err) } info, err := os.Stat(manifestPath) if err != nil { @@ -150,3 +409,262 @@ func TestSetEnabledByIDMissingPlugin(t *testing.T) { t.Fatalf("error = %v, want ErrNotInstalled", err) } } + +func TestSetEnabledPublishFailureLeavesManifestIntact(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Windows directory permissions do not block writes the way this test needs") + } + if os.Geteuid() == 0 { + t.Skip("root bypasses directory permission checks") + } + root := t.TempDir() + raw := demoManifest(true) + manifestPath := writeRawManifest(t, root, "demo", raw) + pluginDir := filepath.Dir(manifestPath) + if err := os.Chmod(pluginDir, 0o555); err != nil { + t.Fatal(err) + } + defer func() { _ = os.Chmod(pluginDir, 0o755) }() + + if _, err := SetEnabledByID(enableTestOptions(root), "zero.demo", false); err == nil { + t.Fatal("expected the publish to fail in a read-only plugin directory") + } + after, err := os.ReadFile(manifestPath) + if err != nil { + t.Fatal(err) + } + if string(after) != raw { + t.Fatalf("failed publish changed the manifest:\n got %q\nwant %q", after, raw) + } +} + +// TestSetEnabledByIDWaitsForInstallRootLock proves the toggle takes the same +// cross-process lock Install and Remove take on the plugin's install root: it +// must not complete while an install holds that lock. +func TestSetEnabledByIDWaitsForInstallRootLock(t *testing.T) { + root := t.TempDir() + manifestPath := writeRawManifest(t, root, "demo", demoManifest(true)) + + unlock, err := installtxn.Lock(root) + if err != nil { + t.Fatal(err) + } + + results := make(chan SetEnabledResult, 1) + failures := make(chan error, 1) + go func() { + result, err := SetEnabledByID(enableTestOptions(root), "zero.demo", false) + if err != nil { + failures <- err + return + } + results <- result + }() + + select { + case result := <-results: + unlock() + t.Fatalf("toggle completed while the install lock was held: %#v", result) + case err := <-failures: + unlock() + t.Fatalf("toggle failed while the install lock was held: %v", err) + case <-time.After(200 * time.Millisecond): + } + + unlock() + + select { + case result := <-results: + if !result.Changed { + t.Fatalf("toggle did not report a change: %#v", result) + } + case err := <-failures: + t.Fatalf("toggle failed after the lock was released: %v", err) + case <-time.After(10 * time.Second): + t.Fatal("toggle did not finish after the install lock was released") + } + + raw, err := os.ReadFile(manifestPath) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(raw), `"enabled": false`) { + t.Fatalf("manifest not disabled: %s", raw) + } +} + +// TestSetEnabledByIDSynchronizesWithStagedInstallCommit pauses an install +// between staging and commit, lets the toggle try to run, then commits the +// install. The toggle must apply to the newly installed manifest instead of +// overwriting it with bytes read before the install, and the lockfile entry +// must describe the tree actually on disk. +func TestSetEnabledByIDSynchronizesWithStagedInstallCommit(t *testing.T) { + root := t.TempDir() + oldRaw := demoManifest(true) + pluginDir := filepath.Dir(writeRawManifest(t, root, "zero.demo", oldRaw)) + + // Build the replacement tree with the same staging primitives Install + // uses and leave it staged but uncommitted. + src := t.TempDir() + newRaw := `{ + "schemaVersion": 1, + "id": "zero.demo", + "name": "Demo", + "version": "2.0.0", + "description": "reinstalled", + "enabled": true +} +` + srcPlugin := filepath.Join(src, "zero.demo") + if err := os.MkdirAll(srcPlugin, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(srcPlugin, "plugin.json"), []byte(newRaw), 0o600); err != nil { + t.Fatal(err) + } + staged, cleanup, err := installtxn.StageDir(root) + if err != nil { + t.Fatal(err) + } + defer cleanup() + if err := copyTree(srcPlugin, staged); err != nil { + t.Fatal(err) + } + stagedHash, err := hashTree(staged) + if err != nil { + t.Fatal(err) + } + + // An install holds the root lock from before its commit until after it. + unlock, err := installtxn.Lock(root) + if err != nil { + t.Fatal(err) + } + + results := make(chan SetEnabledResult, 1) + failures := make(chan error, 1) + go func() { + result, err := SetEnabledByID(enableTestOptions(root), "zero.demo", false) + if err != nil { + failures <- err + return + } + results <- result + }() + + select { + case result := <-results: + unlock() + t.Fatalf("toggle completed while the install lock was held: %#v", result) + case err := <-failures: + unlock() + t.Fatalf("toggle failed while the install lock was held: %v", err) + case <-time.After(200 * time.Millisecond): + } + + // Commit the staged install exactly like Install does: swap the tree and + // publish the lockfile entry while still holding the lock. + lock, err := ReadLock(root) + if err != nil { + unlock() + t.Fatal(err) + } + lock["zero.demo"] = LockEntry{Source: string(SourceUser), Hash: stagedHash} + if err := installtxn.CommitDir(pluginDir, staged, func() error { return writeLock(root, lock) }); err != nil { + unlock() + t.Fatal(err) + } + unlock() + + var result SetEnabledResult + select { + case result = <-results: + case err := <-failures: + t.Fatalf("toggle failed after the install committed: %v", err) + case <-time.After(10 * time.Second): + t.Fatal("toggle did not finish after the install committed") + } + if !result.Changed { + t.Fatalf("toggle result = %#v, want changed", result) + } + + // The toggle must have applied to the newly installed manifest, not to the + // bytes it first read. + final, err := os.ReadFile(filepath.Join(pluginDir, "plugin.json")) + if err != nil { + t.Fatal(err) + } + want := strings.Replace(newRaw, `"enabled": true`, `"enabled": false`, 1) + if string(final) != want { + t.Fatalf("manifest after concurrent install + disable:\n got %q\nwant %q", final, want) + } + + // The lockfile entry must describe the tree that is actually on disk. + entries, err := ReadLock(root) + if err != nil { + t.Fatal(err) + } + current, err := hashTree(pluginDir) + if err != nil { + t.Fatal(err) + } + if entries["zero.demo"].Hash != current { + t.Fatalf("plugins.lock hash = %q, want current tree hash %q", entries["zero.demo"].Hash, current) + } +} + +func TestSetEnabledByIDRefreshesCleanLockEntry(t *testing.T) { + root := t.TempDir() + manifestPath := writeRawManifest(t, root, "zero.demo", demoManifest(true)) + pluginDir := filepath.Dir(manifestPath) + + current, err := hashTree(pluginDir) + if err != nil { + t.Fatal(err) + } + if err := writeLock(root, map[string]LockEntry{"zero.demo": {Source: string(SourceUser), Hash: current}}); err != nil { + t.Fatal(err) + } + + if _, err := SetEnabledByID(enableTestOptions(root), "zero.demo", false); err != nil { + t.Fatalf("SetEnabledByID: %v", err) + } + entries, err := ReadLock(root) + if err != nil { + t.Fatal(err) + } + afterToggle, err := hashTree(pluginDir) + if err != nil { + t.Fatal(err) + } + if entries["zero.demo"].Hash == current { + t.Fatal("lock hash was not refreshed for a clean install") + } + if entries["zero.demo"].Hash != afterToggle { + t.Fatalf("lock hash = %q, want refreshed tree hash %q", entries["zero.demo"].Hash, afterToggle) + } + + info, err := Info(InfoOptions{LoadOptions: enableTestOptions(root)}, "zero.demo") + if err != nil { + t.Fatal(err) + } + if info.HashDrift { + t.Fatal("toggle left hash drift behind for a clean install") + } + + // Pre-existing drift must survive the next toggle instead of being + // absorbed into the lockfile. + if err := os.WriteFile(filepath.Join(pluginDir, "extra.txt"), []byte("edited\n"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := SetEnabledByID(enableTestOptions(root), "zero.demo", true); err != nil { + t.Fatalf("SetEnabledByID(true): %v", err) + } + entries, err = ReadLock(root) + if err != nil { + t.Fatal(err) + } + if entries["zero.demo"].Hash != afterToggle { + t.Fatalf("toggle absorbed pre-existing drift: hash = %q, want %q", entries["zero.demo"].Hash, afterToggle) + } +} diff --git a/internal/plugins/info.go b/internal/plugins/info.go index 0dac22570d..82b64f8464 100644 --- a/internal/plugins/info.go +++ b/internal/plugins/info.go @@ -7,7 +7,8 @@ import ( "strings" ) -// ErrNotInstalled is returned when Info cannot find a plugin with the requested id. +// ErrNotInstalled is returned when a plugin id cannot be found under the given +// LoadOptions (for example by Info or SetEnabledByID). var ErrNotInstalled = errors.New("plugin is not installed") // PluginInfo combines a loaded plugin with optional lockfile metadata. From 4d8aaf5a3ebac7d96b0842614889bacf4f4d7936 Mon Sep 17 00:00:00 2001 From: jatmn Date: Sat, 7 Nov 2026 08:01:22 -0800 Subject: [PATCH 3/7] fix(plugins): recover interrupted install transactions before toggling SetEnabledByID takes the plugin root's installtxn lock but went straight to reading and rewriting the tree. installtxn.Recover requires every holder of that lock to resolve interrupted transactions first and to abort on its error, as Install and Remove already do. Without it, a toggle after an install killed between its tree swap and its lockfile publish edited the unpublished tree, and the next install or removal restored the retained backup over it, silently undoing the enable/disable. A transaction recovery could not resolve also failed to stop the toggle. Call installtxn.Recover with the plugins reconciler right after taking the lock, and add regression tests for every interrupted state that leaves the plugin discoverable, the unresolved-transaction abort, and a plugin removed while the toggle waits on the lock. Co-Authored-By: Claude Opus 5.5 --- internal/plugins/enabled.go | 11 ++- internal/plugins/enabled_test.go | 153 +++++++++++++++++++++++++++++++ 2 files changed, 163 insertions(+), 1 deletion(-) diff --git a/internal/plugins/enabled.go b/internal/plugins/enabled.go index 38ce5d8008..f2ab4171e2 100644 --- a/internal/plugins/enabled.go +++ b/internal/plugins/enabled.go @@ -49,7 +49,8 @@ func FindByID(options LoadOptions, id string) (LoadedPlugin, bool, error) { // // The read-modify-write is serialized with plugin installs and removals: it // takes the same cross-process installtxn lock they take on the plugin's -// install root, re-resolves the plugin under that lock, and publishes the +// install root, runs the same interrupted-transaction recovery they run under +// it, re-resolves the plugin under that lock, and publishes the // manifest with an atomic rename while still holding it, so a concurrent // install can never be interleaved between the read and the write. Only the // bytes of the "enabled" value change, so field order, formatting, and numeric @@ -69,6 +70,14 @@ func SetEnabledByID(options LoadOptions, id string, enabled bool) (SetEnabledRes if err != nil { return SetEnabledResult{}, err } + // Put back anything an earlier install or removal was killed mid-commit, + // and abort if a transaction could not be resolved: editing a tree that is + // still owed a restore loses the edit when the next install or removal + // puts the backup back over it. See installtxn.Recover. + if err := installtxn.Recover(plugin.Root, reconcileInterrupted(plugin.Root)); err != nil { + unlock() + return SetEnabledResult{}, err + } final, ok, err := FindByID(options, id) if err != nil { unlock() diff --git a/internal/plugins/enabled_test.go b/internal/plugins/enabled_test.go index 5e19a5b522..3ef289e84a 100644 --- a/internal/plugins/enabled_test.go +++ b/internal/plugins/enabled_test.go @@ -668,3 +668,156 @@ func TestSetEnabledByIDRefreshesCleanLockEntry(t *testing.T) { t.Fatalf("toggle absorbed pre-existing drift: hash = %q, want %q", entries["zero.demo"].Hash, afterToggle) } } + +// TestSetEnabledByIDReportsAPluginRemovedWhileWaiting removes the plugin while +// the toggle is blocked on the install-root lock, exactly as Remove does while +// it holds that lock. The toggle must report the plugin as not installed +// instead of editing, or recreating, a tree that no longer exists. +func TestSetEnabledByIDReportsAPluginRemovedWhileWaiting(t *testing.T) { + root := t.TempDir() + pluginDir := filepath.Dir(writeRawManifest(t, root, "zero.demo", demoManifest(true))) + + unlock, err := installtxn.Lock(root) + if err != nil { + t.Fatal(err) + } + + failures := make(chan error, 1) + go func() { + _, err := SetEnabledByID(enableTestOptions(root), "zero.demo", false) + failures <- err + }() + + select { + case err := <-failures: + unlock() + t.Fatalf("toggle returned while the install lock was held: %v", err) + case <-time.After(200 * time.Millisecond): + } + + if err := installtxn.RemoveDir(pluginDir, func() error { return nil }); err != nil { + unlock() + t.Fatal(err) + } + unlock() + + select { + case err := <-failures: + if !errors.Is(err, ErrNotInstalled) { + t.Fatalf("toggle after a concurrent removal: error = %v, want ErrNotInstalled", err) + } + case <-time.After(10 * time.Second): + t.Fatal("toggle did not finish after the removal released the lock") + } + if _, err := os.Stat(pluginDir); !os.IsNotExist(err) { + t.Fatalf("toggle recreated the removed plugin: %v", err) + } +} + +// TestSetEnabledByIDResolvesInterruptedUpdatesFirst covers every point an +// update can be killed at that leaves the plugin discoverable. The toggle +// holds the install-root lock, so it has to +// run the same recovery pass Install and Remove run before it reads the tree: +// otherwise it edits, or fails to find, a tree that is still owed a restore, +// and the next install or removal puts the backup back over the user's edit. +func TestSetEnabledByIDResolvesInterruptedUpdatesFirst(t *testing.T) { + for _, state := range interruptedStates() { + t.Run(state.name, func(t *testing.T) { + u := seedInterruptedUpdate(t) + workspace := state.plant(t, u) + want := state.want(u) + if _, err := os.Lstat(u.target()); os.IsNotExist(err) { + // No root lists a plugin whose only copy is in a workspace, so the + // toggle reports it not installed without taking any lock, just as + // list and info do; the next install or removal restores it. + t.Skip("nothing is at the target, so the toggle never takes the lock") + } + + result, err := SetEnabledByID(enableTestOptions(u.dir), "zero.demo", false) + if err != nil { + t.Fatalf("toggle after the interrupted update: %v", err) + } + if !result.Changed || result.Enabled { + t.Fatalf("toggle result = %#v, want changed and disabled", result) + } + assertDisabledAfterRecovery(t, u, workspace, want) + + // The next lock holder runs recovery again. The disable has to survive + // it rather than be replaced by a backup the toggle never saw. + if err := installOther(t, u.dir, "zero.other"); err != nil { + t.Fatalf("install after the toggle: %v", err) + } + assertDisabledAfterRecovery(t, u, workspace, want) + }) + } +} + +func assertDisabledAfterRecovery(t *testing.T, u interruptedUpdate, workspace string, want recoveryWant) { + t.Helper() + data, err := os.ReadFile(filepath.Join(u.target(), "generation.txt")) + if err != nil { + t.Fatalf("reading the live tree: %v", err) + } + if string(data) != want.generation { + t.Errorf("the live tree is the %q generation, want %q", data, want.generation) + } + plugin, ok, err := FindByID(enableTestOptions(u.dir), "zero.demo") + if err != nil { + t.Fatal(err) + } + if !ok { + t.Fatal("Load does not see the toggled plugin") + } + if plugin.Version != want.version { + t.Errorf("Load sees version %q, want %q", plugin.Version, want.version) + } + if plugin.Enabled { + t.Errorf("the disable did not stick: Load sees the plugin enabled") + } + _, err = os.Stat(workspace) + if want.workspace && err != nil { + t.Errorf("the workspace should be left alone, got %v", err) + } + if !want.workspace && !os.IsNotExist(err) { + t.Errorf("the resolved workspace should be cleared, got %v", err) + } +} + +// TestSetEnabledByIDAbortsOnAnUnresolvedInterruptedUpdate leaves a workspace +// whose trees match neither lockfile hash. Recovery cannot pick one, so the +// toggle must fail without editing the live manifest or the lockfile. +func TestSetEnabledByIDAbortsOnAnUnresolvedInterruptedUpdate(t *testing.T) { + u := seedInterruptedUpdate(t) + workspace := u.plantWorkspace(t) + u.mustRename(t, u.target(), filepath.Join(workspace, "previous")) + u.mustRename(t, filepath.Join(workspace, "staged"), u.target()) + unmatched := LockEntry{Source: u.oldSource, Hash: "sha256:0000000000000000000000000000000000000000000000000000000000000000"} + lock, err := ReadLock(u.dir) + if err != nil { + t.Fatal(err) + } + lock["zero.demo"] = unmatched + if err := writeLock(u.dir, lock); err != nil { + t.Fatal(err) + } + manifestPath := filepath.Join(u.target(), "plugin.json") + before, err := os.ReadFile(manifestPath) + if err != nil { + t.Fatal(err) + } + + if _, err := SetEnabledByID(enableTestOptions(u.dir), "zero.demo", false); err == nil { + t.Fatal("toggle did not report the unresolved transaction") + } + after, err := os.ReadFile(manifestPath) + if err != nil { + t.Fatal(err) + } + if string(after) != string(before) { + t.Errorf("the aborted toggle edited the manifest:\n got %q\nwant %q", after, before) + } + assertUntouched(t, u, "new", unmatched) + if _, err := os.Stat(filepath.Join(workspace, "previous")); err != nil { + t.Errorf("the backup should still be there for a hand rescue, got %v", err) + } +} From 87ecb289ed803169ce63843cdb16c66f71af0175 Mon Sep 17 00:00:00 2001 From: jatmn Date: Sat, 7 Nov 2026 08:12:35 -0800 Subject: [PATCH 4/7] docs(plugins): say when a plugin toggle takes effect Zero reads plugin.json "enabled" only when it activates plugins at startup (runExec and the interactive TUI bootstrap), and nothing reloads them afterwards. A running interactive session therefore keeps the tools, hooks, and skills of a plugin disabled from another terminal. State that in the plugins docs and in the enable/disable help so the documented activation rule matches what the command does. Co-Authored-By: Claude Opus 5.5 --- docs/EXTENDING.md | 2 +- internal/cli/extensions.go | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/EXTENDING.md b/docs/EXTENDING.md index fec923f453..cf9695c161 100644 --- a/docs/EXTENDING.md +++ b/docs/EXTENDING.md @@ -352,7 +352,7 @@ zero plugins enable github-pr-review # sets "enabled": true in plugin.json zero plugins remove github-pr-review # alias: rm ``` -A plugin is active when it is present under a plugins directory and its `plugin.json` has `"enabled": true` (the default when the field is omitted). Use `zero plugins disable ` / `zero plugins enable ` to toggle that field without removing the plugin. Pass `--user` to target only user plugins and ignore `./.zero/plugins`; without it, a project plugin with the same id takes precedence. The toggle edits the `enabled` value in place — the rest of the manifest keeps its formatting, field order, and numeric literals — and serializes with `plugins add` / `plugins remove` on the same plugins root. +A plugin is active when it is present under a plugins directory and its `plugin.json` has `"enabled": true` (the default when the field is omitted). Use `zero plugins disable ` / `zero plugins enable ` to toggle that field without removing the plugin. Pass `--user` to target only user plugins and ignore `./.zero/plugins`; without it, a project plugin with the same id takes precedence. The toggle edits the `enabled` value in place — the rest of the manifest keeps its formatting, field order, and numeric literals — and serializes with `plugins add` / `plugins remove` on the same plugins root. Zero reads plugins when it starts, so the change applies to the next `zero exec` run or interactive session; an interactive session that is already running keeps the plugin tools, hooks, and skills it started with until you restart it. Plugin commands run with the plugin directory as their working directory. Use relative paths; the loader resolves them at activation time. diff --git a/internal/cli/extensions.go b/internal/cli/extensions.go index fe8da1c533..cc9012c3bb 100644 --- a/internal/cli/extensions.go +++ b/internal/cli/extensions.go @@ -670,6 +670,10 @@ Flags: Without --user, a project plugin with the same id takes precedence over a user plugin, matching the loader's discovery order. + +Zero reads plugins when it starts, so the change applies to the next zero exec +run or interactive session. A running interactive session keeps the plugins it +started with until you restart it. `, command) return err } From 30974778df071a6833d3d07e7e826f0f40a88d47 Mon Sep 17 00:00:00 2001 From: jatmn Date: Sat, 7 Nov 2026 08:57:52 -0800 Subject: [PATCH 5/7] fix(plugins): pin toggled manifests, redact toggle errors, honor last enabled key Address the review findings on the plugin enable/disable toggle. Pin the plugin directory before editing its manifest. The install lock only serializes cooperating installers, so swapping the plugin directory for a link after discovery redirected the read and the atomic publish through it, overwriting another manifest. The toggle now opens the directory under its install root with pathjail, refuses a link or reparse point, checks that the handle is the directory entry itself, and reads, stats, creates the temporary file, and renames through that handle. Redact every stderr message the toggle writes. Parser and not-installed usage errors echoed the raw argument, so a mistyped credential reached stderr unredacted while the toggle's other output was redacted. Validate only the last "enabled" value, as the loader does. The loader keeps the last duplicate key, but the toggle rejected an earlier, overwritten non-boolean value, so a plugin discovered as enabled could not be toggled. Co-Authored-By: Claude Opus 5.5 --- internal/cli/extensions.go | 18 +++-- internal/cli/extensions_test.go | 38 +++++++++ internal/plugins/enabled.go | 135 +++++++++++++++++++++++++++++-- internal/plugins/enabled_test.go | 105 +++++++++++++++++++++++- 4 files changed, 282 insertions(+), 14 deletions(-) diff --git a/internal/cli/extensions.go b/internal/cli/extensions.go index cc9012c3bb..0e8f2b8947 100644 --- a/internal/cli/extensions.go +++ b/internal/cli/extensions.go @@ -97,14 +97,22 @@ type pluginToggleOptions struct { user bool } +// runPluginsToggle implements `zero plugins enable|disable `. +// +// Every message it writes, including usage errors that echo the caller's +// arguments, passes through the redaction pipeline: an argument is user input +// and can be a mistyped credential. func runPluginsToggle(args []string, stdout io.Writer, stderr io.Writer, deps appDeps, disabled bool) int { commandName := "enable" if disabled { commandName = "disable" } + usageError := func(message string) int { + return writeExecUsageError(stderr, redaction.RedactString(message, redaction.Options{})) + } options, positional, help, err := parsePluginToggleArgs(args, commandName) if err != nil { - return writeExecUsageError(stderr, err.Error()) + return usageError(err.Error()) } if help { if err := writePluginsToggleHelp(stdout, commandName); err != nil { @@ -113,22 +121,22 @@ func runPluginsToggle(args []string, stdout io.Writer, stderr io.Writer, deps ap return exitSuccess } if len(positional) != 1 { - return writeExecUsageError(stderr, fmt.Sprintf("usage: zero plugins %s [--user] [--json]", commandName)) + return usageError(fmt.Sprintf("usage: zero plugins %s [--user] [--json]", commandName)) } pluginID := strings.TrimSpace(positional[0]) if pluginID == "" { - return writeExecUsageError(stderr, fmt.Sprintf("usage: zero plugins %s [--user] [--json]", commandName)) + return usageError(fmt.Sprintf("usage: zero plugins %s [--user] [--json]", commandName)) } cwd, err := deps.getwd() if err != nil { - return writeAppError(stderr, "failed to resolve workspace: "+err.Error(), exitCrash) + return writeAppError(stderr, "failed to resolve workspace: "+redaction.ErrorMessage(err, redaction.Options{}), exitCrash) } loadOptions := plugins.LoadOptions{Cwd: cwd, ExcludeProject: options.user} result, err := plugins.SetEnabledByID(loadOptions, pluginID, !disabled) if err != nil { if errors.Is(err, plugins.ErrNotInstalled) { - return writeExecUsageError(stderr, err.Error()) + return usageError(err.Error()) } return writeAppError(stderr, redaction.ErrorMessage(err, redaction.Options{}), exitCrash) } diff --git a/internal/cli/extensions_test.go b/internal/cli/extensions_test.go index b8b7e17038..4db95c2bdf 100644 --- a/internal/cli/extensions_test.go +++ b/internal/cli/extensions_test.go @@ -527,3 +527,41 @@ func TestRunPluginsDisableUserIgnoresProject(t *testing.T) { t.Fatalf("project manifest should stay enabled: %s", projectRaw) } } + +// The toggle's usage errors echo the caller's arguments, which can be a +// mistyped credential, so they pass through redaction like its other output. +func TestRunPluginsToggleUsageErrorsAreRedacted(t *testing.T) { + home := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", home) + t.Setenv("HOME", home) + deps := appDeps{getwd: func() (string, error) { return t.TempDir(), nil }} + const secret = "sk-proj-abcdefghijklmnopqrstuvwxyz" + + cases := []struct { + name string + args []string + want string + }{ + {"unknown flag", []string{"zero.demo", "--token=" + secret}, "unknown plugins"}, + {"missing plugin", []string{secret}, "plugin is not installed"}, + } + for _, subcommand := range []string{"enable", "disable"} { + for _, tc := range cases { + t.Run(subcommand+" "+tc.name, func(t *testing.T) { + var stdout bytes.Buffer + var stderr bytes.Buffer + args := append([]string{"plugins", subcommand}, tc.args...) + exitCode := runWithDeps(args, &stdout, &stderr, deps) + if exitCode != exitUsage { + t.Fatalf("exit=%d want %d stderr=%s", exitCode, exitUsage, stderr.String()) + } + if strings.Contains(stderr.String(), secret) { + t.Fatalf("usage error leaked the argument: %q", stderr.String()) + } + if !strings.Contains(stderr.String(), tc.want) || !strings.Contains(stderr.String(), "[REDACTED]") { + t.Fatalf("stderr = %q, want a redacted %q error", stderr.String(), tc.want) + } + }) + } + } +} diff --git a/internal/plugins/enabled.go b/internal/plugins/enabled.go index f2ab4171e2..b0e94f1320 100644 --- a/internal/plugins/enabled.go +++ b/internal/plugins/enabled.go @@ -7,9 +7,11 @@ import ( "fmt" "io" "os" + "path/filepath" "strings" "github.com/Twigpine/zero/internal/installtxn" + "github.com/Twigpine/zero/internal/pathjail" ) // SetEnabledResult describes a successful enable/disable of one plugin manifest. @@ -114,8 +116,20 @@ func SetEnabledByID(options LoadOptions, id string, enabled bool) (SetEnabledRes // setEnabledLocked performs the manifest read-modify-write while the caller // holds the installtxn lock for the plugin's install root. +// +// The lock only serializes cooperating installers; it does not stop the plugin +// directory from being swapped for a link after discovery found it. So the +// manifest is read and published through a handle pinned to that directory +// (openPluginDir), never by re-resolving its path. func setEnabledLocked(plugin LoadedPlugin, enabled bool) (bool, error) { - raw, err := os.ReadFile(plugin.ManifestPath) + dir, err := openPluginDir(plugin) + if err != nil { + return false, err + } + defer dir.Close() + + manifestName := filepath.Base(plugin.ManifestPath) + raw, perm, err := readManifest(dir, manifestName) if err != nil { return false, err } @@ -132,12 +146,7 @@ func setEnabledLocked(plugin LoadedPlugin, enabled bool) (bool, error) { // pre-existing drift. lock, entry, hashClean := cleanLockEntry(plugin) - // Fail closed on stat errors instead of widening the permissions. - info, err := os.Stat(plugin.ManifestPath) - if err != nil { - return false, fmt.Errorf("inspect plugin manifest: %w", err) - } - if err := installtxn.WriteFileAtomically(plugin.ManifestPath, data, info.Mode().Perm()); err != nil { + if err := publishManifest(dir, manifestName, data, perm); err != nil { return false, err } if !hashClean { @@ -155,6 +164,96 @@ func setEnabledLocked(plugin LoadedPlugin, enabled bool) (bool, error) { return true, nil } +// openPluginDir returns a handle on the plugin directory discovery found, +// confined to the plugin's install root. +// +// The directory entry must be a real directory, not a symlink, junction, or +// other reparse point, and it must be the very directory the handle opened: a +// link swapped in before the open is refused here, and one swapped in after it +// cannot redirect anything, because every later read and write is relative to +// the returned handle rather than to a path. +func openPluginDir(plugin LoadedPlugin) (*os.Root, error) { + root, name, err := pathjail.Open(plugin.Root, plugin.PluginDir) + if err != nil { + return nil, fmt.Errorf("open plugin directory: %w", err) + } + defer root.Close() + if name == "." || filepath.Base(name) != name { + return nil, fmt.Errorf("%w: plugin directory %s is not an entry of %s", pathjail.ErrEscapes, plugin.PluginDir, plugin.Root) + } + if err := pathjail.RefuseReparse(root, name); err != nil { + return nil, fmt.Errorf("open plugin directory: %w", err) + } + dir, err := root.OpenRoot(name) + if err != nil { + return nil, fmt.Errorf("open plugin directory: %w", err) + } + opened, err := dir.Stat(".") + if err != nil { + _ = dir.Close() + return nil, fmt.Errorf("inspect plugin directory: %w", err) + } + entry, err := root.Lstat(name) + if err != nil { + _ = dir.Close() + return nil, fmt.Errorf("inspect plugin directory: %w", err) + } + if entry.Mode()&(os.ModeSymlink|os.ModeIrregular) != 0 || !os.SameFile(entry, opened) { + _ = dir.Close() + return nil, fmt.Errorf("%w: plugin directory %s changed while it was being opened", pathjail.ErrReparse, plugin.PluginDir) + } + return dir, nil +} + +// readManifest reads name from dir and returns its bytes and permission bits. +// Failing on a stat error keeps the publish from widening the permissions. +func readManifest(dir *os.Root, name string) ([]byte, os.FileMode, error) { + file, err := dir.Open(name) + if err != nil { + return nil, 0, fmt.Errorf("read plugin manifest: %w", err) + } + defer file.Close() + info, err := file.Stat() + if err != nil { + return nil, 0, fmt.Errorf("inspect plugin manifest: %w", err) + } + raw, err := io.ReadAll(file) + if err != nil { + return nil, 0, fmt.Errorf("read plugin manifest: %w", err) + } + return raw, info.Mode().Perm(), nil +} + +// publishManifest replaces name in dir with data by renaming a complete +// temporary sibling over it, so a concurrent reader sees either the old +// manifest or the new one, never a partial write. +func publishManifest(dir *os.Root, name string, data []byte, perm os.FileMode) error { + temp, tempName, err := pathjail.CreateTemp(dir, ".", ".zero-manifest", "") + if err != nil { + return fmt.Errorf("write plugin manifest: %w", err) + } + defer func() { _ = dir.Remove(tempName) }() + if err := temp.Chmod(perm); err != nil { + _ = temp.Close() + return fmt.Errorf("write plugin manifest: %w", err) + } + if _, err := temp.Write(data); err != nil { + _ = temp.Close() + return fmt.Errorf("write plugin manifest: %w", err) + } + if err := temp.Sync(); err != nil { + _ = temp.Close() + return fmt.Errorf("write plugin manifest: %w", err) + } + if err := temp.Close(); err != nil { + return fmt.Errorf("write plugin manifest: %w", err) + } + if err := dir.Rename(tempName, name); err != nil { + return fmt.Errorf("write plugin manifest: %w", err) + } + return nil +} + // cleanLockEntry reports whether the tree on disk still matches the lockfile // entry recorded for the plugin and returns both for a refresh. func cleanLockEntry(plugin LoadedPlugin) (map[string]LockEntry, LockEntry, bool) { @@ -188,6 +287,7 @@ func toggleEnabledManifest(raw []byte, enabled bool) (out []byte, changed bool, openEnd := dec.InputOffset() current := true + lastInvalid := false var valueStart, valueEnd int64 = -1, -1 for dec.More() { keyTok, err := dec.Token() @@ -221,8 +321,17 @@ func toggleEnabledManifest(raw []byte, enabled bool) (out []byte, changed bool, current = true literal = "null" default: - return nil, false, ManifestError{FieldPath: "enabled", Message: "Expected a boolean."} + // Only the last occurrence of a duplicate key counts, as in the + // loader's json.Unmarshal, so an earlier non-boolean value that a + // later one overwrites is not an error. Remember it and decide after + // the last member. + if err := skipManifestComposite(dec, valueTok); err != nil { + return nil, false, fmt.Errorf("parse plugin manifest: %w", err) + } + lastInvalid = true + continue } + lastInvalid = false start, err := enabledValueOffset(raw, keyEnd) if err != nil { return nil, false, err @@ -245,6 +354,9 @@ func toggleEnabledManifest(raw []byte, enabled bool) (out []byte, changed bool, if _, err := dec.Token(); err != io.EOF { return nil, false, errors.New("parse plugin manifest: unexpected data after the top-level object") } + if lastInvalid { + return nil, false, ManifestError{FieldPath: "enabled", Message: "Expected a boolean."} + } if current == enabled { return nil, false, nil @@ -351,6 +463,13 @@ func skipManifestValue(dec *json.Decoder) error { if err != nil { return err } + return skipManifestComposite(dec, tok) +} + +// skipManifestComposite consumes the rest of the value whose first token tok +// was just read from dec. A scalar is already complete; an object or array is +// consumed through its matching closing delimiter. +func skipManifestComposite(dec *json.Decoder, tok json.Token) error { delim, ok := tok.(json.Delim) if !ok || (delim != '{' && delim != '[') { return nil diff --git a/internal/plugins/enabled_test.go b/internal/plugins/enabled_test.go index 3ef289e84a..e7e60c81bb 100644 --- a/internal/plugins/enabled_test.go +++ b/internal/plugins/enabled_test.go @@ -10,6 +10,7 @@ import ( "time" "github.com/Twigpine/zero/internal/installtxn" + "github.com/Twigpine/zero/internal/pathjail" ) func enableTestOptions(root string) LoadOptions { @@ -274,6 +275,11 @@ func TestToggleEnabledManifestFormattingEdges(t *testing.T) { {"null to false", `{"enabled": null}`, false, `{"enabled": false}`, true}, {"null to true is a no-op", `{"enabled": null}`, true, `{"enabled": null}`, false}, {"already enabled is a no-op", `{"enabled": true}`, true, `{"enabled": true}`, false}, + // The loader keeps the last duplicate, so an overwritten non-boolean + // value is not an error and only the last value is rewritten. + {"overwritten string", `{"enabled":"obsolete","enabled":true}`, false, `{"enabled":"obsolete","enabled":false}`, true}, + {"overwritten composite", `{"enabled":{"a":[1,{"enabled":2}]},"enabled":null}`, false, `{"enabled":{"a":[1,{"enabled":2}]},"enabled":false}`, true}, + {"overwritten number is a no-op", `{"enabled":1,"enabled":false}`, false, `{"enabled":1,"enabled":false}`, false}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -298,7 +304,7 @@ func TestToggleEnabledManifestFormattingEdges(t *testing.T) { } func TestToggleEnabledManifestRejectsMalformedInput(t *testing.T) { - for _, raw := range []string{`{"enabled": "yes"}`, `{"enabled": 1}`, `{"enabled": []}`, `{"enabled": {}}`} { + for _, raw := range []string{`{"enabled": "yes"}`, `{"enabled": 1}`, `{"enabled": []}`, `{"enabled": {}}`, `{"enabled": true, "enabled": "yes"}`} { t.Run("value "+raw, func(t *testing.T) { _, _, err := toggleEnabledManifest([]byte(raw), false) if err == nil { @@ -322,6 +328,103 @@ func TestToggleEnabledManifestRejectsMalformedInput(t *testing.T) { } } +// TestSetEnabledByIDHonorsTheLastDuplicateEnabledValue keeps the toggle in step +// with the loader on a manifest whose earlier "enabled" value is overwritten: +// the loader discovers the plugin from the last value, so the toggle must be +// able to change it too. +func TestSetEnabledByIDHonorsTheLastDuplicateEnabledValue(t *testing.T) { + root := t.TempDir() + writeRawManifest(t, root, "demo", `{ + "schemaVersion": 1, + "id": "zero.demo", + "name": "Demo", + "version": "1.0.0", + "enabled": "obsolete", + "enabled": true +} +`) + loadedEnabled := func() bool { + t.Helper() + plugin, ok, err := FindByID(enableTestOptions(root), "zero.demo") + if err != nil || !ok { + t.Fatalf("FindByID: ok=%v err=%v", ok, err) + } + return plugin.Enabled + } + if !loadedEnabled() { + t.Fatal("the loader should discover the plugin as enabled from the last value") + } + for _, enabled := range []bool{false, true} { + result, err := SetEnabledByID(enableTestOptions(root), "zero.demo", enabled) + if err != nil { + t.Fatalf("SetEnabledByID(%v): %v", enabled, err) + } + if !result.Changed { + t.Fatalf("SetEnabledByID(%v) reported no change", enabled) + } + if got := loadedEnabled(); got != enabled { + t.Fatalf("after SetEnabledByID(%v) the loader sees enabled=%v", enabled, got) + } + } +} + +// TestSetEnabledRefusesASwappedPluginDirectory swaps the plugin directory that +// discovery found for a link between the lookup and the edit. The install lock +// does not cover that window, because it only serializes cooperating +// installers. The edit must fail without following the link: neither the +// link's target nor the moved-away original may change. +func TestSetEnabledRefusesASwappedPluginDirectory(t *testing.T) { + cases := []struct { + name string + // link returns the symlink target to plant and the manifest it leads to. + link func(t *testing.T, root string) (target string, manifest string) + }{ + {"to a directory outside the plugins root", func(t *testing.T, root string) (string, string) { + manifest := writeRawManifest(t, t.TempDir(), "elsewhere", demoManifest(true)) + return filepath.Dir(manifest), manifest + }}, + {"to another plugin in the same root", func(t *testing.T, root string) (string, string) { + // A relative link stays inside the root, so confinement to the + // root alone would follow it. + manifest := writeRawManifest(t, root, "other", strings.Replace(demoManifest(true), "zero.demo", "zero.other", 1)) + return "other", manifest + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + root := t.TempDir() + raw := demoManifest(true) + writeRawManifest(t, root, "demo", raw) + plugin, ok, err := FindByID(enableTestOptions(root), "zero.demo") + if err != nil || !ok { + t.Fatalf("FindByID: ok=%v err=%v", ok, err) + } + target, targetManifest := tc.link(t, root) + targetBefore, err := os.ReadFile(targetManifest) + if err != nil { + t.Fatal(err) + } + moved := filepath.Join(t.TempDir(), "moved-away") + if err := os.Rename(plugin.PluginDir, moved); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, plugin.PluginDir); err != nil { + t.Skipf("cannot create a directory symlink here: %v", err) + } + + if _, err := setEnabledLocked(plugin, false); !errors.Is(err, pathjail.ErrReparse) { + t.Fatalf("setEnabledLocked through a swapped directory: err = %v, want %v", err, pathjail.ErrReparse) + } + if after, err := os.ReadFile(targetManifest); err != nil || string(after) != string(targetBefore) { + t.Fatalf("the edit followed the link and changed %s (err %v):\n got %q\nwant %q", targetManifest, err, after, targetBefore) + } + if after, err := os.ReadFile(filepath.Join(moved, "plugin.json")); err != nil || string(after) != raw { + t.Fatalf("the moved-away manifest changed (err %v): %q", err, after) + } + }) + } +} + func TestSetEnabledByIDRespectsUserOnlyFilter(t *testing.T) { dir := t.TempDir() userRoot := filepath.Join(dir, "user") From 20b484f011b18a9f43665d13686902b4ea6c0b73 Mon Sep 17 00:00:00 2001 From: jatmn Date: Sat, 7 Nov 2026 09:11:58 -0800 Subject: [PATCH 6/7] fix(plugins): keep the toggle on the pinned plugin directory throughout The previous fix pinned the manifest read and publish to a handle on the plugin directory but still hashed the tree for plugins.lock by path, and reported success without checking that the path still named the pinned directory. If the directory was replaced after it was opened, the edit landed in the moved-away original while the lockfile check and refresh read the replacement, and the command reported a state the installed plugin did not have. Hash the tree before and after the edit through the pinned handle, and confirm that the plugin's directory entry is still the pinned directory before refreshing the lockfile or reporting any result, including a no-op. hashTree now delegates to the same rooted walker, so path and handle callers hash identical bytes. Co-Authored-By: Claude Opus 5.5 --- internal/plugins/enabled.go | 127 ++++++++++++++++++++++--------- internal/plugins/enabled_test.go | 73 ++++++++++++++++++ internal/plugins/install.go | 36 ++++++--- 3 files changed, 188 insertions(+), 48 deletions(-) diff --git a/internal/plugins/enabled.go b/internal/plugins/enabled.go index b0e94f1320..78d012c8d4 100644 --- a/internal/plugins/enabled.go +++ b/internal/plugins/enabled.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "io" + "io/fs" "os" "path/filepath" "strings" @@ -118,18 +119,28 @@ func SetEnabledByID(options LoadOptions, id string, enabled bool) (SetEnabledRes // holds the installtxn lock for the plugin's install root. // // The lock only serializes cooperating installers; it does not stop the plugin -// directory from being swapped for a link after discovery found it. So the -// manifest is read and published through a handle pinned to that directory -// (openPluginDir), never by re-resolving its path. +// directory from being swapped after discovery found it. So the whole update +// works on one directory, pinned by openPluginDir: the manifest is read and +// published, and the tree hashed for the lockfile, through that handle, never +// by re-resolving the path. func setEnabledLocked(plugin LoadedPlugin, enabled bool) (bool, error) { - dir, err := openPluginDir(plugin) + pinned, err := openPluginDir(plugin) if err != nil { return false, err } - defer dir.Close() + defer pinned.Close() + return setEnabledPinned(plugin, pinned, enabled) +} +// setEnabledPinned is setEnabledLocked on an already pinned plugin directory. +// +// The edit lands in the pinned directory even if the path now names another +// one, so before refreshing the lockfile or reporting any result it confirms +// that the directory entry still is the pinned directory. Otherwise the +// command would report a state that the installed plugin does not have. +func setEnabledPinned(plugin LoadedPlugin, pinned *pinnedPluginDir, enabled bool) (bool, error) { manifestName := filepath.Base(plugin.ManifestPath) - raw, perm, err := readManifest(dir, manifestName) + raw, perm, err := readManifest(pinned.dir, manifestName) if err != nil { return false, err } @@ -138,24 +149,33 @@ func setEnabledLocked(plugin LoadedPlugin, enabled bool) (bool, error) { return false, err } if !changed { + if err := pinned.verifyLive(); err != nil { + return false, err + } return false, nil } // Read the lockfile before the edit so the refresh below only runs when the // installed tree still matched its recorded hash; a toggle must never mask // pre-existing drift. - lock, entry, hashClean := cleanLockEntry(plugin) + lock, entry, hashClean := cleanLockEntry(plugin, pinned.dir) - if err := publishManifest(dir, manifestName, data, perm); err != nil { + if err := publishManifest(pinned.dir, manifestName, data, perm); err != nil { return false, err } if !hashClean { + if err := pinned.verifyLive(); err != nil { + return false, err + } return true, nil } - after, err := hashTree(plugin.PluginDir) + after, err := hashRootedTree(pinned.dir) if err != nil { return true, fmt.Errorf("plugin manifest updated but %s hash refresh failed: %w", LockFileName, err) } + if err := pinned.verifyLive(); err != nil { + return false, err + } entry.Hash = after lock[plugin.ID] = entry if err := writeLock(plugin.Root, lock); err != nil { @@ -164,45 +184,80 @@ func setEnabledLocked(plugin LoadedPlugin, enabled bool) (bool, error) { return true, nil } -// openPluginDir returns a handle on the plugin directory discovery found, -// confined to the plugin's install root. +// errPluginDirReplaced reports that the plugin's directory entry no longer +// names the directory the toggle pinned and edited. +var errPluginDirReplaced = errors.New("plugin directory was replaced while it was being updated; the plugin installed there now was not changed") + +// pinnedPluginDir is the plugin directory discovery found, held open for the +// length of one toggle. +type pinnedPluginDir struct { + root *os.Root // the plugin's install root + name string // the plugin directory's entry name in root + path string // the plugin directory's path, for messages + dir *os.Root // the plugin directory itself +} + +// Close releases both handles. +func (p *pinnedPluginDir) Close() { + _ = p.dir.Close() + _ = p.root.Close() +} + +// verifyLive confirms that the plugin's entry in its install root is still a +// real directory, not a symlink, junction, or other reparse point, and is the +// very directory p.dir holds open. +func (p *pinnedPluginDir) verifyLive() error { + opened, err := p.dir.Stat(".") + if err != nil { + return fmt.Errorf("inspect plugin directory: %w", err) + } + entry, err := p.root.Lstat(p.name) + if errors.Is(err, fs.ErrNotExist) { + return fmt.Errorf("%w: %s", errPluginDirReplaced, p.path) + } + if err != nil { + return fmt.Errorf("inspect plugin directory: %w", err) + } + if entry.Mode()&(os.ModeSymlink|os.ModeIrregular) != 0 { + return fmt.Errorf("%w: plugin directory %s", pathjail.ErrReparse, p.path) + } + if !os.SameFile(entry, opened) { + return fmt.Errorf("%w: %s", errPluginDirReplaced, p.path) + } + return nil +} + +// openPluginDir pins the plugin directory discovery found, confined to the +// plugin's install root. // -// The directory entry must be a real directory, not a symlink, junction, or -// other reparse point, and it must be the very directory the handle opened: a -// link swapped in before the open is refused here, and one swapped in after it -// cannot redirect anything, because every later read and write is relative to -// the returned handle rather than to a path. -func openPluginDir(plugin LoadedPlugin) (*os.Root, error) { +// A link swapped in before the open is refused here. One swapped in after it +// cannot redirect anything, because every later read, write, and hash is +// relative to the returned handle rather than to a path; verifyLive then +// detects that the path no longer names the edited directory. +func openPluginDir(plugin LoadedPlugin) (*pinnedPluginDir, error) { root, name, err := pathjail.Open(plugin.Root, plugin.PluginDir) if err != nil { return nil, fmt.Errorf("open plugin directory: %w", err) } - defer root.Close() if name == "." || filepath.Base(name) != name { + _ = root.Close() return nil, fmt.Errorf("%w: plugin directory %s is not an entry of %s", pathjail.ErrEscapes, plugin.PluginDir, plugin.Root) } if err := pathjail.RefuseReparse(root, name); err != nil { + _ = root.Close() return nil, fmt.Errorf("open plugin directory: %w", err) } dir, err := root.OpenRoot(name) if err != nil { + _ = root.Close() return nil, fmt.Errorf("open plugin directory: %w", err) } - opened, err := dir.Stat(".") - if err != nil { - _ = dir.Close() - return nil, fmt.Errorf("inspect plugin directory: %w", err) - } - entry, err := root.Lstat(name) - if err != nil { - _ = dir.Close() - return nil, fmt.Errorf("inspect plugin directory: %w", err) - } - if entry.Mode()&(os.ModeSymlink|os.ModeIrregular) != 0 || !os.SameFile(entry, opened) { - _ = dir.Close() - return nil, fmt.Errorf("%w: plugin directory %s changed while it was being opened", pathjail.ErrReparse, plugin.PluginDir) + pinned := &pinnedPluginDir{root: root, name: name, path: plugin.PluginDir, dir: dir} + if err := pinned.verifyLive(); err != nil { + pinned.Close() + return nil, err } - return dir, nil + return pinned, nil } // readManifest reads name from dir and returns its bytes and permission bits. @@ -254,9 +309,9 @@ func publishManifest(dir *os.Root, name string, data []byte, perm os.FileMode) e return nil } -// cleanLockEntry reports whether the tree on disk still matches the lockfile -// entry recorded for the plugin and returns both for a refresh. -func cleanLockEntry(plugin LoadedPlugin) (map[string]LockEntry, LockEntry, bool) { +// cleanLockEntry reports whether the pinned plugin directory dir still matches +// the lockfile entry recorded for the plugin and returns both for a refresh. +func cleanLockEntry(plugin LoadedPlugin, dir *os.Root) (map[string]LockEntry, LockEntry, bool) { lock, err := ReadLock(plugin.Root) if err != nil { return nil, LockEntry{}, false @@ -265,7 +320,7 @@ func cleanLockEntry(plugin LoadedPlugin) (map[string]LockEntry, LockEntry, bool) if !ok { return nil, LockEntry{}, false } - current, err := hashTree(plugin.PluginDir) + current, err := hashRootedTree(dir) if err != nil || current != entry.Hash { return nil, LockEntry{}, false } diff --git a/internal/plugins/enabled_test.go b/internal/plugins/enabled_test.go index e7e60c81bb..c1eb23c71c 100644 --- a/internal/plugins/enabled_test.go +++ b/internal/plugins/enabled_test.go @@ -425,6 +425,79 @@ func TestSetEnabledRefusesASwappedPluginDirectory(t *testing.T) { } } +// TestSetEnabledDetectsAPluginDirectoryReplacedAfterOpening replaces the live +// plugin directory after the toggle pinned it. The edit then lands in the +// moved-away directory, so the toggle must not refresh the lockfile from either +// tree and must not report success: the plugin installed at the path now is +// unchanged. +func TestSetEnabledDetectsAPluginDirectoryReplacedAfterOpening(t *testing.T) { + for _, tc := range []struct { + name string + pinned bool // the pinned manifest's enabled value + changes bool // whether disabling it is a real edit + }{ + {"edit", true, true}, + {"no-op", false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + root := t.TempDir() + manifestPath := writeRawManifest(t, root, "demo", demoManifest(tc.pinned)) + pluginDir := filepath.Dir(manifestPath) + hash, err := hashTree(pluginDir) + if err != nil { + t.Fatal(err) + } + if err := writeLock(root, map[string]LockEntry{"zero.demo": {Source: "./demo", Hash: hash}}); err != nil { + t.Fatal(err) + } + lockPath := filepath.Join(root, LockFileName) + lockBefore, err := os.ReadFile(lockPath) + if err != nil { + t.Fatal(err) + } + plugin, ok, err := FindByID(enableTestOptions(root), "zero.demo") + if err != nil || !ok { + t.Fatalf("FindByID: ok=%v err=%v", ok, err) + } + pinned, err := openPluginDir(plugin) + if err != nil { + t.Fatalf("openPluginDir: %v", err) + } + defer pinned.Close() + + moved := filepath.Join(t.TempDir(), "moved-away") + if err := os.Rename(pluginDir, moved); err != nil { + t.Fatal(err) + } + replacement := strings.Replace(demoManifest(true), `"version": "1.0.0"`, `"version": "2.0.0"`, 1) + writeRawManifest(t, root, "demo", replacement) + + // The lockfile check hashes the pinned tree, which still matches the + // recorded hash, not the replacement now at the path. + if _, _, clean := cleanLockEntry(plugin, pinned.dir); !clean { + t.Error("cleanLockEntry hashed the replacement at the path instead of the pinned directory") + } + + if _, err := setEnabledPinned(plugin, pinned, false); !errors.Is(err, errPluginDirReplaced) { + t.Fatalf("setEnabledPinned after the directory was replaced: err = %v, want %v", err, errPluginDirReplaced) + } + if after, err := os.ReadFile(manifestPath); err != nil || string(after) != replacement { + t.Fatalf("the replacement manifest changed (err %v): %q", err, after) + } + if after, err := os.ReadFile(lockPath); err != nil || string(after) != string(lockBefore) { + t.Fatalf("the lockfile changed (err %v):\n got %s\nwant %s", err, after, lockBefore) + } + movedRaw, err := os.ReadFile(filepath.Join(moved, "plugin.json")) + if err != nil { + t.Fatal(err) + } + if tc.changes != (string(movedRaw) != demoManifest(tc.pinned)) { + t.Fatalf("pinned manifest edit = %v, want %v: %q", !tc.changes, tc.changes, movedRaw) + } + }) + } +} + func TestSetEnabledByIDRespectsUserOnlyFilter(t *testing.T) { dir := t.TempDir() userRoot := filepath.Join(dir, "user") diff --git a/internal/plugins/install.go b/internal/plugins/install.go index 05dae49a90..e7a3412b65 100644 --- a/internal/plugins/install.go +++ b/internal/plugins/install.go @@ -14,8 +14,10 @@ import ( "errors" "fmt" "io" + "io/fs" "os" "os/exec" + "path" "path/filepath" "sort" "strings" @@ -567,15 +569,29 @@ func validInstallID(id string) bool { // sorted order. Each file contributes its plugin-relative path, executable bit, // and bytes, so renames, mode flips, and content edits all change the hash. func hashTree(root string) (string, error) { + handle, err := os.OpenRoot(root) + if err != nil { + return "", err + } + defer handle.Close() + return hashRootedTree(handle) +} + +// hashRootedTree is hashTree over a directory that is already open. Walking +// relative to the handle hashes the directory it names even if its path is +// replaced meanwhile, and keeps the walk inside it. +func hashRootedTree(handle *os.Root) (string, error) { hasher := sha256.New() - if err := hashTreeInto(hasher, root, root); err != nil { + if err := hashTreeInto(hasher, handle.FS(), "."); err != nil { return "", err } return "sha256:" + hex.EncodeToString(hasher.Sum(nil)), nil } -func hashTreeInto(hasher io.Writer, root string, dir string) error { - entries, err := os.ReadDir(dir) +// hashTreeInto hashes dir, a slash-separated path relative to fsys, into +// hasher. +func hashTreeInto(hasher io.Writer, fsys fs.FS, dir string) error { + entries, err := fs.ReadDir(fsys, dir) if err != nil { return err } @@ -588,8 +604,8 @@ func hashTreeInto(hasher io.Writer, root string, dir string) error { if name == ".git" { continue } - path := filepath.Join(dir, name) - info, err := os.Lstat(path) + rel := path.Join(dir, name) + info, err := fs.Lstat(fsys, rel) if err != nil { return err } @@ -598,25 +614,21 @@ func hashTreeInto(hasher io.Writer, root string, dir string) error { // Skipped by copyTree, so excluded from the hash too. continue case info.IsDir(): - if err := hashTreeInto(hasher, root, path); err != nil { + if err := hashTreeInto(hasher, fsys, rel); err != nil { return err } case info.Mode().IsRegular(): - rel, err := filepath.Rel(root, path) - if err != nil { - return err - } executable := 0 if info.Mode().Perm()&0o111 != 0 { executable = 1 } // Null-delimited header keeps file boundaries unambiguous (paths cannot // contain null bytes) so two trees cannot collide by shifting bytes. - header := fmt.Sprintf("%s\x00%d\x00", filepath.ToSlash(rel), executable) + header := fmt.Sprintf("%s\x00%d\x00", rel, executable) if _, err := io.WriteString(hasher, header); err != nil { return err } - file, err := os.Open(path) + file, err := fsys.Open(rel) if err != nil { return err } From 2a05a8dd5b3e6f84b8825496ec9681eaa054e70b Mon Sep 17 00:00:00 2001 From: jatmn Date: Sat, 7 Nov 2026 09:41:26 -0800 Subject: [PATCH 7/7] fix(plugins): hash plugin trees through native os.Root calls 20b484f moved hashTree onto an os.Root handle but walked it through handle.FS(). That adapter accepts only fs.ValidPath names, which must be UTF-8, so a plugin holding a Linux-valid name such as byte 0xff failed with "lstat ...: invalid argument". copyTree and the previous walker accept those names, so Install, the toggle's lock refresh, and Info's drift check all regressed for such plugins. Walk the handle with its own Open/Lstat methods instead. The walk stays pinned to the directory, and the hash bytes match the merge-base implementation (checked on a fixture with nested and non-UTF-8 names, an exec bit, a symlink, .git and a FIFO). Co-Authored-By: Claude Opus 5.5 --- internal/plugins/install.go | 38 +++++++++++++------- internal/plugins/install_test.go | 59 ++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 12 deletions(-) diff --git a/internal/plugins/install.go b/internal/plugins/install.go index e7a3412b65..7fbb840847 100644 --- a/internal/plugins/install.go +++ b/internal/plugins/install.go @@ -14,10 +14,8 @@ import ( "errors" "fmt" "io" - "io/fs" "os" "os/exec" - "path" "path/filepath" "sort" "strings" @@ -580,18 +578,21 @@ func hashTree(root string) (string, error) { // hashRootedTree is hashTree over a directory that is already open. Walking // relative to the handle hashes the directory it names even if its path is // replaced meanwhile, and keeps the walk inside it. +// +// The walk calls the handle's own methods rather than handle.FS(): the fs.FS +// adapter only accepts fs.ValidPath names, which must be UTF-8, so it would +// refuse file names that the filesystem and copyTree accept. func hashRootedTree(handle *os.Root) (string, error) { hasher := sha256.New() - if err := hashTreeInto(hasher, handle.FS(), "."); err != nil { + if err := hashTreeInto(hasher, handle, "."); err != nil { return "", err } return "sha256:" + hex.EncodeToString(hasher.Sum(nil)), nil } -// hashTreeInto hashes dir, a slash-separated path relative to fsys, into -// hasher. -func hashTreeInto(hasher io.Writer, fsys fs.FS, dir string) error { - entries, err := fs.ReadDir(fsys, dir) +// hashTreeInto hashes dir, a path relative to handle, into hasher. +func hashTreeInto(hasher io.Writer, handle *os.Root, dir string) error { + entries, err := readRootedDir(handle, dir) if err != nil { return err } @@ -604,8 +605,8 @@ func hashTreeInto(hasher io.Writer, fsys fs.FS, dir string) error { if name == ".git" { continue } - rel := path.Join(dir, name) - info, err := fs.Lstat(fsys, rel) + rel := filepath.Join(dir, name) + info, err := handle.Lstat(rel) if err != nil { return err } @@ -614,7 +615,7 @@ func hashTreeInto(hasher io.Writer, fsys fs.FS, dir string) error { // Skipped by copyTree, so excluded from the hash too. continue case info.IsDir(): - if err := hashTreeInto(hasher, fsys, rel); err != nil { + if err := hashTreeInto(hasher, handle, rel); err != nil { return err } case info.Mode().IsRegular(): @@ -624,11 +625,11 @@ func hashTreeInto(hasher io.Writer, fsys fs.FS, dir string) error { } // Null-delimited header keeps file boundaries unambiguous (paths cannot // contain null bytes) so two trees cannot collide by shifting bytes. - header := fmt.Sprintf("%s\x00%d\x00", rel, executable) + header := fmt.Sprintf("%s\x00%d\x00", filepath.ToSlash(rel), executable) if _, err := io.WriteString(hasher, header); err != nil { return err } - file, err := fsys.Open(rel) + file, err := handle.Open(rel) if err != nil { return err } @@ -646,3 +647,16 @@ func hashTreeInto(hasher io.Writer, fsys fs.FS, dir string) error { } return nil } + +// readRootedDir lists dir, a path relative to handle, like os.ReadDir. +func readRootedDir(handle *os.Root, dir string) ([]os.DirEntry, error) { + file, err := handle.Open(dir) + if err != nil { + return nil, err + } + entries, err := file.ReadDir(-1) + if closeErr := file.Close(); err == nil { + err = closeErr + } + return entries, err +} diff --git a/internal/plugins/install_test.go b/internal/plugins/install_test.go index 040d443c7e..cc31dd55e1 100644 --- a/internal/plugins/install_test.go +++ b/internal/plugins/install_test.go @@ -1181,3 +1181,62 @@ func TestRecoveryLeavesAPrefixCollidingDirectoryAlone(t *testing.T) { t.Errorf("recovery published content it does not own: %v", err) } } + +// TestNonUTF8FileNamesAreInstalledHashedAndToggled covers a plugin whose tree +// holds a file and a directory named with bytes that are not valid UTF-8, which +// Linux allows. copyTree copies them, so hashTree must hash them too: Install +// records the hash, the toggle refreshes it, and Info sees an edit to that file +// as drift. A walk that rejects such names breaks all three. +func TestNonUTF8FileNamesAreInstalledHashedAndToggled(t *testing.T) { + src := writeSourcePlugin(t, filepath.Join(t.TempDir(), "src"), validManifest()) + nested := filepath.Join("assets\xff", "data\xfe.bin") + if err := os.Mkdir(filepath.Join(src, "assets\xff"), 0o755); err != nil { + t.Skipf("this filesystem rejects non-UTF-8 names: %v", err) + } + if err := os.WriteFile(filepath.Join(src, nested), []byte("original\n"), 0o644); err != nil { + t.Skipf("this filesystem rejects non-UTF-8 names: %v", err) + } + + destDir := t.TempDir() + if _, err := Install(context.Background(), InstallOptions{Source: src, Dir: destDir}); err != nil { + t.Fatalf("Install a plugin with a non-UTF-8 file name: %v", err) + } + pluginDir := filepath.Join(destDir, "zero.demo") + if data, err := os.ReadFile(filepath.Join(pluginDir, nested)); err != nil || string(data) != "original\n" { + t.Fatalf("installed copy of the non-UTF-8 file = %q, %v", data, err) + } + + options := LoadOptions{Roots: []Root{{Source: SourceUser, Path: destDir}}} + before, err := ReadLock(destDir) + if err != nil { + t.Fatal(err) + } + if _, err := SetEnabledByID(options, "zero.demo", false); err != nil { + t.Fatalf("SetEnabledByID on a plugin with a non-UTF-8 file name: %v", err) + } + after, err := ReadLock(destDir) + if err != nil { + t.Fatal(err) + } + if after["zero.demo"].Hash == before["zero.demo"].Hash { + t.Fatal("the toggle did not refresh the lock hash") + } + info, err := Info(InfoOptions{LoadOptions: options}, "zero.demo") + if err != nil { + t.Fatal(err) + } + if info.HashDrift { + t.Fatal("the toggle left hash drift behind") + } + + if err := os.WriteFile(filepath.Join(pluginDir, nested), []byte("edited\n"), 0o644); err != nil { + t.Fatal(err) + } + info, err = Info(InfoOptions{LoadOptions: options}, "zero.demo") + if err != nil { + t.Fatal(err) + } + if !info.HashDrift { + t.Fatal("an edit to the non-UTF-8 file was not reported as drift") + } +}