mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-03 13:11:05 +00:00
applyMoves and rollbackFiles validated the staging journal and then ran os.MkdirAll/os.Rename on host paths. Both the journal Source and the payload Relative resolve under the data directory, so a component swapped for a symlink after validation could move data into or out of the data directory through the staging rename. Open one os.OpenRoot(dataDir) per call and run root.Lstat, root.MkdirAll and root.Rename with names relative to the data directory, rejecting any name that is not strictly beneath it. validateArchiveStageJournal stays unchanged. The restore path is intentionally untouched: its sources live under the per-archive extracted root, which a single Root anchored at dataDir cannot span. Tests make dataDir/tasks, and separately the payload files directory, symlinks that escape the data dir; both applyMoves directions and the rollback escape are refused after the change, while a normal stage and rollback still apply.
1000 lines
32 KiB
Go
1000 lines
32 KiB
Go
package server
|
|
|
|
import (
|
|
"archive/tar"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"io/fs"
|
|
"log"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/Autumn-27/artex/agent"
|
|
pgdb "github.com/Autumn-27/artex/db"
|
|
"github.com/klauspost/compress/zstd"
|
|
)
|
|
|
|
const (
|
|
archiveDirMode = 0o700
|
|
archiveFileMode = 0o600
|
|
maxArchiveFiles = 1_000_000
|
|
maxArchiveBytes = int64(1 << 47) // 128 TiB safety ceiling for corrupt headers.
|
|
)
|
|
|
|
type archiveFileMove struct {
|
|
Source string `json:"source"`
|
|
Relative string `json:"relative"`
|
|
}
|
|
|
|
type archiveStageJournal struct {
|
|
ArchiveID int64 `json:"archive_id"`
|
|
TaskID string `json:"task_id"`
|
|
Moves []archiveFileMove `json:"moves"`
|
|
}
|
|
|
|
type archiveRestoreJournal struct {
|
|
ArchiveID int64 `json:"archive_id"`
|
|
TaskID int64 `json:"task_id"`
|
|
Moves []restoredArchivePath `json:"moves"`
|
|
}
|
|
|
|
type taskArchiveFileStage struct {
|
|
dataDir string
|
|
root string
|
|
payload string
|
|
journal archiveStageJournal
|
|
done bool
|
|
}
|
|
|
|
type restoredArchivePath struct {
|
|
Source string
|
|
Destination string
|
|
}
|
|
|
|
type taskArchiveRestoreFiles struct {
|
|
extracted string
|
|
moves []restoredArchivePath
|
|
done bool
|
|
}
|
|
|
|
func writeArchiveJournal(path string, value any) error {
|
|
raw, err := json.Marshal(value)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
file, err := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, archiveFileMode)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if _, err := file.Write(raw); err != nil {
|
|
_ = file.Close()
|
|
return err
|
|
}
|
|
if err := file.Sync(); err != nil {
|
|
_ = file.Close()
|
|
return err
|
|
}
|
|
return file.Close()
|
|
}
|
|
|
|
func taskArchiveRoot(dataDir string) string {
|
|
return filepath.Join(dataDir, "archives", "tasks")
|
|
}
|
|
|
|
func taskArchivePath(dataDir string, archiveID int64, taskID string) string {
|
|
return filepath.Join(taskArchiveRoot(dataDir), fmt.Sprintf("task-%s-%d.tar.zst", taskID, archiveID))
|
|
}
|
|
|
|
func stageTaskArchiveFiles(dataDir string, archiveID int64, taskID string, explorationID int64) (*taskArchiveFileStage, error) {
|
|
root := filepath.Join(taskArchiveRoot(dataDir), ".staging", strconv.FormatInt(archiveID, 10))
|
|
stage := &taskArchiveFileStage{dataDir: dataDir, root: root, payload: filepath.Join(root, "payload")}
|
|
journalPath := filepath.Join(root, "journal.json")
|
|
if raw, err := os.ReadFile(journalPath); err == nil {
|
|
if err := json.Unmarshal(raw, &stage.journal); err != nil {
|
|
return nil, fmt.Errorf("read task archive staging journal: %w", err)
|
|
}
|
|
if err := validateArchiveStageJournal(dataDir, archiveID, taskID, explorationID, stage.journal); err != nil {
|
|
return nil, fmt.Errorf("invalid task archive staging journal: %w", err)
|
|
}
|
|
// The journal is written before the first rename, so its presence does not mean
|
|
// the payload is complete: a previous round may have failed mid-loop with a
|
|
// rollback that itself errored, which leaves the root in place. Replay the moves
|
|
// rather than packaging a payload that is missing transcripts or workspace files.
|
|
if err := os.MkdirAll(filepath.Join(stage.payload, "files"), archiveDirMode); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := stage.applyMoves(); err != nil {
|
|
_ = stage.rollback()
|
|
return nil, err
|
|
}
|
|
return stage, nil
|
|
} else if !os.IsNotExist(err) {
|
|
return nil, err
|
|
}
|
|
if err := os.MkdirAll(filepath.Join(stage.payload, "files"), archiveDirMode); err != nil {
|
|
return nil, err
|
|
}
|
|
stage.journal = archiveStageJournal{ArchiveID: archiveID, TaskID: taskID}
|
|
targets := []archiveFileMove{}
|
|
taskDir := filepath.Join(dataDir, "tasks", taskID)
|
|
if _, err := os.Lstat(taskDir); err == nil {
|
|
targets = append(targets, archiveFileMove{Source: taskDir, Relative: filepath.Join("files", "tasks", taskID)})
|
|
} else if !os.IsNotExist(err) {
|
|
return nil, err
|
|
}
|
|
// The command-output spills of the task are packed and deleted with it.
|
|
spillDir := agent.TaskSpillDir(dataDir, taskID)
|
|
if _, err := os.Lstat(spillDir); err == nil {
|
|
targets = append(targets, archiveFileMove{Source: spillDir, Relative: filepath.Join("files", "spill", "tasks", taskID)})
|
|
} else if !os.IsNotExist(err) {
|
|
return nil, err
|
|
}
|
|
transcriptDir := filepath.Join(dataDir, "transcripts")
|
|
entries, err := os.ReadDir(transcriptDir)
|
|
if err != nil && !os.IsNotExist(err) {
|
|
return nil, err
|
|
}
|
|
prefix := fmt.Sprintf("exp%d-", explorationID)
|
|
for _, entry := range entries {
|
|
name := entry.Name()
|
|
if !strings.HasPrefix(name, prefix) || (!entry.IsDir() && !strings.HasSuffix(name, ".jsonl")) {
|
|
continue
|
|
}
|
|
targets = append(targets, archiveFileMove{
|
|
Source: filepath.Join(transcriptDir, name), Relative: filepath.Join("files", "transcripts", name),
|
|
})
|
|
}
|
|
// Persist the complete plan before the first rename. Recovery can therefore
|
|
// roll back any prefix of the moves after an abrupt process termination.
|
|
stage.journal.Moves = targets
|
|
if err := writeArchiveJournal(journalPath, stage.journal); err != nil {
|
|
_ = stage.rollback()
|
|
return nil, err
|
|
}
|
|
if err := stage.applyMoves(); err != nil {
|
|
_ = stage.rollback()
|
|
return nil, err
|
|
}
|
|
return stage, nil
|
|
}
|
|
|
|
// archiveRelUnder returns path as a clean name relative to root, refusing
|
|
// names that are not strictly beneath root. Both the staging source and the
|
|
// payload destination live under the data directory, so a single os.Root can
|
|
// anchor every rename.
|
|
func archiveRelUnder(root, path string) (string, error) {
|
|
rel, err := filepath.Rel(filepath.Clean(root), filepath.Clean(path))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) {
|
|
return "", fmt.Errorf("path %s escapes %s", path, root)
|
|
}
|
|
return rel, nil
|
|
}
|
|
|
|
// applyMoves performs the renames recorded in the journal. Entries already sitting
|
|
// in the payload are skipped, so an interrupted staging round can be resumed in
|
|
// place without moving anything twice. The renames run through
|
|
// os.OpenRoot(dataDir) so a path component swapped for an escaping symlink after
|
|
// validation cannot move data outside the data directory.
|
|
func (s *taskArchiveFileStage) applyMoves() error {
|
|
dataDir := s.resolvedDataDir()
|
|
if err := validateArchiveStageJournal(dataDir, 0, "", 0, s.journal); err != nil {
|
|
return fmt.Errorf("invalid task archive staging journal: %w", err)
|
|
}
|
|
root, err := os.OpenRoot(dataDir)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer root.Close()
|
|
for _, move := range s.journal.Moves {
|
|
destination := filepath.Join(s.payload, move.Relative)
|
|
destinationRel, err := archiveRelUnder(dataDir, destination)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if _, err := root.Lstat(destinationRel); err == nil {
|
|
continue
|
|
} else if !errors.Is(err, fs.ErrNotExist) {
|
|
return err
|
|
}
|
|
sourceRel, err := archiveRelUnder(dataDir, move.Source)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if _, err := root.Lstat(sourceRel); err != nil {
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
// Neither side exists: the path was removed outside the archive flow
|
|
// after the journal was written. Nothing can be staged for it.
|
|
continue
|
|
}
|
|
return err
|
|
}
|
|
if parent := filepath.Dir(destinationRel); parent != "." {
|
|
if err := root.MkdirAll(parent, archiveDirMode); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if err := root.Rename(sourceRel, destinationRel); err != nil {
|
|
return fmt.Errorf("stage task archive path %s: %w", move.Source, err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *taskArchiveFileStage) rollback() error {
|
|
if s == nil || s.done {
|
|
return nil
|
|
}
|
|
err := s.rollbackFiles()
|
|
if err == nil {
|
|
err = os.RemoveAll(s.root)
|
|
}
|
|
s.done = true
|
|
return err
|
|
}
|
|
|
|
// Keep the journal until the caller has also cleaned temporary packages.
|
|
// Like applyMoves, every rename runs through os.OpenRoot(dataDir) so a swapped
|
|
// path component cannot restore data outside the data directory.
|
|
func (s *taskArchiveFileStage) rollbackFiles() error {
|
|
dataDir := s.resolvedDataDir()
|
|
if err := validateArchiveStageJournal(dataDir, 0, "", 0, s.journal); err != nil {
|
|
return fmt.Errorf("invalid task archive staging journal: %w", err)
|
|
}
|
|
root, err := os.OpenRoot(dataDir)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer root.Close()
|
|
var errs []error
|
|
for i := len(s.journal.Moves) - 1; i >= 0; i-- {
|
|
move := s.journal.Moves[i]
|
|
staged := filepath.Join(s.payload, move.Relative)
|
|
stagedRel, err := archiveRelUnder(dataDir, staged)
|
|
if err != nil {
|
|
errs = append(errs, err)
|
|
continue
|
|
}
|
|
if _, err := root.Lstat(stagedRel); errors.Is(err, fs.ErrNotExist) {
|
|
continue
|
|
} else if err != nil {
|
|
errs = append(errs, err)
|
|
continue
|
|
}
|
|
sourceRel, err := archiveRelUnder(dataDir, move.Source)
|
|
if err != nil {
|
|
errs = append(errs, err)
|
|
continue
|
|
}
|
|
if _, err := root.Lstat(sourceRel); err == nil {
|
|
errs = append(errs, fmt.Errorf("archive rollback destination exists: %s", move.Source))
|
|
continue
|
|
} else if !errors.Is(err, fs.ErrNotExist) {
|
|
errs = append(errs, err)
|
|
continue
|
|
}
|
|
if parent := filepath.Dir(sourceRel); parent != "." {
|
|
if err := root.MkdirAll(parent, 0o755); err != nil {
|
|
errs = append(errs, err)
|
|
continue
|
|
}
|
|
}
|
|
if err := root.Rename(stagedRel, sourceRel); err != nil {
|
|
errs = append(errs, err)
|
|
}
|
|
}
|
|
return errors.Join(errs...)
|
|
}
|
|
|
|
func (s *taskArchiveFileStage) commit() error {
|
|
if s == nil || s.done {
|
|
return nil
|
|
}
|
|
s.done = true
|
|
return os.RemoveAll(s.root)
|
|
}
|
|
|
|
// installTaskArchiveFiles moves the extracted workspace, spill directory and
|
|
// transcripts back under the data directory. The workspace is the whole task
|
|
// directory, run directories (main/, i<N>/) included; priv puts their ownership
|
|
// back, and that of the spill directory.
|
|
func installTaskArchiveFiles(dataDir, extractedDir, taskID string, archiveID int64, priv ExecPrivilege) (*taskArchiveRestoreFiles, error) {
|
|
stage := &taskArchiveRestoreFiles{extracted: extractedDir}
|
|
numericTaskID, err := strconv.ParseInt(taskID, 10, 64)
|
|
if err != nil || numericTaskID <= 0 {
|
|
return nil, fmt.Errorf("invalid restore task id %q", taskID)
|
|
}
|
|
sources := []restoredArchivePath{}
|
|
workspace := filepath.Join(extractedDir, "files", "tasks", taskID)
|
|
taskDir := filepath.Join(dataDir, "tasks", taskID)
|
|
hasWorkspace := false
|
|
if _, err := os.Lstat(workspace); err == nil {
|
|
sources = append(sources, restoredArchivePath{Source: workspace, Destination: taskDir})
|
|
hasWorkspace = true
|
|
} else if !os.IsNotExist(err) {
|
|
return nil, err
|
|
}
|
|
spill := filepath.Join(extractedDir, "files", "spill", "tasks", taskID)
|
|
spillDir := agent.TaskSpillDir(dataDir, taskID)
|
|
hasSpill := false
|
|
if _, err := os.Lstat(spill); err == nil {
|
|
sources = append(sources, restoredArchivePath{Source: spill, Destination: spillDir})
|
|
hasSpill = true
|
|
} else if !os.IsNotExist(err) {
|
|
return nil, err
|
|
}
|
|
transcripts := filepath.Join(extractedDir, "files", "transcripts")
|
|
entries, err := os.ReadDir(transcripts)
|
|
if err != nil && !os.IsNotExist(err) {
|
|
return nil, err
|
|
}
|
|
for _, entry := range entries {
|
|
sources = append(sources, restoredArchivePath{
|
|
Source: filepath.Join(transcripts, entry.Name()), Destination: filepath.Join(dataDir, "transcripts", entry.Name()),
|
|
})
|
|
}
|
|
for _, move := range sources {
|
|
if _, err := os.Lstat(move.Destination); err == nil {
|
|
return nil, fmt.Errorf("restore destination already exists: %s", move.Destination)
|
|
} else if !os.IsNotExist(err) {
|
|
return nil, err
|
|
}
|
|
}
|
|
stage.moves = sources
|
|
journal := archiveRestoreJournal{ArchiveID: archiveID, TaskID: numericTaskID, Moves: sources}
|
|
if err := writeArchiveJournal(filepath.Join(extractedDir, "restore-journal.json"), journal); err != nil {
|
|
return nil, err
|
|
}
|
|
for _, move := range sources {
|
|
if err := os.MkdirAll(filepath.Dir(move.Destination), 0o755); err != nil {
|
|
_ = stage.rollback()
|
|
return nil, err
|
|
}
|
|
if err := os.Rename(move.Source, move.Destination); err != nil {
|
|
_ = stage.rollback()
|
|
return nil, err
|
|
}
|
|
}
|
|
if hasWorkspace {
|
|
if err := shareRestoredTaskDir(priv, taskDir); err != nil {
|
|
_ = stage.rollback()
|
|
return nil, fmt.Errorf("restore the run directory ownership of %s: %w", taskDir, err)
|
|
}
|
|
}
|
|
if hasSpill {
|
|
if err := shareRestoredSpillDir(priv, spillDir); err != nil {
|
|
_ = stage.rollback()
|
|
return nil, fmt.Errorf("restore the spill directory ownership of %s: %w", spillDir, err)
|
|
}
|
|
}
|
|
return stage, nil
|
|
}
|
|
|
|
func (s *taskArchiveRestoreFiles) rollback() error {
|
|
if s == nil || s.done {
|
|
return nil
|
|
}
|
|
var errs []error
|
|
for i := len(s.moves) - 1; i >= 0; i-- {
|
|
move := s.moves[i]
|
|
if _, err := os.Lstat(move.Destination); os.IsNotExist(err) {
|
|
continue
|
|
} else if err != nil {
|
|
errs = append(errs, err)
|
|
continue
|
|
}
|
|
if _, err := os.Lstat(move.Source); err == nil {
|
|
errs = append(errs, fmt.Errorf("restore rollback source exists: %s", move.Source))
|
|
continue
|
|
} else if !os.IsNotExist(err) {
|
|
errs = append(errs, err)
|
|
continue
|
|
}
|
|
if err := os.MkdirAll(filepath.Dir(move.Source), archiveDirMode); err != nil {
|
|
errs = append(errs, err)
|
|
continue
|
|
}
|
|
if err := os.Rename(move.Destination, move.Source); err != nil {
|
|
errs = append(errs, err)
|
|
}
|
|
}
|
|
s.done = true
|
|
return errors.Join(errs...)
|
|
}
|
|
|
|
func (s *taskArchiveRestoreFiles) commit() error {
|
|
if s == nil || s.done {
|
|
return nil
|
|
}
|
|
s.done = true
|
|
return os.RemoveAll(s.extracted)
|
|
}
|
|
|
|
// recoverTaskArchiveRestoreStages resolves file installs left by an interrupted
|
|
// restore. If PostgreSQL committed, installed files are authoritative and only
|
|
// the extraction directory is stale. Otherwise all completed renames are moved
|
|
// back so the persistent restore job can retry from a clean destination.
|
|
func recoverTaskArchiveRestoreStages(dataDir string, pg *pgdb.DB) error {
|
|
parent := filepath.Join(taskArchiveRoot(dataDir), ".restore")
|
|
entries, err := os.ReadDir(parent)
|
|
if os.IsNotExist(err) {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var errs []error
|
|
for _, entry := range entries {
|
|
if !entry.IsDir() {
|
|
continue
|
|
}
|
|
root := filepath.Join(parent, entry.Name())
|
|
raw, err := os.ReadFile(filepath.Join(root, "restore-journal.json"))
|
|
if os.IsNotExist(err) {
|
|
// Extraction was interrupted before any destination rename.
|
|
if err := os.RemoveAll(root); err != nil {
|
|
errs = append(errs, err)
|
|
}
|
|
continue
|
|
}
|
|
if err != nil {
|
|
errs = append(errs, err)
|
|
continue
|
|
}
|
|
var journal archiveRestoreJournal
|
|
if err := json.Unmarshal(raw, &journal); err != nil {
|
|
errs = append(errs, err)
|
|
continue
|
|
}
|
|
if err := validateArchiveRestoreJournal(dataDir, root, journal); err != nil {
|
|
errs = append(errs, fmt.Errorf("invalid task archive restore journal in %s: %w", entry.Name(), err))
|
|
continue
|
|
}
|
|
restored, err := pg.IsTaskArchiveRestored(journal.ArchiveID)
|
|
if errors.Is(err, pgdb.ErrTaskArchiveNotFound) && journal.TaskID > 0 {
|
|
task, taskErr := pg.GetTask(journal.TaskID)
|
|
if taskErr != nil {
|
|
errs = append(errs, taskErr)
|
|
continue
|
|
}
|
|
restored = task != nil
|
|
err = nil
|
|
}
|
|
if err != nil {
|
|
errs = append(errs, err)
|
|
continue
|
|
}
|
|
if restored {
|
|
if err := os.RemoveAll(root); err != nil {
|
|
errs = append(errs, err)
|
|
}
|
|
continue
|
|
}
|
|
stage := &taskArchiveRestoreFiles{extracted: root, moves: journal.Moves}
|
|
if err := stage.rollback(); err != nil {
|
|
errs = append(errs, err)
|
|
continue
|
|
}
|
|
if err := os.RemoveAll(root); err != nil {
|
|
errs = append(errs, err)
|
|
}
|
|
}
|
|
return errors.Join(errs...)
|
|
}
|
|
|
|
// recoverTaskArchiveStages resolves file renames left by an interrupted archive.
|
|
// A committed cold task already has a verified package, so stale staging can be
|
|
// discarded; otherwise files are moved back before the persistent job retries.
|
|
func recoverTaskArchiveStages(dataDir string, pg *pgdb.DB) error {
|
|
parent := filepath.Join(taskArchiveRoot(dataDir), ".staging")
|
|
entries, err := os.ReadDir(parent)
|
|
if os.IsNotExist(err) {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var errs []error
|
|
for _, entry := range entries {
|
|
if !entry.IsDir() {
|
|
continue
|
|
}
|
|
root := filepath.Join(parent, entry.Name())
|
|
raw, err := os.ReadFile(filepath.Join(root, "journal.json"))
|
|
if os.IsNotExist(err) {
|
|
// Either staging died between creating the directory tree and writing the
|
|
// journal — no rename had run, so payload holds nothing — or commit/rollback
|
|
// failed part-way through removing the root, in which case payload only holds
|
|
// copies already inside the package. Without a journal there is nothing to
|
|
// roll back, and reporting an error here keeps the archive worker from ever
|
|
// starting, so discard the directory instead.
|
|
if err := os.RemoveAll(root); err != nil {
|
|
errs = append(errs, err)
|
|
}
|
|
continue
|
|
}
|
|
if err != nil {
|
|
errs = append(errs, err)
|
|
continue
|
|
}
|
|
dirArchiveID, idErr := strconv.ParseInt(entry.Name(), 10, 64)
|
|
if idErr != nil || dirArchiveID <= 0 {
|
|
errs = append(errs, fmt.Errorf("invalid archive staging directory name %q", entry.Name()))
|
|
continue
|
|
}
|
|
var journal archiveStageJournal
|
|
if err := json.Unmarshal(raw, &journal); err != nil {
|
|
errs = append(errs, err)
|
|
continue
|
|
}
|
|
if err := validateArchiveStageJournal(dataDir, dirArchiveID, "", 0, journal); err != nil {
|
|
errs = append(errs, fmt.Errorf("invalid task archive staging journal in %s: %w", entry.Name(), err))
|
|
continue
|
|
}
|
|
archive, getErr := pg.GetTaskArchive(journal.ArchiveID)
|
|
if getErr != nil {
|
|
errs = append(errs, getErr)
|
|
continue
|
|
}
|
|
if archive != nil {
|
|
if expectedTID := strconv.FormatInt(archive.TaskID, 10); expectedTID != journal.TaskID {
|
|
errs = append(errs, fmt.Errorf("staging journal task_id %q does not match archive task_id %q", journal.TaskID, expectedTID))
|
|
continue
|
|
}
|
|
}
|
|
if archive != nil && archive.ArchivePath != "" && archive.SHA256 != "" {
|
|
if err := os.RemoveAll(root); err != nil {
|
|
errs = append(errs, err)
|
|
}
|
|
continue
|
|
}
|
|
stage := &taskArchiveFileStage{dataDir: dataDir, root: root, payload: filepath.Join(root, "payload"), journal: journal}
|
|
if err := stage.rollbackFiles(); err != nil {
|
|
errs = append(errs, err)
|
|
continue
|
|
}
|
|
// The process can exit after compression but before an upload journal or
|
|
// database location exists. Remove that temporary package only after the
|
|
// source-file rollback succeeds, for both local and remote backends.
|
|
packagePath := taskArchivePath(dataDir, journal.ArchiveID, journal.TaskID)
|
|
if err := validateArchivePath(dataDir, packagePath); err != nil {
|
|
errs = append(errs, err)
|
|
continue
|
|
}
|
|
// A crash inside compression leaves .partial, before any upload journal.
|
|
// Retain this staging journal on cleanup failure so startup can retry.
|
|
if err := errors.Join(removeLocalArchivePackage(packagePath), removeLocalArchivePackage(packagePath+".partial")); err != nil {
|
|
errs = append(errs, err)
|
|
continue
|
|
}
|
|
if err := os.RemoveAll(root); err != nil {
|
|
errs = append(errs, err)
|
|
}
|
|
}
|
|
return errors.Join(errs...)
|
|
}
|
|
|
|
func recoverTaskArchiveDeletePackages(dataDir string, pg *pgdb.DB) error {
|
|
root := taskArchiveRoot(dataDir)
|
|
entries, err := os.ReadDir(root)
|
|
if os.IsNotExist(err) {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var errs []error
|
|
for _, entry := range entries {
|
|
if entry.IsDir() {
|
|
continue
|
|
}
|
|
name := entry.Name()
|
|
marker := strings.LastIndex(name, ".deleting-")
|
|
if marker < 0 {
|
|
continue
|
|
}
|
|
archiveID, err := strconv.ParseInt(name[marker+len(".deleting-"):], 10, 64)
|
|
if err != nil || archiveID <= 0 {
|
|
continue
|
|
}
|
|
staged := filepath.Join(root, name)
|
|
original := filepath.Join(root, name[:marker])
|
|
archive, err := pg.GetTaskArchive(archiveID)
|
|
if err != nil {
|
|
errs = append(errs, err)
|
|
continue
|
|
}
|
|
if archive == nil {
|
|
if err := os.Remove(staged); err != nil && !os.IsNotExist(err) {
|
|
errs = append(errs, err)
|
|
}
|
|
continue
|
|
}
|
|
if archive.State == pgdb.DeleteQueued || archive.State == pgdb.Deleting || archive.State == pgdb.DeleteFailed {
|
|
// The idempotent delete worker consumes the staged path directly.
|
|
continue
|
|
}
|
|
if _, err := os.Lstat(original); err == nil {
|
|
errs = append(errs, fmt.Errorf("archive delete recovery destination exists: %s", original))
|
|
continue
|
|
} else if !os.IsNotExist(err) {
|
|
errs = append(errs, err)
|
|
continue
|
|
}
|
|
if err := os.Rename(staged, original); err != nil {
|
|
errs = append(errs, err)
|
|
}
|
|
}
|
|
return errors.Join(errs...)
|
|
}
|
|
|
|
func stageTaskArchivePackageDelete(archivePath string, archiveID int64) (string, bool, error) {
|
|
staged := archivePath + fmt.Sprintf(".deleting-%d", archiveID)
|
|
if _, err := os.Lstat(staged); err == nil {
|
|
if _, originalErr := os.Lstat(archivePath); originalErr == nil {
|
|
return staged, false, errors.New("archive package original and delete-staging files both exist")
|
|
} else if !os.IsNotExist(originalErr) {
|
|
return staged, false, originalErr
|
|
}
|
|
return staged, true, nil
|
|
} else if !os.IsNotExist(err) {
|
|
return staged, false, err
|
|
}
|
|
if err := os.Rename(archivePath, staged); err == nil {
|
|
return staged, true, nil
|
|
} else if !os.IsNotExist(err) {
|
|
return staged, false, err
|
|
}
|
|
return staged, false, nil
|
|
}
|
|
|
|
func writeTaskArchivePackage(path, payloadDir string, snapshot *pgdb.TaskArchiveSnapshot) (originalSize, compressedSize int64, checksum string, err error) {
|
|
if snapshot == nil {
|
|
return 0, 0, "", errors.New("nil task archive snapshot")
|
|
}
|
|
if err = os.MkdirAll(filepath.Dir(path), archiveDirMode); err != nil {
|
|
return 0, 0, "", err
|
|
}
|
|
manifestFile, err := os.OpenFile(
|
|
filepath.Join(payloadDir, "manifest.json"),
|
|
os.O_CREATE|os.O_TRUNC|os.O_WRONLY,
|
|
archiveFileMode,
|
|
)
|
|
if err != nil {
|
|
return 0, 0, "", err
|
|
}
|
|
encodeErr := json.NewEncoder(manifestFile).Encode(snapshot)
|
|
var syncErr error
|
|
if encodeErr == nil {
|
|
syncErr = manifestFile.Sync()
|
|
}
|
|
if err := errors.Join(encodeErr, syncErr, manifestFile.Close()); err != nil {
|
|
return 0, 0, "", err
|
|
}
|
|
temporary := path + ".partial"
|
|
_ = os.Remove(temporary)
|
|
file, err := os.OpenFile(temporary, os.O_CREATE|os.O_EXCL|os.O_WRONLY, archiveFileMode)
|
|
if err != nil {
|
|
return 0, 0, "", err
|
|
}
|
|
committed := false
|
|
defer func() {
|
|
_ = file.Close()
|
|
if !committed {
|
|
_ = os.Remove(temporary)
|
|
}
|
|
}()
|
|
hasher := sha256.New()
|
|
multi := io.MultiWriter(file, hasher)
|
|
encoder, err := zstd.NewWriter(multi,
|
|
zstd.WithEncoderLevel(zstd.EncoderLevelFromZstd(10)),
|
|
zstd.WithEncoderCRC(true),
|
|
)
|
|
if err != nil {
|
|
return 0, 0, "", err
|
|
}
|
|
tarWriter := tar.NewWriter(encoder)
|
|
walkErr := filepath.WalkDir(payloadDir, func(current string, entry fs.DirEntry, walkErr error) error {
|
|
if walkErr != nil {
|
|
return walkErr
|
|
}
|
|
relative, err := filepath.Rel(payloadDir, current)
|
|
if err != nil || relative == "." {
|
|
return err
|
|
}
|
|
info, err := entry.Info()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if info.Mode()&os.ModeSymlink != 0 {
|
|
// The archive format supports only regular files and directories end to end (the
|
|
// unpacker errors out on other types), so symlinks cannot be restored. Skip rather
|
|
// than fail the whole package: the link target is not read (lstat, never leaves the tree) and no symlink entry is written; when a link points inside the tree, the target file itself is still walked and archived separately.
|
|
log.Printf("[task-archive] skipping symlink (unsupported by the archive, other files unaffected): %s", current)
|
|
return nil
|
|
}
|
|
if !entry.IsDir() && !info.Mode().IsRegular() {
|
|
// A named pipe, socket or device left by a command: opening a pipe blocks until
|
|
// a writer appears, tar refuses a socket, and the unpacker refuses the rest.
|
|
log.Printf("[task-archive] skipping a file that is not regular (unsupported by the archive): %s", current)
|
|
return nil
|
|
}
|
|
header, err := tar.FileInfoHeader(info, "")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
header.Name = filepath.ToSlash(relative)
|
|
if err := tarWriter.WriteHeader(header); err != nil {
|
|
return err
|
|
}
|
|
if entry.IsDir() {
|
|
return nil
|
|
}
|
|
originalSize += info.Size()
|
|
input, err := os.Open(current)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, copyErr := io.Copy(tarWriter, input)
|
|
closeErr := input.Close()
|
|
return errors.Join(copyErr, closeErr)
|
|
})
|
|
if walkErr != nil {
|
|
_ = tarWriter.Close()
|
|
_ = encoder.Close()
|
|
return 0, 0, "", walkErr
|
|
}
|
|
if err := tarWriter.Close(); err != nil {
|
|
_ = encoder.Close()
|
|
return 0, 0, "", err
|
|
}
|
|
if err := encoder.Close(); err != nil {
|
|
return 0, 0, "", err
|
|
}
|
|
if err := file.Sync(); err != nil {
|
|
return 0, 0, "", err
|
|
}
|
|
if err := file.Close(); err != nil {
|
|
return 0, 0, "", err
|
|
}
|
|
stat, err := os.Stat(temporary)
|
|
if err != nil {
|
|
return 0, 0, "", err
|
|
}
|
|
compressedSize = stat.Size()
|
|
checksum = hex.EncodeToString(hasher.Sum(nil))
|
|
if err := os.Rename(temporary, path); err != nil {
|
|
return 0, 0, "", err
|
|
}
|
|
if err := os.Chmod(path, archiveFileMode); err != nil {
|
|
return 0, 0, "", err
|
|
}
|
|
committed = true
|
|
return originalSize, compressedSize, checksum, nil
|
|
}
|
|
|
|
func extractTaskArchivePackage(path, expectedSHA, destination string) error {
|
|
file, err := os.Open(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer file.Close()
|
|
if expectedSHA != "" {
|
|
hasher := sha256.New()
|
|
if _, err := io.Copy(hasher, file); err != nil {
|
|
return err
|
|
}
|
|
if hex.EncodeToString(hasher.Sum(nil)) != strings.ToLower(expectedSHA) {
|
|
return errors.New("task archive checksum mismatch")
|
|
}
|
|
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
decoder, err := zstd.NewReader(file)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer decoder.Close()
|
|
tarReader := tar.NewReader(decoder)
|
|
if err := os.MkdirAll(destination, archiveDirMode); err != nil {
|
|
return err
|
|
}
|
|
var entries int
|
|
var total int64
|
|
for {
|
|
header, err := tarReader.Next()
|
|
if errors.Is(err, io.EOF) {
|
|
break
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
entries++
|
|
if entries > maxArchiveFiles || header.Size < 0 || total+header.Size > maxArchiveBytes {
|
|
return errors.New("task archive exceeds extraction safety limits")
|
|
}
|
|
total += header.Size
|
|
clean := filepath.Clean(filepath.FromSlash(header.Name))
|
|
if clean == "." || filepath.IsAbs(clean) || clean == ".." || strings.HasPrefix(clean, ".."+string(filepath.Separator)) {
|
|
return fmt.Errorf("unsafe task archive path %q", header.Name)
|
|
}
|
|
target := filepath.Join(destination, clean)
|
|
if relative, err := filepath.Rel(destination, target); err != nil || relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) {
|
|
return fmt.Errorf("unsafe task archive target %q", header.Name)
|
|
}
|
|
switch header.Typeflag {
|
|
case tar.TypeDir:
|
|
if err := os.MkdirAll(target, archiveDirMode); err != nil {
|
|
return err
|
|
}
|
|
case tar.TypeReg, tar.TypeRegA:
|
|
if err := os.MkdirAll(filepath.Dir(target), archiveDirMode); err != nil {
|
|
return err
|
|
}
|
|
output, err := os.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_WRONLY, fs.FileMode(header.Mode)&0o777)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, copyErr := io.CopyN(output, tarReader, header.Size)
|
|
closeErr := output.Close()
|
|
if err := errors.Join(copyErr, closeErr); err != nil {
|
|
return err
|
|
}
|
|
default:
|
|
return fmt.Errorf("unsupported task archive entry type %d", header.Typeflag)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func hasTraversalSegment(raw string) bool {
|
|
if raw == "" || strings.ContainsRune(raw, 0) {
|
|
return true
|
|
}
|
|
norm := strings.ReplaceAll(raw, "\\", "/")
|
|
for _, seg := range strings.Split(norm, "/") {
|
|
if seg == ".." {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func isValidArchiveTaskID(taskID string) bool {
|
|
if taskID == "" {
|
|
return false
|
|
}
|
|
n, err := strconv.ParseInt(taskID, 10, 64)
|
|
return err == nil && n > 0 && strconv.FormatInt(n, 10) == taskID
|
|
}
|
|
|
|
// validateArchiveStageJournal validates a staging journal before any move or
|
|
// rollback runs (GHSA-fqvh): ArchiveID and TaskID must match, every Relative
|
|
// must be a clean relative path under files/ (no absolutes, no ".."), and every
|
|
// Source must match one of the exact server-derived paths under dataDir.
|
|
func validateArchiveStageJournal(dataDir string, expectedArchiveID int64, expectedTaskID string, expectedExplorationID int64, j archiveStageJournal) error {
|
|
if strings.TrimSpace(dataDir) == "" {
|
|
return errors.New("missing data directory")
|
|
}
|
|
if j.ArchiveID <= 0 {
|
|
return fmt.Errorf("invalid archive_id %d", j.ArchiveID)
|
|
}
|
|
if expectedArchiveID > 0 && j.ArchiveID != expectedArchiveID {
|
|
return fmt.Errorf("archive_id mismatch: got %d, want %d", j.ArchiveID, expectedArchiveID)
|
|
}
|
|
if !isValidArchiveTaskID(j.TaskID) {
|
|
return fmt.Errorf("invalid task_id %q", j.TaskID)
|
|
}
|
|
if expectedTaskID != "" && j.TaskID != expectedTaskID {
|
|
return fmt.Errorf("task_id mismatch: got %q, want %q", j.TaskID, expectedTaskID)
|
|
}
|
|
|
|
cleanDataDir := filepath.Clean(dataDir)
|
|
allowedTaskSrc := filepath.Join(cleanDataDir, "tasks", j.TaskID)
|
|
allowedTaskRel := filepath.Join("files", "tasks", j.TaskID)
|
|
allowedSpillSrc := filepath.Clean(agent.TaskSpillDir(cleanDataDir, j.TaskID))
|
|
allowedSpillRel := filepath.Join("files", "spill", "tasks", j.TaskID)
|
|
transcriptsDir := filepath.Join(cleanDataDir, "transcripts")
|
|
transcriptsRelDir := filepath.Join("files", "transcripts")
|
|
|
|
for _, move := range j.Moves {
|
|
if move.Relative == "" || filepath.IsAbs(move.Relative) || strings.HasPrefix(move.Relative, "/") || strings.HasPrefix(move.Relative, "\\") || hasTraversalSegment(move.Relative) {
|
|
return fmt.Errorf("invalid journal relative path %q", move.Relative)
|
|
}
|
|
cleanRel := filepath.Clean(move.Relative)
|
|
if filepath.IsAbs(cleanRel) || cleanRel == "." || cleanRel == ".." || !strings.HasPrefix(filepath.ToSlash(cleanRel), "files/") {
|
|
return fmt.Errorf("journal relative path %q escapes payload/files", move.Relative)
|
|
}
|
|
if move.Source == "" || hasTraversalSegment(move.Source) {
|
|
return fmt.Errorf("invalid journal source path %q", move.Source)
|
|
}
|
|
cleanSrc := filepath.Clean(move.Source)
|
|
switch {
|
|
case cleanSrc == allowedTaskSrc && cleanRel == allowedTaskRel:
|
|
continue
|
|
case cleanSrc == allowedSpillSrc && cleanRel == allowedSpillRel:
|
|
continue
|
|
case filepath.Dir(cleanSrc) == transcriptsDir && filepath.Dir(cleanRel) == transcriptsRelDir:
|
|
name := filepath.Base(cleanSrc)
|
|
if name != filepath.Base(cleanRel) || name == "" || name == "." || name == ".." || strings.ContainsAny(name, "/\\") || !strings.HasPrefix(name, "exp") {
|
|
return fmt.Errorf("invalid journal transcript name %q", name)
|
|
}
|
|
if expectedExplorationID > 0 && !strings.HasPrefix(name, fmt.Sprintf("exp%d-", expectedExplorationID)) {
|
|
return fmt.Errorf("journal transcript %q does not belong to exploration %d", name, expectedExplorationID)
|
|
}
|
|
continue
|
|
default:
|
|
return fmt.Errorf("journal move source %q (relative %q) is not a server-derived task archive path", move.Source, move.Relative)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// validateArchiveRestoreJournal enforces the same server-derived path bounds on
|
|
// restore-journal.json before recoverTaskArchiveRestoreStages rolls back moves.
|
|
func validateArchiveRestoreJournal(dataDir, extractedRoot string, j archiveRestoreJournal) error {
|
|
if strings.TrimSpace(dataDir) == "" || strings.TrimSpace(extractedRoot) == "" {
|
|
return errors.New("missing restore directory")
|
|
}
|
|
if j.ArchiveID <= 0 || j.TaskID <= 0 {
|
|
return fmt.Errorf("invalid restore journal ids archive=%d task=%d", j.ArchiveID, j.TaskID)
|
|
}
|
|
taskID := strconv.FormatInt(j.TaskID, 10)
|
|
cleanDataDir := filepath.Clean(dataDir)
|
|
cleanExtracted := filepath.Clean(extractedRoot)
|
|
allowedTaskSrc := filepath.Join(cleanExtracted, "files", "tasks", taskID)
|
|
allowedTaskDst := filepath.Join(cleanDataDir, "tasks", taskID)
|
|
allowedSpillSrc := filepath.Join(cleanExtracted, "files", "spill", "tasks", taskID)
|
|
allowedSpillDst := filepath.Clean(agent.TaskSpillDir(cleanDataDir, taskID))
|
|
transcriptsSrcDir := filepath.Join(cleanExtracted, "files", "transcripts")
|
|
transcriptsDstDir := filepath.Join(cleanDataDir, "transcripts")
|
|
|
|
for _, move := range j.Moves {
|
|
if move.Source == "" || move.Destination == "" || hasTraversalSegment(move.Source) || hasTraversalSegment(move.Destination) {
|
|
return fmt.Errorf("invalid restore journal move %+v", move)
|
|
}
|
|
cleanSrc := filepath.Clean(move.Source)
|
|
cleanDst := filepath.Clean(move.Destination)
|
|
switch {
|
|
case cleanSrc == allowedTaskSrc && cleanDst == allowedTaskDst:
|
|
continue
|
|
case cleanSrc == allowedSpillSrc && cleanDst == allowedSpillDst:
|
|
continue
|
|
case filepath.Dir(cleanSrc) == transcriptsSrcDir && filepath.Dir(cleanDst) == transcriptsDstDir:
|
|
name := filepath.Base(cleanSrc)
|
|
if name != filepath.Base(cleanDst) || name == "" || name == "." || name == ".." || strings.ContainsAny(name, "/\\") || !strings.HasPrefix(name, "exp") {
|
|
return fmt.Errorf("invalid restore transcript name %q", name)
|
|
}
|
|
continue
|
|
default:
|
|
return fmt.Errorf("restore journal move %q -> %q is not a server-derived path", move.Source, move.Destination)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *taskArchiveFileStage) resolvedDataDir() string {
|
|
if strings.TrimSpace(s.dataDir) != "" {
|
|
return s.dataDir
|
|
}
|
|
if strings.TrimSpace(s.root) == "" {
|
|
return ""
|
|
}
|
|
// s.root is <dataDir>/archives/tasks/.staging/<archiveID>
|
|
stagingDir := filepath.Dir(filepath.Clean(s.root))
|
|
tasksDir := filepath.Dir(stagingDir)
|
|
archivesDir := filepath.Dir(tasksDir)
|
|
if filepath.Base(stagingDir) == ".staging" && filepath.Base(tasksDir) == "tasks" && filepath.Base(archivesDir) == "archives" {
|
|
return filepath.Dir(archivesDir)
|
|
}
|
|
return ""
|
|
}
|