oficina / calendar Public

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

Plain git — no account needed to clone.

Download

Download this file

1package calendar
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "net/http"
8 "net/http/httptest"
9 "net/url"
10 "strings"
11 "testing"
12 "time"
13
14 "gorm.io/gorm"
15
16 "amadan.net/oficina/home/roster"
17 "amadan.net/oficina/home/teammode"
18)
19
20// teamSnapshot is every table a person's write can touch, row by row, so
21// "nothing it wrote survived" is read back rather than assumed. Sealed
22// columns carry a fresh nonce on every write, and every update moves
23// updated_at or a counter, so any write shows.
24func teamSnapshot(t *testing.T, f *teamFixture) string {
25 t.Helper()
26 var b strings.Builder
27 for _, table := range []string{"events", "reminders", "reminder_queues", "reminder_notices", "feeds", "people", "booking_pages", "booking_windows", "bookings", "booking_mails", "attendees", "calendars", "grants"} {
28 rows, err := f.app.DBForTest().Query("SELECT * FROM " + table + " ORDER BY rowid")
29 if err != nil {
30 t.Fatal(err)
31 }
32 cols, _ := rows.Columns()
33 for rows.Next() {
34 vals := make([]any, len(cols))
35 ptrs := make([]any, len(cols))
36 for i := range vals {
37 ptrs[i] = &vals[i]
38 }
39 if err := rows.Scan(ptrs...); err != nil {
40 t.Fatal(err)
41 }
42 fmt.Fprintf(&b, "%s %v\n", table, vals)
43 }
44 rows.Close()
45 }
46 return b.String()
47}
48
49// lapsingGuard is teammode.Guard with the lease running out between the
50// write and its commit: authorize, write, the directory goes away and the
51// clock passes the lease, authorize again.
52func (f *teamFixture) lapsingGuard(ctx context.Context, authorize func(roster.State) error, write func() error) error {
53 if err := authorize(teammode.Standing(ctx)); err != nil {
54 return err
55 }
56 if err := write(); err != nil {
57 return err
58 }
59 f.dir.SetDown(true)
60 f.clock.Step(roster.MaximumAge + time.Second)
61 return authorize(teammode.Standing(ctx))
62}
63
64// writeRoute is one write, and how to make it.
65type writeRoute struct {
66 name string
67 do func() *httptest.ResponseRecorder
68}
69
70// routes is every write a person (or, for the public booking routes, a
71// stranger on the host's standing) makes. Add yours.
72func (w *teamWriteWorld) routes() []writeRoute {
73 f := w.f
74 id := func(n int64) string { return itoa(n) }
75 public := func(do func() *httptest.ResponseRecorder) func() *httptest.ResponseRecorder {
76 return func() *httptest.ResponseRecorder {
77 jar := f.cookies
78 f.cookies = map[string]*http.Cookie{}
79 defer func() { f.cookies = jar }()
80 return do()
81 }
82 }
83 json := func(path, body string) func() *httptest.ResponseRecorder {
84 return func() *httptest.ResponseRecorder { return f.post(path, body) }
85 }
86 return []writeRoute{
87 {"create", func() *httptest.ResponseRecorder {
88 return f.post("/events", "calendar_id="+id(w.team)+"&title=New&start=2027-01-06T10:00&end=2027-01-06T11:00&tz=UTC&kind=meeting&status=confirmed")
89 }},
90 {"quick add", func() *httptest.ResponseRecorder { return f.post("/events/quick", "text=Lunch+tomorrow+at+1pm") }},
91 {"update", func() *httptest.ResponseRecorder {
92 return f.post("/events/"+id(w.single.ID), "title=Renamed&start=2027-01-05T10:00&end=2027-01-05T11:00&tz=UTC&kind=meeting&status=confirmed")
93 }},
94 {"update this occurrence", func() *httptest.ResponseRecorder {
95 return f.post("/events/"+id(w.series.ID), "scope=this&occurrence=2027-01-06T09:00&title=Moved&start=2027-01-06T10:00&end=2027-01-06T10:15&tz=UTC&kind=meeting&status=confirmed")
96 }},
97 {"split the series", func() *httptest.ResponseRecorder {
98 return f.post("/events/"+id(w.series.ID), "scope=following&occurrence=2027-01-08T09:00&title=Later&start=2027-01-08T09:30&end=2027-01-08T09:45&tz=UTC&kind=meeting&status=confirmed&repeat=daily")
99 }},
100 {"delete one occurrence", func() *httptest.ResponseRecorder {
101 return f.post("/events/"+id(w.series.ID)+"/delete", "scope=this&occurrence=2027-01-07T09:00")
102 }},
103 {"dismiss a reminder", func() *httptest.ResponseRecorder {
104 return f.post("/reminders/"+id(w.notices[0])+"/dismiss", "")
105 }},
106 {"dismiss all reminders", func() *httptest.ResponseRecorder { return f.post("/reminders/dismiss", "") }},
107 {"add reminder", func() *httptest.ResponseRecorder {
108 return f.post("/events/"+id(w.single.ID)+"/reminders", "offset_min=60")
109 }},
110 {"remove reminder", func() *httptest.ResponseRecorder {
111 return f.post("/events/"+id(w.single.ID)+"/reminders/remove", "reminder_id="+id(w.reminder))
112 }},
113 {"mint feed", func() *httptest.ResponseRecorder { return f.post("/calendars/"+id(w.team)+"/feeds", "") }},
114 {"revoke feed", func() *httptest.ResponseRecorder {
115 return f.post("/calendars/"+id(w.team)+"/feeds/revoke", "feed_id="+id(w.feed))
116 }},
117 {"import", func() *httptest.ResponseRecorder { return w.importICS() }},
118 {"settings", func() *httptest.ResponseRecorder {
119 return f.post("/settings", "zone=Europe%2FDublin&week_start=7&default_reminder_min=30&default_all_day_min=0&handle=alice")
120 }},
121 {"new booking page", func() *httptest.ResponseRecorder {
122 return f.post("/settings/booking", "title=Two&availability=weekdays+9-5&duration_min=30")
123 }},
124 {"edit booking page", func() *httptest.ResponseRecorder {
125 return f.post("/settings/booking/1", "title=Chat+again&availability=every+day+9-5&duration_min=30")
126 }},
127 {"native create", json("/api/native/events", `{"calendar_id":`+id(w.team)+`,"title":"Native","start_local":"2027-01-09T10:00","end_local":"2027-01-09T11:00","tz":"UTC"}`)},
128 {"native update", json("/api/native/events/"+id(w.single.ID), `{"title":"Native rename","start_local":"2027-01-05T10:00","end_local":"2027-01-05T11:00","tz":"UTC"}`)},
129 {"native quick", json("/api/native/quick", `{"calendar_id":`+id(w.team)+`,"title":"Native quick","start_local":"2027-01-10T10:00","end_local":"2027-01-10T11:00","tz":"UTC","repeat":"none"}`)},
130 {"booker holds", public(func() *httptest.ResponseRecorder {
131 return f.post(w.path, "start="+w.slots[len(w.slots)-1]+"&zone=UTC&name=Sam&address=sam%40example.org&note=hi")
132 })},
133 {"booker confirms", public(func() *httptest.ResponseRecorder { return f.post("/book/m/"+w.heldToken+"/confirm", "") })},
134 {"booker reschedules", public(func() *httptest.ResponseRecorder {
135 picker := f.get("/book/m/" + w.booked + "/reschedule?day=" + w.day + "&zone=UTC")
136 rev := reWorldRev.FindStringSubmatch(picker.Body.String())
137 if rev == nil {
138 return picker
139 }
140 return f.post("/book/m/"+w.booked+"/reschedule", "start="+w.slots[len(w.slots)-3]+"&zone=UTC&rev="+rev[1])
141 })},
142 // Last: they take what the routes above act on.
143 {"unpublish", func() *httptest.ResponseRecorder { return f.post("/settings/booking/1/publish", "publish=0") }},
144 {"delete", func() *httptest.ResponseRecorder { return f.post("/events/"+id(w.single.ID)+"/delete", "") }},
145 }
146}
147
148func TestTeamEveryWriteRouteRefusesALapseBeforeCommit(t *testing.T) {
149 w := newTeamWriteWorld(t)
150 f := w.f
151 defer func() { teamGuard = teammode.Guard }()
152 for _, route := range w.routes() {
153 f.refreshed()
154 before := teamSnapshot(t, f)
155 teamGuard = f.lapsingGuard
156 got := route.do()
157 teamGuard = teammode.Guard
158 retryable(t, route.name+" through a lapse", got)
159 if after := teamSnapshot(t, f); after != before {
160 t.Fatalf("%s: a write refused at commit left something behind", route.name)
161 }
162 }
163 // The success half: the same routes under the real guard, as a
164 // member (not an owner), each change the database.
165 for _, route := range w.routes() {
166 f.refreshed()
167 before := teamSnapshot(t, f)
168 got := route.do()
169 if got.Code >= 400 {
170 t.Fatalf("%s as a member = %d %s", route.name, got.Code, got.Body.String())
171 }
172 if teamSnapshot(t, f) == before {
173 t.Fatalf("%s as a member changed nothing", route.name)
174 }
175 }
176}
177
178func TestTeamGuardRefusesWithoutStanding(t *testing.T) {
179 f := newTeamFixture(t)
180 subject := teamSubject('x')
181 p := f.member(subject, "member")
182 team, _ := f.calendarsOf(p)
183 in := EventInput{CalendarID: team, Title: "Nope", StartLocal: "2027-01-05T10:00", EndLocal: "2027-01-05T11:00", TZ: "UTC", Kind: KindMeeting, Status: StatusConfirmed}
184 count := func() int64 {
185 var n int64
186 f.app.db.G.Model(&Event{}).Count(&n)
187 return n
188 }
189 // No Access at all: refused closed, in the store itself.
190 err := f.app.store.guarded(context.Background(), func(db *gorm.DB) error {
191 return db.Create(&Event{CalendarID: team, Kind: KindMeeting, Status: StatusConfirmed}).Error
192 })
193 if !errors.Is(err, teammode.ErrUnavailable) || count() != 0 {
194 t.Fatalf("a write with no standing = %v, %d events", err, count())
195 }
196 // Unknown: the read finds nothing to write to.
197 f.expired()
198 if _, err := f.app.store.CreateEvent(f.withAccess(subject), p.ID, in); err == nil || count() != 0 {
199 t.Fatalf("a write under Unknown = %v", err)
200 }
201 // A write whose own body lapses the lease rolls back (the guard's
202 // after-check, independent of the test seam).
203 f.refreshed()
204 ctx := f.withAccess(subject)
205 err = f.app.store.guarded(ctx, func(db *gorm.DB) error {
206 if err := db.Create(&Event{CalendarID: team, Kind: KindMeeting, Status: StatusConfirmed}).Error; err != nil {
207 return err
208 }
209 f.expired()
210 return nil
211 })
212 if !errors.Is(err, teammode.ErrUnavailable) || count() != 0 {
213 t.Fatalf("a write that lapsed inside itself = %v, %d events", err, count())
214 }
215 // A write that takes an id rather than reading through a grant
216 // (attendees, after the event was made) is guarded all the same.
217 f.refreshed()
218 made := f.event(p, subject, team, "Attended", "2027-01-05T10:00", "2027-01-05T11:00")
219 f.expired()
220 if err := f.app.store.SetAttendees(f.withAccess(subject), made.ID, []string{"guest@example.org"}); !errors.Is(err, teammode.ErrUnavailable) {
221 t.Fatalf("attendees under Unknown = %v", err)
222 }
223 var attendees int64
224 f.app.db.G.Model(&Attendee{}).Count(&attendees)
225 if attendees != 0 {
226 t.Fatal("attendees were written under Unknown")
227 }
228 withAddress := p // as a person with an address would be
229 withAddress.Address = "someone@example.test"
230 if err := f.app.store.EnsureDefaultReminder(f.withAccess(subject), withAddress, made); !errors.Is(err, teammode.ErrUnavailable) {
231 t.Fatalf("a default reminder under Unknown = %v", err)
232 }
233 var reminders int64
234 f.app.db.G.Model(&Reminder{}).Count(&reminders)
235 if reminders != 0 {
236 t.Fatal("a default reminder was written under Unknown")
237 }
238 f.app.db.G.Exec("DELETE FROM events")
239 // The instance's own work is not a person's write.
240 f.refreshed()
241 if err := f.app.store.guarded(systemWrite(f.withAccess(subject)), func(db *gorm.DB) error {
242 f.expired()
243 return db.Create(&Event{CalendarID: team, Kind: KindMeeting, Status: StatusConfirmed}).Error
244 }); err != nil || count() != 1 {
245 t.Fatalf("system work = %v, %d events", err, count())
246 }
247 // Outside team mode: no guard, exactly as before.
248 f.app.store.team = false
249 defer func() { f.app.store.team = true }()
250 if err := f.app.store.guarded(context.Background(), func(db *gorm.DB) error {
251 return db.Create(&Event{CalendarID: team, Kind: KindMeeting, Status: StatusConfirmed}).Error
252 }); err != nil || count() != 2 {
253 t.Fatalf("team mode off = %v", err)
254 }
255 _ = url.Values{}
256}
257
258// An import the lease runs out on part-way is a retry that says how many
259// events landed and that importing the same file again repeats them
260// (Fable #35 N1): the events before the lapse are committed, each under
261// its own guard, and import does not dedupe on UID.
262func TestTeamImportStoppedPartWaySaysWhatLanded(t *testing.T) {
263 w := newTeamWriteWorld(t)
264 f := w.f
265 defer func() { teamGuard = teammode.Guard }()
266 writes := 0
267 teamGuard = func(ctx context.Context, authorize func(roster.State) error, write func() error) error {
268 writes++
269 if writes == 2 {
270 return f.lapsingGuard(ctx, authorize, write)
271 }
272 return teammode.Guard(ctx, authorize, write)
273 }
274 before := func() int64 {
275 var n int64
276 f.app.db.G.Model(&Event{}).Count(&n)
277 return n
278 }
279 n := before()
280 got := w.importFile("BEGIN:VCALENDAR\r\n" +
281 "BEGIN:VEVENT\r\nUID:a\r\nSUMMARY:First\r\nDTSTART;TZID=UTC:20270111T100000\r\nDTEND;TZID=UTC:20270111T110000\r\nEND:VEVENT\r\n" +
282 "BEGIN:VEVENT\r\nUID:b\r\nSUMMARY:Second\r\nDTSTART;TZID=UTC:20270112T100000\r\nDTEND;TZID=UTC:20270112T110000\r\nEND:VEVENT\r\n" +
283 "END:VCALENDAR\r\n")
284 retryable(t, "an import stopped part-way", got)
285 if body := got.Body.String(); !strings.Contains(body, "1 event was imported") || !strings.Contains(body, "add those a second time") {
286 t.Fatal("the stopped import does not say what landed and what a retry does")
287 }
288 if before() != n+1 {
289 t.Fatalf("events %d → %d, want the one before the lapse", n, before())
290 }
291}
292