feat(practice): add the code runner port and its TLS client
This commit is contained in:
1 parent
53a125f2b5
commit
facc1789b1
24 files changed
+3374
-6
No files matched your search
@@ -108,6 +108,22 @@ IDENTITY_SESSION_ABSOLUTE_LIFETIME=168h
|
||||
# demo_express never assigns a category. Leave false outside a synthetic stand.
|
||||
ASSESSMENT_DEMO_CATEGORIES_ENABLED=false
|
||||
|
||||
# Own code runner for code practice. Empty CODE_RUNNER_URL keeps it off: the
|
||||
# backend then reports the runner as unavailable and runs nothing. To enable
|
||||
# it, set the https URL of the runner VM, its service token, a separate random
|
||||
# run key, and the CA that signed the runner certificate (a file path inside
|
||||
# the container, or the PEM text with \n for line breaks). Generate both
|
||||
# secrets with `openssl rand -hex 32`; keep them in the server environment only.
|
||||
# CODE_RUNNER_SERVER_NAME is the certificate name when the URL is an IP the
|
||||
# certificate does not list; CODE_RUNNER_REQUEST_TIMEOUT defaults to 10s.
|
||||
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=
|
||||
|
||||
# Reverse proxies the backend trusts to report the client address in
|
||||
# X-Forwarded-For. Leave it unset: the default is the frontend container's
|
||||
# APP_FRONTEND_IP as a single address. A wider list lets other containers (or a
|
||||
|
||||
@@ -202,6 +202,15 @@ test-scripts: ## Check integration shard coverage, selection, and failure propag
|
||||
test-int-compile: ## Compile infrastructure integration tests without starting containers
|
||||
$(GO) test -tags=integration -run '^$$' ./integration_test/...
|
||||
|
||||
.PHONY: test-code-runner-live
|
||||
test-code-runner-live: ## Run fixed harmless programs on a real runner (set CODE_RUNNER_URL, CODE_RUNNER_TOKEN, CODE_RUNNER_CA_FILE)
|
||||
@if [ -z "$$CODE_RUNNER_URL" ] || [ -z "$$CODE_RUNNER_TOKEN" ] || [ -z "$$CODE_RUNNER_CA_FILE" ]; then \
|
||||
echo 'set CODE_RUNNER_URL, CODE_RUNNER_TOKEN, and CODE_RUNNER_CA_FILE (optionally CODE_RUNNER_SERVER_NAME)' >&2; exit 2; \
|
||||
fi
|
||||
CODE_RUNNER_LIVE_URL="$$CODE_RUNNER_URL" CODE_RUNNER_LIVE_TOKEN="$$CODE_RUNNER_TOKEN" \
|
||||
CODE_RUNNER_LIVE_CA_FILE="$$CODE_RUNNER_CA_FILE" CODE_RUNNER_LIVE_SERVER_NAME="$$CODE_RUNNER_SERVER_NAME" \
|
||||
$(GO) test -count=1 -v -run '^TestLiveRunner' ./internal/adapter/secondary/code_runner/
|
||||
|
||||
.PHONY: verify check
|
||||
check: ## Run local formatting, build, unit, and lint checks in order
|
||||
$(MAKE) --no-print-directory fmt-check
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
// Package coderunner is the client of the own code runner service (api/runner).
|
||||
// The generated ogen client in ./api carries the contract; this adapter adds
|
||||
// the TLS 1.3 transport pinned to the configured CA, the service token, the
|
||||
// request timeout and a response size cap, the opaque idempotent run ID, the
|
||||
// request and response validation, and the split between a candidate's verdict
|
||||
// and an infrastructure failure.
|
||||
package coderunner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/code_runner/api"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
// maxResponseBytes caps one response. A result has at most 4 groups of 50
|
||||
// tests with a few hundred bytes each, far below it.
|
||||
maxResponseBytes = 4 << 20
|
||||
dialTimeout = 5 * time.Second
|
||||
handshakeTimeout = 5 * time.Second
|
||||
// minRunKeyBytes keeps the run ID key unguessable; it matches the
|
||||
// minimum of the service token.
|
||||
minRunKeyBytes = 32
|
||||
redacted = "[redacted]"
|
||||
)
|
||||
|
||||
var errResponseTooLarge = errors.New("response body exceeds the size limit")
|
||||
|
||||
// Settings configure the client. Token, RunKey, and CAPEM come from the
|
||||
// deployment secret store.
|
||||
type Settings struct {
|
||||
// BaseURL is the runner origin, for example https://10.80.0.2:8443. Only
|
||||
// https is accepted.
|
||||
BaseURL string
|
||||
// Token is the shared service token sent as a bearer token.
|
||||
Token string
|
||||
// RunKey keys the HMAC that derives run IDs from submissions.
|
||||
RunKey string
|
||||
// CAPEM holds the PEM certificates that sign the runner certificate. The
|
||||
// system roots are not used.
|
||||
CAPEM []byte
|
||||
// ServerName overrides the name the certificate is verified against, for
|
||||
// a runner addressed by an IP that its certificate does not list. The
|
||||
// certificate is verified either way.
|
||||
ServerName string
|
||||
// RequestTimeout bounds one HTTP exchange, including reading the body.
|
||||
RequestTimeout time.Duration
|
||||
}
|
||||
|
||||
func (settings Settings) String() string { return redacted }
|
||||
|
||||
func (settings Settings) GoString() string { return redacted }
|
||||
|
||||
// Format redacts every verb; without it %+v would print the secrets.
|
||||
func (settings Settings) Format(state fmt.State, _ rune) {
|
||||
_, _ = state.Write([]byte(redacted))
|
||||
}
|
||||
|
||||
func (settings Settings) LogValue() slog.Value { return slog.StringValue(redacted) }
|
||||
|
||||
// Client implements outbound.CodeRunner over HTTPS.
|
||||
type Client struct {
|
||||
api *api.Client
|
||||
secret []byte
|
||||
}
|
||||
|
||||
var _ outbound.CodeRunner = (*Client)(nil)
|
||||
|
||||
// NewClient validates the settings and builds the client. Nothing connects.
|
||||
func NewClient(settings Settings) (*Client, error) {
|
||||
const location = "coderunner.NewClient"
|
||||
if err := validateOrigin(settings.BaseURL); err != nil {
|
||||
return nil, fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
if err := validateSecret(settings.Token, "token", 1); err != nil {
|
||||
return nil, fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
if err := validateSecret(settings.RunKey, "run key", minRunKeyBytes); err != nil {
|
||||
return nil, fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
if settings.RequestTimeout <= 0 {
|
||||
return nil, errors.New(location + " - request timeout must be positive")
|
||||
}
|
||||
pool := x509.NewCertPool()
|
||||
if !pool.AppendCertsFromPEM(settings.CAPEM) {
|
||||
return nil, errors.New(location + " - CA must hold at least one PEM certificate")
|
||||
}
|
||||
|
||||
transport := &http.Transport{
|
||||
// The runner sits on a private bridge; an environment proxy must
|
||||
// never see its traffic.
|
||||
Proxy: nil,
|
||||
DialContext: (&net.Dialer{Timeout: dialTimeout}).DialContext,
|
||||
TLSClientConfig: &tls.Config{
|
||||
MinVersion: tls.VersionTLS13,
|
||||
RootCAs: pool,
|
||||
ServerName: settings.ServerName,
|
||||
},
|
||||
TLSHandshakeTimeout: handshakeTimeout,
|
||||
ForceAttemptHTTP2: true,
|
||||
MaxIdleConns: 4,
|
||||
IdleConnTimeout: time.Minute,
|
||||
}
|
||||
httpClient := &http.Client{
|
||||
Timeout: settings.RequestTimeout,
|
||||
Transport: cappedTransport{next: transport},
|
||||
// The runner is a fixed origin; a redirect is never expected and
|
||||
// would carry the token elsewhere.
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
||||
}
|
||||
client, err := api.NewClient(settings.BaseURL, tokenSource{token: settings.Token}, api.WithClient(httpClient))
|
||||
if err != nil {
|
||||
return nil, errors.New(location + " - create client")
|
||||
}
|
||||
return &Client{api: client, secret: []byte(settings.RunKey)}, nil
|
||||
}
|
||||
|
||||
func validateOrigin(raw string) error {
|
||||
parsed, err := url.Parse(raw)
|
||||
if err != nil || parsed.Scheme != "https" || parsed.Hostname() == "" || parsed.User != nil ||
|
||||
parsed.RawQuery != "" || parsed.Fragment != "" || strings.Trim(parsed.Path, "/") != "" {
|
||||
return errors.New("runner URL must be an https origin without credentials or path")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateSecret(value, name string, minBytes int) error {
|
||||
if len(value) < minBytes {
|
||||
return fmt.Errorf("%s must have at least %d bytes", name, minBytes)
|
||||
}
|
||||
for index := range len(value) {
|
||||
if value[index] <= ' ' || value[index] > '~' {
|
||||
return fmt.Errorf("%s must contain printable ASCII characters without spaces", name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// tokenSource supplies the bearer token to the generated client.
|
||||
type tokenSource struct{ token string }
|
||||
|
||||
func (source tokenSource) BearerAuth(context.Context, api.OperationName) (api.BearerAuth, error) {
|
||||
return api.BearerAuth{Token: source.token}, nil
|
||||
}
|
||||
|
||||
// Submit sends the run, or reads it back when the runner already holds the
|
||||
// same key with the same payload.
|
||||
func (client *Client) Submit(ctx context.Context, request outbound.CodeRunRequest) (outbound.CodeRunStatus, error) {
|
||||
const location = "coderunner.Client.Submit"
|
||||
runID, err := client.prepare(ctx, location, request)
|
||||
if err != nil {
|
||||
return outbound.CodeRunStatus{}, err
|
||||
}
|
||||
response, err := client.api.SubmitRun(ctx, toAPIRequest(request), api.SubmitRunParams{RunID: runID})
|
||||
if err != nil {
|
||||
return outbound.CodeRunStatus{}, classifyError(ctx, location, err, false)
|
||||
}
|
||||
switch typed := response.(type) {
|
||||
case *api.SubmitRunAccepted:
|
||||
return statusFromResponse(location, runID, request, api.RunStatus(*typed), true)
|
||||
case *api.SubmitRunOK:
|
||||
return statusFromResponse(location, runID, request, api.RunStatus(*typed), false)
|
||||
case *api.RunnerBusyHeaders:
|
||||
return busyStatus(location, runID, typed)
|
||||
default:
|
||||
return outbound.CodeRunStatus{}, fmt.Errorf("%s - unexpected response type: %w", location, outbound.ErrCodeRunnerBadResponse)
|
||||
}
|
||||
}
|
||||
|
||||
// Poll reads the state of the run that Submit started. The request is the one
|
||||
// that was submitted: its groups are what the result is checked against.
|
||||
func (client *Client) Poll(ctx context.Context, request outbound.CodeRunRequest) (outbound.CodeRunStatus, error) {
|
||||
const location = "coderunner.Client.Poll"
|
||||
runID, err := client.prepare(ctx, location, request)
|
||||
if err != nil {
|
||||
return outbound.CodeRunStatus{}, err
|
||||
}
|
||||
response, err := client.api.GetRun(ctx, api.GetRunParams{RunID: runID})
|
||||
if err != nil {
|
||||
return outbound.CodeRunStatus{}, classifyError(ctx, location, err, true)
|
||||
}
|
||||
return statusFromResponse(location, runID, request, *response, false)
|
||||
}
|
||||
|
||||
// prepare rejects what cannot be sent and derives the run ID.
|
||||
func (client *Client) prepare(ctx context.Context, location string, request outbound.CodeRunRequest) (uuid.UUID, error) {
|
||||
if err := request.Validate(); err != nil {
|
||||
return uuid.Nil, fmt.Errorf("%s - validate request: %w", location, err)
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return uuid.Nil, fmt.Errorf("%s - context: %w", location, err)
|
||||
}
|
||||
return deriveRunID(client.secret, request.Key), nil
|
||||
}
|
||||
|
||||
func busyStatus(location string, runID uuid.UUID, busy *api.RunnerBusyHeaders) (outbound.CodeRunStatus, error) {
|
||||
if busy.Response.Code != api.ProblemCodeRunnerBusy || busy.Response.Status != 503 {
|
||||
return outbound.CodeRunStatus{}, fmt.Errorf("%s - 503 without runner_busy: %w", location, outbound.ErrCodeRunnerUnavailable)
|
||||
}
|
||||
return outbound.CodeRunStatus{
|
||||
State: outbound.CodeRunBusy,
|
||||
RunID: runID.String(),
|
||||
RetryAfter: time.Duration(busy.RetryAfter) * time.Second,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// statusFromResponse checks a run status against the contract and the request
|
||||
// and converts it. accepted is true for the 202 answer, which is always a run
|
||||
// that has just started.
|
||||
func statusFromResponse(
|
||||
location string, runID uuid.UUID, request outbound.CodeRunRequest, response api.RunStatus, accepted bool,
|
||||
) (outbound.CodeRunStatus, error) {
|
||||
if response.RunID != runID {
|
||||
return outbound.CodeRunStatus{}, fmt.Errorf("%s - the run ID does not match the request: %w", location, outbound.ErrCodeRunnerBadResponse)
|
||||
}
|
||||
switch response.State {
|
||||
case api.RunStateRunning:
|
||||
if response.Result.Set {
|
||||
return outbound.CodeRunStatus{}, fmt.Errorf("%s - a running run carries a result: %w", location, outbound.ErrCodeRunnerBadResponse)
|
||||
}
|
||||
return outbound.CodeRunStatus{State: outbound.CodeRunRunning, RunID: runID.String()}, nil
|
||||
case api.RunStateFinished:
|
||||
if accepted || !response.Result.Set {
|
||||
return outbound.CodeRunStatus{}, fmt.Errorf("%s - a finished run has no result or was just accepted: %w", location, outbound.ErrCodeRunnerBadResponse)
|
||||
}
|
||||
result, err := convertResult(response.Result.Value, request)
|
||||
if err != nil {
|
||||
return outbound.CodeRunStatus{}, fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
return outbound.CodeRunStatus{State: outbound.CodeRunFinished, RunID: runID.String(), Result: result}, nil
|
||||
default:
|
||||
return outbound.CodeRunStatus{}, fmt.Errorf("%s - unknown run state: %w", location, outbound.ErrCodeRunnerBadResponse)
|
||||
}
|
||||
}
|
||||
|
||||
// classifyError turns an error of the generated client into a port error. The
|
||||
// error text never includes the runner URL, the response body, or the token.
|
||||
// forPoll marks GetRun, where 404 means that the runner lost the run.
|
||||
func classifyError(ctx context.Context, location string, err error, forPoll bool) error {
|
||||
if ctxErr := ctx.Err(); ctxErr != nil {
|
||||
return fmt.Errorf("%s - context: %w", location, ctxErr)
|
||||
}
|
||||
var problem *api.ProblemStatusCode
|
||||
if errors.As(err, &problem) {
|
||||
return classifyProblem(location, problem, forPoll)
|
||||
}
|
||||
var transportErr *url.Error
|
||||
var timeoutErr net.Error
|
||||
switch {
|
||||
case errors.As(err, &transportErr):
|
||||
return fmt.Errorf("%s - %s: %w", location, transportReason(transportErr), outbound.ErrCodeRunnerUnavailable)
|
||||
case errors.As(err, &timeoutErr) && timeoutErr.Timeout():
|
||||
// The client timeout can also fire while the body is read.
|
||||
return fmt.Errorf("%s - the request timed out: %w", location, outbound.ErrCodeRunnerUnavailable)
|
||||
}
|
||||
return fmt.Errorf("%s - the response does not match the contract: %w", location, outbound.ErrCodeRunnerBadResponse)
|
||||
}
|
||||
|
||||
func classifyProblem(location string, problem *api.ProblemStatusCode, forPoll bool) error {
|
||||
status := problem.StatusCode
|
||||
switch {
|
||||
case status == http.StatusUnauthorized:
|
||||
return fmt.Errorf("%s - HTTP 401: %w", location, outbound.ErrCodeRunnerUnauthorized)
|
||||
case status == http.StatusNotFound && forPoll:
|
||||
return fmt.Errorf("%s - HTTP 404: %w", location, outbound.ErrCodeRunNotFound)
|
||||
case status == http.StatusUnprocessableEntity && problem.Response.Code == api.ProblemCodeIdempotencyKeyReused:
|
||||
return fmt.Errorf("%s - HTTP 422: %w", location, outbound.ErrCodeRunKeyReused)
|
||||
case status == http.StatusBadRequest || status == http.StatusRequestEntityTooLarge:
|
||||
return fmt.Errorf("%s - the runner rejected the request with HTTP %d: %w", location, status, outbound.ErrInvalidCodeRunRequest)
|
||||
case status >= http.StatusInternalServerError:
|
||||
return fmt.Errorf("%s - the runner failed with HTTP %d: %w", location, status, outbound.ErrCodeRunnerUnavailable)
|
||||
default:
|
||||
return fmt.Errorf("%s - unexpected HTTP %d: %w", location, status, outbound.ErrCodeRunnerBadResponse)
|
||||
}
|
||||
}
|
||||
|
||||
// transportReason names why no answer came back, without the URL that the
|
||||
// underlying error carries.
|
||||
func transportReason(err *url.Error) string {
|
||||
var unknownAuthority x509.UnknownAuthorityError
|
||||
var hostname x509.HostnameError
|
||||
var invalid x509.CertificateInvalidError
|
||||
var recordHeader tls.RecordHeaderError
|
||||
var alert tls.AlertError
|
||||
var network *net.OpError
|
||||
switch {
|
||||
case errors.As(err, &unknownAuthority), errors.As(err, &hostname), errors.As(err, &invalid):
|
||||
return "the runner certificate was not verified against the configured CA"
|
||||
case err.Timeout():
|
||||
return "the request timed out"
|
||||
case errors.As(err, &recordHeader), errors.As(err, &alert):
|
||||
return "the TLS handshake failed"
|
||||
case errors.As(err, &network) && network.Op == "dial":
|
||||
return "the connection failed"
|
||||
default:
|
||||
return "the request failed"
|
||||
}
|
||||
}
|
||||
|
||||
// cappedTransport fails a response body that grows past maxResponseBytes, so
|
||||
// a faulty runner cannot exhaust memory.
|
||||
type cappedTransport struct {
|
||||
next http.RoundTripper
|
||||
}
|
||||
|
||||
func (transport cappedTransport) RoundTrip(request *http.Request) (*http.Response, error) {
|
||||
response, err := transport.next.RoundTrip(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if response.ContentLength > maxResponseBytes {
|
||||
_ = response.Body.Close()
|
||||
return nil, errResponseTooLarge
|
||||
}
|
||||
response.Body = &cappedBody{body: response.Body, remaining: maxResponseBytes}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
type cappedBody struct {
|
||||
body io.ReadCloser
|
||||
remaining int64
|
||||
}
|
||||
|
||||
func (body *cappedBody) Read(buffer []byte) (int, error) {
|
||||
// One byte beyond the limit tells an exact fit from an overrun.
|
||||
if int64(len(buffer)) > body.remaining+1 {
|
||||
buffer = buffer[:body.remaining+1]
|
||||
}
|
||||
count, err := body.body.Read(buffer)
|
||||
if int64(count) > body.remaining {
|
||||
return int(body.remaining), errResponseTooLarge
|
||||
}
|
||||
body.remaining -= int64(count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
func (body *cappedBody) Close() error { return body.body.Close() }
|
||||
@@ -0,0 +1,687 @@
|
||||
package coderunner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/code_runner/api"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// submitAndPoll runs the normal flow against the fixture and returns the
|
||||
// final status.
|
||||
func submitAndPoll(t *testing.T, client *Client, request outbound.CodeRunRequest) outbound.CodeRunStatus {
|
||||
t.Helper()
|
||||
started, err := client.Submit(context.Background(), request)
|
||||
if err != nil {
|
||||
t.Fatalf("Submit() error = %v", err)
|
||||
}
|
||||
if started.State != outbound.CodeRunRunning {
|
||||
t.Fatalf("Submit() state = %q, want running", started.State)
|
||||
}
|
||||
finished, err := client.Poll(context.Background(), request)
|
||||
if err != nil {
|
||||
t.Fatalf("Poll() error = %v", err)
|
||||
}
|
||||
return finished
|
||||
}
|
||||
|
||||
func TestClientAcceptedRunSendsOnlyCodeTestsAndLimits(t *testing.T) {
|
||||
fixture := newFixtureRunner(t)
|
||||
request := testRequest()
|
||||
|
||||
status := submitAndPoll(t, fixture.client(t), request)
|
||||
|
||||
if status.State != outbound.CodeRunFinished || status.Result == nil {
|
||||
t.Fatalf("status = %+v, want finished with a result", status)
|
||||
}
|
||||
result := status.Result
|
||||
if result.Outcome != outbound.CodeOutcomeAccepted || len(result.Groups) != 2 || result.Duration != 42*time.Millisecond {
|
||||
t.Fatalf("result = %+v, want accepted over two groups", result)
|
||||
}
|
||||
for _, group := range result.Groups {
|
||||
if group.Outcome != outbound.CodeOutcomeAccepted || group.PassedTests != 2 || group.TotalTests != 2 || len(group.Tests) != 2 {
|
||||
t.Fatalf("group = %+v, want two of two tests accepted", group)
|
||||
}
|
||||
}
|
||||
|
||||
requests := fixture.seen()
|
||||
if len(requests) != 2 || requests[0].Method != http.MethodPut || requests[1].Method != http.MethodGet {
|
||||
t.Fatalf("requests = %d, want PUT then GET", len(requests))
|
||||
}
|
||||
var payload map[string]json.RawMessage
|
||||
if err := json.Unmarshal(requests[0].Body, &payload); err != nil {
|
||||
t.Fatalf("PUT body is not JSON: %v", err)
|
||||
}
|
||||
if len(payload) != 4 || payload["language"] == nil || payload["source"] == nil || payload["limits"] == nil || payload["groups"] == nil {
|
||||
t.Fatalf("PUT body fields = %v, want language, source, limits, groups only", keysOf(payload))
|
||||
}
|
||||
for _, seen := range requests {
|
||||
for _, identifier := range []string{
|
||||
request.Key.AttemptItemID.String(), request.Key.SubmissionID.String(),
|
||||
strings.ReplaceAll(request.Key.AttemptItemID.String(), "-", ""),
|
||||
} {
|
||||
if strings.Contains(seen.Path, identifier) || containsBytes(seen.Body, identifier) || strings.Contains(headerText(seen.Header), identifier) {
|
||||
t.Fatalf("request %s %s carries an attempt or submission identifier", seen.Method, seen.Path)
|
||||
}
|
||||
}
|
||||
if got := seen.Header.Get("Authorization"); got != "Bearer "+testToken {
|
||||
t.Fatalf("Authorization header = %q, want the bearer token", got)
|
||||
}
|
||||
}
|
||||
wantPath := "/v1/runs/" + deriveRunID([]byte(testRunKey), request.Key).String()
|
||||
if requests[0].Path != wantPath || requests[1].Path != wantPath {
|
||||
t.Fatalf("paths = %q and %q, want the derived opaque run ID %q", requests[0].Path, requests[1].Path, wantPath)
|
||||
}
|
||||
if status.RunID != wantPath[len("/v1/runs/"):] {
|
||||
t.Fatalf("status.RunID = %q, want the derived run ID", status.RunID)
|
||||
}
|
||||
}
|
||||
|
||||
func keysOf(values map[string]json.RawMessage) []string {
|
||||
keys := make([]string, 0, len(values))
|
||||
for key := range values {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
func headerText(header http.Header) string {
|
||||
var builder strings.Builder
|
||||
for name, values := range header {
|
||||
builder.WriteString(name + "=" + strings.Join(values, ",") + ";")
|
||||
}
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
func TestClientRetryReusesTheRunAndRunsItOnce(t *testing.T) {
|
||||
fixture := newFixtureRunner(t)
|
||||
client := fixture.client(t)
|
||||
request := testRequest()
|
||||
|
||||
first, err := client.Submit(context.Background(), request)
|
||||
if err != nil {
|
||||
t.Fatalf("first Submit() error = %v", err)
|
||||
}
|
||||
// A retry after a lost answer sends the same payload under the same key.
|
||||
second, err := client.Submit(context.Background(), request)
|
||||
if err != nil {
|
||||
t.Fatalf("second Submit() error = %v", err)
|
||||
}
|
||||
if first.RunID != second.RunID || fixture.startedRuns() != 1 {
|
||||
t.Fatalf("run IDs %q and %q, started runs %d, want one run under one ID", first.RunID, second.RunID, fixture.startedRuns())
|
||||
}
|
||||
|
||||
// The same key with another payload must not change the stored run.
|
||||
changed := testRequest()
|
||||
changed.Source = "print(42)"
|
||||
_, err = client.Submit(context.Background(), changed)
|
||||
if !errors.Is(err, outbound.ErrCodeRunKeyReused) {
|
||||
t.Fatalf("Submit(changed payload) error = %v, want ErrCodeRunKeyReused", err)
|
||||
}
|
||||
if errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
||||
t.Fatalf("a reused key is a caller bug, not an unavailable runner: %v", err)
|
||||
}
|
||||
|
||||
// A new generation starts a new run under a new ID.
|
||||
changed.Key.Generation = 1
|
||||
if _, err := client.Submit(context.Background(), changed); err != nil {
|
||||
t.Fatalf("Submit(next generation) error = %v", err)
|
||||
}
|
||||
if fixture.startedRuns() != 2 {
|
||||
t.Fatalf("started runs = %d, want 2", fixture.startedRuns())
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientReturnsCandidateVerdictsAsResultsNotErrors(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
evaluate func(api.RunRequest) api.RunResult
|
||||
want outbound.CodeRunOutcome
|
||||
}{
|
||||
{"wrong answer", func(r api.RunRequest) api.RunResult {
|
||||
return resultFor(r, map[string]api.RunOutcome{"hidden-1": api.RunOutcomeWrongAnswer})
|
||||
}, outbound.CodeOutcomeWrongAnswer},
|
||||
{"time limit exceeded", func(r api.RunRequest) api.RunResult {
|
||||
return resultFor(r, map[string]api.RunOutcome{"public": api.RunOutcomeTimeLimitExceeded})
|
||||
}, outbound.CodeOutcomeTimeLimitExceeded},
|
||||
{"memory limit exceeded", func(r api.RunRequest) api.RunResult {
|
||||
return resultFor(r, map[string]api.RunOutcome{"hidden-1": api.RunOutcomeMemoryLimitExceeded})
|
||||
}, outbound.CodeOutcomeMemoryLimitExceeded},
|
||||
{"output limit exceeded", func(r api.RunRequest) api.RunResult {
|
||||
return resultFor(r, map[string]api.RunOutcome{"public": api.RunOutcomeOutputLimitExceeded})
|
||||
}, outbound.CodeOutcomeOutputLimitExceeded},
|
||||
{"runtime error", func(r api.RunRequest) api.RunResult {
|
||||
return resultFor(r, map[string]api.RunOutcome{"public": api.RunOutcomeRuntimeError})
|
||||
}, outbound.CodeOutcomeRuntimeError},
|
||||
{"compile error", compileErrorResult, outbound.CodeOutcomeCompileError},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
fixture := newFixtureRunner(t)
|
||||
fixture.evaluate = test.evaluate
|
||||
|
||||
status := submitAndPoll(t, fixture.client(t), testRequest())
|
||||
|
||||
if status.State != outbound.CodeRunFinished || status.Result == nil || status.Result.Outcome != test.want {
|
||||
t.Fatalf("status = %+v, want a finished %s result", status, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientCompileErrorKeepsDiagnosticAndStopsTests(t *testing.T) {
|
||||
fixture := newFixtureRunner(t)
|
||||
fixture.evaluate = compileErrorResult
|
||||
|
||||
result := submitAndPoll(t, fixture.client(t), testRequest()).Result
|
||||
|
||||
if result.Compile == nil || result.Compile.Outcome != outbound.CodeOutcomeCompileError || result.Compile.Diagnostic == "" {
|
||||
t.Fatalf("compile = %+v, want a compile error with a diagnostic", result.Compile)
|
||||
}
|
||||
for _, group := range result.Groups {
|
||||
if group.Outcome != outbound.CodeOutcomeCompileError || len(group.Tests) != 0 || group.PassedTests != 0 || group.TotalTests != 2 {
|
||||
t.Fatalf("group = %+v, want no tests after a compile error", group)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientFailedGroupKeepsOtherGroupsAndDropsHiddenDiagnostics(t *testing.T) {
|
||||
fixture := newFixtureRunner(t)
|
||||
fixture.evaluate = func(request api.RunRequest) api.RunResult {
|
||||
result := resultFor(request, map[string]api.RunOutcome{
|
||||
"public": api.RunOutcomeRuntimeError, "hidden-1": api.RunOutcomeWrongAnswer,
|
||||
})
|
||||
// A faulty runner that leaks a diagnostic of a hidden test.
|
||||
result.Groups[1].Tests[0].Diagnostic = api.NewOptString("expected 300 got 299")
|
||||
return result
|
||||
}
|
||||
|
||||
result := submitAndPoll(t, fixture.client(t), testRequest()).Result
|
||||
|
||||
public, hidden := result.Groups[0], result.Groups[1]
|
||||
if public.Outcome != outbound.CodeOutcomeRuntimeError || public.PassedTests != 0 || public.Tests[0].Diagnostic == "" {
|
||||
t.Fatalf("public group = %+v, want a runtime error with its diagnostic", public)
|
||||
}
|
||||
if hidden.Outcome != outbound.CodeOutcomeWrongAnswer || hidden.Tests[0].Diagnostic != "" {
|
||||
t.Fatalf("hidden group = %+v, want a wrong answer without a diagnostic", hidden)
|
||||
}
|
||||
if result.Outcome != outbound.CodeOutcomeRuntimeError {
|
||||
t.Fatalf("run outcome = %q, want the first failed group's outcome", result.Outcome)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientPollSeesRunningThenFinished(t *testing.T) {
|
||||
fixture := newFixtureRunner(t)
|
||||
fixture.pollsBeforeFinish = 2
|
||||
client := fixture.client(t)
|
||||
request := testRequest()
|
||||
if _, err := client.Submit(context.Background(), request); err != nil {
|
||||
t.Fatalf("Submit() error = %v", err)
|
||||
}
|
||||
|
||||
states := make([]outbound.CodeRunState, 0, 3)
|
||||
for range 3 {
|
||||
status, err := client.Poll(context.Background(), request)
|
||||
if err != nil {
|
||||
t.Fatalf("Poll() error = %v", err)
|
||||
}
|
||||
if status.State == outbound.CodeRunRunning && status.Result != nil {
|
||||
t.Fatalf("a running status carries a result: %+v", status)
|
||||
}
|
||||
states = append(states, status.State)
|
||||
}
|
||||
want := []outbound.CodeRunState{outbound.CodeRunRunning, outbound.CodeRunFinished, outbound.CodeRunFinished}
|
||||
if strings.Join(statesText(states), ",") != strings.Join(statesText(want), ",") {
|
||||
t.Fatalf("states = %v, want %v", states, want)
|
||||
}
|
||||
}
|
||||
|
||||
func statesText(states []outbound.CodeRunState) []string {
|
||||
text := make([]string, 0, len(states))
|
||||
for _, state := range states {
|
||||
text = append(text, string(state))
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
func TestClientBusyKeepsTheKeyAndReportsRetryAfter(t *testing.T) {
|
||||
fixture := newFixtureRunner(t)
|
||||
fixture.busy = true
|
||||
client := fixture.client(t)
|
||||
|
||||
status, err := client.Submit(context.Background(), testRequest())
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Submit() error = %v, want a busy status", err)
|
||||
}
|
||||
if status.State != outbound.CodeRunBusy || status.RetryAfter != 3*time.Second || status.Result != nil {
|
||||
t.Fatalf("status = %+v, want busy with Retry-After 3s", status)
|
||||
}
|
||||
if fixture.startedRuns() != 0 {
|
||||
t.Fatalf("started runs = %d, want none while busy", fixture.startedRuns())
|
||||
}
|
||||
|
||||
fixture.mu.Lock()
|
||||
fixture.busy = false
|
||||
fixture.mu.Unlock()
|
||||
retried, err := client.Submit(context.Background(), testRequest())
|
||||
if err != nil || retried.State != outbound.CodeRunRunning || retried.RunID != status.RunID {
|
||||
t.Fatalf("retry = %+v, %v, want the run started under the same ID", retried, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientRunnerInfrastructureFailureIsNotAVerdict(t *testing.T) {
|
||||
fixture := newFixtureRunner(t)
|
||||
fixture.evaluate = func(request api.RunRequest) api.RunResult {
|
||||
return uniformResult(request, api.RunOutcomeInfrastructureFailure)
|
||||
}
|
||||
client := fixture.client(t)
|
||||
request := testRequest()
|
||||
if _, err := client.Submit(context.Background(), request); err != nil {
|
||||
t.Fatalf("Submit() error = %v", err)
|
||||
}
|
||||
|
||||
status, err := client.Poll(context.Background(), request)
|
||||
|
||||
if !errors.Is(err, outbound.ErrCodeRunnerInfrastructureFailure) || !errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
||||
t.Fatalf("Poll() error = %v, want ErrCodeRunnerInfrastructureFailure under ErrCodeRunnerUnavailable", err)
|
||||
}
|
||||
if status != (outbound.CodeRunStatus{}) {
|
||||
t.Fatalf("Poll() status = %+v, want the zero status next to an error", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientMapsRunnerErrorsToInfrastructureErrors(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
answer func(http.ResponseWriter)
|
||||
want error
|
||||
}{
|
||||
{"wrong token", func(w http.ResponseWriter) {
|
||||
writeProblem(w, http.StatusUnauthorized, api.ProblemCodeUnauthenticated, nil)
|
||||
}, outbound.ErrCodeRunnerUnauthorized},
|
||||
{"internal error", func(w http.ResponseWriter) {
|
||||
writeProblem(w, http.StatusInternalServerError, api.ProblemCodeInternal, nil)
|
||||
}, outbound.ErrCodeRunnerUnavailable},
|
||||
{"bad gateway page", func(w http.ResponseWriter) {
|
||||
writeJSON(w, http.StatusBadGateway, "text/html", []byte("<html>502</html>"), nil)
|
||||
}, outbound.ErrCodeRunnerBadResponse},
|
||||
{"busy without Retry-After", func(w http.ResponseWriter) {
|
||||
writeProblem(w, http.StatusServiceUnavailable, api.ProblemCodeRunnerBusy, nil)
|
||||
}, outbound.ErrCodeRunnerBadResponse},
|
||||
{"503 that is not busy", func(w http.ResponseWriter) {
|
||||
writeProblem(w, http.StatusServiceUnavailable, api.ProblemCodeInternal, http.Header{"Retry-After": {"1"}})
|
||||
}, outbound.ErrCodeRunnerUnavailable},
|
||||
{"runner rejects the payload", func(w http.ResponseWriter) {
|
||||
writeProblem(w, http.StatusBadRequest, api.ProblemCodeValidationFailed, nil)
|
||||
}, outbound.ErrInvalidCodeRunRequest},
|
||||
{"payload too large", func(w http.ResponseWriter) {
|
||||
writeProblem(w, http.StatusRequestEntityTooLarge, api.ProblemCodePayloadTooLarge, nil)
|
||||
}, outbound.ErrInvalidCodeRunRequest},
|
||||
{"unsupported media type", func(w http.ResponseWriter) {
|
||||
writeProblem(w, http.StatusUnsupportedMediaType, api.ProblemCodeUnsupportedMediaType, nil)
|
||||
}, outbound.ErrCodeRunnerBadResponse},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
fixture := newFixtureRunner(t)
|
||||
fixture.override = func(w http.ResponseWriter, _ *http.Request) bool {
|
||||
test.answer(w)
|
||||
return true
|
||||
}
|
||||
|
||||
status, err := fixture.client(t).Submit(context.Background(), testRequest())
|
||||
|
||||
if !errors.Is(err, test.want) {
|
||||
t.Fatalf("Submit() error = %v, want %v", err, test.want)
|
||||
}
|
||||
if !errors.Is(err, outbound.ErrInvalidCodeRunRequest) && !errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
||||
t.Fatalf("Submit() error = %v, want it under ErrCodeRunnerUnavailable", err)
|
||||
}
|
||||
if status != (outbound.CodeRunStatus{}) {
|
||||
t.Fatalf("status = %+v, want the zero status next to an error", status)
|
||||
}
|
||||
if strings.Contains(err.Error(), testToken) || strings.Contains(err.Error(), fixture.server.URL) {
|
||||
t.Fatalf("error exposes the token or the runner URL: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientPollReportsALostRun(t *testing.T) {
|
||||
fixture := newFixtureRunner(t)
|
||||
|
||||
status, err := fixture.client(t).Poll(context.Background(), testRequest())
|
||||
|
||||
if !errors.Is(err, outbound.ErrCodeRunNotFound) || errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
||||
t.Fatalf("Poll() error = %v, want ErrCodeRunNotFound only", err)
|
||||
}
|
||||
if status != (outbound.CodeRunStatus{}) {
|
||||
t.Fatalf("status = %+v, want the zero status", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientRejectsMalformedResponses(t *testing.T) {
|
||||
good := func(request api.RunRequest) api.RunResult { return resultFor(request, nil) }
|
||||
tests := []struct {
|
||||
name string
|
||||
// raw answers GET with a raw body instead of the protocol.
|
||||
raw string
|
||||
evaluate func(api.RunRequest) api.RunResult
|
||||
mutate func(*api.RunResult)
|
||||
}{
|
||||
{name: "not JSON", raw: "{not json"},
|
||||
{name: "empty body", raw: ""},
|
||||
{name: "unknown outcome", raw: `{"run_id":"%s","state":"finished","result":{"outcome":"great","groups":[],"duration_ms":1}}`},
|
||||
{name: "finished without a result", raw: `{"run_id":"%s","state":"finished"}`},
|
||||
{name: "running with a result", raw: `{"run_id":"%s","state":"running","result":{"outcome":"accepted","groups":[],"duration_ms":1}}`},
|
||||
{name: "another run ID", raw: `{"run_id":"11111111-1111-4111-8111-111111111111","state":"running"}`},
|
||||
{name: "unknown state", raw: `{"run_id":"%s","state":"queued"}`},
|
||||
{name: "trailing data", raw: `{"run_id":"%s","state":"running"} {}`},
|
||||
{name: "missing group", evaluate: good, mutate: func(r *api.RunResult) { r.Groups = r.Groups[:1] }},
|
||||
{name: "wrong group ID", evaluate: good, mutate: func(r *api.RunResult) { r.Groups[0].ID = "other" }},
|
||||
{name: "wrong visibility", evaluate: good, mutate: func(r *api.RunResult) { r.Groups[1].Visibility = api.TestVisibilityPublic }},
|
||||
{name: "wrong total", evaluate: good, mutate: func(r *api.RunResult) { r.Groups[0].TotalTests = 3 }},
|
||||
{name: "passed above evaluated", evaluate: good, mutate: func(r *api.RunResult) { r.Groups[0].PassedTests = 1 }},
|
||||
{name: "wrong test ID", evaluate: good, mutate: func(r *api.RunResult) { r.Groups[0].Tests[1].ID = "9" }},
|
||||
{name: "accepted run with a failed group", evaluate: good, mutate: func(r *api.RunResult) {
|
||||
r.Groups[1].Outcome = api.RunOutcomeWrongAnswer
|
||||
r.Groups[1].Tests[1].Outcome = api.RunOutcomeWrongAnswer
|
||||
r.Groups[1].PassedTests = 1
|
||||
}},
|
||||
{name: "accepted group with a missing test", evaluate: good, mutate: func(r *api.RunResult) {
|
||||
r.Groups[0].Tests = r.Groups[0].Tests[:1]
|
||||
r.Groups[0].PassedTests = 1
|
||||
}},
|
||||
{name: "test after a failed one", evaluate: good, mutate: func(r *api.RunResult) {
|
||||
r.Outcome = api.RunOutcomeWrongAnswer
|
||||
r.Groups[0].Outcome = api.RunOutcomeWrongAnswer
|
||||
r.Groups[0].Tests[0].Outcome = api.RunOutcomeWrongAnswer
|
||||
r.Groups[0].PassedTests = 0
|
||||
}},
|
||||
{name: "infrastructure outcome in a test", evaluate: good, mutate: func(r *api.RunResult) {
|
||||
r.Groups[0].Tests[1].Outcome = api.RunOutcomeInfrastructureFailure
|
||||
}},
|
||||
{name: "compile error without compile result", evaluate: compileErrorResult, mutate: func(r *api.RunResult) { r.Compile = api.OptCompileResult{} }},
|
||||
{name: "compile error with tests", evaluate: compileErrorResult, mutate: func(r *api.RunResult) {
|
||||
r.Groups[0].Tests = []api.TestResult{{ID: "1", Outcome: api.RunOutcomeAccepted}}
|
||||
}},
|
||||
{name: "accepted run with a failed compile", evaluate: good, mutate: func(r *api.RunResult) {
|
||||
r.Compile = api.NewOptCompileResult(api.CompileResult{Outcome: api.RunOutcomeCompileError})
|
||||
}},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
fixture := newFixtureRunner(t)
|
||||
if test.evaluate != nil {
|
||||
fixture.evaluate = func(request api.RunRequest) api.RunResult {
|
||||
result := test.evaluate(request)
|
||||
test.mutate(&result)
|
||||
return result
|
||||
}
|
||||
}
|
||||
client := fixture.client(t)
|
||||
request := testRequest()
|
||||
if _, err := client.Submit(context.Background(), request); err != nil {
|
||||
t.Fatalf("Submit() error = %v", err)
|
||||
}
|
||||
if test.raw != "" || test.name == "empty body" {
|
||||
runID := deriveRunID([]byte(testRunKey), request.Key).String()
|
||||
body := strings.ReplaceAll(test.raw, "%s", runID)
|
||||
fixture.override = func(w http.ResponseWriter, r *http.Request) bool {
|
||||
if r.Method != http.MethodGet {
|
||||
return false
|
||||
}
|
||||
writeJSON(w, http.StatusOK, "application/json", []byte(body), nil)
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
status, err := client.Poll(context.Background(), request)
|
||||
|
||||
if !errors.Is(err, outbound.ErrCodeRunnerBadResponse) || !errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
||||
t.Fatalf("Poll() = %+v, %v, want ErrCodeRunnerBadResponse", status, err)
|
||||
}
|
||||
if status != (outbound.CodeRunStatus{}) {
|
||||
t.Fatalf("status = %+v, want the zero status next to an error", status)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientRejectsAnAcceptedAnswerThatIsFinished(t *testing.T) {
|
||||
fixture := newFixtureRunner(t)
|
||||
fixture.override = func(w http.ResponseWriter, r *http.Request) bool {
|
||||
if r.Method != http.MethodPut {
|
||||
return false
|
||||
}
|
||||
runID := strings.TrimPrefix(r.URL.Path, "/v1/runs/")
|
||||
body := `{"run_id":"` + runID + `","state":"finished","result":{"outcome":"accepted","groups":[],"duration_ms":1}}`
|
||||
writeJSON(w, http.StatusAccepted, "application/json", []byte(body), nil)
|
||||
return true
|
||||
}
|
||||
|
||||
_, err := fixture.client(t).Submit(context.Background(), testRequest())
|
||||
|
||||
if !errors.Is(err, outbound.ErrCodeRunnerBadResponse) {
|
||||
t.Fatalf("Submit() error = %v, want ErrCodeRunnerBadResponse", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientRejectsAnOversizedResponse(t *testing.T) {
|
||||
fixture := newFixtureRunner(t)
|
||||
fixture.override = func(w http.ResponseWriter, _ *http.Request) bool {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
filler := []byte(strings.Repeat(" ", 1<<20))
|
||||
for range 6 {
|
||||
if _, err := w.Write(filler); err != nil {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
_, err := fixture.client(t).Poll(context.Background(), testRequest())
|
||||
|
||||
if !errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
||||
t.Fatalf("Poll() error = %v, want an infrastructure error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientTimesOutWithoutAVerdict(t *testing.T) {
|
||||
fixture := newFixtureRunner(t)
|
||||
fixture.override = func(_ http.ResponseWriter, r *http.Request) bool {
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
case <-time.After(5 * time.Second):
|
||||
}
|
||||
return true
|
||||
}
|
||||
settings := fixture.settings()
|
||||
settings.RequestTimeout = 150 * time.Millisecond
|
||||
client, err := NewClient(settings)
|
||||
if err != nil {
|
||||
t.Fatalf("NewClient() error = %v", err)
|
||||
}
|
||||
|
||||
status, err := client.Submit(context.Background(), testRequest())
|
||||
|
||||
if !errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
||||
t.Fatalf("Submit() error = %v, want ErrCodeRunnerUnavailable", err)
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, outbound.ErrCodeRunNotFound) {
|
||||
t.Fatalf("Submit() error = %v, want a runner timeout, not the caller's deadline", err)
|
||||
}
|
||||
if status != (outbound.CodeRunStatus{}) {
|
||||
t.Fatalf("status = %+v, want the zero status", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientReportsTheCallerContext(t *testing.T) {
|
||||
fixture := newFixtureRunner(t)
|
||||
client := fixture.client(t)
|
||||
|
||||
canceled, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_, err := client.Submit(canceled, testRequest())
|
||||
if !errors.Is(err, context.Canceled) || errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
||||
t.Fatalf("Submit(canceled) error = %v, want context.Canceled only", err)
|
||||
}
|
||||
if len(fixture.seen()) != 0 {
|
||||
t.Fatal("a canceled context still reached the runner")
|
||||
}
|
||||
|
||||
fixture.override = func(_ http.ResponseWriter, r *http.Request) bool {
|
||||
<-r.Context().Done()
|
||||
return true
|
||||
}
|
||||
deadline, cancelDeadline := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancelDeadline()
|
||||
_, err = client.Poll(deadline, testRequest())
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("Poll(deadline) error = %v, want context.DeadlineExceeded", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientStoppedRunnerIsUnavailableWithoutAVerdict(t *testing.T) {
|
||||
fixture := newFixtureRunner(t)
|
||||
client := fixture.client(t)
|
||||
fixture.server.Close()
|
||||
|
||||
for name, call := range map[string]func(context.Context, outbound.CodeRunRequest) (outbound.CodeRunStatus, error){
|
||||
"Submit": client.Submit, "Poll": client.Poll,
|
||||
} {
|
||||
status, err := call(context.Background(), testRequest())
|
||||
if !errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
||||
t.Fatalf("%s() error = %v, want ErrCodeRunnerUnavailable", name, err)
|
||||
}
|
||||
// Nothing a caller could read as a verdict or as progress.
|
||||
if status != (outbound.CodeRunStatus{}) || status.Result != nil || status.State != "" {
|
||||
t.Fatalf("%s() status = %+v, want the zero status", name, status)
|
||||
}
|
||||
if strings.Contains(err.Error(), fixture.server.URL) || strings.Contains(err.Error(), testToken) {
|
||||
t.Fatalf("%s() error exposes the runner URL or the token: %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientVerifiesTheRunnerCertificateAgainstTheConfiguredCA(t *testing.T) {
|
||||
fixture := newFixtureRunner(t)
|
||||
|
||||
settings := fixture.settings()
|
||||
settings.CAPEM = foreignCAPEM(t) // a CA that did not sign this runner
|
||||
client, err := NewClient(settings)
|
||||
if err != nil {
|
||||
t.Fatalf("NewClient() error = %v", err)
|
||||
}
|
||||
|
||||
_, err = client.Submit(context.Background(), testRequest())
|
||||
|
||||
if !errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
||||
t.Fatalf("Submit() error = %v, want ErrCodeRunnerUnavailable", err)
|
||||
}
|
||||
if len(fixture.seen()) != 0 {
|
||||
t.Fatal("the request reached a runner whose certificate does not match the CA, so the token was sent to it")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientRefusesRunnerWithoutTLS13(t *testing.T) {
|
||||
fixture := newFixtureRunner(t)
|
||||
fixture.server.Close()
|
||||
legacy := httptest.NewUnstartedServer(http.HandlerFunc(fixture.serve))
|
||||
legacy.TLS = &tls.Config{MinVersion: tls.VersionTLS12, MaxVersion: tls.VersionTLS12}
|
||||
legacy.StartTLS()
|
||||
t.Cleanup(legacy.Close)
|
||||
// The servers share one certificate, which the CA trusts, so the only
|
||||
// reason left to fail is the protocol version.
|
||||
settings := fixture.settings()
|
||||
settings.BaseURL = legacy.URL
|
||||
client, err := NewClient(settings)
|
||||
if err != nil {
|
||||
t.Fatalf("NewClient() error = %v", err)
|
||||
}
|
||||
|
||||
_, err = client.Submit(context.Background(), testRequest())
|
||||
|
||||
if !errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
||||
t.Fatalf("Submit() error = %v, want ErrCodeRunnerUnavailable", err)
|
||||
}
|
||||
if len(fixture.seen()) != 0 {
|
||||
t.Fatal("a TLS 1.2 connection carried the request")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientRejectsInvalidRequestsBeforeSending(t *testing.T) {
|
||||
fixture := newFixtureRunner(t)
|
||||
client := fixture.client(t)
|
||||
request := testRequest()
|
||||
request.Limits.TimeLimitMs = 10
|
||||
|
||||
for name, call := range map[string]func(context.Context, outbound.CodeRunRequest) (outbound.CodeRunStatus, error){
|
||||
"Submit": client.Submit, "Poll": client.Poll,
|
||||
} {
|
||||
_, err := call(context.Background(), request)
|
||||
if !errors.Is(err, outbound.ErrInvalidCodeRunRequest) || errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
||||
t.Fatalf("%s() error = %v, want ErrInvalidCodeRunRequest only", name, err)
|
||||
}
|
||||
}
|
||||
if len(fixture.seen()) != 0 {
|
||||
t.Fatal("an invalid request reached the runner")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewClientValidatesSettings(t *testing.T) {
|
||||
fixture := newFixtureRunner(t)
|
||||
valid := fixture.settings()
|
||||
tests := []struct {
|
||||
name string
|
||||
change func(*Settings)
|
||||
}{
|
||||
{"plain http", func(s *Settings) { s.BaseURL = "http://runner.internal:8443" }},
|
||||
{"path in URL", func(s *Settings) { s.BaseURL = "https://runner.internal:8443/api" }},
|
||||
{"credentials in URL", func(s *Settings) { s.BaseURL = "https://user:pass@runner.internal" }},
|
||||
{"no host", func(s *Settings) { s.BaseURL = "https://" }},
|
||||
{"empty token", func(s *Settings) { s.Token = "" }},
|
||||
{"token with space", func(s *Settings) { s.Token = "bad token" }},
|
||||
{"short run key", func(s *Settings) { s.RunKey = "short" }},
|
||||
{"no CA", func(s *Settings) { s.CAPEM = nil }},
|
||||
{"CA that is not PEM", func(s *Settings) { s.CAPEM = []byte("not a certificate") }},
|
||||
{"zero timeout", func(s *Settings) { s.RequestTimeout = 0 }},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
settings := valid
|
||||
test.change(&settings)
|
||||
|
||||
client, err := NewClient(settings)
|
||||
|
||||
if err == nil || client != nil {
|
||||
t.Fatalf("NewClient() = %v, %v, want an error", client, err)
|
||||
}
|
||||
if strings.Contains(err.Error(), testToken) || strings.Contains(err.Error(), testRunKey) {
|
||||
t.Fatalf("error exposes a secret: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsRedactSecrets(t *testing.T) {
|
||||
settings := Settings{BaseURL: "https://runner", Token: testToken, RunKey: testRunKey}
|
||||
for _, rendered := range []string{
|
||||
settings.String(), settings.LogValue().String(),
|
||||
formatWith("%v", settings), formatWith("%+v", settings), formatWith("%#v", settings),
|
||||
} {
|
||||
if strings.Contains(rendered, testToken) || strings.Contains(rendered, testRunKey) {
|
||||
t.Fatalf("settings rendering exposes a secret: %q", rendered)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// Package disabled provides the code runner for an unset CODE_RUNNER_URL.
|
||||
package disabled
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// Runner runs nothing. Every valid request is reported as
|
||||
// outbound.ErrCodeRunnerDisabled, never as a verdict, so a caller cannot grade
|
||||
// a submission while the practice runner is off.
|
||||
type Runner struct{}
|
||||
|
||||
var _ outbound.CodeRunner = (*Runner)(nil)
|
||||
|
||||
func NewRunner() *Runner {
|
||||
return &Runner{}
|
||||
}
|
||||
|
||||
// Submit validates the request first so that local runs without a runner
|
||||
// still expose invalid task content, then reports the runner as disabled. It
|
||||
// logs nothing and keeps no copy of the source or the tests.
|
||||
func (runner *Runner) Submit(_ context.Context, request outbound.CodeRunRequest) (outbound.CodeRunStatus, error) {
|
||||
return outbound.CodeRunStatus{}, refuse("Runner.Submit", request)
|
||||
}
|
||||
|
||||
// Poll behaves like Submit.
|
||||
func (runner *Runner) Poll(_ context.Context, request outbound.CodeRunRequest) (outbound.CodeRunStatus, error) {
|
||||
return outbound.CodeRunStatus{}, refuse("Runner.Poll", request)
|
||||
}
|
||||
|
||||
func refuse(location string, request outbound.CodeRunRequest) error {
|
||||
if err := request.Validate(); err != nil {
|
||||
return fmt.Errorf("%s - validate request: %w", location, err)
|
||||
}
|
||||
return fmt.Errorf("%s - CODE_RUNNER_URL is not set: %w", location, outbound.ErrCodeRunnerDisabled)
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package disabled_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/code_runner/disabled"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const secretSource = "print('secret-source-marker')"
|
||||
|
||||
func validRequest() outbound.CodeRunRequest {
|
||||
return outbound.CodeRunRequest{
|
||||
Key: outbound.CodeRunKey{AttemptItemID: uuid.New(), SubmissionID: uuid.New()},
|
||||
Language: outbound.CodeLanguagePython3,
|
||||
Source: secretSource,
|
||||
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: "1\n", ExpectedOutput: "1\n"}},
|
||||
}},
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerReportsDisabledAndNeverAVerdict(t *testing.T) {
|
||||
canceled, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
runner := disabled.NewRunner()
|
||||
|
||||
for name, ctx := range map[string]context.Context{"active context": context.Background(), "canceled context": canceled} {
|
||||
for method, call := range map[string]func(context.Context, outbound.CodeRunRequest) (outbound.CodeRunStatus, error){
|
||||
"Submit": runner.Submit, "Poll": runner.Poll,
|
||||
} {
|
||||
status, err := call(ctx, validRequest())
|
||||
if !errors.Is(err, outbound.ErrCodeRunnerDisabled) || !errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
||||
t.Fatalf("%s %s error = %v, want ErrCodeRunnerDisabled under ErrCodeRunnerUnavailable", name, method, err)
|
||||
}
|
||||
if status != (outbound.CodeRunStatus{}) || status.Result != nil {
|
||||
t.Fatalf("%s %s status = %+v, want the zero status", name, method, status)
|
||||
}
|
||||
if strings.Contains(err.Error(), "secret-source-marker") {
|
||||
t.Fatalf("%s %s error exposes the source: %v", name, method, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerRejectsInvalidRequestsBeforeReportingDisabled(t *testing.T) {
|
||||
_, err := disabled.NewRunner().Submit(context.Background(), outbound.CodeRunRequest{})
|
||||
|
||||
if !errors.Is(err, outbound.ErrInvalidCodeRunRequest) || errors.Is(err, outbound.ErrCodeRunnerDisabled) {
|
||||
t.Fatalf("Submit(empty) error = %v, want ErrInvalidCodeRunRequest only", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
package coderunner
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/pem"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/code_runner/api"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
testToken = "test-token-0123456789abcdef0123456789abcdef"
|
||||
testRunKey = "test-run-key-0123456789abcdef0123456789abcdef"
|
||||
)
|
||||
|
||||
// recordedRequest is what the fixture saw on the wire.
|
||||
type recordedRequest struct {
|
||||
Method string
|
||||
Path string
|
||||
Header http.Header
|
||||
Body []byte
|
||||
}
|
||||
|
||||
// fixtureRunner is a local stand-in for the runner that speaks the protocol
|
||||
// of api/runner over TLS 1.3: bearer token, PUT and GET of /v1/runs/{id},
|
||||
// idempotency by payload fingerprint, and the busy answer.
|
||||
type fixtureRunner struct {
|
||||
server *httptest.Server
|
||||
|
||||
mu sync.Mutex
|
||||
runs map[string]*fixtureRun
|
||||
requests []recordedRequest
|
||||
started int
|
||||
|
||||
// busy makes PUT of a new run answer 503 runner_busy.
|
||||
busy bool
|
||||
// pollsBeforeFinish is the number of GET calls that still see running.
|
||||
pollsBeforeFinish int
|
||||
// evaluate produces the result of a started run.
|
||||
evaluate func(request api.RunRequest) api.RunResult
|
||||
// override, when set, answers before the protocol does; it reports whether
|
||||
// it handled the request.
|
||||
override func(writer http.ResponseWriter, request *http.Request) bool
|
||||
}
|
||||
|
||||
type fixtureRun struct {
|
||||
fingerprint [sha256.Size]byte
|
||||
result api.RunResult
|
||||
polls int
|
||||
}
|
||||
|
||||
func newFixtureRunner(t *testing.T) *fixtureRunner {
|
||||
t.Helper()
|
||||
fixture := &fixtureRunner{
|
||||
runs: make(map[string]*fixtureRun),
|
||||
evaluate: func(request api.RunRequest) api.RunResult { return resultFor(request, nil) },
|
||||
}
|
||||
fixture.server = httptest.NewUnstartedServer(http.HandlerFunc(fixture.serve))
|
||||
fixture.server.TLS = &tls.Config{MinVersion: tls.VersionTLS13}
|
||||
fixture.server.StartTLS()
|
||||
t.Cleanup(fixture.server.Close)
|
||||
return fixture
|
||||
}
|
||||
|
||||
func (fixture *fixtureRunner) caPEM() []byte {
|
||||
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: fixture.server.Certificate().Raw})
|
||||
}
|
||||
|
||||
func (fixture *fixtureRunner) settings() Settings {
|
||||
return Settings{
|
||||
BaseURL: fixture.server.URL,
|
||||
Token: testToken,
|
||||
RunKey: testRunKey,
|
||||
CAPEM: fixture.caPEM(),
|
||||
RequestTimeout: 2 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
func (fixture *fixtureRunner) client(t *testing.T) *Client {
|
||||
t.Helper()
|
||||
client, err := NewClient(fixture.settings())
|
||||
if err != nil {
|
||||
t.Fatalf("NewClient() error = %v", err)
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
func (fixture *fixtureRunner) startedRuns() int {
|
||||
fixture.mu.Lock()
|
||||
defer fixture.mu.Unlock()
|
||||
return fixture.started
|
||||
}
|
||||
|
||||
func (fixture *fixtureRunner) seen() []recordedRequest {
|
||||
fixture.mu.Lock()
|
||||
defer fixture.mu.Unlock()
|
||||
return append([]recordedRequest(nil), fixture.requests...)
|
||||
}
|
||||
|
||||
func (fixture *fixtureRunner) serve(writer http.ResponseWriter, request *http.Request) {
|
||||
body, _ := io.ReadAll(request.Body)
|
||||
fixture.mu.Lock()
|
||||
fixture.requests = append(fixture.requests, recordedRequest{
|
||||
Method: request.Method, Path: request.URL.Path, Header: request.Header.Clone(), Body: body,
|
||||
})
|
||||
override := fixture.override
|
||||
fixture.mu.Unlock()
|
||||
|
||||
if override != nil && override(writer, request) {
|
||||
return
|
||||
}
|
||||
if request.Header.Get("Authorization") != "Bearer "+testToken {
|
||||
writeProblem(writer, http.StatusUnauthorized, api.ProblemCodeUnauthenticated, nil)
|
||||
return
|
||||
}
|
||||
runID := strings.TrimPrefix(request.URL.Path, "/v1/runs/")
|
||||
switch request.Method {
|
||||
case http.MethodPut:
|
||||
fixture.put(writer, runID, body)
|
||||
case http.MethodGet:
|
||||
fixture.get(writer, runID)
|
||||
default:
|
||||
writeProblem(writer, http.StatusMethodNotAllowed, api.ProblemCodeMethodNotAllowed, nil)
|
||||
}
|
||||
}
|
||||
|
||||
func (fixture *fixtureRunner) put(writer http.ResponseWriter, runID string, body []byte) {
|
||||
var payload api.RunRequest
|
||||
if err := payload.UnmarshalJSON(body); err != nil {
|
||||
writeProblem(writer, http.StatusBadRequest, api.ProblemCodeValidationFailed, nil)
|
||||
return
|
||||
}
|
||||
fingerprint := sha256.Sum256(body)
|
||||
|
||||
fixture.mu.Lock()
|
||||
defer fixture.mu.Unlock()
|
||||
if existing, ok := fixture.runs[runID]; ok {
|
||||
if existing.fingerprint != fingerprint {
|
||||
writeProblem(writer, http.StatusUnprocessableEntity, api.ProblemCodeIdempotencyKeyReused, nil)
|
||||
return
|
||||
}
|
||||
writeStatus(writer, http.StatusOK, existing.status(runID, fixture.pollsBeforeFinish))
|
||||
return
|
||||
}
|
||||
if fixture.busy {
|
||||
writeProblem(writer, http.StatusServiceUnavailable, api.ProblemCodeRunnerBusy, http.Header{"Retry-After": {"3"}})
|
||||
return
|
||||
}
|
||||
run := &fixtureRun{fingerprint: fingerprint, result: fixture.evaluate(payload)}
|
||||
fixture.runs[runID] = run
|
||||
fixture.started++
|
||||
parsed := uuid.MustParse(runID)
|
||||
writeStatus(writer, http.StatusAccepted, api.RunStatus{RunID: parsed, State: api.RunStateRunning})
|
||||
}
|
||||
|
||||
func (fixture *fixtureRunner) get(writer http.ResponseWriter, runID string) {
|
||||
fixture.mu.Lock()
|
||||
defer fixture.mu.Unlock()
|
||||
run, ok := fixture.runs[runID]
|
||||
if !ok {
|
||||
writeProblem(writer, http.StatusNotFound, api.ProblemCodeNotFound, nil)
|
||||
return
|
||||
}
|
||||
run.polls++
|
||||
writeStatus(writer, http.StatusOK, run.status(runID, fixture.pollsBeforeFinish))
|
||||
}
|
||||
|
||||
func (run *fixtureRun) status(runID string, pollsBeforeFinish int) api.RunStatus {
|
||||
status := api.RunStatus{RunID: uuid.MustParse(runID), State: api.RunStateRunning}
|
||||
if run.polls >= pollsBeforeFinish {
|
||||
status.State = api.RunStateFinished
|
||||
status.Result = api.NewOptRunResult(run.result)
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
func writeStatus(writer http.ResponseWriter, code int, status api.RunStatus) {
|
||||
// The generated types encode themselves; json.Marshal cannot encode an
|
||||
// unset optional field.
|
||||
body, err := status.MarshalJSON()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
writeJSON(writer, code, "application/json", body, nil)
|
||||
}
|
||||
|
||||
func writeProblem(writer http.ResponseWriter, code int, problem api.ProblemCode, header http.Header) {
|
||||
body, err := (&api.Problem{
|
||||
Type: "urn:lincodex:problem:" + string(problem),
|
||||
Title: "Problem",
|
||||
Status: int32(code),
|
||||
Code: problem,
|
||||
}).MarshalJSON()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
writeJSON(writer, code, "application/problem+json", body, header)
|
||||
}
|
||||
|
||||
func writeJSON(writer http.ResponseWriter, code int, contentType string, body []byte, header http.Header) {
|
||||
for name, values := range header {
|
||||
for _, value := range values {
|
||||
writer.Header().Add(name, value)
|
||||
}
|
||||
}
|
||||
writer.Header().Set("Content-Type", contentType)
|
||||
writer.Header().Set("Content-Length", strconv.Itoa(len(body)))
|
||||
writer.WriteHeader(code)
|
||||
_, _ = writer.Write(body)
|
||||
}
|
||||
|
||||
// resultFor builds the runner result for a request. failures maps a group ID
|
||||
// to the outcome of its first test; other groups pass.
|
||||
func resultFor(request api.RunRequest, failures map[string]api.RunOutcome) api.RunResult {
|
||||
result := api.RunResult{Outcome: api.RunOutcomeAccepted, DurationMs: 42}
|
||||
for _, group := range request.Groups {
|
||||
groupResult := api.GroupResult{
|
||||
ID: group.ID, Visibility: group.Visibility, Outcome: api.RunOutcomeAccepted,
|
||||
TotalTests: int32(len(group.Tests)),
|
||||
}
|
||||
failure, failed := failures[string(group.ID)]
|
||||
for index, test := range group.Tests {
|
||||
testResult := api.TestResult{ID: test.ID, Outcome: api.RunOutcomeAccepted, TimeMs: 5, WallTimeMs: 7, MemoryKB: 2048}
|
||||
if failed && index == 0 {
|
||||
testResult.Outcome = failure
|
||||
if group.Visibility == api.TestVisibilityPublic {
|
||||
testResult.Diagnostic = api.NewOptString("stderr excerpt")
|
||||
}
|
||||
groupResult.Outcome = failure
|
||||
groupResult.Tests = append(groupResult.Tests, testResult)
|
||||
break
|
||||
}
|
||||
groupResult.PassedTests++
|
||||
groupResult.Tests = append(groupResult.Tests, testResult)
|
||||
}
|
||||
if result.Outcome == api.RunOutcomeAccepted {
|
||||
result.Outcome = groupResult.Outcome
|
||||
}
|
||||
result.Groups = append(result.Groups, groupResult)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// uniformResult gives every group the outcome of a run that stopped early.
|
||||
func uniformResult(request api.RunRequest, outcome api.RunOutcome) api.RunResult {
|
||||
result := api.RunResult{Outcome: outcome, DurationMs: 3}
|
||||
for _, group := range request.Groups {
|
||||
result.Groups = append(result.Groups, api.GroupResult{
|
||||
ID: group.ID, Visibility: group.Visibility, Outcome: outcome,
|
||||
TotalTests: int32(len(group.Tests)),
|
||||
Tests: []api.TestResult{},
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func compileErrorResult(request api.RunRequest) api.RunResult {
|
||||
result := uniformResult(request, api.RunOutcomeCompileError)
|
||||
result.Compile = api.NewOptCompileResult(api.CompileResult{
|
||||
Outcome: api.RunOutcomeCompileError, Diagnostic: api.NewOptString("syntax error on line 1"),
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
func testRequest() outbound.CodeRunRequest {
|
||||
return outbound.CodeRunRequest{
|
||||
Key: outbound.CodeRunKey{
|
||||
AttemptItemID: uuid.MustParse("0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d"),
|
||||
SubmissionID: uuid.MustParse("5f4e3d2c-1b0a-4f9e-8d7c-6b5a49382716"),
|
||||
},
|
||||
Language: outbound.CodeLanguagePython3,
|
||||
Source: "print(sum(map(int, input().split())))",
|
||||
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: "1 2\n", ExpectedOutput: "3\n"},
|
||||
{ID: "2", Input: "5 7\n", ExpectedOutput: "12\n"},
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "hidden-1", Visibility: outbound.CodeTestHidden,
|
||||
Checker: outbound.CodeChecker{Kind: outbound.CodeCheckerTokens},
|
||||
Tests: []outbound.CodeTest{
|
||||
{ID: "1", Input: "100 200\n", ExpectedOutput: "300\n"},
|
||||
{ID: "2", Input: "-4 4\n", ExpectedOutput: "0\n"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func containsBytes(haystack []byte, needle string) bool {
|
||||
return bytes.Contains(haystack, []byte(needle))
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package coderunner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// The live test runs fixed harmless programs on a real, prepared runner. It is
|
||||
// skipped unless CODE_RUNNER_LIVE_URL is set; `make -C backend
|
||||
// test-code-runner-live` sets the variables from CODE_RUNNER_URL,
|
||||
// CODE_RUNNER_TOKEN, and CODE_RUNNER_CA_FILE. The runner receives only the
|
||||
// tiny programs below and random run IDs.
|
||||
const liveRunTimeout = 90 * time.Second
|
||||
|
||||
// liveSettings reads the runner under test from the environment; the run key
|
||||
// is random, so no two test runs share run IDs.
|
||||
func liveSettings(t *testing.T) Settings {
|
||||
t.Helper()
|
||||
url := os.Getenv("CODE_RUNNER_LIVE_URL")
|
||||
if url == "" {
|
||||
t.Skip("CODE_RUNNER_LIVE_URL is not set; the live runner test is skipped")
|
||||
}
|
||||
token := os.Getenv("CODE_RUNNER_LIVE_TOKEN")
|
||||
caFile := os.Getenv("CODE_RUNNER_LIVE_CA_FILE")
|
||||
if token == "" || caFile == "" {
|
||||
t.Fatal("CODE_RUNNER_LIVE_TOKEN and CODE_RUNNER_LIVE_CA_FILE must be set with CODE_RUNNER_LIVE_URL")
|
||||
}
|
||||
caPEM, err := os.ReadFile(caFile)
|
||||
if err != nil {
|
||||
t.Fatalf("read CODE_RUNNER_LIVE_CA_FILE: %v", err)
|
||||
}
|
||||
runKey := make([]byte, 32)
|
||||
if _, err := rand.Read(runKey); err != nil {
|
||||
t.Fatalf("rand.Read() error = %v", err)
|
||||
}
|
||||
return Settings{
|
||||
BaseURL: url,
|
||||
Token: token,
|
||||
RunKey: hex.EncodeToString(runKey),
|
||||
CAPEM: caPEM,
|
||||
ServerName: os.Getenv("CODE_RUNNER_LIVE_SERVER_NAME"),
|
||||
RequestTimeout: 10 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
func liveClient(t *testing.T, settings Settings) *Client {
|
||||
t.Helper()
|
||||
client, err := NewClient(settings)
|
||||
if err != nil {
|
||||
t.Fatalf("NewClient() error = %v", err)
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
func liveRequest(language outbound.CodeLanguage, source, expected string) outbound.CodeRunRequest {
|
||||
return outbound.CodeRunRequest{
|
||||
Key: outbound.CodeRunKey{AttemptItemID: uuid.New(), SubmissionID: uuid.New()},
|
||||
Language: language,
|
||||
Source: source,
|
||||
Limits: outbound.CodeRunLimits{TimeLimitMs: 2000, MemoryLimitMB: 128, OutputLimitKB: 16},
|
||||
Groups: []outbound.CodeTestGroup{
|
||||
{
|
||||
ID: "public", Visibility: outbound.CodeTestPublic,
|
||||
Checker: outbound.CodeChecker{Kind: outbound.CodeCheckerExact},
|
||||
Tests: []outbound.CodeTest{{ID: "1", Input: "2 3\n", ExpectedOutput: expected}},
|
||||
},
|
||||
{
|
||||
ID: "hidden-1", Visibility: outbound.CodeTestHidden,
|
||||
Checker: outbound.CodeChecker{Kind: outbound.CodeCheckerTokens},
|
||||
Tests: []outbound.CodeTest{{ID: "1", Input: "10 20\n", ExpectedOutput: "30"}},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// runLive submits a request and polls it to the final status.
|
||||
func runLive(t *testing.T, client *Client, request outbound.CodeRunRequest) outbound.CodeRunStatus {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), liveRunTimeout)
|
||||
defer cancel()
|
||||
for {
|
||||
status, err := client.Submit(ctx, request)
|
||||
if err != nil {
|
||||
t.Fatalf("Submit() error = %v", err)
|
||||
}
|
||||
if status.State != outbound.CodeRunBusy {
|
||||
break
|
||||
}
|
||||
time.Sleep(max(status.RetryAfter, 500*time.Millisecond))
|
||||
}
|
||||
for {
|
||||
status, err := client.Poll(ctx, request)
|
||||
if err != nil {
|
||||
t.Fatalf("Poll() error = %v", err)
|
||||
}
|
||||
if status.State == outbound.CodeRunFinished {
|
||||
return status
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveRunnerGradesFixedHarmlessPrograms(t *testing.T) {
|
||||
client := liveClient(t, liveSettings(t))
|
||||
const pythonSum = "a, b = map(int, input().split())\nprint(a + b)\n"
|
||||
const goSum = "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar a, b int\n\tfmt.Scan(&a, &b)\n\tfmt.Println(a + b)\n}\n"
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
request outbound.CodeRunRequest
|
||||
want outbound.CodeRunOutcome
|
||||
}{
|
||||
{"python accepted", liveRequest(outbound.CodeLanguagePython3, pythonSum, "5\n"), outbound.CodeOutcomeAccepted},
|
||||
{"go accepted", liveRequest(outbound.CodeLanguageGo, goSum, "5\n"), outbound.CodeOutcomeAccepted},
|
||||
{"python wrong answer", liveRequest(outbound.CodeLanguagePython3, "print(0)\n", "5\n"), outbound.CodeOutcomeWrongAnswer},
|
||||
{"python syntax error", liveRequest(outbound.CodeLanguagePython3, "print(\n", "5\n"), outbound.CodeOutcomeCompileError},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
status := runLive(t, client, test.request)
|
||||
|
||||
if status.Result == nil || status.Result.Outcome != test.want {
|
||||
t.Fatalf("status = %+v, want a %s result", status, test.want)
|
||||
}
|
||||
// A second submit of the same key returns the stored result.
|
||||
again, err := client.Submit(context.Background(), test.request)
|
||||
if err != nil || again.State != outbound.CodeRunFinished || again.Result.Outcome != test.want {
|
||||
t.Fatalf("repeat Submit() = %+v, %v, want the same finished result", again, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveRunnerRefusesAWrongToken(t *testing.T) {
|
||||
settings := liveSettings(t)
|
||||
settings.Token = "wrong-token-0123456789abcdef0123456789"
|
||||
client := liveClient(t, settings)
|
||||
|
||||
_, err := client.Submit(context.Background(), liveRequest(outbound.CodeLanguagePython3, "print(1)\n", "1\n"))
|
||||
|
||||
if !errors.Is(err, outbound.ErrCodeRunnerUnauthorized) {
|
||||
t.Fatalf("Submit() error = %v, want ErrCodeRunnerUnauthorized", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package coderunner
|
||||
|
||||
import (
|
||||
"lincodex/backend/internal/adapter/secondary/code_runner/api"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// toAPIRequest maps a validated request to the wire form. It copies only the
|
||||
// language, source, limits, and test groups; the key never leaves the process.
|
||||
func toAPIRequest(request outbound.CodeRunRequest) *api.RunRequest {
|
||||
groups := make([]api.TestGroup, 0, len(request.Groups))
|
||||
for _, group := range request.Groups {
|
||||
tests := make([]api.TestCase, 0, len(group.Tests))
|
||||
for _, test := range group.Tests {
|
||||
tests = append(tests, api.TestCase{
|
||||
ID: api.TestKey(test.ID),
|
||||
Input: test.Input,
|
||||
ExpectedOutput: test.ExpectedOutput,
|
||||
})
|
||||
}
|
||||
groups = append(groups, api.TestGroup{
|
||||
ID: api.TestKey(group.ID),
|
||||
Visibility: api.TestVisibility(group.Visibility),
|
||||
Checker: toAPIChecker(group.Checker),
|
||||
Tests: tests,
|
||||
})
|
||||
}
|
||||
return &api.RunRequest{
|
||||
Language: api.RunLanguage(request.Language),
|
||||
Source: request.Source,
|
||||
Limits: api.RunLimits{
|
||||
TimeLimitMs: request.Limits.TimeLimitMs,
|
||||
MemoryLimitMB: request.Limits.MemoryLimitMB,
|
||||
OutputLimitKB: request.Limits.OutputLimitKB,
|
||||
},
|
||||
Groups: groups,
|
||||
}
|
||||
}
|
||||
|
||||
func toAPIChecker(checker outbound.CodeChecker) api.Checker {
|
||||
wire := api.Checker{Kind: api.CheckerKind(checker.Kind)}
|
||||
if checker.AbsTolerance != 0 {
|
||||
wire.AbsTolerance = api.NewOptFloat64(checker.AbsTolerance)
|
||||
}
|
||||
if checker.RelTolerance != 0 {
|
||||
wire.RelTolerance = api.NewOptFloat64(checker.RelTolerance)
|
||||
}
|
||||
if checker.Program != nil {
|
||||
wire.Program = api.NewOptCheckerProgram(api.CheckerProgram{
|
||||
Language: api.RunLanguage(checker.Program.Language),
|
||||
Source: checker.Program.Source,
|
||||
})
|
||||
}
|
||||
return wire
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
package coderunner
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/code_runner/api"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// maxRunDuration rejects a duration that no bounded run can have. It also
|
||||
// keeps the conversion to time.Duration far from overflow.
|
||||
const maxRunDuration = 24 * time.Hour
|
||||
|
||||
// convertResult checks a finished run against the contract rules that the
|
||||
// schema cannot express and against the request, then converts it. A score is
|
||||
// computed from the groups, so a result that contradicts the request or
|
||||
// itself is refused rather than trusted.
|
||||
//
|
||||
// An infrastructure_failure run is not a result: it says nothing about the
|
||||
// program and becomes outbound.ErrCodeRunnerInfrastructureFailure.
|
||||
func convertResult(raw api.RunResult, request outbound.CodeRunRequest) (*outbound.CodeRunResult, error) {
|
||||
if raw.Outcome == api.RunOutcomeInfrastructureFailure {
|
||||
return nil, outbound.ErrCodeRunnerInfrastructureFailure
|
||||
}
|
||||
outcome, err := convertOutcome(raw.Outcome)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
compile, err := convertCompile(raw.Compile, outcome)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(raw.Groups) != len(request.Groups) {
|
||||
return nil, badResult("the number of groups differs from the request")
|
||||
}
|
||||
if raw.DurationMs < 0 || time.Duration(raw.DurationMs) > maxRunDuration/time.Millisecond {
|
||||
return nil, badResult("the run duration is out of range")
|
||||
}
|
||||
|
||||
compileFailed := outcome == outbound.CodeOutcomeCompileError
|
||||
groups := make([]outbound.CodeGroupResult, 0, len(raw.Groups))
|
||||
expectedOutcome := outbound.CodeOutcomeAccepted
|
||||
for index, rawGroup := range raw.Groups {
|
||||
group, err := convertGroup(rawGroup, request.Groups[index], compileFailed)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if expectedOutcome == outbound.CodeOutcomeAccepted {
|
||||
expectedOutcome = group.Outcome
|
||||
}
|
||||
groups = append(groups, group)
|
||||
}
|
||||
// The run outcome is compile_error when that happened, otherwise the
|
||||
// outcome of the first failed group, otherwise accepted.
|
||||
if outcome != expectedOutcome {
|
||||
return nil, badResult("the run outcome contradicts its groups")
|
||||
}
|
||||
return &outbound.CodeRunResult{
|
||||
Outcome: outcome,
|
||||
Compile: compile,
|
||||
Groups: groups,
|
||||
Duration: time.Duration(raw.DurationMs) * time.Millisecond,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func convertOutcome(raw api.RunOutcome) (outbound.CodeRunOutcome, error) {
|
||||
switch raw {
|
||||
case api.RunOutcomeAccepted:
|
||||
return outbound.CodeOutcomeAccepted, nil
|
||||
case api.RunOutcomeWrongAnswer:
|
||||
return outbound.CodeOutcomeWrongAnswer, nil
|
||||
case api.RunOutcomeCompileError:
|
||||
return outbound.CodeOutcomeCompileError, nil
|
||||
case api.RunOutcomeTimeLimitExceeded:
|
||||
return outbound.CodeOutcomeTimeLimitExceeded, nil
|
||||
case api.RunOutcomeMemoryLimitExceeded:
|
||||
return outbound.CodeOutcomeMemoryLimitExceeded, nil
|
||||
case api.RunOutcomeOutputLimitExceeded:
|
||||
return outbound.CodeOutcomeOutputLimitExceeded, nil
|
||||
case api.RunOutcomeRuntimeError:
|
||||
return outbound.CodeOutcomeRuntimeError, nil
|
||||
case api.RunOutcomeInfrastructureFailure:
|
||||
// The caller handles it where it is legitimate (the run outcome);
|
||||
// anywhere else it contradicts a graded run.
|
||||
return "", badResult("the outcome is not valid here")
|
||||
default:
|
||||
return "", badResult("the outcome is unknown")
|
||||
}
|
||||
}
|
||||
|
||||
func convertCompile(raw api.OptCompileResult, runOutcome outbound.CodeRunOutcome) (*outbound.CodeCompileResult, error) {
|
||||
compileFailed := runOutcome == outbound.CodeOutcomeCompileError
|
||||
if !raw.Set {
|
||||
if compileFailed {
|
||||
return nil, badResult("a compile error has no compile result")
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
outcome, err := convertOutcome(raw.Value.Outcome)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// A compile step either passed or failed the run; nothing else is valid.
|
||||
if compileFailed != (outcome == outbound.CodeOutcomeCompileError) ||
|
||||
(!compileFailed && outcome != outbound.CodeOutcomeAccepted) {
|
||||
return nil, badResult("the compile result contradicts the run outcome")
|
||||
}
|
||||
return &outbound.CodeCompileResult{Outcome: outcome, Diagnostic: raw.Value.Diagnostic.Or("")}, nil
|
||||
}
|
||||
|
||||
// checkGroupShape compares a group result with the group that was requested.
|
||||
func checkGroupShape(raw api.GroupResult, expected outbound.CodeTestGroup) error {
|
||||
if string(raw.ID) != expected.ID || outbound.CodeTestVisibility(raw.Visibility) != expected.Visibility {
|
||||
return badResult("a group differs from the request")
|
||||
}
|
||||
total := len(expected.Tests)
|
||||
if int(raw.TotalTests) != total || int(raw.PassedTests) > total || len(raw.Tests) > total {
|
||||
return badResult("a group count differs from the request")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func convertGroup(raw api.GroupResult, expected outbound.CodeTestGroup, compileFailed bool) (outbound.CodeGroupResult, error) {
|
||||
if err := checkGroupShape(raw, expected); err != nil {
|
||||
return outbound.CodeGroupResult{}, err
|
||||
}
|
||||
outcome, err := convertOutcome(raw.Outcome)
|
||||
if err != nil {
|
||||
return outbound.CodeGroupResult{}, err
|
||||
}
|
||||
total := len(expected.Tests)
|
||||
|
||||
group := outbound.CodeGroupResult{
|
||||
ID: expected.ID,
|
||||
Visibility: expected.Visibility,
|
||||
Outcome: outcome,
|
||||
PassedTests: int(raw.PassedTests),
|
||||
TotalTests: total,
|
||||
MaxTimeMs: raw.MaxTimeMs.Or(0),
|
||||
MaxMemoryKB: raw.MaxMemoryKB.Or(0),
|
||||
Tests: []outbound.CodeTestResult{},
|
||||
}
|
||||
if compileFailed {
|
||||
if outcome != outbound.CodeOutcomeCompileError || len(raw.Tests) != 0 || raw.PassedTests != 0 {
|
||||
return outbound.CodeGroupResult{}, badResult("a group after a compile error ran tests")
|
||||
}
|
||||
return group, nil
|
||||
}
|
||||
|
||||
tests, passed, groupOutcome, err := convertGroupTests(raw.Tests, expected)
|
||||
if err != nil {
|
||||
return outbound.CodeGroupResult{}, err
|
||||
}
|
||||
if len(tests) < total && groupOutcome == outbound.CodeOutcomeAccepted {
|
||||
return outbound.CodeGroupResult{}, badResult("a group stopped before its last test without a failure")
|
||||
}
|
||||
if group.PassedTests != passed || group.Outcome != groupOutcome {
|
||||
return outbound.CodeGroupResult{}, badResult("a group result contradicts its tests")
|
||||
}
|
||||
group.Tests = tests
|
||||
return group, nil
|
||||
}
|
||||
|
||||
// convertGroupTests converts the evaluated tests of a group. A group stops at
|
||||
// its first failed test, so they are a prefix of the request: all accepted,
|
||||
// then at most one failed. It returns the tests, the number of accepted ones,
|
||||
// and the outcome they imply for the group.
|
||||
func convertGroupTests(raw []api.TestResult, expected outbound.CodeTestGroup) ([]outbound.CodeTestResult, int, outbound.CodeRunOutcome, error) {
|
||||
tests := make([]outbound.CodeTestResult, 0, len(raw))
|
||||
passed := 0
|
||||
outcome := outbound.CodeOutcomeAccepted
|
||||
for index, rawTest := range raw {
|
||||
if outcome != outbound.CodeOutcomeAccepted {
|
||||
return nil, 0, "", badResult("a group evaluated a test after a failed one")
|
||||
}
|
||||
test, err := convertTest(rawTest, expected.Tests[index].ID, expected.Visibility)
|
||||
if err != nil {
|
||||
return nil, 0, "", err
|
||||
}
|
||||
if test.Outcome == outbound.CodeOutcomeCompileError {
|
||||
return nil, 0, "", badResult("a test has a compile error outcome")
|
||||
}
|
||||
if test.Outcome == outbound.CodeOutcomeAccepted {
|
||||
passed++
|
||||
}
|
||||
outcome = test.Outcome
|
||||
tests = append(tests, test)
|
||||
}
|
||||
return tests, passed, outcome, nil
|
||||
}
|
||||
|
||||
func convertTest(raw api.TestResult, expectedID string, visibility outbound.CodeTestVisibility) (outbound.CodeTestResult, error) {
|
||||
if string(raw.ID) != expectedID {
|
||||
return outbound.CodeTestResult{}, badResult("a test differs from the request")
|
||||
}
|
||||
outcome, err := convertOutcome(raw.Outcome)
|
||||
if err != nil {
|
||||
return outbound.CodeTestResult{}, err
|
||||
}
|
||||
test := outbound.CodeTestResult{
|
||||
ID: expectedID,
|
||||
Outcome: outcome,
|
||||
TimeMs: raw.TimeMs,
|
||||
WallTimeMs: raw.WallTimeMs,
|
||||
MemoryKB: raw.MemoryKB,
|
||||
}
|
||||
if raw.ExitCode.Set {
|
||||
value := raw.ExitCode.Value
|
||||
test.ExitCode = &value
|
||||
}
|
||||
if raw.Signal.Set {
|
||||
value := raw.Signal.Value
|
||||
test.Signal = &value
|
||||
}
|
||||
if raw.Limit.Set {
|
||||
test.Limit = outbound.CodeTerminationLimit(raw.Limit.Value)
|
||||
}
|
||||
// Hidden tests never carry program output. The runner promises it; the
|
||||
// client does not pass such text on even if a faulty runner sends it.
|
||||
if visibility == outbound.CodeTestPublic {
|
||||
test.Diagnostic = raw.Diagnostic.Or("")
|
||||
}
|
||||
return test, nil
|
||||
}
|
||||
|
||||
func badResult(reason string) error {
|
||||
return fmt.Errorf("%s: %w", reason, outbound.ErrCodeRunnerBadResponse)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package coderunner
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// runIDDomain separates run IDs from any other use of the same HMAC key.
|
||||
const runIDDomain = "lincodex.code-run.v1"
|
||||
|
||||
// deriveRunID maps a run key to the opaque ID the runner stores the run under.
|
||||
//
|
||||
// The ID is deterministic, so a retry of the same submission reuses the run
|
||||
// instead of starting a second one (the runner is idempotent by run ID). It is
|
||||
// keyed with a secret that only the backend knows, so the runner cannot link
|
||||
// an ID back to an attempt item or a submission, and nobody can guess the ID
|
||||
// of another submission. The result is a valid UUID (version 8, RFC 9562) as
|
||||
// the runner contract requires.
|
||||
func deriveRunID(secret []byte, key outbound.CodeRunKey) uuid.UUID {
|
||||
mac := hmac.New(sha256.New, secret)
|
||||
mac.Write([]byte(runIDDomain))
|
||||
mac.Write([]byte{0})
|
||||
mac.Write(key.AttemptItemID[:])
|
||||
mac.Write(key.SubmissionID[:])
|
||||
var generation [4]byte
|
||||
binary.BigEndian.PutUint32(generation[:], key.Generation)
|
||||
mac.Write(generation[:])
|
||||
|
||||
var id uuid.UUID
|
||||
copy(id[:], mac.Sum(nil))
|
||||
id[6] = id[6]&0x0f | 0x80
|
||||
id[8] = id[8]&0x3f | 0x80
|
||||
return id
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package coderunner
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestDeriveRunIDIsStableOpaqueAndSeparatesKeys(t *testing.T) {
|
||||
secret := []byte(testRunKey)
|
||||
key := testRequest().Key
|
||||
|
||||
first := deriveRunID(secret, key)
|
||||
if again := deriveRunID(secret, key); again != first {
|
||||
t.Fatalf("deriveRunID() = %s then %s, want a deterministic ID", first, again)
|
||||
}
|
||||
if first.Version() != 8 || first.Variant() != uuid.RFC4122 {
|
||||
t.Fatalf("run ID %s has version %d variant %v, want a version 8 RFC 9562 UUID", first, first.Version(), first.Variant())
|
||||
}
|
||||
for _, identifier := range []uuid.UUID{key.AttemptItemID, key.SubmissionID} {
|
||||
text := strings.ReplaceAll(first.String(), "-", "")
|
||||
if strings.Contains(text, strings.ReplaceAll(identifier.String(), "-", "")) || strings.Contains(text, strings.ReplaceAll(identifier.String(), "-", "")[:8]) {
|
||||
t.Fatalf("run ID %s contains a source identifier", first)
|
||||
}
|
||||
}
|
||||
|
||||
swapped := outbound.CodeRunKey{AttemptItemID: key.SubmissionID, SubmissionID: key.AttemptItemID}
|
||||
nextGeneration := key
|
||||
nextGeneration.Generation = 1
|
||||
otherItem := key
|
||||
otherItem.AttemptItemID = uuid.MustParse("00000000-0000-4000-8000-000000000001")
|
||||
ids := map[uuid.UUID]string{first: "base"}
|
||||
for name, derived := range map[string]uuid.UUID{
|
||||
"swapped identifiers": deriveRunID(secret, swapped),
|
||||
"next generation": deriveRunID(secret, nextGeneration),
|
||||
"other item": deriveRunID(secret, otherItem),
|
||||
"other secret": deriveRunID([]byte(testRunKey+"x"), key),
|
||||
} {
|
||||
if previous, clash := ids[derived]; clash {
|
||||
t.Fatalf("run ID of %q equals the one of %q", name, previous)
|
||||
}
|
||||
ids[derived] = name
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package coderunner
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func formatWith(verb string, value any) string { return fmt.Sprintf(verb, value) }
|
||||
|
||||
// foreignCAPEM returns a CA certificate that signed nothing the fixtures serve.
|
||||
// httptest servers all share one built-in certificate, so a second fixture
|
||||
// cannot stand in for a different CA.
|
||||
func foreignCAPEM(t *testing.T) []byte {
|
||||
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: "foreign test CA"},
|
||||
NotBefore: time.Now().Add(-time.Hour),
|
||||
NotAfter: time.Now().Add(time.Hour),
|
||||
IsCA: true,
|
||||
BasicConstraintsValid: true,
|
||||
KeyUsage: x509.KeyUsageCertSign,
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateCertificate() error = %v", err)
|
||||
}
|
||||
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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"}},
|
||||
}},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,516 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Bounds of the code runner contract (api/runner). They are checked before a
|
||||
// request leaves the process, so a task family that breaks one fails in the
|
||||
// caller's tests instead of as a runner rejection in production.
|
||||
const (
|
||||
// MaxCodeRunGroups and MaxCodeRunTestsPerGroup also bound a result.
|
||||
MaxCodeRunGroups = 4
|
||||
MaxCodeRunTestsPerGroup = 50
|
||||
|
||||
maxCodeRunSourceBytes = 65536
|
||||
maxCodeRunTestTextBytes = 262144
|
||||
minCodeRunTimeLimitMs = 100
|
||||
maxCodeRunTimeLimitMs = 10000
|
||||
minCodeRunMemoryLimitMB = 32
|
||||
maxCodeRunMemoryLimitMB = 512
|
||||
minCodeRunOutputLimitKB = 1
|
||||
maxCodeRunOutputLimitKB = 1024
|
||||
maxCodeRunAbsTolerance = 1_000_000_000
|
||||
maxCodeRunRelTolerance = 1
|
||||
// maxCodeRunCPUBudgetMs bounds tests multiplied by the time limit of one
|
||||
// run, as the runner does.
|
||||
maxCodeRunCPUBudgetMs = 300000
|
||||
// maxCodeRunPayloadBytes is the default runner request limit (8 MiB)
|
||||
// minus room for the JSON structure around the texts.
|
||||
maxCodeRunPayloadBytes = 8<<20 - 64<<10
|
||||
redactedCodeRunRequest = "[redacted code run request]"
|
||||
redactedCodeRunResultLog = "[code run result]"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrCodeRunnerUnavailable is the umbrella of every failure that leaves a
|
||||
// submission without a verdict although the candidate did nothing wrong:
|
||||
// the runner is disabled, unreachable, too slow, refuses the service
|
||||
// token, fails with a server error, answers outside the contract, or
|
||||
// reports that it could not evaluate the source. Nothing is graded and
|
||||
// the caller must not score, fail, or accept the submission; it reports
|
||||
// the service as unavailable and retries later. Check it with errors.Is
|
||||
// before the specific errors below.
|
||||
ErrCodeRunnerUnavailable = errors.New("code runner unavailable")
|
||||
|
||||
// ErrCodeRunnerDisabled means CODE_RUNNER_URL is not set, so no request
|
||||
// was made. It is an unavailable runner, never a verdict.
|
||||
ErrCodeRunnerDisabled = fmt.Errorf("code runner is disabled: %w", ErrCodeRunnerUnavailable)
|
||||
|
||||
// ErrCodeRunnerUnauthorized means the runner refused the service token
|
||||
// (401). It points at deployment configuration and needs an operator, not
|
||||
// a retry.
|
||||
ErrCodeRunnerUnauthorized = fmt.Errorf("code runner refused the service token: %w", ErrCodeRunnerUnavailable)
|
||||
|
||||
// ErrCodeRunnerBadResponse means the runner answered, but not as the
|
||||
// contract says: a malformed or oversized body, a wrong content type, an
|
||||
// unexpected status, or a result that contradicts the request or itself.
|
||||
// The run may exist on the runner, so a retry with the same key is
|
||||
// harmless.
|
||||
ErrCodeRunnerBadResponse = fmt.Errorf("code runner answered outside its contract: %w", ErrCodeRunnerUnavailable)
|
||||
|
||||
// ErrCodeRunnerInfrastructureFailure means the runner finished the run
|
||||
// with the outcome infrastructure_failure: it could not evaluate the
|
||||
// source. The runner keeps that result under the run ID, so the same key
|
||||
// would return it again; the caller starts the next try with a higher
|
||||
// CodeRunKey.Generation.
|
||||
ErrCodeRunnerInfrastructureFailure = fmt.Errorf("code runner could not evaluate the source: %w", ErrCodeRunnerUnavailable)
|
||||
|
||||
// ErrInvalidCodeRunRequest reports a request that fails
|
||||
// CodeRunRequest.Validate, or that the runner rejected as invalid
|
||||
// (400, 413). It is a caller or task content bug. Nothing ran, and it is
|
||||
// not a candidate's wrong answer.
|
||||
ErrInvalidCodeRunRequest = errors.New("invalid code run request")
|
||||
|
||||
// ErrCodeRunNotFound means the runner does not hold the run: it was
|
||||
// forgotten after its retention time or lost in a restart. Submit the
|
||||
// request again with the same key; the runner starts a new run.
|
||||
ErrCodeRunNotFound = errors.New("code run not found")
|
||||
|
||||
// ErrCodeRunKeyReused means the runner already holds a run under this
|
||||
// key with a different payload (422). The payload of one key must not
|
||||
// change; the caller bumps CodeRunKey.Generation to run the new payload.
|
||||
ErrCodeRunKeyReused = errors.New("code run key reused with another payload")
|
||||
)
|
||||
|
||||
var codeRunTestKeyPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,31}$`)
|
||||
|
||||
// CodeLanguage is a language the runner can compile or interpret.
|
||||
type CodeLanguage string
|
||||
|
||||
const (
|
||||
CodeLanguagePython3 CodeLanguage = "python3"
|
||||
CodeLanguageGo CodeLanguage = "go"
|
||||
)
|
||||
|
||||
// CodeCheckerKind says how the runner compares program output with the
|
||||
// expected output of a test.
|
||||
type CodeCheckerKind string
|
||||
|
||||
const (
|
||||
// CodeCheckerExact compares the texts after line-ending and trailing
|
||||
// white space normalization.
|
||||
CodeCheckerExact CodeCheckerKind = "exact"
|
||||
// CodeCheckerTokens compares whitespace-separated tokens.
|
||||
CodeCheckerTokens CodeCheckerKind = "tokens"
|
||||
// CodeCheckerNumbers compares tokens and accepts numeric tokens within
|
||||
// AbsTolerance or RelTolerance.
|
||||
CodeCheckerNumbers CodeCheckerKind = "numbers"
|
||||
// CodeCheckerCustom runs the checker program of the task family.
|
||||
CodeCheckerCustom CodeCheckerKind = "custom"
|
||||
)
|
||||
|
||||
// CodeTestVisibility says whether the person who wrote the source may see
|
||||
// details of a test. Hidden tests never carry program output or diagnostics.
|
||||
type CodeTestVisibility string
|
||||
|
||||
const (
|
||||
CodeTestPublic CodeTestVisibility = "public"
|
||||
CodeTestHidden CodeTestVisibility = "hidden"
|
||||
)
|
||||
|
||||
// CodeRunKey identifies one logical run. The adapter turns it into the opaque
|
||||
// run ID the runner stores, so the runner never sees these values and every
|
||||
// retry of the same key reuses the same run.
|
||||
type CodeRunKey struct {
|
||||
// AttemptItemID is the assessment attempt item the source answers.
|
||||
AttemptItemID uuid.UUID
|
||||
// SubmissionID identifies the submission of that item.
|
||||
SubmissionID uuid.UUID
|
||||
// Generation is 0 for the first try. After ErrCodeRunnerInfrastructureFailure
|
||||
// the caller increments it; the runner would return the stored failure for
|
||||
// the old key.
|
||||
Generation uint32
|
||||
}
|
||||
|
||||
// CodeRunLimits are the technical limits applied to every test of a run.
|
||||
type CodeRunLimits struct {
|
||||
// TimeLimitMs is the CPU time per test.
|
||||
TimeLimitMs int32
|
||||
// MemoryLimitMB is the memory of the test's processes.
|
||||
MemoryLimitMB int32
|
||||
// OutputLimitKB is the standard output per test.
|
||||
OutputLimitKB int32
|
||||
}
|
||||
|
||||
// CodeChecker configures the comparison of a group.
|
||||
type CodeChecker struct {
|
||||
Kind CodeCheckerKind
|
||||
// AbsTolerance and RelTolerance apply to CodeCheckerNumbers only; zero
|
||||
// means unset, and at least one must be positive.
|
||||
AbsTolerance float64
|
||||
RelTolerance float64
|
||||
// Program is the checker program of CodeCheckerCustom only.
|
||||
Program *CodeCheckerProgram
|
||||
}
|
||||
|
||||
// CodeCheckerProgram is the checker program of a task family.
|
||||
type CodeCheckerProgram struct {
|
||||
Language CodeLanguage
|
||||
Source string
|
||||
}
|
||||
|
||||
// CodeTest is one input and the output the checker expects.
|
||||
type CodeTest struct {
|
||||
// ID is an opaque label such as "1" or "hidden-1" that is unique in its
|
||||
// group. It is not a database identifier.
|
||||
ID string
|
||||
Input string
|
||||
ExpectedOutput string
|
||||
}
|
||||
|
||||
// CodeTestGroup is a set of tests with one checker. A group stops at its
|
||||
// first failed test.
|
||||
type CodeTestGroup struct {
|
||||
// ID is an opaque label such as "public" or "hidden-1" that is unique in
|
||||
// the run.
|
||||
ID string
|
||||
Visibility CodeTestVisibility
|
||||
Checker CodeChecker
|
||||
Tests []CodeTest
|
||||
}
|
||||
|
||||
// CodeRunRequest is one source with its limits and test groups. It carries
|
||||
// nothing about the candidate: the runner receives only code, tests, and
|
||||
// technical limits.
|
||||
//
|
||||
// String, GoString, Format, and LogValue redact the whole request, because
|
||||
// the source is candidate work and the tests of hidden groups are secret task
|
||||
// content. Read the fields directly where they are needed.
|
||||
type CodeRunRequest struct {
|
||||
Key CodeRunKey
|
||||
Language CodeLanguage
|
||||
Source string
|
||||
Limits CodeRunLimits
|
||||
Groups []CodeTestGroup
|
||||
}
|
||||
|
||||
func (request CodeRunRequest) String() string { return redactedCodeRunRequest }
|
||||
|
||||
func (request CodeRunRequest) GoString() string { return redactedCodeRunRequest }
|
||||
|
||||
// Format redacts every verb; without it %+v would print the fields.
|
||||
func (request CodeRunRequest) Format(state fmt.State, _ rune) {
|
||||
_, _ = state.Write([]byte(redactedCodeRunRequest))
|
||||
}
|
||||
|
||||
func (request CodeRunRequest) LogValue() slog.Value { return slog.StringValue(redactedCodeRunRequest) }
|
||||
|
||||
// Validate reports a request that the runner would reject, using the rules of
|
||||
// the runner contract. Errors wrap ErrInvalidCodeRunRequest and name only the
|
||||
// field, never source or test text.
|
||||
func (request CodeRunRequest) Validate() error {
|
||||
if request.Key.AttemptItemID == uuid.Nil || request.Key.SubmissionID == uuid.Nil {
|
||||
return invalidCodeRunRequest("key must name the attempt item and the submission")
|
||||
}
|
||||
if !validCodeLanguage(request.Language) {
|
||||
return invalidCodeRunRequest("language must be python3 or go")
|
||||
}
|
||||
if err := validateCodeText("source", request.Source, maxCodeRunSourceBytes, true); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := request.Limits.validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(request.Groups) < 1 || len(request.Groups) > MaxCodeRunGroups {
|
||||
return invalidCodeRunRequest("groups must have 1 to 4 entries")
|
||||
}
|
||||
size := len(request.Source)
|
||||
seenGroups := make(map[string]struct{}, len(request.Groups))
|
||||
totalTests := 0
|
||||
for _, group := range request.Groups {
|
||||
if _, duplicate := seenGroups[group.ID]; duplicate {
|
||||
return invalidCodeRunRequest("group IDs must be unique")
|
||||
}
|
||||
seenGroups[group.ID] = struct{}{}
|
||||
groupSize, err := group.validate()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
size += groupSize
|
||||
totalTests += len(group.Tests)
|
||||
}
|
||||
// The runner stops a test at its CPU limit and bounds the whole run.
|
||||
if totalTests*int(request.Limits.TimeLimitMs) > maxCodeRunCPUBudgetMs {
|
||||
return invalidCodeRunRequest("tests multiplied by the time limit must not exceed 300000 ms")
|
||||
}
|
||||
if size > maxCodeRunPayloadBytes {
|
||||
return invalidCodeRunRequest("payload must fit the runner request limit")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (limits CodeRunLimits) validate() error {
|
||||
switch {
|
||||
case limits.TimeLimitMs < minCodeRunTimeLimitMs || limits.TimeLimitMs > maxCodeRunTimeLimitMs:
|
||||
return invalidCodeRunRequest("time limit must be 100 to 10000 ms")
|
||||
case limits.MemoryLimitMB < minCodeRunMemoryLimitMB || limits.MemoryLimitMB > maxCodeRunMemoryLimitMB:
|
||||
return invalidCodeRunRequest("memory limit must be 32 to 512 MiB")
|
||||
case limits.OutputLimitKB < minCodeRunOutputLimitKB || limits.OutputLimitKB > maxCodeRunOutputLimitKB:
|
||||
return invalidCodeRunRequest("output limit must be 1 to 1024 KiB")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validate checks one group and returns the bytes of text it carries.
|
||||
func (group CodeTestGroup) validate() (int, error) {
|
||||
if !codeRunTestKeyPattern.MatchString(group.ID) {
|
||||
return 0, invalidCodeRunRequest("group ID must match [a-z0-9][a-z0-9_-]{0,31}")
|
||||
}
|
||||
if group.Visibility != CodeTestPublic && group.Visibility != CodeTestHidden {
|
||||
return 0, invalidCodeRunRequest("group visibility must be public or hidden")
|
||||
}
|
||||
size, err := group.Checker.validate()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if len(group.Tests) < 1 || len(group.Tests) > MaxCodeRunTestsPerGroup {
|
||||
return 0, invalidCodeRunRequest("group must have 1 to 50 tests")
|
||||
}
|
||||
seenTests := make(map[string]struct{}, len(group.Tests))
|
||||
for _, test := range group.Tests {
|
||||
if !codeRunTestKeyPattern.MatchString(test.ID) {
|
||||
return 0, invalidCodeRunRequest("test ID must match [a-z0-9][a-z0-9_-]{0,31}")
|
||||
}
|
||||
if _, duplicate := seenTests[test.ID]; duplicate {
|
||||
return 0, invalidCodeRunRequest("test IDs must be unique in a group")
|
||||
}
|
||||
seenTests[test.ID] = struct{}{}
|
||||
if err := validateCodeText("test input", test.Input, maxCodeRunTestTextBytes, false); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err := validateCodeText("test expected output", test.ExpectedOutput, maxCodeRunTestTextBytes, false); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
size += len(test.Input) + len(test.ExpectedOutput)
|
||||
}
|
||||
return size, nil
|
||||
}
|
||||
|
||||
// validate checks one checker and returns the bytes of program source.
|
||||
func (checker CodeChecker) validate() (int, error) {
|
||||
hasTolerance := checker.AbsTolerance != 0 || checker.RelTolerance != 0
|
||||
switch checker.Kind {
|
||||
case CodeCheckerExact, CodeCheckerTokens:
|
||||
if hasTolerance || checker.Program != nil {
|
||||
return 0, invalidCodeRunRequest("checker exact and tokens take no tolerance or program")
|
||||
}
|
||||
case CodeCheckerNumbers:
|
||||
if err := checker.validateNumbers(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
case CodeCheckerCustom:
|
||||
if hasTolerance {
|
||||
return 0, invalidCodeRunRequest("checker custom takes no tolerance")
|
||||
}
|
||||
if checker.Program == nil || !validCodeLanguage(checker.Program.Language) {
|
||||
return 0, invalidCodeRunRequest("checker custom needs a program in python3 or go")
|
||||
}
|
||||
if err := validateCodeText("checker program", checker.Program.Source, maxCodeRunSourceBytes, true); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(checker.Program.Source), nil
|
||||
default:
|
||||
return 0, invalidCodeRunRequest("checker kind must be exact, tokens, numbers, or custom")
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (checker CodeChecker) validateNumbers() error {
|
||||
if checker.Program != nil {
|
||||
return invalidCodeRunRequest("checker numbers takes no program")
|
||||
}
|
||||
// NaN fails every comparison, so the negated range checks reject it.
|
||||
if !(checker.AbsTolerance >= 0 && checker.AbsTolerance <= maxCodeRunAbsTolerance) ||
|
||||
!(checker.RelTolerance >= 0 && checker.RelTolerance <= maxCodeRunRelTolerance) ||
|
||||
(checker.AbsTolerance == 0 && checker.RelTolerance == 0) {
|
||||
return invalidCodeRunRequest("checker numbers needs a positive tolerance within its range")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validCodeLanguage(language CodeLanguage) bool {
|
||||
return language == CodeLanguagePython3 || language == CodeLanguageGo
|
||||
}
|
||||
|
||||
func validateCodeText(name, text string, maxBytes int, required bool) error {
|
||||
switch {
|
||||
case required && strings.TrimSpace(text) == "":
|
||||
return invalidCodeRunRequest(name + " must not be empty")
|
||||
case len(text) > maxBytes:
|
||||
return invalidCodeRunRequest(fmt.Sprintf("%s must have at most %d bytes", name, maxBytes))
|
||||
case !utf8.ValidString(text):
|
||||
return invalidCodeRunRequest(name + " must be valid UTF-8")
|
||||
case strings.ContainsRune(text, 0):
|
||||
return invalidCodeRunRequest(name + " must not contain NUL")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func invalidCodeRunRequest(reason string) error {
|
||||
return fmt.Errorf("CodeRunRequest.Validate - %s: %w", reason, ErrInvalidCodeRunRequest)
|
||||
}
|
||||
|
||||
// CodeRunState is what a runner call established about a run. The zero value
|
||||
// is not a state and must never be read as progress or acceptance.
|
||||
type CodeRunState string
|
||||
|
||||
const (
|
||||
// CodeRunRunning means the runner holds the run and has no result yet.
|
||||
// Poll again later.
|
||||
CodeRunRunning CodeRunState = "running"
|
||||
|
||||
// CodeRunFinished means Result holds the final, validated result.
|
||||
CodeRunFinished CodeRunState = "finished"
|
||||
|
||||
// CodeRunBusy means every sandbox slot is busy or the runner is draining.
|
||||
// The runner stored nothing; submit again with the same key after
|
||||
// RetryAfter. Only Submit reports it, and it is a capacity signal, not a
|
||||
// failure of the candidate or of the runner.
|
||||
CodeRunBusy CodeRunState = "busy"
|
||||
)
|
||||
|
||||
// CodeRunOutcome is the verdict of a test, a group, a compile step, or a run.
|
||||
// It has no value for the runner's infrastructure_failure, which is
|
||||
// ErrCodeRunnerInfrastructureFailure: a failure to evaluate says nothing about
|
||||
// the program.
|
||||
type CodeRunOutcome string
|
||||
|
||||
const (
|
||||
CodeOutcomeAccepted CodeRunOutcome = "accepted"
|
||||
CodeOutcomeWrongAnswer CodeRunOutcome = "wrong_answer"
|
||||
CodeOutcomeCompileError CodeRunOutcome = "compile_error"
|
||||
CodeOutcomeTimeLimitExceeded CodeRunOutcome = "time_limit_exceeded"
|
||||
CodeOutcomeMemoryLimitExceeded CodeRunOutcome = "memory_limit_exceeded"
|
||||
CodeOutcomeOutputLimitExceeded CodeRunOutcome = "output_limit_exceeded"
|
||||
CodeOutcomeRuntimeError CodeRunOutcome = "runtime_error"
|
||||
)
|
||||
|
||||
// CodeTerminationLimit is the limit that stopped a test.
|
||||
type CodeTerminationLimit string
|
||||
|
||||
const (
|
||||
CodeLimitCPUTime CodeTerminationLimit = "cpu_time"
|
||||
CodeLimitWallTime CodeTerminationLimit = "wall_time"
|
||||
CodeLimitMemory CodeTerminationLimit = "memory"
|
||||
CodeLimitOutput CodeTerminationLimit = "output"
|
||||
CodeLimitProcesses CodeTerminationLimit = "processes"
|
||||
)
|
||||
|
||||
// CodeCompileResult is the compile phase of a run. Only compile_error carries
|
||||
// a diagnostic, which can quote the source but never test data.
|
||||
type CodeCompileResult struct {
|
||||
Outcome CodeRunOutcome
|
||||
Diagnostic string
|
||||
}
|
||||
|
||||
// CodeTestResult is the result of one evaluated test.
|
||||
type CodeTestResult struct {
|
||||
ID string
|
||||
Outcome CodeRunOutcome
|
||||
TimeMs int64
|
||||
WallTimeMs int64
|
||||
MemoryKB int64
|
||||
// ExitCode is set when the program exited normally; Signal when a signal
|
||||
// killed it. Limit is empty unless a limit stopped the test.
|
||||
ExitCode *int32
|
||||
Signal *int32
|
||||
Limit CodeTerminationLimit
|
||||
Diagnostic string
|
||||
}
|
||||
|
||||
// CodeGroupResult is the result of one group. Tests lists the evaluated tests
|
||||
// only: the tests after the first failed one are not run.
|
||||
type CodeGroupResult struct {
|
||||
ID string
|
||||
Visibility CodeTestVisibility
|
||||
Outcome CodeRunOutcome
|
||||
PassedTests int
|
||||
TotalTests int
|
||||
MaxTimeMs int64
|
||||
MaxMemoryKB int64
|
||||
Tests []CodeTestResult
|
||||
}
|
||||
|
||||
// CodeRunResult is the validated final result of a run. The caller computes
|
||||
// the score from the groups; the runner only reports which ones passed.
|
||||
type CodeRunResult struct {
|
||||
Outcome CodeRunOutcome
|
||||
Compile *CodeCompileResult
|
||||
Groups []CodeGroupResult
|
||||
Duration time.Duration
|
||||
}
|
||||
|
||||
// LogValue summarizes the result without diagnostics, which can quote the
|
||||
// candidate's source.
|
||||
func (result CodeRunResult) LogValue() slog.Value {
|
||||
return slog.GroupValue(
|
||||
slog.String("outcome", string(result.Outcome)),
|
||||
slog.Int("groups", len(result.Groups)),
|
||||
slog.Duration("duration", result.Duration),
|
||||
)
|
||||
}
|
||||
|
||||
func (result CodeRunResult) String() string { return redactedCodeRunResultLog }
|
||||
|
||||
// CodeRunStatus is the state of a run after one runner call.
|
||||
type CodeRunStatus struct {
|
||||
State CodeRunState
|
||||
|
||||
// RunID is the opaque ID the runner holds the run under. It identifies no
|
||||
// user, attempt, or task; it is safe to log and matches the runner's logs.
|
||||
RunID string
|
||||
|
||||
// RetryAfter is the runner's wait hint for CodeRunBusy only.
|
||||
RetryAfter time.Duration
|
||||
|
||||
// Result is set for CodeRunFinished only.
|
||||
Result *CodeRunResult
|
||||
}
|
||||
|
||||
// CodeRunner runs candidate code against test groups in the own sandboxed
|
||||
// runner service (api/runner). Judge0 is not used.
|
||||
//
|
||||
// Both methods make exactly one runner call and never retry or sleep; queueing,
|
||||
// backoff, and polling belong to the caller. Submit is idempotent by
|
||||
// request.Key: the same key with the same payload returns the current state of
|
||||
// one run and never runs it twice. Poll reads that run without sending the
|
||||
// payload again.
|
||||
//
|
||||
// A nil error comes with a state of running, finished, or (Submit only) busy.
|
||||
// A finished state always holds a validated result. An error means that
|
||||
// nothing was graded:
|
||||
// - ErrInvalidCodeRunRequest: the request is invalid, nothing was sent.
|
||||
// - ErrCodeRunnerUnavailable (including the disabled, unauthorized,
|
||||
// bad-response, and infrastructure-failure forms): no verdict could be
|
||||
// obtained. It is never a wrong answer and never a reason to fail the
|
||||
// candidate.
|
||||
// - ErrCodeRunNotFound (Poll): the runner lost the run; Submit again.
|
||||
// - ErrCodeRunKeyReused: the key was used with another payload.
|
||||
// - the context error when ctx ended.
|
||||
//
|
||||
// The returned status is zero when err is not nil. Errors and logs never
|
||||
// include source, tests, program output, or the token.
|
||||
type CodeRunner interface {
|
||||
Submit(ctx context.Context, request CodeRunRequest) (CodeRunStatus, error)
|
||||
Poll(ctx context.Context, request CodeRunRequest) (CodeRunStatus, error)
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package outbound_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const sourceMarker = "source-marker-7f3a"
|
||||
|
||||
func validCodeRunRequest() outbound.CodeRunRequest {
|
||||
return outbound.CodeRunRequest{
|
||||
Key: outbound.CodeRunKey{AttemptItemID: uuid.New(), SubmissionID: uuid.New()},
|
||||
Language: outbound.CodeLanguageGo,
|
||||
Source: "package main // " + sourceMarker,
|
||||
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: "1\n", ExpectedOutput: "2\n"}},
|
||||
},
|
||||
{
|
||||
ID: "hidden-1", Visibility: outbound.CodeTestHidden,
|
||||
Checker: outbound.CodeChecker{Kind: outbound.CodeCheckerNumbers, AbsTolerance: 1e-6},
|
||||
Tests: []outbound.CodeTest{{ID: "1", Input: "hidden-input-marker\n", ExpectedOutput: "hidden-output-marker\n"}},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodeRunRequestValidateAcceptsAContractRequest(t *testing.T) {
|
||||
if err := validCodeRunRequest().Validate(); err != nil {
|
||||
t.Fatalf("Validate() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodeRunRequestValidateRejectsWhatTheRunnerRejects(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
change func(*outbound.CodeRunRequest)
|
||||
}{
|
||||
{"no attempt item", func(r *outbound.CodeRunRequest) { r.Key.AttemptItemID = uuid.Nil }},
|
||||
{"no submission", func(r *outbound.CodeRunRequest) { r.Key.SubmissionID = uuid.Nil }},
|
||||
{"unknown language", func(r *outbound.CodeRunRequest) { r.Language = "java" }},
|
||||
{"empty source", func(r *outbound.CodeRunRequest) { r.Source = " \n" }},
|
||||
{"source above 64 KiB", func(r *outbound.CodeRunRequest) { r.Source = strings.Repeat("a", 65537) }},
|
||||
{"source not UTF-8", func(r *outbound.CodeRunRequest) { r.Source = "\xff\xfe" }},
|
||||
{"source with NUL", func(r *outbound.CodeRunRequest) { r.Source = "a\x00b" }},
|
||||
{"time limit below range", func(r *outbound.CodeRunRequest) { r.Limits.TimeLimitMs = 99 }},
|
||||
{"time limit above range", func(r *outbound.CodeRunRequest) { r.Limits.TimeLimitMs = 10001 }},
|
||||
{"memory below range", func(r *outbound.CodeRunRequest) { r.Limits.MemoryLimitMB = 31 }},
|
||||
{"memory above range", func(r *outbound.CodeRunRequest) { r.Limits.MemoryLimitMB = 513 }},
|
||||
{"output below range", func(r *outbound.CodeRunRequest) { r.Limits.OutputLimitKB = 0 }},
|
||||
{"output above range", func(r *outbound.CodeRunRequest) { r.Limits.OutputLimitKB = 1025 }},
|
||||
{"no groups", func(r *outbound.CodeRunRequest) { r.Groups = nil }},
|
||||
{"five groups", func(r *outbound.CodeRunRequest) {
|
||||
for index := range 3 {
|
||||
group := r.Groups[0]
|
||||
group.ID = fmt.Sprintf("extra-%d", index)
|
||||
r.Groups = append(r.Groups, group)
|
||||
}
|
||||
}},
|
||||
{"duplicate group ID", func(r *outbound.CodeRunRequest) { r.Groups[1].ID = r.Groups[0].ID }},
|
||||
{"group ID with capitals", func(r *outbound.CodeRunRequest) { r.Groups[0].ID = "Public" }},
|
||||
{"unknown visibility", func(r *outbound.CodeRunRequest) { r.Groups[0].Visibility = "secret" }},
|
||||
{"group without tests", func(r *outbound.CodeRunRequest) { r.Groups[0].Tests = nil }},
|
||||
{"fifty one tests", func(r *outbound.CodeRunRequest) {
|
||||
r.Limits.TimeLimitMs = 100
|
||||
r.Groups[0].Tests = nil
|
||||
for index := range 51 {
|
||||
r.Groups[0].Tests = append(r.Groups[0].Tests, outbound.CodeTest{ID: fmt.Sprintf("t%d", index)})
|
||||
}
|
||||
}},
|
||||
{"duplicate test ID", func(r *outbound.CodeRunRequest) {
|
||||
r.Groups[0].Tests = append(r.Groups[0].Tests, r.Groups[0].Tests[0])
|
||||
}},
|
||||
{"test input too large", func(r *outbound.CodeRunRequest) { r.Groups[0].Tests[0].Input = strings.Repeat("a", 262145) }},
|
||||
{"expected output too large", func(r *outbound.CodeRunRequest) { r.Groups[0].Tests[0].ExpectedOutput = strings.Repeat("a", 262145) }},
|
||||
{"CPU budget above 300 s", func(r *outbound.CodeRunRequest) {
|
||||
r.Limits.TimeLimitMs = 10000
|
||||
for index := range 30 {
|
||||
r.Groups[0].Tests = append(r.Groups[0].Tests, outbound.CodeTest{ID: fmt.Sprintf("t%d", index+2)})
|
||||
}
|
||||
}},
|
||||
{"unknown checker", func(r *outbound.CodeRunRequest) { r.Groups[0].Checker.Kind = "regex" }},
|
||||
{"exact with tolerance", func(r *outbound.CodeRunRequest) { r.Groups[0].Checker.AbsTolerance = 1 }},
|
||||
{"numbers without tolerance", func(r *outbound.CodeRunRequest) { r.Groups[1].Checker.AbsTolerance = 0 }},
|
||||
{"numbers with NaN tolerance", func(r *outbound.CodeRunRequest) { r.Groups[1].Checker.AbsTolerance = math.NaN() }},
|
||||
{"numbers with negative tolerance", func(r *outbound.CodeRunRequest) { r.Groups[1].Checker.RelTolerance = -1 }},
|
||||
{"numbers with relative tolerance above 1", func(r *outbound.CodeRunRequest) { r.Groups[1].Checker.RelTolerance = 2 }},
|
||||
{"numbers with a program", func(r *outbound.CodeRunRequest) {
|
||||
r.Groups[1].Checker.Program = &outbound.CodeCheckerProgram{Language: outbound.CodeLanguageGo, Source: "package main"}
|
||||
}},
|
||||
{"custom without program", func(r *outbound.CodeRunRequest) {
|
||||
r.Groups[0].Checker = outbound.CodeChecker{Kind: outbound.CodeCheckerCustom}
|
||||
}},
|
||||
{"custom with tolerance", func(r *outbound.CodeRunRequest) {
|
||||
r.Groups[0].Checker = outbound.CodeChecker{
|
||||
Kind: outbound.CodeCheckerCustom, AbsTolerance: 1,
|
||||
Program: &outbound.CodeCheckerProgram{Language: outbound.CodeLanguageGo, Source: "package main"},
|
||||
}
|
||||
}},
|
||||
{"custom with empty program", func(r *outbound.CodeRunRequest) {
|
||||
r.Groups[0].Checker = outbound.CodeChecker{Kind: outbound.CodeCheckerCustom, Program: &outbound.CodeCheckerProgram{Language: outbound.CodeLanguageGo}}
|
||||
}},
|
||||
{"payload above the runner limit", func(r *outbound.CodeRunRequest) {
|
||||
r.Limits.TimeLimitMs = 100
|
||||
r.Groups = r.Groups[:1]
|
||||
r.Groups[0].Tests = nil
|
||||
for index := range 50 {
|
||||
r.Groups[0].Tests = append(r.Groups[0].Tests, outbound.CodeTest{
|
||||
ID: fmt.Sprintf("t%d", index), Input: strings.Repeat("a", 262144), ExpectedOutput: strings.Repeat("b", 262144),
|
||||
})
|
||||
}
|
||||
}},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
request := validCodeRunRequest()
|
||||
test.change(&request)
|
||||
|
||||
err := request.Validate()
|
||||
|
||||
if !errors.Is(err, outbound.ErrInvalidCodeRunRequest) {
|
||||
t.Fatalf("Validate() error = %v, want ErrInvalidCodeRunRequest", err)
|
||||
}
|
||||
for _, marker := range []string{sourceMarker, "hidden-input-marker", "hidden-output-marker"} {
|
||||
if strings.Contains(err.Error(), marker) {
|
||||
t.Fatalf("Validate() error exposes %q: %v", marker, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodeRunRequestIsRedactedInEveryRendering(t *testing.T) {
|
||||
request := validCodeRunRequest()
|
||||
renderings := []string{
|
||||
request.String(), request.GoString(), request.LogValue().String(),
|
||||
fmt.Sprintf("%v", request), fmt.Sprintf("%+v", request), fmt.Sprintf("%#v", request), fmt.Sprint(request),
|
||||
slog.Group("run", slog.Any("request", request)).Value.String(),
|
||||
}
|
||||
for _, rendered := range renderings {
|
||||
for _, marker := range []string{sourceMarker, "hidden-input-marker", "hidden-output-marker", request.Key.AttemptItemID.String()} {
|
||||
if strings.Contains(rendered, marker) {
|
||||
t.Fatalf("rendering %q exposes %q", rendered, marker)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodeRunnerFailuresShareTheUnavailableUmbrella(t *testing.T) {
|
||||
for name, err := range map[string]error{
|
||||
"disabled": outbound.ErrCodeRunnerDisabled,
|
||||
"unauthorized": outbound.ErrCodeRunnerUnauthorized,
|
||||
"bad response": outbound.ErrCodeRunnerBadResponse,
|
||||
"infrastructure failure": outbound.ErrCodeRunnerInfrastructureFailure,
|
||||
} {
|
||||
if !errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
||||
t.Fatalf("%s is not under ErrCodeRunnerUnavailable", name)
|
||||
}
|
||||
}
|
||||
for name, err := range map[string]error{
|
||||
"invalid request": outbound.ErrInvalidCodeRunRequest,
|
||||
"not found": outbound.ErrCodeRunNotFound,
|
||||
"key reused": outbound.ErrCodeRunKeyReused,
|
||||
} {
|
||||
if errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
||||
t.Fatalf("%s must not read as an unavailable runner", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -242,6 +242,18 @@ services:
|
||||
IDENTITY_SESSION_IDLE_TIMEOUT: ${IDENTITY_SESSION_IDLE_TIMEOUT:-24h}
|
||||
IDENTITY_SESSION_ABSOLUTE_LIFETIME: ${IDENTITY_SESSION_ABSOLUTE_LIFETIME:-168h}
|
||||
ASSESSMENT_DEMO_CATEGORIES_ENABLED: ${ASSESSMENT_DEMO_CATEGORIES_ENABLED:-false}
|
||||
# Own code runner (see docs/en/DEPLOY.md#code-runner-client). Off while
|
||||
# CODE_RUNNER_URL is empty: practice then reports the runner as
|
||||
# unavailable and runs nothing. The token and the run key are secrets;
|
||||
# pass the CA inline (CODE_RUNNER_CA_PEM) or mount a file and set its
|
||||
# in-container path in CODE_RUNNER_CA_FILE. Empty values count as unset.
|
||||
CODE_RUNNER_URL: ${CODE_RUNNER_URL:-}
|
||||
CODE_RUNNER_TOKEN: ${CODE_RUNNER_TOKEN:-}
|
||||
CODE_RUNNER_RUN_KEY: ${CODE_RUNNER_RUN_KEY:-}
|
||||
CODE_RUNNER_CA_FILE: ${CODE_RUNNER_CA_FILE:-}
|
||||
CODE_RUNNER_CA_PEM: ${CODE_RUNNER_CA_PEM:-}
|
||||
CODE_RUNNER_SERVER_NAME: ${CODE_RUNNER_SERVER_NAME:-}
|
||||
CODE_RUNNER_REQUEST_TIMEOUT: ${CODE_RUNNER_REQUEST_TIMEOUT:-}
|
||||
# Proxies whose X-Forwarded-For is believed: only the frontend container,
|
||||
# which has a fixed address on the pinned app network below. Other
|
||||
# containers of that network (Prometheus, exporters, Alloy) are not
|
||||
|
||||
+17
-2
@@ -573,7 +573,7 @@ backend/
|
||||
usecase/files/ shared private file layer: policies, opaque keys, stream limits, checksums
|
||||
usecase/notification/ mail requests and the consumer that stores them as deliveries, the quota gate, the service mail enqueue (`ServiceMailer`), the senders of service mail (`ServiceMailSender`) and of product notifications (`NewNotificationSender`), and their rights checks
|
||||
usecase/notification/mailtemplate/ pure rendering of versioned service emails; the delivery consumer renders notifications with it
|
||||
port/outbound/ readiness, cache, object storage, transaction, outbox, outbox relay, event publishing, event consumption, identity, consent ledger, organization and membership, policy, password hashing, and mail boundaries
|
||||
port/outbound/ readiness, cache, object storage, transaction, outbox, outbox relay, event publishing, event consumption, identity, consent ledger, organization and membership, policy, password hashing, mail, and code runner boundaries
|
||||
adapter/primary/http/
|
||||
api/ generated ogen handler
|
||||
middleware/ request log and request metrics by route template
|
||||
@@ -588,7 +588,9 @@ backend/
|
||||
mail/resend/ mail transport that sends one request to the Resend HTTP API per message
|
||||
mail/resend/resendfixture/ local stand-in for the Resend API, for tests only; production never imports it
|
||||
ml/api/ generated client from backend/codegen/ogen-ml.yml
|
||||
code_runner/ client of the code runner: TLS 1.3 transport pinned to the configured CA, opaque idempotent run IDs, request and response validation
|
||||
code_runner/api/ generated client from backend/codegen/ogen-code-runner.yml
|
||||
code_runner/disabled/ code runner that runs nothing and reports itself unavailable
|
||||
postgres/ pool, migrator, transactor, outbox writer and relay store, event consumer store, identity, consent ledger, organization, membership, and policy repositories, health check
|
||||
postgres/sqlc/ generated SQL adapter
|
||||
redis/ cache adapter and Redis check
|
||||
@@ -746,10 +748,23 @@ A checker is set per group: `exact`, `tokens`, `numbers` (numeric tokens are equ
|
||||
|
||||
Outcomes distinguish `accepted`, `wrong_answer`, `compile_error` (for Python, a syntax check with `compile()` before the tests; for Go, compile and link), `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` (including the process limit), and `infrastructure_failure`. Test time is the CPU time of every process of the test, including interpreter startup; memory is the cgroup peak of the test, including nsjail and file cache charged to the test.
|
||||
|
||||
Planned and not implemented: deployment of the runner VM with TLS, firewall, and monitoring; calls from the backend and the run queue; service metrics; running the A16 suite on the runner VM.
|
||||
Planned and not implemented: deployment of the runner VM with TLS, firewall, and monitoring; the run queue and the practice usecases that call the backend port (the port and its client are implemented, see below); service metrics; running the A16 suite on the runner VM.
|
||||
|
||||
The A16 hostile-program suite (`make -C runner test-a16`, see [checks](TESTING.md#a16-hostile-program-suite)) is implemented and passes locally. Code practice is enabled only after the suite has passed on the runner VM with the verdict `pass`; any failed case blocks enabling it.
|
||||
|
||||
#### Backend port and client
|
||||
|
||||
Implemented: the outbound `CodeRunner` port (`backend/internal/port/outbound/code_runner.go`), its client over HTTPS (`backend/internal/adapter/secondary/code_runner/`, built on the generated client in `api/`), and the disabled runner (`code_runner/disabled/`). Bootstrap selects the runner from `CODE_RUNNER_URL` (`bootstrap/code_runner.go`): an unset URL selects the disabled runner, a set one the client, and an unusable setting stops startup instead of falling back. Nothing calls the port yet: the practice usecases, the run queue, and scoring are planned. The environment variables are in [DEPLOY.md](DEPLOY.md#code-runner-client).
|
||||
|
||||
- What leaves the backend. A request holds the language, the source, the technical limits, and the test groups with their checkers; the checker program of a task family is part of a group. It holds no account, attempt, task, or company identifier and no name or contact. `CodeRunRequest.Validate` checks the runner contract rules (ranges, unique IDs, checker parameters, the CPU budget of 300000 ms, the payload size) before anything is sent. A request prints as `[redacted code run request]` in every format and in logs, because the source is candidate work and the hidden tests are task secrets.
|
||||
- Two calls, no hidden retries. `Submit` is idempotent by run key and reports `running`, `finished`, or `busy`; `Poll` reads the run without sending the payload again. Each makes one runner call and neither retries nor sleeps. `busy` is the runner's 503 `runner_busy`: the runner stored nothing, `RetryAfter` carries its `Retry-After`, and the caller keeps the queue and submits again with the same key. When the runner has lost a run (a restart or the retention time), `Poll` returns `ErrCodeRunNotFound` and the caller submits again.
|
||||
- Opaque idempotent run ID. The run ID is HMAC-SHA256 over the attempt item ID, the submission ID, and a generation counter, keyed with `CODE_RUNNER_RUN_KEY` and domain-separated, formatted as a UUID. A retry of the same submission therefore reuses the run and the runner starts it once, while the runner cannot link an ID to an attempt or a submission and nobody can guess the ID of another submission. The key differs from the service token, which the runner knows. After a run the runner could not evaluate, the caller raises the generation: the runner keeps the stored failure under the old ID. The same key with another payload is refused (`ErrCodeRunKeyReused`).
|
||||
- Infrastructure failure is never a verdict. `finished` always holds a validated result with the outcomes `accepted`, `wrong_answer`, `compile_error`, `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, and `runtime_error`, per group and test. Everything else is an error: `ErrCodeRunnerUnavailable` is the umbrella for a disabled runner, an unreachable one, a timeout, a failed TLS check, a rejected token (`ErrCodeRunnerUnauthorized`, HTTP 401), a server error, an answer outside the contract (`ErrCodeRunnerBadResponse`), and a run that finished with `infrastructure_failure` (`ErrCodeRunnerInfrastructureFailure`). With such an error the returned status is empty. A caller must report the practice as unavailable and keep the submission ungraded; it never scores, fails, or accepts it. A request the runner rejects as invalid (400, 413) is `ErrInvalidCodeRunRequest`, a bug of the task content, not of the candidate.
|
||||
- Response validation. The generated client already checks the schema. The adapter adds the rules the schema cannot express: the run ID equals the one derived, a `running` run has no result, a 202 answer is `running`, the groups and tests of the result are the requested ones in order with the requested counts, a group stops at its first failed test, `passed_tests` equals the accepted tests, and the group, compile, and run outcomes agree with each other (the run outcome is `compile_error` or the outcome of the first failed group). A hidden test never passes on a diagnostic, even if a faulty runner sends one. A body above 4 MiB fails.
|
||||
- Transport. TLS 1.3 only, the runner certificate is verified against the configured CA alone (the system roots are not trusted; there is no switch that skips verification), the optional `CODE_RUNNER_SERVER_NAME` changes only the name checked, redirects and environment proxies are not followed, one request is limited by `CODE_RUNNER_REQUEST_TIMEOUT`, and the token is sent only in the `Authorization` header and appears in no error or log. Error texts name the failure class, never the URL or the response body.
|
||||
|
||||
What the checks cover: the fixture tests run the client against a local TLS 1.3 stand-in that speaks the `api/runner` protocol (success, every outcome, compile error, runner timeout, busy, 401 and 5xx, malformed and contradictory answers, a stopped service, a foreign CA, TLS 1.2, idempotent retry). They do not prove sandbox isolation or behavior on the production runner VM. The run on a real runner is `make -C backend test-code-runner-live` (see DEPLOY) and has not been performed against the runner VM.
|
||||
|
||||
## Matching and explanations
|
||||
|
||||
Implemented as a deterministic search without ML: `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.en.md](../../api/README.en.md#match-search)). Code: the usecase `backend/internal/usecase/matching/` (`search.go` the flow, `filter.go` the filters, `score.go` the integer scoring, `explain.go` the explanation), the card list `candidateview.Service.ListVisibleCards`, the policy section `domain.MatchingPolicy` (`policy_matching.go`), the skill relations `domain.RelateEvidenceSkill` (`evidence_relation.go`), the handler `adapter/primary/http/v1/matches.go`, and the wiring `bootstrap/matches.go`. There is no new table, migration, or query file: the search reuses the barrier queries that the card and the evidence already use, so there is one copy of the visibility rule.
|
||||
|
||||
+17
-2
@@ -573,7 +573,7 @@ backend/
|
||||
usecase/files/ общий закрытый файловый слой: политики, непрозрачные ключи, лимиты потока, контрольные суммы
|
||||
usecase/notification/ запросы писем и обработчик, который сохраняет их как доставки, шлюз квот, постановка служебной почты (`ServiceMailer`) и отправители служебной почты (`ServiceMailSender`) и продуктовых уведомлений (`NewNotificationSender`) с проверкой прав
|
||||
usecase/notification/mailtemplate/ чистый рендеринг версионированных служебных писем; обработчик доставки рендерит им уведомления
|
||||
port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, relay outbox, публикации и потребления событий, identity, журнала согласий, организаций и членств, политики, хеширования паролей и почты
|
||||
port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, relay outbox, публикации и потребления событий, identity, журнала согласий, организаций и членств, политики, хеширования паролей, почты и исполнителя кода
|
||||
adapter/primary/http/
|
||||
api/ generated ogen handler
|
||||
middleware/ журнал и метрики запросов по шаблону маршрута
|
||||
@@ -588,7 +588,9 @@ backend/
|
||||
mail/resend/ почтовый транспорт, который отправляет одно письмо одним запросом к HTTP API Resend
|
||||
mail/resend/resendfixture/ локальная замена API Resend только для тестов; production ее не импортирует
|
||||
ml/api/ generated client из backend/codegen/ogen-ml.yml
|
||||
code_runner/ клиент исполнителя кода: транспорт TLS 1.3 с привязкой к заданному CA, непрозрачные идемпотентные ID прогонов, проверка запроса и ответа
|
||||
code_runner/api/ generated client из backend/codegen/ogen-code-runner.yml
|
||||
code_runner/disabled/ исполнитель кода, который ничего не запускает и сообщает о недоступности
|
||||
postgres/ pool, migrator, transactor, запись outbox и хранилище relay, хранилище обработчиков событий, репозитории identity, журнала согласий, организаций, членств и политики, health check
|
||||
postgres/sqlc/ generated SQL adapter
|
||||
redis/ адаптер кеша и проверка Redis
|
||||
@@ -746,10 +748,23 @@ Checker задается для группы: `exact`, `tokens`, `numbers` (чи
|
||||
|
||||
Исходы различают `accepted`, `wrong_answer`, `compile_error` (для Python - проверка синтаксиса через `compile()` до тестов, для Go - компиляция и линковка), `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` (включая лимит процессов) и `infrastructure_failure`. Время теста - CPU всех процессов теста вместе с запуском интерпретатора; память - пик cgroup теста, включая nsjail и файловый кеш, отнесенный к тесту.
|
||||
|
||||
Запланировано и не реализовано: развертывание VM исполнителя с TLS, firewall и мониторингом; вызов исполнителя из backend и очередь прогонов; метрики сервиса; прогон набора A16 на VM исполнителя.
|
||||
Запланировано и не реализовано: развертывание VM исполнителя с TLS, firewall и мониторингом; очередь прогонов и usecase практики, которые вызывают порт backend (порт и его клиент реализованы, см. ниже); метрики сервиса; прогон набора A16 на VM исполнителя.
|
||||
|
||||
Набор враждебных программ A16 (`make -C runner test-a16`, см. [проверки](TESTING.md#набор-враждебных-программ-a16)) реализован и проходит локально. Практика с кодом включается только после того, как набор прошел на VM исполнителя с вердиктом `pass`; любой проваленный случай блокирует включение.
|
||||
|
||||
#### Порт и клиент в backend
|
||||
|
||||
Реализовано: исходящий порт `CodeRunner` (`backend/internal/port/outbound/code_runner.go`), его клиент по HTTPS (`backend/internal/adapter/secondary/code_runner/` поверх generated client в `api/`) и отключенный исполнитель (`code_runner/disabled/`). Bootstrap выбирает исполнителя по `CODE_RUNNER_URL` (`bootstrap/code_runner.go`): незаданный URL выбирает отключенного исполнителя, заданный - клиент, а непригодная настройка останавливает запуск и не откатывается к другому варианту. Порт пока никто не вызывает: usecase практики, очередь прогонов и подсчет баллов запланированы. Переменные окружения описаны в [DEPLOY.md](DEPLOY.md#клиент-исполнителя-кода).
|
||||
|
||||
- Что уходит из backend. Запрос содержит язык, исходный код, технические лимиты и группы тестов с их checker; программа checker семейства задач входит в группу. В нем нет идентификатора аккаунта, попытки, задачи или компании, имени и контактов. `CodeRunRequest.Validate` проверяет правила контракта исполнителя (диапазоны, уникальные ID, параметры checker, CPU-бюджет 300000 мс, размер запроса) до отправки. Запрос печатается как `[redacted code run request]` в любом формате и в логах, потому что исходный код - работа кандидата, а скрытые тесты - секрет задачи.
|
||||
- Два вызова без скрытых повторов. `Submit` идемпотентен по ключу прогона и сообщает `running`, `finished` или `busy`; `Poll` читает прогон, не отправляя данные снова. Каждый делает один вызов исполнителя и не повторяет и не ждет. `busy` - это 503 `runner_busy` исполнителя: он ничего не сохранил, `RetryAfter` несет его `Retry-After`, а очередь ведет вызывающий и отправляет снова с тем же ключом. Если исполнитель потерял прогон (перезапуск или истекшее хранение), `Poll` возвращает `ErrCodeRunNotFound`, и вызывающий отправляет прогон заново.
|
||||
- Непрозрачный идемпотентный ID прогона. ID - это HMAC-SHA256 от ID элемента попытки, ID отправки и счетчика поколения с ключом `CODE_RUNNER_RUN_KEY` и разделением доменов, оформленный как UUID. Повтор той же отправки поэтому использует тот же прогон, и исполнитель запускает его один раз, но исполнитель не может связать ID с попыткой или отправкой, и никто не угадает ID чужой отправки. Ключ отличается от сервисного токена, который знает исполнитель. После прогона, который исполнитель не смог оценить, вызывающий повышает поколение: исполнитель хранит сбой под старым ID. Тот же ключ с другими данными отклоняется (`ErrCodeRunKeyReused`).
|
||||
- Сбой инфраструктуры никогда не вердикт. `finished` всегда содержит проверенный результат с исходами `accepted`, `wrong_answer`, `compile_error`, `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded` и `runtime_error` по группам и тестам. Все остальное - ошибка: `ErrCodeRunnerUnavailable` объединяет отключенного исполнителя, недоступного, таймаут, неудачную проверку TLS, отклоненный токен (`ErrCodeRunnerUnauthorized`, HTTP 401), ошибку сервера, ответ вне контракта (`ErrCodeRunnerBadResponse`) и прогон, завершенный с `infrastructure_failure` (`ErrCodeRunnerInfrastructureFailure`). При такой ошибке возвращаемый статус пуст. Вызывающий должен сообщить, что практика недоступна, и оставить отправку неоцененной; он никогда не начисляет баллы, не проваливает и не принимает ее. Запрос, который исполнитель отклонил как неверный (400, 413), - это `ErrInvalidCodeRunRequest`, ошибка содержимого задачи, а не кандидата.
|
||||
- Проверка ответа. Generated client уже проверяет схему. Адаптер добавляет правила, которые схема выразить не может: ID прогона равен выведенному, у `running` нет результата, ответ 202 - это `running`, группы и тесты результата - запрошенные, в том же порядке и с теми же числами, группа останавливается на первом проваленном тесте, `passed_tests` равен числу принятых тестов, а исходы группы, компиляции и прогона согласованы (исход прогона - `compile_error` или исход первой проваленной группы). Диагностика скрытого теста не передается дальше, даже если ее прислал неисправный исполнитель. Тело больше 4 МиБ отклоняется.
|
||||
- Транспорт. Только TLS 1.3; сертификат исполнителя проверяется только по заданному CA (системные корни не доверенные, переключателя, который отключает проверку, нет); необязательный `CODE_RUNNER_SERVER_NAME` меняет только проверяемое имя; редиректы и прокси из окружения не используются; один запрос ограничен `CODE_RUNNER_REQUEST_TIMEOUT`; токен отправляется только в заголовке `Authorization` и не попадает ни в ошибки, ни в логи. Тексты ошибок называют класс сбоя, но не URL и не тело ответа.
|
||||
|
||||
Что покрывают проверки: тесты с fixture запускают клиент против локальной замены с TLS 1.3, которая говорит по протоколу `api/runner` (успех, каждый исход, ошибка компиляции, таймаут исполнителя, занятость, 401 и 5xx, искаженные и противоречивые ответы, остановленный сервис, чужой CA, TLS 1.2, идемпотентный повтор). Они не доказывают изоляцию песочницы и поведение на производственной VM исполнителя. Прогон на настоящем исполнителе - `make -C backend test-code-runner-live` (см. DEPLOY); против VM исполнителя он не выполнялся.
|
||||
|
||||
## Подбор и объяснение
|
||||
|
||||
Реализован как детерминированный поиск без ML: `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.md](../../api/README.md#подбор)). Код: usecase `backend/internal/usecase/matching/` (`search.go` - порядок работы, `filter.go` - фильтры, `score.go` - целочисленный расчет, `explain.go` - объяснение), список карточек `candidateview.Service.ListVisibleCards`, раздел политики `domain.MatchingPolicy` (`policy_matching.go`), связи навыков `domain.RelateEvidenceSkill` (`evidence_relation.go`), обработчик `adapter/primary/http/v1/matches.go` и сборка `bootstrap/matches.go`. Новых таблиц, миграций и файлов запросов нет: поиск использует барьерные запросы, которыми уже пользуются карточка и доказательства, поэтому правило видимости существует в одном экземпляре.
|
||||
|
||||
Reference in new issue
Block a user