From 9144fc168a5cb82bbc81adc244103bd1e6ae99cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20Gro=C3=9Fmann?= Date: Thu, 19 Nov 2026 10:05:58 +0100 Subject: [PATCH 1/2] feat(pass): add install command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit InstallCommand builds a secrets engine plugin from Go source and copies the binary into the engine's plugin directory, which the embedding binary supplies: docker pass install github.com/docker/secrets-engine/plugins/stdinreader docker pass install ./plugins/stdinreader It runs `go install` with GOBIN set to a staging directory, so the toolchain resolves, verifies and builds the package. A package path defaults to @latest; a path that starts with "." or "/" is built in that directory. The binary is installed only if its build info lists the plugin SDK module. Nothing is executed. The engine launches every executable file in the plugin directory and takes the file name as the plugin name, hence --name. The copy is staged in a subdirectory of the plugin directory and renamed into place: the engine's scan skips directories, so it never sees a partial file. GOOS and GOARCH are dropped from the build environment because `go install` refuses to cross-compile when GOBIN is set. On Linux the plugin directory is root-owned. The build always runs as the caller; if the copy fails with a permission error, the command prints and runs `sudo install -m 0755`. plugins/stdinreader is the plugin the examples and tests use. It reads dotenv secrets from stdin and serves them through the standalone engine. Its version comes from the build info unless -ldflags sets one, so a copy installed at v0.1.0 reports v0.1.0. The tests run the real go command against that plugin and against throwaway modules, with GOPROXY=off, so they need no network. Signed-off-by: Johannes Großmann --- go.work | 1 + plugins/pass/README.md | 26 ++ plugins/pass/commands/install.go | 255 ++++++++++++++++++ plugins/pass/commands/install_example.md | 23 ++ plugins/pass/commands/install_long.md | 17 ++ plugins/pass/commands/install_test.go | 245 +++++++++++++++++ plugins/stdinreader/README.md | 34 +++ plugins/stdinreader/go.mod | 28 ++ plugins/stdinreader/go.sum | 27 ++ .../internal/plugin/stdinreader.go | 228 ++++++++++++++++ .../internal/plugin/stdinreader_test.go | 109 ++++++++ plugins/stdinreader/main.go | 38 +++ 12 files changed, 1031 insertions(+) create mode 100644 plugins/pass/commands/install.go create mode 100644 plugins/pass/commands/install_example.md create mode 100644 plugins/pass/commands/install_long.md create mode 100644 plugins/pass/commands/install_test.go create mode 100644 plugins/stdinreader/README.md create mode 100644 plugins/stdinreader/go.mod create mode 100644 plugins/stdinreader/go.sum create mode 100644 plugins/stdinreader/internal/plugin/stdinreader.go create mode 100644 plugins/stdinreader/internal/plugin/stdinreader_test.go create mode 100644 plugins/stdinreader/main.go diff --git a/go.work b/go.work index 6087dc5f..10e52614 100644 --- a/go.work +++ b/go.work @@ -5,6 +5,7 @@ use ( ./plugin ./plugins/credentialhelper ./plugins/pass + ./plugins/stdinreader ./secrets ./store ./x diff --git a/plugins/pass/README.md b/plugins/pass/README.md index 951c3fde..84348019 100644 --- a/plugins/pass/README.md +++ b/plugins/pass/README.md @@ -78,6 +78,28 @@ $ docker pass run -e DB_PASSWORD=se://POSTGRES_PASSWORD -- ./deploy.sh `--env-file` files, and in `--env` flags, then starts the command with the resolved values. It needs the Secrets Engine daemon to be running. +### Install a plugin + +`docker pass install` builds a Secrets Engine plugin from Go source and copies +the binary into the engine's plugin directory: + +```console +$ docker pass install github.com/docker/secrets-engine/plugins/stdinreader +$ docker pass install github.com/docker/secrets-engine/plugins/stdinreader@v0.1.0 +$ docker pass install ./plugins/stdinreader +``` + +All three install the [stdinreader plugin](../stdinreader); the last builds it +from a checkout of this repository. + +It needs the Go toolchain and accepts only binaries that use the +[`plugin`](../../plugin) SDK. The file name becomes the plugin name; change it +with `--name`. If the plugin directory is not writable, the final copy runs +through `sudo`. The engine loads plugins at startup, so restart it afterwards. + +The command exists only in builds whose engine launches plugins from a +directory. + ### Troubleshooting - **Locked keychain (Linux):** log in to the desktop session, or run @@ -149,3 +171,7 @@ back to another store there if your application supports one. connect to Docker Desktop's socket by default; pass `commands.WithSocketPath` to use another one, and `commands.WithTimeout` or `commands.WithResponseTimeout` to change the timeouts. + +`commands.InstallCommand(pluginDir)` needs neither the store nor the engine. +Pass it the directory your engine launches plugins from, and add it only where +that directory exists. diff --git a/plugins/pass/commands/install.go b/plugins/pass/commands/install.go new file mode 100644 index 00000000..d6b74c04 --- /dev/null +++ b/plugins/pass/commands/install.go @@ -0,0 +1,255 @@ +// Copyright 2026 Docker, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package commands + +import ( + "debug/buildinfo" + _ "embed" + "errors" + "fmt" + "io" + "io/fs" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "strings" + + "github.com/spf13/cobra" +) + +const pluginSDKModule = "github.com/docker/secrets-engine/plugin" + +//go:embed install_example.md +var installExample string + +//go:embed install_long.md +var installLong string + +type installOpts struct { + pluginDir string + name string + elevate func(cmd *cobra.Command, src, dst string) error +} + +// InstallCommand builds a plugin from Go source and installs it into +// pluginDir, the directory the secrets engine launches plugins from. The +// engine scans that directory only at startup and takes each file name as the +// plugin name. +func InstallCommand(pluginDir string) (*cobra.Command, error) { + if !filepath.IsAbs(pluginDir) { + return nil, fmt.Errorf("plugin directory must be an absolute path, got %q", pluginDir) + } + return newInstallCommand(installOpts{ + pluginDir: pluginDir, + elevate: sudoInstall, + }), nil +} + +func newInstallCommand(opts installOpts) *cobra.Command { + cmd := &cobra.Command{ + Use: "install PACKAGE", + Short: "Build a plugin from Go source and install it into the plugin directory.", + Long: strings.Trim(installLong, "\n"), + Example: strings.Trim(installExample, "\n"), + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + return runInstall(cmd, opts, args[0]) + }, + } + cmd.Flags().StringVar(&opts.name, "name", "", "Install the plugin as `NAME` instead of the binary's default name.") + return cmd +} + +func runInstall(cmd *cobra.Command, opts installOpts, arg string) error { + if err := checkPluginName(opts.name); err != nil { + return err + } + target, err := parseBuildTarget(arg) + if err != nil { + return err + } + stage, err := os.MkdirTemp("", "docker-pass-install-*") + if err != nil { + return err + } + defer func() { _ = os.RemoveAll(stage) }() + + if err := goInstall(cmd, target, stage); err != nil { + return fmt.Errorf("building %s: %w", arg, err) + } + built, err := os.ReadDir(stage) + if err != nil { + return err + } + if len(built) == 0 { + return fmt.Errorf("%s is not a main package: go install produced no binary", arg) + } + src := filepath.Join(stage, built[0].Name()) + info, err := buildinfo.ReadFile(src) + if err != nil { + return fmt.Errorf("reading build info of %s: %w", arg, err) + } + if !usesPluginSDK(info) { + return fmt.Errorf("%s is not a secrets engine plugin: it does not use %s", arg, pluginSDKModule) + } + + name := pluginFileName(opts.name, built[0].Name()) + dst := filepath.Join(opts.pluginDir, name) + if err := place(cmd, opts, src, dst); err != nil { + return err + } + _, err = fmt.Fprintf(cmd.OutOrStdout(), "Installed %s (%s %s, %s) to %s\nRestart the secrets engine to load it.\n", + name, info.Main.Path, info.Main.Version, info.GoVersion, dst) + return err +} + +type buildTarget struct { + dir string + pkg string +} + +func parseBuildTarget(arg string) (buildTarget, error) { + if strings.Contains(arg, "...") { + return buildTarget{}, fmt.Errorf("%s: patterns are not supported, name one main package", arg) + } + if !filepath.IsAbs(arg) && !strings.HasPrefix(arg, ".") { + if !strings.Contains(arg, "@") { + arg += "@latest" + } + return buildTarget{pkg: arg}, nil + } + dir, err := filepath.Abs(arg) + if err != nil { + return buildTarget{}, err + } + fi, err := os.Stat(dir) + if err != nil { + return buildTarget{}, err + } + if !fi.IsDir() { + return buildTarget{}, fmt.Errorf("%s: not a directory", arg) + } + return buildTarget{dir: dir, pkg: "."}, nil +} + +func goInstall(cmd *cobra.Command, target buildTarget, gobin string) error { + env := slices.DeleteFunc(os.Environ(), func(kv string) bool { + key, _, _ := strings.Cut(kv, "=") + return strings.EqualFold(key, "GOOS") || strings.EqualFold(key, "GOARCH") + }) + goCmd := exec.CommandContext(cmd.Context(), "go", "install", target.pkg) + goCmd.Dir = target.dir + goCmd.Env = append(env, "GOBIN="+gobin) + goCmd.Stdout = cmd.ErrOrStderr() + goCmd.Stderr = cmd.ErrOrStderr() + err := goCmd.Run() + if errors.Is(err, exec.ErrNotFound) { + return fmt.Errorf("the Go toolchain is required to build plugins: %w", err) + } + return err +} + +func usesPluginSDK(info *buildinfo.BuildInfo) bool { + for _, dep := range info.Deps { + if dep.Path == pluginSDKModule { + return true + } + } + return info.Main.Path == pluginSDKModule +} + +func checkPluginName(name string) error { + if name == "" || (name == filepath.Base(name) && name != "." && name != "..") { + return nil + } + return fmt.Errorf("invalid --name %q: want a file name without a directory", name) +} + +func pluginFileName(name, built string) string { + if name == "" { + return built + } + if runtime.GOOS == "windows" && !strings.EqualFold(filepath.Ext(name), ".exe") { + name += ".exe" + } + return name +} + +func place(cmd *cobra.Command, opts installOpts, src, dst string) error { + err := copyExecutable(src, dst) + if errors.Is(err, fs.ErrPermission) { + return opts.elevate(cmd, src, dst) + } + return err +} + +func copyExecutable(src, dst string) error { + tmpDir, err := os.MkdirTemp(filepath.Dir(dst), ".install-*") + if err != nil { + return err + } + defer func() { _ = os.RemoveAll(tmpDir) }() + + tmp := filepath.Join(tmpDir, filepath.Base(dst)) + // Copy rather than rename: os.Rename fails across filesystems (e.g. tmpfs + // to ext4). src is the go install output in the system temp directory, + // which is often tmpfs. + if err := copyFile(src, tmp); err != nil { + return err + } + if err := os.Chmod(tmp, 0o755); err != nil { + return err + } + return os.Rename(tmp, dst) +} + +func copyFile(src, dst string) error { + in, err := os.Open(src) + if err != nil { + return err + } + defer func() { _ = in.Close() }() + + out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o755) + if err != nil { + return err + } + if _, err := io.Copy(out, in); err != nil { + _ = out.Close() + return err + } + return out.Close() +} + +// sudoInstall copies src to dst as root; this process stays unprivileged. +// sudo, being setuid-root, prompts for the password on the terminal itself, +// so the password never passes through here. Without a terminal it fails. +func sudoInstall(cmd *cobra.Command, src, dst string) error { + if runtime.GOOS == "windows" { + return fmt.Errorf("installing to %s: %w", filepath.Dir(dst), fs.ErrPermission) + } + args := []string{"install", "-m", "0755", src, dst} + _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Installing to %s requires root; running: sudo %s\n", filepath.Dir(dst), strings.Join(args, " ")) + sudo := exec.CommandContext(cmd.Context(), "sudo", args...) + sudo.Stdin = cmd.InOrStdin() + sudo.Stdout = cmd.OutOrStdout() + sudo.Stderr = cmd.ErrOrStderr() + if err := sudo.Run(); err != nil { + return fmt.Errorf("sudo install: %w", err) + } + return nil +} diff --git a/plugins/pass/commands/install_example.md b/plugins/pass/commands/install_example.md new file mode 100644 index 00000000..7f344803 --- /dev/null +++ b/plugins/pass/commands/install_example.md @@ -0,0 +1,23 @@ +### Install the latest version of the stdinreader plugin: + +```console +$ docker pass install github.com/docker/secrets-engine/plugins/stdinreader +``` + +### Install a specific version: + +```console +$ docker pass install github.com/docker/secrets-engine/plugins/stdinreader@v0.1.0 +``` + +### Build and install it from a checkout of docker/secrets-engine: + +```console +$ docker pass install ./plugins/stdinreader +``` + +### Install it under a different plugin name: + +```console +$ docker pass install --name stdin ./plugins/stdinreader +``` diff --git a/plugins/pass/commands/install_long.md b/plugins/pass/commands/install_long.md new file mode 100644 index 00000000..c1ec1fa7 --- /dev/null +++ b/plugins/pass/commands/install_long.md @@ -0,0 +1,17 @@ +Builds a secrets engine plugin from Go source with `go install` and copies the +binary into the engine's plugin directory. + +PACKAGE is a Go package path, optionally with a version +(`github.com/docker/secrets-engine/plugins/stdinreader@v0.1.0`; the default is +`@latest`). A PACKAGE that starts with `.` or `/` is a local directory that +holds a main package. + +The build runs in a temporary directory. The binary is installed only if it is +a Go program that uses the plugin SDK +(`github.com/docker/secrets-engine/plugin`). The file name becomes the plugin +name; set it with `--name`. + +Requires the Go toolchain. If the plugin directory is not writable, the final +copy runs through `sudo`. + +The engine loads plugins at startup, so restart it afterwards. diff --git a/plugins/pass/commands/install_test.go b/plugins/pass/commands/install_test.go new file mode 100644 index 00000000..e96c2eda --- /dev/null +++ b/plugins/pass/commands/install_test.go @@ -0,0 +1,245 @@ +// Copyright 2026 Docker, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package commands + +import ( + "io/fs" + "os" + "os/exec" + "path/filepath" + "runtime" + "runtime/debug" + "testing" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + stdinReaderModule = "github.com/docker/secrets-engine/plugins/stdinreader" + toolMain = "package main\n\nfunc main() {}\n" +) + +func TestInstallCommandOptions(t *testing.T) { + t.Parallel() + for _, dir := range []string{"", "plugins", "./plugins"} { + _, err := InstallCommand(dir) + assert.ErrorContains(t, err, "absolute path", dir) + } + cmd, err := InstallCommand(t.TempDir()) + require.NoError(t, err) + assert.Equal(t, "install", cmd.Name()) +} + +func TestParseBuildTarget(t *testing.T) { + t.Parallel() + wd, err := os.Getwd() + require.NoError(t, err) + dir := t.TempDir() + file := filepath.Join(dir, "main.go") + require.NoError(t, os.WriteFile(file, nil, 0o600)) + + tests := []struct { + name string + arg string + want buildTarget + }{ + {"absolute directory", dir, buildTarget{dir: dir, pkg: "."}}, + {"current directory", ".", buildTarget{dir: wd, pkg: "."}}, + {"relative directory", "./internal", buildTarget{dir: filepath.Join(wd, "internal"), pkg: "."}}, + {"package path", "example.com/acme/plugin", buildTarget{pkg: "example.com/acme/plugin@latest"}}, + {"package path with version", "example.com/acme/plugin@v1.2.0", buildTarget{pkg: "example.com/acme/plugin@v1.2.0"}}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + got, err := parseBuildTarget(tc.arg) + require.NoError(t, err) + assert.Equal(t, tc.want, got) + }) + } + t.Run("missing directory", func(t *testing.T) { + _, err := parseBuildTarget(filepath.Join(dir, "missing")) + assert.ErrorIs(t, err, fs.ErrNotExist) + }) + t.Run("file", func(t *testing.T) { + _, err := parseBuildTarget(file) + assert.ErrorContains(t, err, "not a directory") + }) + t.Run("pattern", func(t *testing.T) { + for _, arg := range []string{"./...", "example.com/acme/...", "example.com/acme/...@latest"} { + _, err := parseBuildTarget(arg) + assert.ErrorContains(t, err, "patterns are not supported", arg) + } + }) +} + +func TestUsesPluginSDK(t *testing.T) { + t.Parallel() + tests := []struct { + name string + info debug.BuildInfo + want bool + }{ + {"main module", debug.BuildInfo{Main: debug.Module{Path: pluginSDKModule}}, true}, + {"dependency", debug.BuildInfo{Deps: []*debug.Module{{Path: "example.com/other"}, {Path: pluginSDKModule, Version: "v0.3.4"}}}, true}, + {"replaced dependency", debug.BuildInfo{Deps: []*debug.Module{{Path: pluginSDKModule, Replace: &debug.Module{Path: "../plugin"}}}}, true}, + {"unrelated", debug.BuildInfo{Main: debug.Module{Path: "example.com/tool"}, Deps: []*debug.Module{{Path: "example.com/other"}}}, false}, + {"longer module path", debug.BuildInfo{Deps: []*debug.Module{{Path: pluginSDKModule + "s/pass"}}}, false}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, usesPluginSDK(&tc.info)) + }) + } +} + +func TestCheckPluginName(t *testing.T) { + t.Parallel() + for _, name := range []string{"", "acme", "acme-plugin.v2"} { + assert.NoError(t, checkPluginName(name), name) + } + for _, name := range []string{".", "..", "dir/acme", "/acme", "acme/"} { + assert.ErrorContains(t, checkPluginName(name), "invalid --name", name) + } +} + +func TestInstallCommand(t *testing.T) { + if _, err := exec.LookPath("go"); err != nil { + t.Skip("go toolchain not on PATH") + } + plugin := filepath.Join("..", "..", "stdinreader") + if _, err := os.Stat(plugin); err != nil { + t.Skip("stdinreader plugin not found next to this module") + } + t.Setenv("GOFLAGS", "-buildvcs=false") + t.Setenv("GOTOOLCHAIN", "local") + t.Setenv("GOPROXY", "off") + + install := func(t *testing.T, args ...string) (pluginDir, out string, err error) { + t.Helper() + pluginDir = t.TempDir() + out, err = execute(t, newInstallCommand(installOpts{pluginDir: pluginDir}), nil, args...) + return pluginDir, out, err + } + + t.Run("installs the stdinreader plugin", func(t *testing.T) { + pluginDir, out, err := install(t, plugin) + require.NoError(t, err, out) + installed := filepath.Join(pluginDir, exeName("stdinreader")) + assert.Equal(t, []string{exeName("stdinreader")}, dirNames(t, pluginDir)) + if runtime.GOOS != "windows" { + fi, err := os.Stat(installed) + require.NoError(t, err) + assert.Equal(t, fs.FileMode(0o755), fi.Mode().Perm()) + } + assert.Contains(t, out, "Installed "+exeName("stdinreader")+" ("+stdinReaderModule+" ") + assert.Contains(t, out, " to "+installed+"\nRestart the secrets engine to load it.\n") + }) + t.Run("--name renames the plugin", func(t *testing.T) { + pluginDir, out, err := install(t, plugin, "--name", "acme") + require.NoError(t, err, out) + assert.Equal(t, []string{exeName("acme")}, dirNames(t, pluginDir)) + }) + t.Run("rejects an invalid --name before building", func(t *testing.T) { + pluginDir, out, err := install(t, filepath.Join(plugin, "missing"), "--name", "dir/acme") + assert.ErrorContains(t, err, "invalid --name", out) + assert.Empty(t, dirNames(t, pluginDir)) + }) + t.Run("replaces an existing plugin", func(t *testing.T) { + pluginDir := t.TempDir() + installed := filepath.Join(pluginDir, exeName("stdinreader")) + require.NoError(t, os.WriteFile(installed, []byte("old"), 0o600)) + out, err := execute(t, newInstallCommand(installOpts{pluginDir: pluginDir}), nil, plugin) + require.NoError(t, err, out) + fi, err := os.Stat(installed) + require.NoError(t, err) + assert.Greater(t, fi.Size(), int64(len("old"))) + assert.Equal(t, []string{exeName("stdinreader")}, dirNames(t, pluginDir)) + }) + t.Run("builds for the host despite GOOS and GOARCH", func(t *testing.T) { + t.Setenv("GOOS", "plan9") + t.Setenv("GOARCH", "386") + pluginDir, out, err := install(t, plugin) + require.NoError(t, err, out) + assert.Equal(t, []string{exeName("stdinreader")}, dirNames(t, pluginDir)) + }) + t.Run("compile error", func(t *testing.T) { + broken := writeModule(t, "package main\n\nfunc main() { missing() }\n") + pluginDir, out, err := install(t, broken) + assert.ErrorContains(t, err, "building "+broken, out) + assert.Contains(t, out, "undefined: missing") + assert.Empty(t, dirNames(t, pluginDir)) + }) + t.Run("library package", func(t *testing.T) { + lib := writeModule(t, "package tool\n") + pluginDir, out, err := install(t, lib) + assert.ErrorContains(t, err, "is not a main package", out) + assert.Empty(t, dirNames(t, pluginDir)) + }) + t.Run("binary without the plugin SDK", func(t *testing.T) { + tool := writeModule(t, toolMain) + pluginDir, out, err := install(t, tool) + assert.ErrorContains(t, err, "is not a secrets engine plugin", out) + assert.Empty(t, dirNames(t, pluginDir)) + }) +} + +func TestPlaceElevates(t *testing.T) { + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + t.Skip("needs a directory the current user cannot write to") + } + t.Parallel() + src := filepath.Join(t.TempDir(), "myplugin") + require.NoError(t, os.WriteFile(src, []byte("binary"), 0o600)) + pluginDir := t.TempDir() + require.NoError(t, os.Chmod(pluginDir, 0o555)) + dst := filepath.Join(pluginDir, "myplugin") + + var elevated []string + opts := installOpts{elevate: func(_ *cobra.Command, from, to string) error { + elevated = append(elevated, from, to) + return nil + }} + require.NoError(t, place(&cobra.Command{}, opts, src, dst)) + assert.Equal(t, []string{src, dst}, elevated) + assert.Empty(t, dirNames(t, pluginDir)) +} + +func writeModule(t *testing.T, src string) string { + t.Helper() + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module example.com/acme/tool\n\ngo 1.21\n"), 0o600)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "main.go"), []byte(src), 0o600)) + return dir +} + +func dirNames(t *testing.T, dir string) []string { + t.Helper() + entries, err := os.ReadDir(dir) + require.NoError(t, err) + var names []string + for _, e := range entries { + names = append(names, e.Name()) + } + return names +} + +func exeName(name string) string { + if runtime.GOOS == "windows" { + return name + ".exe" + } + return name +} diff --git a/plugins/stdinreader/README.md b/plugins/stdinreader/README.md new file mode 100644 index 00000000..3974ca43 --- /dev/null +++ b/plugins/stdinreader/README.md @@ -0,0 +1,34 @@ +# stdinreader + +The stdinreader plugin serves secrets that it reads from standard input. It +suits CI: a job pipes its secrets in once, and later steps reference them as +`se://NAME`. + +At startup it reads the secrets, connects to the standalone Secrets Engine at +[`config.StandaloneSocketPath`](../../client/config), and registers as +`stdinreader`. It keeps the secrets in memory and serves all of them until it +receives SIGINT or SIGTERM. It does not reach Docker Desktop's engine, which +listens on another socket. + +## Usage + +With the engine running, from a checkout of this repository: + +```console +$ printf 'DB_TOKEN=hunter2\n' | go run ./plugins/stdinreader +``` + +While the plugin runs, the engine resolves `se://DB_TOKEN` to `hunter2`. + +Start the plugin yourself. A copy that the engine launches from its plugin +directory gets an empty stdin and exits. + +## Input + +Stdin holds one `KEY=VALUE` pair per line. Each key must be a valid secret ID. + +- Blank lines and lines that start with `#` are skipped. +- A leading `export ` is dropped. +- Matching single or double quotes around a value are removed. +- Values are taken literally: the plugin expands no variables and interprets + no escape sequences. diff --git a/plugins/stdinreader/go.mod b/plugins/stdinreader/go.mod new file mode 100644 index 00000000..e4ed3b16 --- /dev/null +++ b/plugins/stdinreader/go.mod @@ -0,0 +1,28 @@ +module github.com/docker/secrets-engine/plugins/stdinreader + +go 1.26.11 + +// This `replace` is only for CI to function. +// The correct version will get resolved from below when this module is +// retrieved using `go get`. +replace github.com/docker/secrets-engine/plugin => ../../plugin + +replace github.com/docker/secrets-engine/secrets => ../../secrets + +replace github.com/docker/secrets-engine/client => ../../client + +require ( + github.com/docker/secrets-engine/client v0.2.2 + github.com/docker/secrets-engine/plugin v0.3.4 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/docker/secrets-engine/secrets v1.0.0 // indirect + github.com/hashicorp/yamux v0.1.2 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + golang.org/x/sys v0.46.0 // indirect + google.golang.org/protobuf v1.36.11 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/plugins/stdinreader/go.sum b/plugins/stdinreader/go.sum new file mode 100644 index 00000000..a737d3bd --- /dev/null +++ b/plugins/stdinreader/go.sum @@ -0,0 +1,27 @@ +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/hashicorp/yamux v0.1.2 h1:XtB8kyFOyHXYVFnwT5C3+Bdo8gArse7j2AQ0DA0Uey8= +github.com/hashicorp/yamux v0.1.2/go.mod h1:C+zze2n6e/7wshOZep2A70/aQU6QBRWJO/G6FT1wIns= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= +golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= +golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= +golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/plugins/stdinreader/internal/plugin/stdinreader.go b/plugins/stdinreader/internal/plugin/stdinreader.go new file mode 100644 index 00000000..71f4d7cd --- /dev/null +++ b/plugins/stdinreader/internal/plugin/stdinreader.go @@ -0,0 +1,228 @@ +// Copyright 2026 Docker, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package plugin + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "log" + "net" + "os" + "runtime/debug" + + "github.com/docker/secrets-engine/client/config" + clientversion "github.com/docker/secrets-engine/client/version" + "github.com/docker/secrets-engine/plugin" +) + +const pluginName = "stdinreader" + +// Run reads dotenv-formatted secrets from stdin, connects to the secrets +// engine daemon, and serves the secrets as the stdinreader plugin. +// buildVersion is the plugin's build version (typically injected via +// -ldflags). When it is empty or "dev", the module version from the build +// info applies. +func Run(ctx context.Context, buildVersion string) error { + logger := newStderrLogger(pluginName) + + raw, err := io.ReadAll(os.Stdin) + if err != nil { + return fmt.Errorf("reading secrets from stdin: %w", err) + } + + secretsByID, err := parseSecrets(raw) + zero(raw) + if err != nil { + return err + } + + socketPath := config.StandaloneSocketPath() + conn, err := net.Dial("unix", socketPath) + if err != nil { + return fmt.Errorf("connecting to secrets engine at %q: %w", socketPath, err) + } + defer conn.Close() + + version, err := pluginVersion(buildVersion) + if err != nil { + return err + } + + stub, err := plugin.NewSecretsProvider( + &resolver{secrets: secretsByID, logger: logger}, + plugin.Config{ + Version: version, + Logger: logger, + SecretsProviderConfig: &plugin.SecretsProviderConfig{ + Pattern: plugin.MustParsePattern("**"), + }, + }, + plugin.WithPluginName(pluginName), + plugin.WithConnection(conn), + ) + if err != nil { + return fmt.Errorf("creating plugin: %w", err) + } + + return stub.Run(ctx) +} + +func pluginVersion(override string) (plugin.Version, error) { + if override != "" && override != "dev" { + return clientversion.NewVersion(override) + } + if info, ok := debug.ReadBuildInfo(); ok { + if v, err := clientversion.NewVersion(info.Main.Version); err == nil { + return v, nil + } + } + return clientversion.NewVersion("v0.0.0-not-set") +} + +func parseSecrets(raw []byte) (map[plugin.ID][]byte, error) { + if len(bytes.TrimSpace(raw)) == 0 { + return nil, errors.New("no secrets provided on stdin") + } + + flat, err := parseDotenv(raw) + if err != nil { + return nil, fmt.Errorf("parsing dotenv secrets: %w", err) + } + if len(flat) == 0 { + return nil, errors.New("no secrets provided on stdin") + } + + out := make(map[plugin.ID][]byte, len(flat)) + for k, v := range flat { + id, err := plugin.ParseID(k) + if err != nil { + // Abandoning the parsed secrets early: wipe every value buffer + // (those already in out share backing with flat) so no secret + // bytes linger on the heap until GC. + for _, sv := range flat { + zero(sv) + } + return nil, fmt.Errorf("invalid secret key %q: %w", k, err) + } + out[id] = v + } + return out, nil +} + +// zero overwrites b with zero bytes. +func zero(b []byte) { + for i := range b { + b[i] = 0 + } +} + +// parseDotenv parses dotenv-formatted bytes into key/value pairs without +// performing any variable substitution. Secret values are stored verbatim: +// a value like `token$SUFFIX` is preserved literally rather than expanded, +// which would corrupt the credential. +// +// It operates directly on the input bytes (no intermediate string copy of +// the full payload) so that zeroing the caller's buffer also clears the +// parser's working data; only the returned per-value buffers are fresh +// copies that outlive raw. +// +// Supported syntax: blank lines and `#` comment lines are skipped; each +// remaining line is `KEY=VALUE` (an optional leading `export ` is stripped). +// Values may be wrapped in matching single or double quotes, which are +// removed; unquoted values are taken literally after trimming surrounding +// whitespace. No escape sequences are interpreted. +func parseDotenv(raw []byte) (map[string][]byte, error) { + out := make(map[string][]byte) + for i, line := range bytes.Split(raw, []byte("\n")) { + trimmed := bytes.TrimSpace(line) + if len(trimmed) == 0 || trimmed[0] == '#' { + continue + } + trimmed = bytes.TrimPrefix(trimmed, []byte("export ")) + + key, value, ok := bytes.Cut(trimmed, []byte("=")) + if !ok { + return nil, fmt.Errorf("line %d: missing '=' separator", i+1) + } + key = bytes.TrimSpace(key) + if len(key) == 0 { + return nil, fmt.Errorf("line %d: empty key", i+1) + } + + value = bytes.TrimSpace(value) + if len(value) >= 2 { + if q := value[0]; (q == '"' || q == '\'') && value[len(value)-1] == q { + value = value[1 : len(value)-1] + } + } + // Copy so the value outlives (and is independent of) raw, which the + // caller zeroes after parsing. + buf := make([]byte, len(value)) + copy(buf, value) + // A duplicate key rebinds the slot; wipe the displaced buffer so the + // superseded secret does not linger on the heap until GC. + if prev, ok := out[string(key)]; ok { + zero(prev) + } + out[string(key)] = buf + } + return out, nil +} + +type resolver struct { + secrets map[plugin.ID][]byte + logger plugin.Logger +} + +var _ plugin.SecretsProvider = (*resolver)(nil) + +func (r *resolver) GetSecrets(_ context.Context, pattern plugin.Pattern) ([]plugin.Envelope, error) { + var result []plugin.Envelope + for id, value := range r.secrets { + if !pattern.Match(id) { + continue + } + result = append(result, plugin.Envelope{ID: id, Value: value}) + } + if len(result) == 0 { + return nil, plugin.ErrNotFound + } + return result, nil +} + +type stderrLogger struct { + logger *log.Logger +} + +var _ plugin.Logger = (*stderrLogger)(nil) + +func newStderrLogger(prefix string) *stderrLogger { + return &stderrLogger{logger: log.New(os.Stderr, prefix+": ", log.LstdFlags|log.Lmsgprefix)} +} + +func (l *stderrLogger) Printf(format string, v ...any) { + l.logger.Printf(format, v...) +} + +func (l *stderrLogger) Warnf(format string, v ...any) { + l.logger.Printf("[WARN] "+format, v...) +} + +func (l *stderrLogger) Errorf(format string, v ...any) { + l.logger.Printf("[ERR] "+format, v...) +} diff --git a/plugins/stdinreader/internal/plugin/stdinreader_test.go b/plugins/stdinreader/internal/plugin/stdinreader_test.go new file mode 100644 index 00000000..78100723 --- /dev/null +++ b/plugins/stdinreader/internal/plugin/stdinreader_test.go @@ -0,0 +1,109 @@ +// Copyright 2026 Docker, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package plugin + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/docker/secrets-engine/plugin" +) + +func TestPluginVersion(t *testing.T) { + for _, override := range []string{ + "v1.2.3", + "v0.0.0-20261119125715-1e09e23a5625", + "v0.1.1-0.20261119125715-1e09e23a5625+dirty", + } { + v, err := pluginVersion(override) + require.NoError(t, err, override) + assert.Equal(t, override, v.String()) + } + + _, err := pluginVersion("1.2.3") + require.Error(t, err) + + for _, unset := range []string{"", "dev"} { + v, err := pluginVersion(unset) + require.NoError(t, err, unset) + assert.Equal(t, "v0.0.0-not-set", v.String()) + } +} + +func TestParseSecretsDotenv(t *testing.T) { + got, err := parseSecrets([]byte("# comment\nDB_TOKEN=hunter2\nAPI_KEY=\"quoted value\"\n")) + require.NoError(t, err) + + require.Len(t, got, 2) + assert.Equal(t, []byte("hunter2"), got[plugin.MustParseID("DB_TOKEN")]) + assert.Equal(t, []byte("quoted value"), got[plugin.MustParseID("API_KEY")]) +} + +func TestParseSecretsNoVariableSubstitution(t *testing.T) { + got, err := parseSecrets([]byte("DB_PASS=token$SUFFIX\nLITERAL='a$b${c}'\nDQ=\"x$y\"\n")) + require.NoError(t, err) + + assert.Equal(t, []byte("token$SUFFIX"), got[plugin.MustParseID("DB_PASS")]) + assert.Equal(t, []byte("a$b${c}"), got[plugin.MustParseID("LITERAL")]) + assert.Equal(t, []byte("x$y"), got[plugin.MustParseID("DQ")]) +} + +func TestParseSecretsInvalidKey(t *testing.T) { + _, err := parseSecrets([]byte("bad key=value\n")) + require.Error(t, err) + assert.Contains(t, err.Error(), "invalid secret key") +} + +func TestParseSecretsEmpty(t *testing.T) { + for _, raw := range [][]byte{nil, []byte(" \n\t"), []byte("# only a comment\n")} { + _, err := parseSecrets(raw) + require.Error(t, err) + } +} + +func TestResolverGetSecretsMatchAll(t *testing.T) { + r := newTestResolver(t) + + got, err := r.GetSecrets(context.Background(), plugin.MustParsePattern("**")) + require.NoError(t, err) + assert.Len(t, got, 2) +} + +func TestResolverGetSecretsFiltered(t *testing.T) { + r := newTestResolver(t) + + got, err := r.GetSecrets(context.Background(), plugin.MustParsePattern("DB_TOKEN")) + require.NoError(t, err) + require.Len(t, got, 1) + assert.Equal(t, "DB_TOKEN", got[0].ID.String()) + assert.Equal(t, []byte("hunter2"), got[0].Value) +} + +func TestResolverGetSecretsNotFound(t *testing.T) { + r := newTestResolver(t) + + _, err := r.GetSecrets(context.Background(), plugin.MustParsePattern("MISSING")) + require.ErrorIs(t, err, plugin.ErrNotFound) +} + +func newTestResolver(t *testing.T) *resolver { + t.Helper() + secrets, err := parseSecrets([]byte("DB_TOKEN=hunter2\nAPI_KEY=abc\n")) + require.NoError(t, err) + return &resolver{secrets: secrets} +} diff --git a/plugins/stdinreader/main.go b/plugins/stdinreader/main.go new file mode 100644 index 00000000..81be2b03 --- /dev/null +++ b/plugins/stdinreader/main.go @@ -0,0 +1,38 @@ +// Copyright 2026 Docker, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "context" + "fmt" + "os" + "os/signal" + "syscall" + + "github.com/docker/secrets-engine/plugins/stdinreader/internal/plugin" +) + +// version is the build version, injected via -ldflags at build time. +var version = "dev" + +func main() { + ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT) + defer cancel() + + if err := plugin.Run(ctx, version); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} From 4a2a4615c8ee085522a0f67b4a9f06df5289ef28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20Gro=C3=9Fmann?= Date: Thu, 19 Nov 2026 14:39:45 +0100 Subject: [PATCH 2/2] feat(pass): add uninstall command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit UninstallCommand deletes plugins from the engine's plugin directory by file name: docker pass uninstall stdinreader docker pass uninstall stdinreader stdin A name must be a file name without a directory, so the command cannot reach outside the plugin directory. It checks every name before it deletes anything, and it refuses directories. Install and uninstall leave sudo to the user. If the plugin directory is not writable, the command fails and says to rerun it with sudo. This replaces the `sudo install` call that install made: install now creates its staging directory first, so the permission error comes before the build. On Windows the hint says to rerun the command from an elevated terminal. A process that already runs as root, or elevated on Windows, gets no hint. Under sudo, install runs `go install` as the user who called sudo, not as root. If sudo drops Go from PATH, the error says to rerun with `sudo PATH="$PATH"`. The engine scans the plugin directory only at startup, so a deleted plugin keeps running until the engine restarts. The shared name check also fixes install: `--name /` passed the old check. plugins/stdinreader requires client v1.0.0 and plugin v0.4.1, the versions the workspace vendors. Signed-off-by: Johannes Großmann --- plugins/pass/README.md | 27 +++-- plugins/pass/commands/install.go | 106 +++++++++-------- plugins/pass/commands/install_long.md | 4 +- plugins/pass/commands/install_test.go | 50 +++++--- plugins/pass/commands/install_unix.go | 56 +++++++++ plugins/pass/commands/install_windows.go | 33 ++++++ plugins/pass/commands/uninstall.go | 98 ++++++++++++++++ plugins/pass/commands/uninstall_example.md | 5 + plugins/pass/commands/uninstall_long.md | 9 ++ plugins/pass/commands/uninstall_test.go | 126 +++++++++++++++++++++ plugins/stdinreader/go.mod | 4 +- 11 files changed, 439 insertions(+), 79 deletions(-) create mode 100644 plugins/pass/commands/install_unix.go create mode 100644 plugins/pass/commands/install_windows.go create mode 100644 plugins/pass/commands/uninstall.go create mode 100644 plugins/pass/commands/uninstall_example.md create mode 100644 plugins/pass/commands/uninstall_long.md create mode 100644 plugins/pass/commands/uninstall_test.go diff --git a/plugins/pass/README.md b/plugins/pass/README.md index 84348019..759b9947 100644 --- a/plugins/pass/README.md +++ b/plugins/pass/README.md @@ -94,11 +94,24 @@ from a checkout of this repository. It needs the Go toolchain and accepts only binaries that use the [`plugin`](../../plugin) SDK. The file name becomes the plugin name; change it -with `--name`. If the plugin directory is not writable, the final copy runs -through `sudo`. The engine loads plugins at startup, so restart it afterwards. +with `--name`. If the plugin directory is not writable, run the command with +`sudo`: the build still runs as the user who called `sudo`. The engine loads +plugins at startup, so restart it afterwards. -The command exists only in builds whose engine launches plugins from a -directory. +### Uninstall a plugin + +`docker pass uninstall` deletes plugins from the engine's plugin directory by +file name: + +```console +$ docker pass uninstall stdinreader +``` + +If the plugin directory is not writable, run the command with `sudo`. A deleted +plugin keeps running until the engine restarts, so restart it afterwards. + +`install` and `uninstall` exist only in builds whose engine launches plugins +from a directory. ### Troubleshooting @@ -172,6 +185,6 @@ connect to Docker Desktop's socket by default; pass `commands.WithSocketPath` to use another one, and `commands.WithTimeout` or `commands.WithResponseTimeout` to change the timeouts. -`commands.InstallCommand(pluginDir)` needs neither the store nor the engine. -Pass it the directory your engine launches plugins from, and add it only where -that directory exists. +`commands.InstallCommand(pluginDir)` and `commands.UninstallCommand(pluginDir)` +need neither the store nor the engine. Pass them the directory your engine +launches plugins from, and add them only where that directory exists. diff --git a/plugins/pass/commands/install.go b/plugins/pass/commands/install.go index d6b74c04..0e060de0 100644 --- a/plugins/pass/commands/install.go +++ b/plugins/pass/commands/install.go @@ -33,6 +33,8 @@ import ( const pluginSDKModule = "github.com/docker/secrets-engine/plugin" +const sudoPathHint = `If Go is installed, sudo dropped it from PATH. Rerun the command with sudo PATH="$PATH".` + //go:embed install_example.md var installExample string @@ -42,7 +44,6 @@ var installLong string type installOpts struct { pluginDir string name string - elevate func(cmd *cobra.Command, src, dst string) error } // InstallCommand builds a plugin from Go source and installs it into @@ -53,10 +54,7 @@ func InstallCommand(pluginDir string) (*cobra.Command, error) { if !filepath.IsAbs(pluginDir) { return nil, fmt.Errorf("plugin directory must be an absolute path, got %q", pluginDir) } - return newInstallCommand(installOpts{ - pluginDir: pluginDir, - elevate: sudoInstall, - }), nil + return newInstallCommand(installOpts{pluginDir: pluginDir}), nil } func newInstallCommand(opts installOpts) *cobra.Command { @@ -82,24 +80,37 @@ func runInstall(cmd *cobra.Command, opts installOpts, arg string) error { if err != nil { return err } - stage, err := os.MkdirTemp("", "docker-pass-install-*") + stage, err := os.MkdirTemp(opts.pluginDir, ".install-*") + if errors.Is(err, fs.ErrPermission) { + err = fmt.Errorf("installing to %s: %w", opts.pluginDir, fs.ErrPermission) + } if err != nil { - return err + return withEscalationHint(err) } defer func() { _ = os.RemoveAll(stage) }() - if err := goInstall(cmd, target, stage); err != nil { + gobin, err := os.MkdirTemp("", "docker-pass-install-*") + if err != nil { + return err + } + defer func() { _ = os.RemoveAll(gobin) }() + + if err := goInstall(cmd, target, gobin); err != nil { return fmt.Errorf("building %s: %w", arg, err) } - built, err := os.ReadDir(stage) + built, err := os.ReadDir(gobin) if err != nil { return err } if len(built) == 0 { return fmt.Errorf("%s is not a main package: go install produced no binary", arg) } - src := filepath.Join(stage, built[0].Name()) - info, err := buildinfo.ReadFile(src) + name := pluginFileName(opts.name, built[0].Name()) + staged := filepath.Join(stage, name) + if err := copyExecutable(filepath.Join(gobin, built[0].Name()), staged); err != nil { + return err + } + info, err := buildinfo.ReadFile(staged) if err != nil { return fmt.Errorf("reading build info of %s: %w", arg, err) } @@ -107,9 +118,8 @@ func runInstall(cmd *cobra.Command, opts installOpts, arg string) error { return fmt.Errorf("%s is not a secrets engine plugin: it does not use %s", arg, pluginSDKModule) } - name := pluginFileName(opts.name, built[0].Name()) dst := filepath.Join(opts.pluginDir, name) - if err := place(cmd, opts, src, dst); err != nil { + if err := os.Rename(staged, dst); err != nil { return err } _, err = fmt.Fprintf(cmd.OutOrStdout(), "Installed %s (%s %s, %s) to %s\nRestart the secrets engine to load it.\n", @@ -117,6 +127,13 @@ func runInstall(cmd *cobra.Command, opts installOpts, arg string) error { return err } +func withEscalationHint(err error) error { + if errors.Is(err, fs.ErrPermission) && !escalated() { + return fmt.Errorf("%w\n\n%s", err, escalationHint) + } + return err +} + type buildTarget struct { dir string pkg string @@ -156,13 +173,23 @@ func goInstall(cmd *cobra.Command, target buildTarget, gobin string) error { goCmd.Env = append(env, "GOBIN="+gobin) goCmd.Stdout = cmd.ErrOrStderr() goCmd.Stderr = cmd.ErrOrStderr() + if err := deescalate(goCmd, gobin); err != nil { + return err + } err := goCmd.Run() if errors.Is(err, exec.ErrNotFound) { - return fmt.Errorf("the Go toolchain is required to build plugins: %w", err) + err = fmt.Errorf("the Go toolchain is required to build plugins: %w", err) + if underSudo() { + err = fmt.Errorf("%w\n\n%s", err, sudoPathHint) + } } return err } +func underSudo() bool { + return os.Geteuid() == 0 && os.Getenv("SUDO_UID") != "" +} + func usesPluginSDK(info *buildinfo.BuildInfo) bool { for _, dep := range info.Deps { if dep.Path == pluginSDKModule { @@ -173,48 +200,38 @@ func usesPluginSDK(info *buildinfo.BuildInfo) bool { } func checkPluginName(name string) error { - if name == "" || (name == filepath.Base(name) && name != "." && name != "..") { + if name == "" || isFileName(name) { return nil } return fmt.Errorf("invalid --name %q: want a file name without a directory", name) } +func isFileName(name string) bool { + return name != "." && filepath.IsLocal(name) && name == filepath.Base(name) +} + func pluginFileName(name, built string) string { if name == "" { return built } + return withExeSuffix(name) +} + +func withExeSuffix(name string) string { if runtime.GOOS == "windows" && !strings.EqualFold(filepath.Ext(name), ".exe") { name += ".exe" } return name } -func place(cmd *cobra.Command, opts installOpts, src, dst string) error { - err := copyExecutable(src, dst) - if errors.Is(err, fs.ErrPermission) { - return opts.elevate(cmd, src, dst) - } - return err -} - func copyExecutable(src, dst string) error { - tmpDir, err := os.MkdirTemp(filepath.Dir(dst), ".install-*") - if err != nil { - return err - } - defer func() { _ = os.RemoveAll(tmpDir) }() - - tmp := filepath.Join(tmpDir, filepath.Base(dst)) // Copy rather than rename: os.Rename fails across filesystems (e.g. tmpfs // to ext4). src is the go install output in the system temp directory, // which is often tmpfs. - if err := copyFile(src, tmp); err != nil { - return err - } - if err := os.Chmod(tmp, 0o755); err != nil { + if err := copyFile(src, dst); err != nil { return err } - return os.Rename(tmp, dst) + return os.Chmod(dst, 0o755) } func copyFile(src, dst string) error { @@ -234,22 +251,3 @@ func copyFile(src, dst string) error { } return out.Close() } - -// sudoInstall copies src to dst as root; this process stays unprivileged. -// sudo, being setuid-root, prompts for the password on the terminal itself, -// so the password never passes through here. Without a terminal it fails. -func sudoInstall(cmd *cobra.Command, src, dst string) error { - if runtime.GOOS == "windows" { - return fmt.Errorf("installing to %s: %w", filepath.Dir(dst), fs.ErrPermission) - } - args := []string{"install", "-m", "0755", src, dst} - _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Installing to %s requires root; running: sudo %s\n", filepath.Dir(dst), strings.Join(args, " ")) - sudo := exec.CommandContext(cmd.Context(), "sudo", args...) - sudo.Stdin = cmd.InOrStdin() - sudo.Stdout = cmd.OutOrStdout() - sudo.Stderr = cmd.ErrOrStderr() - if err := sudo.Run(); err != nil { - return fmt.Errorf("sudo install: %w", err) - } - return nil -} diff --git a/plugins/pass/commands/install_long.md b/plugins/pass/commands/install_long.md index c1ec1fa7..4265ed35 100644 --- a/plugins/pass/commands/install_long.md +++ b/plugins/pass/commands/install_long.md @@ -11,7 +11,7 @@ a Go program that uses the plugin SDK (`github.com/docker/secrets-engine/plugin`). The file name becomes the plugin name; set it with `--name`. -Requires the Go toolchain. If the plugin directory is not writable, the final -copy runs through `sudo`. +Requires the Go toolchain. If the plugin directory is not writable, run the +command with `sudo`: the build still runs as the user who called `sudo`. The engine loads plugins at startup, so restart it afterwards. diff --git a/plugins/pass/commands/install_test.go b/plugins/pass/commands/install_test.go index e96c2eda..97cedaa0 100644 --- a/plugins/pass/commands/install_test.go +++ b/plugins/pass/commands/install_test.go @@ -23,7 +23,6 @@ import ( "runtime/debug" "testing" - "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -111,7 +110,7 @@ func TestCheckPluginName(t *testing.T) { for _, name := range []string{"", "acme", "acme-plugin.v2"} { assert.NoError(t, checkPluginName(name), name) } - for _, name := range []string{".", "..", "dir/acme", "/acme", "acme/"} { + for _, name := range []string{".", "..", "/", "dir/acme", "/acme", "acme/"} { assert.ErrorContains(t, checkPluginName(name), "invalid --name", name) } } @@ -127,6 +126,7 @@ func TestInstallCommand(t *testing.T) { t.Setenv("GOFLAGS", "-buildvcs=false") t.Setenv("GOTOOLCHAIN", "local") t.Setenv("GOPROXY", "off") + t.Setenv("SUDO_UID", "") install := func(t *testing.T, args ...string) (pluginDir, out string, err error) { t.Helper() @@ -176,6 +176,22 @@ func TestInstallCommand(t *testing.T) { require.NoError(t, err, out) assert.Equal(t, []string{exeName("stdinreader")}, dirNames(t, pluginDir)) }) + t.Run("ignores SUDO_UID without root", func(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("needs an unprivileged user") + } + t.Setenv("SUDO_UID", "0") + pluginDir, out, err := install(t, plugin) + require.NoError(t, err, out) + assert.Equal(t, []string{exeName("stdinreader")}, dirNames(t, pluginDir)) + }) + t.Run("go not on PATH", func(t *testing.T) { + t.Setenv("PATH", t.TempDir()) + pluginDir, out, err := install(t, plugin) + assert.ErrorContains(t, err, "the Go toolchain is required to build plugins", out) + assert.NotContains(t, out, sudoPathHint) + assert.Empty(t, dirNames(t, pluginDir)) + }) t.Run("compile error", func(t *testing.T) { broken := writeModule(t, "package main\n\nfunc main() { missing() }\n") pluginDir, out, err := install(t, broken) @@ -197,27 +213,33 @@ func TestInstallCommand(t *testing.T) { }) } -func TestPlaceElevates(t *testing.T) { +func TestInstallCommandHintsSudo(t *testing.T) { if runtime.GOOS == "windows" || os.Geteuid() == 0 { t.Skip("needs a directory the current user cannot write to") } t.Parallel() - src := filepath.Join(t.TempDir(), "myplugin") - require.NoError(t, os.WriteFile(src, []byte("binary"), 0o600)) pluginDir := t.TempDir() require.NoError(t, os.Chmod(pluginDir, 0o555)) - dst := filepath.Join(pluginDir, "myplugin") - - var elevated []string - opts := installOpts{elevate: func(_ *cobra.Command, from, to string) error { - elevated = append(elevated, from, to) - return nil - }} - require.NoError(t, place(&cobra.Command{}, opts, src, dst)) - assert.Equal(t, []string{src, dst}, elevated) + + out, err := execute(t, newInstallCommand(installOpts{pluginDir: pluginDir}), nil, t.TempDir()) + require.ErrorIs(t, err, fs.ErrPermission, out) + assert.Equal(t, "Error: installing to "+pluginDir+": permission denied\n\n"+escalationHint+"\n", out) assert.Empty(t, dirNames(t, pluginDir)) } +func TestWithEscalationHint(t *testing.T) { + t.Parallel() + denied := &fs.PathError{Op: "remove", Path: "plugin", Err: fs.ErrPermission} + want := denied.Error() + "\n\n" + escalationHint + if escalated() { + want = denied.Error() + } + got := withEscalationHint(denied) + require.ErrorIs(t, got, fs.ErrPermission) + assert.EqualError(t, got, want) + assert.Equal(t, fs.ErrNotExist, withEscalationHint(fs.ErrNotExist)) +} + func writeModule(t *testing.T, src string) string { t.Helper() dir := t.TempDir() diff --git a/plugins/pass/commands/install_unix.go b/plugins/pass/commands/install_unix.go new file mode 100644 index 00000000..6fdfaa4c --- /dev/null +++ b/plugins/pass/commands/install_unix.go @@ -0,0 +1,56 @@ +// Copyright 2026 Docker, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build !windows + +package commands + +import ( + "fmt" + "os" + "os/exec" + "os/user" + "strconv" + "syscall" +) + +const escalationHint = "Rerun the command with sudo." + +func escalated() bool { + return os.Geteuid() == 0 +} + +func deescalate(goCmd *exec.Cmd, gobin string) error { + if !underSudo() { + return nil + } + caller, err := user.LookupId(os.Getenv("SUDO_UID")) + if err != nil { + return fmt.Errorf("looking up the user who ran sudo: %w", err) + } + uid, err := strconv.ParseUint(caller.Uid, 10, 32) + if err != nil { + return err + } + gid, err := strconv.ParseUint(caller.Gid, 10, 32) + if err != nil { + return err + } + if err := os.Lchown(gobin, int(uid), int(gid)); err != nil { + return err + } + goCmd.SysProcAttr = &syscall.SysProcAttr{Credential: &syscall.Credential{Uid: uint32(uid), Gid: uint32(gid)}} + goCmd.Env = append(goCmd.Env, "HOME="+caller.HomeDir, "USER="+caller.Username, "LOGNAME="+caller.Username) + return nil +} diff --git a/plugins/pass/commands/install_windows.go b/plugins/pass/commands/install_windows.go new file mode 100644 index 00000000..e29f3992 --- /dev/null +++ b/plugins/pass/commands/install_windows.go @@ -0,0 +1,33 @@ +// Copyright 2026 Docker, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build windows + +package commands + +import ( + "os/exec" + + "golang.org/x/sys/windows" +) + +const escalationHint = "Rerun the command from an elevated terminal." + +func escalated() bool { + return windows.GetCurrentProcessToken().IsElevated() +} + +func deescalate(_ *exec.Cmd, _ string) error { + return nil +} diff --git a/plugins/pass/commands/uninstall.go b/plugins/pass/commands/uninstall.go new file mode 100644 index 00000000..599b7e8f --- /dev/null +++ b/plugins/pass/commands/uninstall.go @@ -0,0 +1,98 @@ +// Copyright 2026 Docker, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package commands + +import ( + _ "embed" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "slices" + "strings" + + "github.com/spf13/cobra" +) + +//go:embed uninstall_example.md +var uninstallExample string + +//go:embed uninstall_long.md +var uninstallLong string + +// UninstallCommand deletes plugins from pluginDir, the directory the secrets +// engine launches plugins from. The engine scans that directory only at +// startup, so a deleted plugin keeps running until the engine restarts. +func UninstallCommand(pluginDir string) (*cobra.Command, error) { + if !filepath.IsAbs(pluginDir) { + return nil, fmt.Errorf("plugin directory must be an absolute path, got %q", pluginDir) + } + return newUninstallCommand(pluginDir), nil +} + +func newUninstallCommand(pluginDir string) *cobra.Command { + return &cobra.Command{ + Use: "uninstall NAME [NAME...]", + Short: "Delete plugins from the plugin directory.", + Long: strings.Trim(uninstallLong, "\n"), + Example: strings.Trim(uninstallExample, "\n"), + Args: cobra.MinimumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + return runUninstall(cmd, pluginDir, args) + }, + } +} + +func runUninstall(cmd *cobra.Command, pluginDir string, names []string) error { + var paths []string + for _, name := range names { + path, err := pluginPath(pluginDir, name) + if err != nil { + return err + } + if !slices.Contains(paths, path) { + paths = append(paths, path) + } + } + for _, path := range paths { + if err := withEscalationHint(os.Remove(path)); err != nil { + return err + } + if _, err := fmt.Fprintf(cmd.OutOrStdout(), "Uninstalled %s from %s\n", filepath.Base(path), pluginDir); err != nil { + return err + } + } + _, err := fmt.Fprintln(cmd.OutOrStdout(), "Restart the secrets engine to apply the change.") + return err +} + +func pluginPath(dir, name string) (string, error) { + if !isFileName(name) { + return "", fmt.Errorf("invalid plugin name %q: want a file name without a directory", name) + } + path := filepath.Join(dir, withExeSuffix(name)) + fi, err := os.Lstat(path) + if errors.Is(err, fs.ErrNotExist) { + return "", fmt.Errorf("plugin %s is not installed in %s: %w", name, dir, fs.ErrNotExist) + } + if err != nil { + return "", err + } + if fi.IsDir() { + return "", fmt.Errorf("%s is a directory, not a plugin", path) + } + return path, nil +} diff --git a/plugins/pass/commands/uninstall_example.md b/plugins/pass/commands/uninstall_example.md new file mode 100644 index 00000000..e4c085bf --- /dev/null +++ b/plugins/pass/commands/uninstall_example.md @@ -0,0 +1,5 @@ +### Uninstall the stdinreader plugin: + +```console +$ docker pass uninstall stdinreader +``` diff --git a/plugins/pass/commands/uninstall_long.md b/plugins/pass/commands/uninstall_long.md new file mode 100644 index 00000000..d7794149 --- /dev/null +++ b/plugins/pass/commands/uninstall_long.md @@ -0,0 +1,9 @@ +Deletes the named plugins from the engine's plugin directory. + +NAME is a plugin's file name in that directory: the name that +`docker pass install` printed, or the one set with `--name`. + +If the plugin directory is not writable, run the command with `sudo`. + +A deleted plugin keeps running until the engine restarts, so restart it +afterwards. diff --git a/plugins/pass/commands/uninstall_test.go b/plugins/pass/commands/uninstall_test.go new file mode 100644 index 00000000..9598f017 --- /dev/null +++ b/plugins/pass/commands/uninstall_test.go @@ -0,0 +1,126 @@ +// Copyright 2026 Docker, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package commands + +import ( + "io/fs" + "os" + "path/filepath" + "runtime" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestUninstallCommandOptions(t *testing.T) { + t.Parallel() + for _, dir := range []string{"", "plugins", "./plugins"} { + _, err := UninstallCommand(dir) + assert.ErrorContains(t, err, "absolute path", dir) + } + cmd, err := UninstallCommand(t.TempDir()) + require.NoError(t, err) + assert.Equal(t, "uninstall", cmd.Name()) +} + +func TestUninstallCommand(t *testing.T) { + t.Parallel() + pluginDir := func(t *testing.T, names ...string) string { + t.Helper() + dir := t.TempDir() + for _, name := range names { + require.NoError(t, os.WriteFile(filepath.Join(dir, exeName(name)), []byte("binary"), 0o755)) + } + return dir + } + uninstall := func(t *testing.T, dir string, args ...string) (string, error) { + t.Helper() + return execute(t, newUninstallCommand(dir), nil, args...) + } + + t.Run("deletes the plugin", func(t *testing.T) { + t.Parallel() + dir := pluginDir(t, "acme", "other") + out, err := uninstall(t, dir, "acme") + require.NoError(t, err, out) + assert.Equal(t, []string{exeName("other")}, dirNames(t, dir)) + assert.Equal(t, "Uninstalled "+exeName("acme")+" from "+dir+"\nRestart the secrets engine to apply the change.\n", out) + }) + t.Run("deletes several plugins", func(t *testing.T) { + t.Parallel() + dir := pluginDir(t, "acme", "other", "third") + out, err := uninstall(t, dir, "third", "acme", "third") + require.NoError(t, err, out) + assert.Equal(t, []string{exeName("other")}, dirNames(t, dir)) + assert.Equal(t, "Uninstalled "+exeName("third")+" from "+dir+"\n"+ + "Uninstalled "+exeName("acme")+" from "+dir+"\n"+ + "Restart the secrets engine to apply the change.\n", out) + }) + t.Run("missing plugin deletes nothing", func(t *testing.T) { + t.Parallel() + dir := pluginDir(t, "acme") + out, err := uninstall(t, dir, "acme", "missing") + require.ErrorIs(t, err, fs.ErrNotExist, out) + assert.ErrorContains(t, err, "plugin missing is not installed in "+dir) + assert.Equal(t, []string{exeName("acme")}, dirNames(t, dir)) + }) + t.Run("rejects a name with a directory", func(t *testing.T) { + t.Parallel() + parent := t.TempDir() + dir := filepath.Join(parent, "plugins") + require.NoError(t, os.Mkdir(dir, 0o755)) + outside := filepath.Join(parent, exeName("outside")) + require.NoError(t, os.WriteFile(outside, []byte("keep"), 0o600)) + for _, name := range []string{"", ".", "..", "/", "../outside", outside} { + out, err := uninstall(t, dir, name) + assert.ErrorContains(t, err, "invalid plugin name", name, out) + } + assert.FileExists(t, outside) + }) + t.Run("refuses a directory", func(t *testing.T) { + t.Parallel() + dir := t.TempDir() + sub := filepath.Join(dir, exeName("acme")) + require.NoError(t, os.Mkdir(sub, 0o755)) + out, err := uninstall(t, dir, "acme") + assert.ErrorContains(t, err, "is a directory, not a plugin", out) + assert.DirExists(t, sub) + }) + t.Run("requires a name", func(t *testing.T) { + t.Parallel() + dir := pluginDir(t, "acme") + out, err := uninstall(t, dir, []string{}...) + assert.ErrorContains(t, err, "requires at least 1 arg", out) + assert.Equal(t, []string{exeName("acme")}, dirNames(t, dir)) + }) +} + +func TestUninstallCommandHintsSudo(t *testing.T) { + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + t.Skip("needs a directory the current user cannot write to") + } + t.Parallel() + pluginDir := t.TempDir() + path := filepath.Join(pluginDir, "myplugin") + require.NoError(t, os.WriteFile(path, []byte("binary"), 0o755)) + require.NoError(t, os.Chmod(pluginDir, 0o555)) + t.Cleanup(func() { _ = os.Chmod(pluginDir, 0o755) }) + + out, err := execute(t, newUninstallCommand(pluginDir), nil, "myplugin") + require.ErrorIs(t, err, fs.ErrPermission, out) + assert.Equal(t, "Error: remove "+path+": permission denied\n\n"+escalationHint+"\n", out) + assert.FileExists(t, path) +} diff --git a/plugins/stdinreader/go.mod b/plugins/stdinreader/go.mod index e4ed3b16..2257f1f5 100644 --- a/plugins/stdinreader/go.mod +++ b/plugins/stdinreader/go.mod @@ -12,8 +12,8 @@ replace github.com/docker/secrets-engine/secrets => ../../secrets replace github.com/docker/secrets-engine/client => ../../client require ( - github.com/docker/secrets-engine/client v0.2.2 - github.com/docker/secrets-engine/plugin v0.3.4 + github.com/docker/secrets-engine/client v1.0.0 + github.com/docker/secrets-engine/plugin v0.4.1 github.com/stretchr/testify v1.11.1 )