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 "context"
5 "encoding/json"
6 "net/http"
7 "slices"
8 "testing"
9
10 "amadan.net/oficina/equipo/internal/equipo"
11 "amadan.net/oficina/equipo/internal/wire"
12)
13
14// errorBody is a refusal's status and body (code, copy key, request id).
15func errorBody(t *testing.T, err error) (int, wire.Error) {
16 t.Helper()
17 s, ok := err.(*ErrStatus)
18 if !ok {
19 t.Fatalf("not a refusal: %v", err)
20 }
21 var e wire.Error
22 if json.Unmarshal(s.Body, &e) != nil {
23 t.Fatalf("body %s", s.Body)
24 }
25 return s.Status, e
26}
27
28// nextMessage reads the runner's frames up to the next message command
29// (warm, acks and attachment chunks go before it).
30func nextMessage(t *testing.T, r *rig, f *FakeRunner) *wire.MessageCommand {
31 t.Helper()
32 for {
33 frame, body, err := f.Next(r.ctx)
34 if err != nil {
35 t.Fatal(err)
36 }
37 if frame.Type == wire.FrameMessage {
38 return body.(*wire.MessageCommand)
39 }
40 }
41}
42
43// TestContractAssistantFiles (assistant attachments spec A1): over the
44// person API, as Base calls it. With a primary at 32 (unfinished work, no files) the snapshot says
45// can_attach false and a send with files is 409 attachments_unavailable
46// with the usual body, while words still go; with one at 33 it says true,
47// and the files ride to the runner in the Assistant's lane.
48func TestContractAssistantFiles(t *testing.T) {
49 r := newRig(t)
50 a := r.client.Assistant()
51 old := r.dialAt(wire.Protocol32)
52 up, err := r.client.Upload(r.ctx, "notes.md", "text/markdown", []byte("# Notes\nThe word is heron.\n"))
53 if err != nil {
54 t.Fatal(err)
55 }
56 if snap, err := a.Snapshot(r.ctx); err != nil || !snap.Available || snap.CanAttach {
57 t.Fatalf("snapshot at 32 %+v %v", snap, err)
58 }
59 _, err = a.SendWith(r.ctx, "What does it say?", "a-1", []string{up.ID})
60 if status, e := errorBody(t, err); status != http.StatusConflict || e.Code != "attachments_unavailable" || e.CopyKey != "api.attachments_unavailable" || e.RequestID == "" {
61 t.Fatalf("send with files at 32: %d %+v", status, e)
62 }
63 if _, err := a.Send(r.ctx, "Words alone", "a-2"); err != nil {
64 t.Fatalf("words at 32: %v", err)
65 }
66 nextMessage(t, r, old)
67
68 r = newRig(t)
69 a = r.client.Assistant()
70 if up, err = r.client.Upload(r.ctx, "notes.md", "text/markdown", []byte("# Notes\nThe word is heron.\n")); err != nil {
71 t.Fatal(err)
72 }
73 current := r.dialAt(wire.ProtocolAssistantFiles)
74 if snap, err := a.Snapshot(r.ctx); err != nil || !snap.CanAttach {
75 t.Fatalf("snapshot at 33 %+v %v", snap, err)
76 }
77 sent, err := a.SendWith(r.ctx, "What does it say?", "a-3", []string{up.ID})
78 if err != nil || len(sent.Message.Attachments) != 1 || sent.Message.Attachments[0].ID != up.ID {
79 t.Fatalf("send at 33 %+v %v", sent, err)
80 }
81 m := nextMessage(t, r, current)
82 if m.Lane != wire.LaneAssistant || m.TurnID != sent.Turn.ID || len(m.Attachments) != 1 || m.Attachments[0].ID != up.ID {
83 t.Fatalf("message frame %+v", m)
84 }
85}
86
87// TestContractAttachmentDelete (spec A2): the person deletes their own
88// unsent upload with their bearer. Gone is 404 (another person's too), a
89// sent one is 409 attachment_sent, and a browser session is refused.
90func TestContractAttachmentDelete(t *testing.T) {
91 r := newRig(t)
92 r.dialAt(wire.ProtocolAssistantFiles)
93 up := func(name string) string {
94 t.Helper()
95 a, err := r.client.Upload(r.ctx, name, "text/markdown", []byte("# "+name))
96 if err != nil {
97 t.Fatal(err)
98 }
99 return a.ID
100 }
101 gone, sent := up("gone.md"), up("sent.md")
102 for _, auth := range []struct {
103 token string
104 cookie bool
105 }{{"", false}, {"", true}} {
106 var cookie *http.Cookie
107 if auth.cookie {
108 cookie = r.inst.Cookie()
109 }
110 if status, _, body := raw(t, http.MethodDelete, r.inst.URL+"/api/v1/attachments/"+gone, auth.token, cookie, ""); status != http.StatusUnauthorized {
111 t.Fatalf("delete without a bearer (cookie %v): %d %s", auth.cookie, status, body)
112 }
113 }
114 if err := r.client.DeleteAttachment(r.ctx, gone); err != nil {
115 t.Fatalf("delete: %v", err)
116 }
117 if _, _, err := r.client.Attachment(r.ctx, gone, false); err == nil {
118 t.Fatal("a deleted upload still reads")
119 }
120 if status, e := errorBody(t, r.client.DeleteAttachment(r.ctx, gone)); status != http.StatusNotFound || e.Code != "not_found" {
121 t.Fatalf("second delete %d %+v", status, e)
122 }
123 if _, err := r.client.Assistant().SendWith(r.ctx, "", "a-1", []string{sent}); err != nil {
124 t.Fatal(err)
125 }
126 if status, e := errorBody(t, r.client.DeleteAttachment(r.ctx, sent)); status != http.StatusConflict || e.Code != "attachment_sent" || e.CopyKey != "api.attachment_sent" {
127 t.Fatalf("delete a sent upload %d %+v", status, e)
128 }
129 // Another person's id is not theirs to know of.
130 const address = "member@example.com"
131 if err := r.inst.Store.SetMember(context.Background(), equipo.Actor{Address: Owner}, address, equipo.RoleMember, true, 0); err != nil {
132 t.Fatal(err)
133 }
134 member := NewClient(r.inst.URL, r.inst.DeviceTokenFor(t, address))
135 if status, e := errorBody(t, member.DeleteAttachment(r.ctx, up("mine.md"))); status != http.StatusNotFound {
136 t.Fatalf("another person's upload %d %+v", status, e)
137 }
138 page, err := r.client.Assistant().Messages(r.ctx, "", 5)
139 if err != nil || len(page.Items) != 1 || !slices.ContainsFunc(page.Items[0].Attachments, func(a wire.MessageAttachment) bool { return a.ID == sent }) {
140 t.Fatalf("the sent file left its message %+v %v", page.Items, err)
141 }
142}
143
144// TestContractAttachmentDeletePage (review S2): the conversation page's
145// own DELETE /conversation/attachments/{id} takes the person's session
146// from this origin only, as its upload does: Sec-Fetch-Site must say
147// same-origin (a same-origin Origin alone passes the CSRF check, not the
148// route). A cross-site request, one that does not say where it came
149// from, and one with no session are refused and the upload stays; another member's id answers 204 like a gone one, and their
150// upload stays.
151func TestContractAttachmentDeletePage(t *testing.T) {
152 r := newRig(t)
153 const address = "member@example.com"
154 if err := r.inst.Store.SetMember(context.Background(), equipo.Actor{Address: Owner}, address, equipo.RoleMember, true, 0); err != nil {
155 t.Fatal(err)
156 }
157 up, err := r.client.Upload(r.ctx, "notes.md", "text/markdown", []byte("# Notes\n"))
158 if err != nil {
159 t.Fatal(err)
160 }
161 held := func() int {
162 t.Helper()
163 var n int
164 if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_attachments WHERE id = ?", up.ID).Scan(&n); err != nil {
165 t.Fatal(err)
166 }
167 return n
168 }
169 del := func(cookie *http.Cookie, site, origin string) int {
170 t.Helper()
171 req, _ := http.NewRequest(http.MethodDelete, r.inst.URL+"/conversation/attachments/"+up.ID, nil)
172 if cookie != nil {
173 req.AddCookie(cookie)
174 }
175 if site != "" {
176 req.Header.Set("Sec-Fetch-Site", site)
177 }
178 if origin != "" {
179 req.Header.Set("Origin", origin)
180 }
181 client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
182 res, err := client.Do(req)
183 if err != nil {
184 t.Fatal(err)
185 }
186 res.Body.Close()
187 return res.StatusCode
188 }
189 for name, tc := range map[string]struct {
190 cookie *http.Cookie
191 site, origin string
192 }{
193 "cross-site": {r.inst.Cookie(), "cross-site", "https://foreign.example"},
194 "no fetch site": {r.inst.Cookie(), "", ""},
195 "origin alone": {r.inst.Cookie(), "", r.inst.URL},
196 "same-site": {r.inst.Cookie(), "same-site", ""},
197 "no session": {nil, "same-origin", r.inst.URL},
198 "another member's": {r.inst.SessionFor(t, address), "same-origin", r.inst.URL},
199 } {
200 status := del(tc.cookie, tc.site, tc.origin)
201 if held() != 1 {
202 t.Fatalf("%s: the upload was deleted (%d)", name, status)
203 }
204 if name == "another member's" {
205 if status != http.StatusNoContent {
206 t.Fatalf("%s: %d, want 204 as for a gone upload", name, status)
207 }
208 } else if status == http.StatusNoContent || status/100 == 2 {
209 t.Fatalf("%s: %d", name, status)
210 }
211 }
212 if status := del(r.inst.Cookie(), "same-origin", r.inst.URL); status != http.StatusNoContent || held() != 0 {
213 t.Fatalf("the owner's own delete: %d, %d left", status, held())
214 }
215}
216