package http import ( "context" "fmt" "io" "net/http" "net/http/httptest" "strings" "sync" "testing" "time" "gitea.federated.computer/Federated_Computer/brain/internal/db" ) // fakeCaldav is a mutable RFC 4791 server for integration tests: a home at // root (default /home; the unified Nextcloud fake re-roots it) with "work" // and "personal" calendars whose events a test can add/remove/change to // exercise the full reconcile. Auth erwin/s3cret. type fakeCaldav struct { mu sync.Mutex root string events map[string]cdEvent // href -> event srv *httptest.Server extra map[string]cdEvent // for the personal calendar } type cdEvent struct { etag, uid, summary string start time.Time } func newFakeCaldav(t *testing.T) *fakeCaldav { t.Helper() f := &fakeCaldav{root: "/home", events: map[string]cdEvent{}, extra: map[string]cdEvent{}} f.srv = httptest.NewServer(http.HandlerFunc(f.serve)) t.Cleanup(f.srv.Close) return f } func (f *fakeCaldav) add(cal, href, etag, uid, summary string, start time.Time) { f.mu.Lock() defer f.mu.Unlock() if cal == "personal" { f.extra[href] = cdEvent{etag, uid, summary, start} return } f.events[href] = cdEvent{etag, uid, summary, start} } func (f *fakeCaldav) remove(href string) { f.mu.Lock() defer f.mu.Unlock() delete(f.events, href) } func (f *fakeCaldav) serve(w http.ResponseWriter, r *http.Request) { u, p, ok := r.BasicAuth() if !ok || u != "erwin" || p != "s3cret" { w.Header().Set("WWW-Authenticate", `Basic realm="x"`) http.Error(w, "no", http.StatusUnauthorized) return } f.mu.Lock() defer f.mu.Unlock() switch r.Method { case "PROPFIND": w.Header().Set("Content-Type", "application/xml") w.WriteHeader(http.StatusMultiStatus) if r.Header.Get("Depth") == "0" { fmt.Fprintf(w, `%s/`, f.root) return } fmt.Fprintf(w, ` %s/ %s/work/Work %s/personal/Personal `, f.root, f.root, f.root) case "REPORT": key := strings.Trim(strings.TrimPrefix(r.URL.Path, f.root+"/"), "/") collection := f.events if key == "personal" { collection = f.extra } w.Header().Set("Content-Type", "application/xml") w.WriteHeader(http.StatusMultiStatus) var b strings.Builder b.WriteString(``) fmt.Fprintf(&b, `%s/%s/"cal"`, f.root, key) for href, ev := range collection { ics := "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nUID:" + ev.uid + "\r\nSUMMARY:" + ev.summary + "\r\nDTSTART:" + ev.start.UTC().Format("20060102T150405") + "Z\r\nEND:VEVENT\r\nEND:VCALENDAR" fmt.Fprintf(&b, `%s/%s/%s"%s"%s`, f.root, key, strings.ReplaceAll(href, " ", "%20"), ev.etag, xmlEsc(ics)) } b.WriteString(``) io.WriteString(w, b.String()) default: http.Error(w, "no", http.StatusMethodNotAllowed) } } func xmlEsc(s string) string { return strings.NewReplacer("&", "&", "<", "<", ">", ">").Replace(s) } func calDavBody(url string) map[string]any { return map[string]any{"name": "My calendars", "url": url + "/home", "username": "erwin", "password": "s3cret"} } func TestCalDavLifecycle(t *testing.T) { srv, _ := testServerDB(t) fake := newFakeCaldav(t) now := time.Now().UTC() fake.add("work", "standup.ics", "S1", "uid-standup", "Daily standup", now.Add(24*time.Hour)) fake.add("personal", " dentist.ics", "D1", "uid-dentist", "Dentist appointment", now.Add(48*time.Hour)) c, _ := accountClient(t, srv.URL, "cd@superbrain.test") c.request("POST", "/api/caldav/connections", map[string]any{"name": "x", "url": "ftp://h/home", "username": "erwin", "password": "s3cret"}, 400) c.request("POST", "/api/caldav/connections", map[string]any{"name": "x", "url": fake.srv.URL + "/home", "username": "", "password": "s3cret"}, 400) c.request("POST", "/api/caldav/connections", map[string]any{"name": "x", "url": fake.srv.URL + "/home", "username": "erwin"}, 400) created := c.request("POST", "/api/caldav/connections", calDavBody(fake.srv.URL), 201) id := created["id"].(string) if created["secret"] != "••••••••" { t.Fatalf("password not masked: %v", created["secret"]) } list := c.request("GET", "/api/caldav/connections", nil, 200) if list["allowed"] != true { t.Fatal("selfhosted plan must allow the caldav connector") } if n := len(list["connections"].([]any)); n != 1 { t.Fatalf("want 1 connection, got %d", n) } if r := c.request("POST", "/api/caldav/connections/"+id+"/test", map[string]any{}, 200); r["ok"] != true || len(r["calendars"].([]any)) != 2 { t.Fatalf("test discovery: %v", r) } // First sync materializes one collection PER calendar, one bookmark per event. res := c.request("POST", "/api/caldav/connections/"+id+"/sync", map[string]any{}, 200) if res["calendars"] != float64(2) || res["events"] != float64(2) || res["created"] != float64(2) { t.Fatalf("first sync: %v", res) } cols := c.getJSON("/api/collections", 200) var workCol, persCol string for _, x := range cols { switch x["name"] { case "Work": workCol = x["id"].(string) case "Personal": persCol = x["id"].(string) } } if workCol == "" || persCol == "" { t.Fatalf("expected a Work and a Personal collection, got %v", cols) } if n := len(c.getJSON("/api/collections/"+workCol+"/items?limit=50", 200)); n != 1 { t.Fatalf("want 1 work member, got %d", n) } // Bookmark carries the event's DAV .ics URL and the summary as title. items := c.getJSON("/api/collections/"+persCol+"/items?limit=50", 200) if len(items) != 1 { t.Fatalf("want 1 personal member, got %d", len(items)) } bm := items[0]["bookmark"].(map[string]any) if !strings.Contains(bm["url"].(string), "/home/personal/%20dentist.ics") || bm["title"] != "Dentist appointment" { t.Fatalf("event bookmark wrong: %v", bm) } // Idempotent re-sync. res = c.request("POST", "/api/caldav/connections/"+id+"/sync", map[string]any{}, 200) if res["created"] != float64(0) || res["kept"] != float64(2) { t.Fatalf("re-sync not idempotent: %v", res) } // Content change (new etag) refreshes the ledger only. fake.add("work", "standup.ics", "S2", "uid-standup", "Daily standup", now.Add(24*time.Hour)) if res = c.request("POST", "/api/caldav/connections/"+id+"/sync", map[string]any{}, 200); res["updated"] != float64(1) { t.Fatalf("etag change not counted: %v", res) } // New event joins the right calendar. fake.add("work", "retro.ics", "R1", "uid-retro", "Retro", now.Add(72*time.Hour)) c.request("POST", "/api/caldav/connections/"+id+"/sync", map[string]any{}, 200) if n := len(c.getJSON("/api/collections/"+workCol+"/items?limit=50", 200)); n != 2 { t.Fatalf("want 2 work members, got %d", n) } // Event disappears -> membership detaches, BOOKMARK SURVIVES. var retroBm string for _, x := range c.getJSON("/api/collections/"+workCol+"/items?limit=50", 200) { b := x["bookmark"].(map[string]any) if b["title"] == "Retro" { retroBm = b["id"].(string) } } if retroBm == "" { t.Fatal("retro member not found") } fake.remove("retro.ics") if res = c.request("POST", "/api/caldav/connections/"+id+"/sync", map[string]any{}, 200); res["removed"] != float64(1) { t.Fatalf("event removal not reconciled: %v", res) } c.request("GET", "/api/bookmarks/"+retroBm, nil, 200) // survives // Version contract + write-only password. c.request("PATCH", "/api/caldav/connections/"+id, map[string]any{"name": "R", "version": 99}, 409) c.request("PATCH", "/api/caldav/connections/"+id, map[string]any{"name": "R"}, 400) noop := c.request("PATCH", "/api/caldav/connections/"+id, map[string]any{"password": "••••••••", "version": 1}, 200) if noop["version"] != float64(1) { t.Fatalf("mask-only PATCH bumped version: %v", noop) } c.request("PATCH", "/api/caldav/connections/"+id, map[string]any{"password": "wrong", "version": 1}, 200) c.request("POST", "/api/caldav/connections/"+id+"/sync", map[string]any{}, 502) // lastError surfaced. row := c.request("GET", "/api/caldav/connections", nil, 200)["connections"].([]any)[0].(map[string]any) if row["lastError"] == nil { t.Fatal("failed sync did not surface lastError") } // calendars list present on the connection row. if _, ok := row["calendars"].([]any); !ok { t.Fatalf("connection row missing calendars array: %v", row["calendars"]) } // Owner scoping + delete keeps collections/bookmarks. bob, _ := accountClient(t, srv.URL, "calice@superbrain.test") bob.request("DELETE", "/api/caldav/connections/"+id, nil, 404) c.request("DELETE", "/api/caldav/connections/"+id, nil, 200) c.request("GET", "/api/collections/"+workCol, nil, 200) c.request("GET", "/api/bookmarks/"+retroBm, nil, 200) } // Deleting a calendar's Collection makes the next sync re-create it and // re-link its events (delete the collection, not the members). func TestCalDavCollectionRecreation(t *testing.T) { srv, _ := testServerDB(t) fake := newFakeCaldav(t) now := time.Now().UTC() fake.add("work", "a.ics", "A1", "ua", "Alpha", now.Add(24*time.Hour)) c, _ := accountClient(t, srv.URL, "cdr@superbrain.test") id := c.request("POST", "/api/caldav/connections", calDavBody(fake.srv.URL), 201)["id"].(string) c.request("POST", "/api/caldav/connections/"+id+"/sync", map[string]any{}, 200) var workCol string for _, x := range c.getJSON("/api/collections", 200) { if x["name"] == "Work" { workCol = x["id"].(string) } } c.request("DELETE", "/api/collections/"+workCol, nil, 200) c.request("POST", "/api/caldav/connections/"+id+"/sync", map[string]any{}, 200) var newCol string for _, x := range c.getJSON("/api/collections", 200) { if x["name"] == "Work" { newCol = x["id"].(string) } } if newCol == "" { t.Fatal("Work collection not re-created") } if n := len(c.getJSON("/api/collections/"+newCol+"/items?limit=50", 200)); n != 1 { t.Fatalf("re-created Work collection lost its member: %d", n) } } func TestCalDavPlanGateAndSuggestion(t *testing.T) { srv, d := testServerDB(t) t.Setenv("NEXTCLOUD_URL", "https://cloud.example") share := newFakeCaldav(t) c, uid := accountClient(t, srv.URL, "cdg@superbrain.test") var tid string if err := d.QueryRowContext(context.Background(), `SELECT "tenantId" FROM "User" WHERE id=$1`, uid).Scan(&tid); err != nil { t.Fatal(err) } id := c.request("POST", "/api/caldav/connections", calDavBody(share.srv.URL), 201)["id"].(string) // Suggestion carries the calendars DAV path. sugg := c.request("GET", "/api/caldav/connections", nil, 200)["suggestions"].([]any) if len(sugg) != 1 || sugg[0].(map[string]any)["url"] != "https://cloud.example/remote.php/dav/calendars/" { t.Fatalf("bad suggestion: %v", sugg) } repo := db.NewTenantRepo(d) if err := repo.SetEntitlement(context.Background(), tid, "connectors", "url,file,carddav"); err != nil { t.Fatal(err) } c.request("POST", "/api/caldav/connections", calDavBody(share.srv.URL), 403) list := c.request("GET", "/api/caldav/connections", nil, 200) if list["allowed"] != false { t.Fatalf("downgraded plan still allowed: %v", list["allowed"]) } c.request("POST", "/api/caldav/connections/"+id+"/sync", map[string]any{}, 403) }