package thintest import ( "bytes" "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "net/http" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/attach" "amadan.net/oficina/equipo/internal/attach/attachtest" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/wire" ) // notesOf is a text file of n bytes. func notesOf(n int) []byte { var b bytes.Buffer for i := 0; b.Len() < n; i++ { b.WriteString("line " + strings.Repeat("x", i%40) + "\n") } return b.Bytes()[:n] } func errCode(err error) (int, string) { var s *ErrStatus if !errors.As(err, &s) { return 0, "" } var e wire.Error _ = json.Unmarshal(s.Body, &e) return s.Status, e.Code } // TestContractAttachments: upload, limits, location stripped, person // scoped, sent with a message, and relayed through the mailbox as chunk // frames before the message frame, exactly once across a reconnect. func TestContractAttachments(t *testing.T) { r := newRig(t) runner := r.dial(0) r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online }) photo := attachtest.Photo(40, 20, 6) img, err := r.client.Upload(r.ctx, "IMG_0001.jpg", "image/jpeg", photo) if err != nil { t.Fatal(err) } shape(t, "api/attachment.json", img) if img.Kind != wire.AttachmentImage || img.MediaType != attach.JPEG || img.Width != 20 || img.Height != 40 || img.MessageID != "" || img.Revision != 1 { t.Fatalf("upload %+v", img) } kept, header, err := r.client.Attachment(r.ctx, img.ID, false) if err != nil { t.Fatal(err) } sum := sha256.Sum256(kept) if attachtest.HasGPS(kept) || hex.EncodeToString(sum[:]) != img.SHA256 || int64(len(kept)) != img.Size { t.Fatal("the kept photo still has its location, or its hash or size is wrong") } if header.Get("Content-Type") != attach.JPEG || header.Get("X-Content-Type-Options") != "nosniff" || !strings.Contains(header.Get("Content-Security-Policy"), "sandbox") { t.Fatalf("served with %v", header) } notes := notesOf(300 << 10) file, err := r.client.Upload(r.ctx, "../notes.md", "text/markdown", notes) if err != nil || file.Name != "notes.md" || file.MediaType != attach.Markdown || file.Kind != wire.AttachmentFile { t.Fatalf("file upload %+v %v", file, err) } // Astra round 1: every file that is not an image downloads, never // shows inline (text accepted as plain text may be HTML). for name, body := range map[string][]byte{"page.html": []byte(""), "notes2.md": []byte("# hi")} { a, err := r.client.Upload(r.ctx, name, "text/html", body) if err != nil { t.Fatal(err) } _, h, err := r.client.Attachment(r.ctx, a.ID, false) 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") { t.Fatalf("%s served as %q %q", name, h.Get("Content-Disposition"), h.Get("Content-Type")) } } if _, h, _ := r.client.Attachment(r.ctx, img.ID, false); !strings.HasPrefix(h.Get("Content-Disposition"), "inline;") { t.Fatalf("an image no longer shows inline: %q", h.Get("Content-Disposition")) } // Limits, refused in words by code. _, err = r.client.Upload(r.ctx, "IMG_0002.HEIC", "image/heic", []byte("\x00\x00\x00\x18ftypheic\x00\x00\x00\x00mif1heic")) if status, code := errCode(err); status != http.StatusUnsupportedMediaType || code != "attachment_heic" { t.Fatalf("heic %d %s", status, code) } var e *ErrStatus errors.As(err, &e) shape(t, "api/error-attachment.json", e.Body) _, err = r.client.Upload(r.ctx, "big.log", "text/plain", bytes.Repeat([]byte("a"), attach.MaxBytes+1)) if status, code := errCode(err); status != http.StatusRequestEntityTooLarge || code != "attachment_too_large" { t.Fatalf("too large %d %s", status, code) } _, err = r.client.Upload(r.ctx, "huge.png", "image/png", attachtest.PNGHeader(100000, 100000)) if status, code := errCode(err); status != http.StatusRequestEntityTooLarge || code != "attachment_pixels" { t.Fatalf("a 100,000 px square %d %s", status, code) } _, err = r.client.Upload(r.ctx, "tool.exe", "application/octet-stream", []byte{0x4d, 0x5a, 0, 1, 2}) if status, code := errCode(err); status != http.StatusUnsupportedMediaType || code != "attachment_type" { t.Fatalf("binary %d %s", status, code) } // Person scoped: a teammate can neither read nor send someone's upload. const member = "member@example.com" if err := r.inst.Store.SetMember(context.Background(), equipo.Actor{Address: Owner}, member, equipo.RoleMember, true, 0); err != nil { t.Fatal(err) } other := NewClient(r.inst.URL, r.inst.DeviceTokenFor(t, member)) if _, _, err := other.Attachment(r.ctx, img.ID, false); Status(err) != http.StatusNotFound { t.Fatalf("a teammate read the upload: %v", err) } if _, err := other.SendWith(r.ctx, "mine now", "m-1", []string{img.ID}); Status(err) != 422 { t.Fatalf("a teammate sent the upload: %v", err) } 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 { t.Fatalf("six attachments: %v", err) } // Sent with no words: the message carries both, in order. sent, err := r.client.SendWith(r.ctx, "", "k-files", []string{img.ID, file.ID}) if err != nil { t.Fatal(err) } if len(sent.Message.Attachments) != 2 || sent.Message.Attachments[0].ID != img.ID || sent.Message.Attachments[1].MessageID != sent.Message.ID { t.Fatalf("sent %+v", sent.Message) } again, err := r.client.SendWith(r.ctx, "", "k-files", []string{img.ID, file.ID}) if err != nil || again.Message.ID != sent.Message.ID { t.Fatalf("idempotent resend %+v %v", again, err) } if _, err := r.client.SendWith(r.ctx, "", "k-files", []string{file.ID}); Status(err) != http.StatusConflict { t.Fatalf("same key, other files: %v", err) } if _, err := r.client.SendWith(r.ctx, "again", "k-reuse", []string{img.ID}); Status(err) != 422 { t.Fatalf("an attachment sent twice: %v", err) } // The mailbox: the photo's one chunk, the notes' three, then the // message frame naming both. type got struct { id string chunk *wire.AttachmentChunk } var frames []got var cmd *wire.MessageCommand var msgID string for cmd == nil { f, body, err := runner.Next(r.ctx) if err != nil { t.Fatal(err) } switch v := body.(type) { case *wire.AttachmentChunk: if len(frames) == 0 { shape(t, "frames/attachment.json", runner.Received[len(runner.Received)-1]) } frames = append(frames, got{f.ID, v}) case *wire.MessageCommand: cmd, msgID = v, f.ID shape(t, "frames/message-attachments.json", runner.Received[len(runner.Received)-1]) } } 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 { t.Fatalf("chunk frames %d", len(frames)) } var whole []byte for _, f := range frames[1:] { if len(f.chunk.Data) > attach.ChunkBytes || f.chunk.Person != Owner { t.Fatal("a chunk is too large or not the person's") } whole = append(whole, f.chunk.Data...) } if !bytes.Equal(whole, notes) || !bytes.Equal(frames[0].chunk.Data, kept) { t.Fatal("the chunks do not make the files") } 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] != "" { t.Fatalf("message command %+v", cmd) } // Exactly once across a reconnect: ack two chunks, drop the stream. for _, f := range frames[:2] { if err := runner.Send(r.ctx, "a-"+f.id, wire.FrameAck, wire.Ack{ID: f.id}); err != nil { t.Fatal(err) } } waitAcked(t, r, frames[1].id) runner.Close() runner = r.dial(runner.Welcome.Generation) var resent []string for { f, body, err := runner.Next(r.ctx) if err != nil { t.Fatal(err) } if _, ok := body.(*wire.AttachmentChunk); ok { resent = append(resent, f.ID) } if f.Type == wire.FrameMessage { if f.ID != msgID { t.Fatalf("a new message frame %s after reconnect", f.ID) } break } } if strings.Join(resent, ",") != frames[2].id+","+frames[3].id { t.Fatalf("resent %v, want only the unacked chunks %s %s", resent, frames[2].id, frames[3].id) } // The message reads back with its attachments, as the event did. page, err := r.client.Messages(r.ctx, "", 50) if err != nil { t.Fatal(err) } shape(t, "api/messages-attachments.json", page) r.wait("message event", func(c *Conversation) bool { m, ok := c.Messages[sent.Message.ID] return ok && len(m.Attachments) == 2 }) } // waitAcked waits until the instance has recorded the ack of a command. func waitAcked(t *testing.T, r *rig, id string) { t.Helper() for i := 0; i < 200; i++ { var n int 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 { return } select { case <-r.ctx.Done(): t.Fatal("ack not recorded") default: } time.Sleep(20 * time.Millisecond) } t.Fatal("ack not recorded") } // TestContractStorageFullInWords: Astra round 2: a runner with no room // for an attachment refuses it and fails the turn runner_storage_full; // the conversation says so in words, not the general failure. func TestContractStorageFullInWords(t *testing.T) { r := newRig(t) runner := r.dial(0) r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online }) a, err := r.client.Upload(r.ctx, "notes.txt", "text/plain", []byte("notes")) if err != nil { t.Fatal(err) } sent, err := r.client.SendWith(r.ctx, "look", "k-full", []string{a.ID}) if err != nil { t.Fatal(err) } f, _, err := runner.Expect(r.ctx, wire.FrameAttachment) if err != nil { t.Fatal(err) } runner.Send(r.ctx, "a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}) m, _, err := runner.Expect(r.ctx, wire.FrameMessage) if err != nil { t.Fatal(err) } runner.Send(r.ctx, "a-"+m.ID, wire.FrameAck, wire.Ack{ID: m.ID}) 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 { t.Fatal(err) } r.wait("failed", func(c *Conversation) bool { v := c.Turns[sent.Turn.ID] return v.State == wire.TurnFailed && v.Reason == wire.ReasonStorageFull }) page := r.inst.Get(t, "/conversation") if !strings.Contains(page, `data-ended="`+sent.Turn.ID+`">
Your runner has no room left for these attachments.`) || !strings.Contains(page, `data-failed-storage="Your runner has no room left`) { t.Fatal("the conversation does not say the runner had no room") } }