Files
superbrain/internal/webdav/client_test.go
T
Andrew S Erwin 564bdc87b6 WebDAV file shares: connect any RFC 4918 service as a Collection of per-file bookmark URLs
Settings -> WebDAV: a user connects an external WebDAV share (any service;
on Core the deployment's NEXTCLOUD_URL offers Nextcloud as a one-click
prefill - DATA, never a TIER code fork). The share materializes as a
Collection and every file becomes a Bookmark carrying the file's DAV URL,
reconciled by the WebDavItem path ledger (migration 020 + schema.sql,
db-converge proven):

- idempotent syncs; etag changes refresh the ledger only, never user-edited
  title/notes/tags; same-URL bookmarks are reused (URL-identity invariant);
- vanished files detach membership but keep the bookmark (sync never
  destroys user data); a user-deleted bookmark is a tombstone that is never
  resurrected; a user-removed membership stays removed - unless the whole
  collection was deleted, when the next sync re-links every live row;
- bounded walks (200 dirs / 1000 files / depth 12) and a truncated listing
  never reconciles deletions;
- netguard-pinned dials (80/443, no trusted exemption for user hosts),
  Basic auth in a header only, redirects refused outright;
- the webdav connector entitlement gates creation AND every sync; a
  downgrade suppresses instead of deleting;
- engine tick per notify/agent discipline (jitter, advisory lease, budget,
  log-not-fatal); /test proves PROPFIND, /sync reconciles on demand;
  passwords write-only + masked, PATCH carries version (409 on stale), cap
  10 per user.

internal/webdav (client+engine), handlers/webdav.go + routes, main.go 4th
loop, config.NextcloudSuggestion, Settings tab + webdav-settings.tsx,
API.md contract section, env docs, Core installer writes NEXTCLOUD_URL.
Client unit tests on an httptest fake DAV server; four integration tests
cover lifecycle, recreation, plan gate and suggestion; regressions drive
the Settings UI end-to-end (masked rows, prefill, connect/sync/test, no
secret echo). All suites green.
2026-11-13 08:23:09 -06:00

200 lines
6.1 KiB
Go

