ronantakizawa/codereview-bench huggingface dataset:
Repository: hashicorp/nomad
File: command/agent/config.go (Go)

Code before:
func (r *RPCConfig) Merge(rpc *RPCConfig) *RPCConfig {
	if r == nil {
		return rpc
	}

	result := *r

	if rpc == nil {
		return &result
	}

	if rpc.AcceptBacklog > 0 {
		result.AcceptBacklog = rpc.AcceptBacklog
	}
	if rpc.KeepAliveInterval > 0 {
		result.KeepAliveInterval = rpc.KeepAliveInterval
	}
	if rpc.ConnectionWriteTimeout > 0 {
		result.ConnectionWriteTimeout = rpc.ConnectionWriteTimeout
	}
	if rpc.StreamOpenTimeout > 0 {
		result.StreamOpenTimeout = rpc.StreamOpenTimeout
	}
	if rpc.StreamCloseTimeout > 0 {
		result.StreamCloseTimeout = rpc.StreamCloseTimeout
	}
	return &result
}

func (r *RPCConfig) Validate() error {
	if r != nil {
		if r.AcceptBacklog < 0 {
			return errors.New("rcp.accept_backlog interval must be greater than zero")
		}

		if r.KeepAliveInterval < 0 {
			return errors.New("rcp.keep_alive_interval must be greater than zero")
		}

		if r.ConnectionWriteTimeout < 0 {
			return errors.New("rcp.connection_write_timeout must be greater than zero")
		}
		if r.StreamCloseTimeout < 0 {
			return errors.New("rcp.stream_close_timeout must be greater than zero")
		}
		if r.StreamOpenTimeout < 0 {
			return errors.New("rcp.stream_open_timeout must be greater than zero")
		}
	}

	return nil

Review comment (bug):
Although the downstream consumers don't need the strings, we're dropping them here when we merge, which means we'll end up with string fields that don't match the parsed values. For debugging purposes, we should make sure we're retaining the strings too.

Code after:
func (r *RPCConfig) Merge(rpc *RPCConfig) *RPCConfig {
	if r == nil {
		return rpc
	}

	result := *r

	if rpc == nil {
		return &result
	}

	if rpc.AcceptBacklog > 0 {
		result.AcceptBacklog = rpc.AcceptBacklog
	}
	if rpc.KeepAliveIntervalHCL != "" {
		result.KeepAliveIntervalHCL = rpc.KeepAliveIntervalHCL
	}
	if rpc.KeepAliveInterval > 0 {
		result.KeepAliveInterval = rpc.KeepAliveInterval
	}
	if rpc.ConnectionWriteTimeoutHCL != "" {
		result.ConnectionWriteTimeoutHCL = rpc.ConnectionWriteTimeoutHCL
	}
	if rpc.ConnectionWriteTimeout > 0 {
		result.ConnectionWriteTimeout = rpc.ConnectionWriteTimeout
	}
	if rpc.StreamOpenTimeoutHCL != "" {
		result.StreamOpenTimeoutHCL = rpc.StreamOpenTimeoutHCL
	}
	if rpc.StreamOpenTimeout > 0 {
		result.StreamOpenTimeout = rpc.StreamOpenTimeout
	}
	if rpc.StreamCloseTimeoutHCL != "" {
		result.StreamCloseTimeoutHCL = rpc.StreamCloseTimeoutHCL
	}
	if rpc.StreamCloseTimeout > 0 {
		result.StreamCloseTimeout = rpc.StreamCloseTimeout
	}
	return &result
}

func (r *RPCConfig) Validate() error {
	if r != nil {
		if r.AcceptBacklog < 0 {
			return errors.New("rcp.accept_backlog interval must be greater than zero")
		}
		if r.KeepAliveInterval < 0 {
			return errors.New("rcp.keep_alive_interval must be greater than zero")
		}
		if r.ConnectionWriteTimeout < 0 {
			return errors.New("rcp.connection_write_timeout must be greater than zero")
Repository: hashicorp/nomad
File: client/allocrunner/csi_hook.go (Go)

Code before:
	usageOpts := &csimanager.UsageOptions{
		ReadOnly:       result.request.ReadOnly,
		AttachmentMode: result.request.AttachmentMode,
		AccessMode:     result.request.AccessMode,
		MountOptions:   result.request.MountOptions,
	}

	return manager.UnmountVolume(c.shutdownCtx,
		result.stub.VolumeNamespace, result.stub.VolumeID,
		result.stub.VolumeExternalID, c.alloc.ID, usageOpts)
}

// Shutdown will get called when the client is gracefully
// stopping. Cancel our shutdown context so that we don't block client
// shutdown while in the CSI RPC retry loop.
func (c *csiHook) Shutdown() {
	c.logger.Trace("shutting down hook")
	c.shutdownCancelFn()
}

// Destroy will get called when an allocation gets GC'd on the client
// or when a -dev mode client is stopped. Cancel our shutdown context
// so that we don't block client shutdown while in the CSI RPC retry
// loop.
func (c *csiHook) Destroy() error {
	c.logger.Trace("destroying hook")
	c.shutdownCancelFn()
	return nil
}


Review comment (suggestion):
Unrelated but we already have trace level logs for every hook in alloc_runner_hooks.go
```suggestion
```

Code after:
	usageOpts := &csimanager.UsageOptions{
		ReadOnly:       result.request.ReadOnly,
		AttachmentMode: result.request.AttachmentMode,
		AccessMode:     result.request.AccessMode,
		MountOptions:   result.request.MountOptions,
	}

	return manager.UnmountVolume(c.shutdownCtx,
		result.stub.VolumeNamespace, result.stub.VolumeID,
		result.stub.VolumeExternalID, c.alloc.ID, usageOpts)
}

// Shutdown will get called when the client is gracefully
// stopping. Cancel our shutdown context so that we don't block client
// shutdown while in the CSI RPC retry loop.
func (c *csiHook) Shutdown() {
	c.shutdownCancelFn()
}

// Destroy will get called when an allocation gets GC'd on the client
// or when a -dev mode client is stopped. Cancel our shutdown context
// so that we don't block client shutdown while in the CSI RPC retry
// loop.
func (c *csiHook) Destroy() error {
	c.shutdownCancelFn()
	return nil
}
Repository: hashicorp/nomad
File: drivers/shared/executor/executor_windows.go (Go)

Code before:
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

//go:build windows

package executor

import (
	"errors"
	"fmt"
	"os"
	"os/exec"
	"strings"
	"syscall"
	"unsafe"

	hclog "github.com/hashicorp/go-hclog"
	"github.com/hashicorp/go-set/v3"
	"github.com/hashicorp/nomad/client/lib/cpustats"
	"github.com/hashicorp/nomad/drivers/shared/executor/procstats"
	"github.com/hashicorp/nomad/plugins/drivers"
	"golang.org/x/sys/windows"
)

func NewExecutorWithIsolation(logger hclog.Logger, compute cpustats.Compute) Executor {
	logger = logger.Named("executor")
	logger.Error("isolation executor is not supported on this platform, using default")
	return NewExecutor(logger, compute)
}

func (e *UniversalExecutor) configureResourceContainer(_ *ExecCommand, _ int) (func() error, func(), error) {

Review comment (security):
For some reason you've changed the permissions on the source code files. These should not be made executable.

Code after:
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

//go:build windows

package executor

import (
	"errors"
	"fmt"
	"os"
	"os/exec"
	"runtime"
	"strings"
	"syscall"
	"unsafe"

	hclog "github.com/hashicorp/go-hclog"
	"github.com/hashicorp/go-set/v3"
	"github.com/hashicorp/nomad/client/lib/cpustats"
	"github.com/hashicorp/nomad/drivers/shared/executor/procstats"
	"github.com/hashicorp/nomad/plugins/drivers"
	"golang.org/x/sys/windows"
)

func NewExecutorWithIsolation(logger hclog.Logger, compute cpustats.Compute) Executor {
	logger = logger.Named("executor")
	logger.Error("isolation executor is not supported on this platform, using default")
	return NewExecutor(logger, compute)
}
Repository: hashicorp/nomad
File: drivers/shared/executor/executor_windows.go (Go)

Code before:
	if len(nameParts) != 2 {
		return errors.New("user name must contain domain")
	}
	token, err := createUserToken(nameParts[1], nameParts[0])
	if err != nil {
		return fmt.Errorf("failed to create user token: %v", err)
	}

	if cmd.SysProcAttr == nil {
		cmd.SysProcAttr = &syscall.SysProcAttr{}
	}
	cmd.SysProcAttr.Token = *token
	return nil
}

var (
	advapiDll      = windows.NewLazySystemDLL("advapi32.dll")
	procLogonUserW = advapiDll.NewProc("LogonUserW")
)

const (
	_LOGON_SERVICE    uint32 = 5
	_PROVIDER_DEFAULT uint32 = 0
)

func createUserToken(username, domain string) (*syscall.Token, error) {
	userw, err := syscall.UTF16PtrFromString(username)
	if err != nil {
		return nil, fmt.Errorf("failed to convert username to UTF-16: %v", err)
	}
	domainw, err := syscall.UTF16PtrFromString(domain)
	if err != nil {
		return nil, fmt.Errorf("failed to convert user domain to UTF-16: %v", err)
	}
	var token syscall.Token
	ret, _, e := procLogonUserW.Call(
		uintptr(unsafe.Pointer(userw)),
		uintptr(unsafe.Pointer(domainw)),
		uintptr(unsafe.Pointer(nil)),
		uintptr(_LOGON_SERVICE),
		uintptr(_PROVIDER_DEFAULT),
		uintptr(unsafe.Pointer(&token)),
	)
	if ret == 0 {
		return nil, e
	}

	return &token, nil
}

func (e *UniversalExecutor) ListProcesses() set.Collection[int] {

Review comment (bug):
Super nitpick: I wouldn't swap the domain and username args like this. It just makes everything a little easier to read/debug if we can map directly from the user's input to the args.

Code after:
	nameParts := strings.Split(user, "\\")
	if len(nameParts) != 2 {
		return errors.New("user name must contain domain")
	}
	token, err := createUserToken(nameParts[0], nameParts[1])
	if err != nil {
		return fmt.Errorf("failed to create user token: %w", err)
	}

	if cmd.SysProcAttr == nil {
		cmd.SysProcAttr = &syscall.SysProcAttr{}
	}
	cmd.SysProcAttr.Token = *token

	runtime.AddCleanup(cmd, func(attr *syscall.SysProcAttr) {
		_ = attr.Token.Close()
	}, cmd.SysProcAttr)

	return nil
}

var (
	advapiDll      = windows.NewLazySystemDLL("advapi32.dll")
	procLogonUserW = advapiDll.NewProc("LogonUserW")
)

const (
	_LOGON_SERVICE    uint32 = 5
	_PROVIDER_DEFAULT uint32 = 0
)

func createUserToken(domain, username string) (*syscall.Token, error) {
	userw, err := syscall.UTF16PtrFromString(username)
	if err != nil {
		return nil, fmt.Errorf("failed to convert username to UTF-16: %w", err)
	}
	domainw, err := syscall.UTF16PtrFromString(domain)
	if err != nil {
		return nil, fmt.Errorf("failed to convert user domain to UTF-16: %w", err)
	}
	var token syscall.Token
	ret, _, e := procLogonUserW.Call(
		uintptr(unsafe.Pointer(userw)),
		uintptr(unsafe.Pointer(domainw)),
		uintptr(unsafe.Pointer(nil)),
		uintptr(_LOGON_SERVICE),
		uintptr(_PROVIDER_DEFAULT),
		uintptr(unsafe.Pointer(&token)),
	)
	if ret == 0 {
		return nil, e
Repository: hashicorp/nomad
File: drivers/shared/executor/executor_windows.go (Go)

Code before:
	token, err := createUserToken(nameParts[1], nameParts[0])
	if err != nil {
		return fmt.Errorf("failed to create user token: %v", err)
	}

	if cmd.SysProcAttr == nil {
		cmd.SysProcAttr = &syscall.SysProcAttr{}
	}
	cmd.SysProcAttr.Token = *token
	return nil
}

var (
	advapiDll      = windows.NewLazySystemDLL("advapi32.dll")
	procLogonUserW = advapiDll.NewProc("LogonUserW")
)

const (
	_LOGON_SERVICE    uint32 = 5
	_PROVIDER_DEFAULT uint32 = 0
)

func createUserToken(username, domain string) (*syscall.Token, error) {
	userw, err := syscall.UTF16PtrFromString(username)
	if err != nil {
		return nil, fmt.Errorf("failed to convert username to UTF-16: %v", err)
	}
	domainw, err := syscall.UTF16PtrFromString(domain)
	if err != nil {
		return nil, fmt.Errorf("failed to convert user domain to UTF-16: %v", err)
	}
	var token syscall.Token
	ret, _, e := procLogonUserW.Call(
		uintptr(unsafe.Pointer(userw)),
		uintptr(unsafe.Pointer(domainw)),
		uintptr(unsafe.Pointer(nil)),
		uintptr(_LOGON_SERVICE),
		uintptr(_PROVIDER_DEFAULT),
		uintptr(unsafe.Pointer(&token)),
	)
	if ret == 0 {
		return nil, e
	}

	return &token, nil
}

func (e *UniversalExecutor) ListProcesses() set.Collection[int] {
	return procstats.ListByPid(e.childCmd.Process.Pid)
}


Review comment (bug):
There's likely nothing using this wrapped error, but we try to wrap them anyways for future callers / tests.

```suggestion
		return nil, fmt.Errorf("failed to convert username to UTF-16: %w", err)
```

Code after:
	}
	token, err := createUserToken(nameParts[0], nameParts[1])
	if err != nil {
		return fmt.Errorf("failed to create user token: %w", err)
	}

	if cmd.SysProcAttr == nil {
		cmd.SysProcAttr = &syscall.SysProcAttr{}
	}
	cmd.SysProcAttr.Token = *token

	runtime.AddCleanup(cmd, func(attr *syscall.SysProcAttr) {
		_ = attr.Token.Close()
	}, cmd.SysProcAttr)

	return nil
}

var (
	advapiDll      = windows.NewLazySystemDLL("advapi32.dll")
	procLogonUserW = advapiDll.NewProc("LogonUserW")
)

const (
	_LOGON_SERVICE    uint32 = 5
	_PROVIDER_DEFAULT uint32 = 0
)

func createUserToken(domain, username string) (*syscall.Token, error) {
	userw, err := syscall.UTF16PtrFromString(username)
	if err != nil {
		return nil, fmt.Errorf("failed to convert username to UTF-16: %w", err)
	}
	domainw, err := syscall.UTF16PtrFromString(domain)
	if err != nil {
		return nil, fmt.Errorf("failed to convert user domain to UTF-16: %w", err)
	}
	var token syscall.Token
	ret, _, e := procLogonUserW.Call(
		uintptr(unsafe.Pointer(userw)),
		uintptr(unsafe.Pointer(domainw)),
		uintptr(unsafe.Pointer(nil)),
		uintptr(_LOGON_SERVICE),
		uintptr(_PROVIDER_DEFAULT),
		uintptr(unsafe.Pointer(&token)),
	)
	if ret == 0 {
		return nil, e
	}

	return &token, nil
Repository: hashicorp/nomad
File: drivers/shared/executor/executor_windows.go (Go)

Code before:

	if cmd.SysProcAttr == nil {
		cmd.SysProcAttr = &syscall.SysProcAttr{}
	}
	cmd.SysProcAttr.Token = *token
	return nil
}

var (
	advapiDll      = windows.NewLazySystemDLL("advapi32.dll")
	procLogonUserW = advapiDll.NewProc("LogonUserW")
)

const (
	_LOGON_SERVICE    uint32 = 5
	_PROVIDER_DEFAULT uint32 = 0
)

func createUserToken(username, domain string) (*syscall.Token, error) {
	userw, err := syscall.UTF16PtrFromString(username)
	if err != nil {
		return nil, fmt.Errorf("failed to convert username to UTF-16: %v", err)
	}
	domainw, err := syscall.UTF16PtrFromString(domain)
	if err != nil {
		return nil, fmt.Errorf("failed to convert user domain to UTF-16: %v", err)
	}
	var token syscall.Token
	ret, _, e := procLogonUserW.Call(
		uintptr(unsafe.Pointer(userw)),
		uintptr(unsafe.Pointer(domainw)),
		uintptr(unsafe.Pointer(nil)),
		uintptr(_LOGON_SERVICE),
		uintptr(_PROVIDER_DEFAULT),
		uintptr(unsafe.Pointer(&token)),
	)
	if ret == 0 {
		return nil, e
	}

	return &token, nil
}

func (e *UniversalExecutor) ListProcesses() set.Collection[int] {
	return procstats.ListByPid(e.childCmd.Process.Pid)
}

func (e *UniversalExecutor) setSubCmdCgroup(*exec.Cmd, string) (func(), error) {
	return func() {}, nil
}


Review comment (bug):
```suggestion
		return nil, fmt.Errorf("failed to convert user domain to UTF-16: %w", err)
```

Code after:
	}

	if cmd.SysProcAttr == nil {
		cmd.SysProcAttr = &syscall.SysProcAttr{}
	}
	cmd.SysProcAttr.Token = *token

	runtime.AddCleanup(cmd, func(attr *syscall.SysProcAttr) {
		_ = attr.Token.Close()
	}, cmd.SysProcAttr)

	return nil
}

var (
	advapiDll      = windows.NewLazySystemDLL("advapi32.dll")
	procLogonUserW = advapiDll.NewProc("LogonUserW")
)

const (
	_LOGON_SERVICE    uint32 = 5
	_PROVIDER_DEFAULT uint32 = 0
)

func createUserToken(domain, username string) (*syscall.Token, error) {
	userw, err := syscall.UTF16PtrFromString(username)
	if err != nil {
		return nil, fmt.Errorf("failed to convert username to UTF-16: %w", err)
	}
	domainw, err := syscall.UTF16PtrFromString(domain)
	if err != nil {
		return nil, fmt.Errorf("failed to convert user domain to UTF-16: %w", err)
	}
	var token syscall.Token
	ret, _, e := procLogonUserW.Call(
		uintptr(unsafe.Pointer(userw)),
		uintptr(unsafe.Pointer(domainw)),
		uintptr(unsafe.Pointer(nil)),
		uintptr(_LOGON_SERVICE),
		uintptr(_PROVIDER_DEFAULT),
		uintptr(unsafe.Pointer(&token)),
	)
	if ret == 0 {
		return nil, e
	}

	return &token, nil
}

func (e *UniversalExecutor) ListProcesses() set.Collection[int] {
	return procstats.ListByPid(e.childCmd.Process.Pid)
Repository: hashicorp/nomad
File: drivers/shared/executor/executor_windows.go (Go)

Code before:
	logger.Error("isolation executor is not supported on this platform, using default")
	return NewExecutor(logger, compute)
}

func (e *UniversalExecutor) configureResourceContainer(_ *ExecCommand, _ int) (func() error, func(), error) {
	cleanup := func() {}
	running := func() error { return nil }
	return running, cleanup, nil
}

func (e *UniversalExecutor) start(command *ExecCommand) error {
	return e.childCmd.Start()
}

func withNetworkIsolation(f func() error, _ *drivers.NetworkIsolationSpec) error {
	return f()
}

func setCmdUser(cmd *exec.Cmd, user string) error {
	nameParts := strings.Split(user, "\\")
	if len(nameParts) != 2 {
		return errors.New("user name must contain domain")
	}
	token, err := createUserToken(nameParts[1], nameParts[0])
	if err != nil {
		return fmt.Errorf("failed to create user token: %v", err)
	}

	if cmd.SysProcAttr == nil {
		cmd.SysProcAttr = &syscall.SysProcAttr{}
	}
	cmd.SysProcAttr.Token = *token
	return nil
}

var (
	advapiDll      = windows.NewLazySystemDLL("advapi32.dll")
	procLogonUserW = advapiDll.NewProc("LogonUserW")
)

const (
	_LOGON_SERVICE    uint32 = 5
	_PROVIDER_DEFAULT uint32 = 0
)

func createUserToken(username, domain string) (*syscall.Token, error) {
	userw, err := syscall.UTF16PtrFromString(username)
	if err != nil {
		return nil, fmt.Errorf("failed to convert username to UTF-16: %v", err)
	}
	domainw, err := syscall.UTF16PtrFromString(domain)

Review comment (bug):
```suggestion
		return fmt.Errorf("failed to create user token: %w", err)
```

Code after:
	logger = logger.Named("executor")
	logger.Error("isolation executor is not supported on this platform, using default")
	return NewExecutor(logger, compute)
}

func (e *UniversalExecutor) configureResourceContainer(_ *ExecCommand, _ int) (func() error, func(), error) {
	cleanup := func() {}
	running := func() error { return nil }
	return running, cleanup, nil
}

func (e *UniversalExecutor) start(command *ExecCommand) error {
	return e.childCmd.Start()
}

func withNetworkIsolation(f func() error, _ *drivers.NetworkIsolationSpec) error {
	return f()
}

func setCmdUser(cmd *exec.Cmd, user string) error {
	nameParts := strings.Split(user, "\\")
	if len(nameParts) != 2 {
		return errors.New("user name must contain domain")
	}
	token, err := createUserToken(nameParts[0], nameParts[1])
	if err != nil {
		return fmt.Errorf("failed to create user token: %w", err)
	}

	if cmd.SysProcAttr == nil {
		cmd.SysProcAttr = &syscall.SysProcAttr{}
	}
	cmd.SysProcAttr.Token = *token

	runtime.AddCleanup(cmd, func(attr *syscall.SysProcAttr) {
		_ = attr.Token.Close()
	}, cmd.SysProcAttr)

	return nil
}

var (
	advapiDll      = windows.NewLazySystemDLL("advapi32.dll")
	procLogonUserW = advapiDll.NewProc("LogonUserW")
)

const (
	_LOGON_SERVICE    uint32 = 5
	_PROVIDER_DEFAULT uint32 = 0
)
Repository: hashicorp/nomad
File: drivers/rawexec/driver_test.go (Go)

Code before:
			envList := d.buildEnvList(tc.taskConfig, tc.driverTaskConfig)
			deniedList := strings.Join(slices.Concat(tc.taskConfig.DeniedEnvvars, tc.driverConfig.DeniedEnvvars), ", ")

			for _, v := range envList {
				key, _, found := strings.Cut(v, "=")
				if !found {
					t.Fatalf("Unable to parse environment variable list, cannot evaluate")
				}
				keyGlob := "*" + key + "*"
				if glob.Glob(keyGlob, deniedList) {
					present = true
					foundVars = append(foundVars, key)
				}
			}

			if present != tc.deniedPresent {
				t.Fatalf("Expected deniedPresent to be %t, got %t, list= %#v", tc.deniedPresent, present, foundVars)
			}
		})
	}
}

func TestRawExecDriver_Env(t *testing.T) {
	ci.Parallel(t)

	require := require.New(t)

	d := newEnabledRawExecDriver(t)
	allocID := uuid.Generate()
	taskName := "sleep"

	testCases := []struct {
		name         string
		driver       *Driver
		driverConfig *Config
		taskConfig   *TaskConfig
		varsExpected bool
		checkVars    []string
	}{
		{name: "no denied vars",
			driver:       d,
			driverConfig: nil,
			taskConfig: &TaskConfig{
				Command: testtask.Path(),
			},
			checkVars:    []string{"NOMAD_TOKEN", "GITHUB_TOKEN", "AWS_SECRET_KEY", "NOMAD_ADDR", "TEST_TOKEN", "TEST_AWS_VAR", "VAR_TEST_AWS", "PORT"},
			varsExpected: true,
		},
		{name: "both levels, named vars",
			driver: d,
			driverConfig: &Config{

Review comment (suggestion):
Nomad uses https://pkg.go.dev/github.com/shoenig/test over testify, although you'll find there's still quite a few older tests using it that we've never got around to converting. We try to convert older tests as we touch them. `shoenig/test` uses generics to fix some meaningful equality checking gotchas in testify, and improves ergonomics over testify in a non-backwards-compatible way (ex. making sure the expectation is in a consistent order in the arguments list).

Code after:
				"NOMAD_ADDR=klm",
				"NOMAD_TOKEN=abcd",
				"PORT=wxyz",
				"TEST_TOKEN=nop",
			},
		},
	}
	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			d := newEnabledRawExecDriver(t)
			d.config = tc.driverConfig
			envList := d.buildEnvList(tc.taskConfig, tc.driverTaskConfig)
			must.SliceEqOp(t, envList, tc.expectedVars)
		})
	}
}

func TestRawExecDriver_Env(t *testing.T) {
	ci.Parallel(t)
	ctestutil.RequireNotWindows(t)

	d := newEnabledRawExecDriver(t)
	allocID := uuid.Generate()
	taskName := "sleep"

	task :=
		&drivers.TaskConfig{
			AllocID:   allocID,
			ID:        uuid.Generate(),
			Name:      taskName,
			Env:       genEnv(),
			Resources: testResources(allocID, taskName),
		}
	testCases := []struct {
		name         string
		driver       *Driver
		driverConfig *Config
		taskConfig   *TaskConfig
		varsExpected bool
		deniedVars   []string
	}{
		{name: "no denied vars",
			driver:       d,
			driverConfig: nil,
			taskConfig: &TaskConfig{
				Command: testtask.Path(),
				Args:    []string{"sleep", "10ms"},
			},
			deniedVars:   []string{},
			varsExpected: true,
		},
Repository: hashicorp/nomad
File: drivers/rawexec/driver_test.go (Go)

Code before:
	}
	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			present := false
			foundVars := []string{}

			d := newEnabledRawExecDriver(t)
			d.config = tc.driverConfig
			envList := d.buildEnvList(tc.taskConfig, tc.driverTaskConfig)
			deniedList := strings.Join(slices.Concat(tc.taskConfig.DeniedEnvvars, tc.driverConfig.DeniedEnvvars), ", ")

			for _, v := range envList {
				key, _, found := strings.Cut(v, "=")
				if !found {
					t.Fatalf("Unable to parse environment variable list, cannot evaluate")
				}
				keyGlob := "*" + key + "*"
				if glob.Glob(keyGlob, deniedList) {
					present = true
					foundVars = append(foundVars, key)
				}
			}

			if present != tc.deniedPresent {
				t.Fatalf("Expected deniedPresent to be %t, got %t, list= %#v", tc.deniedPresent, present, foundVars)
			}
		})
	}
}

func TestRawExecDriver_Env(t *testing.T) {
	ci.Parallel(t)

	require := require.New(t)

	d := newEnabledRawExecDriver(t)
	allocID := uuid.Generate()
	taskName := "sleep"

	testCases := []struct {
		name         string
		driver       *Driver
		driverConfig *Config
		taskConfig   *TaskConfig
		varsExpected bool
		checkVars    []string
	}{
		{name: "no denied vars",
			driver:       d,
			driverConfig: nil,
			taskConfig: &TaskConfig{

Review comment (refactor):
The input of `buildEnvList` is known statically and the output is sorted. We can probably simplify this test a lot by having the test case provide an exact list of strings we expect. Ex. something like

```go
expect: []string{
	"NOMAD_ADDR=klm",
	"PORT=wxyz",
},
```

And then use [`test.SliceEqual`](https://pkg.go.dev/github.com/shoenig/test#SliceEqual) to compare the two slices exactly without having to parse the strings out or write any of that code yourself. We may be able to do the same for the other test below, or use `test.SliceContains`/`test.SliceNotContains` instead if there's too much extra stuff in the environment on those tests.

Code after:
			driverTaskConfig: &drivers.TaskConfig{
				Env: defaultEnvironment,
			},
			driverConfig: &Config{
				DeniedEnvvars: []string{"*AWS*"},
			},
			expectedVars: []string{
				"GITHUB_TOKEN=efg",
				"NOMAD_ADDR=klm",
				"NOMAD_TOKEN=abcd",
				"PORT=wxyz",
				"TEST_TOKEN=nop",
			},
		},
	}
	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			d := newEnabledRawExecDriver(t)
			d.config = tc.driverConfig
			envList := d.buildEnvList(tc.taskConfig, tc.driverTaskConfig)
			must.SliceEqOp(t, envList, tc.expectedVars)
		})
	}
}

func TestRawExecDriver_Env(t *testing.T) {
	ci.Parallel(t)
	ctestutil.RequireNotWindows(t)

	d := newEnabledRawExecDriver(t)
	allocID := uuid.Generate()
	taskName := "sleep"

	task :=
		&drivers.TaskConfig{
			AllocID:   allocID,
			ID:        uuid.Generate(),
			Name:      taskName,
			Env:       genEnv(),
			Resources: testResources(allocID, taskName),
		}
	testCases := []struct {
		name         string
		driver       *Driver
		driverConfig *Config
		taskConfig   *TaskConfig
		varsExpected bool
		deniedVars   []string
	}{
		{name: "no denied vars",
			driver:       d,