feat(runner): add the own code runner contract, client and nsjail service
This commit is contained in:
1 parent
5e1db37746
commit
cdf6bcbb91
109 files changed
+24084
-28
No files matched your search
@@ -0,0 +1,266 @@
|
||||
// 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"
|
||||
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
|
||||
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),
|
||||
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,
|
||||
} {
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const testToken = "test-token-0123456789abcdefghijklmnop"
|
||||
|
||||
func env(values map[string]string) lookupFunc {
|
||||
return func(name string) (string, bool) {
|
||||
value, ok := values[name]
|
||||
return value, ok
|
||||
}
|
||||
}
|
||||
|
||||
func noFiles(string) ([]byte, error) {
|
||||
return nil, fs.ErrNotExist
|
||||
}
|
||||
|
||||
func TestParseDefaultsWithTLS(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cfg, err := parse(env(map[string]string{
|
||||
"RUNNER_TLS_CERT_FILE": "/run/secrets/tls.crt",
|
||||
"RUNNER_TLS_KEY_FILE": "/run/secrets/tls.key",
|
||||
"RUNNER_API_TOKEN": testToken,
|
||||
}), noFiles)
|
||||
if err != nil {
|
||||
t.Fatalf("parse: %v", err)
|
||||
}
|
||||
if cfg.MaxConcurrentRuns != DefaultMaxConcurrentRuns || cfg.ResultTTL != DefaultResultTTL || cfg.AllowPlaintextHTTP {
|
||||
t.Fatalf("unexpected defaults: %+v", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRequiresTLSUnlessTheDevSwitchIsSet(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, err := parse(env(map[string]string{"RUNNER_API_TOKEN": testToken}), noFiles)
|
||||
if err == nil || !strings.Contains(err.Error(), "TLS is required") {
|
||||
t.Fatalf("parse without TLS = %v, want a TLS error", err)
|
||||
}
|
||||
cfg, err := parse(env(map[string]string{
|
||||
"RUNNER_API_TOKEN": testToken,
|
||||
"RUNNER_DEV_ALLOW_PLAINTEXT_HTTP": "true",
|
||||
}), noFiles)
|
||||
if err != nil || !cfg.AllowPlaintextHTTP {
|
||||
t.Fatalf("parse with the dev switch = %+v, %v", cfg, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseReadsTheTokenFileAndHidesTheValue(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
files := func(path string) ([]byte, error) {
|
||||
if path == "/run/secrets/token" {
|
||||
return []byte(testToken + "\n"), nil
|
||||
}
|
||||
return nil, fs.ErrNotExist
|
||||
}
|
||||
cfg, err := parse(env(map[string]string{
|
||||
"RUNNER_API_TOKEN_FILE": "/run/secrets/token",
|
||||
"RUNNER_DEV_ALLOW_PLAINTEXT_HTTP": "1",
|
||||
}), files)
|
||||
if err != nil || cfg.APIToken != testToken {
|
||||
t.Fatalf("parse token file = %q, %v", cfg.APIToken, err)
|
||||
}
|
||||
|
||||
short := "short-secret"
|
||||
_, err = parse(env(map[string]string{
|
||||
"RUNNER_API_TOKEN": short,
|
||||
"RUNNER_DEV_ALLOW_PLAINTEXT_HTTP": "1",
|
||||
}), noFiles)
|
||||
if err == nil || strings.Contains(err.Error(), short) {
|
||||
t.Fatalf("parse short token = %v, want an error without the value", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseReportsEveryInvalidValue(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, err := parse(env(map[string]string{
|
||||
"RUNNER_API_TOKEN": testToken,
|
||||
"RUNNER_DEV_ALLOW_PLAINTEXT_HTTP": "true",
|
||||
"RUNNER_MAX_CONCURRENT_RUNS": "many",
|
||||
"RUNNER_RESULT_TTL": "soon",
|
||||
"RUNNER_SANDBOX_UID": "0",
|
||||
"RUNNER_WORK_DIR": "relative/work",
|
||||
}), noFiles)
|
||||
if err == nil {
|
||||
t.Fatal("parse accepted invalid values")
|
||||
}
|
||||
for _, name := range []string{"RUNNER_MAX_CONCURRENT_RUNS", "RUNNER_RESULT_TTL", "RUNNER_SANDBOX_UID", "RUNNER_WORK_DIR"} {
|
||||
if !strings.Contains(err.Error(), name) {
|
||||
t.Errorf("error %q does not name %s", err, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRejectsConflictingTLSAndPlaintext(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, err := parse(env(map[string]string{
|
||||
"RUNNER_API_TOKEN": testToken,
|
||||
"RUNNER_DEV_ALLOW_PLAINTEXT_HTTP": "true",
|
||||
"RUNNER_TLS_CERT_FILE": "/tls.crt",
|
||||
"RUNNER_TLS_KEY_FILE": "/tls.key",
|
||||
"RUNNER_SHUTDOWN_TIMEOUT": time.Second.String(),
|
||||
}), noFiles)
|
||||
if err == nil || !strings.Contains(err.Error(), "conflicts") {
|
||||
t.Fatalf("parse = %v, want a conflict error", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user