package webdav
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// harness env escape hatch: the fakes live on 127.0.0.1, which netguard
// would otherwise refuse like any production private range.
func allowPrivate(t *testing.T) { t.Setenv("INTEGRATIONS_ALLOW_PRIVATE", "1") }
const (
davUser = "erwin"
davPass = "s3cret"
)
// fakeDAV serves a fixed three-file tree with the Nextcloud-style URL shape:
//
// /dav/ a.txt, "b c.md", sub/d.txt
// /dav/sub/ d.txt
//
// plus dedicated paths for the error branches: /bad/ (always 401),
// /notdav (405 — speaks no WebDAV), /redir/ (302 — must not be followed).
func fakeDAV(t *testing.T) *httptest.Server {
t.Helper()
body := func(href string, isDir bool, etag string, size string, mtime string) string {
rt := `<resourcetype/>`
if isDir {
rt = `<resourcetype><collection xmlns="DAV:"/></resourcetype>`
}
extra := ""
if etag != "" {
extra += `<getetag>` + etag + `</getetag>`
}
if size != "" {
extra += `<getcontentlength>` + size + `</getcontentlength>`
}
if mtime != "" {
extra += `<getlastmodified>` + mtime + `</getlastmodified>`
}
return `<response><href>` + href + `</href><propstat><prop xmlns="DAV:">` + rt + extra +
`</prop><status>HTTP/1.1 200 OK</status></propstat></response>`
}
root := `<multistatus xmlns="DAV:">` +
body("/dav/", true, `"root"`, "", "") +
body("/dav/a.txt", false, `"A1"`, "10", "Mon, 11 Nov 2026 10:00:00 GMT") +
body("/dav/b%20c.md", false, `"B1"`, "7", "") +
body("/dav/sub/", true, "", "", "") +
`</multistatus>`
sub := `<multistatus xmlns="DAV:">` +
body("/dav/sub/", true, "", "", "") +
body("/dav/sub/d.txt", false, `"D1"`, "3", "") +
`</multistatus>`
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/bad/":
http.Error(w, "no", http.StatusUnauthorized)
return
case "/notdav/": // normalized bases always carry the trailing slash
http.Error(w, "no", http.StatusMethodNotAllowed)
return
case "/redir/":
http.Redirect(w, r, "https://elsewhere.invalid/", http.StatusFound)
return
}
if u, p, ok := r.BasicAuth(); !ok || u != davUser || p != davPass {
w.Header().Set("WWW-Authenticate", `Basic realm="fake"`)
http.Error(w, "no", http.StatusUnauthorized)
return
}
if r.Method != "PROPFIND" {
http.Error(w, "no", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
w.WriteHeader(http.StatusMultiStatus)
switch r.URL.Path {
case "/dav/":
if r.Header.Get("Depth") == "0" {
// self-only answer, like a compliant server
_, _ = w.Write([]byte(`<multistatus xmlns="DAV:">` + body("/dav/", true, `"root"`, "", "") + `</multistatus>`))
return
}
_, _ = w.Write([]byte(root))
case "/dav/sub/":
_, _ = w.Write([]byte(sub))
default:
http.Error(w, "no", http.StatusNotFound)
}
}))
t.Cleanup(ts.Close)
return ts
}
func connFor(base, pw string) Conn {
return Conn{BaseURL: base, Username: davUser, Password: pw}
}
func TestCheckSucceeds(t *testing.T) {
allowPrivate(t)
ts := fakeDAV(t)
if err := Check(context.Background(), connFor(ts.URL+"/dav", davPass)); err != nil {
t.Fatalf("Check: %v", err)
}
}
func TestCheckErrorBranches(t *testing.T) {
allowPrivate(t)
ts := fakeDAV(t)
ctx := context.Background()
cases := []struct{ url, want string }{
{"/bad/", "rejected these credentials"},
{"/notdav", "does not speak WebDAV"},
{"/redir", "redirect"},
}
for _, c := range cases {
err := Check(ctx, connFor(ts.URL+c.url, davPass))
if err == nil || !strings.Contains(err.Error(), c.want) {
t.Fatalf("Check(%s) = %v, want error containing %q", c.url, err, c.want)
}
}
// Wrong password against the real tree hits the 401 branch.
if err := Check(ctx, connFor(ts.URL+"/dav", "nope")); err == nil || !strings.Contains(err.Error(), "credentials") {
t.Fatalf("Check with wrong password: %v", err)
}
}
func TestCheckRejectsUserinfoURL(t *testing.T) {
allowPrivate(t)
err := Check(context.Background(), Conn{BaseURL: "http://erwin:pass@127.0.0.1/dav", Username: davUser, Password: davPass})
if err == nil || !strings.Contains(err.Error(), "never in the URL") {
t.Fatalf("expected userinfo rejection, got %v", err)
}
}
func TestListWalksRecursively(t *testing.T) {
allowPrivate(t)
ts := fakeDAV(t)
res, err := List(context.Background(), connFor(ts.URL+"/dav", davPass))
if err != nil {
t.Fatalf("List: %v", err)
}
if res.Truncated {
t.Fatal("unexpected truncation")
}
if len(res.Files) != 3 {
t.Fatalf("want 3 files, got %d: %+v", len(res.Files), res.Files)
}
want := map[string]string{"a.txt": "A1", "b c.md": "B1", "sub/d.txt": "D1"}
for _, f := range res.Files {
etag, ok := want[f.Path]
if !ok {
t.Fatalf("unexpected file %q", f.Path)
}
if f.ETag != etag {
t.Fatalf("%s etag %q want %q", f.Path, f.ETag, etag)
}
if f.Path == "a.txt" {
if f.Size != 10 || f.Modified.Year() != 2026 {
t.Fatalf("metadata not parsed: %+v", f)
}
}
}
}
func TestFileURL(t *testing.T) {
base := "https://cloud.example/remote.php/dav/files/erwin"
if got, err := FileURL(base, "sub/my doc.txt"); err != nil || got != "https://cloud.example/remote.php/dav/files/erwin/sub/my%20doc.txt" {
t.Fatalf("FileURL = %q, err %v", got, err)
}
if got, err := FileURL("https://h/", "x.bin"); err != nil || got != "https://h/x.bin" {
t.Fatalf("root join = %q, err %v", got, err)
}
if _, err := FileURL("nope", "x"); err == nil {
t.Fatal("bad base accepted")
}
}
func TestNormalizeBasePercentSafety(t *testing.T) {
// A pre-escaped segment must survive one round trip, never become %2520.
u, err := normalizeBase("https://h/remote.php/dav/files/a%20b")
if err != nil {
t.Fatal(err)
}
if got := joinURL(u, "c.txt"); got != "https://h/remote.php/dav/files/a%20b/c.txt" {
t.Fatalf("escaped base mangled: %q", got)
}
// A raw space in the user-supplied base is valid and stays a single encoding.
u2, err := normalizeBase("https://h/space test")
if err != nil {
t.Fatal(err)
}
if got := joinURL(u2, "x"); !strings.HasSuffix(got, "/space%20test/x") {
t.Fatalf("double or missing encoding: %q", got)
}
}