Files
rclone/backend/protondrive/nodes_internal_test.go
StereotypicalCatandClaude Opus 5.5 c0bdbcde6b
build / windows (push) Skipped
build / other_os (push) Skipped
build / mac_amd64 (push) Skipped
build / mac_arm64 (push) Skipped
build / linux (push) Skipped
build / go1.26 (push) Skipped
build / linux_386 (push) Skipped
build / lint (push) Skipped
build / android-all (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/386 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/amd64 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm/v6 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm/v7 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm64 (push) Skipped
Build & Push Docker Images / Merge & Push Final Docker Image (push) Waiting for needed jobs
protondrive: rewrite the backend as a native Go client of the Proton Drive API
Replace Proton-API-Bridge and go-proton-api with a client in
backend/protondrive written against Proton's current Drive API, following
the behaviour of Proton's official Drive SDK:

- volume-based and v2 routes only
- upload block verification, signed manifests and extended attributes
- current content encryption (v4 node keys, v6 PKESK, SEIPDv2)
- browser (session fork) sign-in, with username and password still
  supported
- the volume's change events, used to keep the metadata cache current and
  for ChangeNotify, polled at most every 30 s
- an in-memory fake Proton server (protontest) so the tests run without
  an account

Uses ProtonMail/gopenpgp/v3 and ProtonMail/go-srp directly; no cgo.

Written with heavy AI assistance (Claude Code).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 23:22:46 +01:00

1354 lines
47 KiB
Go

package protondrive
import (
"context"
"crypto/sha1"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"runtime"
"strings"
"sync"
"testing"
"time"
"unicode/utf8"
"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})
ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
defer cancel()
clients := make([]*client, 2)
errs := make([]error, 2)
var wg sync.WaitGroup
for i := range clients {
wg.Go(func() {
clients[i], errs[i] = 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))
// Attributes which record no usable size leave it unknown.
n.X = &xattrs{SHA1: "ABCDEF", NoSize: true}
_, known := n.plaintextSize()
assert.False(t, known)
assert.Equal(t, int64(42), n.size(true))
}
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)
}
// TestListChildrenRepeatedPage checks a listing whose pages lead back
// to one already read fails rather than paging until ctx ends.
func TestListChildrenRepeatedPage(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddUser("user", "pass")
srv.SetChildrenPageSize(1)
for _, name := range []string{"a", "b"} {
u.SeedFolder(u.RootID(), name)
}
c := newTestClientTransport(t, srv, u, clientOptions{}, func(next http.RoundTripper) http.RoundTripper {
return roundTripFunc(func(r *http.Request) (*http.Response, error) {
if strings.HasSuffix(r.URL.Path, "/children") {
// Every page names the same anchor, as from the
// first page.
q := r.URL.Query()
q.Del("AnchorID")
r = r.Clone(r.Context())
r.URL.RawQuery = q.Encode()
}
return next.RoundTrip(r)
})
})
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err := c.listChildren(ctx, c.rootID(), func([]*node) error { return nil })
require.Error(t, err)
assert.NotErrorIs(t, err, context.DeadlineExceeded)
assert.ErrorContains(t, err, "repeated")
}
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
code int // Proton code of the *api.Error; 2000 if 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: "422 code 2028", status: 422, code: api.CodeFeatureBlocked, retry: true},
{name: "422 code 2028 with Retry-After", status: 422, code: api.CodeFeatureBlocked, header: "4", retry: true, retryAfter: 4 * time.Second},
{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)
}
code := test.code
if code == 0 {
code = api.CodeInvalidRequirements
}
err = &api.Error{Status: test.status, Code: code, 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)
// Far below the hold this guards against, with room for a slow
// runner under -race.
assert.Less(t, time.Since(start), 3*time.Second)
// 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)
// Far below the hold this guards against, with room for a slow
// runner under -race.
assert.Less(t, time.Since(start), 3*time.Second)
}
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)
}
func TestHasChildren(t *testing.T) {
t.Parallel()
c, _, u := newTestClient(t)
ctx := context.Background()
empty := u.SeedFolder(u.RootID(), "empty")
docs := u.SeedFolder(u.RootID(), "docs")
u.SeedDoc(docs, "notes")
unreadable := u.SeedFolder(u.RootID(), "unreadable")
u.Corrupt(u.SeedFile(unreadable, "x", []byte("x"), time.Now()), "name")
later := u.SeedFolder(u.RootID(), "later")
for id, want := range map[string]bool{empty: false, docs: true, unreadable: true, later: false} {
got, err := c.hasChildren(ctx, id)
require.NoError(t, err)
assert.Equal(t, want, got, id)
}
// A listing cached as empty doesn't hide a child added since.
assert.Empty(t, listAll(t, c, later))
u.SeedFile(later, "new", []byte("x"), time.Now())
got, err := c.hasChildren(ctx, later)
require.NoError(t, err)
assert.True(t, got)
_, err = c.hasChildren(ctx, "missing")
assert.Equal(t, api.CodeNotExists, apiErrorCode(err))
}
func TestActiveNode(t *testing.T) {
t.Parallel()
c, srv, u := newTestClient(t)
ctx := context.Background()
id := u.SeedFile(u.RootID(), "x", []byte("x"), time.Now())
n, err := c.activeNode(ctx, id)
require.NoError(t, err)
assert.Equal(t, "x", n.Name)
require.Len(t, listAll(t, c, c.rootID()), 1)
// Trashed by another client while this one has it cached.
other := newTestClientFor(t, srv, u, clientOptions{})
require.NoError(t, other.trash(ctx, id))
cached, err := c.getNode(ctx, id)
require.NoError(t, err)
require.Equal(t, api.LinkStateActive, cached.State, "the cache is stale")
_, err = c.activeNode(ctx, id)
assert.ErrorIs(t, err, errNotFound)
assert.Empty(t, listAll(t, c, c.rootID()), "the stale listing is dropped")
_, err = c.activeNode(ctx, "missing")
assert.ErrorIs(t, err, errNotFound)
}
// TestNewNodesKeepListing checks making a node in a listed folder adds
// it to the cached listing rather than forgetting the listing, so
// making many nodes in a folder doesn't list it again each time.
func TestNewNodesKeepListing(t *testing.T) {
t.Parallel()
c, srv, u := newTestClient(t)
ctx := context.Background()
dirID := u.SeedFolder(u.RootID(), "dir")
fileID := u.SeedFile(u.RootID(), "f.txt", []byte("content"), time.Now())
require.Empty(t, listAll(t, c, dirID))
srv.ResetRequests()
_, err := c.createFolder(ctx, dirID, "sub", time.Time{})
require.NoError(t, err)
_, err = c.upload(ctx, uploadRequest{ParentID: dirID, Name: "up.txt", In: strings.NewReader("up"), Size: 2})
require.NoError(t, err)
file, err := c.getNode(ctx, fileID)
require.NoError(t, err)
_, err = c.copyNode(ctx, file, dirID, "copy.txt")
require.NoError(t, err)
assert.Zero(t, srv.Requests()["GET /drive/v2/volumes/{volumeID}/folders/{linkID}/children"], "%v", srv.Requests())
srv.ResetRequests()
listed := listAll(t, c, dirID)
assert.Zero(t, totalRequests(srv), "listing not cached: %v", srv.Requests())
assert.Len(t, listed, 3)
for _, name := range []string{"sub", "up.txt", "copy.txt"} {
assert.Contains(t, listed, name)
}
}
// TestDecryptNodeRefusesHostileValues checks a node which decrypts but
// which the server describes with values no node can have is
// unreadable, not handed on.
func TestDecryptNodeRefusesHostileValues(t *testing.T) {
t.Parallel()
c, _, u := newTestClient(t)
ctx := context.Background()
fileID := u.SeedFile(u.RootID(), "file.txt", []byte("content"), time.Now())
rootKeys, err := c.folderKeysOf(ctx, c.rootID())
require.NoError(t, err)
for name, change := range map[string]func(d *api.LinkDetails){
"no ID": func(d *api.LinkDetails) { d.Link.LinkID = "" },
"negative encrypted size": func(d *api.LinkDetails) { d.File.ActiveRevision.EncryptedSize = -5 },
} {
t.Run(name, func(t *testing.T) {
links, err := c.fetchLinks(ctx, []string{fileID})
require.NoError(t, err)
require.Len(t, links, 1)
n, unreadable, err := c.decryptNode(ctx, &links[0], rootKeys)
require.NoError(t, err)
require.NoError(t, unreadable, "unchanged")
require.NotNil(t, n)
change(&links[0])
n, unreadable, err = c.decryptNode(ctx, &links[0], rootKeys)
require.NoError(t, err)
assert.Error(t, unreadable)
assert.Nil(t, n)
})
}
}
func TestCreatedUnderUnverifiedFolderStaysUnverified(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddUser("user", "pass")
forged := u.SeedForgedFolder(u.RootID(), "forged")
c := newTestClientFor(t, srv, u, clientOptions{EnableCaching: true, IgnoreSignatureErrors: true})
ctx := context.Background()
made, err := c.createFolder(ctx, forged, "made", time.Time{})
require.NoError(t, err)
assert.Error(t, made.keys.unverified, "made in cache")
listed := listAll(t, c, forged)
require.Contains(t, listed, "made")
assert.Error(t, listed["made"].keys.unverified, "made in the cached listing")
fresh, err := c.fetchNode(ctx, made.ID)
require.NoError(t, err)
assert.Error(t, fresh.keys.unverified, "made read afresh")
}
// TestListingRacingChange checks a listing whose pages were read
// before a change to the folder doesn't cache what it read: the next
// listing shows the change, whether a file, folder or copy was made in
// the folder or a child was trashed.
func TestListingRacingChange(t *testing.T) {
t.Parallel()
for _, test := range []struct {
name string
change func(ctx context.Context, c *client, dirID, srcID, trashID string) error
present string // a name the folder must list after the change
absent string // a name it must not
}{
{"upload", func(ctx context.Context, c *client, dirID, _, _ string) error {
_, err := c.upload(ctx, uploadRequest{ParentID: dirID, Name: "new", In: strings.NewReader("new"), Size: 3})
return err
}, "new", ""},
{"mkdir", func(ctx context.Context, c *client, dirID, _, _ string) error {
_, err := c.createFolder(ctx, dirID, "new", time.Time{})
return err
}, "new", ""},
{"copy", func(ctx context.Context, c *client, dirID, srcID, _ string) error {
src, err := c.getNode(ctx, srcID)
if err != nil {
return err
}
_, err = c.copyNode(ctx, src, dirID, "new")
return err
}, "new", ""},
{"trash", func(ctx context.Context, c *client, _, _, trashID string) error {
return c.trash(ctx, trashID)
}, "keep.txt", "trash.txt"},
} {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
c, srv, u := newTestClient(t)
ctx := context.Background()
dirID := u.SeedFolder(u.RootID(), "dir")
u.SeedFile(dirID, "keep.txt", []byte("keep"), time.Now())
trashID := u.SeedFile(dirID, "trash.txt", []byte("trash"), time.Now())
srcID := u.SeedFile(u.RootID(), "src.txt", []byte("src"), time.Now())
// Read before the listing, so its batch of children is the
// only links request held.
_, err := c.getNode(ctx, dirID)
require.NoError(t, err)
_, err = c.getNode(ctx, srcID)
require.NoError(t, err)
release := make(chan struct{})
var releaseOnce sync.Once
releaseHeld := func() { releaseOnce.Do(func() { close(release) }) }
// Released however the test ends, or the server's close
// waits for the held request for ever.
defer releaseHeld()
held := make(chan struct{}, 1)
srv.Inject(protontest.Fault{Method: "POST", Pattern: "/drive/v2/volumes/{volumeID}/links", Times: 1, Hold: release, Held: held})
listed := make(chan error, 1)
go func() {
listed <- c.listChildren(ctx, dirID, func([]*node) error { return nil })
}()
select {
case <-held:
case <-time.After(10 * time.Second):
t.Fatal("the listing's request wasn't held")
}
require.NoError(t, test.change(ctx, c, dirID, srcID, trashID))
releaseHeld()
require.NoError(t, <-listed)
got := listAll(t, c, dirID)
assert.Contains(t, got, test.present)
if test.absent != "" {
assert.NotContains(t, got, test.absent)
}
// The listing after the change is cached as usual.
srv.ResetRequests()
listAll(t, c, dirID)
assert.Zero(t, totalRequests(srv), "%v", srv.Requests())
})
}
}
func TestParentCycle(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddUser("user", "pass")
a := u.SeedFolder(u.RootID(), "a")
b := u.SeedFolder(a, "b")
self := u.SeedFolder(u.RootID(), "self")
u.SeedFile(b, "file", []byte("x"), time.Now())
u.SetParent(a, b)
u.SetParent(self, self)
c := newTestClientFor(t, srv, u, clientOptions{})
for name, id := range map[string]string{"two folders": b, "self": self} {
srv.ResetRequests()
_, err := c.getNode(context.Background(), id)
require.ErrorIs(t, err, errIntegrity, name)
assert.Contains(t, err.Error(), "its own ancestor", name)
assert.LessOrEqual(t, srv.Requests()["POST /drive/v2/volumes/{volumeID}/links"], 3, name)
}
}
func TestFolderDepthLimit(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddUser("user", "pass")
id := u.RootID()
var ids []string
for i := range 6 {
id = u.SeedFolder(id, fmt.Sprintf("d%d", i))
ids = append(ids, id)
}
c := newTestClientFor(t, srv, u, clientOptions{})
c.maxFolderDepth = 4
_, err := c.getNode(context.Background(), ids[5])
require.ErrorIs(t, err, errIntegrity)
assert.Contains(t, err.Error(), "more than 4 deep")
// The error names the node asked for and the one too deep, not
// every folder between, which a hostile server could make 2048.
assert.Equal(t, 2, strings.Count(err.Error(), "get node"), err.Error())
assert.True(t, strings.HasPrefix(err.Error(), "get node "+ids[5]+": "), err.Error())
// Within the limit is fine.
c = newTestClientFor(t, srv, u, clientOptions{})
c.maxFolderDepth = 6
_, err = c.getNode(context.Background(), ids[5])
require.NoError(t, err)
}
// TestCopyReadBackLag copies a file while the server takes a moment to
// show the copy.
func TestCopyReadBackLag(t *testing.T) {
t.Parallel()
c, srv, u := newTestClient(t)
ctx := context.Background()
fileID := u.SeedFile(u.RootID(), "f.txt", []byte("content"), time.Now())
file, err := c.getNode(ctx, fileID)
require.NoError(t, err)
srv.SetReadLag(2, protontest.LagMissing)
cp, err := c.copyNode(ctx, file, u.RootID(), "copy.txt")
require.NoError(t, err)
assert.Equal(t, "copy.txt", cp.Name)
assert.Equal(t, file.sha1(), cp.sha1())
}
func TestTruncateName(t *testing.T) {
assert.Equal(t, "short", truncateName("short"))
got := truncateName("a" + strings.Repeat("é", 40))
assert.True(t, utf8.ValidString(got), "%q", got)
assert.Equal(t, "a"+strings.Repeat("é", 31)+"...", got)
}