Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 52 additions & 8 deletions plugins/pass/commands/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,14 @@ import (
"context"
"errors"
"fmt"
"maps"
"os"
"os/exec"
"os/signal"
"sort"
"strings"

"github.com/joho/godotenv"
"github.com/spf13/cobra"

"github.com/docker/secrets-engine/client"
Expand Down Expand Up @@ -50,19 +53,28 @@ const runExample = `
SE_TOKEN=se://gh-token docker pass run -- gh repo list

### Multiple references:
DB_PASSWORD=se://myapp/postgres/password \
API_KEY=se://myapp/anthropic/api-key \
docker pass run -- ./my-binary
DB_PASSWORD=se://myapp/postgres/password API_KEY=se://myapp/anthropic/api-key docker pass run -- ./my-binary

### Resolve references from a dotenv file:
docker pass run --env-file .env -- ./my-binary

### Multiple files (later overrides earlier; files override the process environment):
docker pass run --env-file .env --env-file .env.local -- ./my-binary
`

type runOpts struct {
envFiles []string
}

func RunCommand() *cobra.Command {
opts := runOpts{}
cmd := &cobra.Command{
Use: "run -- CMD [ARGS...]",
Short: "Run a command with se:// environment references resolved.",
Long: `Scans the current environment for variables whose value is exactly se://NAME.
Each reference is resolved through the secrets-engine daemon and the resolved
value is passed to the child process. The child inherits stdin, stdout, and
stderr.
Long: `Scans the current environment (plus any --env-file inputs) for variables
whose value is exactly se://NAME. Each reference is resolved through the
secrets-engine daemon and the resolved value is passed to the child process.
The child inherits stdin, stdout, and stderr.

Requires the secrets-engine daemon (Docker Desktop) to be running.

Expand All @@ -71,12 +83,17 @@ started and exits non-zero.`,
Example: strings.Trim(runExample, "\n"),
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
merged, err := mergeEnv(os.Environ(), opts.envFiles)
if err != nil {
return err
}

c, err := client.New(client.WithSocketPath(api.DefaultSocketPath()))
if err != nil {
return err
}

env, err := resolveEnv(cmd.Context(), c, os.Environ())
env, err := resolveEnv(cmd.Context(), c, merged)
if err != nil {
return err
}
Expand Down Expand Up @@ -130,9 +147,36 @@ started and exits non-zero.`,
return nil
},
}
cmd.Flags().StringArrayVar(&opts.envFiles, "env-file", nil,
"Read environment variables from a dotenv-formatted file. Repeatable; later files override earlier files and the process environment.")
return cmd
}

// mergeEnv folds the process environment and any --env-file inputs into a
// single deterministic KEY=VALUE slice. Precedence: process env first, then
Comment thread
joe0BAB marked this conversation as resolved.
// each file in order; later entries override earlier ones.
func mergeEnv(processEnv, files []string) ([]string, error) {
merged := make(map[string]string, len(processEnv))
for _, kv := range processEnv {
if k, v, ok := strings.Cut(kv, "="); ok {
merged[k] = v
}
}
for _, f := range files {
parsed, err := godotenv.Read(f)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BUG: godotenv.Read expands $VAR using only the in-file variable map; process-env vars silently become empty strings

godotenv.Read(f) resolves $VAR references during parsing using only variables defined within the same file. The process environment is never consulted.

parsed, err := godotenv.Read(f)   //  expansion is in-file-only

Silent failure scenario: If a user writes a parameterised secret reference in their .env file:

# .env file
SE_TOKEN=se://$ACCOUNT/prod/db

expecting $ACCOUNT to come from the process environment, godotenv.Read silently expands it to the empty string, yielding se:///prod/db. This invalid path is then sent to the secrets daemon, which returns a cryptic error — the user has no indication that variable expansion failed.

Fix: Use godotenv.Parse (which returns raw values without expansion) instead of godotenv.Read, then perform variable expansion against the merged environment map after combining process env and file values:

parsed, err := godotenv.Parse(file)   // no expansion
// then apply os.Expand(v, mergedMap.Get) on values that contain $

Or at minimum, document this limitation prominently in the flag help text so users know $VAR in .env values only references other variables in the same file.

if err != nil {
return nil, fmt.Errorf("reading env-file %s: %w", f, err)
}
maps.Copy(merged, parsed)
}
out := make([]string, 0, len(merged))
for k, v := range merged {
out = append(out, k+"="+v)
}
sort.Strings(out)
return out, nil
}

