返回 DeepSeek-Reasonix
attachment_upload_test.go
根目录 / desktop / attachment_upload_test.go
1 package main
2
3 import (
4 "encoding/json"
5 "io"
6 "net/http"
7 "net/http/httptest"
8 "net/url"
9 "os"
10 "path/filepath"
11 "strings"
12 "testing"
13 "time"
14
15 "reasonix/internal/control"
16 )
17
18 func uploadFixture(t *testing.T) (*App, string, string) {
19 t.Helper()
20 home := t.TempDir()
21 t.Setenv("REASONIX_HOME", home)
22 if err := os.WriteFile(filepath.Join(home, "config.toml"), nil, 0600); err != nil {
23 t.Fatal(err)
24 }
25 root := t.TempDir()
26 c := control.New(control.Options{WorkspaceRoot: root})
27 t.Cleanup(c.Close)
28 a := &App{tabs: map[string]*WorkspaceTab{"a": {ID: "a", WorkspaceRoot: root, Ctrl: c, SessionGeneration: 1}}, activeTabID: "a"}
29 target, err := a.CaptureAttachmentTarget(ComposerTarget{Kind: "session", TabID: "a"})
30 if err != nil {
31 t.Fatal(err)
32 }
33 t.Cleanup(func() { a.ReleaseAttachmentTarget(target.Token) })
34 return a, root, target.Token
35 }
36
37 type uploadZeros struct{}
38
39 func (uploadZeros) Read(p []byte) (int, error) {
40 clear(p)
41 return len(p), nil
42 }
43
44 func uploadRequest(token string, body io.Reader) *http.Request {
45 query := url.Values{"target": {token}, "name": {"large app.apk"}}
46 r := httptest.NewRequest(http.MethodPost, attachmentUploadPath+"?"+query.Encode(), body)
47 r.Header.Set("Content-Type", "application/octet-stream")
48 r.Header.Set("Authorization", "Bearer test-secret")
49 return r
50 }
51
52 func TestAttachmentUploadLargeFileKeepsCapturedWorkspace(t *testing.T) {
53 a, root, token := uploadFixture(t)
54 other := t.TempDir()
55 a.tabs["b"] = &WorkspaceTab{ID: "b", WorkspaceRoot: other}
56 a.activeTabID = "b"
57 const size = 80 << 20
58 recorder := httptest.NewRecorder()
59 handler := bearerAuth("test-secret", a.attachmentUploadMiddleware()(http.NotFoundHandler()))
60 handler.ServeHTTP(recorder, uploadRequest(token, io.LimitReader(uploadZeros{}, size)))
61 if recorder.Code != http.StatusOK {
62 t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body)
63 }
64 var result struct {
65 Path string `json:"path"`
66 }
67 if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil {
68 t.Fatal(err)
69 }
70 info, err := os.Stat(filepath.Join(root, filepath.FromSlash(result.Path)))
71 if err != nil || info.Size() != size {
72 t.Fatalf("file=%v err=%v", info, err)
73 }
74 if !strings.HasSuffix(result.Path, ".apk") {
75 t.Fatalf("path=%s", result.Path)
76 }
77 if _, err := os.Stat(filepath.Join(other, filepath.FromSlash(result.Path))); !os.IsNotExist(err) {
78 t.Fatalf("wrote into focused tab: %v", err)
79 }
80 }
81
82 func TestAttachmentUploadRejectsUntrustedAndStaleRequests(t *testing.T) {
83 a, root, token := uploadFixture(t)
84 handler := bearerAuth("test-secret", a.attachmentUploadMiddleware()(http.NotFoundHandler()))
85 for _, scenario := range []string{"no auth", "bad type", "bad method", "unknown target", "released target"} {
86 t.Run(scenario, func(t *testing.T) {
87 r := uploadRequest(token, strings.NewReader("body"))
88 want := http.StatusConflict
89 switch scenario {
90 case "no auth":
91 r.Header.Del("Authorization")
92 want = http.StatusUnauthorized
93 case "bad type":
94 r.Header.Set("Content-Type", "text/plain")
95 want = http.StatusUnsupportedMediaType
96 case "bad method":
97 r.Method = http.MethodGet
98 want = http.StatusMethodNotAllowed
99 case "unknown target":
100 r.URL.RawQuery = "target=not-a-token"
101 case "released target":
102 a.ReleaseAttachmentTarget(token)
103 }
104 recorder := httptest.NewRecorder()
105 handler.ServeHTTP(recorder, r)
106 if recorder.Code != want {
107 t.Fatalf("status=%d want=%d", recorder.Code, want)
108 }
109 })
110 }
111 if _, err := os.Stat(filepath.Join(root, ".reasonix", "attachments")); !os.IsNotExist(err) {
112 t.Fatalf("rejected upload created files: %v", err)
113 }
114 }
115
116 func TestAttachmentUploadRemovesFileWhenTargetChangesBeforeCommit(t *testing.T) {
117 a, root, token := uploadFixture(t)
118 a.attachmentIOHook = func() { a.tabs["a"].SessionGeneration++ }
119 recorder := httptest.NewRecorder()
120 a.attachmentUploadMiddleware()(http.NotFoundHandler()).ServeHTTP(recorder, uploadRequest(token, strings.NewReader("partial")))
121 if recorder.Code != http.StatusConflict {
122 t.Fatalf("status=%d", recorder.Code)
123 }
124 entries, err := os.ReadDir(filepath.Join(root, ".reasonix", "attachments"))
125 if err != nil || len(entries) != 0 {
126 t.Fatalf("left partial files: %v err=%v", entries, err)
127 }
128 }
129
130 func TestAttachmentUploadCancellationClosesBlockedBodyAndCleansFile(t *testing.T) {
131 a, root, token := uploadFixture(t)
132 reader, writer := io.Pipe()
133 defer writer.Close()
134 done := make(chan struct{})
135 go func() {
136 defer close(done)
137 a.attachmentUploadMiddleware()(http.NotFoundHandler()).ServeHTTP(httptest.NewRecorder(), uploadRequest(token, reader))
138 }()
139 if _, err := writer.Write(make([]byte, 64<<10)); err != nil {
140 t.Fatal(err)
141 }
142 a.ReleaseAttachmentTarget(token)
143 select {
144 case <-done:
145 case <-time.After(5 * time.Second):
146 t.Fatal("cancelled upload kept reading its body")
147 }
148 entries, err := os.ReadDir(filepath.Join(root, ".reasonix", "attachments"))
149 if err != nil || len(entries) != 0 {
150 t.Fatalf("files=%v err=%v", entries, err)
151 }
152 }
153
154 func TestAttachmentUploadLateCancellationRemovesCompletedFile(t *testing.T) {
155 a, root, token := uploadFixture(t)
156 a.attachmentIOHook = func() { a.ReleaseAttachmentTarget(token) }
157 recorder := httptest.NewRecorder()
158 a.attachmentUploadMiddleware()(http.NotFoundHandler()).ServeHTTP(recorder, uploadRequest(token, strings.NewReader("complete but cancelled")))
159 if recorder.Code != http.StatusConflict {
160 t.Fatalf("status=%d", recorder.Code)
161 }
162 entries, err := os.ReadDir(filepath.Join(root, ".reasonix", "attachments"))
163 if err != nil || len(entries) != 0 {
164 t.Fatalf("files=%v err=%v", entries, err)
165 }
166 }
167
168 func TestDroppedLargeExternalFileRemainsReference(t *testing.T) {
169 a, root, token := uploadFixture(t)
170 path := filepath.Join(t.TempDir(), "large app.apk")
171 f, err := os.Create(path)
172 if err != nil {
173 t.Fatal(err)
174 }
175 if err := f.Truncate(120 << 20); err != nil {
176 t.Fatal(err)
177 }
178 if err := f.Close(); err != nil {
179 t.Fatal(err)
180 }
181 item, err := a.AttachDroppedForTarget(token, path)
182 if err != nil {
183 t.Fatal(err)
184 }
185 if item.Kind != "workspace" || !filepath.IsAbs(item.Path) || item.IsDir {
186 t.Fatalf("item=%+v", item)
187 }
188 if _, err := os.Stat(filepath.Join(root, ".reasonix", "attachments")); !os.IsNotExist(err) {
189 t.Fatalf("native file was copied: %v", err)
190 }
191 item2, err := a.AttachDroppedForTarget(token, item.DisplayPath)
192 if err != nil || item2.Path != item.Path {
193 t.Fatalf("restored=%+v err=%v", item2, err)
194 }
195 }
196
197 func TestDraftExternalFileReferenceEscapesSpacesAndPreservesOtherPaths(t *testing.T) {
198 a, _, _ := uploadFixture(t)
199 path := filepath.Join(t.TempDir(), "large app.apk")
200 if err := os.WriteFile(path, []byte("PK\x00binary"), 0o600); err != nil {
201 t.Fatal(err)
202 }
203 other := "@" + control.EscapeRefPath(path+".backup")
204 request := SessionDraftSubmissionRequest{Input: "inspect @" + control.EscapeRefPath(path) + " " + other, WorkspaceRefs: []DraftWorkspaceRef{{Path: path, DisplayPath: path}}}
205 if err := a.resolveDraftExternalRefs("a", &request); err != nil {
206 t.Fatal(err)
207 }
208 canonical, err := filepath.EvalSymlinks(path)
209 if err != nil {
210 t.Fatal(err)
211 }
212 want := "inspect @" + control.EscapeRefPath(filepath.ToSlash(canonical)) + " " + other
213 if request.Input != want {
214 t.Fatalf("input=%q want=%q", request.Input, want)
215 }
216 }
217
218 func TestDraftNativeFileReferenceMatchesSessionReference(t *testing.T) {
219 a, root, _ := uploadFixture(t)
220 sourceRoot := t.TempDir()
221 canonicalPath := filepath.Join(sourceRoot, "large app.apk")
222 if err := os.WriteFile(canonicalPath, []byte("APK"), 0o600); err != nil {
223 t.Fatal(err)
224 }
225 path := canonicalPath
226 alias := filepath.Join(t.TempDir(), "parent alias")
227 if err := os.Symlink(sourceRoot, alias); err == nil {
228 path = filepath.Join(alias, filepath.Base(canonicalPath))
229 }
230 item, err := a.attachDroppedForTarget(attachmentTarget{root: root, draftID: "draft"}, path)
231 if err != nil {
232 t.Fatal(err)
233 }
234 restored, err := a.AttachDroppedForTab("a", item.DisplayPath)
235 if err != nil {
236 t.Fatal(err)
237 }
238 if item.Path != restored.Path || item.Path != filepath.ToSlash(item.Path) {
239 t.Fatalf("draft=%+v session=%+v", item, restored)
240 }
241 }
242
242 lines GO