oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thintest
2
3import (
4 "bytes"
5 "context"
6 "crypto/sha256"
7 "encoding/hex"
8 "encoding/json"
9 "errors"
10 "net/http"
11 "strings"
12 "testing"
13 "time"
14
15 "amadan.net/oficina/equipo/internal/attach"
16 "amadan.net/oficina/equipo/internal/attach/attachtest"
17 "amadan.net/oficina/equipo/internal/equipo"
18 "amadan.net/oficina/equipo/internal/wire"
19)
20
21// notesOf is a text file of n bytes.
22func notesOf(n int) []byte {
23 var b bytes.Buffer
24 for i := 0; b.Len() < n; i++ {
25 b.WriteString("line " + strings.Repeat("x", i%40) + "\n")
26 }
27 return b.Bytes()[:n]
28}
29
30func errCode(err error) (int, string) {
31 var s *ErrStatus
32 if !errors.As(err, &s) {
33 return 0, ""
34 }
35 var e wire.Error
36 _ = json.Unmarshal(s.Body, &e)
37 return s.Status, e.Code
38}
39
40// TestContractAttachments: upload, limits, location stripped, person
41// scoped, sent with a message, and relayed through the mailbox as chunk
42// frames before the message frame, exactly once across a reconnect.
43func TestContractAttachments(t *testing.T) {
44 r := newRig(t)
45 runner := r.dial(0)
46 r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online })
47
48 photo := attachtest.Photo(40, 20, 6)
49 img, err := r.client.Upload(r.ctx, "IMG_0001.jpg", "image/jpeg", photo)
50 if err != nil {
51 t.Fatal(err)
52 }
53 shape(t, "api/attachment.json", img)
54 if img.Kind != wire.AttachmentImage || img.MediaType != attach.JPEG || img.Width != 20 || img.Height != 40 || img.MessageID != "" || img.Revision != 1 {
55 t.Fatalf("upload %+v", img)
56 }
57 kept, header, err := r.client.Attachment(r.ctx, img.ID, false)
58 if err != nil {
59 t.Fatal(err)
60 }
61 sum := sha256.Sum256(kept)
62 if attachtest.HasGPS(kept) || hex.EncodeToString(sum[:]) != img.SHA256 || int64(len(kept)) != img.Size {
63 t.Fatal("the kept photo still has its location, or its hash or size is wrong")
64 }
65 if header.Get("Content-Type") != attach.JPEG || header.Get("X-Content-Type-Options") != "nosniff" || !strings.Contains(header.Get("Content-Security-Policy"), "sandbox") {
66 t.Fatalf("served with %v", header)
67 }
68 notes := notesOf(300 << 10)
69 file, err := r.client.Upload(r.ctx, "../notes.md", "text/markdown", notes)
70 if err != nil || file.Name != "notes.md" || file.MediaType != attach.Markdown || file.Kind != wire.AttachmentFile {
71 t.Fatalf("file upload %+v %v", file, err)
72 }
73 // Astra round 1: every file that is not an image downloads, never
74 // shows inline (text accepted as plain text may be HTML).
75 for name, body := range map[string][]byte{"page.html": []byte("<html><script>alert(1)</script></html>"), "notes2.md": []byte("# hi")} {
76 a, err := r.client.Upload(r.ctx, name, "text/html", body)
77 if err != nil {
78 t.Fatal(err)
79 }
80 _, h, err := r.client.Attachment(r.ctx, a.ID, false)
81 if err != nil || !strings.HasPrefix(h.Get("Content-Disposition"), "attachment;") || !strings.HasPrefix(h.Get("Content-Type"), "text/plain") && !strings.HasPrefix(h.Get("Content-Type"), "text/markdown") {
82 t.Fatalf("%s served as %q %q", name, h.Get("Content-Disposition"), h.Get("Content-Type"))
83 }
84 }
85 if _, h, _ := r.client.Attachment(r.ctx, img.ID, false); !strings.HasPrefix(h.Get("Content-Disposition"), "inline;") {
86 t.Fatalf("an image no longer shows inline: %q", h.Get("Content-Disposition"))
87 }
88
89 // Limits, refused in words by code.
90 _, err = r.client.Upload(r.ctx, "IMG_0002.HEIC", "image/heic", []byte("\x00\x00\x00\x18ftypheic\x00\x00\x00\x00mif1heic"))
91 if status, code := errCode(err); status != http.StatusUnsupportedMediaType || code != "attachment_heic" {
92 t.Fatalf("heic %d %s", status, code)
93 }
94 var e *ErrStatus
95 errors.As(err, &e)
96 shape(t, "api/error-attachment.json", e.Body)
97 _, err = r.client.Upload(r.ctx, "big.log", "text/plain", bytes.Repeat([]byte("a"), attach.MaxBytes+1))
98 if status, code := errCode(err); status != http.StatusRequestEntityTooLarge || code != "attachment_too_large" {
99 t.Fatalf("too large %d %s", status, code)
100 }
101 _, err = r.client.Upload(r.ctx, "huge.png", "image/png", attachtest.PNGHeader(100000, 100000))
102 if status, code := errCode(err); status != http.StatusRequestEntityTooLarge || code != "attachment_pixels" {
103 t.Fatalf("a 100,000 px square %d %s", status, code)
104 }
105 _, err = r.client.Upload(r.ctx, "tool.exe", "application/octet-stream", []byte{0x4d, 0x5a, 0, 1, 2})
106 if status, code := errCode(err); status != http.StatusUnsupportedMediaType || code != "attachment_type" {
107 t.Fatalf("binary %d %s", status, code)
108 }
109
110 // Person scoped: a teammate can neither read nor send someone's upload.
111 const member = "member@example.com"
112 if err := r.inst.Store.SetMember(context.Background(), equipo.Actor{Address: Owner}, member, equipo.RoleMember, true, 0); err != nil {
113 t.Fatal(err)
114 }
115 other := NewClient(r.inst.URL, r.inst.DeviceTokenFor(t, member))
116 if _, _, err := other.Attachment(r.ctx, img.ID, false); Status(err) != http.StatusNotFound {
117 t.Fatalf("a teammate read the upload: %v", err)
118 }
119 if _, err := other.SendWith(r.ctx, "mine now", "m-1", []string{img.ID}); Status(err) != 422 {
120 t.Fatalf("a teammate sent the upload: %v", err)
121 }
122 if _, err := r.client.SendWith(r.ctx, "too many", "k-many", []string{"at_a1", "at_a2", "at_a3", "at_a4", "at_a5", "at_a6"}); Status(err) != 422 {
123 t.Fatalf("six attachments: %v", err)
124 }
125
126 // Sent with no words: the message carries both, in order.
127 sent, err := r.client.SendWith(r.ctx, "", "k-files", []string{img.ID, file.ID})
128 if err != nil {
129 t.Fatal(err)
130 }
131 if len(sent.Message.Attachments) != 2 || sent.Message.Attachments[0].ID != img.ID || sent.Message.Attachments[1].MessageID != sent.Message.ID {
132 t.Fatalf("sent %+v", sent.Message)
133 }
134 again, err := r.client.SendWith(r.ctx, "", "k-files", []string{img.ID, file.ID})
135 if err != nil || again.Message.ID != sent.Message.ID {
136 t.Fatalf("idempotent resend %+v %v", again, err)
137 }
138 if _, err := r.client.SendWith(r.ctx, "", "k-files", []string{file.ID}); Status(err) != http.StatusConflict {
139 t.Fatalf("same key, other files: %v", err)
140 }
141 if _, err := r.client.SendWith(r.ctx, "again", "k-reuse", []string{img.ID}); Status(err) != 422 {
142 t.Fatalf("an attachment sent twice: %v", err)
143 }
144
145 // The mailbox: the photo's one chunk, the notes' three, then the
146 // message frame naming both.
147 type got struct {
148 id string
149 chunk *wire.AttachmentChunk
150 }
151 var frames []got
152 var cmd *wire.MessageCommand
153 var msgID string
154 for cmd == nil {
155 f, body, err := runner.Next(r.ctx)
156 if err != nil {
157 t.Fatal(err)
158 }
159 switch v := body.(type) {
160 case *wire.AttachmentChunk:
161 if len(frames) == 0 {
162 shape(t, "frames/attachment.json", runner.Received[len(runner.Received)-1])
163 }
164 frames = append(frames, got{f.ID, v})
165 case *wire.MessageCommand:
166 cmd, msgID = v, f.ID
167 shape(t, "frames/message-attachments.json", runner.Received[len(runner.Received)-1])
168 }
169 }
170 if len(frames) != 4 || frames[0].chunk.ID != img.ID || frames[1].chunk.ID != file.ID || frames[3].chunk.Index != 2 || frames[3].chunk.Count != 3 {
171 t.Fatalf("chunk frames %d", len(frames))
172 }
173 var whole []byte
174 for _, f := range frames[1:] {
175 if len(f.chunk.Data) > attach.ChunkBytes || f.chunk.Person != Owner {
176 t.Fatal("a chunk is too large or not the person's")
177 }
178 whole = append(whole, f.chunk.Data...)
179 }
180 if !bytes.Equal(whole, notes) || !bytes.Equal(frames[0].chunk.Data, kept) {
181 t.Fatal("the chunks do not make the files")
182 }
183 if len(cmd.Attachments) != 2 || cmd.Attachments[1].SHA256 != file.SHA256 || withoutProjectContext(t, cmd.Text) != "(files only, no words)" || len(cmd.PersonText) != 1 || cmd.PersonText[0] != "" {
184 t.Fatalf("message command %+v", cmd)
185 }
186
187 // Exactly once across a reconnect: ack two chunks, drop the stream.
188 for _, f := range frames[:2] {
189 if err := runner.Send(r.ctx, "a-"+f.id, wire.FrameAck, wire.Ack{ID: f.id}); err != nil {
190 t.Fatal(err)
191 }
192 }
193 waitAcked(t, r, frames[1].id)
194 runner.Close()
195 runner = r.dial(runner.Welcome.Generation)
196 var resent []string
197 for {
198 f, body, err := runner.Next(r.ctx)
199 if err != nil {
200 t.Fatal(err)
201 }
202 if _, ok := body.(*wire.AttachmentChunk); ok {
203 resent = append(resent, f.ID)
204 }
205 if f.Type == wire.FrameMessage {
206 if f.ID != msgID {
207 t.Fatalf("a new message frame %s after reconnect", f.ID)
208 }
209 break
210 }
211 }
212 if strings.Join(resent, ",") != frames[2].id+","+frames[3].id {
213 t.Fatalf("resent %v, want only the unacked chunks %s %s", resent, frames[2].id, frames[3].id)
214 }
215
216 // The message reads back with its attachments, as the event did.
217 page, err := r.client.Messages(r.ctx, "", 50)
218 if err != nil {
219 t.Fatal(err)
220 }
221 shape(t, "api/messages-attachments.json", page)
222 r.wait("message event", func(c *Conversation) bool {
223 m, ok := c.Messages[sent.Message.ID]
224 return ok && len(m.Attachments) == 2
225 })
226}
227
228// waitAcked waits until the instance has recorded the ack of a command.
229func waitAcked(t *testing.T, r *rig, id string) {
230 t.Helper()
231 for i := 0; i < 200; i++ {
232 var n int
233 if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE seq = ? AND acked_at IS NOT NULL", strings.TrimPrefix(id, "c")).Scan(&n); err == nil && n == 1 {
234 return
235 }
236 select {
237 case <-r.ctx.Done():
238 t.Fatal("ack not recorded")
239 default:
240 }
241 time.Sleep(20 * time.Millisecond)
242 }
243 t.Fatal("ack not recorded")
244}
245
246// TestContractStorageFullInWords: Astra round 2: a runner with no room
247// for an attachment refuses it and fails the turn runner_storage_full;
248// the conversation says so in words, not the general failure.
249func TestContractStorageFullInWords(t *testing.T) {
250 r := newRig(t)
251 runner := r.dial(0)
252 r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online })
253 a, err := r.client.Upload(r.ctx, "notes.txt", "text/plain", []byte("notes"))
254 if err != nil {
255 t.Fatal(err)
256 }
257 sent, err := r.client.SendWith(r.ctx, "look", "k-full", []string{a.ID})
258 if err != nil {
259 t.Fatal(err)
260 }
261 f, _, err := runner.Expect(r.ctx, wire.FrameAttachment)
262 if err != nil {
263 t.Fatal(err)
264 }
265 runner.Send(r.ctx, "a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID})
266 m, _, err := runner.Expect(r.ctx, wire.FrameMessage)
267 if err != nil {
268 t.Fatal(err)
269 }
270 runner.Send(r.ctx, "a-"+m.ID, wire.FrameAck, wire.Ack{ID: m.ID})
271 if err := runner.Send(r.ctx, "r-full", wire.FrameTurn, wire.TurnReport{TurnID: sent.Turn.ID, Attempt: 1, State: wire.TurnFailed, Reason: wire.ReasonStorageFull}); err != nil {
272 t.Fatal(err)
273 }
274 r.wait("failed", func(c *Conversation) bool {
275 v := c.Turns[sent.Turn.ID]
276 return v.State == wire.TurnFailed && v.Reason == wire.ReasonStorageFull
277 })
278 page := r.inst.Get(t, "/conversation")
279 if !strings.Contains(page, `data-ended="`+sent.Turn.ID+`"><p>Your runner has no room left for these attachments.`) || !strings.Contains(page, `data-failed-storage="Your runner has no room left`) {
280 t.Fatal("the conversation does not say the runner had no room")
281 }
282}
283