// Package config reads the runner configuration from the environment. package config import ( "errors" "fmt" "log/slog" "os" "strconv" "strings" "time" ) // Defaults of the runner settings. const ( DefaultListenAddress = ":8443" DefaultMaxConcurrentRuns = 1 DefaultMaxRequestBytes = 8 << 20 DefaultResultTTL = 15 * time.Minute DefaultMaxRetainedRuns = 256 DefaultWorkDir = "/var/lib/lincodex-runner/work" DefaultCgroupRoot = "/sys/fs/cgroup" DefaultNsjailPath = "/usr/bin/nsjail" DefaultPythonPath = "/usr/local/bin/python3" DefaultGoToolDir = "/usr/local/lib/lincodex-runner/go" DefaultSandboxUID = 99999 DefaultMaxProcesses = 16 DefaultMemoryOverheadBytes = 4 << 20 DefaultTmpfsBytes = 16 << 20 DefaultFileSizeBytes = 8 << 20 DefaultOpenFiles = 64 DefaultShutdownTimeout = 30 * time.Second DefaultRetryAfter = 2 * time.Second // MinTokenLength is the shortest accepted service token. MinTokenLength = 32 ) // Config is the validated runner configuration. type Config struct { ListenAddress string TLSCertFile string TLSKeyFile string // AllowPlaintextHTTP serves HTTP without TLS. Only the local dev // Compose file sets it. AllowPlaintextHTTP bool APIToken string MaxConcurrentRuns int MaxRequestBytes int64 ResultTTL time.Duration MaxRetainedRuns int RetryAfter time.Duration ShutdownTimeout time.Duration WorkDir string CgroupRoot string NsjailPath string PythonPath string GoToolDir string SandboxUID int MaxProcesses int MemoryOverheadBytes int64 TmpfsBytes int64 FileSizeBytes int64 OpenFiles int LogLevel slog.Level } // Load reads the configuration from the process environment. func Load() (Config, error) { return parse(os.LookupEnv, os.ReadFile) } type ( lookupFunc func(string) (string, bool) readFileFunc func(string) ([]byte, error) ) func parse(lookup lookupFunc, readFile readFileFunc) (Config, error) { r := reader{lookup: lookup} cfg := Config{ ListenAddress: r.text("RUNNER_LISTEN_ADDRESS", DefaultListenAddress), TLSCertFile: r.text("RUNNER_TLS_CERT_FILE", ""), TLSKeyFile: r.text("RUNNER_TLS_KEY_FILE", ""), AllowPlaintextHTTP: r.boolean("RUNNER_DEV_ALLOW_PLAINTEXT_HTTP"), MaxConcurrentRuns: r.integer("RUNNER_MAX_CONCURRENT_RUNS", DefaultMaxConcurrentRuns), MaxRequestBytes: r.int64("RUNNER_MAX_REQUEST_BYTES", DefaultMaxRequestBytes), ResultTTL: r.duration("RUNNER_RESULT_TTL", DefaultResultTTL), MaxRetainedRuns: r.integer("RUNNER_MAX_RETAINED_RUNS", DefaultMaxRetainedRuns), RetryAfter: r.duration("RUNNER_RETRY_AFTER", DefaultRetryAfter), ShutdownTimeout: r.duration("RUNNER_SHUTDOWN_TIMEOUT", DefaultShutdownTimeout), WorkDir: r.text("RUNNER_WORK_DIR", DefaultWorkDir), CgroupRoot: r.text("RUNNER_CGROUP_ROOT", DefaultCgroupRoot), NsjailPath: r.text("RUNNER_NSJAIL_PATH", DefaultNsjailPath), PythonPath: r.text("RUNNER_PYTHON_PATH", DefaultPythonPath), GoToolDir: r.text("RUNNER_GO_TOOL_DIR", DefaultGoToolDir), SandboxUID: r.integer("RUNNER_SANDBOX_UID", DefaultSandboxUID), MaxProcesses: r.integer("RUNNER_SANDBOX_MAX_PROCESSES", DefaultMaxProcesses), MemoryOverheadBytes: r.int64("RUNNER_SANDBOX_MEMORY_OVERHEAD_BYTES", DefaultMemoryOverheadBytes), TmpfsBytes: r.int64("RUNNER_SANDBOX_TMPFS_BYTES", DefaultTmpfsBytes), FileSizeBytes: r.int64("RUNNER_SANDBOX_FILE_SIZE_BYTES", DefaultFileSizeBytes), OpenFiles: r.integer("RUNNER_SANDBOX_OPEN_FILES", DefaultOpenFiles), LogLevel: r.logLevel("RUNNER_LOG_LEVEL"), } cfg.APIToken = r.token(readFile) // Report parse and validation errors together, so one start names // every setting to fix. if err := errors.Join(append(r.errs, cfg.validate())...); err != nil { return Config{}, err } return cfg, nil } func (c Config) validate() error { return errors.Join(c.validateTransport(), c.validateLimits(), c.validatePaths()) } func (c Config) validateTransport() error { tlsSet := c.TLSCertFile != "" || c.TLSKeyFile != "" switch { case tlsSet && (c.TLSCertFile == "" || c.TLSKeyFile == ""): return errors.New("config.validate - RUNNER_TLS_CERT_FILE and RUNNER_TLS_KEY_FILE must be set together") case tlsSet && c.AllowPlaintextHTTP: return errors.New("config.validate - RUNNER_DEV_ALLOW_PLAINTEXT_HTTP conflicts with TLS settings") case !tlsSet && !c.AllowPlaintextHTTP: return errors.New("config.validate - TLS is required: set RUNNER_TLS_CERT_FILE and RUNNER_TLS_KEY_FILE") } return nil } func (c Config) validateLimits() error { var errs []error positive := map[string]int64{ "RUNNER_MAX_CONCURRENT_RUNS": int64(c.MaxConcurrentRuns), "RUNNER_MAX_REQUEST_BYTES": c.MaxRequestBytes, "RUNNER_MAX_RETAINED_RUNS": int64(c.MaxRetainedRuns), "RUNNER_SANDBOX_MAX_PROCESSES": int64(c.MaxProcesses), "RUNNER_SANDBOX_TMPFS_BYTES": c.TmpfsBytes, "RUNNER_SANDBOX_FILE_SIZE_BYTES": c.FileSizeBytes, "RUNNER_SANDBOX_OPEN_FILES": int64(c.OpenFiles), "RUNNER_RESULT_TTL": int64(c.ResultTTL), "RUNNER_RETRY_AFTER": int64(c.RetryAfter), "RUNNER_SHUTDOWN_TIMEOUT": int64(c.ShutdownTimeout), } for name, value := range positive { if value <= 0 { errs = append(errs, fmt.Errorf("config.validate - %s must be positive", name)) } } if c.MaxRetainedRuns < c.MaxConcurrentRuns { errs = append(errs, errors.New("config.validate - RUNNER_MAX_RETAINED_RUNS must not be below RUNNER_MAX_CONCURRENT_RUNS")) } if c.SandboxUID <= 0 { errs = append(errs, errors.New("config.validate - RUNNER_SANDBOX_UID must not be root")) } if c.MemoryOverheadBytes < 0 { errs = append(errs, errors.New("config.validate - RUNNER_SANDBOX_MEMORY_OVERHEAD_BYTES must not be negative")) } return errors.Join(errs...) } func (c Config) validatePaths() error { var errs []error for name, path := range map[string]string{ "RUNNER_WORK_DIR": c.WorkDir, "RUNNER_CGROUP_ROOT": c.CgroupRoot, "RUNNER_NSJAIL_PATH": c.NsjailPath, "RUNNER_PYTHON_PATH": c.PythonPath, "RUNNER_GO_TOOL_DIR": c.GoToolDir, } { if !strings.HasPrefix(path, "/") { errs = append(errs, fmt.Errorf("config.validate - %s must be an absolute path", name)) } } return errors.Join(errs...) } // reader collects parse errors so that one start reports every bad value. type reader struct { lookup lookupFunc errs []error } func (r *reader) text(name, fallback string) string { value, ok := r.lookup(name) if !ok || value == "" { return fallback } return value } func (r *reader) boolean(name string) bool { value, ok := r.lookup(name) if !ok || value == "" { return false } parsed, err := strconv.ParseBool(value) if err != nil { r.errs = append(r.errs, fmt.Errorf("config.reader.boolean - %s is not a boolean", name)) } return parsed } func (r *reader) integer(name string, fallback int) int { return int(r.int64(name, int64(fallback))) } func (r *reader) int64(name string, fallback int64) int64 { value, ok := r.lookup(name) if !ok || value == "" { return fallback } parsed, err := strconv.ParseInt(value, 10, 64) if err != nil { r.errs = append(r.errs, fmt.Errorf("config.reader.int64 - %s is not an integer", name)) } return parsed } func (r *reader) duration(name string, fallback time.Duration) time.Duration { value, ok := r.lookup(name) if !ok || value == "" { return fallback } parsed, err := time.ParseDuration(value) if err != nil { r.errs = append(r.errs, fmt.Errorf("config.reader.duration - %s is not a duration", name)) } return parsed } func (r *reader) logLevel(name string) slog.Level { value, ok := r.lookup(name) if !ok || value == "" { return slog.LevelInfo } var level slog.Level if err := level.UnmarshalText([]byte(value)); err != nil { r.errs = append(r.errs, fmt.Errorf("config.reader.logLevel - %s is not a log level", name)) } return level } // token reads the service token from RUNNER_API_TOKEN_FILE or, failing // that, RUNNER_API_TOKEN. The value never appears in an error. func (r *reader) token(readFile readFileFunc) string { file := r.text("RUNNER_API_TOKEN_FILE", "") direct := r.text("RUNNER_API_TOKEN", "") var token string switch { case file != "" && direct != "": r.errs = append(r.errs, errors.New("config.reader.token - set RUNNER_API_TOKEN_FILE or RUNNER_API_TOKEN, not both")) return "" case file != "": content, err := readFile(file) if err != nil { r.errs = append(r.errs, fmt.Errorf("config.reader.token - read RUNNER_API_TOKEN_FILE: %w", err)) return "" } token = strings.TrimSpace(string(content)) default: token = direct } if len(token) < MinTokenLength { r.errs = append(r.errs, fmt.Errorf("config.reader.token - the service token must have at least %d characters", MinTokenLength)) return "" } return token }