feat(runner): add the own code runner contract, client and nsjail service

This commit is contained in:
shira committed 2026-10-11 08:23:42 +03:00
1 parent 5e1db37746
commit cdf6bcbb91
109 files changed
+24084 -28

No files matched your search

+84
View File
@@ -0,0 +1,84 @@
package sandbox
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
)
const (
// The jailed user only reads and traverses the box; it owns nothing.
boxDirMode = 0o555
boxFileMode = 0o444
// ownerOnlyMode lets the supervisor delete the box again.
ownerOnlyMode = 0o700
// workRootMode lets nsjail traverse to a box without listing the root:
// inside its user namespace host root's DAC override does not apply.
workRootMode = 0o711
boxPrefix = "run-"
)
// Box is the host directory with the files of one run. It is mounted
// read-only into every jail of the run and removed with Remove.
type Box struct {
dir string
}
// Dir returns the host path of the box.
func (b *Box) Dir() string {
return b.dir
}
// CreateBox creates a box under root with one file.
func CreateBox(root, fileName string, content []byte) (*Box, error) {
if fileName == "" || fileName != filepath.Base(fileName) || strings.HasPrefix(fileName, ".") {
return nil, fmt.Errorf("sandbox.CreateBox - invalid file name %q", fileName)
}
dir, err := os.MkdirTemp(root, boxPrefix)
if err != nil {
return nil, fmt.Errorf("sandbox.CreateBox - create: %w", err)
}
box := &Box{dir: dir}
if err := os.WriteFile(filepath.Join(dir, fileName), content, boxFileMode); err != nil {
return nil, errors.Join(fmt.Errorf("sandbox.CreateBox - write: %w", err), box.Remove())
}
if err := os.Chmod(dir, boxDirMode); err != nil {
return nil, errors.Join(fmt.Errorf("sandbox.CreateBox - chmod: %w", err), box.Remove())
}
return box, nil
}
// Remove deletes the box and its files.
func (b *Box) Remove() error {
if err := os.Chmod(b.dir, ownerOnlyMode); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("sandbox.Box.Remove - chmod: %w", err)
}
if err := os.RemoveAll(b.dir); err != nil {
return fmt.Errorf("sandbox.Box.Remove - remove: %w", err)
}
return nil
}
// emptyWorkRoot removes every entry of root, for example boxes of a process
// that crashed, and creates root when it is missing.
func emptyWorkRoot(root string) error {
if err := os.MkdirAll(root, workRootMode); err != nil {
return fmt.Errorf("sandbox.emptyWorkRoot - create: %w", err)
}
if err := os.Chmod(root, workRootMode); err != nil {
return fmt.Errorf("sandbox.emptyWorkRoot - chmod: %w", err)
}
entries, err := os.ReadDir(root)
if err != nil {
return fmt.Errorf("sandbox.emptyWorkRoot - list: %w", err)
}
for _, entry := range entries {
box := &Box{dir: filepath.Join(root, entry.Name())}
if err := box.Remove(); err != nil {
return err
}
}
return nil
}