Files
ARTEX/sandbox/runner.go
Marco Azarmaneche 3eedbdc326 fix(sandbox): pass scope entries on in canonical form and refuse IPv6 zones
Review of the scope filter:
- netip.ParseAddr accepts any text after % as an IPv6 zone, commas
  included, so "fe80::1%eth0,10.0.0.0/8" was kept and the comma join
  added 10.0.0.0/8. Zoned addresses are now dropped, and every kept
  entry is passed on in canonical form (p.Masked().String(),
  a.String()), which never holds a comma or space. IPv4-mapped entries
  become the IPv4 range they map.
- The cap was 1,024 entries; a company scope can be larger. It is now
  8,192 entries and 120 KiB per list (the proxy gets each list as one
  environment string, limited to 128 KiB).
- The runner logs dropped entries with the task ID and their values (up
  to 20), so an operator can see why an approved target is refused.
- More names that make a shell or interpreter run extra code are
  refused: SHELLOPTS, BASHOPTS, PS4, IFS, PROMPT_COMMAND, GLIBC_TUNABLES,
  PYTHONSTARTUP, PYTHONHOME, NODE_OPTIONS, PERL5OPT, PERL5LIB, RUBYOPT,
  JAVA_TOOL_OPTIONS, GIT_SSH_COMMAND, GIT_CONFIG_PARAMETERS.
2026-12-03 14:38:15 +02:00

173 lines
5.0 KiB
Go

package sandbox
import (
"context"
"crypto/subtle"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"strings"
)
// Backend is the container lifecycle backend used by RunnerServer (DockerBackend in production,
// fake backend in unit tests).
type Backend interface {
Ping(ctx context.Context) error
Recover(ctx context.Context) (int, error)
WorkerCount() int
Exec(ctx context.Context, taskID string, req ExecRequest) (ExecResponse, error)
Kill(ctx context.Context, taskID string) error
Delete(ctx context.Context, taskID string) error
}
// RunnerServer implements the pinned HTTP API from CONTRACT.md §3.
type RunnerServer struct {
token string
version string
backend Backend
mux *http.ServeMux
}
// NewRunnerServer builds an authenticated RunnerServer. Empty token is refused.
func NewRunnerServer(token, version string, backend Backend) (*RunnerServer, error) {
token = strings.TrimSpace(token)
if token == "" {
return nil, errors.New("ARTEX_RUNNER_TOKEN is required")
}
if version == "" {
version = "dev"
}
rs := &RunnerServer{
token: token,
version: version,
backend: backend,
mux: http.NewServeMux(),
}
rs.mux.HandleFunc("GET /v1/health", rs.withAuth(rs.handleHealth))
rs.mux.HandleFunc("POST /v1/tasks/{id}/exec", rs.withAuth(rs.handleExec))
rs.mux.HandleFunc("POST /v1/tasks/{id}/kill", rs.withAuth(rs.handleKill))
rs.mux.HandleFunc("DELETE /v1/tasks/{id}", rs.withAuth(rs.handleDelete))
return rs, nil
}
// Handler returns the HTTP handler for artex-runner.
func (rs *RunnerServer) Handler() http.Handler { return rs.mux }
func (rs *RunnerServer) withAuth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
if !strings.HasPrefix(auth, "Bearer ") {
writeRunnerErr(w, http.StatusUnauthorized, "missing bearer token")
return
}
got := strings.TrimPrefix(auth, "Bearer ")
if subtle.ConstantTimeCompare([]byte(got), []byte(rs.token)) != 1 {
writeRunnerErr(w, http.StatusUnauthorized, "invalid bearer token")
return
}
next(w, r)
}
}
func (rs *RunnerServer) handleHealth(w http.ResponseWriter, r *http.Request) {
dockerOK := rs.backend != nil && rs.backend.Ping(r.Context()) == nil
workers := 0
if rs.backend != nil {
workers = rs.backend.WorkerCount()
}
resp := HealthResponse{
OK: dockerOK,
Docker: dockerOK,
Workers: workers,
Version: rs.version,
}
if !dockerOK {
writeRunnerJSON(w, http.StatusConflict, resp)
return
}
writeRunnerJSON(w, http.StatusOK, resp)
}
func (rs *RunnerServer) handleExec(w http.ResponseWriter, r *http.Request) {
taskID := r.PathValue("id")
if err := ValidateTaskID(taskID); err != nil {
writeRunnerErr(w, http.StatusBadRequest, err.Error())
return
}
var req ExecRequest
dec := json.NewDecoder(io.LimitReader(r.Body, 1<<20))
if err := dec.Decode(&req); err != nil {
writeRunnerErr(w, http.StatusBadRequest, "invalid json: "+err.Error())
return
}
if err := ValidateExecRequest(&req); err != nil {
writeRunnerErr(w, http.StatusBadRequest, err.Error())
return
}
if d := req.droppedScope; len(d) > 0 {
if len(d) > 20 {
d = append(d[:20:20], fmt.Sprintf("... %d more", len(req.droppedScope)-20))
}
log.Printf("[runner] task %s: dropped %d invalid scope entries: %q", taskID, len(req.droppedScope), d)
}
res, err := rs.backend.Exec(r.Context(), taskID, req)
if err != nil {
rs.writeBackendErr(w, err)
return
}
writeRunnerJSON(w, http.StatusOK, res)
}
func (rs *RunnerServer) handleKill(w http.ResponseWriter, r *http.Request) {
taskID := r.PathValue("id")
if err := ValidateTaskID(taskID); err != nil {
writeRunnerErr(w, http.StatusBadRequest, err.Error())
return
}
if err := rs.backend.Kill(r.Context(), taskID); err != nil {
rs.writeBackendErr(w, err)
return
}
writeRunnerJSON(w, http.StatusOK, KillResponse{Killed: true})
}
func (rs *RunnerServer) handleDelete(w http.ResponseWriter, r *http.Request) {
taskID := r.PathValue("id")
if err := ValidateTaskID(taskID); err != nil {
writeRunnerErr(w, http.StatusBadRequest, err.Error())
return
}
if err := rs.backend.Delete(r.Context(), taskID); err != nil {
rs.writeBackendErr(w, err)
return
}
writeRunnerJSON(w, http.StatusOK, DeleteResponse{Deleted: true})
}
func (rs *RunnerServer) writeBackendErr(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, ErrBadRequest):
writeRunnerErr(w, http.StatusBadRequest, err.Error())
case errors.Is(err, ErrNotFound):
writeRunnerErr(w, http.StatusNotFound, err.Error())
case errors.Is(err, ErrDockerUnavailable):
writeRunnerErr(w, http.StatusConflict, err.Error())
default:
log.Printf("[runner] backend error: %v", err)
writeRunnerErr(w, http.StatusInternalServerError, fmt.Sprintf("runner error: %v", err))
}
}
func writeRunnerJSON(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
_ = json.NewEncoder(w).Encode(v)
}
func writeRunnerErr(w http.ResponseWriter, code int, msg string) {
writeRunnerJSON(w, code, map[string]string{"error": msg})
}