file_adapter_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. package workflow_test
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net/http"
  8. "net/http/httptest"
  9. "os"
  10. "path/filepath"
  11. "strings"
  12. "testing"
  13. "workflow"
  14. )
  15. // ────────────────────────────────────────────────────────────────────────────
  16. // LocalFileAdapter tests
  17. // ────────────────────────────────────────────────────────────────────────────
  18. func TestLocalFileAdapter_WriteRead(t *testing.T) {
  19. root := t.TempDir()
  20. a, err := workflow.NewLocalFileAdapter(root, "proj1")
  21. if err != nil {
  22. t.Fatalf("NewLocalFileAdapter: %v", err)
  23. }
  24. ctx := context.Background()
  25. const path = "/Output/hello.txt"
  26. const content = "hello world"
  27. if err := a.Write(ctx, path, []byte(content), workflow.WriteModeOverwrite); err != nil {
  28. t.Fatalf("Write: %v", err)
  29. }
  30. got, err := a.Read(ctx, path)
  31. if err != nil {
  32. t.Fatalf("Read: %v", err)
  33. }
  34. if string(got) != content {
  35. t.Errorf("Read = %q, want %q", got, content)
  36. }
  37. }
  38. func TestLocalFileAdapter_Exists(t *testing.T) {
  39. root := t.TempDir()
  40. a, err := workflow.NewLocalFileAdapter(root, "proj1")
  41. if err != nil {
  42. t.Fatalf("NewLocalFileAdapter: %v", err)
  43. }
  44. ctx := context.Background()
  45. exists, err := a.Exists(ctx, "/Output/nope.txt")
  46. if err != nil {
  47. t.Fatalf("Exists: %v", err)
  48. }
  49. if exists {
  50. t.Error("expected file to not exist")
  51. }
  52. _ = a.Write(ctx, "/Output/nope.txt", []byte("x"), workflow.WriteModeOverwrite)
  53. exists, err = a.Exists(ctx, "/Output/nope.txt")
  54. if err != nil {
  55. t.Fatalf("Exists after write: %v", err)
  56. }
  57. if !exists {
  58. t.Error("expected file to exist after write")
  59. }
  60. }
  61. func TestLocalFileAdapter_WriteModeFailIfExists(t *testing.T) {
  62. root := t.TempDir()
  63. a, _ := workflow.NewLocalFileAdapter(root, "proj1")
  64. ctx := context.Background()
  65. if err := a.Write(ctx, "/f.txt", []byte("v1"), workflow.WriteModeOverwrite); err != nil {
  66. t.Fatalf("first write: %v", err)
  67. }
  68. err := a.Write(ctx, "/f.txt", []byte("v2"), workflow.WriteModeFailIfExists)
  69. if err == nil {
  70. t.Fatal("expected FileExistsError, got nil")
  71. }
  72. var fee *workflow.FileExistsError
  73. if !errors.As(err, &fee) {
  74. t.Fatalf("expected FileExistsError, got %T: %v", err, err)
  75. }
  76. // Content should be unchanged
  77. got, _ := a.Read(ctx, "/f.txt")
  78. if string(got) != "v1" {
  79. t.Errorf("content should be v1, got %q", got)
  80. }
  81. }
  82. func TestLocalFileAdapter_WriteModeAppend(t *testing.T) {
  83. root := t.TempDir()
  84. a, _ := workflow.NewLocalFileAdapter(root, "proj1")
  85. ctx := context.Background()
  86. _ = a.Write(ctx, "/log.txt", []byte("line1\n"), workflow.WriteModeOverwrite)
  87. _ = a.Write(ctx, "/log.txt", []byte("line2\n"), workflow.WriteModeAppend)
  88. got, _ := a.Read(ctx, "/log.txt")
  89. if string(got) != "line1\nline2\n" {
  90. t.Errorf("append result = %q, want %q", got, "line1\nline2\n")
  91. }
  92. }
  93. func TestLocalFileAdapter_WriteModePrepend(t *testing.T) {
  94. root := t.TempDir()
  95. a, _ := workflow.NewLocalFileAdapter(root, "proj1")
  96. ctx := context.Background()
  97. _ = a.Write(ctx, "/doc.txt", []byte("world"), workflow.WriteModeOverwrite)
  98. _ = a.Write(ctx, "/doc.txt", []byte("hello "), workflow.WriteModePrepend)
  99. got, _ := a.Read(ctx, "/doc.txt")
  100. if string(got) != "hello world" {
  101. t.Errorf("prepend result = %q, want %q", got, "hello world")
  102. }
  103. }
  104. func TestLocalFileAdapter_List(t *testing.T) {
  105. root := t.TempDir()
  106. a, _ := workflow.NewLocalFileAdapter(root, "proj1")
  107. ctx := context.Background()
  108. files := []string{"/Output/a.txt", "/Output/b.txt", "/Other/c.md"}
  109. for _, f := range files {
  110. _ = a.Write(ctx, f, []byte("x"), workflow.WriteModeOverwrite)
  111. }
  112. got, err := a.List(ctx, "Output/*")
  113. if err != nil {
  114. t.Fatalf("List: %v", err)
  115. }
  116. if len(got) != 2 {
  117. t.Errorf("List(Output/*) = %v, want 2 items", got)
  118. }
  119. for _, p := range got {
  120. if !strings.HasPrefix(p, "/Output/") {
  121. t.Errorf("path %q should start with /Output/", p)
  122. }
  123. }
  124. }
  125. func TestLocalFileAdapter_GIDIsolation(t *testing.T) {
  126. root := t.TempDir()
  127. a1, _ := workflow.NewLocalFileAdapter(root, "proj-A")
  128. a2, _ := workflow.NewLocalFileAdapter(root, "proj-B")
  129. ctx := context.Background()
  130. _ = a1.Write(ctx, "/file.txt", []byte("from A"), workflow.WriteModeOverwrite)
  131. exists, _ := a2.Exists(ctx, "/file.txt")
  132. if exists {
  133. t.Error("proj-B should not see proj-A's file")
  134. }
  135. _, err := a2.Read(ctx, "/file.txt")
  136. if err == nil {
  137. t.Error("proj-B reading proj-A file should fail")
  138. }
  139. }
  140. func TestLocalFileAdapter_PathTraversalBlocked(t *testing.T) {
  141. root := t.TempDir()
  142. a, _ := workflow.NewLocalFileAdapter(root, "proj1")
  143. ctx := context.Background()
  144. err := a.Write(ctx, "../../etc/passwd", []byte("evil"), workflow.WriteModeOverwrite)
  145. if err == nil {
  146. t.Error("path traversal should be rejected")
  147. }
  148. }
  149. func TestLocalFileAdapter_ReadNotFound(t *testing.T) {
  150. root := t.TempDir()
  151. a, _ := workflow.NewLocalFileAdapter(root, "proj1")
  152. ctx := context.Background()
  153. _, err := a.Read(ctx, "/nonexistent.txt")
  154. if err == nil {
  155. t.Fatal("expected FileNotFoundError")
  156. }
  157. var fnf *workflow.FileNotFoundError
  158. if !errors.As(err, &fnf) {
  159. t.Fatalf("expected FileNotFoundError, got %T: %v", err, err)
  160. }
  161. }
  162. func TestLocalFileAdapter_WorkspaceDir(t *testing.T) {
  163. root := t.TempDir()
  164. a, _ := workflow.NewLocalFileAdapter(root, "my-gid")
  165. // WorkspaceDir should be root/gid
  166. absRoot, _ := filepath.Abs(root)
  167. expected := filepath.Join(absRoot, "my-gid")
  168. if a.WorkspaceDir() != expected {
  169. t.Errorf("WorkspaceDir = %q, want %q", a.WorkspaceDir(), expected)
  170. }
  171. }
  172. func TestLocalFileAdapter_AutoCreatesParentDirs(t *testing.T) {
  173. root := t.TempDir()
  174. a, _ := workflow.NewLocalFileAdapter(root, "proj1")
  175. ctx := context.Background()
  176. // Deep nested path — parent dirs should be created
  177. err := a.Write(ctx, "/deep/nested/path/file.txt", []byte("data"), workflow.WriteModeOverwrite)
  178. if err != nil {
  179. t.Fatalf("Write nested path: %v", err)
  180. }
  181. absRoot, _ := filepath.Abs(root)
  182. expected := filepath.Join(absRoot, "proj1", "deep", "nested", "path", "file.txt")
  183. if _, err := os.Stat(expected); err != nil {
  184. t.Errorf("expected file at %s: %v", expected, err)
  185. }
  186. }
  187. // ────────────────────────────────────────────────────────────────────────────
  188. // WorkspaceFileAdapter tests (mock HTTP server)
  189. // ────────────────────────────────────────────────────────────────────────────
  190. // mockWorkspaceServer builds an httptest.Server that handles the four
  191. // workspace API endpoints used by WorkspaceFileAdapter.
  192. type mockWorkspaceServer struct {
  193. // files maps path → content (version=1 if present)
  194. files map[string]string
  195. // cookie expected in requests (without "ih5bearer=" prefix)
  196. cookie string
  197. }
  198. func (m *mockWorkspaceServer) handler(w http.ResponseWriter, r *http.Request) {
  199. if r.Method != http.MethodPost {
  200. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  201. return
  202. }
  203. // Check cookie
  204. if m.cookie != "" {
  205. expected := "ih5bearer=" + m.cookie
  206. if r.Header.Get("Cookie") != expected {
  207. http.Error(w, "unauthorized", http.StatusUnauthorized)
  208. return
  209. }
  210. }
  211. // Parse body
  212. var body map[string]interface{}
  213. if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
  214. http.Error(w, "bad request", http.StatusBadRequest)
  215. return
  216. }
  217. path, _ := body["path"].(string)
  218. // Route
  219. endpoint := filepath.Base(r.URL.Path)
  220. switch endpoint {
  221. case "createFile":
  222. if _, exists := m.files[path]; !exists {
  223. m.files[path] = "" // mark as created (version=0)
  224. }
  225. w.Header().Set("Content-Type", "application/json")
  226. fmt.Fprintf(w, `{"status":0}`)
  227. case "writeFile":
  228. content, _ := body["content"].(string)
  229. m.files[path] = content
  230. w.Header().Set("Content-Type", "application/json")
  231. fmt.Fprintf(w, `{"gid":"test","path":%q,"version":1}`, path)
  232. case "readFile":
  233. content, exists := m.files[path]
  234. if !exists || content == "" {
  235. http.Error(w, "not found", http.StatusNotFound)
  236. return
  237. }
  238. w.Header().Set("Content-Type", "application/json")
  239. fmt.Fprintf(w, `{"version":1,"status":0,"content":%s}`, jsonStr(content))
  240. case "listFile":
  241. type fileEntry struct {
  242. Path string `json:"path"`
  243. Version int `json:"version"`
  244. }
  245. var entries []fileEntry
  246. for p, c := range m.files {
  247. v := 0
  248. if c != "" {
  249. v = 1
  250. }
  251. entries = append(entries, fileEntry{Path: p, Version: v})
  252. }
  253. out, _ := json.Marshal(map[string]interface{}{"files": entries})
  254. w.Header().Set("Content-Type", "application/json")
  255. w.Write(out)
  256. default:
  257. http.Error(w, "unknown endpoint: "+endpoint, http.StatusNotFound)
  258. }
  259. }
  260. func jsonStr(s string) string {
  261. b, _ := json.Marshal(s)
  262. return string(b)
  263. }
  264. func newMockWorkspaceServer(t *testing.T, token string) (*httptest.Server, *mockWorkspaceServer) {
  265. t.Helper()
  266. mock := &mockWorkspaceServer{
  267. files: make(map[string]string),
  268. cookie: token,
  269. }
  270. srv := httptest.NewServer(http.HandlerFunc(mock.handler))
  271. t.Cleanup(srv.Close)
  272. return srv, mock
  273. }
  274. func newWorkspaceAdapter(t *testing.T, srv *httptest.Server, token, gid string) *workflow.WorkspaceFileAdapter {
  275. t.Helper()
  276. a, err := workflow.NewWorkspaceFileAdapter(workflow.WorkspaceFileConfig{
  277. BaseURL: srv.URL,
  278. GID: gid,
  279. Cookie: "ih5bearer=" + token,
  280. })
  281. if err != nil {
  282. t.Fatalf("NewWorkspaceFileAdapter: %v", err)
  283. }
  284. return a
  285. }
  286. func TestWorkspaceFileAdapter_WriteRead(t *testing.T) {
  287. srv, _ := newMockWorkspaceServer(t, "tok123")
  288. a := newWorkspaceAdapter(t, srv, "tok123", "proj1")
  289. ctx := context.Background()
  290. if err := a.Write(ctx, "/Output/result.txt", []byte("hello"), workflow.WriteModeOverwrite); err != nil {
  291. t.Fatalf("Write: %v", err)
  292. }
  293. got, err := a.Read(ctx, "/Output/result.txt")
  294. if err != nil {
  295. t.Fatalf("Read: %v", err)
  296. }
  297. if string(got) != "hello" {
  298. t.Errorf("Read = %q, want %q", got, "hello")
  299. }
  300. }
  301. func TestWorkspaceFileAdapter_Exists(t *testing.T) {
  302. srv, _ := newMockWorkspaceServer(t, "tok123")
  303. a := newWorkspaceAdapter(t, srv, "tok123", "proj1")
  304. ctx := context.Background()
  305. exists, err := a.Exists(ctx, "/Output/nope.txt")
  306. if err != nil {
  307. t.Fatalf("Exists: %v", err)
  308. }
  309. if exists {
  310. t.Error("expected file to not exist")
  311. }
  312. _ = a.Write(ctx, "/Output/nope.txt", []byte("x"), workflow.WriteModeOverwrite)
  313. exists, err = a.Exists(ctx, "/Output/nope.txt")
  314. if err != nil {
  315. t.Fatalf("Exists after write: %v", err)
  316. }
  317. if !exists {
  318. t.Error("expected file to exist after write")
  319. }
  320. }
  321. func TestWorkspaceFileAdapter_WriteModeAppend(t *testing.T) {
  322. srv, _ := newMockWorkspaceServer(t, "tok123")
  323. a := newWorkspaceAdapter(t, srv, "tok123", "proj1")
  324. ctx := context.Background()
  325. _ = a.Write(ctx, "/log.txt", []byte("line1\n"), workflow.WriteModeOverwrite)
  326. _ = a.Write(ctx, "/log.txt", []byte("line2\n"), workflow.WriteModeAppend)
  327. got, _ := a.Read(ctx, "/log.txt")
  328. if string(got) != "line1\nline2\n" {
  329. t.Errorf("append result = %q, want %q", got, "line1\nline2\n")
  330. }
  331. }
  332. func TestWorkspaceFileAdapter_WriteModePrepend(t *testing.T) {
  333. srv, _ := newMockWorkspaceServer(t, "tok123")
  334. a := newWorkspaceAdapter(t, srv, "tok123", "proj1")
  335. ctx := context.Background()
  336. _ = a.Write(ctx, "/doc.txt", []byte("world"), workflow.WriteModeOverwrite)
  337. _ = a.Write(ctx, "/doc.txt", []byte("hello "), workflow.WriteModePrepend)
  338. got, _ := a.Read(ctx, "/doc.txt")
  339. if string(got) != "hello world" {
  340. t.Errorf("prepend result = %q, want %q", got, "hello world")
  341. }
  342. }
  343. func TestWorkspaceFileAdapter_WriteModeFailIfExists(t *testing.T) {
  344. srv, _ := newMockWorkspaceServer(t, "tok123")
  345. a := newWorkspaceAdapter(t, srv, "tok123", "proj1")
  346. ctx := context.Background()
  347. _ = a.Write(ctx, "/f.txt", []byte("v1"), workflow.WriteModeOverwrite)
  348. err := a.Write(ctx, "/f.txt", []byte("v2"), workflow.WriteModeFailIfExists)
  349. if err == nil {
  350. t.Fatal("expected FileExistsError, got nil")
  351. }
  352. var fee *workflow.FileExistsError
  353. if !errors.As(err, &fee) {
  354. t.Fatalf("expected FileExistsError, got %T: %v", err, err)
  355. }
  356. }
  357. func TestWorkspaceFileAdapter_List(t *testing.T) {
  358. srv, _ := newMockWorkspaceServer(t, "tok123")
  359. a := newWorkspaceAdapter(t, srv, "tok123", "proj1")
  360. ctx := context.Background()
  361. _ = a.Write(ctx, "/Output/a.txt", []byte("x"), workflow.WriteModeOverwrite)
  362. _ = a.Write(ctx, "/Output/b.txt", []byte("x"), workflow.WriteModeOverwrite)
  363. _ = a.Write(ctx, "/Other/c.md", []byte("x"), workflow.WriteModeOverwrite)
  364. got, err := a.List(ctx, "Output/*")
  365. if err != nil {
  366. t.Fatalf("List: %v", err)
  367. }
  368. if len(got) != 2 {
  369. t.Errorf("List(Output/*) = %v, want 2 items", got)
  370. }
  371. for _, p := range got {
  372. if !strings.HasPrefix(p, "/Output/") {
  373. t.Errorf("path %q should start with /Output/", p)
  374. }
  375. }
  376. }
  377. func TestWorkspaceFileAdapter_GID(t *testing.T) {
  378. srv, _ := newMockWorkspaceServer(t, "tok123")
  379. a := newWorkspaceAdapter(t, srv, "tok123", "my-gid")
  380. if a.GID() != "my-gid" {
  381. t.Errorf("GID = %q, want %q", a.GID(), "my-gid")
  382. }
  383. }