Files
rclone/backend/protondrive/upload_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

976 lines
37 KiB
Go

package protondrive
import (
"bytes"
"context"
"crypto/sha1"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/rclone/rclone/backend/protondrive/api"
"github.com/rclone/rclone/backend/protondrive/protontest"
"github.com/rclone/rclone/lib/pacer"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
filesPattern = "/drive/v2/volumes/{volumeID}/files"
commitPattern = "/drive/v2/volumes/{volumeID}/files/{linkID}/revisions/{revisionID}"
deleteDraftsPattern = "/drive/v2/volumes/{volumeID}/delete_multiple"
storageUploadPattern = "/storage/upload/{token}"
testDraftClientUID = "rclone-test-draft-client"
)
// newUploadClient returns a client of a new user of a new fake server
// with a draft client UID and the options opt.
func newUploadClient(t *testing.T, opt clientOptions) (*client, *protontest.Server, *protontest.User) {
t.Helper()
if opt.DraftClientUID == "" {
opt.DraftClientUID = testDraftClientUID
}
return newTestClientOpt(t, opt)
}
// testModTime is the modification time of uploaded files.
var testModTime = time.Date(2024, 5, 6, 7, 8, 9, 0, time.UTC)
// sha1Of returns the hex SHA-1 of b.
func sha1Of(b []byte) string {
sum := sha1.Sum(b)
return hex.EncodeToString(sum[:])
}
// uploadContent uploads content as name in the root with size declared
// as size.
func uploadContent(ctx context.Context, c *client, name string, in io.Reader, size int64) (*node, error) {
return c.upload(ctx, uploadRequest{
ParentID: c.rootID(),
Name: name,
In: in,
Size: size,
ModTime: testModTime,
MIMEType: "application/octet-stream",
})
}
// uploadBytes uploads content as name in the root, declaring its size.
func uploadBytes(t *testing.T, c *client, name string, content []byte) *node {
t.Helper()
n, err := uploadContent(context.Background(), c, name, bytes.NewReader(content), int64(len(content)))
require.NoError(t, err)
return n
}
// requireUploaded fails the test unless the fake decrypts and verifies
// every node of u without error, and finds the files of want, by path,
// with that content, the test modification time and its SHA1.
func requireUploaded(t *testing.T, u *protontest.User, want map[string][]byte) {
t.Helper()
dump := u.Dump()
got := make(map[string]bool)
for _, d := range dump {
require.NoError(t, d.Err, "node %q", d.Path)
content, ok := want[d.Path]
if !ok {
continue
}
got[d.Path] = true
assert.True(t, bytes.Equal(content, d.Content), "%q: content differs: %d bytes, want %d", d.Path, len(d.Content), len(content))
assert.Equal(t, sha1Of(content), d.SHA1, "%q: SHA1", d.Path)
assert.True(t, testModTime.Equal(d.ModTime), "%q: modification time %v", d.Path, d.ModTime)
}
for path := range want {
assert.True(t, got[path], "%q not in the drive", path)
}
assert.Empty(t, u.Drafts(), "drafts left")
}
// files returns the paths of the files in u's drive.
func files(u *protontest.User) []string {
var paths []string
for _, d := range u.Dump() {
if !d.IsFolder {
paths = append(paths, d.Path)
}
}
return paths
}
func TestUploadSizes(t *testing.T) {
t.Parallel()
c, srv, u := newUploadClient(t, clientOptions{})
want := make(map[string][]byte)
for _, size := range []int{0, 1, 4<<20 - 1, 4 << 20, 4<<20 + 1, bigSize} {
t.Run(strconv.Itoa(size), func(t *testing.T) {
name := "f" + strconv.Itoa(size)
content := testContent(size)
want[name] = content
srv.ResetRequests()
n := uploadBytes(t, c, name, content)
blocks := (size + 4<<20 - 1) / (4 << 20)
assert.Equal(t, blocks, srv.Requests()["POST "+storageUploadPattern], "blocks uploaded")
assert.Equal(t, name, n.Name)
assert.Equal(t, int64(size), n.size(true))
assert.Equal(t, sha1Of(content), n.sha1())
assert.True(t, testModTime.Equal(n.modTime()))
require.NotNil(t, n.X)
assert.Len(t, n.X.BlockSizes, blocks)
})
}
requireUploaded(t, u, want)
}
func TestUploadUnknownSize(t *testing.T) {
t.Parallel()
c, _, u := newUploadClient(t, clientOptions{})
want := make(map[string][]byte)
for _, size := range []int{0, 5 << 20} {
name := "f" + strconv.Itoa(size)
want[name] = testContent(size)
n, err := uploadContent(context.Background(), c, name, bytes.NewReader(want[name]), -1)
require.NoError(t, err)
assert.Equal(t, int64(size), n.size(true))
}
requireUploaded(t, u, want)
}
func TestUploadNewRevision(t *testing.T) {
t.Parallel()
c, _, u := newUploadClient(t, clientOptions{})
first := uploadBytes(t, c, "f", testContent(5<<20))
content := []byte("new content")
n, err := c.upload(context.Background(), uploadRequest{
Existing: first,
In: bytes.NewReader(content),
Size: int64(len(content)),
ModTime: testModTime,
SHA1: sha1Of(content),
})
require.NoError(t, err)
assert.Equal(t, first.ID, n.ID)
assert.NotEqual(t, first.RevisionID, n.RevisionID)
requireUploaded(t, u, map[string][]byte{"f": content})
assert.Equal(t, []string{"f"}, files(u))
old, err := c.revisionBlocks(context.Background(), first, 1, 1)
require.NoError(t, err)
assert.Equal(t, 2, old.State, "old revision not superseded")
}
func TestUploadOverExistingNameCreatesRevision(t *testing.T) {
t.Parallel()
c, _, u := newUploadClient(t, clientOptions{})
first := uploadBytes(t, c, "f", []byte("first"))
n := uploadBytes(t, c, "f", []byte("second"))
assert.Equal(t, first.ID, n.ID)
assert.NotEqual(t, first.RevisionID, n.RevisionID)
requireUploaded(t, u, map[string][]byte{"f": []byte("second")})
assert.Equal(t, []string{"f"}, files(u))
// A folder in the way is not replaced.
_, err := c.createFolder(context.Background(), c.rootID(), "dir", time.Time{})
require.NoError(t, err)
_, err = uploadContent(context.Background(), c, "dir", strings.NewReader("x"), 1)
assert.ErrorIs(t, err, errExists)
assert.Empty(t, u.Drafts())
}
// testSourceMismatch uploads actual bytes declared as 5 MiB, which must
// fail cleanly.
func testSourceMismatch(t *testing.T, actual int) {
c, srv, u := newUploadClient(t, clientOptions{})
goroutines, buffers := leakBaseline(srv)
_, err := uploadContent(context.Background(), c, "f", bytes.NewReader(testContent(actual)), 5<<20)
assert.ErrorIs(t, err, errUploadMismatch)
assert.Empty(t, u.Drafts())
assert.Empty(t, files(u))
requireNoLeaks(t, srv, goroutines, buffers)
}
func TestUploadShortSource(t *testing.T) {
testSourceMismatch(t, 3<<20)
testSourceMismatch(t, 0)
}
func TestUploadLongSource(t *testing.T) {
testSourceMismatch(t, 6<<20)
testSourceMismatch(t, 9<<20)
}
func TestUploadSHA1Mismatch(t *testing.T) {
t.Parallel()
c, _, u := newUploadClient(t, clientOptions{})
content := testContent(1000)
_, err := c.upload(context.Background(), uploadRequest{
ParentID: c.rootID(), Name: "f", In: bytes.NewReader(content), Size: 1000,
SHA1: sha1Of([]byte("something else")),
})
assert.ErrorIs(t, err, errUploadMismatch)
assert.Empty(t, u.Drafts())
assert.Empty(t, files(u))
_, err = c.upload(context.Background(), uploadRequest{
ParentID: c.rootID(), Name: "f", In: bytes.NewReader(content), Size: 1000,
ModTime: testModTime, SHA1: strings.ToUpper(sha1Of(content)),
})
require.NoError(t, err)
requireUploaded(t, u, map[string][]byte{"f": content})
}
func TestUploadBlock502Once(t *testing.T) {
t.Parallel()
c, srv, u := newUploadClient(t, clientOptions{})
srv.Inject(protontest.Fault{Method: "POST", Pattern: storageUploadPattern, Status: http.StatusBadGateway, Times: 1})
srv.ResetRequests()
content := testContent(5 << 20)
uploadBytes(t, c, "f", content)
requireUploaded(t, u, map[string][]byte{"f": content})
assert.Equal(t, 3, srv.Requests()["POST "+storageUploadPattern], "two blocks and the resent one")
}
func TestRefusedCommit(t *testing.T) {
for _, test := range []struct {
name string
err error
want bool
}{
{"422 with a code", &api.Error{Status: 422, Code: api.CodeInvalidRequirements}, true},
{"408 with a code", &api.Error{Status: 408, Code: api.CodeInvalidRequirements}, false},
{"422 without a code", &api.Error{Status: 422}, false},
{"500 with a code", &api.Error{Status: 500, Code: api.CodeInvalidRequirements}, false},
{"200 with a code", &api.Error{Status: 200, Code: api.CodeInvalidRequirements}, false},
{"network error", io.ErrUnexpectedEOF, false},
} {
t.Run(test.name, func(t *testing.T) {
assert.Equal(t, test.want, refusedCommit(fmt.Errorf("commit: %w", test.err)))
})
}
}
// TestUploadBlock502Forever is issue 10224: a block which can't be
// uploaded must fail the upload, not hang it.
func TestUploadBlock502Forever(t *testing.T) {
c, srv, u := newUploadClient(t, clientOptions{})
goroutines, buffers := leakBaseline(srv)
srv.Inject(protontest.Fault{Method: "POST", Pattern: storageUploadPattern, Status: http.StatusBadGateway})
start := time.Now()
_, err := uploadContent(context.Background(), c, "f", bytes.NewReader(testContent(9<<20)), 9<<20)
require.Error(t, err)
assert.Less(t, time.Since(start), 30*time.Second)
var apiErr *api.Error
require.ErrorAs(t, err, &apiErr)
assert.Equal(t, http.StatusBadGateway, apiErr.Status)
assert.Empty(t, u.Drafts())
requireNoLeaks(t, srv, goroutines, buffers)
}
func TestUploadStorageTokenExpired(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddUser("user", "pass")
var expired atomic.Bool
c := newTestClientTransport(t, srv, u, clientOptions{DraftClientUID: testDraftClientUID}, func(next http.RoundTripper) http.RoundTripper {
return roundTripFunc(func(r *http.Request) (*http.Response, error) {
if strings.HasPrefix(r.URL.Path, "/storage/upload/") && !expired.Swap(true) {
srv.ExpireUploadTokens()
}
return next.RoundTrip(r)
})
})
content := testContent(9 << 20)
uploadBytes(t, c, "f", content)
assert.Greater(t, srv.Requests()["POST /drive/blocks"], 1, "no new URL requested")
assert.Greater(t, srv.Requests()["POST "+storageUploadPattern], 3, "no upload refused")
requireUploaded(t, u, map[string][]byte{"f": content})
}
func TestUploadCommitErrorButCommitted(t *testing.T) {
t.Parallel()
c, srv, u := newUploadClient(t, clientOptions{})
srv.Inject(protontest.Fault{Method: "PUT", Pattern: commitPattern, Status: http.StatusBadGateway, AfterHandler: true, Times: 1})
content := testContent(1 << 20)
n := uploadBytes(t, c, "f", content)
assert.Equal(t, 2, srv.Requests()["PUT "+commitPattern], "commit not retried")
assert.Equal(t, "f", n.Name)
requireUploaded(t, u, map[string][]byte{"f": content})
assert.Equal(t, []string{"f"}, files(u))
}
func TestUploadDraftResponseLost(t *testing.T) {
t.Parallel()
c, srv, u := newUploadClient(t, clientOptions{})
srv.Inject(protontest.Fault{Method: "POST", Pattern: filesPattern, Status: http.StatusBadGateway, AfterHandler: true, Times: 1})
content := testContent(1000)
uploadBytes(t, c, "f", content)
assert.Equal(t, 3, srv.Requests()["POST "+filesPattern], "draft creation: first, retry, after deleting the draft")
requireUploaded(t, u, map[string][]byte{"f": content})
assert.Equal(t, []string{"f"}, files(u))
}
// leaveDraft makes an upload of name by c fail at commit and its
// cleanup fail too, leaving its draft behind.
func leaveDraft(t *testing.T, c *client, srv *protontest.Server, u *protontest.User, name string) {
t.Helper()
srv.Inject(protontest.Fault{Method: "PUT", Pattern: commitPattern, Status: http.StatusUnprocessableEntity, Code: api.CodeInvalidValue, Times: 1})
srv.Inject(protontest.Fault{Method: "POST", Pattern: deleteDraftsPattern, Status: http.StatusUnprocessableEntity, Code: api.CodeInvalidValue, Times: 1})
_, err := uploadContent(context.Background(), c, name, strings.NewReader("draft"), 5)
require.Error(t, err)
require.Len(t, u.Drafts(), 1)
}
// TestUploadOwnDraftReplaced is issue 9622: a draft left by a failed
// upload must not block the next upload of the name.
func TestUploadOwnDraftReplaced(t *testing.T) {
t.Parallel()
c, srv, u := newUploadClient(t, clientOptions{})
leaveDraft(t, c, srv, u, "f")
content := testContent(1000)
uploadBytes(t, c, "f", content)
requireUploaded(t, u, map[string][]byte{"f": content})
assert.Equal(t, []string{"f"}, files(u))
}
func TestUploadForeignDraft(t *testing.T) {
t.Parallel()
other, srv, u := newUploadClient(t, clientOptions{DraftClientUID: "another client"})
leaveDraft(t, other, srv, u, "f")
c := newTestClientFor(t, srv, u, clientOptions{DraftClientUID: testDraftClientUID})
_, err := uploadContent(context.Background(), c, "f", strings.NewReader("x"), 1)
assert.ErrorIs(t, err, errExists)
assert.Len(t, u.Drafts(), 1, "another client's draft deleted")
// Without a draft client UID no draft is the client's own.
anon := newTestClientFor(t, srv, u, clientOptions{})
_, err = uploadContent(context.Background(), anon, "f", strings.NewReader("x"), 1)
assert.ErrorIs(t, err, errExists)
replacer := newTestClientFor(t, srv, u, clientOptions{DraftClientUID: testDraftClientUID, ReplaceExistingDraft: true})
content := testContent(1000)
uploadBytes(t, replacer, "f", content)
requireUploaded(t, u, map[string][]byte{"f": content})
assert.Equal(t, []string{"f"}, files(u))
}
func TestUploadCancel(t *testing.T) {
for _, tc := range []struct {
name string
fault protontest.Fault
drafts int // drafts left: a cancelled commit may have taken effect
}{
{"draft", protontest.Fault{Method: "POST", Pattern: filesPattern}, 0},
{"blocks", protontest.Fault{Method: "POST", Pattern: storageUploadPattern, Skip: 1}, 0},
{"commit", protontest.Fault{Method: "PUT", Pattern: commitPattern}, 1},
} {
t.Run(tc.name, func(t *testing.T) {
c, srv, u := newUploadClient(t, clientOptions{})
goroutines, buffers := leakBaseline(srv)
tc.fault.Delay = time.Minute
srv.Inject(tc.fault)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
start := time.Now()
_, err := uploadContent(ctx, c, "f", bytes.NewReader(testContent(9<<20)), 9<<20)
assert.ErrorIs(t, err, context.DeadlineExceeded)
assert.Less(t, time.Since(start), 10*time.Second)
assert.Len(t, u.Drafts(), tc.drafts)
assert.Empty(t, files(u))
requireNoLeaks(t, srv, goroutines, buffers)
})
}
}
func TestUploadConcurrencyBound(t *testing.T) {
t.Run("PerFile", func(t *testing.T) {
t.Parallel()
c, srv, u := newUploadClient(t, clientOptions{UploadConcurrency: 2})
srv.Inject(protontest.Fault{Method: "POST", Pattern: storageUploadPattern, Delay: 200 * time.Millisecond})
content := testContent(12<<20 + 1)
uploadBytes(t, c, "f", content)
assert.LessOrEqual(t, srv.StorageUploadPeak(), 2)
requireUploaded(t, u, map[string][]byte{"f": content})
})
t.Run("PerClient", func(t *testing.T) {
t.Parallel()
c, srv, u := newUploadClient(t, clientOptions{UploadConcurrency: maxUploadConcurrency})
srv.Inject(protontest.Fault{Method: "POST", Pattern: storageUploadPattern, Delay: 300 * time.Millisecond})
want := make(map[string][]byte)
var wg sync.WaitGroup
errs := make([]error, 16)
for i := range errs {
name := "f" + strconv.Itoa(i)
content := testContent(1000 + i)
want[name] = content
wg.Go(func() {
_, errs[i] = uploadContent(context.Background(), c, name, bytes.NewReader(content), int64(len(content)))
})
}
wg.Wait()
for _, err := range errs {
require.NoError(t, err)
}
peak := srv.StorageUploadPeak()
assert.LessOrEqual(t, peak, blocksInFlight)
assert.Greater(t, peak, 1, "uploads not concurrent")
requireUploaded(t, u, want)
})
}
func TestUploadVerifierChecked(t *testing.T) {
t.Parallel()
c, _, u := newUploadClient(t, clientOptions{})
c.verifierHook = func(token []byte) { token[0] ^= 1 }
_, err := uploadContent(context.Background(), c, "f", bytes.NewReader(testContent(1000)), 1000)
require.Error(t, err)
assert.Equal(t, api.CodeInvalidRequirements, apiErrorCode(err))
assert.Contains(t, err.Error(), "verifier token")
assert.Empty(t, u.Drafts())
assert.Empty(t, files(u))
}
func TestUploadClockSkew(t *testing.T) {
t.Parallel()
for _, skew := range []time.Duration{3 * time.Hour, -3 * time.Hour} {
t.Run(skew.String(), func(t *testing.T) {
srv := protontest.New(t)
srv.SetClockSkew(skew)
u := srv.AddUser("user", "pass")
c := newTestClientFor(t, srv, u, clientOptions{DraftClientUID: testDraftClientUID})
first := uploadBytes(t, c, "f", []byte("first"))
content := testContent(5 << 20)
_, err := c.upload(context.Background(), uploadRequest{Existing: first, In: bytes.NewReader(content), Size: -1, ModTime: testModTime})
require.NoError(t, err)
requireUploaded(t, u, map[string][]byte{"f": content})
})
}
}
func TestUploadThenDownload(t *testing.T) {
t.Parallel()
c, _, u := newUploadClient(t, clientOptions{})
content := testContent(bigSize)
n := uploadBytes(t, c, "f", content)
data, err := readRange(t, c, n, 0, -1)
require.NoError(t, err)
assert.True(t, bytes.Equal(content, data), "content differs")
data, err = readRange(t, c, n, bigSize-1, -1)
require.NoError(t, err)
assert.Equal(t, content[bigSize-1:], data)
requireUploaded(t, u, map[string][]byte{"f": content})
}
func TestIntendedUploadSize(t *testing.T) {
ptr := func(v int64) *int64 { return &v }
for _, tc := range []struct {
size int64
draft, revise *int64
}{
{-1, nil, nil},
{0, nil, nil},
{1, nil, ptr(4095)},
{4096, nil, ptr(100_000)},
{150_000, nil, ptr(100_000)},
{199_999, nil, ptr(100_000)},
{200_000, ptr(200_000), ptr(200_000)},
{9_876_543, ptr(9_800_000), ptr(9_800_000)},
} {
assert.Equal(t, tc.draft, draftIntendedSize(tc.size), "draft %d", tc.size)
assert.Equal(t, tc.revise, revisionIntendedSize(tc.size), "revision %d", tc.size)
}
}
// TestAcquireTokenCancel checks a cancelled wait for a token returns at
// once and gives the token back when it gets it.
func TestAcquireTokenCancel(t *testing.T) {
td := pacer.NewTokenDispenser(1)
td.Get()
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error)
go func() { done <- acquireToken(ctx, td) }()
time.Sleep(20 * time.Millisecond)
cancel()
select {
case err := <-done:
assert.ErrorIs(t, err, context.Canceled)
case <-time.After(5 * time.Second):
t.Fatal("cancelled wait for a token didn't return")
}
td.Put()
got := make(chan error)
go func() { got <- acquireToken(context.Background(), td) }()
select {
case err := <-got:
require.NoError(t, err)
case <-time.After(5 * time.Second):
t.Fatal("token kept by the cancelled wait")
}
assert.True(t, errors.Is(acquireToken(ctx, td), context.Canceled))
}
const (
linksPattern = "/drive/v2/volumes/{volumeID}/links"
deleteRevisionRequest = "DELETE " + commitPattern
deleteDraftsRequest = "POST " + deleteDraftsPattern
)
// TestUploadCancelDuringCommit cancels an upload while a commit which
// the server makes is in flight: the committed file must not be deleted.
func TestUploadCancelDuringCommit(t *testing.T) {
t.Parallel()
for _, revision := range []bool{false, true} {
t.Run("revision="+strconv.FormatBool(revision), func(t *testing.T) {
srv := protontest.New(t)
u := srv.AddUser("user", "pass")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var armed atomic.Bool
c := newTestClientTransport(t, srv, u, clientOptions{DraftClientUID: testDraftClientUID}, func(next http.RoundTripper) http.RoundTripper {
return roundTripFunc(func(r *http.Request) (*http.Response, error) {
if !armed.Load() || r.Method != "PUT" || !strings.Contains(r.URL.Path, "/revisions/") {
return next.RoundTrip(r)
}
// The server commits, then the caller gives up
// before the response arrives.
resp, err := next.RoundTrip(r)
if err == nil {
_ = resp.Body.Close()
}
cancel()
return nil, context.Canceled
})
})
var existing *node
if revision {
existing = uploadBytes(t, c, "f", []byte("old"))
}
srv.ResetRequests()
armed.Store(true)
content := testContent(5 << 20)
_, err := c.upload(ctx, uploadRequest{ParentID: c.rootID(), Name: "f", Existing: existing, In: bytes.NewReader(content), Size: int64(len(content)), ModTime: testModTime})
require.NoError(t, err, "a commit which is active is a success")
reqs := srv.Requests()
assert.Zero(t, reqs[deleteDraftsRequest], "draft deletion sent")
assert.Zero(t, reqs[deleteRevisionRequest], "revision deletion sent")
requireUploaded(t, u, map[string][]byte{"f": content})
})
}
}
// TestUploadCommitOutcomeUnknown makes the commit fail without a
// refusal and the read which would tell whether it took effect fail
// too: nothing may be deleted, and the error must say the outcome is
// unknown.
func TestUploadCommitOutcomeUnknown(t *testing.T) {
t.Parallel()
c, srv, u := newUploadClient(t, clientOptions{})
srv.Inject(protontest.Fault{Method: "PUT", Pattern: commitPattern, Status: http.StatusUnprocessableEntity})
srv.Inject(protontest.Fault{Method: "POST", Pattern: linksPattern, Status: http.StatusUnprocessableEntity, Code: api.CodeInvalidValue})
_, err := uploadContent(context.Background(), c, "f", strings.NewReader("content"), 7)
require.Error(t, err)
assert.ErrorIs(t, err, errUploadOutcomeUnknown)
assert.Contains(t, err.Error(), "may have succeeded")
reqs := srv.Requests()
assert.Zero(t, reqs[deleteDraftsRequest], "draft deletion sent")
assert.Zero(t, reqs[deleteRevisionRequest], "revision deletion sent")
assert.Len(t, u.Drafts(), 1, "the draft is left to the own-draft rule")
}
// TestUploadCommitRefused makes the commit fail without effect: the
// draft is deleted.
func TestUploadCommitRefused(t *testing.T) {
t.Parallel()
c, srv, u := newUploadClient(t, clientOptions{})
srv.Inject(protontest.Fault{Method: "PUT", Pattern: commitPattern, Status: http.StatusUnprocessableEntity, Code: api.CodeInvalidValue, Times: 1})
_, err := uploadContent(context.Background(), c, "f", strings.NewReader("content"), 7)
require.Error(t, err)
assert.NotErrorIs(t, err, errUploadOutcomeUnknown)
assert.Equal(t, 1, srv.Requests()[deleteDraftsRequest])
assert.Empty(t, u.Drafts())
assert.Empty(t, files(u))
}
// failingReader reads r, then fails with err where r ends.
type failingReader struct {
r io.Reader
err error
}
// Read reads from r, then fails with err.
func (f *failingReader) Read(p []byte) (int, error) {
n, err := f.r.Read(p)
if err == io.EOF {
return n, f.err
}
return n, err
}
func TestUploadSourceError(t *testing.T) {
c, srv, u := newUploadClient(t, clientOptions{})
goroutines, buffers := leakBaseline(srv)
errSource := errors.New("source broke")
in := &failingReader{r: bytes.NewReader(testContent(5<<20 + 10)), err: errSource}
_, err := uploadContent(context.Background(), c, "f", in, 9<<20)
assert.ErrorIs(t, err, errSource)
assert.Empty(t, u.Drafts())
assert.Empty(t, files(u))
requireNoLeaks(t, srv, goroutines, buffers)
}
// TestUploadBlockFailsProducerBlocked fails every block upload with one
// worker, so the producer is waiting to hand on a block when the
// worker gives up.
func TestUploadBlockFailsProducerBlocked(t *testing.T) {
c, srv, u := newUploadClient(t, clientOptions{UploadConcurrency: 1})
goroutines, buffers := leakBaseline(srv)
srv.Inject(protontest.Fault{Method: "POST", Pattern: storageUploadPattern, Status: http.StatusBadGateway})
_, err := uploadContent(context.Background(), c, "f", bytes.NewReader(testContent(12<<20+1)), 12<<20+1)
require.Error(t, err)
assert.Equal(t, 3, srv.Requests()["POST "+storageUploadPattern], "one block, tried 3 times")
assert.Empty(t, u.Drafts())
assert.Empty(t, files(u))
requireNoLeaks(t, srv, goroutines, buffers)
}
// revisionIn returns the revision ID in the path of a request to a
// revision route, and the node ID.
func revisionIn(path string) (nodeID, revisionID string) {
parts := strings.Split(path, "/")
for i, p := range parts {
if p == "files" && i+3 < len(parts) && parts[i+2] == "revisions" {
return parts[i+1], parts[i+3]
}
}
return "", ""
}
// interveneAfterCommit returns a client of u whose commit requests reach
// the server, which commits, after which act runs with the node and
// revision IDs; the client then sees a network error unless keep is set.
func interveneAfterCommit(t *testing.T, srv *protontest.Server, u *protontest.User, keep bool, act func(nodeID, revisionID string)) (c *client, armed *atomic.Bool) {
armed = new(atomic.Bool)
c = newTestClientTransport(t, srv, u, clientOptions{DraftClientUID: testDraftClientUID}, func(next http.RoundTripper) http.RoundTripper {
return roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.Method != "PUT" || !armed.Load() {
return next.RoundTrip(r)
}
resp, err := next.RoundTrip(r)
armed.Store(false)
act(revisionIn(r.URL.Path))
if keep {
return resp, err
}
if err == nil {
_ = resp.Body.Close()
}
return nil, errors.New("connection reset")
})
})
return c, armed
}
// requireNoDeletes fails the test if a draft or revision deletion was
// sent.
func requireNoDeletes(t *testing.T, srv *protontest.Server) {
t.Helper()
reqs := srv.Requests()
assert.Zero(t, reqs[deleteDraftsRequest], "draft deletion sent")
assert.Zero(t, reqs[deleteRevisionRequest], "revision deletion sent")
}
// TestUploadCommitThenChanged commits an upload whose response is lost,
// after which another client changes the file: the follow-up read
// can't prove what happened, so nothing may be deleted.
func TestUploadCommitThenChanged(t *testing.T) {
t.Parallel()
other := []byte("another client's content")
t.Run("NewFileNewRevision", func(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddUser("user", "pass")
c, armed := interveneAfterCommit(t, srv, u, false, func(nodeID, _ string) { u.SeedRevision(nodeID, other, testModTime) })
armed.Store(true)
_, err := uploadContent(context.Background(), c, "f", strings.NewReader("mine"), 4)
assert.ErrorIs(t, err, errUploadOutcomeUnknown)
requireNoDeletes(t, srv)
requireUploaded(t, u, map[string][]byte{"f": other})
})
t.Run("NewFileTrashed", func(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddUser("user", "pass")
trasher := newTestClientFor(t, srv, u, clientOptions{})
c, armed := interveneAfterCommit(t, srv, u, false, func(nodeID, _ string) {
require.NoError(t, trasher.trash(context.Background(), nodeID))
})
armed.Store(true)
_, err := uploadContent(context.Background(), c, "f", strings.NewReader("mine"), 4)
assert.ErrorIs(t, err, errUploadOutcomeUnknown)
requireNoDeletes(t, srv)
dump := requireDump(t, u)
require.Contains(t, dump, trashedPrefix+"f")
assert.Equal(t, []byte("mine"), dump[trashedPrefix+"f"].Content)
})
t.Run("NewRevision", func(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddUser("user", "pass")
var ours string
c, armed := interveneAfterCommit(t, srv, u, false, func(nodeID, revisionID string) {
ours = revisionID
u.SeedRevision(nodeID, other, testModTime)
})
first := uploadBytes(t, c, "f", []byte("first"))
srv.ResetRequests()
armed.Store(true)
_, err := c.upload(context.Background(), uploadRequest{Existing: first, In: strings.NewReader("mine"), Size: 4, ModTime: testModTime})
assert.ErrorIs(t, err, errUploadOutcomeUnknown)
requireNoDeletes(t, srv)
requireUploaded(t, u, map[string][]byte{"f": other})
// Our committed revision is kept, superseded.
mine := *first
mine.RevisionID = ours
rev, err := c.revisionBlocks(context.Background(), &mine, 1, 1)
require.NoError(t, err)
assert.Equal(t, 2, rev.State)
})
}
// TestUploadCommittedThenSuperseded commits an upload which succeeds,
// after which another client gives the file a new revision before it
// is read back: the other revision is not returned as the upload's.
func TestUploadCommittedThenSuperseded(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddUser("user", "pass")
other := []byte("another client's content")
c, armed := interveneAfterCommit(t, srv, u, true, func(nodeID, _ string) { u.SeedRevision(nodeID, other, testModTime) })
armed.Store(true)
n, err := uploadContent(context.Background(), c, "f", strings.NewReader("mine"), 4)
assert.ErrorIs(t, err, errUploadSuperseded)
assert.Nil(t, n)
requireNoDeletes(t, srv)
requireUploaded(t, u, map[string][]byte{"f": other})
}
// TestUploadRevisionCommitRefused makes the commit of a new revision
// fail without effect: the draft revision is deleted and the file keeps
// its content.
func TestUploadRevisionCommitRefused(t *testing.T) {
t.Parallel()
c, srv, u := newUploadClient(t, clientOptions{})
first := uploadBytes(t, c, "f", []byte("first"))
srv.ResetRequests()
srv.Inject(protontest.Fault{Method: "PUT", Pattern: commitPattern, Status: http.StatusUnprocessableEntity, Code: api.CodeInvalidValue, Times: 1})
_, err := c.upload(context.Background(), uploadRequest{Existing: first, In: strings.NewReader("mine"), Size: 4, ModTime: testModTime})
require.Error(t, err)
assert.NotErrorIs(t, err, errUploadOutcomeUnknown)
assert.Equal(t, 1, srv.Requests()[deleteRevisionRequest])
requireUploaded(t, u, map[string][]byte{"f": []byte("first")})
}
// TestUploadReadBackLag uploads while the server takes a moment to show
// what was committed, as Proton's does: the upload still succeeds with
// its own revision and nothing is deleted.
func TestUploadReadBackLag(t *testing.T) {
t.Parallel()
content := []byte("content")
for _, tc := range []struct {
name string
view protontest.LagView
existing bool
}{
{name: "NewFileStale", view: protontest.LagBefore},
{name: "NewFileMissing", view: protontest.LagMissing},
{name: "NewFileNoRevision", view: protontest.LagNoRevision},
{name: "NewRevisionStale", view: protontest.LagBefore, existing: true},
{name: "NewRevisionMissing", view: protontest.LagMissing, existing: true},
{name: "NewRevisionNoRevision", view: protontest.LagNoRevision, existing: true},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
c, srv, u := newUploadClient(t, clientOptions{})
r := uploadRequest{ParentID: c.rootID(), Name: "f", In: bytes.NewReader(content), Size: int64(len(content)), ModTime: testModTime}
var first *node
if tc.existing {
first = uploadBytes(t, c, "f", []byte("first"))
r.Existing = first
}
srv.ResetRequests()
srv.SetReadLag(2, tc.view)
n, err := c.upload(context.Background(), r)
require.NoError(t, err)
assert.NotEmpty(t, n.RevisionID)
if first != nil {
assert.NotEqual(t, first.RevisionID, n.RevisionID)
}
assert.Equal(t, sha1Of(content), n.sha1())
requireNoDeletes(t, srv)
requireUploaded(t, u, map[string][]byte{"f": content})
})
}
}
// TestUploadIntoNewFolderReadBackLag creates nested folders and uploads
// into the deepest without a cache while the server takes a moment to
// show new nodes.
func TestUploadIntoNewFolderReadBackLag(t *testing.T) {
t.Parallel()
c, srv, u := newTestClientOpt(t, clientOptions{DraftClientUID: testDraftClientUID})
srv.SetReadLag(2, protontest.LagMissing)
ctx := context.Background()
parentID := c.rootID()
for _, name := range []string{"A1", "B1", "C1"} {
n, err := c.createFolder(ctx, parentID, name, time.Time{})
require.NoError(t, err)
parentID = n.ID
}
content := []byte("aaa")
_, err := c.upload(ctx, uploadRequest{ParentID: parentID, Name: "one", In: bytes.NewReader(content), Size: int64(len(content)), ModTime: testModTime})
require.NoError(t, err)
requireNoDeletes(t, srv)
requireUploaded(t, u, map[string][]byte{"A1/B1/C1/one": content})
}
// TestUploadReadBackLagOutlasted commits an upload which the server
// doesn't show for longer than the client reads it back: the upload
// fails as unconfirmed and nothing is deleted.
func TestUploadReadBackLagOutlasted(t *testing.T) {
t.Parallel()
for _, view := range []protontest.LagView{protontest.LagBefore, protontest.LagMissing, protontest.LagNoRevision} {
t.Run(fmt.Sprintf("view=%d", view), func(t *testing.T) {
t.Parallel()
c, srv, u := newUploadClient(t, clientOptions{})
c.readBackDelay = time.Millisecond
srv.SetReadLag(readBackAttempts, view)
n, err := uploadContent(context.Background(), c, "f", strings.NewReader("mine"), 4)
assert.ErrorIs(t, err, errUploadUnconfirmed)
assert.NotErrorIs(t, err, errUploadSuperseded)
assert.Nil(t, n)
assert.Equal(t, readBackAttempts, srv.Requests()["POST /drive/v2/volumes/{volumeID}/links"])
requireNoDeletes(t, srv)
requireUploaded(t, u, map[string][]byte{"f": []byte("mine")})
})
}
}
// commitFailure returns a client of u whose next commit lands on srv
// and then fails.
type commitFailure func(t *testing.T, srv *protontest.Server, u *protontest.User) *client
// TestUploadAmbiguousCommitFailureUnderLag makes a commit land on the
// server and then fail in a way which doesn't prove it didn't, while
// the read back shows the node as before the commit: nothing may be
// deleted, as the deletion could hit the committed file or revision.
func TestUploadAmbiguousCommitFailureUnderLag(t *testing.T) {
t.Parallel()
failures := map[string]commitFailure{
// The commit lands and its response is lost; the resent commit
// is refused, as the draft revision is gone.
"ResentThenRefused": func(t *testing.T, srv *protontest.Server, u *protontest.User) *client {
srv.Inject(protontest.Fault{Method: "PUT", Pattern: commitPattern, Status: http.StatusBadGateway, AfterHandler: true, Times: 1})
srv.Inject(protontest.Fault{Method: "PUT", Pattern: commitPattern, Status: http.StatusUnprocessableEntity, Code: api.CodeInvalidValue, AfterHandler: true, Skip: 1, Times: 1})
return newTestClientFor(t, srv, u, clientOptions{DraftClientUID: testDraftClientUID})
},
// The commit lands and the connection drops before its response.
"ConnectionLost": func(t *testing.T, srv *protontest.Server, u *protontest.User) *client {
c, armed := interveneAfterCommit(t, srv, u, false, func(string, string) {})
armed.Store(true)
return c
},
}
for name, fail := range failures {
for _, existing := range []bool{false, true} {
t.Run(fmt.Sprintf("%s/existing=%v", name, existing), func(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddUser("user", "pass")
var first *node
if existing {
c := newTestClientFor(t, srv, u, clientOptions{DraftClientUID: testDraftClientUID})
first = uploadBytes(t, c, "f", []byte("first"))
}
c := fail(t, srv, u)
c.readBackDelay = time.Millisecond
srv.ResetRequests()
srv.SetReadLag(readBackAttempts, protontest.LagBefore)
r := uploadRequest{ParentID: c.rootID(), Name: "f", Existing: first, In: strings.NewReader("mine"), Size: 4, ModTime: testModTime}
_, err := c.upload(context.Background(), r)
assert.ErrorIs(t, err, errUploadOutcomeUnknown)
requireNoDeletes(t, srv)
requireUploaded(t, u, map[string][]byte{"f": []byte("mine")})
})
}
}
}
// TestUploadCommitRefusedNoReadBack makes the server refuse a commit on
// its only attempt: the refusal alone proves it didn't land, so the
// draft is deleted without reading the file back, as a read may lag.
func TestUploadCommitRefusedNoReadBack(t *testing.T) {
t.Parallel()
for _, existing := range []bool{false, true} {
t.Run(fmt.Sprintf("existing=%v", existing), func(t *testing.T) {
t.Parallel()
c, srv, u := newUploadClient(t, clientOptions{})
var first *node
want := map[string][]byte{}
if existing {
first = uploadBytes(t, c, "f", []byte("first"))
want["f"] = []byte("first")
}
srv.ResetRequests()
srv.Inject(protontest.Fault{Method: "PUT", Pattern: commitPattern, Status: http.StatusUnprocessableEntity, Code: api.CodeInvalidValue, Times: 1})
_, err := c.upload(context.Background(), uploadRequest{ParentID: c.rootID(), Name: "f", Existing: first, In: strings.NewReader("mine"), Size: 4, ModTime: testModTime})
require.Error(t, err)
assert.NotErrorIs(t, err, errUploadOutcomeUnknown)
reqs := srv.Requests()
assert.Equal(t, 1, reqs["PUT "+commitPattern])
assert.Zero(t, reqs["POST "+linksPattern], "file read back")
assert.Equal(t, 1, reqs[deleteDraftsRequest]+reqs[deleteRevisionRequest], "draft not deleted")
assert.Empty(t, u.Drafts())
requireUploaded(t, u, want)
})
}
}
// TestUploadCommittedThenCancelledUnderLag cancels an upload once its
// commit has succeeded and the first read back lagged: it returns at
// once as unconfirmed and deletes nothing.
func TestUploadCommittedThenCancelledUnderLag(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddUser("user", "pass")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
c := newTestClientTransport(t, srv, u, clientOptions{DraftClientUID: testDraftClientUID}, func(next http.RoundTripper) http.RoundTripper {
var committed atomic.Bool
return roundTripFunc(func(r *http.Request) (*http.Response, error) {
resp, err := next.RoundTrip(r)
switch {
case r.Method == "PUT" && strings.Contains(r.URL.Path, "/revisions/"):
committed.Store(true)
case committed.Load() && strings.HasSuffix(r.URL.Path, "/links"):
cancel()
}
return resp, err
})
})
srv.SetReadLag(readBackAttempts, protontest.LagBefore)
start := time.Now()
_, err := uploadContent(ctx, c, "f", strings.NewReader("mine"), 4)
assert.ErrorIs(t, err, errUploadUnconfirmed)
assert.Less(t, time.Since(start), 2*time.Second, "kept reading after cancel")
requireNoDeletes(t, srv)
requireUploaded(t, u, map[string][]byte{"f": []byte("mine")})
}