Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: hide os shell envs #1052

Merged
merged 2 commits into from
Sep 15, 2024
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
32 changes: 29 additions & 3 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 All @@ -38,14 +52,16 @@ type Artifact struct {
}

type ExecDetails struct {
Error error `json:"-"`
Stdout string `json:"stdout"`
Stderr string `json:"stderr"`
ExitCode int `json:"exitCode"`
Path string `json:"path"`
Args []string `json:"args"`

// Any extra details about the command execution, e.g. git commit id, etc.
Extra map[string]any `json:"extra,omitempty"`
Extra map[string]any `json:"extra,omitempty"`

Error error `json:"-" yaml:"-"`
Artifacts []artifacts.Artifact `json:"-" yaml:"-"`
}

Expand All @@ -72,9 +88,19 @@ func Run(ctx context.Context, exec Exec) (*ExecDetails, error) {
return nil, ctx.Oops().Wrap(err)
}

// 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(os.Environ(), envParams.envs...)
cmd.Env = append(cmd.Env, envParams.envs...)
adityathebe marked this conversation as resolved.
Show resolved Hide resolved
}

if envParams.mountPoint != "" {
Expand Down
85 changes: 85 additions & 0 deletions shell/shell_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package shell

import (
"strings"
"testing"

"github.com/flanksource/commons/collections"
"github.com/flanksource/duty/context"
"github.com/flanksource/duty/types"
"github.com/samber/lo"
)

func TestEnv(t *testing.T) {
testData := []struct {
name string
exec Exec
expectedVars []string
}{
{
name: "access custom env vars",
exec: Exec{
Script: "env",
EnvVars: []types.EnvVar{
{Name: "mc_test_secret", ValueStatic: "abcdef"},
},
},
expectedVars: []string{"mc_test_secret"},
},
{
name: "access multiple custom env vars",
exec: Exec{
Script: "env",
EnvVars: []types.EnvVar{
{Name: "mc_test_secret_key", ValueStatic: "abc"},
{Name: "mc_test_secret_id", ValueStatic: "xyz"},
},
},
expectedVars: []string{"mc_test_secret_key", "mc_test_secret_id"},
},
{
name: "no access to process env",
exec: Exec{
Script: "env",
},
expectedVars: []string{},
},
}

ctx := context.New()
for _, td := range testData {
t.Run(td.name, func(t *testing.T) {
result, err := Run(ctx, td.exec)
if err != nil {
t.Fatalf("failed to run command %s", err)
}

if result.ExitCode != 0 {
t.Errorf("unexpected non-zero exit code: %d", result.ExitCode)
}

if result.Stderr != "" {
t.Errorf("unexpected stderr: %s", result.Stderr)
}

envVars := strings.Split(result.Stdout, "\n")

// These env vars are always made available.
envVars = lo.Filter(envVars, func(v string, _ int) bool {
key, _, _ := strings.Cut(v, "=")
return key != "PWD" && key != "SHLVL" && key != "_"
})

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)
}
})
}
}
Loading