oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1package slides
2
3import (
4 "context"
5 "crypto/sha256"
6 "encoding/hex"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "image/color"
11 "net/http"
12 "net/http/httptest"
13 "net/url"
14 "strings"
15 "testing"
16 "time"
17
18 "amadan.net/oficina/home/roster"
19 "amadan.net/oficina/home/teammode"
20 "amadan.net/oficina/slides/internal/slides/assist"
21 "amadan.net/rastrillo/rastrillo/blobs"
22)
23
24// lapsingGuard makes every team-mode write's lease run out between the
25// write and its commit: the directory goes down and the clock passes the
26// lease inside the transaction, so the guard's after-check reads Unknown.
27func lapsingGuard(t *testing.T, f *teamFixture) {
28 t.Helper()
29 teamGuard = lapsing(f)
30 t.Cleanup(func() { teamGuard = teammode.Guard })
31}
32
33// lapsing is the guard lapsingGuard installs.
34func lapsing(f *teamFixture) func(context.Context, func(roster.State) error, func() error) error {
35 return func(ctx context.Context, authorize func(roster.State) error, write func() error) error {
36 return teammode.Guard(ctx, authorize, func() error {
37 err := write()
38 f.dir.SetDown(true)
39 f.clock.Step(roster.MaximumAge + time.Second)
40 return err
41 })
42 }
43}
44
45// renewed brings the directory back and refreshes, so the next request
46// starts on a fresh Member lease.
47func (f *teamFixture) renewed() {
48 f.t.Helper()
49 f.dir.SetDown(false)
50 f.refreshed()
51}
52
53// update is a valid Yjs update for d made by the core itself: ops on a
54// freshly replayed handle, as the editor's would be.
55func (f *teamFixture) update(d Deck, title string) []byte {
56 f.t.Helper()
57 ctx := context.Background()
58 var fresh Deck
59 if err := f.d.G.Take(&fresh, d.ID).Error; err != nil {
60 f.t.Fatal(err)
61 }
62 h, _, err := f.a.openDeck(ctx, fresh)
63 if err != nil {
64 f.t.Fatal(err)
65 }
66 defer h.Close(ctx)
67 ops, err := opsJSON([]op{{"op": "set_meta", "title": title, "theme": defaultTheme}})
68 if err != nil {
69 f.t.Fatal(err)
70 }
71 b, err := h.Ops(ctx, ops)
72 if err != nil {
73 f.t.Fatal(err)
74 }
75 return b
76}
77
78// agent mints a live agent for u and returns its token.
79func (f *teamFixture) agent(u User) string {
80 f.t.Helper()
81 token, err := newAgentToken()
82 if err != nil {
83 f.t.Fatal(err)
84 }
85 if err := f.d.G.Create(&Agent{Name: "claude", OperatorID: u.ID, TokenHash: hashAgentToken(token), CreatedAt: time.Now().UTC()}).Error; err != nil {
86 f.t.Fatal(err)
87 }
88 return token
89}
90
91func (f *teamFixture) api(token, method, path, body string) *httptest.ResponseRecorder {
92 r := httptest.NewRequest(method, homeTestOrigin+path, strings.NewReader(body))
93 r.Header.Set("Authorization", "Bearer "+token)
94 if body != "" {
95 r.Header.Set("Content-Type", "application/json")
96 }
97 w := httptest.NewRecorder()
98 f.mux.ServeHTTP(w, r)
99 return w
100}
101
102// snapshot is what a refused write must leave exactly as it was.
103type teamSnapshot struct {
104 decks, updates, links, revoked, presentations int64
105 uploads, uploadsLanded, uploadsSpent, assets int64
106 title, rung string
107 seq int64
108}
109
110func (f *teamFixture) snapshot(d Deck) teamSnapshot {
111 f.t.Helper()
112 var s teamSnapshot
113 g := f.d.G
114 g.Model(&Deck{}).Count(&s.decks)
115 g.Model(&DeckUpdate{}).Count(&s.updates)
116 g.Model(&ShareLink{}).Count(&s.links)
117 g.Model(&ShareLink{}).Where("revoked_at IS NOT NULL").Count(&s.revoked)
118 g.Model(&Presentation{}).Count(&s.presentations)
119 g.Model(&AssetUpload{}).Count(&s.uploads)
120 g.Model(&AssetUpload{}).Where("object_key != ''").Count(&s.uploadsLanded)
121 g.Model(&AssetUpload{}).Where("consumed_at IS NOT NULL").Count(&s.uploadsSpent)
122 g.Model(&DeckAsset{}).Count(&s.assets)
123 var row Deck
124 if err := g.Take(&row, d.ID).Error; err != nil {
125 f.t.Fatalf("deck %d gone: %v", d.ID, err)
126 }
127 s.title, s.rung, s.seq = row.Title, row.Rung, row.Seq
128 return s
129}
130
131// Every write route, with the lease lapsing between the write and its
132// commit: each answers the retryable 503, and nothing any of them wrote
133// survived (Fable's #53 required test 2, for Slides: the database is
134// read back, not just the status).
135func TestTeamEveryWriteRouteRefusesALapseBeforeCommit(t *testing.T) {
136 t.Run("delegated deck edit", testAgentDeckEditGuardLapse)
137 f := newTeamFixture(t)
138 store, err := blobs.Dir(t.TempDir())
139 if err != nil {
140 t.Fatal(err)
141 }
142 f.a.cfg.Blobs = store
143 u := f.member(teamSubject('a'), "member")
144 plan := f.deck(u, "Team plan", rungTeam)
145 token := f.agent(u)
146 link := ShareLink{DeckID: plan.ID, TokenHash: "h", Actor: actorFor(u), CreatedAt: time.Now().UTC()}
147 if err := f.d.G.Create(&link).Error; err != nil {
148 t.Fatal(err)
149 }
150 lapsingGuard(t, f)
151
152 // The picture the upload routes carry, and its staging: signed (and
153 // for registration also landed) under the real guard, so only the
154 // route under test meets the lapse.
155 png := pngBytes(t, 4, 4, color.Black)
156 sum := sha256.Sum256(png)
157 signBody := fmt.Sprintf(`{"name":"a.png","size":%d,"type":"image/png","hash":%q}`, len(png), hex.EncodeToString(sum[:]))
158 var staged struct {
159 Ref string `json:"ref"`
160 URL string `json:"url"`
161 }
162 stage := func(land bool) {
163 teamGuard = teammode.Guard
164 defer func() { teamGuard = lapsing(f) }()
165 f.renewed()
166 got := f.do("POST", deckPath(plan)+"/uploads", signBody, "application/json", homeTestOrigin)
167 if got.Code != 200 || json.Unmarshal(got.Body.Bytes(), &staged) != nil {
168 t.Fatalf("staging an upload = %d %s", got.Code, got.Body.String())
169 }
170 if land {
171 if put := f.do("PUT", staged.URL, string(png), "image/png", homeTestOrigin); put.Code != http.StatusNoContent {
172 t.Fatalf("landing an upload = %d %s", put.Code, put.Body.String())
173 }
174 }
175 }
176
177 routes := []struct {
178 name string
179 setup func()
180 do func() *httptest.ResponseRecorder
181 }{
182 {"create", nil, func() *httptest.ResponseRecorder {
183 return f.post("/decks", url.Values{"title": {"New"}, "theme": {defaultTheme}})
184 }},
185 {"live update", nil, func() *httptest.ResponseRecorder {
186 return f.do("POST", deckPath(plan)+"/updates", string(f.update(plan, "Typed")), "application/octet-stream", homeTestOrigin)
187 }},
188 {"settings", nil, func() *httptest.ResponseRecorder {
189 return f.post(deckPath(plan)+"/settings", url.Values{"title": {"Renamed"}, "theme": {defaultTheme}, "rung": {rungPrivate}})
190 }},
191 {"share access", nil, func() *httptest.ResponseRecorder {
192 return f.post(deckPath(plan)+"/share/access", url.Values{"rung": {rungPrivate}})
193 }},
194 {"delete", nil, func() *httptest.ResponseRecorder { return f.post(deckPath(plan)+"/delete", nil) }},
195 {"share link", nil, func() *httptest.ResponseRecorder { return f.post(deckPath(plan)+"/share", nil) }},
196 {"share revoke", nil, func() *httptest.ResponseRecorder {
197 return f.post(fmt.Sprintf("%s/share/%d/revoke", deckPath(plan), link.ID), nil)
198 }},
199 {"present", nil, func() *httptest.ResponseRecorder { return f.post(deckPath(plan)+"/present", nil) }},
200 {"upload", nil, func() *httptest.ResponseRecorder {
201 return f.do("POST", deckPath(plan)+"/uploads", signBody, "application/json", homeTestOrigin)
202 }},
203 {"upload put", func() { stage(false) }, func() *httptest.ResponseRecorder {
204 return f.do("PUT", staged.URL, string(png), "image/png", homeTestOrigin)
205 }},
206 {"asset register", func() { stage(true) }, func() *httptest.ResponseRecorder {
207 return f.do("POST", deckPath(plan)+"/assets", fmt.Sprintf(`{"ref":%q,"name":"a.png","width":4,"height":4,"alt":"a dot"}`, staged.Ref), "application/json", homeTestOrigin)
208 }},
209 // The assistant writes nothing itself, but it must not send a
210 // team's deck to a model for somebody whose standing lapsed:
211 // the guard runs before the model is asked.
212 {"assist", func() {
213 f.a.assist = newAssistant(nil, []string{"m"})
214 f.a.assist.client = refusingModel{t}
215 }, func() *httptest.ResponseRecorder {
216 return f.do("POST", deckPath(plan)+"/assist", `{"prompt":"x","scope":"deck"}`, "application/json", homeTestOrigin)
217 }},
218 {"api create", nil, func() *httptest.ResponseRecorder {
219 return f.api(token, "POST", apiPrefix+"/decks", `{"title":"By agent"}`)
220 }},
221 {"api ops", nil, func() *httptest.ResponseRecorder {
222 return f.api(token, "POST", apiPrefix+"/decks/"+plan.Sqid+"/ops", `{"ops":[{"op":"set_meta","title":"Agent title"}]}`)
223 }},
224 {"api present", nil, func() *httptest.ResponseRecorder {
225 return f.api(token, "POST", apiPrefix+"/decks/"+plan.Sqid+"/present", "")
226 }},
227 {"api asset", nil, func() *httptest.ResponseRecorder {
228 return f.api(token, "POST", apiPrefix+"/decks/"+plan.Sqid+"/assets", string(png))
229 }},
230 }
231 for _, route := range routes {
232 if route.setup != nil {
233 route.setup()
234 }
235 f.renewed()
236 before := f.snapshot(plan)
237 got := route.do()
238 if got.Code != http.StatusServiceUnavailable {
239 t.Errorf("%s with a lapsing lease = %d %s, want 503", route.name, got.Code, got.Body.String())
240 }
241 if after := f.snapshot(plan); after != before {
242 t.Errorf("%s: something a refused write made survived: %+v -> %+v", route.name, before, after)
243 }
244 }
245}
246
247// refusingModel is an assistant client that fails the test if asked.
248type refusingModel struct{ t *testing.T }
249
250func (m refusingModel) Complete(context.Context, string, []assist.Message) (string, error) {
251 m.t.Error("the model was asked for a deck whose standing lapsed")
252 return "", errors.New("refused")
253}
254
255// The rule teammode leaves to the app: a write a grant reaches does not
256// rest on standing, so it is made under Unknown; one that rests on the
257// team rung is the retryable 503.
258func TestTeamGrantStillWritesUnderUnknownStanding(t *testing.T) {
259 f := newTeamFixture(t)
260 colleague := f.member(teamSubject('b'), "member")
261 shared := f.deck(colleague, "Shared", rungPrivate)
262 plan := f.deck(colleague, "Team plan", rungTeam)
263 u := f.member(teamSubject('a'), "member")
264 f.grant(shared, u, colleague)
265 sharedUpdate, planUpdate := f.update(shared, "Typed"), f.update(plan, "Typed")
266 f.expired()
267 if got := f.do("POST", deckPath(shared)+"/updates", string(sharedUpdate), "application/octet-stream", homeTestOrigin); got.Code != http.StatusNoContent {
268 t.Fatalf("granted deck write under Unknown = %d %s", got.Code, got.Body.String())
269 }
270 if got := f.do("POST", deckPath(plan)+"/updates", string(planUpdate), "application/octet-stream", homeTestOrigin); got.Code != http.StatusServiceUnavailable {
271 t.Fatalf("team deck write under Unknown = %d, want 503", got.Code)
272 }
273 // And the grant carries a write through a lapse too: nothing about it
274 // rested on the lease.
275 f.renewed()
276 lapsingGuard(t, f)
277 if got := f.do("POST", deckPath(shared)+"/updates", string(f.update(shared, "Again")), "application/octet-stream", homeTestOrigin); got.Code != http.StatusNoContent {
278 t.Fatalf("granted deck write through a lapse = %d", got.Code)
279 }
280}
281
282// A standing already Unknown refuses before anything is written, and a
283// user with no Access at all reads Unknown.
284func TestTeamGuardRefusesBeforeTheWrite(t *testing.T) {
285 f := newTeamFixture(t)
286 u := f.member(teamSubject('a'), "member")
287 check := func(name string) {
288 t.Helper()
289 called := false
290 err := f.a.memberGuard(context.Background(), u).run(func() error { called = true; return nil })
291 if !errors.Is(err, teammode.ErrUnavailable) || called {
292 t.Fatalf("%s: guard = %v, write called %v", name, err, called)
293 }
294 }
295 u.team = nil
296 check("no access")
297 f.expired()
298 u.team = &teamAccess{Access: f.a.team.Access(context.Background(), teamSubject('a'))}
299 check("unknown")
300}
301
302// Outside team mode there is no guard, and every write takes its old path.
303func TestNoGuardOutsideTeamMode(t *testing.T) {
304 _, a, u := homeFixture(t)
305 if a.memberGuard(context.Background(), u) != nil || a.deckGuard(context.Background(), u, Deck{ID: 1}) != nil {
306 t.Fatal("a guard outside team mode")
307 }
308 if a.team != nil || a.teamOn != nil {
309 t.Fatal("team mode on without configuration")
310 }
311 if !a.member(u) || a.teamPartial(u) || a.teamUnknown(u) {
312 t.Fatal("team answers outside team mode")
313 }
314 if a.presignTTLFor(u) != presignTTL {
315 t.Fatal("presign TTL changed outside team mode")
316 }
317}
318
319// An agent's picture is two writes: the verification row, then the
320// register_asset op. Standing that lapses during the second leaves the
321// first (a row that serves nothing) and refuses the second: a 503, the
322// document and its seq as they were, and the ref not served.
323func TestTeamAnAgentPictureLapsingDuringItsOpIsRefused(t *testing.T) {
324 f := newTeamFixture(t)
325 store, err := blobs.Dir(t.TempDir())
326 if err != nil {
327 t.Fatal(err)
328 }
329 f.a.cfg.Blobs = store
330 u := f.member(teamSubject('a'), "member")
331 plan := f.deck(u, "Team plan", rungTeam)
332 token := f.agent(u)
333 png := pngBytes(t, 4, 4, color.Black)
334 sum := sha256.Sum256(png)
335 ref := hex.EncodeToString(sum[:])
336
337 writes := 0
338 teamGuard = func(ctx context.Context, authorize func(roster.State) error, write func() error) error {
339 writes++
340 if writes == 1 {
341 return teammode.Guard(ctx, authorize, write)
342 }
343 return lapsing(f)(ctx, authorize, write)
344 }
345 t.Cleanup(func() { teamGuard = teammode.Guard })
346
347 before := f.snapshot(plan)
348 got := f.api(token, "POST", apiPrefix+"/decks/"+plan.Sqid+"/assets", string(png))
349 if got.Code != http.StatusServiceUnavailable {
350 t.Fatalf("a picture whose op lapsed = %d %s, want 503", got.Code, got.Body.String())
351 }
352 if writes != 2 {
353 t.Fatalf("%d guarded writes, want the row and then the op", writes)
354 }
355 after := f.snapshot(plan)
356 if after.seq != before.seq || after.updates != before.updates {
357 t.Errorf("the op was written: seq %d -> %d, updates %d -> %d", before.seq, after.seq, before.updates, after.updates)
358 }
359 if after.assets != before.assets+1 {
360 t.Errorf("verification rows %d -> %d, want the row committed", before.assets, after.assets)
361 }
362 var fresh Deck
363 if err := f.d.G.Take(&fresh, plan.ID).Error; err != nil {
364 t.Fatal(err)
365 }
366 h, view, err := f.a.openDeck(context.Background(), fresh)
367 if err != nil {
368 t.Fatal(err)
369 }
370 h.Close(context.Background())
371 if len(view.Assets) != 0 {
372 t.Errorf("the deck registers assets after a refused op: %+v", view.Assets)
373 }
374
375 teamGuard = teammode.Guard
376 f.renewed()
377 if rec := f.do("GET", deckPath(plan)+"/assets/"+ref, "", "", ""); rec.Code != http.StatusNotFound {
378 t.Errorf("the picture of a refused op is served: %d", rec.Code)
379 }
380 // And the same upload with standing back registers and serves it.
381 if rec := f.api(token, "POST", apiPrefix+"/decks/"+plan.Sqid+"/assets", string(png)); rec.Code != http.StatusCreated {
382 t.Fatalf("the upload again = %d %s, want 201", rec.Code, rec.Body.String())
383 }
384 if rec := f.do("GET", deckPath(plan)+"/assets/"+ref, "", "", ""); rec.Code != http.StatusOK {
385 t.Errorf("the picture once registered = %d, want 200", rec.Code)
386 }
387}
388