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

+12 -2
View File
@@ -37,6 +37,9 @@ type Application struct {
// mailSender is the transport selected by EMAIL_PROVIDER. Only the mail
// sending worker calls it.
mailSender outbound.MailSender
// codeRunner is the runner selected by CODE_RUNNER_URL: the disabled one
// when unset. Practice usecases receive it from here once they exist.
codeRunner outbound.CodeRunner
// relay publishes outbox events while the servers run. It is nil when
// the relay is disabled or the database is not configured.
relay *outboxrelay.Relay
@@ -127,8 +130,8 @@ func run(ctx context.Context, config config.Config, logger *slog.Logger) error {
}
// start prepares the application without opening listeners. The mail
// transport is selected before migrations, so a configuration that cannot
// start never changes the database. The demo policy seed and the mail quota
// transport and the code runner are selected before migrations, so a
// configuration that cannot start never changes the database. The demo policy seed and the mail quota
// report run after the migrations that create their tables.
func start(ctx context.Context, config config.Config, logger *slog.Logger) (*Application, func(), error) {
if err := config.Validate(); err != nil {
@@ -138,6 +141,10 @@ func start(ctx context.Context, config config.Config, logger *slog.Logger) (*App
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.start - select mail transport: %w", err)
}
codeRunner, err := newCodeRunner(config, logger)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.start - select code runner: %w", err)
}
if err := migrateDatabase(ctx, config, logger); err != nil {
return nil, nil, fmt.Errorf("bootstrap.start - migrate database: %w", err)
}
@@ -149,6 +156,9 @@ func start(ctx context.Context, config config.Config, logger *slog.Logger) (*App
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.start - initialize application: %w", err)
}
// No dependency needs the runner yet, so it is attached here rather than
// injected; the practice usecases will take it from the injector.
application.codeRunner = codeRunner
return application, cleanup, nil
}
+60
View File
@@ -0,0 +1,60 @@
package bootstrap
import (
"fmt"
"log/slog"
"os"
"lincodex/backend/config"
coderunner "lincodex/backend/internal/adapter/secondary/code_runner"
coderunnerdisabled "lincodex/backend/internal/adapter/secondary/code_runner/disabled"
"lincodex/backend/internal/port/outbound"
)
// newCodeRunner binds the CodeRunner port. An unset CODE_RUNNER_URL selects
// the disabled runner, which reports every request as unavailable and never as
// a verdict. A set URL selects the TLS client, and a failure to build it stops
// startup instead of falling back to the disabled runner. The constructor
// makes no network call, so startup does not depend on the runner.
func newCodeRunner(settings config.Config, logger *slog.Logger) (outbound.CodeRunner, error) {
runner := settings.CodeRunner
if err := runner.Validate(); err != nil {
return nil, fmt.Errorf("bootstrap.newCodeRunner - validate settings: %w", err)
}
if !runner.Enabled() {
logger.Info("code runner selected", slog.Bool("enabled", false))
logger.Warn("code runner is disabled; code practice runs nothing and every request is reported as unavailable")
return coderunnerdisabled.NewRunner(), nil
}
caPEM, err := codeRunnerCA(runner)
if err != nil {
return nil, fmt.Errorf("bootstrap.newCodeRunner - read CA: %w", err)
}
client, err := coderunner.NewClient(coderunner.Settings{
BaseURL: runner.URL,
Token: runner.Token,
RunKey: runner.RunKey,
CAPEM: caPEM,
ServerName: runner.ServerName,
RequestTimeout: runner.RequestTimeout,
})
if err != nil {
return nil, fmt.Errorf("bootstrap.newCodeRunner - create client: %w", err)
}
// Neither the URL nor any secret is logged.
logger.Info("code runner selected", slog.Bool("enabled", true))
return client, nil
}
// codeRunnerCA returns the CA PEM from the inline setting or the file.
func codeRunnerCA(runner config.CodeRunnerSettings) ([]byte, error) {
if runner.CAPEM != "" {
return []byte(runner.CAPEM), nil
}
pemBytes, err := os.ReadFile(runner.CAFile)
if err != nil {
return nil, fmt.Errorf("CODE_RUNNER_CA_FILE is not readable: %w", err)
}
return pemBytes, nil
}
@@ -0,0 +1,134 @@
package bootstrap
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"log/slog"
"math/big"
"os"
"path/filepath"
"strings"
"testing"
"time"
"lincodex/backend/config"
coderunner "lincodex/backend/internal/adapter/secondary/code_runner"
"lincodex/backend/internal/port/outbound"
)
const (
testRunnerToken = "bootstrap-runner-token-0123456789abcdef"
testRunnerRunKey = "bootstrap-runner-run-key-0123456789abcd"
)
func testCAPEM(t *testing.T) string {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("GenerateKey() error = %v", err)
}
template := &x509.Certificate{
SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "bootstrap 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 {
t.Fatalf("CreateCertificate() error = %v", err)
}
return string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))
}
func enabledRunnerSettings() config.CodeRunnerSettings {
return config.CodeRunnerSettings{
URL: "https://10.80.0.2:8443", Token: testRunnerToken, RunKey: testRunnerRunKey,
RequestTimeout: 10 * time.Second,
}
}
func TestNewCodeRunnerDefaultsToTheDisabledRunner(t *testing.T) {
var logs bytes.Buffer
logger := slog.New(slog.NewTextHandler(&logs, nil))
runner, err := newCodeRunner(config.Config{}, logger)
if err != nil {
t.Fatalf("newCodeRunner() error = %v", err)
}
if _, isClient := runner.(*coderunner.Client); isClient {
t.Fatal("an unset CODE_RUNNER_URL selected the TLS client")
}
// Practice must see an unavailable runner, never a verdict.
_, err = runner.Poll(context.Background(), disabledProbeRequest())
if !errors.Is(err, outbound.ErrCodeRunnerDisabled) {
t.Fatalf("Poll() error = %v, want ErrCodeRunnerDisabled", err)
}
if !strings.Contains(logs.String(), "code runner is disabled") {
t.Fatalf("log = %q, want a disabled warning", logs.String())
}
}
func TestNewCodeRunnerBuildsTheClientFromAnInlineCAOrAFile(t *testing.T) {
caPEM := testCAPEM(t)
caFile := filepath.Join(t.TempDir(), "runner-ca.pem")
if err := os.WriteFile(caFile, []byte(caPEM), 0o600); err != nil {
t.Fatalf("WriteFile() error = %v", err)
}
inline, fromFile := enabledRunnerSettings(), enabledRunnerSettings()
inline.CAPEM = caPEM
fromFile.CAFile = caFile
for name, runner := range map[string]config.CodeRunnerSettings{"inline PEM": inline, "file": fromFile} {
var logs bytes.Buffer
selected, err := newCodeRunner(config.Config{CodeRunner: runner}, slog.New(slog.NewTextHandler(&logs, nil)))
if err != nil {
t.Fatalf("%s: newCodeRunner() error = %v", name, err)
}
if _, isClient := selected.(*coderunner.Client); !isClient {
t.Fatalf("%s: selected %T, want the TLS client", name, selected)
}
for _, secret := range []string{testRunnerToken, testRunnerRunKey, "10.80.0.2"} {
if strings.Contains(logs.String(), secret) {
t.Fatalf("%s: the startup log exposes %q", name, secret)
}
}
}
}
func TestNewCodeRunnerFailsInsteadOfFallingBackToDisabled(t *testing.T) {
missing := enabledRunnerSettings()
missing.CAFile = filepath.Join(t.TempDir(), "absent.pem")
notPEM := enabledRunnerSettings()
notPEM.CAPEM = "not a certificate"
for name, runner := range map[string]config.CodeRunnerSettings{"unreadable CA file": missing, "invalid CA": notPEM} {
selected, err := newCodeRunner(config.Config{CodeRunner: runner}, slog.New(slog.NewTextHandler(&bytes.Buffer{}, nil)))
if err == nil || selected != nil {
t.Fatalf("%s: newCodeRunner() = %v, %v, want a startup error", name, selected, err)
}
if strings.Contains(err.Error(), testRunnerToken) || strings.Contains(err.Error(), testRunnerRunKey) {
t.Fatalf("%s: the error exposes a secret: %v", name, err)
}
}
}
func disabledProbeRequest() outbound.CodeRunRequest {
return outbound.CodeRunRequest{
Key: outbound.CodeRunKey{AttemptItemID: [16]byte{1}, SubmissionID: [16]byte{2}},
Language: outbound.CodeLanguagePython3,
Source: "print(1)",
Limits: outbound.CodeRunLimits{TimeLimitMs: 1000, MemoryLimitMB: 128, OutputLimitKB: 64},
Groups: []outbound.CodeTestGroup{{
ID: "public", Visibility: outbound.CodeTestPublic,
Checker: outbound.CodeChecker{Kind: outbound.CodeCheckerExact},
Tests: []outbound.CodeTest{{ID: "1", Input: "", ExpectedOutput: "1\n"}},
}},
}
}