Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming. Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
216 lines
6.8 KiB
Go
216 lines
6.8 KiB
Go
package server
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/xml"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"pageswiki/internal/calendar"
|
|
"path"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type calendarAuthTransport struct {
|
|
base http.RoundTripper
|
|
origin, user, password string
|
|
}
|
|
|
|
func (t calendarAuthTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
|
origin, e := url.Parse(t.origin)
|
|
if e != nil || !strings.EqualFold(origin.Host, r.URL.Host) || origin.Scheme != r.URL.Scheme {
|
|
return nil, errors.New("calendar credential origin mismatch")
|
|
}
|
|
clone := r.Clone(r.Context())
|
|
clone.SetBasicAuth(t.user, t.password)
|
|
return t.base.RoundTrip(clone)
|
|
}
|
|
|
|
type remoteCalendarObject struct{ href, etag, data string }
|
|
|
|
func remoteCalendarReport(ctx context.Context, client *http.Client, address, body string) ([]remoteCalendarObject, error) {
|
|
req, e := http.NewRequestWithContext(ctx, "REPORT", address, strings.NewReader(body))
|
|
if e != nil {
|
|
return nil, errors.New("invalid CalDAV URL")
|
|
}
|
|
req.Header.Set("Content-Type", "application/xml; charset=utf-8")
|
|
req.Header.Set("Depth", "1")
|
|
response, e := client.Do(req)
|
|
if e != nil {
|
|
return nil, calendarSourceRequestError(e)
|
|
}
|
|
defer response.Body.Close()
|
|
if response.StatusCode != 207 {
|
|
return nil, errors.New("external CalDAV REPORT returned " + http.StatusText(response.StatusCode))
|
|
}
|
|
b, e := io.ReadAll(io.LimitReader(response.Body, calendar.MaxFeed+1))
|
|
if e != nil || len(b) > calendar.MaxFeed {
|
|
return nil, calendar.ErrLimit
|
|
}
|
|
dec := xml.NewDecoder(bytes.NewReader(b))
|
|
depth, count := 0, 0
|
|
for {
|
|
token, e := dec.Token()
|
|
if e == io.EOF {
|
|
break
|
|
}
|
|
if e != nil {
|
|
return nil, errors.New("invalid CalDAV XML")
|
|
}
|
|
switch token.(type) {
|
|
case xml.Directive:
|
|
return nil, errors.New("CalDAV DTD rejected")
|
|
case xml.StartElement:
|
|
depth++
|
|
count++
|
|
if depth > 16 || count > 100000 {
|
|
return nil, calendar.ErrLimit
|
|
}
|
|
case xml.EndElement:
|
|
depth--
|
|
}
|
|
}
|
|
var root davNode
|
|
if xml.Unmarshal(b, &root) != nil || root.XMLName.Space != davNS || root.XMLName.Local != "multistatus" {
|
|
return nil, errors.New("invalid CalDAV multistatus")
|
|
}
|
|
origin, _ := url.Parse(address)
|
|
prefix := strings.TrimSuffix(path.Clean(origin.Path), "/") + "/"
|
|
seen := map[string]bool{}
|
|
out := []remoteCalendarObject{}
|
|
for _, row := range root.Children {
|
|
if row.XMLName.Space != davNS || row.XMLName.Local != "response" {
|
|
return nil, errors.New("unsupported CalDAV report response")
|
|
}
|
|
href := row.child(davNS, "href")
|
|
if href == nil {
|
|
return nil, errors.New("CalDAV href missing")
|
|
}
|
|
u, e := url.Parse(strings.TrimSpace(href.Text))
|
|
if e != nil {
|
|
return nil, errors.New("invalid CalDAV href")
|
|
}
|
|
u = origin.ResolveReference(u)
|
|
if !strings.EqualFold(u.Host, origin.Host) || u.Scheme != origin.Scheme || u.User != nil || u.RawQuery != "" || u.Fragment != "" || !strings.HasPrefix(path.Clean(u.Path), prefix) {
|
|
return nil, errors.New("CalDAV href outside collection")
|
|
}
|
|
key := u.EscapedPath()
|
|
if seen[key] {
|
|
return nil, errors.New("duplicate CalDAV href")
|
|
}
|
|
seen[key] = true
|
|
item := remoteCalendarObject{href: key}
|
|
for _, ps := range row.Children {
|
|
if ps.XMLName.Space == davNS && ps.XMLName.Local == "status" {
|
|
return nil, errors.New("incomplete CalDAV report")
|
|
}
|
|
if ps.XMLName.Space != davNS || ps.XMLName.Local != "propstat" {
|
|
continue
|
|
}
|
|
status := ps.child(davNS, "status")
|
|
props := ps.child(davNS, "prop")
|
|
if status == nil || props == nil || !strings.Contains(status.Text, " 200 ") {
|
|
return nil, errors.New("CalDAV property unavailable")
|
|
}
|
|
if tag := props.child(davNS, "getetag"); tag != nil {
|
|
item.etag = tag.Text
|
|
}
|
|
if data := props.child(calNS, "calendar-data"); data != nil {
|
|
item.data = data.Text
|
|
}
|
|
}
|
|
if item.etag == "" {
|
|
return nil, errors.New("CalDAV ETag missing")
|
|
}
|
|
out = append(out, item)
|
|
if len(out) > 5000 {
|
|
return nil, calendar.ErrLimit
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// Materialize a bounded read-only window: 90 days back, 275 days forward.
|
|
// REPORT fetches validators; calendar-multiget retrieves only changed resources.
|
|
func fetchCalDAVSource(ctx context.Context, client *http.Client, repo *calendar.Repository, domain string, c calendar.Calendar) ([]calendar.Event, map[string]calendar.RemoteResource, error) {
|
|
start := time.Now().UTC().Truncate(24*time.Hour).AddDate(0, 0, -90)
|
|
end := start.AddDate(0, 0, 365)
|
|
query := `<c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav"><d:prop><d:getetag/></d:prop><c:filter><c:comp-filter name="VCALENDAR"><c:comp-filter name="VEVENT"><c:time-range start="` + start.Format("20060102T150405Z") + `" end="` + end.Format("20060102T150405Z") + `"/></c:comp-filter></c:comp-filter></c:filter></c:calendar-query>`
|
|
rows, e := remoteCalendarReport(ctx, client, c.Source.URL, query)
|
|
if e != nil {
|
|
return nil, nil, e
|
|
}
|
|
result := []calendar.Event{}
|
|
resources := map[string]calendar.RemoteResource{}
|
|
missing := []remoteCalendarObject{}
|
|
uids := map[string]bool{}
|
|
totalBytes := 0
|
|
add := func(row remoteCalendarObject, event calendar.Event) error {
|
|
totalBytes += len(event.Data)
|
|
if totalBytes > calendar.MaxFeed {
|
|
return calendar.ErrLimit
|
|
}
|
|
if uids[event.UID] {
|
|
return errors.New("CalDAV contains duplicate UID or recurrence exceptions")
|
|
}
|
|
uids[event.UID] = true
|
|
result = append(result, event)
|
|
resources[row.href] = calendar.RemoteResource{UID: event.UID, ETag: row.etag}
|
|
return nil
|
|
}
|
|
for _, row := range rows {
|
|
old, ok := c.Source.Resources[row.href]
|
|
if ok && old.ETag == row.etag {
|
|
event, e := repo.Event(ctx, domain, c.ID, c.Owner, old.UID)
|
|
if e == nil {
|
|
if e = add(row, event); e != nil {
|
|
return nil, nil, e
|
|
}
|
|
continue
|
|
}
|
|
if !errors.Is(e, calendar.ErrMissing) {
|
|
return nil, nil, e
|
|
}
|
|
}
|
|
missing = append(missing, row)
|
|
}
|
|
for offset := 0; offset < len(missing); offset += 100 {
|
|
limit := offset + 100
|
|
if limit > len(missing) {
|
|
limit = len(missing)
|
|
}
|
|
wanted := map[string]string{}
|
|
var body strings.Builder
|
|
body.WriteString(`<c:calendar-multiget xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav"><d:prop><d:getetag/><c:calendar-data/></d:prop>`)
|
|
for _, row := range missing[offset:limit] {
|
|
wanted[row.href] = row.etag
|
|
body.WriteString("<d:href>" + xmlText(row.href) + "</d:href>")
|
|
}
|
|
body.WriteString("</c:calendar-multiget>")
|
|
batch, e := remoteCalendarReport(ctx, client, c.Source.URL, body.String())
|
|
if e != nil {
|
|
return nil, nil, e
|
|
}
|
|
if len(batch) != len(wanted) {
|
|
return nil, nil, errors.New("incomplete CalDAV multiget")
|
|
}
|
|
for _, row := range batch {
|
|
tag, ok := wanted[row.href]
|
|
if !ok || tag != row.etag {
|
|
return nil, nil, errors.New("CalDAV changed during synchronization; retry required")
|
|
}
|
|
event, e := calendar.Parse(row.data)
|
|
if e != nil {
|
|
return nil, nil, e
|
|
}
|
|
if e = add(row, event); e != nil {
|
|
return nil, nil, e
|
|
}
|
|
}
|
|
}
|
|
return result, resources, nil
|
|
}
|