feat(practice): add the code runner port and its TLS client

This commit is contained in:
shira committed 2026-10-11 09:48:44 +03:00
1 parent 53a125f2b5
commit facc1789b1
24 files changed
+3374 -6

No files matched your search

+189
View File
@@ -0,0 +1,189 @@
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
}
+193
View File
@@ -0,0 +1,193 @@
package config
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"log/slog"
"math/big"
"strings"
"testing"
"time"
)
const (
testRunnerToken = "runner-token-0123456789abcdef0123456789"
testRunnerRunKey = "runner-run-key-0123456789abcdef012345678"
)
// testRunnerCAPEM is a real, self-signed CA certificate made once per test run.
var testRunnerCAPEM = func() string {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
panic(err)
}
template := &x509.Certificate{
SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "config test CA"},
NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
IsCA: true, BasicConstraintsValid: true,
}
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
if err != nil {
panic(err)
}
return string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))
}()
func codeRunnerLookup(values map[string]string) LookupEnv {
return func(key string) (string, bool) {
value, ok := values[key]
return value, ok
}
}
func enabledRunnerEnv() map[string]string {
return map[string]string{
"CODE_RUNNER_URL": "https://10.80.0.2:8443",
"CODE_RUNNER_TOKEN": testRunnerToken,
"CODE_RUNNER_RUN_KEY": testRunnerRunKey,
"CODE_RUNNER_CA_FILE": "/run/secrets/runner-ca.pem",
}
}
func TestCodeRunnerSettingsAreDisabledByDefault(t *testing.T) {
for name, values := range map[string]map[string]string{
"unset": nil,
"empty values as Compose passes them": {
"CODE_RUNNER_URL": "", "CODE_RUNNER_TOKEN": "", "CODE_RUNNER_RUN_KEY": "", "CODE_RUNNER_CA_FILE": "",
"CODE_RUNNER_CA_PEM": "", "CODE_RUNNER_SERVER_NAME": "", "CODE_RUNNER_REQUEST_TIMEOUT": "",
},
} {
settings, err := LoadCodeRunnerSettings(codeRunnerLookup(values))
if err != nil || settings.Enabled() {
t.Fatalf("%s: settings = %v, %v, want a disabled runner", name, settings.Enabled(), err)
}
}
}
func TestCodeRunnerSettingsLoadAnEnabledRunner(t *testing.T) {
values := enabledRunnerEnv()
values["CODE_RUNNER_SERVER_NAME"] = "runner.internal"
values["CODE_RUNNER_REQUEST_TIMEOUT"] = "20s"
settings, err := LoadCodeRunnerSettings(codeRunnerLookup(values))
if err != nil || !settings.Enabled() {
t.Fatalf("LoadCodeRunnerSettings() = %v, %v, want an enabled runner", settings.Enabled(), err)
}
if settings.URL != "https://10.80.0.2:8443" || settings.CAFile != "/run/secrets/runner-ca.pem" ||
settings.ServerName != "runner.internal" || settings.RequestTimeout != 20*time.Second {
t.Fatalf("settings were not read as set")
}
}
func TestCodeRunnerSettingsAcceptAnInlineCAWithEscapedNewlines(t *testing.T) {
values := enabledRunnerEnv()
delete(values, "CODE_RUNNER_CA_FILE")
values["CODE_RUNNER_CA_PEM"] = strings.ReplaceAll(strings.TrimSpace(testRunnerCAPEM), "\n", `\n`)
settings, err := LoadCodeRunnerSettings(codeRunnerLookup(values))
if err != nil || !strings.HasPrefix(settings.CAPEM, "-----BEGIN CERTIFICATE-----\n") {
t.Fatalf("LoadCodeRunnerSettings() CAPEM = %q, %v, want the PEM with real newlines", settings.CAPEM, err)
}
}
func TestCodeRunnerSettingsRejectInvalidValuesWithoutEchoingThem(t *testing.T) {
tests := []struct {
name string
change func(map[string]string)
}{
{"plain http", func(v map[string]string) { v["CODE_RUNNER_URL"] = "http://10.80.0.2:8443" }},
{"path", func(v map[string]string) { v["CODE_RUNNER_URL"] = "https://10.80.0.2:8443/api" }},
{"credentials", func(v map[string]string) { v["CODE_RUNNER_URL"] = "https://user:password-value@10.80.0.2" }},
{"query", func(v map[string]string) { v["CODE_RUNNER_URL"] = "https://10.80.0.2:8443?x=1" }},
{"port zero", func(v map[string]string) { v["CODE_RUNNER_URL"] = "https://10.80.0.2:0" }},
{"short token", func(v map[string]string) { v["CODE_RUNNER_TOKEN"] = "short-token-value" }},
{"token with space", func(v map[string]string) { v["CODE_RUNNER_TOKEN"] = testRunnerToken + " x" }},
{"missing token", func(v map[string]string) { delete(v, "CODE_RUNNER_TOKEN") }},
{"short run key", func(v map[string]string) { v["CODE_RUNNER_RUN_KEY"] = "short-run-key-value" }},
{"placeholder run key", func(v map[string]string) { v["CODE_RUNNER_RUN_KEY"] = "replace-this-run-key-0123456789abcdef0123" }},
{"run key equals token", func(v map[string]string) { v["CODE_RUNNER_RUN_KEY"] = testRunnerToken }},
{"no CA", func(v map[string]string) { delete(v, "CODE_RUNNER_CA_FILE") }},
{"both CAs", func(v map[string]string) { v["CODE_RUNNER_CA_PEM"] = testRunnerCAPEM }},
{"CA that is not PEM", func(v map[string]string) {
delete(v, "CODE_RUNNER_CA_FILE")
v["CODE_RUNNER_CA_PEM"] = "not-a-certificate-value"
}},
{"bad server name", func(v map[string]string) { v["CODE_RUNNER_SERVER_NAME"] = "bad name!" }},
{"timeout that is not a duration", func(v map[string]string) { v["CODE_RUNNER_REQUEST_TIMEOUT"] = "soon" }},
{"timeout too short", func(v map[string]string) { v["CODE_RUNNER_REQUEST_TIMEOUT"] = "100ms" }},
{"timeout too long", func(v map[string]string) { v["CODE_RUNNER_REQUEST_TIMEOUT"] = "5m" }},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
values := enabledRunnerEnv()
test.change(values)
_, err := LoadCodeRunnerSettings(codeRunnerLookup(values))
if err == nil {
t.Fatal("LoadCodeRunnerSettings() accepted invalid settings")
}
for _, secret := range []string{testRunnerToken, testRunnerRunKey, "password-value", "not-a-certificate-value"} {
if strings.Contains(err.Error(), secret) {
t.Fatalf("error echoes a value: %v", err)
}
}
})
}
}
func TestCodeRunnerSettingsRefuseSecretsWithoutAURL(t *testing.T) {
for _, key := range []string{
"CODE_RUNNER_TOKEN", "CODE_RUNNER_RUN_KEY", "CODE_RUNNER_CA_FILE", "CODE_RUNNER_CA_PEM",
"CODE_RUNNER_SERVER_NAME", "CODE_RUNNER_REQUEST_TIMEOUT",
} {
value := testRunnerToken
if key == "CODE_RUNNER_REQUEST_TIMEOUT" {
value = "5s"
}
_, err := LoadCodeRunnerSettings(codeRunnerLookup(map[string]string{key: value}))
if err == nil {
t.Errorf("%s without CODE_RUNNER_URL was silently ignored", key)
}
}
}
func TestCodeRunnerSettingsAreRedactedInEveryRendering(t *testing.T) {
values := enabledRunnerEnv()
settings, err := LoadCodeRunnerSettings(codeRunnerLookup(values))
if err != nil {
t.Fatalf("LoadCodeRunnerSettings() error = %v", err)
}
for _, rendered := range []string{
settings.String(), settings.GoString(), settings.LogValue().String(),
fmt.Sprintf("%v", settings), fmt.Sprintf("%+v", settings), fmt.Sprintf("%#v", settings),
slog.Group("runner", slog.Any("settings", settings)).Value.String(),
} {
if strings.Contains(rendered, testRunnerToken) || strings.Contains(rendered, testRunnerRunKey) {
t.Fatalf("rendering exposes a secret: %q", rendered)
}
}
}
func TestConfigLoadsAndValidatesTheCodeRunner(t *testing.T) {
base := map[string]string{}
config, err := LoadFromEnv(testEnvironment(base))
if err != nil || config.CodeRunner.Enabled() {
t.Fatalf("LoadFromEnv() runner enabled = %v, error = %v, want a disabled runner by default", config.CodeRunner.Enabled(), err)
}
for key, value := range enabledRunnerEnv() {
base[key] = value
}
config, err = LoadFromEnv(testEnvironment(base))
if err != nil || !config.CodeRunner.Enabled() {
t.Fatalf("LoadFromEnv() runner enabled = %v, error = %v, want an enabled runner", config.CodeRunner.Enabled(), err)
}
}
+9
View File
@@ -156,6 +156,10 @@ type Config struct {
// assignment. Reviewed source provenance is required separately.
AssessmentDemoCategoriesEnabled bool
// CodeRunner configures the client of the own code runner. It is disabled
// unless CODE_RUNNER_URL is set.
CodeRunner CodeRunnerSettings
// TrustedProxyCIDRs are the reverse proxies in front of the API. The
// client address is taken from X-Forwarded-For only through them (see
// middleware.ClientIP). Empty trusts no proxy.
@@ -250,6 +254,11 @@ func (config *Config) loadIdentityAndProxySettings(lookup LookupEnv) error {
if err := config.loadAssessment(lookup); err != nil {
return err
}
codeRunner, err := LoadCodeRunnerSettings(lookup)
if err != nil {
return err
}
config.CodeRunner = codeRunner
return config.loadTrustedProxies(lookup)
}