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
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>
436 lines
14 KiB
Go
436 lines
14 KiB
Go
package protondrive
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
"unicode/utf16"
|
|
"unicode/utf8"
|
|
|
|
"github.com/ProtonMail/gopenpgp/v3/crypto"
|
|
"github.com/rclone/rclone/backend/protondrive/api"
|
|
"github.com/rclone/rclone/backend/protondrive/protontest"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
// Fuzz targets for everything which parses bytes the server controls.
|
|
// Each is seeded from the old library's fixtures in testdata/oldlib and
|
|
// from payloads the fake server makes, and checks invariants of what
|
|
// is accepted, not only that nothing panics.
|
|
|
|
// oldlibFixture is the part of testdata/oldlib/file.json and
|
|
// folder.json the fuzz targets use.
|
|
type oldlibFixture struct {
|
|
NodeKey string
|
|
NodePassphrasePlain string
|
|
NamePlain string
|
|
ChildName string
|
|
XAttr string
|
|
}
|
|
|
|
// loadOldlibFixture returns testdata/oldlib/name.
|
|
func loadOldlibFixture(t testing.TB, name string) oldlibFixture {
|
|
t.Helper()
|
|
data, err := os.ReadFile(filepath.Join("testdata/oldlib", name))
|
|
require.NoError(t, err)
|
|
var fx oldlibFixture
|
|
require.NoError(t, json.Unmarshal(data, &fx))
|
|
return fx
|
|
}
|
|
|
|
// fuzzLinks returns a client for a user of a fake server holding the
|
|
// keys of the old library's v6 file fixture, the root folder's keys,
|
|
// and the JSON of a link of each kind the client reads: the fixture
|
|
// itself, and nodes the fake makes as SDK clients would.
|
|
func fuzzLinks(f *testing.F) (*client, *nodeKeys, [][]byte) {
|
|
frozen := loadFrozenFile(f, filepath.Join(frozenFileDir, "v6"))
|
|
srv := protontest.New(f)
|
|
u := srv.AddUserWithKeys(frozen.Email, "pass", frozen.Keys)
|
|
c := newTestClientFor(f, srv, u, clientOptions{})
|
|
root := u.RootID()
|
|
ids := []string{
|
|
u.SeedStoredFile(root, frozen.Stored),
|
|
u.SeedFolder(root, "folder"),
|
|
u.SeedFile(root, "file.txt", []byte("content"), time.Now()),
|
|
u.SeedFile(root, "empty", nil, time.Now()),
|
|
u.SeedLegacyFile(root, "legacy", []byte("legacy")),
|
|
u.SeedAnonymousFile(root, "anonymous", []byte("anonymous"), time.Now()),
|
|
u.SeedAnonymousFolder(root, "anonymous folder"),
|
|
u.SeedFileClaimingBlockSizes(root, "claims", []byte("claims"), []int64{1, 2, 3}),
|
|
u.SeedDoc(root, "doc"),
|
|
}
|
|
ctx := context.Background()
|
|
links, err := c.fetchLinks(ctx, ids)
|
|
require.NoError(f, err)
|
|
require.Len(f, links, len(ids))
|
|
var seeds [][]byte
|
|
for _, d := range links {
|
|
data, err := json.Marshal(d)
|
|
require.NoError(f, err)
|
|
seeds = append(seeds, data)
|
|
}
|
|
keys, err := c.folderKeysOf(ctx, root)
|
|
require.NoError(f, err)
|
|
return c, keys, seeds
|
|
}
|
|
|
|
func FuzzValidateName(f *testing.F) {
|
|
for _, name := range []string{
|
|
loadOldlibFixture(f, "file.json").NamePlain,
|
|
loadOldlibFixture(f, "folder.json").NamePlain,
|
|
loadOldlibFixture(f, "folder.json").ChildName,
|
|
"file.txt", ".", "..", "...", "", "a/b", "/", "a\x00b", " ", "é", "é",
|
|
strings.Repeat("a", maxNameLength), strings.Repeat("a", maxNameLength+1),
|
|
strings.Repeat("\U0001F600", maxNameLength/2), strings.Repeat("\U0001F600", maxNameLength/2+1),
|
|
"\xff\xfe",
|
|
} {
|
|
f.Add(name)
|
|
}
|
|
f.Fuzz(func(t *testing.T, name string) {
|
|
if validateName(name) != nil {
|
|
return
|
|
}
|
|
assert.NotEmpty(t, name)
|
|
assert.True(t, utf8.ValidString(name), "%q", name)
|
|
assert.NotEqual(t, ".", name)
|
|
assert.NotEqual(t, "..", name)
|
|
assert.NotContains(t, name, "/")
|
|
assert.NotContains(t, name, "\x00")
|
|
assert.LessOrEqual(t, len(utf16.Encode([]rune(name))), maxNameLength)
|
|
})
|
|
}
|
|
|
|
func FuzzDecodeLink(f *testing.F) {
|
|
c, rootKeys, seeds := fuzzLinks(f)
|
|
for _, seed := range seeds {
|
|
f.Add(seed)
|
|
// Hostile values in links which otherwise decrypt.
|
|
var d api.LinkDetails
|
|
require.NoError(f, json.Unmarshal(seed, &d))
|
|
for _, change := range []func(d *api.LinkDetails){
|
|
func(d *api.LinkDetails) { d.Link.LinkID = "" },
|
|
func(d *api.LinkDetails) { d.Link.Type = 3 - d.Link.Type },
|
|
func(d *api.LinkDetails) {
|
|
if d.File != nil && d.File.ActiveRevision != nil {
|
|
d.File.ActiveRevision.EncryptedSize = -5
|
|
}
|
|
},
|
|
} {
|
|
changed := d
|
|
changed.File = cloneFile(d.File)
|
|
change(&changed)
|
|
data, err := json.Marshal(changed)
|
|
require.NoError(f, err)
|
|
f.Add(data)
|
|
}
|
|
}
|
|
// Shapes the client can't decrypt.
|
|
for _, format := range []string{"legacy", "v6"} {
|
|
data, err := os.ReadFile(filepath.Join(frozenFileDir, format, "link.json"))
|
|
require.NoError(f, err)
|
|
f.Add(data)
|
|
}
|
|
f.Add([]byte(`{}`))
|
|
f.Add([]byte(`{"Link":{"LinkID":"x","Type":1,"ParentLinkID":"p"},"Folder":{}}`))
|
|
ctx := context.Background()
|
|
f.Fuzz(func(t *testing.T, data []byte) {
|
|
var d api.LinkDetails
|
|
if json.Unmarshal(data, &d) != nil {
|
|
return
|
|
}
|
|
n, unreadable, err := c.decryptNode(ctx, &d, rootKeys)
|
|
if err != nil || unreadable != nil {
|
|
assert.Nil(t, n)
|
|
return
|
|
}
|
|
require.NotNil(t, n)
|
|
assert.NotEmpty(t, n.ID)
|
|
assert.Equal(t, d.Link.LinkID, n.ID)
|
|
assert.True(t, utf8.ValidString(n.Name), "%q", n.Name)
|
|
if d.Link.ParentLinkID != "" {
|
|
assert.NoError(t, validateName(n.Name))
|
|
}
|
|
assert.True(t, n.IsFolder == (d.Link.Type == api.LinkTypeFolder))
|
|
for _, original := range []bool{true, false} {
|
|
assert.GreaterOrEqual(t, n.size(original), int64(0), "original=%v", original)
|
|
}
|
|
if n.X != nil {
|
|
checkXAttrs(t, n.X)
|
|
}
|
|
})
|
|
}
|
|
|
|
// cloneFile returns a copy of file, sharing nothing changeable with it.
|
|
func cloneFile(file *api.File) *api.File {
|
|
if file == nil {
|
|
return nil
|
|
}
|
|
out := *file
|
|
if file.ActiveRevision != nil {
|
|
rev := *file.ActiveRevision
|
|
out.ActiveRevision = &rev
|
|
}
|
|
return &out
|
|
}
|
|
|
|
// checkXAttrs checks the invariants of parsed extended attributes.
|
|
//
|
|
// That the block sizes add up to the size isn't one: as in the SDK
|
|
// neither is checked against the other, and a read checks each block
|
|
// against its recorded size, so a file whose attributes disagree fails
|
|
// to read rather than reading wrong.
|
|
func checkXAttrs(t *testing.T, x *xattrs) {
|
|
t.Helper()
|
|
assert.GreaterOrEqual(t, x.Size, int64(0))
|
|
if x.NoSize {
|
|
assert.Zero(t, x.Size)
|
|
}
|
|
if x.BlockSizes != nil {
|
|
assert.NotEmpty(t, x.BlockSizes)
|
|
}
|
|
for i, size := range x.BlockSizes {
|
|
assert.Positive(t, size, "block %d", i+1)
|
|
}
|
|
if !x.ModTime.IsZero() {
|
|
assert.Equal(t, time.UTC, x.ModTime.Location())
|
|
// RFC 3339 years, moved by a zone offset of under a day.
|
|
assert.True(t, x.ModTime.Year() >= -1 && x.ModTime.Year() <= 10000, "%v", x.ModTime)
|
|
}
|
|
assert.NotContains(t, x.Extra, "Common")
|
|
}
|
|
|
|
func FuzzCheckKeyS2K(f *testing.F) {
|
|
f.Add(unarmor(f, loadOldlibFixture(f, "file.json").NodeKey))
|
|
now := time.Now()
|
|
parent, signer := newTestKeyRing(f, now), newTestKeyRing(f, now)
|
|
_, _, _, keys := testNodeKeys(f, parent, signer, true, now)
|
|
for _, memExp := range []byte{3, 17, 18, 31} {
|
|
f.Add(unarmor(f, argon2Locked(f, keys, 1, 1, memExp)))
|
|
}
|
|
f.Fuzz(func(t *testing.T, data []byte) {
|
|
// Whatever the bytes, the check never runs a KDF and never
|
|
// panics; a key it lets through still parses or fails to.
|
|
if checkKeyS2K(data) == nil {
|
|
_, _ = crypto.NewKey(data)
|
|
}
|
|
})
|
|
}
|
|
|
|
func FuzzDecryptXAttrs(f *testing.F) {
|
|
fx := loadOldlibFixture(f, "file.json")
|
|
key, err := unlockKey(fx.NodeKey, []byte(fx.NodePassphrasePlain))
|
|
require.NoError(f, err)
|
|
nodeKR, err := crypto.NewKeyRing(key)
|
|
require.NoError(f, err)
|
|
now := time.Now()
|
|
|
|
// The old library's attributes, encrypted and in plain text.
|
|
res, _, _, err := decryptMessage(fx.XAttr, nodeKR, nil, now, maxXAttrsSize)
|
|
require.NoError(f, err)
|
|
f.Add(fx.XAttr, res.Bytes())
|
|
// Attributes as the fake writes them for SDK clients.
|
|
c, _, seeds := fuzzLinks(f)
|
|
for _, seed := range seeds {
|
|
var d api.LinkDetails
|
|
require.NoError(f, json.Unmarshal(seed, &d))
|
|
if d.File == nil || d.File.ActiveRevision == nil || d.File.ActiveRevision.XAttr == "" {
|
|
continue
|
|
}
|
|
n, err := c.getNode(context.Background(), d.Link.LinkID)
|
|
require.NoError(f, err)
|
|
res, _, _, err := decryptMessage(d.File.ActiveRevision.XAttr, n.keys.keyRing, nil, now, maxXAttrsSize)
|
|
require.NoError(f, err)
|
|
f.Add("", res.Bytes())
|
|
}
|
|
for _, plain := range []string{
|
|
`{"Common":{"ModificationTime":"2021-09-16T07:40:54+0000","Size":-1,"BlockSizes":[4194304,-1],"Digests":{"SHA1":"x"}}}`,
|
|
`{"Common":{"Size":1152921504606846976,"BlockSizes":[1152921504606846976,1]}}`,
|
|
`{"Common":{"ModificationTime":"99999-01-01T00:00:00Z"}}`,
|
|
`{"Common":{"ModificationTime":"0000-01-01T00:00:00+23:59"}}`,
|
|
`{"Common":{"BlockSizes":[]},"Media":{"Width":1}}`,
|
|
`{"Common":{"BlockSizes":[` + strings.Repeat("4194304,", 10000) + `1]}}`,
|
|
strings.Repeat(`{"Common":`, 20000) + strings.Repeat("}", 20000),
|
|
`{"Common":` + strings.Repeat("[", 100000) + strings.Repeat("]", 100000) + `}`,
|
|
} {
|
|
f.Add("", []byte(plain))
|
|
}
|
|
|
|
f.Fuzz(func(t *testing.T, enc string, plain []byte) {
|
|
if x, _, err := decryptXAttrs(enc, nodeKR, nodeKR, now); err == nil {
|
|
checkXAttrs(t, x)
|
|
}
|
|
if len(plain) > maxXAttrsSize/2 {
|
|
return
|
|
}
|
|
enc, err := encryptArmored(plain, nil, nodeKR, nodeKR, true, now)
|
|
require.NoError(t, err)
|
|
x, verifyErr, err := decryptXAttrs(enc, nodeKR, nodeKR, now)
|
|
if !utf8.Valid(plain) {
|
|
assert.Error(t, err)
|
|
return
|
|
}
|
|
require.NoError(t, err)
|
|
require.NoError(t, verifyErr)
|
|
checkXAttrs(t, x)
|
|
})
|
|
}
|
|
|
|
func FuzzDecodeAPIError(f *testing.F) {
|
|
for _, seed := range []struct {
|
|
status int
|
|
body string
|
|
retryAfter string
|
|
}{
|
|
{422, `{"Code":2500,"Error":"A file or folder with that name already exists","Details":{"ConflictLinkID":"abc","ConflictRevisionID":"def"}}`, ""},
|
|
{422, `{"Code":2501,"Error":"File or folder not found"}`, ""},
|
|
{429, `{"Code":85131,"Error":"Too many recent API requests"}`, "17"},
|
|
{429, ``, "Wed, 21 Oct 2015 07:28:00 GMT"},
|
|
{429, ``, "99999999999999999999999"},
|
|
{401, `{"Code":401,"Error":"Invalid access token"}`, ""},
|
|
{400, `{"Code":2064,"Error":"protontest: invalid x-pm-appversion \"x\""}`, ""},
|
|
{500, `<html>Internal Server Error</html>`, ""},
|
|
{200, `{"Code":"1000"}`, ""},
|
|
{0, `{"Error":null,"Details":[1,2,3]}`, "-5"},
|
|
} {
|
|
f.Add(seed.status, []byte(seed.body), seed.retryAfter)
|
|
}
|
|
f.Fuzz(func(t *testing.T, status int, body []byte, retryAfterValue string) {
|
|
resp := &http.Response{
|
|
StatusCode: status,
|
|
Status: fmt.Sprintf("%d %s", status, http.StatusText(status)),
|
|
Header: http.Header{"Retry-After": {retryAfterValue}},
|
|
Body: io.NopCloser(bytes.NewReader(body)),
|
|
}
|
|
err := errorHandler(resp)
|
|
var apiErr *api.Error
|
|
require.ErrorAs(t, err, &apiErr)
|
|
assert.Equal(t, status, apiErr.Status)
|
|
assert.NotEmpty(t, apiErr.Message)
|
|
assert.NotEmpty(t, err.Error())
|
|
assert.Equal(t, apiErr.Code, apiErrorCode(err))
|
|
|
|
wait := retryAfter(resp)
|
|
assert.Positive(t, wait)
|
|
assert.LessOrEqual(t, wait, maxRetryAfter)
|
|
})
|
|
}
|
|
|
|
func FuzzDecryptForkPayload(f *testing.F) {
|
|
key := bytes.Repeat([]byte{7}, 32)
|
|
for _, seed := range []struct{ plain, aad string }{
|
|
{`{"type":"default","keyPassword":"the-key-password"}`, forkPayloadAAD},
|
|
{`{"keyPassword":""}`, forkPayloadAAD},
|
|
{`{"keyPassword":null}`, forkPayloadAAD},
|
|
{`{"type":"default"}`, forkPayloadAAD},
|
|
{`not json`, forkPayloadAAD},
|
|
{`{"keyPassword":"wrong additional data"}`, "other"},
|
|
} {
|
|
f.Add(sealForkPayload(f, key, seed.plain, seed.aad))
|
|
}
|
|
f.Add("")
|
|
f.Add("not base64!")
|
|
f.Add(base64.StdEncoding.EncodeToString(make([]byte, 12)))
|
|
f.Fuzz(func(t *testing.T, payload string) {
|
|
keyPassword, err := decryptForkPayload(payload, key)
|
|
if err != nil {
|
|
assert.Empty(t, keyPassword)
|
|
return
|
|
}
|
|
// Success only for a payload sealed with key: open it here
|
|
// independently.
|
|
blob, err := base64.StdEncoding.DecodeString(payload)
|
|
require.NoError(t, err)
|
|
block, err := aes.NewCipher(key)
|
|
require.NoError(t, err)
|
|
gcm, err := cipher.NewGCM(block)
|
|
require.NoError(t, err)
|
|
require.GreaterOrEqual(t, len(blob), gcm.NonceSize())
|
|
plain, err := gcm.Open(nil, blob[:gcm.NonceSize()], blob[gcm.NonceSize():], []byte(forkPayloadAAD))
|
|
require.NoError(t, err, "accepted a payload which doesn't authenticate")
|
|
var p struct{ KeyPassword *string }
|
|
require.NoError(t, json.Unmarshal(plain, &p))
|
|
require.NotNil(t, p.KeyPassword)
|
|
assert.Equal(t, *p.KeyPassword, keyPassword)
|
|
})
|
|
}
|
|
|
|
func FuzzDecodeEvents(f *testing.F) {
|
|
// Pages the fake sends for changes of each kind.
|
|
srv := protontest.New(f)
|
|
u := srv.AddUser("user", "pass")
|
|
var (
|
|
mu sync.Mutex
|
|
pages [][]byte
|
|
)
|
|
c := newTestClientTransport(f, srv, u, clientOptions{EnableCaching: true}, func(next http.RoundTripper) http.RoundTripper {
|
|
return roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
|
resp, err := next.RoundTrip(r)
|
|
if err != nil || !strings.Contains(r.URL.Path, "/events/") {
|
|
return resp, err
|
|
}
|
|
body, err := io.ReadAll(resp.Body)
|
|
_ = resp.Body.Close()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
mu.Lock()
|
|
pages = append(pages, body)
|
|
mu.Unlock()
|
|
resp.Body = io.NopCloser(bytes.NewReader(body))
|
|
return resp, nil
|
|
})
|
|
})
|
|
srv.SetEventsPageSize(3)
|
|
ctx := context.Background()
|
|
start, err := c.latestEventID(ctx)
|
|
require.NoError(f, err)
|
|
dir := u.SeedFolder(u.RootID(), "dir")
|
|
file := u.SeedFile(dir, "file", []byte("x"), time.Now())
|
|
u.SetParent(file, u.RootID())
|
|
srv.InjectEvent(u, protontest.Event{Type: protontest.EventUpdateMetadata, LinkID: dir, ParentLinkID: u.RootID(), IsTrashed: true})
|
|
srv.InjectEvent(u, protontest.Event{Type: protontest.EventDelete, LinkID: dir})
|
|
_, _, _, err = c.pollEvents(ctx, start)
|
|
require.NoError(f, err)
|
|
srv.ExpireEvents(u)
|
|
_, _, _, err = c.pollEvents(ctx, start)
|
|
require.NoError(f, err)
|
|
require.NotEmpty(f, pages)
|
|
for _, page := range pages {
|
|
f.Add(page)
|
|
}
|
|
f.Add([]byte(`{"Code":1000,"Events":[{"EventID":"e","EventType":0,"Link":{"LinkID":"dir","ParentLinkID":null}}],"EventID":"e","More":true}`))
|
|
f.Add([]byte(`{"Events":[{"EventType":99,"Link":{"LinkID":"root","ParentLinkID":"root","IsTrashed":true}}]}`))
|
|
f.Add([]byte(`{"Events":[{"EventType":2,"Link":{"LinkID":"a","ParentLinkID":"a"}}]}`))
|
|
f.Add([]byte(`{"Events":null,"More":1}`))
|
|
f.Fuzz(func(t *testing.T, data []byte) {
|
|
var resp api.EventsResponse
|
|
if json.Unmarshal(data, &resp) != nil {
|
|
return
|
|
}
|
|
c := eventsTestClient()
|
|
c.cache.put(&node{ID: "a", ParentID: "b", IsFolder: true})
|
|
c.cache.put(&node{ID: "b", ParentID: "a", IsFolder: true})
|
|
changes := eventChanges(resp.Events)
|
|
stale := c.applyEvents(changes)
|
|
require.Len(t, stale, len(changes))
|
|
for i, ch := range changes {
|
|
assert.NotEmpty(t, ch.linkID)
|
|
assert.Equal(t, ch.linkID, stale[i].id)
|
|
assert.Nil(t, c.cache.get(ch.linkID), "changed node %s still cached", ch.linkID)
|
|
}
|
|
})
|
|
}
|