Files
magpie/internal/davsync/dav_test.go
T
yetone 7ab91961d2 davsync: an unchanged file on the server costs a request, not a download (Crispin on Discord: 是不是Magpie后台一直在自动同步,导致被坚果云给限制了) — every 3 minutes sync read the whole sealed file even when nothing had changed, and 坚果云's free plan caps monthly downloads and requests per 30 minutes. The sync state now keeps the server's version beside its hash (its ETag, or a Last-Modified at least a second older than the server's Date, so a write in that same second can't go unseen), from the read or from the ETag a write answers with (none said: the next sync reads in full, as before); the next read sends If-None-Match (or If-Modified-Since) and a 304 with nothing changed here ends the sync, while a change here merges with a copy of the server's file kept beside sync-state.json (sync-server.magpie-backup, 0600, checked against the hash; gone or different, the file is read again), so it isn't read twice. A server that ignores the condition sends the file and syncs exactly as today. S3 does the same with If-None-Match on GetObject, signed with the rest (the fake S3 checks every signature). A 429 or 503 (S3's SlowDown) now says the server is limiting how often magpie may reach it, and Run waits as long as Retry-After says (up to 6 h) or else doubles from 6 up to 30 minutes, back to 3 after a sync that goes through; log de-dup is kept, as the message doesn't carry the wait. The 403 paths (there, forbidden) only run when the server answers 403, so a working setup costs one conditional GET per cycle. TestSyncUnchangedIsNotRead (ETag, ETag not on PUT, Last-Modified: three unchanged cycles read 0 bytes, a server change is read once and merged, a change here is pushed without a read, a missing copy is read again), TestSyncRateLimited and TestS3Unchanged fail without the change (with the conditions dropped: 3 full reads of 1932 bytes, 'HTTP 429' with no backoff, unconditional S3 GETs); TestSyncIgnoringConditions guards servers without conditional reads. go vet ./internal/..., go build -tags nogui ./... (darwin, GOOS=linux), GOOS=windows go build ./..., go test -tags nogui ./internal/davsync/ ./internal/gui/ pass.
2026-10-02 11:08:14 +08:00

134 lines
4.7 KiB
Go

package davsync
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// A 403 is told apart: a folder in the address that isn't on the server, one
// the account may only read, and a server that won't say — not all of them a
// wrong password, as they read before.
func TestDAVForbidden(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if u, p, ok := r.BasicAuth(); !ok || u != "me" || p != "pw" {
w.WriteHeader(http.StatusUnauthorized)
return
}
path := strings.TrimSuffix(r.URL.Path, "/")
switch {
case r.Method == "PROPFIND" && (path == "" || path == "/ro"):
w.WriteHeader(http.StatusMultiStatus)
case r.Method == "PROPFIND" && path == "/missing":
w.WriteHeader(http.StatusNotFound)
case r.Method == http.MethodGet && strings.HasPrefix(path, "/ro/"):
w.WriteHeader(http.StatusNotFound)
default: // a Synology: anything else, 403
w.WriteHeader(http.StatusForbidden)
}
}))
defer srv.Close()
ctx := context.Background()
for _, c := range []struct{ dir, pass, want string }{
{"/missing", "pw", "there is no folder /missing"},
{"/ro", "pw", "doesn't let this account write in /ro"},
{"/secret", "pw", "doesn't let this account use /secret"},
{"/missing", "bad", "user name or password"},
} {
d, err := newDAV(Config{URL: srv.URL + c.dir, User: "me", Password: c.pass})
if err != nil {
t.Fatal(err)
}
_, _, err = d.get(ctx, version{})
if err == nil {
_, err = d.put(ctx, []byte("x"), "")
}
if err == nil || !strings.Contains(err.Error(), c.want) {
t.Errorf("%s: %v, want %q", c.dir, err, c.want)
}
}
}
// OpenList's and Alist's /dav/ lists their storages: a folder can't be made
// there (MKCOL 405, as if it were) and a file can't be put (404). The error
// says to put a storage in the address, naming them.
func TestDAVStorageRoot(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == "PROPFIND" && r.URL.Path == "/dav/" && r.Header.Get("Depth") == "1":
w.WriteHeader(http.StatusMultiStatus)
io.WriteString(w, `<?xml version="1.0" encoding="UTF-8"?><D:multistatus xmlns:D="DAV:">`+
`<D:response><D:href>/dav/</D:href><D:propstat><D:prop><D:resourcetype><D:collection/></D:resourcetype></D:prop></D:propstat></D:response>`+
`<D:response><D:href>/dav/local/</D:href><D:propstat><D:prop><D:resourcetype><D:collection/></D:resourcetype></D:prop></D:propstat></D:response>`+
`<D:response><D:href>/dav/aliyun/</D:href><D:propstat><D:prop><D:resourcetype><D:collection/></D:resourcetype></D:prop></D:propstat></D:response>`+
`<D:response><D:href>/dav/readme.txt</D:href><D:propstat><D:prop><D:resourcetype/></D:prop></D:propstat></D:response>`+
`</D:multistatus>`)
case r.Method == "MKCOL":
w.WriteHeader(http.StatusMethodNotAllowed)
default:
w.WriteHeader(http.StatusNotFound)
}
}))
defer srv.Close()
d, err := newDAV(Config{URL: srv.URL + "/dav/"})
if err != nil {
t.Fatal(err)
}
_, err = d.put(context.Background(), []byte("x"), "")
if err == nil || !strings.Contains(err.Error(), "(local, aliyun), like "+srv.URL+"/dav/local") {
t.Fatalf("%v", err)
}
}
// A Synology answers 403 for anything under a folder that isn't there yet,
// PROPFIND too: magpie's own folder, before the first sync, is made rather
// than taken for a folder the account can't write in.
func TestDAVForbiddenUntilMade(t *testing.T) {
made, stored := false, ""
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := strings.TrimSuffix(r.URL.Path, "/")
switch {
case path == "/data" && r.Method == "PROPFIND":
w.WriteHeader(http.StatusMultiStatus)
case path == "/data/magpie" && r.Method == "MKCOL":
made = true
w.WriteHeader(http.StatusCreated)
case strings.HasPrefix(path, "/data/magpie") && made:
switch r.Method {
case "PROPFIND":
w.WriteHeader(http.StatusMultiStatus)
case http.MethodPut:
b, _ := io.ReadAll(r.Body)
stored = string(b)
w.WriteHeader(http.StatusCreated)
case http.MethodGet:
if stored == "" {
w.WriteHeader(http.StatusNotFound)
return
}
io.WriteString(w, stored)
}
default:
w.WriteHeader(http.StatusForbidden)
}
}))
defer srv.Close()
ctx := context.Background()
d, err := newDAV(Config{URL: srv.URL + "/data"})
if err != nil {
t.Fatal(err)
}
if data, _, err := d.get(ctx, version{}); err != nil || data != nil {
t.Fatalf("before the first sync: %q %v", data, err)
}
if _, err := d.put(ctx, []byte("x"), ""); err != nil {
t.Fatal(err)
}
if data, _, err := d.get(ctx, version{}); err != nil || string(data) != "x" {
t.Fatalf("after: %q %v", data, err)
}
}