// SPDX-License-Identifier: AGPL-3.0-or-later package calendar import ( "context" "encoding/json" "encoding/xml" "errors" "fmt" "io" "net/http" "net/http/httptest" "regexp" "strconv" "strings" "sync" "testing" "time" "docwell/server/internal/access" "docwell/server/internal/apperr" "docwell/server/internal/oauth" "docwell/server/internal/store/pocketbase" ) // fakeStore is an in-memory PocketBase for the two calendar collections. // Filters are read as "field = 'value'" pairs joined by &&; anything else // in a filter is ignored. type fakeStore struct { mu sync.Mutex next int rows map[string]map[string]map[string]any // collection -> id -> record } var filterPair = regexp.MustCompile(`(\w+) = '([^']*)'`) func newFakeStore(t *testing.T) (*fakeStore, *pocketbase.Client) { t.Helper() f := &fakeStore{rows: map[string]map[string]map[string]any{}} mux := http.NewServeMux() reply := func(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(v) } mux.HandleFunc("POST /api/collections/_superusers/auth-with-password", func(w http.ResponseWriter, r *http.Request) { reply(w, 200, map[string]string{"token": "su"}) }) mux.HandleFunc("GET /api/collections/{c}/records", func(w http.ResponseWriter, r *http.Request) { f.mu.Lock() defer f.mu.Unlock() want := map[string]string{} filter := r.URL.Query().Get("filter") if !strings.Contains(filter, "||") { for _, m := range filterPair.FindAllStringSubmatch(filter, -1) { want[m[1]] = m[2] } } else if m := filterPair.FindStringSubmatch(filter); m != nil && m[1] == "user" { want["user"] = m[2] } items := []map[string]any{} for _, rec := range f.rows[r.PathValue("c")] { ok := true for k, v := range want { ok = ok && fmt.Sprint(rec[k]) == v } if ok { items = append(items, rec) } } reply(w, 200, map[string]any{"page": 1, "perPage": len(items), "totalPages": 1, "totalItems": len(items), "items": items}) }) mux.HandleFunc("POST /api/collections/{c}/records", func(w http.ResponseWriter, r *http.Request) { var body map[string]any _ = json.NewDecoder(r.Body).Decode(&body) reply(w, 200, f.put(r.PathValue("c"), "", body)) }) mux.HandleFunc("GET /api/collections/{c}/records/{id}", func(w http.ResponseWriter, r *http.Request) { if rec := f.get(r.PathValue("c"), r.PathValue("id")); rec != nil { reply(w, 200, rec) return } reply(w, 404, map[string]any{"status": 404, "message": "not found"}) }) mux.HandleFunc("PATCH /api/collections/{c}/records/{id}", func(w http.ResponseWriter, r *http.Request) { var body map[string]any _ = json.NewDecoder(r.Body).Decode(&body) reply(w, 200, f.put(r.PathValue("c"), r.PathValue("id"), body)) }) mux.HandleFunc("DELETE /api/collections/{c}/records/{id}", func(w http.ResponseWriter, r *http.Request) { f.mu.Lock() delete(f.rows[r.PathValue("c")], r.PathValue("id")) f.mu.Unlock() w.WriteHeader(204) }) srv := httptest.NewServer(mux) t.Cleanup(srv.Close) return f, pocketbase.New(srv.URL, "su@test", "pw") } func (f *fakeStore) put(c, id string, body map[string]any) map[string]any { f.mu.Lock() defer f.mu.Unlock() if f.rows[c] == nil { f.rows[c] = map[string]map[string]any{} } rec := f.rows[c][id] if rec == nil { f.next++ id = fmt.Sprintf("r%014d", f.next) rec = map[string]any{"id": id} f.rows[c][id] = rec } for k, v := range body { rec[k] = v } return rec } func (f *fakeStore) get(c, id string) map[string]any { f.mu.Lock() defer f.mu.Unlock() return f.rows[c][id] } func (f *fakeStore) count(c string) int { f.mu.Lock() defer f.mu.Unlock() return len(f.rows[c]) } // fakeDAV is a CalDAV calendar at /cal/ that keeps objects with ETags and // honours If-Match and If-None-Match. type fakeDAV struct { mu sync.Mutex objects map[string]string // path -> iCalendar etags map[string]int puts []string // "path If-Match If-None-Match" } func newFakeDAV(t *testing.T) (*fakeDAV, *httptest.Server) { d := &fakeDAV{objects: map[string]string{}, etags: map[string]int{}} srv := httptest.NewServer(http.HandlerFunc(d.serve)) t.Cleanup(srv.Close) return d, srv } func (d *fakeDAV) set(path, data string) { d.mu.Lock() defer d.mu.Unlock() data = strings.ReplaceAll(strings.TrimSpace(data), "\r\n", "\n") d.objects[path] = strings.ReplaceAll(data, "\n", "\r\n") + "\r\n" d.etags[path]++ } func (d *fakeDAV) etag(path string) string { return `"` + strconv.Itoa(d.etags[path]) + `"` } func (d *fakeDAV) serve(w http.ResponseWriter, r *http.Request) { d.mu.Lock() defer d.mu.Unlock() if u, p, ok := r.BasicAuth(); !ok || u != "ann" || p != "pw" { w.WriteHeader(http.StatusUnauthorized) return } path := r.URL.Path _, exists := d.objects[path] switch r.Method { case "REPORT": var b strings.Builder b.WriteString(``) for p, data := range d.objects { var esc strings.Builder _ = xml.EscapeText(&esc, []byte(data)) fmt.Fprintf(&b, `%s%s%sHTTP/1.1 200 OK`, p, strings.ReplaceAll(d.etag(p), `"`, """), esc.String()) } b.WriteString(``) w.Header().Set("Content-Type", "application/xml; charset=utf-8") w.WriteHeader(http.StatusMultiStatus) _, _ = io.WriteString(w, b.String()) case http.MethodGet: if !exists { http.NotFound(w, r) return } w.Header().Set("Content-Type", "text/calendar") w.Header().Set("ETag", d.etag(path)) _, _ = io.WriteString(w, d.objects[path]) case http.MethodPut: d.puts = append(d.puts, path+" "+r.Header.Get("If-Match")+" "+r.Header.Get("If-None-Match")) if m := r.Header.Get("If-Match"); m != "" && (!exists || m != d.etag(path)) { w.WriteHeader(http.StatusPreconditionFailed) return } if r.Header.Get("If-None-Match") == "*" && exists { w.WriteHeader(http.StatusPreconditionFailed) return } data, _ := io.ReadAll(r.Body) d.objects[path] = string(data) d.etags[path]++ w.Header().Set("ETag", d.etag(path)) w.WriteHeader(http.StatusCreated) case http.MethodDelete: if !exists { http.NotFound(w, r) return } if m := r.Header.Get("If-Match"); m != "" && m != d.etag(path) { w.WriteHeader(http.StatusPreconditionFailed) return } delete(d.objects, path) w.WriteHeader(http.StatusNoContent) default: w.WriteHeader(http.StatusMethodNotAllowed) } } func eventByTitle(t *testing.T, events []Event, title string) Event { t.Helper() for _, e := range events { if e.Title == title { return e } } t.Fatalf("no event %q in %+v", title, events) return Event{} } func isKind(err error, kind apperr.Kind) bool { e, ok := apperr.As(err) return ok && e.Kind == kind } func ptr[T any](v T) *T { return &v } func TestCalDAVWrites(t *testing.T) { store, pb := newFakeStore(t) dav, srv := newFakeDAV(t) day := time.Now().UTC().AddDate(0, 0, 3).Format("20060102") dav.set("/cal/single.ics", `BEGIN:VCALENDAR VERSION:2.0 PRODID:-//test//EN BEGIN:VEVENT UID:single-1 DTSTAMP:20260101T000000Z DTSTART;TZID=Europe/Warsaw:`+day+`T090000 DTEND;TZID=Europe/Warsaw:`+day+`T100000 SUMMARY:Planning X-KEEP:yes END:VEVENT END:VCALENDAR`) dav.set("/cal/weekly.ics", `BEGIN:VCALENDAR VERSION:2.0 PRODID:-//test//EN BEGIN:VEVENT UID:weekly-1 DTSTAMP:20260101T000000Z DTSTART:`+day+`T120000Z DTEND:`+day+`T123000Z RRULE:FREQ=WEEKLY;COUNT=3 SUMMARY:Standup END:VEVENT END:VCALENDAR`) s := New(pb, Options{Secret: "x", Client: srv.Client()}) ctx := context.Background() c := access.Caller{ID: "u1"} acc := store.put("calendar_accounts", "", map[string]any{ "user": "u1", "name": "Work", "kind": KindCalDAV, "url": srv.URL + "/cal/", "username": "ann", "secret": s.seal("pw"), "color": "blue", "enabled": true, }) rec, err := s.get(ctx, c, acc["id"].(string)) if err != nil { t.Fatal(err) } if err := s.Sync(ctx, rec); err != nil { t.Fatal(err) } if rec, _ = s.get(ctx, c, rec.ID); !rec.CanWrite || rec.target() != "/cal/" { t.Fatalf("after sync: canWrite %v, targets %+v", rec.CanWrite, rec.Targets) } date := time.Now().UTC().AddDate(0, 0, 3).Format(time.DateOnly) events, err := s.Events(ctx, c, date, date, "Europe/Warsaw") if err != nil { t.Fatal(err) } planning, standup := eventByTitle(t, events, "Planning"), eventByTitle(t, events, "Standup") if !planning.Editable || standup.Editable { t.Fatalf("editable: planning %v, standup %v", planning.Editable, standup.Editable) } // A change goes to the server with the ETag the sync read, and keeps // what Docwell does not know about (X-KEEP). got, err := s.UpdateEvent(ctx, c, planning.ID, EventInput{Title: ptr("Planning (moved)"), Location: ptr("Room 2")}) if err != nil { t.Fatal(err) } if got.Title != "Planning (moved)" || got.Location != "Room 2" || got.Start != planning.Start { t.Fatalf("updated = %+v", got) } if last := dav.puts[len(dav.puts)-1]; last != `/cal/single.ics "1" ` { t.Fatalf("put = %q", last) } body := dav.objects["/cal/single.ics"] if !strings.Contains(body, "SUMMARY:Planning (moved)") || !strings.Contains(body, "X-KEEP:yes") || !strings.Contains(body, "SEQUENCE:1") { t.Fatalf("stored object:\n%s", body) } // Moving it changes its id; the old one is gone. newStart := time.Now().UTC().AddDate(0, 0, 3).Truncate(time.Hour).Add(2 * time.Hour) moved, err := s.UpdateEvent(ctx, c, got.ID, EventInput{Start: ptr(newStart.Format(time.RFC3339))}) if err != nil { t.Fatal(err) } if moved.ID == got.ID || moved.Start != newStart.Format(time.RFC3339) || moved.End != newStart.Add(time.Hour).Format(time.RFC3339) { t.Fatalf("moved = %+v (was %+v)", moved, got) } // Changed elsewhere since: refused, nothing overwritten. dav.set("/cal/single.ics", strings.ReplaceAll(dav.objects["/cal/single.ics"], "Planning (moved)", "Changed on the phone")) if _, err := s.UpdateEvent(ctx, c, moved.ID, EventInput{Title: ptr("Mine")}); !isKind(err, apperr.KindConflict) { t.Fatalf("stale update: %v", err) } if !strings.Contains(dav.objects["/cal/single.ics"], "Changed on the phone") { t.Fatal("a stale change overwrote the calendar") } if err := s.DeleteEvent(ctx, c, moved.ID); !isKind(err, apperr.KindConflict) { t.Fatalf("stale delete: %v", err) } // Repeating events are left alone. if _, err := s.UpdateEvent(ctx, c, standup.ID, EventInput{Title: ptr("x")}); !isKind(err, apperr.KindInvalid) { t.Fatalf("repeating update: %v", err) } // New events: all-day, into the account's calendar, never over an existing object. before := store.count("calendar_events") added, err := s.CreateEvent(ctx, c, EventInput{Calendar: ptr(rec.ID), Title: ptr("Holiday"), Start: ptr(date), AllDay: ptr(true)}) if err != nil { t.Fatal(err) } if !added.AllDay || added.Start != date || !added.Editable || store.count("calendar_events") != before+1 { t.Fatalf("added = %+v", added) } var path string for p, data := range dav.objects { if strings.Contains(data, "SUMMARY:Holiday") { path = p if !strings.Contains(data, "DTSTART;VALUE=DATE:") { t.Errorf("all-day start not a date:\n%s", data) } } } if !strings.HasPrefix(path, "/cal/") || !strings.HasSuffix(path, "@docwell.ics") { t.Fatalf("new object at %q", path) } if last := dav.puts[len(dav.puts)-1]; !strings.HasSuffix(last, " *") { t.Fatalf("create put = %q", last) } if err := s.DeleteEvent(ctx, c, added.ID); err != nil { t.Fatal(err) } if _, ok := dav.objects[path]; ok || store.count("calendar_events") != before { t.Fatal("deleted event still there") } // Input checks. for name, in := range map[string]EventInput{ "no title": {Calendar: ptr(rec.ID), Title: ptr(" "), Start: ptr(date), AllDay: ptr(true)}, "bad start": {Calendar: ptr(rec.ID), Title: ptr("x"), Start: ptr("tomorrow")}, "end first": {Calendar: ptr(rec.ID), Title: ptr("x"), Start: ptr("2026-11-17T10:00:00Z"), End: ptr("2026-11-17T09:00:00Z")}, "too long": {Calendar: ptr(rec.ID), Title: ptr("x"), Start: ptr("2026-11-17"), End: ptr("2028-11-17"), AllDay: ptr(true)}, "not a target": {Calendar: ptr("nope"), Title: ptr("x"), Start: ptr("2026-11-17"), AllDay: ptr(true)}, } { if _, err := s.CreateEvent(ctx, c, in); err == nil { t.Errorf("%s: accepted", name) } } // Someone else's event. if err := s.DeleteEvent(ctx, access.Caller{ID: "u2"}, standup.ID); !isKind(err, apperr.KindNotFound) { t.Errorf("other user: %v", err) } } func TestGoogleWrites(t *testing.T) { store, pb := newFakeStore(t) var mu sync.Mutex etag := `"g1"` var calls []string mux := http.NewServeMux() mux.HandleFunc("POST /token", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(`{"access_token":"access-1","expires_in":3600}`)) }) mux.HandleFunc("POST /calendar/v3/calendars/{cal}/events", func(w http.ResponseWriter, r *http.Request) { var in map[string]any _ = json.NewDecoder(r.Body).Decode(&in) mu.Lock() calls = append(calls, "POST "+r.PathValue("cal")) mu.Unlock() out := map[string]any{"id": "new1", "etag": `"n1"`, "summary": in["summary"], "location": in["location"], "start": in["start"], "end": in["end"], "htmlLink": "https://calendar.google.com/new1"} _ = json.NewEncoder(w).Encode(out) }) mux.HandleFunc("PATCH /calendar/v3/calendars/{cal}/events/{id}", func(w http.ResponseWriter, r *http.Request) { mu.Lock() defer mu.Unlock() calls = append(calls, "PATCH "+r.PathValue("id")+" "+r.Header.Get("If-Match")) if r.Header.Get("If-Match") != etag { w.WriteHeader(http.StatusPreconditionFailed) return } var in map[string]any _ = json.NewDecoder(r.Body).Decode(&in) etag = `"g2"` _ = json.NewEncoder(w).Encode(map[string]any{"id": r.PathValue("id"), "etag": etag, "summary": in["summary"], "start": in["start"], "end": in["end"]}) }) mux.HandleFunc("DELETE /calendar/v3/calendars/{cal}/events/{id}", func(w http.ResponseWriter, r *http.Request) { mu.Lock() defer mu.Unlock() calls = append(calls, "DELETE "+r.PathValue("id")+" "+r.Header.Get("If-Match")) w.WriteHeader(http.StatusNoContent) }) g := httptest.NewServer(mux) defer g.Close() s := New(pb, Options{ Secret: "x", Client: g.Client(), GoogleAPI: g.URL, Google: oauth.Provider{Name: "google", ClientID: "c", ClientSecret: "s", TokenURL: g.URL + "/token"}, }) ctx := context.Background() c := access.Caller{ID: "u1"} acc := store.put("calendar_accounts", "", map[string]any{ "user": "u1", "name": "Google", "kind": KindGoogle, "url": "https://calendar.google.com", "username": "me@example.com", "secret": s.seal("refresh-1"), "color": "green", "enabled": true, "can_write": false, "targets": []Target{{ID: "me@example.com", Name: "Me"}}, }) id := acc["id"].(string) // Connected before writing existed: the person is asked to reconnect. _, err := s.CreateEvent(ctx, c, EventInput{Calendar: ptr(id), Title: ptr("Lunch"), Start: ptr("2026-11-20T12:00:00Z")}) if err == nil || !strings.Contains(err.Error(), "Connect the Google account again") { t.Fatalf("read-only account: %v", err) } if v, _ := s.List(ctx, c); !v[0].NeedsReconnect || v[0].CanWrite { t.Fatalf("account view = %+v", v[0]) } store.put("calendar_accounts", id, map[string]any{"can_write": true}) added, err := s.CreateEvent(ctx, c, EventInput{Calendar: ptr(id), Title: ptr("Lunch"), Start: ptr("2026-11-20T12:00:00Z")}) if err != nil { t.Fatal(err) } if added.End != "2026-11-20T13:00:00Z" || added.URL == "" || !added.Editable { t.Fatalf("added = %+v", added) } // Pretend the sync read the event with ETag g1. for _, rec := range store.rows["calendar_events"] { rec["etag"] = `"g1"` } changed, err := s.UpdateEvent(ctx, c, added.ID, EventInput{Title: ptr("Long lunch")}) if err != nil { t.Fatal(err) } if changed.Title != "Long lunch" { t.Fatalf("changed = %+v", changed) } // The stored ETag is now g2; Google moving on to g3 makes the next change stale. mu.Lock() etag = `"g3"` mu.Unlock() if _, err := s.UpdateEvent(ctx, c, changed.ID, EventInput{Title: ptr("x")}); !isKind(err, apperr.KindConflict) { t.Fatalf("stale: %v", err) } if err := s.DeleteEvent(ctx, c, changed.ID); err != nil { t.Fatal(err) } want := []string{"POST me@example.com", `PATCH new1 "g1"`, `PATCH new1 "g2"`, `DELETE new1 "g2"`} if strings.Join(calls, "|") != strings.Join(want, "|") { t.Fatalf("calls = %q\nwant %q", calls, want) } } func TestGrantsEvents(t *testing.T) { if !grantsEvents("openid email https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/calendar.events") { t.Error("events scope not seen") } if grantsEvents("openid https://www.googleapis.com/auth/calendar.readonly") { t.Error("read-only seen as writable") } } func TestApplyKeepsLength(t *testing.T) { start := time.Date(2026, 11, 17, 9, 0, 0, 0, time.UTC) it := item{title: "x", start: start, end: start.Add(90 * time.Minute)} if err := (EventInput{Start: ptr("2026-11-18T09:00:00Z")}).apply(&it); err != nil { t.Fatal(err) } if it.end.Sub(it.start) != 90*time.Minute { t.Errorf("length = %v", it.end.Sub(it.start)) } if err := (EventInput{AllDay: ptr(true)}).apply(&it); err == nil { t.Error("switched to all-day without a date") } if err := (EventInput{AllDay: ptr(true), Start: ptr("2026-11-18")}).apply(&it); err != nil || it.end.Sub(it.start) != 24*time.Hour { t.Errorf("all-day = %+v, %v", it, err) } if !errors.Is(errStale, errStale) { t.Fatal() } }