// SPDX-License-Identifier: AGPL-3.0-or-later package calendar import ( "context" "net/http" "net/http/httptest" "net/url" "strings" "testing" "time" "docwell/server/internal/access" "docwell/server/internal/oauth" ) func fakeGoogle(t *testing.T) *httptest.Server { t.Helper() mux := http.NewServeMux() mux.HandleFunc("POST /token", func(w http.ResponseWriter, r *http.Request) { _ = r.ParseForm() if r.Form.Get("refresh_token") != "refresh-1" { w.WriteHeader(http.StatusBadRequest) _, _ = w.Write([]byte(`{"error":"invalid_grant"}`)) return } _, _ = w.Write([]byte(`{"access_token":"access-1","expires_in":3600}`)) }) auth := func(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Authorization") != "Bearer access-1" { w.WriteHeader(http.StatusUnauthorized) return } next(w, r) } } mux.HandleFunc("GET /calendar/v3/users/me/calendarList", auth(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(`{"items":[{"id":"me@example.com","primary":true},{"id":"team@group","selected":true},{"id":"hidden@group","selected":false}]}`)) })) mux.HandleFunc("GET /calendar/v3/calendars/{id}/events", auth(func(w http.ResponseWriter, r *http.Request) { if r.URL.Query().Get("singleEvents") != "true" { t.Error("events asked without singleEvents") } switch r.PathValue("id") { case "me@example.com": if r.URL.Query().Get("pageToken") == "" { _, _ = w.Write([]byte(`{"items":[{"id":"e1","summary":"Lunch","start":{"dateTime":"2026-11-16T12:00:00+01:00"},"end":{"dateTime":"2026-11-16T13:00:00+01:00"},"htmlLink":"https://calendar.google.com/e1"},` + `{"id":"e2","status":"cancelled","start":{"date":"2026-11-16"},"end":{"date":"2026-11-17"}}],"nextPageToken":"p2"}`)) return } _, _ = w.Write([]byte(`{"items":[{"id":"e3","summary":"Trip","start":{"date":"2026-11-20"},"end":{"date":"2026-11-23"}}]}`)) case "team@group": _, _ = w.Write([]byte(`{"items":[{"id":"t1","summary":"Retro","location":"Room 1","start":{"dateTime":"2026-11-17T09:00:00Z"},"end":{"dateTime":"2026-11-17T10:00:00Z"}}]}`)) default: t.Errorf("read a hidden calendar: %s", r.PathValue("id")) } })) return httptest.NewServer(mux) } func TestGoogleItems(t *testing.T) { g := fakeGoogle(t) defer g.Close() s := New(nil, Options{ Secret: "x", Client: g.Client(), GoogleAPI: g.URL, Google: oauth.Provider{Name: "google", ClientID: "c", ClientSecret: "s", AuthURL: g.URL + "/auth", TokenURL: g.URL + "/token"}, }) from, to := window(time.Date(2026, 11, 16, 0, 0, 0, 0, time.UTC)) items, n, err := s.googleItems(context.Background(), record{Kind: KindGoogle, Secret: s.seal("refresh-1")}, from, to) if err != nil { t.Fatal(err) } if n != 3 || len(items) != 3 { t.Fatalf("items = %+v", items) } byTitle := map[string]item{} for _, it := range items { byTitle[it.title] = it } if l := byTitle["Lunch"]; l.start != time.Date(2026, 11, 16, 11, 0, 0, 0, time.UTC) || l.allDay || l.url == "" { t.Errorf("lunch = %+v", l) } if tr := byTitle["Trip"]; !tr.allDay || tr.start.Format(time.DateOnly) != "2026-11-20" || tr.end.Format(time.DateOnly) != "2026-11-23" { t.Errorf("trip = %+v", tr) } if byTitle["Retro"].location != "Room 1" { t.Errorf("retro = %+v", byTitle["Retro"]) } if _, _, err := s.googleItems(context.Background(), record{Kind: KindGoogle, Secret: s.seal("revoked")}, from, to); err == nil || !strings.Contains(err.Error(), "revoked") { t.Errorf("revoked token: %v", err) } } func TestGoogleConnectURL(t *testing.T) { s := New(nil, Options{Secret: "x", PublicURL: "https://api.example.com"}) if _, err := s.GoogleConnectURL(context.Background(), access.Caller{ID: "u1"}); err == nil { t.Fatal("connect allowed without a Google app") } if s.GoogleEnabled() { t.Fatal("enabled without a Google app") } s.google = oauth.Google("client", "secret") // GoogleConnectURL needs the account list from PocketBase; check the URL parts directly. u, _ := url.Parse(s.google.AuthCodeURL(s.states.Sign(oauth.State{User: "u1", Purpose: PurposeGoogle}), s.googleRedirect(), googleScopes)) q := u.Query() if q.Get("redirect_uri") != "https://api.example.com/api/v1/oauth/google/callback" || !strings.Contains(q.Get("scope"), "calendar.readonly") { t.Errorf("auth url = %s", u) } if st, err := s.states.Verify(q.Get("state"), PurposeGoogle); err != nil || st.User != "u1" { t.Errorf("state = %+v, %v", st, err) } }