package thintest import ( "context" "encoding/json" "net/http" "slices" "testing" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/wire" ) // errorBody is a refusal's status and body (code, copy key, request id). func errorBody(t *testing.T, err error) (int, wire.Error) { t.Helper() s, ok := err.(*ErrStatus) if !ok { t.Fatalf("not a refusal: %v", err) } var e wire.Error if json.Unmarshal(s.Body, &e) != nil { t.Fatalf("body %s", s.Body) } return s.Status, e } // nextMessage reads the runner's frames up to the next message command // (warm, acks and attachment chunks go before it). func nextMessage(t *testing.T, r *rig, f *FakeRunner) *wire.MessageCommand { t.Helper() for { frame, body, err := f.Next(r.ctx) if err != nil { t.Fatal(err) } if frame.Type == wire.FrameMessage { return body.(*wire.MessageCommand) } } } // TestContractAssistantFiles (assistant attachments spec A1): over the // person API, as Base calls it. With a primary at 32 (unfinished work, no files) the snapshot says // can_attach false and a send with files is 409 attachments_unavailable // with the usual body, while words still go; with one at 33 it says true, // and the files ride to the runner in the Assistant's lane. func TestContractAssistantFiles(t *testing.T) { r := newRig(t) a := r.client.Assistant() old := r.dialAt(wire.Protocol32) up, err := r.client.Upload(r.ctx, "notes.md", "text/markdown", []byte("# Notes\nThe word is heron.\n")) if err != nil { t.Fatal(err) } if snap, err := a.Snapshot(r.ctx); err != nil || !snap.Available || snap.CanAttach { t.Fatalf("snapshot at 32 %+v %v", snap, err) } _, err = a.SendWith(r.ctx, "What does it say?", "a-1", []string{up.ID}) if status, e := errorBody(t, err); status != http.StatusConflict || e.Code != "attachments_unavailable" || e.CopyKey != "api.attachments_unavailable" || e.RequestID == "" { t.Fatalf("send with files at 32: %d %+v", status, e) } if _, err := a.Send(r.ctx, "Words alone", "a-2"); err != nil { t.Fatalf("words at 32: %v", err) } nextMessage(t, r, old) r = newRig(t) a = r.client.Assistant() if up, err = r.client.Upload(r.ctx, "notes.md", "text/markdown", []byte("# Notes\nThe word is heron.\n")); err != nil { t.Fatal(err) } current := r.dialAt(wire.ProtocolAssistantFiles) if snap, err := a.Snapshot(r.ctx); err != nil || !snap.CanAttach { t.Fatalf("snapshot at 33 %+v %v", snap, err) } sent, err := a.SendWith(r.ctx, "What does it say?", "a-3", []string{up.ID}) if err != nil || len(sent.Message.Attachments) != 1 || sent.Message.Attachments[0].ID != up.ID { t.Fatalf("send at 33 %+v %v", sent, err) } m := nextMessage(t, r, current) if m.Lane != wire.LaneAssistant || m.TurnID != sent.Turn.ID || len(m.Attachments) != 1 || m.Attachments[0].ID != up.ID { t.Fatalf("message frame %+v", m) } } // TestContractAttachmentDelete (spec A2): the person deletes their own // unsent upload with their bearer. Gone is 404 (another person's too), a // sent one is 409 attachment_sent, and a browser session is refused. func TestContractAttachmentDelete(t *testing.T) { r := newRig(t) r.dialAt(wire.ProtocolAssistantFiles) up := func(name string) string { t.Helper() a, err := r.client.Upload(r.ctx, name, "text/markdown", []byte("# "+name)) if err != nil { t.Fatal(err) } return a.ID } gone, sent := up("gone.md"), up("sent.md") for _, auth := range []struct { token string cookie bool }{{"", false}, {"", true}} { var cookie *http.Cookie if auth.cookie { cookie = r.inst.Cookie() } if status, _, body := raw(t, http.MethodDelete, r.inst.URL+"/api/v1/attachments/"+gone, auth.token, cookie, ""); status != http.StatusUnauthorized { t.Fatalf("delete without a bearer (cookie %v): %d %s", auth.cookie, status, body) } } if err := r.client.DeleteAttachment(r.ctx, gone); err != nil { t.Fatalf("delete: %v", err) } if _, _, err := r.client.Attachment(r.ctx, gone, false); err == nil { t.Fatal("a deleted upload still reads") } if status, e := errorBody(t, r.client.DeleteAttachment(r.ctx, gone)); status != http.StatusNotFound || e.Code != "not_found" { t.Fatalf("second delete %d %+v", status, e) } if _, err := r.client.Assistant().SendWith(r.ctx, "", "a-1", []string{sent}); err != nil { t.Fatal(err) } if status, e := errorBody(t, r.client.DeleteAttachment(r.ctx, sent)); status != http.StatusConflict || e.Code != "attachment_sent" || e.CopyKey != "api.attachment_sent" { t.Fatalf("delete a sent upload %d %+v", status, e) } // Another person's id is not theirs to know of. const address = "member@example.com" if err := r.inst.Store.SetMember(context.Background(), equipo.Actor{Address: Owner}, address, equipo.RoleMember, true, 0); err != nil { t.Fatal(err) } member := NewClient(r.inst.URL, r.inst.DeviceTokenFor(t, address)) if status, e := errorBody(t, member.DeleteAttachment(r.ctx, up("mine.md"))); status != http.StatusNotFound { t.Fatalf("another person's upload %d %+v", status, e) } page, err := r.client.Assistant().Messages(r.ctx, "", 5) if err != nil || len(page.Items) != 1 || !slices.ContainsFunc(page.Items[0].Attachments, func(a wire.MessageAttachment) bool { return a.ID == sent }) { t.Fatalf("the sent file left its message %+v %v", page.Items, err) } } // TestContractAttachmentDeletePage (review S2): the conversation page's // own DELETE /conversation/attachments/{id} takes the person's session // from this origin only, as its upload does: Sec-Fetch-Site must say // same-origin (a same-origin Origin alone passes the CSRF check, not the // route). A cross-site request, one that does not say where it came // from, and one with no session are refused and the upload stays; another member's id answers 204 like a gone one, and their // upload stays. func TestContractAttachmentDeletePage(t *testing.T) { r := newRig(t) const address = "member@example.com" if err := r.inst.Store.SetMember(context.Background(), equipo.Actor{Address: Owner}, address, equipo.RoleMember, true, 0); err != nil { t.Fatal(err) } up, err := r.client.Upload(r.ctx, "notes.md", "text/markdown", []byte("# Notes\n")) if err != nil { t.Fatal(err) } held := func() int { t.Helper() var n int if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_attachments WHERE id = ?", up.ID).Scan(&n); err != nil { t.Fatal(err) } return n } del := func(cookie *http.Cookie, site, origin string) int { t.Helper() req, _ := http.NewRequest(http.MethodDelete, r.inst.URL+"/conversation/attachments/"+up.ID, nil) if cookie != nil { req.AddCookie(cookie) } if site != "" { req.Header.Set("Sec-Fetch-Site", site) } if origin != "" { req.Header.Set("Origin", origin) } client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} res, err := client.Do(req) if err != nil { t.Fatal(err) } res.Body.Close() return res.StatusCode } for name, tc := range map[string]struct { cookie *http.Cookie site, origin string }{ "cross-site": {r.inst.Cookie(), "cross-site", "https://foreign.example"}, "no fetch site": {r.inst.Cookie(), "", ""}, "origin alone": {r.inst.Cookie(), "", r.inst.URL}, "same-site": {r.inst.Cookie(), "same-site", ""}, "no session": {nil, "same-origin", r.inst.URL}, "another member's": {r.inst.SessionFor(t, address), "same-origin", r.inst.URL}, } { status := del(tc.cookie, tc.site, tc.origin) if held() != 1 { t.Fatalf("%s: the upload was deleted (%d)", name, status) } if name == "another member's" { if status != http.StatusNoContent { t.Fatalf("%s: %d, want 204 as for a gone upload", name, status) } } else if status == http.StatusNoContent || status/100 == 2 { t.Fatalf("%s: %d", name, status) } } if status := del(r.inst.Cookie(), "same-origin", r.inst.URL); status != http.StatusNoContent || held() != 0 { t.Fatalf("the owner's own delete: %d, %d left", status, held()) } }