| 1 | package serve |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/json" |
| 6 | "net/http" |
| 7 | "net/http/httptest" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "runtime" |
| 11 | "testing" |
| 12 | |
| 13 | "reasonix/internal/config" |
| 14 | "reasonix/internal/control" |
| 15 | ) |
| 16 | |
| 17 | func TestDeleteSessionValidatesLocalBasenameBeforeCleanup(t *testing.T) { |
| 18 | dir := t.TempDir() |
| 19 | bc := NewBroadcaster() |
| 20 | ctrl := control.New(control.Options{Sink: bc, SessionDir: dir, SessionPath: filepath.Join(dir, "active.jsonl")}) |
| 21 | handler := newLifecycleTestServer(t, ctrl, bc, config.ServeConfig{}).Handler() |
| 22 | post := func(name string) *httptest.ResponseRecorder { |
| 23 | t.Helper() |
| 24 | body, err := json.Marshal(map[string]string{"name": name}) |
| 25 | if err != nil { |
| 26 | t.Fatal(err) |
| 27 | } |
| 28 | w := httptest.NewRecorder() |
| 29 | r := httptest.NewRequest(http.MethodPost, "http://127.0.0.1/delete-session", bytes.NewReader(body)) |
| 30 | r.Header.Set("Content-Type", "application/json") |
| 31 | handler.ServeHTTP(w, r) |
| 32 | return w |
| 33 | } |
| 34 | invalid := []string{"", " ", ".", "..", "../escape", `..\escape`, "/absolute", `\absolute`, "nested/session", `nested\session`} |
| 35 | if runtime.GOOS == "windows" { |
| 36 | // Device names with an extension are absent: Windows 11 stopped |
| 37 | // reserving them, and filepath.IsLocal defers to the host's |
| 38 | // RtlIsDosDeviceName_U, so their answer varies by Windows build. |
| 39 | invalid = append(invalid, "C:escape", "C:", "CON", "NUL", "AUX", "COM1", "LPT1") |
| 40 | } |
| 41 | for _, name := range invalid { |
| 42 | t.Run("reject "+name, func(t *testing.T) { |
| 43 | if response := post(name); response.Code != http.StatusBadRequest { |
| 44 | t.Fatalf("delete %q = %d (%s), want 400", name, response.Code, response.Body.String()) |
| 45 | } |
| 46 | }) |
| 47 | } |
| 48 | // IsLocal must not be replaced with a blanket dot-dot substring ban: |
| 49 | // ordinary names containing dots, spaces and Unicode remain supported. |
| 50 | for _, name := range []string{"saved..session", "session draft", "会话.v2"} { |
| 51 | t.Run("delete "+name, func(t *testing.T) { |
| 52 | path := filepath.Join(dir, name+".jsonl") |
| 53 | if err := os.WriteFile(path, []byte("{}\n"), 0o600); err != nil { |
| 54 | t.Fatal(err) |
| 55 | } |
| 56 | if response := post(name); response.Code != http.StatusNoContent { |
| 57 | t.Fatalf("delete %q = %d (%s), want 204", name, response.Code, response.Body.String()) |
| 58 | } |
| 59 | if _, err := os.Stat(path); !os.IsNotExist(err) { |
| 60 | t.Fatalf("session %q survived deletion: %v", name, err) |
| 61 | } |
| 62 | }) |
| 63 | } |
| 64 | } |
| 65 |