func resolveEnv(ctx context.Context, r secrets.Resolver, env []string) ([]string, error) {
out := make([]string, 0, len(env))
for _, kv := range env {
Expand Down
58 changes: 58 additions & 0 deletions plugins/pass/commands/run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"syscall"
Expand Down Expand Up @@ -176,6 +177,63 @@ func TestResolveEnv(t *testing.T) {
})
}

func TestMergeEnv(t *testing.T) {
t.Parallel()

writeFile := func(t *testing.T, body string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "env")
require.NoError(t, os.WriteFile(path, []byte(body), 0o600))
return path
}

t.Run("no files returns sorted process env", func(t *testing.T) {
out, err := mergeEnv([]string{"B=2", "A=1"}, nil)
require.NoError(t, err)
assert.Equal(t, []string{"A=1", "B=2"}, out)
})

t.Run("file overrides process env", func(t *testing.T) {
f := writeFile(t, "A=from-file\nC=new\n")
out, err := mergeEnv([]string{"A=from-process", "B=keep"}, []string{f})
require.NoError(t, err)
assert.Equal(t, []string{"A=from-file", "B=keep", "C=new"}, out)
})

t.Run("later file overrides earlier file", func(t *testing.T) {
f1 := writeFile(t, "A=from-file-1\n")
f2 := writeFile(t, "A=from-file-2\n")
out, err := mergeEnv(nil, []string{f1, f2})
require.NoError(t, err)
assert.Equal(t, []string{"A=from-file-2"}, out)
})

t.Run("comments and quoted values", func(t *testing.T) {
f := writeFile(t, "# this is a comment\nGREETING=\"hello world\"\nQUOTED='no $expand'\n")
out, err := mergeEnv(nil, []string{f})
require.NoError(t, err)
assert.Equal(t, []string{
"GREETING=hello world",
"QUOTED=no $expand",
}, out)
})

t.Run("missing file returns error and does not partially apply", func(t *testing.T) {
f := writeFile(t, "A=present\n")
out, err := mergeEnv([]string{"B=keep"}, []string{f, "/does/not/exist/.env"})
require.Error(t, err)
assert.Nil(t, out)
assert.Contains(t, err.Error(), "/does/not/exist/.env")
})

t.Run("preserves se:// values for downstream resolveEnv", func(t *testing.T) {
f := writeFile(t, "SE_TOKEN=se://gh-token\nPLAIN=v\n")
out, err := mergeEnv(nil, []string{f})
require.NoError(t, err)
assert.Equal(t, []string{"PLAIN=v", "SE_TOKEN=se://gh-token"}, out)
})
}

// TestRunCommand covers cobra-level behavior that does not depend on a running
// daemon. Resolution behavior is covered by TestResolveEnv.
func TestRunCommand(t *testing.T) {
Expand Down
1 change: 1 addition & 0 deletions plugins/pass/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ require (
github.com/docker/secrets-engine/plugin v0.0.22
github.com/docker/secrets-engine/store v0.0.23
github.com/docker/secrets-engine/x v0.0.32-do.not.use
github.com/joho/godotenv v1.5.1
github.com/spf13/cobra v1.10.1
github.com/stretchr/testify v1.11.1
go.opentelemetry.io/otel v1.40.0
Expand Down
2 changes: 2 additions & 0 deletions plugins/pass/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ 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/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
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=
Expand Down
1 change: 1 addition & 0 deletions vendor/github.com/joho/godotenv/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 23 additions & 0 deletions vendor/github.com/joho/godotenv/LICENCE

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading