From 064a543ff0ed414bf3c99d7898a54c4ec5fc5978 Mon Sep 17 00:00:00 2001 From: Ilia Dmitriev Date: Mon, 22 Jun 2026 22:20:06 +0300 Subject: [PATCH] fix: resolve golangci-lint violations failing CI Switch CreateTarFromDirWithExcludes to root-scoped os.Root I/O to address gosec G122 (symlink TOCTOU), and extract repeated string literals into constants to satisfy goconst. --- config/config.go | 31 +++++--- config/config_test.go | 58 +++++++-------- integration_test.go | 32 ++++----- sandbox/consts_test.go | 22 ++++++ sandbox/docker.go | 12 ++-- sandbox/executor_exclude_integration_test.go | 74 ++++++++++---------- sandbox/executor_test.go | 12 ++-- sandbox/interface.go | 19 ++++- sandbox/interface_test.go | 36 +++++----- sandbox/podman.go | 8 +-- sandbox/should_exclude_file_test.go | 46 ++++++------ sandbox/tar_excludes_test.go | 28 ++++---- 12 files changed, 212 insertions(+), 166 deletions(-) create mode 100644 sandbox/consts_test.go diff --git a/config/config.go b/config/config.go index b178b6d..5b88d7d 100644 --- a/config/config.go +++ b/config/config.go @@ -21,6 +21,17 @@ const ( DefaultMaxArtifactSize = 20 ) +// Configuration value constants. +const ( + TransportHTTP = "http" + TransportStdio = "stdio" + BackendDocker = "docker" + BackendLocal = "local" + LogModeProduction = "production" + LogModeDevelopment = "development" + LogLevelInfo = "info" +) + // Config represents the application configuration. type Config struct { Server ServerConfig `mapstructure:"server"` @@ -104,11 +115,11 @@ func New() (*Config, error) { // setDefaults sets the default configuration values. func setDefaults(v *viper.Viper) { // Server defaults - v.SetDefault("server.transport", "stdio") + v.SetDefault("server.transport", TransportStdio) v.SetDefault("server.http_port", DefaultHTTPPort) // Sandbox defaults - v.SetDefault("sandbox.backend", "docker") + v.SetDefault("sandbox.backend", BackendDocker) v.SetDefault("sandbox.timeout_sec", DefaultTimeoutSec) v.SetDefault("sandbox.memory_mb", DefaultMemoryMB) v.SetDefault("sandbox.max_artifact_size_mb", DefaultMaxArtifactSize) @@ -116,8 +127,8 @@ func setDefaults(v *viper.Viper) { v.SetDefault("sandbox.enable_local_backend", false) // Logging defaults - v.SetDefault("logging.mode", "production") - v.SetDefault("logging.level", "info") + v.SetDefault("logging.mode", LogModeProduction) + v.SetDefault("logging.level", LogLevelInfo) } // loadEnvironmentVariables loads environment variables from the config file preserving case @@ -168,7 +179,7 @@ func loadLanguageEnvironments(rawConfig map[string]any, config *Config) error { // validate ensures the configuration is valid. func (c *Config) validate() error { - if t := c.Server.Transport; t != "stdio" && t != "http" { + if t := c.Server.Transport; t != TransportStdio && t != TransportHTTP { return fmt.Errorf("invalid server.transport: %s, must be 'stdio' or 'http'", t) } @@ -185,19 +196,19 @@ func (c *Config) validate() error { } supportedBackends := map[string]bool{ - "docker": true, - "podman": true, - "local": c.Sandbox.EnableLocalBackend, + BackendDocker: true, + "podman": true, + BackendLocal: c.Sandbox.EnableLocalBackend, } if !supportedBackends[c.Sandbox.Backend] { return fmt.Errorf("unsupported sandbox.backend: %s", c.Sandbox.Backend) } - if m := c.Logging.Mode; m != "production" && m != "development" { + if m := c.Logging.Mode; m != LogModeProduction && m != LogModeDevelopment { return fmt.Errorf("invalid logging.mode: %s, must be 'production' or 'development'", m) } - logLevels := map[string]bool{"debug": true, "info": true, "warn": true, "error": true, "dpanic": true, "panic": true, "fatal": true} + logLevels := map[string]bool{"debug": true, LogLevelInfo: true, "warn": true, "error": true, "dpanic": true, "panic": true, "fatal": true} if !logLevels[c.Logging.Level] { return fmt.Errorf("invalid logging.level: %s", c.Logging.Level) } diff --git a/config/config_test.go b/config/config_test.go index cb1a7ee..dd8f764 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -12,11 +12,11 @@ func TestConfigValidation(t *testing.T) { // Test that a valid config does not fail validation cfg := &Config{ Server: ServerConfig{ - Transport: "http", + Transport: TransportHTTP, HTTPPort: 8080, }, Sandbox: SandboxConfig{ - Backend: "docker", + Backend: BackendDocker, TimeoutSec: 30, MemoryMB: 512, MaxArtifactSizeMB: 20, @@ -24,8 +24,8 @@ func TestConfigValidation(t *testing.T) { EnableLocalBackend: false, }, Logging: LoggingConfig{ - Mode: "production", - Level: "info", + Mode: LogModeProduction, + Level: LogLevelInfo, }, Languages: map[string]Language{ "python": { @@ -45,7 +45,7 @@ func TestConfigValidation(t *testing.T) { HTTPPort: 8080, }, Sandbox: SandboxConfig{ - Backend: "docker", + Backend: BackendDocker, TimeoutSec: 30, MemoryMB: 512, MaxArtifactSizeMB: 20, @@ -53,8 +53,8 @@ func TestConfigValidation(t *testing.T) { EnableLocalBackend: false, }, Logging: LoggingConfig{ - Mode: "production", - Level: "info", + Mode: LogModeProduction, + Level: LogLevelInfo, }, } @@ -66,11 +66,11 @@ func TestConfigValidation(t *testing.T) { t.Run("InvalidSandboxTimeout", func(t *testing.T) { cfg := &Config{ Server: ServerConfig{ - Transport: "http", + Transport: TransportHTTP, HTTPPort: 8080, }, Sandbox: SandboxConfig{ - Backend: "docker", + Backend: BackendDocker, TimeoutSec: 0, // Invalid: must be positive MemoryMB: 512, MaxArtifactSizeMB: 20, @@ -78,8 +78,8 @@ func TestConfigValidation(t *testing.T) { EnableLocalBackend: false, }, Logging: LoggingConfig{ - Mode: "production", - Level: "info", + Mode: LogModeProduction, + Level: LogLevelInfo, }, } @@ -91,11 +91,11 @@ func TestConfigValidation(t *testing.T) { t.Run("InvalidSandboxMemory", func(t *testing.T) { cfg := &Config{ Server: ServerConfig{ - Transport: "http", + Transport: TransportHTTP, HTTPPort: 8080, }, Sandbox: SandboxConfig{ - Backend: "docker", + Backend: BackendDocker, TimeoutSec: 30, MemoryMB: 0, // Invalid: must be positive MaxArtifactSizeMB: 20, @@ -103,8 +103,8 @@ func TestConfigValidation(t *testing.T) { EnableLocalBackend: false, }, Logging: LoggingConfig{ - Mode: "production", - Level: "info", + Mode: LogModeProduction, + Level: LogLevelInfo, }, } @@ -116,11 +116,11 @@ func TestConfigValidation(t *testing.T) { t.Run("InvalidLoggingMode", func(t *testing.T) { cfg := &Config{ Server: ServerConfig{ - Transport: "http", + Transport: TransportHTTP, HTTPPort: 8080, }, Sandbox: SandboxConfig{ - Backend: "docker", + Backend: BackendDocker, TimeoutSec: 30, MemoryMB: 512, MaxArtifactSizeMB: 20, @@ -129,7 +129,7 @@ func TestConfigValidation(t *testing.T) { }, Logging: LoggingConfig{ Mode: "invalid_mode", // Invalid mode - Level: "info", + Level: LogLevelInfo, }, } @@ -141,11 +141,11 @@ func TestConfigValidation(t *testing.T) { t.Run("InvalidLogLevel", func(t *testing.T) { cfg := &Config{ Server: ServerConfig{ - Transport: "http", + Transport: TransportHTTP, HTTPPort: 8080, }, Sandbox: SandboxConfig{ - Backend: "docker", + Backend: BackendDocker, TimeoutSec: 30, MemoryMB: 512, MaxArtifactSizeMB: 20, @@ -153,7 +153,7 @@ func TestConfigValidation(t *testing.T) { EnableLocalBackend: false, }, Logging: LoggingConfig{ - Mode: "production", + Mode: LogModeProduction, Level: "invalid_level", // Invalid level }, } @@ -166,11 +166,11 @@ func TestConfigValidation(t *testing.T) { t.Run("ValidBackendWhenLocalEnabled", func(t *testing.T) { cfg := &Config{ Server: ServerConfig{ - Transport: "http", + Transport: TransportHTTP, HTTPPort: 8080, }, Sandbox: SandboxConfig{ - Backend: "local", + Backend: BackendLocal, TimeoutSec: 30, MemoryMB: 512, MaxArtifactSizeMB: 20, @@ -178,8 +178,8 @@ func TestConfigValidation(t *testing.T) { EnableLocalBackend: true, // Local backend enabled }, Logging: LoggingConfig{ - Mode: "production", - Level: "info", + Mode: LogModeProduction, + Level: LogLevelInfo, }, } @@ -190,11 +190,11 @@ func TestConfigValidation(t *testing.T) { t.Run("InvalidBackendWhenLocalNotEnabled", func(t *testing.T) { cfg := &Config{ Server: ServerConfig{ - Transport: "http", + Transport: TransportHTTP, HTTPPort: 8080, }, Sandbox: SandboxConfig{ - Backend: "local", + Backend: BackendLocal, TimeoutSec: 30, MemoryMB: 512, MaxArtifactSizeMB: 20, @@ -202,8 +202,8 @@ func TestConfigValidation(t *testing.T) { EnableLocalBackend: false, // Local backend not enabled }, Logging: LoggingConfig{ - Mode: "production", - Level: "info", + Mode: LogModeProduction, + Level: LogLevelInfo, }, } diff --git a/integration_test.go b/integration_test.go index a5abbcd..b51b465 100644 --- a/integration_test.go +++ b/integration_test.go @@ -19,7 +19,7 @@ func TestIntegrationConfigLoggerSandbox(t *testing.T) { // Test that config validation works properly with logger initialization cfg := &config.Config{ Server: config.ServerConfig{ - Transport: "stdio", + Transport: config.TransportStdio, HTTPPort: 8080, }, Sandbox: config.SandboxConfig{ @@ -31,7 +31,7 @@ func TestIntegrationConfigLoggerSandbox(t *testing.T) { EnableLocalBackend: false, }, Logging: config.LoggingConfig{ - Mode: "development", + Mode: config.LogModeDevelopment, Level: "debug", }, Languages: map[string]config.Language{}, @@ -50,23 +50,23 @@ func TestIntegrationConfigLoggerSandbox(t *testing.T) { t.Run("ConfigLoggerSandboxFactoryIntegration", func(t *testing.T) { cfg := &config.Config{ Server: config.ServerConfig{ - Transport: "stdio", + Transport: config.TransportStdio, HTTPPort: 8080, }, Sandbox: config.SandboxConfig{ - Backend: "local", // Use local backend for testing without Docker - TimeoutSec: 10, // Short timeout for tests - MemoryMB: 128, // Lower memory for faster tests + Backend: config.BackendLocal, // Use local backend for testing without Docker + TimeoutSec: 10, // Short timeout for tests + MemoryMB: 128, // Lower memory for faster tests MaxArtifactSizeMB: 5, NetworkEnabled: false, EnableLocalBackend: true, // Must be enabled for local backend }, Logging: config.LoggingConfig{ - Mode: "development", + Mode: config.LogModeDevelopment, Level: "info", }, Languages: map[string]config.Language{ - "python": { + sandbox.LanguagePython: { Image: "python:3.11-slim", Environment: map[string]string{"PYTHONPATH": "/workdir"}, }, @@ -91,11 +91,11 @@ func TestIntegrationConfigLoggerSandbox(t *testing.T) { t.Run("FullMCPIntegration", func(t *testing.T) { cfg := &config.Config{ Server: config.ServerConfig{ - Transport: "stdio", + Transport: config.TransportStdio, HTTPPort: 8080, }, Sandbox: config.SandboxConfig{ - Backend: "local", + Backend: config.BackendLocal, TimeoutSec: 5, MemoryMB: 128, MaxArtifactSizeMB: 5, @@ -103,11 +103,11 @@ func TestIntegrationConfigLoggerSandbox(t *testing.T) { EnableLocalBackend: true, }, Logging: config.LoggingConfig{ - Mode: "development", + Mode: config.LogModeDevelopment, Level: "info", }, Languages: map[string]config.Language{ - "python": { + sandbox.LanguagePython: { Environment: map[string]string{}, }, "nodejs": { @@ -151,7 +151,7 @@ func TestIntegrationSandboxExecution(t *testing.T) { t.Run("LocalExecutorCreation", func(t *testing.T) { cfg := &config.Config{ Sandbox: config.SandboxConfig{ - Backend: "local", + Backend: config.BackendLocal, TimeoutSec: 5, MemoryMB: 128, MaxArtifactSizeMB: 5, @@ -159,7 +159,7 @@ func TestIntegrationSandboxExecution(t *testing.T) { EnableLocalBackend: true, }, Languages: map[string]config.Language{ - "python": { + sandbox.LanguagePython: { Environment: map[string]string{}, }, }, @@ -176,7 +176,7 @@ func TestIntegrationSandboxExecution(t *testing.T) { t.Run("ExecutorWithDifferentLanguages", func(t *testing.T) { cfg := &config.Config{ Sandbox: config.SandboxConfig{ - Backend: "local", + Backend: config.BackendLocal, TimeoutSec: 5, MemoryMB: 128, MaxArtifactSizeMB: 5, @@ -184,7 +184,7 @@ func TestIntegrationSandboxExecution(t *testing.T) { EnableLocalBackend: true, }, Languages: map[string]config.Language{ - "python": { + sandbox.LanguagePython: { Environment: map[string]string{}, }, "nodejs": { diff --git a/sandbox/consts_test.go b/sandbox/consts_test.go new file mode 100644 index 0000000..6ddfb39 --- /dev/null +++ b/sandbox/consts_test.go @@ -0,0 +1,22 @@ +package sandbox + +// Shared string constants used across the sandbox test suite. They exist to +// keep repeated literals in table-driven tests in a single place. +const ( + testFilePy = "test.py" + testFileMainJS = "main.js" + testFileGitConfig = ".git/config" + testFileNodePkg = "node_modules/package.json" + testFileApp = "app" + testPatternPy = "*.py" + testPatternPyc = "*.pyc" + testPatternPyo = "*.pyo" + testPatternObj = "*.o" + testDirNodeModules = "node_modules/" + testDirGit = ".git/" + testDirPycache = "__pycache__/" + testDirBuild = "build/" + testDirDist = "dist/" + testDirPytestCache = ".pytest_cache/" + testEnvPythonPath = "PYTHONPATH" +) diff --git a/sandbox/docker.go b/sandbox/docker.go index 9f931ae..f11376c 100644 --- a/sandbox/docker.go +++ b/sandbox/docker.go @@ -121,12 +121,12 @@ func (d *DockerExecutor) Execute(ctx context.Context, req ExecuteRequest) (Execu "docker", "run", "--name", containerName, "--rm", // Remove container after execution - "-v", fmt.Sprintf("%s:/workdir", workdirPath), - "--workdir", "/workdir", + "-v", fmt.Sprintf("%s:%s", workdirPath, WorkDirPath), + "--workdir", WorkDirPath, "--memory", fmt.Sprintf("%dm", d.config.MemoryMB), "--network", "none", // Disable network by default - "--ulimit", "fsize=100000000", // Limit file size to 100MB - "--ulimit", "cpu=10", // Limit CPU time (10 seconds) + FlagUlimit, "fsize=100000000", // Limit file size to 100MB + FlagUlimit, "cpu=10", // Limit CPU time (10 seconds) "--security-opt", "no-new-privileges:true", "--user", "nobody", // Run as non-privileged user "--cap-drop", "ALL", // Drop all capabilities @@ -234,9 +234,9 @@ func (d *DockerExecutor) getLanguageImage(language string) string { // Fallback to defaults if not in config switch language { - case "python": + case LanguagePython: return "python:3.11-slim" - case "nodejs": + case LanguageNodeJS: return "node:20-alpine" case LanguageGo: return "golang:1.23-alpine" diff --git a/sandbox/executor_exclude_integration_test.go b/sandbox/executor_exclude_integration_test.go index 0966351..b05888c 100644 --- a/sandbox/executor_exclude_integration_test.go +++ b/sandbox/executor_exclude_integration_test.go @@ -21,11 +21,11 @@ func TestExecutorExcludePatternsIntegration(t *testing.T) { // Create files that should be excluded (based on defaults) filesToCreate := map[string]string{ - "main.py": "print('hello world')", + FilenamePython: "print('hello world')", "__pycache__/main.cpython-39.pyc": "cache data", - "test.py": "import unittest", + testFilePy: "import unittest", "cache_file.pyc": "another cache", - "node_modules/package.json": "node module", + testFileNodePkg: "node module", "src/nested/__pycache__/file.pyc": "nested cache", ".pytest_cache/v/cache.py": "pytest cache", "build/output.so": "built output", @@ -55,9 +55,9 @@ func TestExecutorExcludePatternsIntegration(t *testing.T) { // Create a mock config for testing mockConfig := &config.Config{ Languages: map[string]config.Language{ - "python": { - Environment: map[string]string{"PYTHONPATH": "/workdir"}, - ExcludePatterns: []string{"__pycache__/", "*.pyc", "*.pyo", ".pytest_cache/", "node_modules/", "build/", "dist/"}, + LanguagePython: { + Environment: map[string]string{testEnvPythonPath: WorkDirPath}, + ExcludePatterns: []string{testDirPycache, testPatternPyc, testPatternPyo, testDirPytestCache, testDirNodeModules, testDirBuild, testDirDist}, }, }, } @@ -83,9 +83,9 @@ func TestExecutorExcludePatternsIntegration(t *testing.T) { // Create a mock config for testing mockConfig := &config.Config{ Languages: map[string]config.Language{ - "python": { - Environment: map[string]string{"PYTHONPATH": "/workdir"}, - ExcludePatterns: []string{"__pycache__/", "*.pyc", "*.pyo", ".pytest_cache/", "node_modules/", "build/", "dist/"}, + LanguagePython: { + Environment: map[string]string{testEnvPythonPath: WorkDirPath}, + ExcludePatterns: []string{testDirPycache, testPatternPyc, testPatternPyo, testDirPytestCache, testDirNodeModules, testDirBuild, testDirDist}, }, }, } @@ -111,9 +111,9 @@ func TestExecutorExcludePatternsIntegration(t *testing.T) { // Create a mock config for testing mockConfig := &config.Config{ Languages: map[string]config.Language{ - "python": { - Environment: map[string]string{"PYTHONPATH": "/workdir"}, - ExcludePatterns: []string{"__pycache__/", "*.pyc", "*.pyo", ".pytest_cache/", "node_modules/", "build/", "dist/"}, + LanguagePython: { + Environment: map[string]string{testEnvPythonPath: WorkDirPath}, + ExcludePatterns: []string{testDirPycache, testPatternPyc, testPatternPyo, testDirPytestCache, testDirNodeModules, testDirBuild, testDirDist}, }, }, } @@ -147,21 +147,21 @@ func TestFactoryWithExcludePatternsIntegration(t *testing.T) { t.Run("Factory-style creation with exclude patterns", func(t *testing.T) { mockConfig := &config.Config{ Languages: map[string]config.Language{ - "python": { - Environment: map[string]string{"PYTHONPATH": "/workdir"}, - ExcludePatterns: []string{"__pycache__/", "*.pyc", "main.py"}, // exclude source + LanguagePython: { + Environment: map[string]string{testEnvPythonPath: WorkDirPath}, + ExcludePatterns: []string{testDirPycache, testPatternPyc, FilenamePython}, // exclude source }, - "nodejs": { - Environment: map[string]string{"NODE_PATH": "/workdir"}, - ExcludePatterns: []string{"node_modules/", "index.js"}, // exclude source + LanguageNodeJS: { + Environment: map[string]string{"NODE_PATH": WorkDirPath}, + ExcludePatterns: []string{testDirNodeModules, FilenameNodeJS}, // exclude source }, - "go": { + LanguageGo: { Environment: map[string]string{"GOCACHE": "/tmp/go-build"}, - ExcludePatterns: []string{"main.go", "app"}, // exclude source and binary + ExcludePatterns: []string{FilenameGo, testFileApp}, // exclude source and binary }, - "cpp": { + LanguageCPP: { Environment: map[string]string{"LANG": "C.UTF-8"}, - ExcludePatterns: []string{"main.cpp", "app"}, // exclude source and binary + ExcludePatterns: []string{FilenameCPP, testFileApp}, // exclude source and binary }, }, } @@ -195,10 +195,10 @@ func TestFactoryWithExcludePatternsIntegration(t *testing.T) { // TestExecutorWithVariousLanguagesExcludePatterns tests exclude patterns for different languages func TestExecutorWithVariousLanguagesExcludePatterns(t *testing.T) { t.Run("Python exclude patterns", func(t *testing.T) { - pythonExcludePatterns := []string{"__pycache__/", "*.pyc", "*.pyo", "*.egg-info/", "main.py"} + pythonExcludePatterns := []string{testDirPycache, testPatternPyc, testPatternPyo, "*.egg-info/", FilenamePython} // Simulate the exclude pattern matching logic - shouldExcludeMainPy := shouldExcludeFile("main.py", pythonExcludePatterns) + shouldExcludeMainPy := shouldExcludeFile(FilenamePython, pythonExcludePatterns) assert.True(t, shouldExcludeMainPy) shouldExcludeCache := shouldExcludeFile("__pycache__/file.pyc", pythonExcludePatterns) @@ -209,9 +209,9 @@ func TestExecutorWithVariousLanguagesExcludePatterns(t *testing.T) { }) t.Run("NodeJS exclude patterns", func(t *testing.T) { - nodejsExcludePatterns := []string{"node_modules/", "*.js.map", "npm-debug.log*", "index.js"} + nodejsExcludePatterns := []string{testDirNodeModules, "*.js.map", "npm-debug.log*", FilenameNodeJS} - shouldExcludeNodeModules := shouldExcludeFile("node_modules/package.json", nodejsExcludePatterns) + shouldExcludeNodeModules := shouldExcludeFile(testFileNodePkg, nodejsExcludePatterns) assert.True(t, shouldExcludeNodeModules) shouldExcludeSourceMap := shouldExcludeFile("app.js.map", nodejsExcludePatterns) @@ -222,15 +222,15 @@ func TestExecutorWithVariousLanguagesExcludePatterns(t *testing.T) { }) t.Run("Go exclude patterns", func(t *testing.T) { - goExcludePatterns := []string{"*.o", "*.a", "*.so", "main.go", "app", "go.sum", "go.mod"} + goExcludePatterns := []string{testPatternObj, "*.a", "*.so", FilenameGo, testFileApp, "go.sum", "go.mod"} shouldExcludeObject := shouldExcludeFile("util.o", goExcludePatterns) assert.True(t, shouldExcludeObject) - shouldExcludeBinary := shouldExcludeFile("app", goExcludePatterns) + shouldExcludeBinary := shouldExcludeFile(testFileApp, goExcludePatterns) assert.True(t, shouldExcludeBinary) - shouldExcludeSource := shouldExcludeFile("main.go", goExcludePatterns) + shouldExcludeSource := shouldExcludeFile(FilenameGo, goExcludePatterns) assert.True(t, shouldExcludeSource) shouldNotExcludeOther := shouldExcludeFile("config.yaml", goExcludePatterns) @@ -238,15 +238,15 @@ func TestExecutorWithVariousLanguagesExcludePatterns(t *testing.T) { }) t.Run("C++ exclude patterns", func(t *testing.T) { - cppExcludePatterns := []string{"*.o", "*.a", "*.so", "*.dll", "*.exe", "main.cpp", "app", "a.out", "a.exe"} + cppExcludePatterns := []string{testPatternObj, "*.a", "*.so", "*.dll", "*.exe", FilenameCPP, testFileApp, "a.out", "a.exe"} shouldExcludeObj := shouldExcludeFile("util.o", cppExcludePatterns) assert.True(t, shouldExcludeObj) - shouldExcludeSource := shouldExcludeFile("main.cpp", cppExcludePatterns) + shouldExcludeSource := shouldExcludeFile(FilenameCPP, cppExcludePatterns) assert.True(t, shouldExcludeSource) - shouldExcludeBinary := shouldExcludeFile("app", cppExcludePatterns) + shouldExcludeBinary := shouldExcludeFile(testFileApp, cppExcludePatterns) assert.True(t, shouldExcludeBinary) shouldNotExcludeHeader := shouldExcludeFile("header.h", cppExcludePatterns) @@ -269,9 +269,9 @@ func TestExecutorExecuteWithExcludes(t *testing.T) { // Create a mock config for testing mockConfig := &config.Config{ Languages: map[string]config.Language{ - "python": { - Environment: map[string]string{"PYTHONPATH": "/workdir"}, - ExcludePatterns: []string{"__pycache__/", "*.pyc", "temp/*", "*.tmp", "main.py"}, + LanguagePython: { + Environment: map[string]string{testEnvPythonPath: WorkDirPath}, + ExcludePatterns: []string{testDirPycache, testPatternPyc, "temp/*", "*.tmp", FilenamePython}, }, }, } @@ -286,11 +286,11 @@ func TestExecutorExecuteWithExcludes(t *testing.T) { assert.NotNil(t, executor) // Test individual pattern matching with the mock config values directly - pythonExcludePatterns := mockConfig.Languages["python"].ExcludePatterns + pythonExcludePatterns := mockConfig.Languages[LanguagePython].ExcludePatterns shouldExcludeCache := shouldExcludeFile("some/path/__pycache__/file.pyc", pythonExcludePatterns) assert.True(t, shouldExcludeCache) - shouldExcludeSource := shouldExcludeFile("main.py", pythonExcludePatterns) + shouldExcludeSource := shouldExcludeFile(FilenamePython, pythonExcludePatterns) assert.True(t, shouldExcludeSource) shouldNotExcludeOther := shouldExcludeFile("requirements.txt", pythonExcludePatterns) diff --git a/sandbox/executor_test.go b/sandbox/executor_test.go index 8be653c..975300b 100644 --- a/sandbox/executor_test.go +++ b/sandbox/executor_test.go @@ -112,8 +112,8 @@ func TestDockerExecutorConstructors(t *testing.T) { } mockConfig := &config.Config{ Languages: map[string]config.Language{ - "python": { - Environment: map[string]string{"PYTHONPATH": "/workdir"}, + LanguagePython: { + Environment: map[string]string{testEnvPythonPath: WorkDirPath}, }, }, } @@ -157,8 +157,8 @@ func TestPodmanExecutorConstructors(t *testing.T) { } mockConfig := &config.Config{ Languages: map[string]config.Language{ - "python": { - Environment: map[string]string{"PYTHONPATH": "/workdir"}, + LanguagePython: { + Environment: map[string]string{testEnvPythonPath: WorkDirPath}, }, }, } @@ -202,8 +202,8 @@ func TestLocalExecutorConstructors(t *testing.T) { } mockConfig := &config.Config{ Languages: map[string]config.Language{ - "python": { - Environment: map[string]string{"PYTHONPATH": "/workdir"}, + LanguagePython: { + Environment: map[string]string{testEnvPythonPath: WorkDirPath}, }, }, } diff --git a/sandbox/interface.go b/sandbox/interface.go index 1326981..3fb55d6 100644 --- a/sandbox/interface.go +++ b/sandbox/interface.go @@ -141,6 +141,13 @@ const ( FilenameCPP = "main.cpp" ) +// Container command constants +const ( + WorkDirPath = "/workdir" + FlagUlimit = "--ulimit" + DirNodeModules = "node_modules" +) + // GetCodeFileName returns the appropriate filename based on the language func GetCodeFileName(language string) (string, error) { switch language { @@ -251,7 +258,13 @@ func CreateTarFromDirWithExcludes(srcDir string, excludePatterns []string) ([]by gzipWriter := gzip.NewWriter(&buf) tarWriter := tar.NewWriter(gzipWriter) - err := filepath.Walk(srcDir, func(file string, fi os.FileInfo, err error) error { + root, err := os.OpenRoot(srcDir) + if err != nil { + return nil, err + } + defer root.Close() + + err = filepath.Walk(srcDir, func(file string, fi os.FileInfo, err error) error { if err != nil { return err } @@ -289,7 +302,7 @@ func CreateTarFromDirWithExcludes(srcDir string, excludePatterns []string) ([]by // If it's not a directory, write the file content if !fi.IsDir() { - data, err := os.Open(file) + data, err := root.Open(relPath) if err != nil { return err } @@ -360,7 +373,7 @@ func shouldExcludeFile(relPath string, excludePatterns []string) bool { func isCommonDirectoryName(name string) bool { // Common directory names that should not be matched by non-directory patterns commonDirNames := map[string]bool{ - "node_modules": true, + DirNodeModules: true, "__pycache__": true, ".git": true, ".svn": true, diff --git a/sandbox/interface_test.go b/sandbox/interface_test.go index 4629f3d..4586336 100644 --- a/sandbox/interface_test.go +++ b/sandbox/interface_test.go @@ -13,10 +13,10 @@ func TestGetCodeFileName(t *testing.T) { expected string hasError bool }{ - {"python", "main.py", false}, - {"nodejs", "index.js", false}, - {"go", "main.go", false}, - {"cpp", "main.cpp", false}, + {LanguagePython, FilenamePython, false}, + {LanguageNodeJS, FilenameNodeJS, false}, + {LanguageGo, FilenameGo, false}, + {LanguageCPP, FilenameCPP, false}, {"invalid", "", true}, } @@ -39,10 +39,10 @@ func TestGetRunCommand(t *testing.T) { expected string hasError bool }{ - {"python", "python main.py", false}, - {"nodejs", "node index.js", false}, - {"go", "go build -o app main.go && ./app", false}, - {"cpp", "g++ -std=c++17 -O2 -o app main.cpp && ./app", false}, + {LanguagePython, "python main.py", false}, + {LanguageNodeJS, "node index.js", false}, + {LanguageGo, "go build -o app main.go && ./app", false}, + {LanguageCPP, "g++ -std=c++17 -O2 -o app main.cpp && ./app", false}, {"invalid", "", true}, } @@ -62,25 +62,25 @@ func TestGetRunCommand(t *testing.T) { func TestApplyHooks(t *testing.T) { t.Run("PythonHooks", func(t *testing.T) { code := "print('hello')" - result := ApplyHooks("python", code, nil) // Second parameter ignored for backward compatibility - assert.Equal(t, code, result) // Since the function now returns code as-is for backward compatibility + result := ApplyHooks(LanguagePython, code, nil) // Second parameter ignored for backward compatibility + assert.Equal(t, code, result) // Since the function now returns code as-is for backward compatibility }) t.Run("NodeJSHooks", func(t *testing.T) { code := "console.log('hello')" - result := ApplyHooks("nodejs", code, nil) // Second parameter ignored for backward compatibility + result := ApplyHooks(LanguageNodeJS, code, nil) // Second parameter ignored for backward compatibility assert.Equal(t, code, result) }) t.Run("GoNoHooks", func(t *testing.T) { code := "package main\nfunc main() { println(\"hello\") }" - result := ApplyHooks("go", code, nil) // Second parameter ignored for backward compatibility + result := ApplyHooks(LanguageGo, code, nil) // Second parameter ignored for backward compatibility assert.Equal(t, code, result) }) t.Run("CppNoHooks", func(t *testing.T) { code := "#include \nint main() { std::cout << \"hello\"; }" - result := ApplyHooks("cpp", code, nil) // Second parameter ignored for backward compatibility + result := ApplyHooks(LanguageCPP, code, nil) // Second parameter ignored for backward compatibility assert.Equal(t, code, result) }) @@ -93,25 +93,25 @@ func TestApplyHooks(t *testing.T) { func TestGetEnvironmentVariables(t *testing.T) { t.Run("PythonEnv", func(t *testing.T) { - env, err := GetEnvironmentVariables(nil, "python") // First parameter ignored for backward compatibility + env, err := GetEnvironmentVariables(nil, LanguagePython) // First parameter ignored for backward compatibility require.NoError(t, err) assert.Equal(t, map[string]string{}, env) // Returns empty map for backward compatibility }) t.Run("NodeJSEnv", func(t *testing.T) { - env, err := GetEnvironmentVariables(nil, "nodejs") // First parameter ignored for backward compatibility + env, err := GetEnvironmentVariables(nil, LanguageNodeJS) // First parameter ignored for backward compatibility require.NoError(t, err) assert.Equal(t, map[string]string{}, env) }) t.Run("GoEnv", func(t *testing.T) { - env, err := GetEnvironmentVariables(nil, "go") // First parameter ignored for backward compatibility + env, err := GetEnvironmentVariables(nil, LanguageGo) // First parameter ignored for backward compatibility require.NoError(t, err) assert.Equal(t, map[string]string{}, env) }) t.Run("CppEnv", func(t *testing.T) { - env, err := GetEnvironmentVariables(nil, "cpp") // First parameter ignored for backward compatibility + env, err := GetEnvironmentVariables(nil, LanguageCPP) // First parameter ignored for backward compatibility require.NoError(t, err) assert.Equal(t, map[string]string{}, env) }) @@ -123,7 +123,7 @@ func TestGetEnvironmentVariables(t *testing.T) { }) t.Run("NilLangEnvs", func(t *testing.T) { - env, err := GetEnvironmentVariables(nil, "python") // First parameter ignored for backward compatibility + env, err := GetEnvironmentVariables(nil, LanguagePython) // First parameter ignored for backward compatibility require.NoError(t, err) assert.Equal(t, map[string]string{}, env) }) diff --git a/sandbox/podman.go b/sandbox/podman.go index 7a59382..629eb76 100644 --- a/sandbox/podman.go +++ b/sandbox/podman.go @@ -110,12 +110,12 @@ func (p *PodmanExecutor) Execute(ctx context.Context, req ExecuteRequest) (Execu "podman", "run", "--name", containerName, "--rm", // Remove container after execution - "-v", fmt.Sprintf("%s:/workdir", workdirPath), - "--workdir", "/workdir", + "-v", fmt.Sprintf("%s:%s", workdirPath, WorkDirPath), + "--workdir", WorkDirPath, "--memory", fmt.Sprintf("%dm", p.config.MemoryMB), "--network", "none", // Disable network by default - "--ulimit", "fsize=100000000", // Limit file size to 100MB - "--ulimit", "cpu=10", // Limit CPU time (10 seconds) + FlagUlimit, "fsize=100000000", // Limit file size to 100MB + FlagUlimit, "cpu=10", // Limit CPU time (10 seconds) "--security-opt", "no-new-privileges:true", "--user", "nobody", // Run as non-privileged user "--cap-drop", "ALL", // Drop all capabilities diff --git a/sandbox/should_exclude_file_test.go b/sandbox/should_exclude_file_test.go index 71f5fbc..d463e04 100644 --- a/sandbox/should_exclude_file_test.go +++ b/sandbox/should_exclude_file_test.go @@ -17,15 +17,15 @@ func TestShouldExcludeFile(t *testing.T) { excludePattern string shouldExclude bool }{ - {"exact file match", "main.py", "main.py", true}, - {"different file", "test.py", "main.py", false}, - {"wildcard extension", "script.py", "*.py", true}, - {"wildcard non-match", "script.js", "*.py", false}, - {"wildcard multiple chars", "main.pyc", "*.pyc", true}, + {"exact file match", FilenamePython, FilenamePython, true}, + {"different file", testFilePy, FilenamePython, false}, + {"wildcard extension", "script.py", testPatternPy, true}, + {"wildcard non-match", "script.js", testPatternPy, false}, + {"wildcard multiple chars", "main.pyc", testPatternPyc, true}, {"wildcard with prefix", "cache_main.py", "cache_*.py", true}, - {"wildcard no match", "main.js", "*.py", false}, - {"relative path", "src/main.py", "main.py", true}, - {"relative path wildcard", "src/cache/main.pyc", "*.pyc", true}, + {"wildcard no match", testFileMainJS, testPatternPy, false}, + {"relative path", "src/main.py", FilenamePython, true}, + {"relative path wildcard", "src/cache/main.pyc", testPatternPyc, true}, } for _, tc := range testCases { @@ -44,11 +44,11 @@ func TestShouldExcludeFile(t *testing.T) { excludePattern string shouldExclude bool }{ - {"directory pattern exact match", "node_modules/package.json", "node_modules/", true}, - {"directory pattern with subdir", "node_modules/deep/nested/file.js", "node_modules/", true}, - {"directory pattern no match", "src/main.js", "node_modules/", false}, - {"git directory", ".git/config", ".git/", true}, - {"git directory file", ".git/HEAD", ".git/", true}, + {"directory pattern exact match", testFileNodePkg, testDirNodeModules, true}, + {"directory pattern with subdir", "node_modules/deep/nested/file.js", testDirNodeModules, true}, + {"directory pattern no match", "src/main.js", testDirNodeModules, false}, + {"git directory", testFileGitConfig, testDirGit, true}, + {"git directory file", ".git/HEAD", testDirGit, true}, {"non-directory pattern on dir", "node_modules", "node_modules", false}, // without trailing slash, shouldn't match directory } @@ -62,7 +62,7 @@ func TestShouldExcludeFile(t *testing.T) { }) t.Run("handles multiple patterns", func(t *testing.T) { - excludePatterns := []string{"__pycache__/", "*.pyc", "node_modules/", ".git/"} + excludePatterns := []string{testDirPycache, testPatternPyc, testDirNodeModules, testDirGit} testCases := []struct { name string @@ -71,10 +71,10 @@ func TestShouldExcludeFile(t *testing.T) { }{ {"matches first pattern", "__pycache__/file.pyc", true}, {"matches second pattern", "cache.pyc", true}, - {"matches third pattern", "node_modules/package.json", true}, - {"matches fourth pattern", ".git/config", true}, - {"no match", "main.py", false}, - {"no match different extension", "main.js", false}, + {"matches third pattern", testFileNodePkg, true}, + {"matches fourth pattern", testFileGitConfig, true}, + {"no match", FilenamePython, false}, + {"no match different extension", testFileMainJS, false}, } for _, tc := range testCases { @@ -86,7 +86,7 @@ func TestShouldExcludeFile(t *testing.T) { }) t.Run("handles complex directory structures", func(t *testing.T) { - excludePatterns := []string{"build/", "node_modules/", "*.o", "dist/"} + excludePatterns := []string{testDirBuild, testDirNodeModules, testPatternObj, testDirDist} testCases := []struct { name string @@ -113,21 +113,21 @@ func TestShouldExcludeFile(t *testing.T) { t.Run("filepath.Match error handling", func(t *testing.T) { // Test with an invalid pattern - should not crash but return false invalidPatterns := []string{"[invalid-pattern"} - result := shouldExcludeFile("main.py", invalidPatterns) + result := shouldExcludeFile(FilenamePython, invalidPatterns) // If there's a pattern match error, it should return false (not exclude) assert.False(t, result) }) t.Run("path separators work across platforms", func(t *testing.T) { // Test that the pattern matching works with different path separators - excludePatterns := []string{"node_modules/"} + excludePatterns := []string{testDirNodeModules} testCases := []struct { name string relPath string shouldExclude bool }{ - {"forward slash", "node_modules/package.json", true}, + {"forward slash", testFileNodePkg, true}, {"nested with forward slashes", "frontend/node_modules/react.js", true}, } @@ -160,7 +160,7 @@ func TestFilePathMatchBehavior(t *testing.T) { }, { pattern: "main.*", - matches: []string{"main.py", "main.js", "main.go", "main.exe"}, + matches: []string{FilenamePython, testFileMainJS, FilenameGo, "main.exe"}, misses: []string{"test.main.py", "py.main"}, }, } diff --git a/sandbox/tar_excludes_test.go b/sandbox/tar_excludes_test.go index 0d22ef8..f257deb 100644 --- a/sandbox/tar_excludes_test.go +++ b/sandbox/tar_excludes_test.go @@ -19,11 +19,11 @@ func createTestDirectoryStructure(t *testing.T) string { // Create test files and directories files := map[string]string{ - "main.py": "print('hello')", + FilenamePython: "print('hello')", "__pycache__/main.cpython-39.pyc": "cache content", - "test.py": "test code", + testFilePy: "test code", "data.txt": "data content", - ".git/config": "git config", + testFileGitConfig: "git config", "node_modules/package/index.js": "module code", "build/output.o": "compiled object", "src/main.go": "go code", @@ -77,14 +77,14 @@ func testExcludePatternsCorrectly(t *testing.T) { tempDir := createTestDirectoryStructure(t) // Test excluding __pycache__, *.pyc, node_modules, etc. - excludePatterns := []string{"__pycache__/", "*.pyc", "node_modules/", "build/"} + excludePatterns := []string{testDirPycache, testPatternPyc, testDirNodeModules, testDirBuild} includedFiles := extractIncludedFiles(t, tempDir, excludePatterns) // Files that should be included (not excluded) - assert.Contains(t, includedFiles, "main.py") - assert.Contains(t, includedFiles, "test.py") + assert.Contains(t, includedFiles, FilenamePython) + assert.Contains(t, includedFiles, testFilePy) assert.Contains(t, includedFiles, "data.txt") - assert.Contains(t, includedFiles, ".git/config") + assert.Contains(t, includedFiles, testFileGitConfig) assert.Contains(t, includedFiles, "src/main.go") // Files that should be excluded @@ -110,11 +110,11 @@ func testNoExcludePatterns(t *testing.T) { includedFiles := extractIncludedFiles(t, tempDir, nil) // All files should be included when no exclude patterns are provided - assert.Contains(t, includedFiles, "main.py") + assert.Contains(t, includedFiles, FilenamePython) assert.Contains(t, includedFiles, "__pycache__/main.cpython-39.pyc") - assert.Contains(t, includedFiles, "test.py") + assert.Contains(t, includedFiles, testFilePy) assert.Contains(t, includedFiles, "data.txt") - assert.Contains(t, includedFiles, ".git/config") + assert.Contains(t, includedFiles, testFileGitConfig) assert.Contains(t, includedFiles, "node_modules/package/index.js") assert.Contains(t, includedFiles, "build/output.o") assert.Contains(t, includedFiles, "src/main.go") @@ -124,17 +124,17 @@ func testSpecificFileExtensionPattern(t *testing.T) { tempDir := createTestDirectoryStructure(t) // Exclude all .py files - excludePatterns := []string{"*.py"} + excludePatterns := []string{testPatternPy} includedFiles := extractIncludedFiles(t, tempDir, excludePatterns) // Python files should be excluded mainPyExcluded := true testPyExcluded := true for _, file := range includedFiles { - if file == "main.py" { + if file == FilenamePython { mainPyExcluded = false } - if file == "test.py" { + if file == testFilePy { testPyExcluded = false } } @@ -143,7 +143,7 @@ func testSpecificFileExtensionPattern(t *testing.T) { // Non-Python files should be included assert.Contains(t, includedFiles, "data.txt") - assert.Contains(t, includedFiles, ".git/config") + assert.Contains(t, includedFiles, testFileGitConfig) assert.Contains(t, includedFiles, "node_modules/package/index.js") assert.Contains(t, includedFiles, "build/output.o") assert.Contains(t, includedFiles, "src/main.go")