Files
Andrew S Erwin 4b6a58118e Rename Go module to gitea.federated.computer/Federated_Computer/superbrain
The Gitea repository was renamed brain -> superbrain (server-side redirect
already in place; local origin updated at 0.3.5). Carry the rename through
for accurate identity, the 0.3.2 precedent: go.mod + every internal import,
the agent's outbound User-Agent contact URL, README/RUNNING clone URLs and
local notes. CHANGELOG history entries stay as written. Pure identifier
rename, no runtime behavior change; verified with build + vet + unit tests
and the full database integration suite under -race.
2026-11-24 16:02:01 -06:00

448 lines
13 KiB
Go

// Package webdav dials external WebDAV shares on behalf of users
// (Settings → WebDAV): any RFC 4918 server (Nextcloud, Synology, ...). A
// connected share materializes as a Collection whose members are bookmarks —
// one per synced file (see sync.go).
//
// House rules enforced here (identical to mcpclient/CardDAV):
// - every dial goes through internal/netguard; user-supplied hosts get NO
// trusted-range exemption, and production dials are pinned to ports
// 80/443 (tests flip INTEGRATIONS_ALLOW_PRIVATE like every suite);
// - credentials travel ONLY in an Authorization: Basic header, never in
// the URL (Go error strings include URLs and get logged);
// - redirects are NOT followed: a verified origin must not be bounced to
// another host carrying the credential;
// - the walk is bounded (directories, files, depth) so a pathological
// share cannot pin a request or the sync tick, and a truncated walk is
// reported so the caller never reconciles deletions against a partial
// listing.
package webdav
import (
"context"
"encoding/xml"
"fmt"
"io"
"net"
"net/http"
"net/url"
"path"
"strconv"
"strings"
"time"
"gitea.federated.computer/Federated_Computer/superbrain/internal/netguard"
)
// Conn is the dial-relevant projection of a stored WebDavConnection row plus
// its DECRYPTED password. Callers own the plaintext lifetime.
type Conn struct {
BaseURL string // share root, e.g. https://cloud.tld/remote.php/dav/files/erwin/Documents
Username string
Password string
}
// Entry is one file discovered by List. Path is relative to the share root,
// decoded and never starting with '/'.
type Entry struct {
Path string
ETag string
Size int64
Modified time.Time
}
// ListResult is a bounded recursive listing.
type ListResult struct {
Files []Entry
Truncated bool // a cap was hit; callers must NOT treat the list as exhaustive
}
const (
dialTimeout = 45 * time.Second
propfindLimit = 2 * 1 << 20 // 2 MiB response cap per PROPFIND
maxDirs = 200 // directory PROPFINDs per listing
maxFiles = 1000 // collected files per listing
maxDepth = 12 // folder nesting below the share root
)
// dial mirrors internal/mcpclient's netguard-pinned transport.
func dial() *http.Transport {
return &http.Transport{
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
if netguard.AllowPrivate() {
return netguard.DialContext(ctx, network, address)
}
return netguard.DialContextPorts(ctx, network, address, 80, 443)
},
TLSHandshakeTimeout: 10 * time.Second,
ResponseHeaderTimeout: 30 * time.Second,
IdleConnTimeout: 30 * time.Second,
}
}
func httpClient(conn Conn) *http.Client {
return &http.Client{
Transport: basicRT{base: dial(), conn: conn},
Timeout: dialTimeout,
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
}
// basicRT injects the credential per request. Clone so the shared transport
// never mutates the caller's request.
type basicRT struct {
base http.RoundTripper
conn Conn
}
func (b basicRT) RoundTrip(r *http.Request) (*http.Response, error) {
r2 := r.Clone(r.Context())
r2.SetBasicAuth(b.conn.Username, b.conn.Password)
return b.base.RoundTrip(r2)
}
// Check verifies the share answers PROPFIND Depth:0 with a 207 Multi-Status
// — the cheapest credential-and-protocol proof. The error strings are safe
// to surface verbatim (they carry no secret).
func Check(ctx context.Context, conn Conn) error {
base, err := normalizeBase(conn.BaseURL)
if err != nil {
return err
}
res, err := propfind(ctx, conn, joinURL(base, ""), "0")
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode == http.StatusMultiStatus {
return nil
}
return describe(res)
}
// List walks the share breadth-wise (Depth:1 per directory, bounded) and
// returns FILES only. Truncated=true means a cap stopped the walk, so the
// caller must not reconcile deletions.
func List(ctx context.Context, conn Conn) (*ListResult, error) {
base, err := normalizeBase(conn.BaseURL)
if err != nil {
return nil, err
}
out := &ListResult{}
seen := map[string]bool{}
queue := []string{""} // relative dir paths, "" = the share root
dials := 0
for len(queue) > 0 && !out.Truncated {
rel := queue[0]
queue = queue[1:]
if strings.Count(rel, "/") >= maxDepth {
out.Truncated = true
continue
}
if dials >= maxDirs {
out.Truncated = true
continue
}
dials++
dirURL := joinURL(base, rel)
if rel != "" {
dirURL += "/"
}
if dials > 1 {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(walkPace):
}
}
entries, err := propfindEntries(ctx, conn, dirURL)
if err != nil {
return nil, err
}
for _, e := range entries {
child, ok := relativize(base, e.href)
if !ok || child == rel || child == "" { // self-entry
continue
}
if !isChildOf(child, rel) {
continue
}
if e.isCollection {
if seen[child] {
continue
}
seen[child] = true
queue = append(queue, child)
continue
}
if seen[child] {
continue
}
seen[child] = true
if len(out.Files) >= maxFiles {
out.Truncated = true
break
}
out.Files = append(out.Files, Entry{Path: child, ETag: e.etag, Size: e.size, Modified: e.modified})
}
}
return out, nil
}
// --- PROPFIND plumbing -------------------------------------------------------
type msResourceType struct {
Collection *struct{} `xml:"collection"`
}
type msProp struct {
ResourceType msResourceType `xml:"resourcetype"`
ETag string `xml:"getetag"`
Size int64 `xml:"getcontentlength"`
Modified string `xml:"getlastmodified"`
}
type msPropStat struct {
Prop msProp `xml:"prop"`
}
type msResp struct {
Href string `xml:"href"`
PropStats []msPropStat `xml:"propstat"`
}
type multiStatus struct {
Responses []msResp `xml:"response"`
}
// parsed is one decoded Multi-Status row.
type parsed struct {
href string
isCollection bool
etag string
size int64
modified time.Time
}
// propfind issues a PROPFIND with the given Depth and returns the raw
// response (caller closes the body). Both Check and List build the same
// request; only Depth differs.
//
// Rate limits (429/503 — Nextcloud throttles bursty PROPFIND walks) are
// retried up to rateRetries times, honoring Retry-After (capped at
// rateWaitCap so a hostile server cannot pin the sync); without the header
// a short linear backoff applies. Every wait is ctx-bound.
func propfind(ctx context.Context, conn Conn, target, depth string) (*http.Response, error) {
for attempt := 0; ; attempt++ {
req, err := http.NewRequestWithContext(ctx, "PROPFIND", target, strings.NewReader(propfindBody))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/xml")
req.Header.Set("Depth", depth)
res, err := httpClient(conn).Do(req)
if err != nil {
return nil, fmt.Errorf("could not reach the WebDAV share: %w", err)
}
if (res.StatusCode == http.StatusTooManyRequests || res.StatusCode == http.StatusServiceUnavailable) && attempt < rateRetries {
wait := rateLimitWait(res.Header.Get("Retry-After"), attempt)
_ = res.Body.Close()
select {
case <-ctx.Done():
return nil, fmt.Errorf("could not reach the WebDAV share: %w", ctx.Err())
case <-time.After(wait):
}
continue
}
return res, nil
}
}
const (
rateRetries = 3
rateWaitCap = 30 * time.Second
rateWaitDefault = 5 * time.Second
// walkPace spaces directory PROPFINDs so a bounded walk stays under
// common server rate limits instead of tripping them and paying
// Retry-After waits on every request.
walkPace = 100 * time.Millisecond
)
// rateLimitWait parses Retry-After (delay-seconds form; the HTTP-date form
// falls back to the default) and caps it. attempt is zero-based.
func rateLimitWait(header string, attempt int) time.Duration {
if secs, err := strconv.Atoi(strings.TrimSpace(header)); err == nil && secs >= 0 {
d := time.Duration(secs) * time.Second
if d > rateWaitCap {
d = rateWaitCap
}
return d
}
d := rateWaitDefault * time.Duration(attempt+1)
if d > rateWaitCap {
d = rateWaitCap
}
return d
}
const propfindBody = `<?xml version="1.0" encoding="utf-8"?>` +
`<propfind xmlns="DAV:"><prop>` +
`<resourcetype/><getetag/><getcontentlength/><getlastmodified/>` +
`</prop></propfind>`
func propfindEntries(ctx context.Context, conn Conn, target string) ([]parsed, error) {
res, err := propfind(ctx, conn, target, "1")
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusMultiStatus {
return nil, describe(res)
}
body, err := io.ReadAll(io.LimitReader(res.Body, propfindLimit))
if err != nil {
return nil, fmt.Errorf("WebDAV listing failed: %w", err)
}
var ms multiStatus
if err := xml.Unmarshal(body, &ms); err != nil {
return nil, fmt.Errorf("WebDAV server returned an unreadable listing")
}
out := make([]parsed, 0, len(ms.Responses))
for _, r := range ms.Responses {
p := parsed{href: decodeHref(r.Href)}
// Some servers signal collections only via a trailing slash on the href.
if strings.HasSuffix(strings.TrimSpace(r.Href), "/") {
p.isCollection = true
}
for _, ps := range r.PropStats {
if ps.Prop.ResourceType.Collection != nil {
p.isCollection = true
}
if ps.Prop.ETag != "" {
p.etag = strings.Trim(ps.Prop.ETag, `"`)
}
if ps.Prop.Size != 0 {
p.size = ps.Prop.Size
}
if ps.Prop.Modified != "" {
if t, err := http.ParseTime(ps.Prop.Modified); err == nil {
p.modified = t
} else if t, err := time.Parse(time.RFC3339, ps.Prop.Modified); err == nil {
p.modified = t
}
}
}
out = append(out, p)
}
return out, nil
}
// describe turns a non-207 PROPFIND answer into a stable, secret-free error.
func describe(res *http.Response) error {
defer res.Body.Close()
switch {
case res.StatusCode == http.StatusUnauthorized:
return fmt.Errorf("the share rejected these credentials (401)")
case res.StatusCode == http.StatusForbidden:
return fmt.Errorf("the share refused access (403)")
case res.StatusCode == http.StatusNotFound:
return fmt.Errorf("no WebDAV resource at that path (404)")
case res.StatusCode >= 300 && res.StatusCode < 400:
return fmt.Errorf("the share redirected the request; Superbrain refuses to carry credentials across redirects")
case res.StatusCode == http.StatusMethodNotAllowed || res.StatusCode == http.StatusNotImplemented:
return fmt.Errorf("the endpoint does not speak WebDAV PROPFIND (%d)", res.StatusCode)
default:
return fmt.Errorf("unexpected answer from the WebDAV share (%d)", res.StatusCode)
}
}
// --- URL / path helpers ------------------------------------------------------
// normalizeBase validates the share root and gives it a trailing slash so
// relative joins are unambiguous.
func normalizeBase(raw string) (*url.URL, error) {
u, err := url.Parse(strings.TrimSpace(raw))
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return nil, fmt.Errorf("share URL must be an absolute http(s) URL")
}
if u.User != nil {
return nil, fmt.Errorf("credentials must be entered as fields, never in the URL")
}
// Work on the DECODED path: assigning an escaped string back to u.Path
// would double-encode it when EscapedPath() regenerates the wire form.
p := path.Clean("/" + strings.TrimPrefix(u.Path, "/"))
if p == "/" {
u.Path = ""
} else if !strings.HasSuffix(p, "/") {
p += "/"
}
u.Path = p
u.RawQuery = ""
u.Fragment = ""
return u, nil
}
func joinURL(base *url.URL, rel string) string {
p := strings.TrimSuffix(base.EscapedPath(), "/")
if rel == "" {
return base.Scheme + "://" + base.Host + p + "/"
}
segs := strings.Split(rel, "/")
for i, s := range segs {
segs[i] = url.PathEscape(s)
}
return base.Scheme + "://" + base.Host + p + "/" + strings.Join(segs, "/")
}
// decodeHref turns a Multi-Status href into an unescaped path.
func decodeHref(h string) string {
if h == "" {
return h
}
// hrefs may be absolute URLs or full paths; keep the path component.
if u, err := url.Parse(h); err == nil && (strings.HasPrefix(h, "http") || strings.HasPrefix(h, "/")) {
h = u.Path
}
if d, err := url.PathUnescape(h); err == nil {
return d
}
return h
}
// relativize maps an href path onto a share-relative decoded path under
// base. Hrefs that are not under the base (foreign bindings) are dropped.
func relativize(base *url.URL, hrefPath string) (string, bool) {
basePath := strings.TrimSuffix(base.Path, "/")
hp := hrefPath
if i := strings.LastIndex(hp, "?"); i >= 0 {
hp = hp[:i]
}
hp = strings.TrimSuffix(hp, "/")
if basePath != "" && !strings.HasPrefix(hp+"/", basePath+"/") && hp != basePath {
return "", false
}
rel := strings.TrimPrefix(strings.TrimPrefix(hp, basePath), "/")
rel = strings.Trim(rel, "/")
if rel == "" || strings.Contains(rel, "..") {
return "", false
}
return rel, true
}
func isChildOf(rel, dir string) bool {
if dir == "" {
return true
}
return strings.HasPrefix(rel, dir+"/")
}
// FileURL resolves a listing entry's relative path to its absolute DAV URL
// under the share base — the URL that becomes the bookmark. Invalid bases
// surface as an error so the caller can mark the sync, never a half-built URL.
func FileURL(baseURL, rel string) (string, error) {
base, err := normalizeBase(baseURL)
if err != nil {
return "", err
}
return joinURL(base, rel), nil
}