Skip to content

Commit

Permalink
feat: allow certain env vars to be passed on to the cmd
Browse files Browse the repository at this point in the history
  • Loading branch information
adityathebe authored and moshloop committed Sep 15, 2024
1 parent 708d505 commit e1b1364
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
22 changes: 22 additions & 0 deletions shell/shell.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,20 @@ import (
"github.com/samber/oops"
)

// List of env var keys that we pass on to the exec command
var allowedEnvVars = map[string]struct{}{
"CLOUDSDK_PYTHON": {},
"DEBIAN_FRONTEND": {},
"DOTNET_SYSTEM_GLOBALIZATION_INVARIANT": {},
"HOME": {},
"LC_CTYPE": {},
"PATH": {},
"PS_INSTALL_FOLDER": {},
"PS_VERSION": {},
"PSModuleAnalysisCachePath": {},
"USER": {},
}

var checkoutLocks = utils.NamedLock{}

type Exec struct {
Expand Down Expand Up @@ -76,6 +90,14 @@ func Run(ctx context.Context, exec Exec) (*ExecDetails, error) {

// Set to a non-nil empty slice to prevent access to current environment variables
cmd.Env = []string{}

for _, e := range os.Environ() {
key, _, ok := strings.Cut(e, "=")
if _, exists := allowedEnvVars[key]; exists && ok {
cmd.Env = append(cmd.Env, e)
}
}

if len(envParams.envs) != 0 {
ctx.Logger.V(6).Infof("using environment %s", logger.Pretty(envParams.envs))
cmd.Env = append(cmd.Env, envParams.envs...)
Expand Down
16 changes: 12 additions & 4 deletions shell/shell_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"strings"
"testing"

"github.com/flanksource/commons/collections"
"github.com/flanksource/duty/context"
"github.com/flanksource/duty/types"
"github.com/samber/lo"
Expand All @@ -23,7 +24,7 @@ func TestEnv(t *testing.T) {
{Name: "mc_test_secret", ValueStatic: "abcdef"},
},
},
expectedVars: []string{"mc_test_secret=abcdef"},
expectedVars: []string{"mc_test_secret"},
},
{
name: "access multiple custom env vars",
Expand All @@ -34,7 +35,7 @@ func TestEnv(t *testing.T) {
{Name: "mc_test_secret_id", ValueStatic: "xyz"},
},
},
expectedVars: []string{"mc_test_secret_key=abc", "mc_test_secret_id=xyz"},
expectedVars: []string{"mc_test_secret_key", "mc_test_secret_id"},
},
{
name: "no access to process env",
Expand Down Expand Up @@ -69,8 +70,15 @@ func TestEnv(t *testing.T) {
return key != "PWD" && key != "SHLVL" && key != "_"
})

if !lo.Every(envVars, td.expectedVars) || !lo.Every(td.expectedVars, envVars) {
t.Errorf("expected %s, got %s", td.expectedVars, envVars)
envVarKeys := lo.Map(envVars, func(v string, _ int) string {
key, _, _ := strings.Cut(v, "=")
return key
})

expected := collections.MapKeys(allowedEnvVars)
expected = append(expected, td.expectedVars...)
if !lo.Every(expected, envVarKeys) {
t.Errorf("expected %s, got %s", td.expectedVars, envVarKeys)
}
})
}
Expand Down

0 comments on commit e1b1364

Please sign in to comment.