Files
rclone/backend/protondrive/nodes_internal_test.go
T
Lucas WintherandClaude Opus 5.5 e23de0b586 protondrive: make the volume creation race test deterministic
TestClientBootstrapCreateVolumeRace failed now and then in whole
package race runs with "expected 2 POST /drive/volumes, got 1".

loadAccount holds the process-wide unlockMu while unlocking keys, so
the second client's first GET drive/v2/shares/my-files is sent one
key unlock, or under load many queued unlocks, after the first's. The
500ms Delay fault on both GETs shifted them equally and so did not
keep them together: when the first client's create had finished
before the second client's GET was handled, the second client found
the volume and never POSTed. The client handles that ordering
correctly; only the test's assertion depended on timing.

Add a Gather option to protontest faults, which holds each faulted
request until all Times have arrived, and use it for both GETs and
both POSTs. The test now starts the second client as late as the
server lets it, which failed 10 of 10 runs with the Delay fault.

Gathering the POSTs runs both create volume checks in the fake at
once, which exposed a data race there: go-crypto records signature
checks in a key on its first use, and the new user's address key had
never been used. Check each request with its own copy of the key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 16:37:14 +01:00

1030 lines
35 KiB
Go

package protondrive
import (
"context"
"crypto/sha1"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"runtime"
"strings"
"sync"
"testing"
"time"
"github.com/rclone/rclone/backend/protondrive/api"
"github.com/rclone/rclone/backend/protondrive/protontest"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/lib/pacer"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// listAll returns the children of folder parentID by name, failing
// the test if a name or ID comes twice.
func listAll(t *testing.T, c *client, parentID string) map[string]*node {
t.Helper()
byName := make(map[string]*node)
ids := make(map[string]bool)
err := c.listChildren(context.Background(), parentID, func(nodes []*node) error {
for _, n := range nodes {
require.False(t, ids[n.ID], "ID %s listed twice", n.ID)
require.NotContains(t, byName, n.Name, "name listed twice")
ids[n.ID] = true
byName[n.Name] = n
}
return nil
})
require.NoError(t, err)
return byName
}
// totalRequests returns the number of requests the server has counted.
func totalRequests(srv *protontest.Server) int {
n := 0
for _, count := range srv.Requests() {
n += count
}
return n
}
// sha1Hex returns the lower-case hex SHA-1 of data.
func sha1Hex(data []byte) string {
sum := sha1.Sum(data)
return hex.EncodeToString(sum[:])
}
// requireNoLegacyRoutes fails the test if a share-scoped route other
// than GET /drive/shares/{shareID} was requested.
func requireNoLegacyRoutes(t *testing.T, srv *protontest.Server) {
t.Helper()
for key := range srv.Requests() {
if strings.Contains(key, "/drive/shares/") && key != "GET /drive/shares/{shareID}" {
t.Errorf("requested %s", key)
}
}
}
func TestClientBootstrap(t *testing.T) {
t.Parallel()
c, srv, u := newTestClient(t)
assert.Equal(t, u.RootID(), c.rootID())
assert.Equal(t, u.VolumeID(), c.volumeID)
assert.Equal(t, u.ShareID(), c.shareID)
assert.True(t, c.root.IsFolder)
assert.NotEmpty(t, c.root.hashKey)
assert.Equal(t, u.Email(), c.addr.Email)
assert.Zero(t, srv.Requests()["POST /drive/volumes"])
requireNoLegacyRoutes(t, srv)
}
// requireUsableDrive checks that c and u's dump agree on a drive with
// working root keys.
func requireUsableDrive(t *testing.T, c *client, u *protontest.User) {
t.Helper()
assert.Equal(t, u.RootID(), c.rootID())
assert.Equal(t, "root", c.root.Name)
// Seeding as another client decrypts the root's key and hash key.
dirID := u.SeedFolder(u.RootID(), "dir")
fileID := u.SeedFile(u.RootID(), "file.txt", []byte("hello"), time.Now())
for _, n := range u.Dump() {
assert.NoError(t, n.Err, n.Path)
}
assert.Len(t, u.Dump(), 2)
listed := listAll(t, c, c.rootID())
require.Len(t, listed, 2)
assert.Equal(t, dirID, listed["dir"].ID)
assert.Equal(t, fileID, listed["file.txt"].ID)
}
func TestClientBootstrapCreatesVolume(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddUserWithoutDrive("new", "pass")
c := newTestClientFor(t, srv, u, clientOptions{})
assert.Equal(t, 1, srv.Requests()["POST /drive/volumes"])
assert.Empty(t, u.Dump())
requireUsableDrive(t, c, u)
requireNoLegacyRoutes(t, srv)
srv.ResetRequests()
c2 := newTestClientFor(t, srv, u, clientOptions{})
assert.Zero(t, srv.Requests()["POST /drive/volumes"])
assert.Equal(t, c.rootID(), c2.rootID())
}
func TestClientBootstrapCreateVolumeRace(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddUserWithoutDrive("new", "pass")
// Both clients find no volume before either creates one, so one of
// them loses the creation with code 2500, and both creations are
// checked at once.
srv.Inject(protontest.Fault{Method: "GET", Pattern: "/drive/v2/shares/my-files", Times: 2, Gather: true})
srv.Inject(protontest.Fault{Method: "POST", Pattern: "/drive/volumes", Times: 2, Gather: true})
// The second client starts once the first has finished, or after 2s
// if the server holds the first back for it, as if its key unlock
// were queued behind others on unlockMu, so its first look at the
// drive comes as late as the server lets it.
ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
defer cancel()
firstDone := make(chan struct{})
clients := make([]*client, 2)
errs := make([]error, 2)
var wg sync.WaitGroup
wg.Go(func() {
defer close(firstDone)
clients[0], errs[0] = newClient(ctx, newAccountSession(srv, u), clientOptions{})
})
wg.Go(func() {
select {
case <-firstDone:
case <-time.After(2 * time.Second):
}
clients[1], errs[1] = newClient(ctx, newAccountSession(srv, u), clientOptions{})
})
wg.Wait()
for i, c := range clients {
require.NoError(t, errs[i])
t.Cleanup(c.close)
}
assert.Equal(t, 2, srv.Requests()["POST /drive/volumes"])
assert.Equal(t, clients[0].rootID(), clients[1].rootID())
requireUsableDrive(t, clients[0], u)
assert.Len(t, listAll(t, clients[1], clients[1].rootID()), 2)
}
func TestListChildren(t *testing.T) {
t.Parallel()
c, _, u := newTestClient(t)
modTime := time.Date(2024, 5, 6, 7, 8, 9, 123e6, time.UTC)
content := []byte(strings.Repeat("rclone ", 150))
dirID := u.SeedFolder(u.RootID(), "dir")
fileID := u.SeedFile(u.RootID(), "file.txt", content, modTime)
emptyID := u.SeedFile(u.RootID(), "empty", nil, modTime.Add(time.Hour))
innerID := u.SeedFile(dirID, "inner.bin", []byte{1, 2, 3}, modTime)
listed := listAll(t, c, c.rootID())
require.Len(t, listed, 3)
dir := listed["dir"]
require.NotNil(t, dir)
assert.Equal(t, dirID, dir.ID)
assert.Equal(t, c.rootID(), dir.ParentID)
assert.True(t, dir.IsFolder)
assert.Equal(t, api.LinkStateActive, dir.State)
assert.NotEmpty(t, dir.hashKey)
file := listed["file.txt"]
require.NotNil(t, file)
assert.Equal(t, fileID, file.ID)
assert.False(t, file.IsFolder)
assert.Equal(t, int64(len(content)), file.size(true))
assert.Greater(t, file.size(false), int64(len(content)))
assert.Equal(t, file.EncryptedSize, file.size(false))
assert.True(t, modTime.Equal(file.modTime()), "modTime %v", file.modTime())
assert.Equal(t, sha1Hex(content), file.sha1())
assert.Equal(t, "text/plain; charset=utf-8", file.MIMEType)
assert.NotEmpty(t, file.RevisionID)
empty := listed["empty"]
require.NotNil(t, empty)
assert.Equal(t, emptyID, empty.ID)
assert.Equal(t, int64(0), empty.size(true))
assert.True(t, modTime.Add(time.Hour).Equal(empty.modTime()))
assert.Equal(t, sha1Hex(nil), empty.sha1())
inner := listAll(t, c, dirID)
require.Len(t, inner, 1)
assert.Equal(t, innerID, inner["inner.bin"].ID)
assert.Equal(t, int64(3), inner["inner.bin"].size(true))
}
func TestNodeWithoutXAttrs(t *testing.T) {
serverTime := time.Unix(1700000000, 0)
n := &node{EncryptedSize: 42, ServerModTime: serverTime}
assert.Equal(t, int64(42), n.size(true))
assert.Equal(t, serverTime, n.modTime())
assert.Equal(t, "", n.sha1())
n.X = &xattrs{SHA1: "ABCDEF"}
assert.Equal(t, "abcdef", n.sha1())
assert.Equal(t, int64(0), n.size(true))
assert.Equal(t, int64(42), n.size(false))
}
func TestGetNode(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddUser("user", "pass")
dirID := u.SeedFolder(u.RootID(), "dir")
subID := u.SeedFolder(dirID, "sub")
fileID := u.SeedFile(subID, "deep.txt", []byte("deep"), time.Now())
for _, caching := range []bool{true, false} {
c := newTestClientFor(t, srv, u, clientOptions{EnableCaching: caching})
n, err := c.getNode(context.Background(), fileID)
require.NoError(t, err)
assert.Equal(t, "deep.txt", n.Name)
assert.Equal(t, subID, n.ParentID)
assert.Equal(t, int64(4), n.size(true))
root, err := c.getNode(context.Background(), c.rootID())
require.NoError(t, err)
assert.Same(t, c.root, root)
_, err = c.getNode(context.Background(), "no-such-node")
assert.True(t, errors.Is(err, errNotFound), "%v", err)
}
}
func TestListChildrenPaged(t *testing.T) {
t.Parallel()
c, srv, u := newTestClient(t)
srv.SetChildrenPageSize(100)
want := make(map[string]string)
for i := range 250 {
name := fmt.Sprintf("file%03d", i)
want[u.SeedFile(u.RootID(), name, []byte(name), time.Now())] = name
}
srv.ResetRequests()
listed := listAll(t, c, c.rootID())
require.Len(t, listed, 250)
for name, n := range listed {
assert.Equal(t, want[n.ID], name)
}
reqs := srv.Requests()
assert.Equal(t, 3, reqs["GET /drive/v2/volumes/{volumeID}/folders/{linkID}/children"])
assert.Equal(t, 3, reqs["POST /drive/v2/volumes/{volumeID}/links"])
assert.Equal(t, 6, totalRequests(srv), "%v", reqs)
}
func TestListUnicodeAndCase(t *testing.T) {
t.Parallel()
c, _, u := newTestClient(t)
names := []string{"é.txt", "é.txt", "A.txt", "a.txt"}
ids := make(map[string]string)
for _, name := range names {
ids[name] = u.SeedFile(u.RootID(), name, []byte(name), time.Now())
}
listed := listAll(t, c, c.rootID())
require.Len(t, listed, 4)
for _, name := range names {
require.Contains(t, listed, name)
assert.Equal(t, ids[name], listed[name].ID, "%q", name)
n, err := c.findChild(context.Background(), c.rootID(), name)
require.NoError(t, err)
assert.Equal(t, ids[name], n.ID, "%q", name)
}
}
func TestListSkipsDocs(t *testing.T) {
t.Parallel()
c, _, u := newTestClientOpt(t, clientOptions{})
u.SeedDoc(u.RootID(), "notes")
u.SeedDoc(u.RootID(), "plan")
fileID := u.SeedFile(u.RootID(), "file.txt", []byte("x"), time.Now())
for range 2 {
listed := listAll(t, c, c.rootID())
require.Len(t, listed, 1)
assert.Equal(t, fileID, listed["file.txt"].ID)
}
assert.True(t, c.docsNoticed)
assert.Zero(t, c.skipped)
_, err := c.findChild(context.Background(), c.rootID(), "notes")
assert.True(t, errors.Is(err, errNotFound))
}
func TestListSkipsUndecryptableName(t *testing.T) {
t.Parallel()
c, _, u := newTestClientOpt(t, clientOptions{})
aID := u.SeedFile(u.RootID(), "a.txt", []byte("a"), time.Now())
badID := u.SeedFile(u.RootID(), "bad.txt", []byte("b"), time.Now())
cID := u.SeedFolder(u.RootID(), "c")
u.Corrupt(badID, "name")
for range 2 {
listed := listAll(t, c, c.rootID())
require.Len(t, listed, 2)
assert.Equal(t, aID, listed["a.txt"].ID)
assert.Equal(t, cID, listed["c"].ID)
}
// Counted and logged once, however often it is listed.
assert.Equal(t, 1, c.skipped)
assert.True(t, c.reported["unreadable:"+badID])
_, err := c.getNode(context.Background(), badID)
assert.Error(t, err)
}
func TestListBadSignatureStillListed(t *testing.T) {
t.Parallel()
c, _, u := newTestClient(t)
nameID := u.SeedFile(u.RootID(), "name.txt", []byte("n"), time.Now())
passID := u.SeedFolder(u.RootID(), "passphrase")
goodID := u.SeedFile(u.RootID(), "good.txt", []byte("g"), time.Now())
u.Corrupt(nameID, "name-signature")
u.Corrupt(passID, "passphrase-signature")
listed := listAll(t, c, c.rootID())
require.Len(t, listed, 3)
assert.Equal(t, nameID, listed["name.txt"].ID)
assert.Equal(t, passID, listed["passphrase"].ID)
assert.Equal(t, goodID, listed["good.txt"].ID)
assert.True(t, c.reported["verify:"+nameID])
assert.True(t, c.reported["verify:"+passID])
assert.False(t, c.reported["verify:"+goodID])
assert.Zero(t, c.skipped)
}
func TestListRejectsHostileNames(t *testing.T) {
t.Parallel()
c, _, u := newTestClient(t)
hostile := []string{"../x", "a/b", "n\x00ul", "..", strings.Repeat("x", 10<<20)}
for _, name := range hostile {
u.SeedFile(u.RootID(), name, []byte("x"), time.Now())
}
okID := u.SeedFile(u.RootID(), "ok.txt", []byte("ok"), time.Now())
listed := listAll(t, c, c.rootID())
require.Len(t, listed, 1)
assert.Equal(t, okID, listed["ok.txt"].ID)
assert.Equal(t, len(hostile), c.skipped)
}
func TestFindChildNotFound(t *testing.T) {
t.Parallel()
c, _, u := newTestClient(t)
u.SeedFile(u.RootID(), "file.txt", []byte("x"), time.Now())
_, err := c.findChild(context.Background(), c.rootID(), "File.txt")
assert.True(t, errors.Is(err, errNotFound), "%v", err)
n, err := c.findChild(context.Background(), c.rootID(), "file.txt")
require.NoError(t, err)
assert.Equal(t, "file.txt", n.Name)
}
func TestCacheWarmListing(t *testing.T) {
t.Parallel()
for _, caching := range []bool{true, false} {
c, srv, u := newTestClientOpt(t, clientOptions{EnableCaching: caching})
dirID := u.SeedFolder(u.RootID(), "dir")
u.SeedFile(dirID, "file.txt", []byte("x"), time.Now())
srv.ResetRequests()
require.Len(t, listAll(t, c, dirID), 1)
first := totalRequests(srv)
require.NotZero(t, first)
srv.ResetRequests()
require.Len(t, listAll(t, c, dirID), 1)
_, err := c.findChild(context.Background(), dirID, "file.txt")
require.NoError(t, err)
if caching {
assert.Zero(t, totalRequests(srv), "%v", srv.Requests())
} else {
// The folder's key is kept, so only the listing repeats,
// once for listChildren and once for findChild.
assert.Equal(t, 4, totalRequests(srv), "%v", srv.Requests())
}
}
}
func TestClientShouldRetry(t *testing.T) {
c := &client{}
canceled, cancel := context.WithCancel(context.Background())
cancel()
for _, test := range []struct {
name string
ctx context.Context
status int // HTTP status of the response and the *api.Error, if not zero
header string // Retry-After of the response
err error // error if status is zero
retry bool
retryAfter time.Duration // expected RetryAfterError, if not zero
}{
{name: "success"},
{name: "context canceled", ctx: canceled, err: errors.New("boom")},
{name: "429 with Retry-After", status: 429, header: "3", retry: true, retryAfter: 3 * time.Second},
{name: "429 without Retry-After", status: 429, retry: true, retryAfter: defaultRetryAfter},
{name: "429 with zero Retry-After", status: 429, header: "0", retry: true, retryAfter: defaultRetryAfter},
{name: "429 with negative Retry-After", status: 429, header: "-5", retry: true, retryAfter: defaultRetryAfter},
{name: "429 with garbage Retry-After", status: 429, header: "soon", retry: true, retryAfter: defaultRetryAfter},
{name: "429 with huge Retry-After", status: 429, header: "999999999", retry: true, retryAfter: maxRetryAfter},
{name: "429 with overflowing Retry-After", status: 429, header: "99999999999999999999999999", retry: true, retryAfter: maxRetryAfter},
{name: "429 with far Retry-After date", status: 429, header: time.Now().Add(time.Hour).UTC().Format(http.TimeFormat), retry: true, retryAfter: maxRetryAfter},
{name: "429 with past Retry-After date", status: 429, header: time.Now().Add(-time.Hour).UTC().Format(http.TimeFormat), retry: true, retryAfter: defaultRetryAfter},
{name: "408", status: 408, retry: true},
{name: "500", status: 500, retry: true},
{name: "503", status: 503, retry: true},
{name: "422", status: 422},
{name: "404", status: 404},
{name: "401 api error without response", err: &api.Error{Status: 401}},
{name: "session expired", err: fserrors.FatalError(errSessionExpired)},
{name: "captcha", err: errCaptcha},
{name: "network error", err: io.ErrUnexpectedEOF, retry: true},
{name: "other error", err: errors.New("boom")},
} {
t.Run(test.name, func(t *testing.T) {
ctx := test.ctx
if ctx == nil {
ctx = context.Background()
}
var resp *http.Response
err := test.err
if test.status != 0 {
resp = &http.Response{StatusCode: test.status, Header: http.Header{}}
if test.header != "" {
resp.Header.Set("Retry-After", test.header)
}
err = &api.Error{Status: test.status, Code: 2000, Message: http.StatusText(test.status)}
}
retry, gotErr := c.shouldRetry(ctx, resp, err)
assert.Equal(t, test.retry, retry)
if err == nil {
assert.NoError(t, gotErr)
} else {
assert.ErrorIs(t, gotErr, err)
}
d, isRetryAfter := pacer.IsRetryAfter(gotErr)
assert.Equal(t, test.retryAfter != 0, isRetryAfter)
assert.Equal(t, test.retryAfter, d)
})
}
}
func TestRetryAfterDate(t *testing.T) {
resp := &http.Response{Header: http.Header{}}
resp.Header.Set("Retry-After", time.Now().Add(5*time.Second).UTC().Format(http.TimeFormat))
d := retryAfter(resp)
// The date has a resolution of one second.
assert.Greater(t, d, 3*time.Second)
assert.LessOrEqual(t, d, 5*time.Second)
}
func TestRetryAfterHonoured(t *testing.T) {
t.Parallel()
c, srv, _ := newTestClient(t)
srv.Inject(protontest.Fault{Method: "GET", Pattern: "/core/v4/users", Status: http.StatusTooManyRequests, RetryAfter: 1, Times: 2})
srv.ResetRequests()
start := time.Now()
_, total, err := c.about(context.Background())
elapsed := time.Since(start)
require.NoError(t, err)
assert.Equal(t, protontest.DefaultMaxSpace, total)
assert.Equal(t, 3, srv.Requests()["GET /core/v4/users"])
assert.GreaterOrEqual(t, elapsed, 2*time.Second)
assert.Less(t, elapsed, 5*time.Second)
}
func TestRetryAfterDoesNotHoldOtherCalls(t *testing.T) {
t.Parallel()
c, srv, _ := newTestClient(t)
srv.Inject(protontest.Fault{Method: "GET", Pattern: "/core/v4/users", Status: http.StatusTooManyRequests, RetryAfter: 1, Times: 1})
start := time.Now()
_, _, err := c.about(context.Background())
require.NoError(t, err)
assert.GreaterOrEqual(t, time.Since(start), time.Second)
start = time.Now()
_, _, err = c.about(context.Background())
require.NoError(t, err)
assert.Less(t, time.Since(start), 500*time.Millisecond)
// loadAccount, the 429, its retry and the second call.
assert.Equal(t, 4, srv.Requests()["GET /core/v4/users"])
}
func TestRetryAfterCancel(t *testing.T) {
t.Parallel()
c, srv, _ := newTestClient(t)
srv.Inject(protontest.Fault{Method: "GET", Pattern: "/core/v4/users", Status: http.StatusTooManyRequests, RetryAfter: 999999999, Times: 1})
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
defer cancel()
start := time.Now()
_, _, err := c.about(ctx)
assert.ErrorIs(t, err, context.DeadlineExceeded)
assert.Less(t, time.Since(start), 2*time.Second)
// The pacer doesn't hold the next call either.
start = time.Now()
_, _, err = c.about(context.Background())
require.NoError(t, err)
assert.Less(t, time.Since(start), 500*time.Millisecond)
}
func TestListPublicKeysRetried(t *testing.T) {
t.Parallel()
c, srv, u := newTestClient(t)
other := srv.AddUser("other", "pass")
id := u.SeedFileSignedBy(other, u.RootID(), "shared.txt", []byte("from other"), time.Now())
srv.Inject(protontest.Fault{Method: "GET", Pattern: "/core/v4/keys/all", Status: http.StatusTooManyRequests, RetryAfter: 1, Times: 1})
listed := listAll(t, c, c.rootID())
require.Len(t, listed, 1)
assert.Equal(t, id, listed["shared.txt"].ID)
assert.Equal(t, int64(len("from other")), listed["shared.txt"].size(true))
assert.Equal(t, 2, srv.Requests()["GET /core/v4/keys/all"])
assert.False(t, c.reported["verify:"+id], "signature by the other user's address should verify")
}
func TestListFailedBatchNotCached(t *testing.T) {
t.Parallel()
c, srv, u := newTestClient(t)
u.SeedFile(u.RootID(), "file.txt", []byte("x"), time.Now())
srv.Inject(protontest.Fault{Method: "POST", Pattern: "/drive/v2/volumes/{volumeID}/links", Status: http.StatusUnprocessableEntity, Code: api.CodeInvalidValue, Times: 1})
err := c.listChildren(context.Background(), c.rootID(), func([]*node) error { return nil })
require.Error(t, err)
srv.ResetRequests()
require.Len(t, listAll(t, c, c.rootID()), 1)
assert.Equal(t, 1, srv.Requests()["POST /drive/v2/volumes/{volumeID}/links"])
}
func TestListCallbackError(t *testing.T) {
t.Parallel()
c, srv, u := newTestClient(t)
srv.SetChildrenPageSize(100)
for i := range 150 {
u.SeedFolder(u.RootID(), fmt.Sprintf("dir%03d", i))
}
stop := errors.New("stop")
calls := 0
err := c.listChildren(context.Background(), c.rootID(), func([]*node) error {
calls++
return stop
})
assert.ErrorIs(t, err, stop)
assert.Equal(t, 1, calls)
// Nothing was cached as the complete listing.
srv.ResetRequests()
require.Len(t, listAll(t, c, c.rootID()), 150)
assert.NotZero(t, totalRequests(srv))
}
func TestListCancel(t *testing.T) {
c, srv, u := newTestClient(t)
srv.SetChildrenPageSize(100)
for i := range 300 {
u.SeedFolder(u.RootID(), fmt.Sprintf("dir%03d", i))
}
srv.Inject(protontest.Fault{Method: "POST", Pattern: "/drive/v2/volumes/{volumeID}/links", Delay: 10 * time.Second})
baseline := runtime.NumGoroutine()
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
defer cancel()
start := time.Now()
err := c.listChildren(ctx, c.rootID(), func([]*node) error { return nil })
assert.ErrorIs(t, err, context.DeadlineExceeded)
assert.Less(t, time.Since(start), 2*time.Second)
// Idle HTTP connections may linger a moment.
n := runtime.NumGoroutine()
for deadline := time.Now().Add(5 * time.Second); n > baseline && time.Now().Before(deadline); n = runtime.NumGoroutine() {
time.Sleep(50 * time.Millisecond)
}
assert.LessOrEqual(t, n, baseline)
}
func TestAbout(t *testing.T) {
t.Parallel()
c, _, u := newTestClient(t)
used, total, err := c.about(context.Background())
require.NoError(t, err)
assert.Zero(t, used)
assert.Equal(t, protontest.DefaultMaxSpace, total)
u.SeedFile(u.RootID(), "file.txt", []byte(strings.Repeat("x", 1000)), time.Now())
n, err := c.findChild(context.Background(), c.rootID(), "file.txt")
require.NoError(t, err)
used, total, err = c.about(context.Background())
require.NoError(t, err)
assert.Equal(t, n.EncryptedSize, used)
assert.Equal(t, protontest.DefaultMaxSpace, total)
}
func TestLegacyFileReadable(t *testing.T) {
t.Parallel()
c, _, u := newTestClient(t)
content := []byte("written by an older client")
before := time.Now().Truncate(time.Second)
id := u.SeedLegacyFile(u.RootID(), "old.txt", content)
listed := listAll(t, c, c.rootID())
require.Len(t, listed, 1)
n := listed["old.txt"]
require.NotNil(t, n)
assert.Equal(t, id, n.ID)
assert.Equal(t, int64(len(content)), n.size(true))
assert.Equal(t, sha1Hex(content), n.sha1())
assert.False(t, n.modTime().Before(before), "modTime %v", n.modTime())
assert.False(t, c.reported["verify:"+id])
assert.False(t, c.reported["decrypt:"+id])
}
// trashedPrefix marks trashed nodes in the map requireDump returns.
const trashedPrefix = "(trashed) "
// requireDump returns the nodes of u's drive by path, trashed ones
// under trashedPrefix plus their path, failing the test if any of them
// can't be decrypted or verified by the fake.
func requireDump(t *testing.T, u *protontest.User) map[string]protontest.DumpedNode {
t.Helper()
out := make(map[string]protontest.DumpedNode)
for _, d := range u.Dump() {
require.NoError(t, d.Err, "%s (ID %s)", d.Path, d.ID)
key := d.Path
if d.State == api.LinkStateTrashed {
key = trashedPrefix + key
}
require.NotContains(t, out, key)
out[key] = d
}
return out
}
// requirePaths fails the test unless dump holds exactly paths.
func requirePaths(t *testing.T, dump map[string]protontest.DumpedNode, paths ...string) {
t.Helper()
var got []string
for p := range dump {
got = append(got, p)
}
assert.ElementsMatch(t, paths, got)
}
func TestCreateFolder(t *testing.T) {
t.Parallel()
c, srv, u := newTestClient(t)
ctx := context.Background()
modTime := time.Date(2024, 5, 6, 7, 8, 9, 123e6, time.UTC)
dir, err := c.createFolder(ctx, c.rootID(), "new folder", modTime)
require.NoError(t, err)
assert.True(t, dir.IsFolder)
assert.Equal(t, "new folder", dir.Name)
assert.Equal(t, c.rootID(), dir.ParentID)
assert.True(t, modTime.Equal(dir.modTime()), "modTime %v", dir.modTime())
assert.NotEmpty(t, dir.hashKey)
sub, err := c.createFolder(ctx, dir.ID, "sub", time.Time{})
require.NoError(t, err)
assert.Equal(t, dir.ID, sub.ParentID)
dump := requireDump(t, u)
requirePaths(t, dump, "new folder", "new folder/sub")
assert.Equal(t, dir.ID, dump["new folder"].ID)
assert.True(t, dump["new folder"].IsFolder)
assert.True(t, modTime.Equal(dump["new folder"].ModTime), "modTime %v", dump["new folder"].ModTime)
assert.Equal(t, sub.ID, dump["new folder/sub"].ID)
assert.True(t, dump["new folder/sub"].ModTime.IsZero())
// Another client reads what was written.
other := newTestClientFor(t, srv, u, clientOptions{})
listed := listAll(t, other, other.rootID())
require.Contains(t, listed, "new folder")
assert.Equal(t, dir.ID, listed["new folder"].ID)
assert.True(t, modTime.Equal(listed["new folder"].modTime()))
assert.Equal(t, dir.hashKey, listed["new folder"].hashKey)
assert.Contains(t, listAll(t, other, dir.ID), "sub")
_, err = c.createFolder(ctx, c.rootID(), "a/b", time.Time{})
assert.Error(t, err)
_, err = c.createFolder(ctx, "no-such-folder", "x", time.Time{})
assert.ErrorIs(t, err, errNotFound)
requirePaths(t, requireDump(t, u), "new folder", "new folder/sub")
}
func TestCreateFolderExists(t *testing.T) {
t.Parallel()
c, _, u := newTestClient(t)
u.SeedFolder(u.RootID(), "dir")
u.SeedFile(u.RootID(), "file", []byte("x"), time.Now())
// A Docs document isn't listed, so only the server knows the name
// is taken.
u.SeedDoc(u.RootID(), "doc")
for _, name := range []string{"dir", "file", "doc"} {
_, err := c.createFolder(context.Background(), c.rootID(), name, time.Time{})
assert.ErrorIs(t, err, errExists, name)
}
requirePaths(t, requireDump(t, u), "dir", "file", "doc")
}
func TestRename(t *testing.T) {
t.Parallel()
c, _, u := newTestClient(t)
ctx := context.Background()
content := []byte("renamed content")
fileID := u.SeedFile(u.RootID(), "old.txt", content, time.Now())
dirID := u.SeedFolder(u.RootID(), "dir")
u.SeedFile(dirID, "child", []byte("child"), time.Now())
file, err := c.getNode(ctx, fileID)
require.NoError(t, err)
require.NoError(t, c.rename(ctx, file, "new.txt"))
dump := requireDump(t, u)
requirePaths(t, dump, "new.txt", "dir", "dir/child")
assert.Equal(t, content, dump["new.txt"].Content)
got, err := c.getNode(ctx, fileID)
require.NoError(t, err)
assert.Equal(t, "new.txt", got.Name)
dir, err := c.getNode(ctx, dirID)
require.NoError(t, err)
require.NoError(t, c.rename(ctx, dir, "renamed dir"))
dump = requireDump(t, u)
requirePaths(t, dump, "new.txt", "renamed dir", "renamed dir/child")
assert.Equal(t, []byte("child"), dump["renamed dir/child"].Content)
// The server refuses a rename of a node whose name changed since
// it was read.
err = c.rename(ctx, file, "again")
assert.Error(t, err)
assert.NotErrorIs(t, err, errExists)
err = c.rename(ctx, got, "renamed dir")
assert.ErrorIs(t, err, errExists)
assert.Error(t, c.rename(ctx, c.root, "root"))
assert.Error(t, c.rename(ctx, got, ""))
requirePaths(t, requireDump(t, u), "new.txt", "renamed dir", "renamed dir/child")
}
func TestMove(t *testing.T) {
t.Parallel()
c, _, u := newTestClient(t)
ctx := context.Background()
aID := u.SeedFolder(u.RootID(), "a")
bID := u.SeedFolder(u.RootID(), "b")
fileID := u.SeedFile(aID, "f.txt", []byte("file"), time.Now())
subID := u.SeedFolder(aID, "sub")
u.SeedFile(subID, "g", []byte("deep"), time.Now())
anonID := u.SeedAnonymousFile(aID, "anon", []byte("anonymous"), time.Now())
requireDump(t, u)
file, err := c.getNode(ctx, fileID)
require.NoError(t, err)
require.NoError(t, c.move(ctx, file, bID, "f.txt"))
sub, err := c.getNode(ctx, subID)
require.NoError(t, err)
require.NoError(t, c.move(ctx, sub, bID, "sub2"))
dump := requireDump(t, u)
requirePaths(t, dump, "a", "a/anon", "b", "b/f.txt", "b/sub2", "b/sub2/g")
assert.Equal(t, []byte("file"), dump["b/f.txt"].Content)
assert.Equal(t, []byte("deep"), dump["b/sub2/g"].Content)
moved, err := c.getNode(ctx, fileID)
require.NoError(t, err)
assert.Equal(t, bID, moved.ParentID)
require.NoError(t, c.move(ctx, moved, c.rootID(), "top.txt"))
requirePaths(t, requireDump(t, u), "a", "a/anon", "b", "top.txt", "b/sub2", "b/sub2/g")
// An anonymous node is signed by the mover.
anon, err := c.getNode(ctx, anonID)
require.NoError(t, err)
require.Empty(t, anon.link.Link.SignatureEmail)
require.NoError(t, c.move(ctx, anon, bID, "anon"))
dump = requireDump(t, u)
assert.Equal(t, []byte("anonymous"), dump["b/anon"].Content)
anon, err = c.getNode(ctx, anonID)
require.NoError(t, err)
assert.Equal(t, u.Email(), anon.link.Link.SignatureEmail)
assert.Equal(t, u.Email(), anon.link.Link.NameSignatureEmail)
_, err = c.getNode(ctx, "no-such-node")
require.ErrorIs(t, err, errNotFound)
assert.Error(t, c.move(ctx, c.root, aID, "root"))
assert.ErrorIs(t, c.move(ctx, anon, "no-such-folder", "anon"), errNotFound)
}
func TestMoveExists(t *testing.T) {
t.Parallel()
c, _, u := newTestClient(t)
ctx := context.Background()
aID := u.SeedFolder(u.RootID(), "a")
bID := u.SeedFolder(u.RootID(), "b")
fileID := u.SeedFile(aID, "x", []byte("a"), time.Now())
u.SeedFile(bID, "x", []byte("b"), time.Now())
u.SeedDoc(bID, "doc")
file, err := c.getNode(ctx, fileID)
require.NoError(t, err)
assert.ErrorIs(t, c.move(ctx, file, bID, "x"), errExists)
assert.ErrorIs(t, c.move(ctx, file, bID, "doc"), errExists)
dump := requireDump(t, u)
requirePaths(t, dump, "a", "a/x", "b", "b/x", "b/doc")
assert.Equal(t, []byte("a"), dump["a/x"].Content)
}
func TestMoveIntoSelf(t *testing.T) {
t.Parallel()
c, _, u := newTestClient(t)
ctx := context.Background()
aID := u.SeedFolder(u.RootID(), "a")
subID := u.SeedFolder(aID, "sub")
a, err := c.getNode(ctx, aID)
require.NoError(t, err)
for _, target := range []string{aID, subID} {
err := c.move(ctx, a, target, "a")
assert.Error(t, err)
assert.NotErrorIs(t, err, errExists)
}
requirePaths(t, requireDump(t, u), "a", "a/sub")
}
func TestCopy(t *testing.T) {
t.Parallel()
c, _, u := newTestClient(t)
ctx := context.Background()
modTime := time.Date(2023, 1, 2, 3, 4, 5, 0, time.UTC)
aID := u.SeedFolder(u.RootID(), "a")
bID := u.SeedFolder(u.RootID(), "b")
fileID := u.SeedFile(aID, "f.txt", []byte("content"), modTime)
anonID := u.SeedAnonymousFile(aID, "anon", []byte("anonymous"), modTime)
dirID := u.SeedFolder(aID, "dir")
u.SeedFile(dirID, "child", []byte("child"), modTime)
file, err := c.getNode(ctx, fileID)
require.NoError(t, err)
cp, err := c.copyNode(ctx, file, bID, "copy.txt")
require.NoError(t, err)
assert.NotEqual(t, fileID, cp.ID)
assert.Equal(t, "copy.txt", cp.Name)
assert.Equal(t, bID, cp.ParentID)
assert.Equal(t, file.sha1(), cp.sha1())
assert.True(t, modTime.Equal(cp.modTime()))
same, err := c.copyNode(ctx, file, aID, "f2.txt")
require.NoError(t, err)
_, err = c.copyNode(ctx, file, aID, "f.txt")
assert.ErrorIs(t, err, errExists)
anon, err := c.getNode(ctx, anonID)
require.NoError(t, err)
anonCopy, err := c.copyNode(ctx, anon, bID, "anon")
require.NoError(t, err)
assert.Equal(t, u.Email(), anonCopy.link.Link.SignatureEmail)
dir, err := c.getNode(ctx, dirID)
require.NoError(t, err)
_, err = c.copyNode(ctx, dir, bID, "dir copy")
require.NoError(t, err)
dump := requireDump(t, u)
requirePaths(t, dump, "a", "a/f.txt", "a/f2.txt", "a/anon", "a/dir", "a/dir/child",
"b", "b/copy.txt", "b/anon", "b/dir copy", "b/dir copy/child")
assert.Equal(t, fileID, dump["a/f.txt"].ID)
assert.Equal(t, cp.ID, dump["b/copy.txt"].ID)
assert.Equal(t, same.ID, dump["a/f2.txt"].ID)
for _, p := range []string{"a/f.txt", "a/f2.txt", "b/copy.txt"} {
assert.Equal(t, []byte("content"), dump[p].Content, p)
}
assert.Equal(t, []byte("anonymous"), dump["b/anon"].Content)
assert.Equal(t, []byte("child"), dump["b/dir copy/child"].Content)
assert.NotEqual(t, dump["a/dir/child"].ID, dump["b/dir copy/child"].ID)
}
func TestTrash(t *testing.T) {
t.Parallel()
c, _, u := newTestClient(t)
ctx := context.Background()
fileID := u.SeedFile(u.RootID(), "f", []byte("f"), time.Now())
dirID := u.SeedFolder(u.RootID(), "d")
u.SeedFile(dirID, "child", []byte("child"), time.Now())
u.SeedFile(u.RootID(), "kept", []byte("kept"), time.Now())
require.Len(t, listAll(t, c, c.rootID()), 3)
require.NoError(t, c.trash(ctx, fileID, dirID))
dump := requireDump(t, u)
requirePaths(t, dump, trashedPrefix+"f", trashedPrefix+"d", "d/child", "kept")
listed := listAll(t, c, c.rootID())
assert.Len(t, listed, 1)
assert.Contains(t, listed, "kept")
// The names of trashed nodes are free again.
_, err := c.createFolder(ctx, c.rootID(), "d", time.Time{})
require.NoError(t, err)
_, err = c.createFolder(ctx, c.rootID(), "f", time.Time{})
require.NoError(t, err)
requirePaths(t, requireDump(t, u), trashedPrefix+"f", trashedPrefix+"d", "d/child", "kept", "d", "f")
require.NoError(t, c.trash(ctx))
}
func TestTrashMissing(t *testing.T) {
t.Parallel()
c, srv, u := newTestClient(t)
ctx := context.Background()
fileID := u.SeedFile(u.RootID(), "f", []byte("f"), time.Now())
err := c.trash(ctx, "no-such-node")
assert.ErrorIs(t, err, errNotFound)
err = c.trash(ctx, "missing-1", fileID, "missing-2")
assert.ErrorIs(t, err, errNotFound)
assert.Contains(t, err.Error(), "missing-1")
assert.Contains(t, err.Error(), "missing-2")
assert.NotContains(t, err.Error(), fileID)
requirePaths(t, requireDump(t, u), trashedPrefix+"f")
// Requests name at most metadataBatchSize nodes.
srv.ResetRequests()
ids := make([]string, metadataBatchSize+1)
for i := range ids {
ids[i] = fmt.Sprintf("missing-%d", i)
}
err = c.trash(ctx, ids...)
assert.ErrorIs(t, err, errNotFound)
assert.Contains(t, err.Error(), ids[metadataBatchSize])
assert.Equal(t, 2, srv.Requests()["POST /drive/v2/volumes/{volumeID}/trash_multiple"])
}
func TestEmptyTrash(t *testing.T) {
t.Parallel()
c, _, u := newTestClient(t)
ctx := context.Background()
fileID := u.SeedFile(u.RootID(), "f", []byte("f"), time.Now())
dirID := u.SeedFolder(u.RootID(), "d")
childID := u.SeedFile(dirID, "child", []byte("child"), time.Now())
u.SeedFile(u.RootID(), "kept", []byte("kept"), time.Now())
child, err := c.getNode(ctx, childID)
require.NoError(t, err)
require.NoError(t, c.trash(ctx, fileID, dirID))
require.NoError(t, c.emptyTrash(ctx))
dump := requireDump(t, u)
requirePaths(t, dump, "kept")
assert.Equal(t, []byte("kept"), dump["kept"].Content)
// The nodes are gone, cached or not.
for _, id := range []string{fileID, dirID, child.ID} {
_, err := c.getNode(ctx, id)
assert.ErrorIs(t, err, errNotFound, id)
}
require.NoError(t, c.emptyTrash(ctx))
}
func TestMutationsInvalidateCache(t *testing.T) {
t.Parallel()
c, _, u := newTestClient(t)
ctx := context.Background()
aID := u.SeedFolder(u.RootID(), "a")
bID := u.SeedFolder(u.RootID(), "b")
fileID := u.SeedFile(aID, "f", []byte("f"), time.Now())
names := func(parentID string) []string {
var out []string
for name := range listAll(t, c, parentID) {
out = append(out, name)
}
return out
}
assert.ElementsMatch(t, []string{"a", "b"}, names(c.rootID()))
assert.ElementsMatch(t, []string{"f"}, names(aID))
assert.Empty(t, names(bID))
// Move between two listed folders, and back.
file, err := c.getNode(ctx, fileID)
require.NoError(t, err)
require.NoError(t, c.move(ctx, file, bID, "f"))
assert.Empty(t, names(aID))
assert.ElementsMatch(t, []string{"f"}, names(bID))
file, err = c.getNode(ctx, fileID)
require.NoError(t, err)
assert.Equal(t, bID, file.ParentID)
require.NoError(t, c.move(ctx, file, aID, "f"))
assert.ElementsMatch(t, []string{"f"}, names(aID))
assert.Empty(t, names(bID))
file, err = c.getNode(ctx, fileID)
require.NoError(t, err)
assert.Equal(t, aID, file.ParentID)
require.NoError(t, c.rename(ctx, file, "g"))
assert.ElementsMatch(t, []string{"g"}, names(aID))
file, err = c.getNode(ctx, fileID)
require.NoError(t, err)
assert.Equal(t, "g", file.Name)
_, err = c.createFolder(ctx, aID, "new", time.Time{})
require.NoError(t, err)
assert.ElementsMatch(t, []string{"g", "new"}, names(aID))
_, err = c.copyNode(ctx, file, bID, "copy")
require.NoError(t, err)
assert.ElementsMatch(t, []string{"copy"}, names(bID))
require.NoError(t, c.trash(ctx, fileID))
assert.ElementsMatch(t, []string{"new"}, names(aID))
file, err = c.getNode(ctx, fileID)
require.NoError(t, err)
assert.Equal(t, api.LinkStateTrashed, file.State)
require.NoError(t, c.trash(ctx, bID))
assert.ElementsMatch(t, []string{"a"}, names(c.rootID()))
requireDump(t, u)
}