Files

352 lines
13 KiB
Go

// 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() }