diff --git a/server/ask_operator.go b/server/ask_operator.go index cad09c4..57e53c1 100644 --- a/server/ask_operator.go +++ b/server/ask_operator.go @@ -2,9 +2,12 @@ package server import ( "context" + "crypto/rand" "encoding/json" + "errors" "fmt" "io" + "io/fs" "os" "path/filepath" "strconv" @@ -189,10 +192,57 @@ func resolveAskOperatorImage(runDir, src string) (string, error) { return real, nil } +// openAskOperatorImage opens the image at path and requires the opened file to be +// the regular file lst describes, lst being the Lstat of path. Between the +// EvalSymlinks of resolveAskOperatorImage and this open, the agent can replace the +// file with a symlink: Lstat does not follow one and the open does, so the two then +// name different files and the image is refused. +func openAskOperatorImage(path string, lst os.FileInfo) (*os.File, error) { + if !lst.Mode().IsRegular() { + return nil, fmt.Errorf("image_path must be a regular file") + } + f, err := os.Open(path) + if err != nil { + return nil, fmt.Errorf("image not readable") + } + if st, err := f.Stat(); err != nil || !os.SameFile(lst, st) { + f.Close() + return nil, fmt.Errorf("image changed while it was read") + } + return f, nil +} + +// askOperatorUploadsDir returns tasks//uploads, created when absent. A symlink +// or anything else that is not a directory is refused: the copy would be written +// through it. +func askOperatorUploadsDir(taskDir string) (string, error) { + dir := filepath.Join(taskDir, "uploads") + if err := os.Mkdir(dir, 0o755); err != nil && !errors.Is(err, fs.ErrExist) { + return "", err + } + if fi, err := os.Lstat(dir); err != nil || !fi.IsDir() { + return "", fmt.Errorf("the task uploads directory is not a directory") + } + return dir, nil +} + +// askOperatorStageTries bounds the names tried for one staged copy. +const askOperatorStageTries = 5 + +// askOperatorStageName returns the file name of a staged copy. It cannot be +// predicted, so it cannot be prepared in uploads/ ahead of the copy. A variable for +// the tests. +var askOperatorStageName = func(ext string) string { + var b [4]byte + _, _ = rand.Read(b[:]) + return fmt.Sprintf("ask-operator-%d-%x%s", time.Now().UnixNano(), b, ext) +} + // stageAskOperatorImage copies the referenced image into the task's uploads dir // (tasks//uploads, where the transcript attachment card resolves) and returns // the attachment descriptor. The image is read from the run directory of the agent // that asks: tasks//i for a worker, tasks//main without an intent. +// The copy is a new file, mode 0640: an existing name is never opened or replaced. // Empty src returns no attachment. func stageAskOperatorImage(dataDir string, taskID, intentID int64, src string) ([]chatAttachment, error) { src = strings.TrimSpace(src) @@ -204,30 +254,34 @@ func stageAskOperatorImage(dataDir string, taskID, intentID int64, src string) ( if err != nil { return nil, err } - st, err := os.Stat(resolved) + st, err := os.Lstat(resolved) if err != nil { return nil, fmt.Errorf("image not readable") } - if !st.Mode().IsRegular() { - return nil, fmt.Errorf("image_path must be a regular file") + in, err := openAskOperatorImage(resolved, st) + if err != nil { + return nil, err } + defer in.Close() if st.Size() > askOperatorMaxImage { return nil, fmt.Errorf("image too large (%s, max 10MB)", humanBytes(st.Size())) } - dir := filepath.Join(taskDir, "uploads") - if err := os.MkdirAll(dir, 0o755); err != nil { + dir, err := askOperatorUploadsDir(taskDir) + if err != nil { return nil, err } ext := strings.ToLower(filepath.Ext(resolved)) - name := fmt.Sprintf("ask-operator-%d%s", time.Now().Unix(), ext) - in, err := os.Open(resolved) - if err != nil { - return nil, fmt.Errorf("image not readable") - } - defer in.Close() - out, err := os.Create(filepath.Join(dir, name)) - if err != nil { - return nil, err + var name string + var out *os.File + for try := 1; ; try++ { + name = askOperatorStageName(ext) + out, err = os.OpenFile(filepath.Join(dir, name), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o640) + if err == nil { + break + } + if !errors.Is(err, fs.ErrExist) || try == askOperatorStageTries { + return nil, err + } } defer out.Close() if _, err := io.Copy(out, in); err != nil { diff --git a/server/ask_operator_test.go b/server/ask_operator_test.go index fae354c..cf03e1d 100644 --- a/server/ask_operator_test.go +++ b/server/ask_operator_test.go @@ -4,6 +4,8 @@ import ( "encoding/json" "os" "path/filepath" + "regexp" + "runtime" "strings" "testing" @@ -116,6 +118,219 @@ func TestStageAskOperatorImage(t *testing.T) { } } +// askOperatorRunDirs creates tasks/7/i3 and tasks/7/main under a new data directory, +// each with a shot.png, and returns the data directory and the task directory. +func askOperatorRunDirs(t *testing.T) (dir, taskDir string) { + t.Helper() + dir = t.TempDir() + taskDir = filepath.Join(dir, "tasks", "7") + for _, leaf := range []string{"i3", "main"} { + if err := os.MkdirAll(filepath.Join(taskDir, leaf), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(taskDir, leaf, "shot.png"), []byte("png of "+leaf), 0o644); err != nil { + t.Fatal(err) + } + } + return dir, taskDir +} + +// The copy of a worker's and of the main agent's image goes to tasks//uploads +// under a name that is not predictable, as a new 0640 file. +func TestStageAskOperatorImageNameAndMode(t *testing.T) { + dir, taskDir := askOperatorRunDirs(t) + nameRE := regexp.MustCompile(`^ask-operator-\d+-[0-9a-f]{8}\.png$`) + seen := map[string]bool{} + for _, c := range []struct { + intent int64 + leaf string + }{{3, "i3"}, {0, "main"}, {3, "i3"}} { + att, err := stageAskOperatorImage(dir, 7, c.intent, "shot.png") + if err != nil || len(att) != 1 { + t.Fatalf("%s/shot.png: att=%v err=%v", c.leaf, att, err) + } + if !nameRE.MatchString(att[0].Name) || att[0].Path != "uploads/"+att[0].Name || seen[att[0].Name] { + t.Fatalf("%s/shot.png: staged as %q (path %q)", c.leaf, att[0].Name, att[0].Path) + } + seen[att[0].Name] = true + staged := filepath.Join(taskDir, "uploads", att[0].Name) + if got, err := os.ReadFile(staged); err != nil || string(got) != "png of "+c.leaf { + t.Fatalf("%s/shot.png: copy holds %q, %v", c.leaf, got, err) + } + fi, err := os.Lstat(staged) + if err != nil || !fi.Mode().IsRegular() { + t.Fatalf("%s/shot.png: staged copy: %v %v", c.leaf, fi, err) + } + if runtime.GOOS != "windows" && fi.Mode().Perm() != 0o640 { + t.Fatalf("%s/shot.png: staged copy has mode %v, want 0640", c.leaf, fi.Mode().Perm()) + } + } + if fi, err := os.Lstat(filepath.Join(taskDir, "uploads")); err != nil || !fi.IsDir() { + t.Fatalf("tasks/7/uploads: %v %v", fi, err) + } + + // A directory with an image name is not staged. + if err := os.Mkdir(filepath.Join(taskDir, "i3", "dir.png"), 0o755); err != nil { + t.Fatal(err) + } + if att, err := stageAskOperatorImage(dir, 7, 3, "dir.png"); err == nil { + t.Fatalf("staged a directory: %v", att) + } + if entries, err := os.ReadDir(filepath.Join(taskDir, "uploads")); err != nil || len(entries) != len(seen) { + t.Fatalf("uploads holds %d entries (%v), want %d", len(entries), err, len(seen)) + } +} + +// An uploads entry that is a symlink to a directory elsewhere, or a file, is +// refused, and nothing is written through it. +func TestStageAskOperatorImageRefusesSymlinkedUploads(t *testing.T) { + dir, taskDir := askOperatorRunDirs(t) + outside := t.TempDir() + uploads := filepath.Join(taskDir, "uploads") + if err := os.Symlink(outside, uploads); err != nil { + t.Skipf("no symlink here: %v", err) + } + for _, intent := range []int64{3, 0} { + if att, err := stageAskOperatorImage(dir, 7, intent, "shot.png"); err == nil { + t.Fatalf("intent %d: staged %v through a symlinked uploads directory", intent, att) + } + } + if entries, err := os.ReadDir(outside); err != nil || len(entries) != 0 { + t.Fatalf("the symlink target holds %v (%v), want it empty", entries, err) + } + if fi, err := os.Lstat(uploads); err != nil || fi.Mode()&os.ModeSymlink == 0 { + t.Fatalf("the uploads symlink changed: %v %v", fi, err) + } + + if err := os.Remove(uploads); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(uploads, []byte("a file"), 0o644); err != nil { + t.Fatal(err) + } + if _, err := stageAskOperatorImage(dir, 7, 3, "shot.png"); err == nil { + t.Fatal("staged with a file in place of the uploads directory") + } + if got, _ := os.ReadFile(uploads); string(got) != "a file" { + t.Fatalf("the file in place of uploads changed: %q", got) + } +} + +// A name that already exists in uploads, as a file or as a symlink, is neither +// opened nor replaced: another name is tried, and after askOperatorStageTries taken +// names the copy is refused. +func TestStageAskOperatorImageNeverOverwrites(t *testing.T) { + dir, taskDir := askOperatorRunDirs(t) + uploads := filepath.Join(taskDir, "uploads") + if err := os.Mkdir(uploads, 0o755); err != nil { + t.Fatal(err) + } + const taken, linked = "ask-operator-taken.png", "ask-operator-linked.png" + if err := os.WriteFile(filepath.Join(uploads, taken), []byte("kept"), 0o644); err != nil { + t.Fatal(err) + } + target := filepath.Join(t.TempDir(), "target.png") + names := []string{taken} + if err := os.Symlink(target, filepath.Join(uploads, linked)); err != nil { + t.Logf("symlink case skipped: %v", err) + } else { + names = append(names, linked) + } + unchanged := func() { + t.Helper() + if got, err := os.ReadFile(filepath.Join(uploads, taken)); err != nil || string(got) != "kept" { + t.Fatalf("the existing file changed: %q, %v", got, err) + } + if _, err := os.Lstat(target); !os.IsNotExist(err) { + t.Fatalf("the copy went through the symlink: %v", err) + } + } + + gen := askOperatorStageName + t.Cleanup(func() { askOperatorStageName = gen }) + calls := 0 + askOperatorStageName = func(ext string) string { + calls++ + if calls <= len(names) { + return names[calls-1] + } + return gen(ext) + } + att, err := stageAskOperatorImage(dir, 7, 3, "shot.png") + if err != nil || len(att) != 1 || att[0].Name == taken || att[0].Name == linked { + t.Fatalf("a free name after the taken ones: att=%v err=%v", att, err) + } + if calls != len(names)+1 { + t.Fatalf("%d names tried, want %d", calls, len(names)+1) + } + unchanged() + + calls = 0 + askOperatorStageName = func(string) string { calls++; return names[calls%len(names)] } + if att, err := stageAskOperatorImage(dir, 7, 3, "shot.png"); err == nil { + t.Fatalf("staged %v with every name taken", att) + } + if calls != askOperatorStageTries { + t.Fatalf("%d names tried, want %d", calls, askOperatorStageTries) + } + unchanged() +} + +// The image is opened only when it is still the file the Lstat saw. The swap is +// done here between the Lstat and openAskOperatorImage, the two steps of +// stageAskOperatorImage: the path becomes another file, or a symlink to a file +// elsewhere. +func TestOpenAskOperatorImageRefusesSwap(t *testing.T) { + dir, taskDir := askOperatorRunDirs(t) + src := filepath.Join(taskDir, "i3", "shot.png") + outside := filepath.Join(dir, "outside.png") + if err := os.WriteFile(outside, []byte("outside"), 0o644); err != nil { + t.Fatal(err) + } + lst, err := os.Lstat(src) + if err != nil { + t.Fatal(err) + } + f, err := openAskOperatorImage(src, lst) + if err != nil { + t.Fatalf("unchanged file: %v", err) + } + f.Close() + + // Another file takes the path: both exist at once, so the inode differs. + other := filepath.Join(taskDir, "i3", "other.png") + if err := os.WriteFile(other, []byte("other"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.Rename(other, src); err != nil { + t.Fatal(err) + } + if f, err := openAskOperatorImage(src, lst); err == nil { + f.Close() + t.Fatal("opened a file that replaced the checked one") + } + + // A symlink to a file outside the run directory takes the path. + if err := os.Remove(src); err != nil { + t.Fatal(err) + } + if err := os.Symlink(outside, src); err != nil { + t.Skipf("no symlink here: %v", err) + } + if f, err := openAskOperatorImage(src, lst); err == nil { + f.Close() + t.Fatal("opened the target of a symlink that replaced the checked file") + } + // The swap came before the Lstat: the last component is a symlink. + if lst, err = os.Lstat(src); err != nil { + t.Fatal(err) + } + if f, err := openAskOperatorImage(src, lst); err == nil { + f.Close() + t.Fatal("opened a path whose last component is a symlink") + } +} + // The emitted activity must carry the {text, attachments} Detail shape the // transcript parser expects, so the operator sees the question with the // attachment card for the screenshot.