Files
lincodex/backend/config/code_runner.go
T

190 lines
7.7 KiB
Go

package config
import (
"encoding/pem"
"errors"
"fmt"
"log/slog"
"net/url"
"strings"
"time"
)
const (
defaultCodeRunnerRequestTimeout = 10 * time.Second
// One request submits or reads a run; the runner answers at once and runs
// asynchronously. A minute is far above any healthy answer and keeps a
// hung runner from holding a worker.
minCodeRunnerRequestTimeout = time.Second
maxCodeRunnerRequestTimeout = time.Minute
// The runner requires a token of at least 32 characters; the run key
// follows the same bound.
minCodeRunnerSecretLength = 32
maxCodeRunnerSecretLength = 256
redactedCodeRunnerSetting = "[redacted code runner settings]"
)
// CodeRunnerSettings configure the client of the own code runner (api/runner).
// The runner is off unless CODE_RUNNER_URL is set: there is no default URL,
// because untrusted code must only ever go to a host the operator named.
//
// String, GoString, Format, and LogValue redact everything, because the
// token, the run key, and the CA are secrets of the deployment.
type CodeRunnerSettings struct {
// URL is the runner origin, for example https://10.80.0.2:8443. Only https
// is accepted; empty means the runner is disabled.
URL string
// Token is the shared service token (Authorization: Bearer).
Token string
// RunKey keys the HMAC that derives opaque run IDs from submissions, so
// the runner never sees attempt or submission identifiers. It is a secret
// that differs from Token.
RunKey string
// CAFile is the path of the PEM file with the CA that signed the runner
// certificate. Exactly one of CAFile and CAPEM is set when enabled.
CAFile string
// CAPEM is the same CA as inline PEM text, for deployments without a
// file mount.
CAPEM string
// ServerName is the optional name to verify the runner certificate
// against, for a runner addressed by an IP the certificate does not list.
ServerName string
// RequestTimeout bounds one request to the runner.
RequestTimeout time.Duration
}
// Enabled reports whether a runner is configured.
func (settings CodeRunnerSettings) Enabled() bool { return settings.URL != "" }
func (settings CodeRunnerSettings) String() string { return redactedCodeRunnerSetting }
func (settings CodeRunnerSettings) GoString() string { return redactedCodeRunnerSetting }
// Format redacts every verb; without it %+v would print the secrets.
func (settings CodeRunnerSettings) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(redactedCodeRunnerSetting))
}
func (settings CodeRunnerSettings) LogValue() slog.Value {
return slog.StringValue(redactedCodeRunnerSetting)
}
// LoadCodeRunnerSettings reads the code runner settings. An empty variable
// counts as unset, as Compose passes an unset variable as an empty string.
func LoadCodeRunnerSettings(lookup LookupEnv) (CodeRunnerSettings, error) {
text := func(key string) string { return strings.TrimSpace(valueOrDefault(lookup, key, "")) }
settings := CodeRunnerSettings{
URL: text("CODE_RUNNER_URL"),
Token: text("CODE_RUNNER_TOKEN"),
RunKey: text("CODE_RUNNER_RUN_KEY"),
CAFile: text("CODE_RUNNER_CA_FILE"),
CAPEM: normalizePEM(text("CODE_RUNNER_CA_PEM")),
ServerName: text("CODE_RUNNER_SERVER_NAME"),
RequestTimeout: defaultCodeRunnerRequestTimeout,
}
if timeout := text("CODE_RUNNER_REQUEST_TIMEOUT"); timeout != "" {
parsed, err := time.ParseDuration(timeout)
if err != nil {
return CodeRunnerSettings{}, errors.New("config.LoadCodeRunnerSettings - CODE_RUNNER_REQUEST_TIMEOUT must be a duration such as 10s")
}
settings.RequestTimeout = parsed
}
return settings, settings.Validate()
}
// normalizePEM accepts a PEM written on one line with literal \n sequences,
// which env files without multi-line values need.
func normalizePEM(value string) string {
if !strings.Contains(value, "\n") {
value = strings.ReplaceAll(value, `\n`, "\n")
}
return value
}
// Validate checks the settings. A disabled runner must have no other runner
// setting, so a secret is never silently ignored. Errors name the setting and
// never print its value.
func (settings CodeRunnerSettings) Validate() error {
const location = "CodeRunnerSettings.Validate"
if !settings.Enabled() {
if settings.Token != "" || settings.RunKey != "" || settings.CAFile != "" || settings.CAPEM != "" || settings.ServerName != "" ||
(settings.RequestTimeout != 0 && settings.RequestTimeout != defaultCodeRunnerRequestTimeout) {
return errors.New(location + " - CODE_RUNNER_URL must be set when any other CODE_RUNNER_* setting is set")
}
return nil
}
if err := settings.validateURL(); err != nil {
return err
}
if err := settings.validateSecrets(); err != nil {
return err
}
if err := settings.validateCA(); err != nil {
return err
}
if settings.ServerName != "" && !validHostOrIP(settings.ServerName) {
return errors.New(location + " - CODE_RUNNER_SERVER_NAME must be a hostname or IP address")
}
return settings.validateTimeout()
}
func (settings CodeRunnerSettings) validateURL() error {
const location = "CodeRunnerSettings.Validate"
origin, err := url.Parse(settings.URL)
if err != nil || origin.Scheme != "https" || origin.Hostname() == "" || !validHostOrIP(origin.Hostname()) {
return errors.New(location + " - CODE_RUNNER_URL must be an https URL with a valid host; the runner is never called over plain HTTP")
}
if !isBareOrigin(origin, settings.URL) {
return errors.New(location + " - CODE_RUNNER_URL must be an origin without credentials, a path, query, or fragment")
}
if !validEndpointPort(origin) {
return errors.New(location + " - CODE_RUNNER_URL must have a valid nonzero port")
}
return nil
}
func (settings CodeRunnerSettings) validateSecrets() error {
const location = "CodeRunnerSettings.Validate"
for _, secret := range []struct{ name, value string }{
{"CODE_RUNNER_TOKEN", settings.Token}, {"CODE_RUNNER_RUN_KEY", settings.RunKey},
} {
if len(secret.value) < minCodeRunnerSecretLength || len(secret.value) > maxCodeRunnerSecretLength ||
!isPrintableASCII(secret.value) || strings.Contains(secret.value, " ") {
return fmt.Errorf("%s - %s must have %d to %d printable ASCII characters without spaces when CODE_RUNNER_URL is set",
location, secret.name, minCodeRunnerSecretLength, maxCodeRunnerSecretLength)
}
if strings.HasPrefix(strings.ToLower(secret.value), "replace-this") {
return fmt.Errorf("%s - %s still has its placeholder value", location, secret.name)
}
}
// The runner knows the token; if it were also the run key, the runner
// could recompute run IDs and link them to submissions.
if settings.Token == settings.RunKey {
return errors.New(location + " - CODE_RUNNER_RUN_KEY must differ from CODE_RUNNER_TOKEN")
}
return nil
}
func (settings CodeRunnerSettings) validateCA() error {
const location = "CodeRunnerSettings.Validate"
switch {
case settings.CAFile == "" && settings.CAPEM == "":
return errors.New(location + " - CODE_RUNNER_CA_FILE or CODE_RUNNER_CA_PEM must be set when CODE_RUNNER_URL is set")
case settings.CAFile != "" && settings.CAPEM != "":
return errors.New(location + " - set only one of CODE_RUNNER_CA_FILE and CODE_RUNNER_CA_PEM")
case settings.CAPEM != "":
if block, _ := pem.Decode([]byte(settings.CAPEM)); block == nil || block.Type != "CERTIFICATE" {
return errors.New(location + " - CODE_RUNNER_CA_PEM must start with a PEM CERTIFICATE block")
}
}
return nil
}
func (settings CodeRunnerSettings) validateTimeout() error {
if settings.RequestTimeout < minCodeRunnerRequestTimeout || settings.RequestTimeout > maxCodeRunnerRequestTimeout {
return fmt.Errorf("CodeRunnerSettings.Validate - CODE_RUNNER_REQUEST_TIMEOUT must be between %s and %s",
minCodeRunnerRequestTimeout, maxCodeRunnerRequestTimeout)
}
return nil
}