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 := ``
if isDir {
rt = ``
}
extra := ""
if etag != "" {
extra += `` + etag + ``
}
if size != "" {
extra += `` + size + ``
}
if mtime != "" {
extra += `` + mtime + ``
}
return `` + href + `` + rt + extra +
`HTTP/1.1 200 OK`
}
root := `` +
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, "", "", "") +
``
sub := `` +
body("/dav/sub/", true, "", "", "") +
body("/dav/sub/d.txt", false, `"D1"`, "3", "") +
``
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(`` + body("/dav/", true, `"root"`, "", "") + ``))
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)
}
}