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

1110 lines
42 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package protondrive_test
import (
"bytes"
"context"
"encoding/base64"
"encoding/hex"
"fmt"
"io"
"log/slog"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"testing"
"time"
"github.com/rclone/rclone/backend/protondrive"
"github.com/rclone/rclone/backend/protondrive/protontest"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/accounting"
"github.com/rclone/rclone/fs/config"
"github.com/rclone/rclone/fs/config/configfile"
"github.com/rclone/rclone/fs/config/configmap"
"github.com/rclone/rclone/fs/config/obscure"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/fs/log"
"github.com/rclone/rclone/fs/object"
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/fs/rc"
fssync "github.com/rclone/rclone/fs/sync"
"github.com/rclone/rclone/lib/random"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// blockSize is the plaintext size of a full block.
const blockSize = 4 << 20
// patternedContent returns n bytes, seeded by seed, which differ per
// block.
func patternedContent(n int, seed byte) []byte {
b := make([]byte, n)
for i := range b {
b[i] = byte(i*7+i/blockSize) ^ seed
}
return b
}
// readAll opens o and reads it to the end, returning every byte the
// reader released and the first error, from Open or Read.
func readAll(ctx context.Context, o fs.Object) ([]byte, error) {
rc, err := o.Open(ctx)
if err != nil {
return nil, err
}
got, err := io.ReadAll(rc)
if closeErr := rc.Close(); err == nil {
err = closeErr
}
return got, err
}
// requireCopyFails copies remote from src to a new local directory and
// checks the copy fails and leaves nothing behind.
func requireCopyFails(ctx context.Context, t *testing.T, src fs.Fs, remote string) {
t.Helper()
dst := newFakeFs(t, "", t.TempDir())
err := operations.CopyFile(ctx, dst, src, remote, remote)
require.Error(t, err, "copied %s", remote)
entries, err := os.ReadDir(dst.Root())
require.NoError(t, err)
assert.Empty(t, entries, "the failed copy left files behind")
}
// hostileContent is a file whose content a hostile server tampers with.
type hostileContent struct {
name string
path string // of the file; victim.bin if empty
content []byte
// prepare seeds the file at path and tampers with it, returning
// its ID.
prepare func(u *protontest.User, content []byte) string
// signatureOnly is set if only a signature check catches the
// tampering, which ignore_signature_errors turns off.
signatureOnly bool
}
// seedCorrupted returns a prepare which seeds the file and applies the
// fake's corruption what.
func seedCorrupted(what string) func(u *protontest.User, content []byte) string {
return func(u *protontest.User, content []byte) string {
id := u.SeedFile(u.RootID(), "victim.bin", content, time.Now())
u.Corrupt(id, what)
return id
}
}
// seedRolledBack returns a prepare which seeds the file with old
// content, gives it a new revision with the content, then serves the
// old revision's blocks under the new revision's manifest.
//
// A server serving the old revision whole - blocks, manifest and
// extended attributes - under the new revision's ID can't be detected:
// nothing signed binds them to the revision. The SDK can't detect it
// either.
func seedRolledBack(old []byte) func(u *protontest.User, content []byte) string {
return func(u *protontest.User, content []byte) string {
id := u.SeedFile(u.RootID(), "victim.bin", old, time.Now())
u.SeedRevision(id, content, time.Now())
u.Corrupt(id, "block-rollback")
return id
}
}
// hostileContents are the hostile content cases of spec section 9.6.
var hostileContents = []hostileContent{{
name: "wrong block hash",
content: patternedContent(blockSize+10, 1),
prepare: seedCorrupted("block-hash"),
}, {
name: "swapped blocks",
content: patternedContent(2*blockSize+10, 2),
prepare: seedCorrupted("swap-blocks"),
signatureOnly: true,
}, {
name: "swapped blocks of different sizes",
content: patternedContent(blockSize+10, 3),
prepare: seedCorrupted("swap-blocks"),
}, {
name: "truncated block list",
content: patternedContent(blockSize+10, 4),
prepare: seedCorrupted("truncate-blocks"),
}, {
name: "older revision's blocks under the current revision",
content: patternedContent(blockSize+10, 5),
prepare: seedRolledBack(patternedContent(blockSize+10, 6)),
signatureOnly: true,
}, {
name: "older revision's blocks of another size under the current revision",
content: patternedContent(20, 7),
prepare: seedRolledBack(patternedContent(10, 8)),
}, {
name: "block from another file",
content: patternedContent(blockSize+10, 9),
prepare: seedCorrupted("foreign-block"),
}, {
name: "attacker-signed passphrase",
content: patternedContent(100, 10),
prepare: seedCorrupted("passphrase-signature"),
signatureOnly: true,
}, {
name: "anonymous file in a folder with a forged key",
path: "forged/victim.bin",
content: patternedContent(100, 11),
prepare: func(u *protontest.User, content []byte) string {
forged := u.SeedForgedFolder(u.RootID(), "forged")
return u.SeedAnonymousFile(forged, "victim.bin", content, time.Now())
},
signatureOnly: true,
}, {
name: "anonymous file nested in a folder with a forged key",
path: "forged/nested/victim.bin",
content: patternedContent(100, 12),
prepare: func(u *protontest.User, content []byte) string {
nested := u.SeedAnonymousFolder(u.SeedForgedFolder(u.RootID(), "forged"), "nested")
return u.SeedAnonymousFile(nested, "victim.bin", content, time.Now())
},
signatureOnly: true,
}, {
name: "unsigned content key the server made",
content: patternedContent(blockSize+10, 15),
prepare: seedCorrupted("content-key-unsigned"),
signatureOnly: true,
}, {
name: "content key signed by another key",
content: patternedContent(blockSize+10, 16),
prepare: seedCorrupted("content-key-signature"),
signatureOnly: true,
}}
// hostileNames are names a hostile server gives nodes, each of which
// must be left out of listings.
var hostileNames = []string{"../x", "a/b", "nul\x00name", "..", ".", strings.Repeat("x", 10<<20)}
// TestHostileServer checks a hostile server can't get rclone to return
// tampered content as the file's, or a path outside the listed
// directory.
func TestHostileServer(t *testing.T) {
for _, tc := range hostileContents {
t.Run(tc.name, func(t *testing.T) {
ctx := context.Background()
remote, _, u := setupFakeRemote(t)
tc.prepare(u, tc.content)
path := tc.path
if path == "" {
path = "victim.bin"
}
f := newFakeFs(t, remote, "")
o, err := f.NewObject(ctx, path)
require.NoError(t, err, "the file is listed")
got, err := readAll(ctx, o)
require.Error(t, err, "read without error")
assert.Empty(t, got, "bytes released before the error")
requireCopyFails(ctx, t, f, path)
// Turning signature checks off leaves the integrity
// checks, and the hash check of a copy.
f = newFakeFs(t, strings.TrimSuffix(remote, ":")+",ignore_signature_errors=true:", "")
o, err = f.NewObject(ctx, path)
require.NoError(t, err)
got, err = readAll(ctx, o)
if !tc.signatureOnly {
require.Error(t, err, "read without error with signature checks off")
assert.Empty(t, got, "bytes released before the error")
}
if bytes.Equal(got, tc.content) {
// Only a signature was tampered with, and the content
// is the file's.
return
}
requireCopyFails(ctx, t, f, path)
})
}
t.Run("writing into a folder with a forged key", func(t *testing.T) {
ctx := context.Background()
remote, _, u := setupFakeRemote(t)
nested := u.SeedAnonymousFolder(u.SeedForgedFolder(u.RootID(), "forged"), "nested")
u.SeedAnonymousFile(nested, "existing.bin", []byte("forged"), time.Now())
u.SeedFile(u.RootID(), "mine.txt", []byte("mine"), time.Now())
before := len(u.Dump())
f := newFakeFs(t, remote, "")
for _, dir := range []string{"forged", "forged/nested"} {
src := object.NewMemoryObject(dir+"/new.txt", time.Now(), []byte("secret"))
_, err := operations.Copy(ctx, f, nil, src.Remote(), src)
require.Error(t, err, "uploaded into %s", dir)
assert.Contains(t, err.Error(), "ignore_signature_errors")
assert.Error(t, f.Mkdir(ctx, dir+"/sub"), "made a folder in %s", dir)
mine, err := f.NewObject(ctx, "mine.txt")
require.NoError(t, err)
_, err = operations.Copy(ctx, f, nil, dir+"/copied.txt", mine)
assert.Error(t, err, "copied into %s", dir)
_, err = operations.Move(ctx, f, nil, dir+"/moved.txt", mine)
assert.Error(t, err, "moved into %s", dir)
}
existing, err := f.NewObject(ctx, "forged/nested/existing.bin")
require.NoError(t, err)
assert.Error(t, existing.Update(ctx, bytes.NewReader([]byte("secret")), object.NewStaticObjectInfo("forged/nested/existing.bin", time.Now(), 6, true, nil, nil)), "updated a file there")
assert.Len(t, u.Dump(), before, "something was written")
f = newFakeFs(t, strings.TrimSuffix(remote, ":")+",ignore_signature_errors=true:", "")
src := object.NewMemoryObject("forged/new.txt", time.Now(), []byte("allowed"))
_, err = operations.Copy(ctx, f, nil, src.Remote(), src)
require.NoError(t, err, "upload with signature checks off")
})
t.Run("writing into a folder whose hash key the server made", func(t *testing.T) {
ctx := context.Background()
remote, _, u := setupFakeRemote(t)
dir := u.SeedFolder(u.RootID(), "dir")
u.SeedFile(dir, "existing.txt", []byte("existing"), time.Now())
u.SeedFile(u.RootID(), "mine.txt", []byte("mine"), time.Now())
u.Corrupt(dir, "hash-key-unsigned")
before := len(u.Dump())
f := newFakeFs(t, remote, "")
src := object.NewMemoryObject("dir/tax-return.pdf", time.Now(), []byte("secret"))
_, err := operations.Copy(ctx, f, nil, src.Remote(), src)
require.Error(t, err, "uploaded")
assert.Contains(t, err.Error(), "ignore_signature_errors")
assert.Error(t, f.Mkdir(ctx, "dir/sub"), "made a folder")
mine, err := f.NewObject(ctx, "mine.txt")
require.NoError(t, err)
_, err = operations.Copy(ctx, f, nil, "dir/copied.txt", mine)
assert.Error(t, err, "copied in")
_, err = operations.Move(ctx, f, nil, "dir/moved.txt", mine)
assert.Error(t, err, "moved in")
existing, err := f.NewObject(ctx, "dir/existing.txt")
require.NoError(t, err)
_, err = operations.Move(ctx, f, nil, "dir/renamed.txt", existing)
assert.Error(t, err, "renamed")
assert.Len(t, u.Dump(), before, "something was written")
got, err := readAll(ctx, existing)
require.NoError(t, err, "reading isn't affected")
assert.Equal(t, "existing", string(got))
shutdown(t, f)
capture := captureLog(t, 0)
f = newFakeFs(t, strings.TrimSuffix(remote, ":")+",ignore_signature_errors=true:", "")
for _, name := range []string{"a.txt", "b.txt"} {
src := object.NewMemoryObject("dir/"+name, time.Now(), []byte("allowed"))
_, err = operations.Copy(ctx, f, nil, src.Remote(), src)
require.NoError(t, err, "upload with signature checks off")
}
want := fmt.Sprintf("ERROR : protondrive: writing into %q (ID %s) although its hash key isn't verified", "dir", dir)
assert.Equal(t, 1, strings.Count(capture.String(), want), "%q logged other than once in:\n%s", want, capture.String())
})
t.Run("renaming or moving a node whose name the server encrypted", func(t *testing.T) {
ctx := context.Background()
remote, _, u := setupFakeRemote(t)
u.SeedFolder(u.RootID(), "dir")
renamed := u.SeedFile(u.RootID(), "renamed.txt", []byte("a"), time.Now())
moved := u.SeedFile(u.RootID(), "moved.txt", []byte("b"), time.Now())
control := u.SeedFile(u.RootID(), "control.txt", []byte("c"), time.Now())
serverKeys := map[string][]byte{}
for _, id := range []string{renamed, moved} {
u.Corrupt(id, "name-unsigned")
serverKeys[id] = u.NameSessionKey(id)
}
controlKey := u.NameSessionKey(control)
f := newFakeFs(t, remote, "")
for _, op := range []struct{ from, to, id string }{
{"renamed.txt", "secret-new-name.txt", renamed},
{"moved.txt", "dir/secret-moved-name.txt", moved},
} {
o, err := f.NewObject(ctx, op.from)
require.NoError(t, err)
_, err = operations.Move(ctx, f, nil, op.to, o)
require.NoError(t, err)
assert.NotEqual(t, serverKeys[op.id], u.NameSessionKey(op.id), "%s: the new name is under the server's session key", op.to)
}
o, err := f.NewObject(ctx, "control.txt")
require.NoError(t, err)
_, err = operations.Move(ctx, f, nil, "control-renamed.txt", o)
require.NoError(t, err)
assert.Equal(t, controlKey, u.NameSessionKey(control), "a verified name keeps its session key, as in the SDK")
})
t.Run("unsigned extended attributes", func(t *testing.T) {
ctx := context.Background()
remote, _, u := setupFakeRemote(t)
content := patternedContent(blockSize+10, 18)
modTime := time.Date(2025, 3, 4, 5, 6, 7, 0, time.UTC)
id := u.SeedFile(u.RootID(), "victim.bin", content, modTime)
dir := u.SeedFolder(u.RootID(), "dir")
u.Corrupt(id, "xattrs-unsigned")
u.Corrupt(dir, "xattrs-unsigned")
forged, err := time.Parse(time.RFC3339, protontest.ForgedModTime)
require.NoError(t, err)
capture := captureLog(t, 0)
f := newFakeFs(t, remote, "")
o, err := f.NewObject(ctx, "victim.bin")
require.NoError(t, err)
assert.False(t, o.ModTime(ctx).Equal(forged), "the forged modification time is used")
sum, err := o.Hash(ctx, hash.SHA1)
require.NoError(t, err)
assert.Empty(t, sum, "the forged SHA-1 is used")
assert.Equal(t, int64(len(content)), o.Size(), "the size comes from the block sizes, which reads check")
got, err := readAll(ctx, o)
require.NoError(t, err, "the file is readable")
assert.True(t, bytes.Equal(content, got))
rc, err := o.Open(ctx, &fs.RangeOption{Start: blockSize, End: blockSize + 9})
require.NoError(t, err)
got, err = io.ReadAll(rc)
require.NoError(t, rc.Close())
require.NoError(t, err)
assert.Equal(t, content[blockSize:], got, "a ranged read")
for _, entry := range mustList(ctx, t, f, "") {
if entry.Remote() == "dir" {
assert.False(t, entry.ModTime(ctx).Equal(forged), "the folder's forged modification time is used")
}
}
assert.Contains(t, capture.String(), "not used")
f = newFakeFs(t, strings.TrimSuffix(remote, ":")+",ignore_signature_errors=true:", "")
o, err = f.NewObject(ctx, "victim.bin")
require.NoError(t, err)
assert.True(t, o.ModTime(ctx).Equal(forged), "with signature checks off the attributes are used")
sum, err = o.Hash(ctx, hash.SHA1)
require.NoError(t, err)
assert.Equal(t, protontest.ForgedSHA1, sum)
})
t.Run("moving or copying out of a folder with a forged key", func(t *testing.T) {
ctx := context.Background()
remote, _, u := setupFakeRemote(t)
forged := u.SeedForgedFolder(u.RootID(), "forged")
u.SeedAnonymousFile(forged, "victim.bin", []byte("forged"), time.Now())
nested := u.SeedAnonymousFolder(forged, "nested")
u.SeedAnonymousFile(nested, "deep.bin", []byte("forged"), time.Now())
u.SeedFolder(u.RootID(), "real")
signed := u.SeedFile(u.RootID(), "signed.bin", []byte("forged"), time.Now())
u.Corrupt(signed, "passphrase-signature")
f := newFakeFs(t, remote, "")
victim, err := f.NewObject(ctx, "forged/victim.bin")
require.NoError(t, err)
_, err = operations.Move(ctx, f, nil, "real/victim.bin", victim)
require.Error(t, err, "moved out")
assert.Contains(t, err.Error(), "ignore_signature_errors")
_, err = operations.Copy(ctx, f, nil, "real/copied.bin", victim)
assert.Error(t, err, "copied out")
assert.Error(t, f.Features().DirMove(ctx, f, "forged/nested", "real/nested"), "folder moved out")
assert.Error(t, f.Features().DirMove(ctx, f, "forged", "real/forged"), "forged folder moved")
o, err := f.NewObject(ctx, "signed.bin")
require.NoError(t, err)
_, err = operations.Move(ctx, f, nil, "renamed.bin", o)
assert.Error(t, err, "renamed")
f = newFakeFs(t, remote, "")
assert.Empty(t, mustList(ctx, t, f, "real"), "something reached real")
for _, path := range []string{"forged/victim.bin", "forged/nested/deep.bin", "signed.bin"} {
o, err := f.NewObject(ctx, path)
require.NoError(t, err, path)
_, err = readAll(ctx, o)
assert.Error(t, err, "%s became readable", path)
}
})
t.Run("what is written into a folder with a forged key stays unverified", func(t *testing.T) {
ctx := context.Background()
remote, _, u := setupFakeRemote(t)
u.SeedForgedFolder(u.RootID(), "forged")
ignoring := newFakeFs(t, strings.TrimSuffix(remote, ":")+",ignore_signature_errors=true:", "")
require.NoError(t, ignoring.Mkdir(ctx, "forged/made"))
src := object.NewMemoryObject("forged/made/file.txt", time.Now(), []byte("written"))
_, err := operations.Copy(ctx, ignoring, nil, src.Remote(), src)
require.NoError(t, err)
// Whoever made the folder's key can read the keys of what is in
// it, however it is signed.
f := newFakeFs(t, remote, "")
o, err := f.NewObject(ctx, "forged/made/file.txt")
require.NoError(t, err)
_, err = readAll(ctx, o)
assert.Error(t, err, "read")
src = object.NewMemoryObject("forged/made/more.txt", time.Now(), []byte("secret"))
_, err = operations.Copy(ctx, f, nil, src.Remote(), src)
assert.Error(t, err, "uploaded")
})
for _, forge := range []struct {
name string
apply func(u, other *protontest.User)
}{
{"drive shared by another user", func(u, other *protontest.User) { u.ForgeShareCreator(other, other.Email()) }},
{"root folder signed by another user", func(u, other *protontest.User) { u.ForgeRootSigner(other, other.Email()) }},
} {
t.Run(forge.name, func(t *testing.T) {
ctx := context.Background()
remote, srv, u := setupFakeRemote(t)
u.SeedFile(u.RootID(), "file.txt", []byte("content"), time.Now())
forge.apply(u, srv.AddUser("other", "pass"))
f := newFakeFs(t, remote, "")
o, err := f.NewObject(ctx, "file.txt")
require.NoError(t, err, "listing works")
got, err := readAll(ctx, o)
require.Error(t, err, "read")
assert.Empty(t, got)
assert.Contains(t, err.Error(), "not one of your addresses")
assert.Contains(t, err.Error(), "ignore_signature_errors")
src := object.NewMemoryObject("new.txt", time.Now(), []byte("secret"))
_, err = operations.Copy(ctx, f, nil, src.Remote(), src)
require.Error(t, err, "uploaded")
assert.Contains(t, err.Error(), "not one of your addresses")
f = newFakeFs(t, strings.TrimSuffix(remote, ":")+",ignore_signature_errors=true:", "")
o, err = f.NewObject(ctx, "file.txt")
require.NoError(t, err)
got, err = readAll(ctx, o)
require.NoError(t, err, "read with signature checks off")
assert.Equal(t, "content", string(got))
})
}
t.Run("a range covering the whole of a file with swapped blocks", func(t *testing.T) {
ctx := context.Background()
remote, _, u := setupFakeRemote(t)
content := patternedContent(2*blockSize+10, 13)
seedCorrupted("swap-blocks")(u, content)
f := newFakeFs(t, remote, "")
o, err := f.NewObject(ctx, "victim.bin")
require.NoError(t, err)
size := int64(len(content))
require.Equal(t, size, o.Size())
for _, r := range []fs.RangeOption{{Start: 0, End: -1}, {Start: 0, End: size - 1}, {Start: 0, End: size + 100}} {
rc, err := o.Open(ctx, &r)
var got []byte
if err == nil {
got, err = io.ReadAll(rc)
_ = rc.Close()
}
assert.Error(t, err, "%v read without error", r)
assert.Zero(t, len(got), "%v: bytes released before the error", r)
}
})
// Forgeries signed by another user's key under an email, which
// return the path of a file beneath them.
ownAddressForgeries := []struct {
name string
forge func(u, other *protontest.User, email string) string
root bool // whether the forgery is of the drive's share or root
}{
{"share creator", func(u, other *protontest.User, email string) string {
u.SeedFile(u.RootID(), "file.txt", []byte("content"), time.Now())
u.ForgeShareCreator(other, email)
return "file.txt"
}, true},
{"root folder signer", func(u, other *protontest.User, email string) string {
u.SeedFile(u.RootID(), "file.txt", []byte("content"), time.Now())
u.ForgeRootSigner(other, email)
return "file.txt"
}, true},
{"folder signer", func(u, other *protontest.User, email string) string {
dir := u.SeedFolderSignedAs(other, email, u.RootID(), "dir")
u.SeedFile(dir, "file.txt", []byte("content"), time.Now())
return "dir/file.txt"
}, false},
{"file signer", func(u, other *protontest.User, email string) string {
u.SeedFileSignedAs(other, email, u.RootID(), "file.txt", []byte("content"))
return "file.txt"
}, false},
}
for _, forgery := range ownAddressForgeries {
for _, variant := range []struct {
name string
email string
own bool // whether the email is the user's own address
}{
{"in capitals", "USER@PROTON.TEST", true},
// U+017F folds to s under Unicode case folding, so isn't
// the user's address.
{"with a long s", "u\u017fer@proton.test", false},
} {
if !variant.own && !forgery.root {
// Another user's signature below the root is checked
// against keys the server serves: a protocol limit.
continue
}
t.Run(forgery.name+" as the user's address "+variant.name, func(t *testing.T) {
ctx := context.Background()
remote, srv, u := setupFakeRemote(t)
other := srv.AddUser("other", "pass")
path := forgery.forge(u, other, variant.email)
srv.ServeKeysAs(variant.email, other)
srv.ResetRequests()
f := newFakeFs(t, remote, "")
o, err := f.NewObject(ctx, path)
require.NoError(t, err, "listing works")
got, err := readAll(ctx, o)
require.Error(t, err, "read")
assert.Empty(t, got)
assert.Contains(t, err.Error(), "ignore_signature_errors")
if variant.own {
assert.Zero(t, srv.Requests()["GET /core/v4/keys/all"], "the server was asked for the user's own keys")
} else {
assert.Contains(t, err.Error(), "not one of your addresses")
}
})
}
}
t.Run("own address stored in mixed case", func(t *testing.T) {
ctx := context.Background()
srv := protontest.New(t)
u := srv.AddUser("Mixed@Proton.Test", "pass")
u.SeedFileSignedAs(u, "mixed@PROTON.test", u.RootID(), "file.txt", []byte("content"))
u.ForgeShareCreator(u, "mixed@proton.test")
u.ForgeRootSigner(u, "MIXED@proton.test")
srv.ResetRequests()
f, err := protondrive.NewFs(ctx, "mixed", "", sessionMap(srv, u))
require.NoError(t, err)
o, err := f.NewObject(ctx, "file.txt")
require.NoError(t, err)
got, err := readAll(ctx, o)
require.NoError(t, err)
assert.Equal(t, "content", string(got))
assert.Zero(t, srv.Requests()["GET /core/v4/keys/all"], "the server was asked for the user's own keys")
})
t.Run("what signature checks off let through on unverified nodes is logged", func(t *testing.T) {
ctx := context.Background()
remote, _, u := setupFakeRemote(t)
forged := u.SeedForgedFolder(u.RootID(), "forged")
victimID := u.SeedAnonymousFile(forged, "victim.bin", []byte("forged"), time.Now())
u.SeedAnonymousFile(forged, "other.bin", []byte("forged"), time.Now())
u.SeedFolder(u.RootID(), "real")
mineID := u.SeedFile(u.RootID(), "mine.txt", []byte("mine"), time.Now())
capture := captureLog(t, 0)
f := newFakeFs(t, strings.TrimSuffix(remote, ":")+",ignore_signature_errors=true:", "")
for range 2 {
o, err := f.NewObject(ctx, "forged/victim.bin")
require.NoError(t, err)
_, err = readAll(ctx, o)
require.NoError(t, err)
}
for _, name := range []string{"a.txt", "b.txt"} {
src := object.NewMemoryObject("forged/"+name, time.Now(), []byte("x"))
_, err := operations.Copy(ctx, f, nil, src.Remote(), src)
require.NoError(t, err)
}
other, err := f.NewObject(ctx, "forged/other.bin")
require.NoError(t, err)
_, err = operations.Copy(ctx, f, nil, "real/other.bin", other)
require.NoError(t, err)
victim, err := f.NewObject(ctx, "forged/victim.bin")
require.NoError(t, err)
_, err = operations.Move(ctx, f, nil, "real/victim.bin", victim)
require.NoError(t, err)
mine, err := f.NewObject(ctx, "mine.txt")
require.NoError(t, err)
_, err = readAll(ctx, mine)
require.NoError(t, err)
_, err = operations.Copy(ctx, f, nil, "real/mine.txt", mine)
require.NoError(t, err)
log := capture.String()
const unverified = "although its key isn't verified"
for _, want := range []string{
`ERROR : protondrive: reading "victim.bin" (ID ` + victimID + `) ` + unverified,
`ERROR : protondrive: writing into "forged" (ID ` + forged + `) ` + unverified,
`ERROR : protondrive: copying "other.bin"`,
`ERROR : protondrive: moving "victim.bin" (ID ` + victimID + `) ` + unverified,
} {
assert.Equal(t, 1, strings.Count(log, want), "%q logged other than once in:\n%s", want, log)
}
assert.Contains(t, log, "trusted from now on")
assert.NotContains(t, log, mineID, "a verified file was reported")
assert.Equal(t, 4, strings.Count(log, unverified), log)
})
t.Run("a range covering the whole of a file claiming a smaller size", func(t *testing.T) {
ctx := context.Background()
remote, _, u := setupFakeRemote(t)
content := patternedContent(blockSize+10, 14)
id := u.SeedFile(u.RootID(), "short.bin", content, time.Now())
const claimed = 100
u.ClaimSize(id, claimed)
f := newFakeFs(t, remote, "")
o, err := f.NewObject(ctx, "short.bin")
require.NoError(t, err)
require.Equal(t, int64(claimed), o.Size())
for _, r := range []fs.RangeOption{{Start: 0, End: -1}, {Start: 0, End: claimed - 1}} {
rc, err := o.Open(ctx, &r)
require.NoError(t, err)
got, err := io.ReadAll(rc)
require.NoError(t, rc.Close())
require.NoError(t, err, "%v", r)
assert.True(t, bytes.Equal(content[:claimed], got), "%v returned %d bytes, not the %d asked for", r, len(got), claimed)
}
})
t.Run("updating a file with an attacker-signed passphrase", func(t *testing.T) {
ctx := context.Background()
remote, _, u := setupFakeRemote(t)
id := u.SeedFile(u.RootID(), "victim.bin", []byte("original"), time.Now())
u.Corrupt(id, "passphrase-signature")
f := newFakeFs(t, remote, "")
o, err := f.NewObject(ctx, "victim.bin")
require.NoError(t, err)
err = o.Update(ctx, bytes.NewReader([]byte("secret")), object.NewStaticObjectInfo("victim.bin", time.Now(), 6, true, nil, nil))
require.Error(t, err, "a new revision was encrypted to the attacker's key")
assert.Contains(t, err.Error(), "ignore_signature_errors")
for _, n := range u.Dump() {
if n.ID == id {
assert.Equal(t, "original", string(n.Content))
}
}
})
for _, corruption := range []string{"content-key-unsigned", "content-key-signature"} {
t.Run("ranged reads and updates of a file with "+corruption, func(t *testing.T) {
ctx := context.Background()
remote, _, u := setupFakeRemote(t)
content := patternedContent(blockSize+10, 17)
id := u.SeedFile(u.RootID(), "victim.bin", content, time.Now())
u.Corrupt(id, corruption)
info := object.NewStaticObjectInfo("victim.bin", time.Now(), 6, true, nil, nil)
f := newFakeFs(t, remote, "")
o, err := f.NewObject(ctx, "victim.bin")
require.NoError(t, err)
for _, r := range []fs.RangeOption{{Start: 1, End: 100}, {Start: blockSize, End: -1}} {
rc, err := o.Open(ctx, &r)
var got []byte
if err == nil {
got, err = io.ReadAll(rc)
_ = rc.Close()
}
require.Error(t, err, "%v read", r)
assert.Empty(t, got, "%v: bytes released", r)
assert.Contains(t, err.Error(), "ignore_signature_errors")
}
err = o.Update(ctx, bytes.NewReader([]byte("secret")), info)
require.Error(t, err, "a new revision was encrypted with the server's content key")
assert.Contains(t, err.Error(), "ignore_signature_errors")
for _, n := range u.Dump() {
if n.ID == id {
assert.Equal(t, content, n.Content)
}
}
// With signature checks off it goes ahead, logged once
// per operation.
shutdown(t, f)
capture := captureLog(t, 0)
f = newFakeFs(t, strings.TrimSuffix(remote, ":")+",ignore_signature_errors=true:", "")
for range 2 {
o, err = f.NewObject(ctx, "victim.bin")
require.NoError(t, err)
got, err := readAll(ctx, o)
require.NoError(t, err)
assert.True(t, bytes.Equal(content, got))
}
require.NoError(t, o.Update(ctx, bytes.NewReader([]byte("secret")), info))
log := capture.String()
for _, op := range []string{"reading", "updating"} {
want := fmt.Sprintf("ERROR : protondrive: %s %q (ID %s): content key", op, "victim.bin", id)
assert.Equal(t, 1, strings.Count(log, want), "%q logged other than once in:\n%s", want, log)
}
})
}
t.Run("names", func(t *testing.T) {
// Its own stats, so the sync sees only its own errors.
ctx := accounting.WithStatsGroup(context.Background(), "hostile names")
remote, _, u := setupFakeRemote(t)
dir := u.SeedFolder(u.RootID(), "dir")
for i, name := range hostileNames {
u.SeedFile(dir, name, []byte("hostile file"), time.Now())
// At the root, "../x" would land beside a sync's destination.
u.SeedFile(u.RootID(), name, []byte("hostile file"), time.Now())
sub := u.SeedFolder(u.RootID(), fmt.Sprintf("sub %d", i))
u.SeedFolder(sub, name)
}
// A legitimate name rclone shows with a lookalike of /.
u.SeedFile(dir, "a/b", []byte("fine"), time.Now())
u.SeedFile(dir, "ok.txt", []byte("fine"), time.Now())
f := newFakeFs(t, remote, "")
var before runtime.MemStats
runtime.ReadMemStats(&before)
start := time.Now()
entries, err := f.List(ctx, "dir")
elapsed := time.Since(start)
var after runtime.MemStats
runtime.ReadMemStats(&after)
require.NoError(t, err)
t.Logf("listing took %v and allocated %d MiB, the fake's encoding included", elapsed, (after.TotalAlloc-before.TotalAlloc)>>20)
assert.Less(t, elapsed, 30*time.Second)
var remotes []string
for _, entry := range entries {
remotes = append(remotes, entry.Remote())
leaf, ok := strings.CutPrefix(entry.Remote(), "dir/")
assert.True(t, ok, "%q is outside dir", entry.Remote())
assert.NotContains(t, leaf, "/")
assert.NotContains(t, leaf, "\x00")
assert.NotEqual(t, "..", leaf)
assert.NotEqual(t, ".", leaf)
}
assert.Len(t, remotes, 2, "%q", remotes)
assert.Contains(t, remotes, "dir/ok.txt")
for _, entry := range mustList(ctx, t, f, "") {
if d, ok := entry.(fs.Directory); ok && strings.HasPrefix(d.Remote(), "sub ") {
assert.Empty(t, mustList(ctx, t, f, d.Remote()), "hostile folder listed in %q", d.Remote())
}
}
// A sync of the whole remote writes only inside its
// destination.
parent := t.TempDir()
dst := newFakeFs(t, "", filepath.Join(parent, "dst"))
require.NoError(t, fssync.Sync(ctx, dst, newFakeFs(t, remote, ""), false))
var written []string
require.NoError(t, filepath.WalkDir(parent, func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
rel, err := filepath.Rel(parent, path)
written = append(written, filepath.ToSlash(rel))
return err
}))
assert.NotContains(t, written, "x")
for _, path := range written {
assert.True(t, path == "." || path == "dst" || strings.HasPrefix(path, "dst/"), "%q written outside the destination", path)
}
assert.Contains(t, written, "dst/dir/ok.txt")
})
}
// mustList lists dir of f.
func mustList(ctx context.Context, t *testing.T, f fs.Fs, dir string) fs.DirEntries {
t.Helper()
entries, err := f.List(ctx, dir)
require.NoError(t, err)
return entries
}
// logCapture holds rclone's log output while it is captured.
type logCapture struct {
mu sync.Mutex
buf strings.Builder
}
// String returns the log output captured so far.
func (c *logCapture) String() string {
c.mu.Lock()
defer c.mu.Unlock()
return c.buf.String()
}
// captureLog captures rclone's log output at debug level, with the HTTP
// dumps of dump, until the test ends.
//
// It changes rclone's global log config, which a poll for changes
// reads, so no Fs may be polling when it is called: make them after
// it, or shut them down. The TestProtonDriveFake: remote doesn't poll
// in the rest of the test, as its polls could end after the config is
// put back.
func captureLog(t *testing.T, dump fs.DumpFlags) *logCapture {
t.Setenv(fakeEnvPrefix+"EVENTS_MIN_INTERVAL", "0")
c := &logCapture{}
log.Handler.SetOutput(func(level slog.Level, text string) {
c.mu.Lock()
defer c.mu.Unlock()
c.buf.WriteString(text)
})
oldLevel := log.Handler.SetLevel(slog.LevelDebug)
ci := fs.GetConfig(context.Background())
oldLogLevel, oldDump := ci.LogLevel, ci.Dump
ci.LogLevel, ci.Dump = fs.LogLevelDebug, dump
t.Cleanup(func() {
ci.LogLevel, ci.Dump = oldLogLevel, oldDump
log.Handler.SetLevel(oldLevel)
log.Handler.ResetOutput()
})
return c
}
// shutdown shuts f down, which stops it polling for changes until it
// is used again.
func shutdown(t *testing.T, f fs.Fs) {
t.Helper()
require.NoError(t, f.(fs.Shutdowner).Shutdown(context.Background()))
}
// secretForms returns the forms a secret could take in a log line.
func secretForms(secret []byte) []string {
forms := []string{base64.StdEncoding.EncodeToString(secret), base64.RawURLEncoding.EncodeToString(secret), hex.EncodeToString(secret)}
if len(secret) >= 8 {
forms = append(forms, string(secret))
}
return forms
}
// assertNoSecrets checks log contains no form of any of secrets,
// described by what.
func assertNoSecrets(t *testing.T, log, what string, secrets ...[]byte) {
t.Helper()
for i, secret := range secrets {
require.NotEmpty(t, secret, "%s %d is empty", what, i)
for _, form := range secretForms(secret) {
assert.False(t, strings.Contains(log, form), "the log holds %s %d as %q", what, i, form)
}
}
}
// secretRun is what a run of signing in, uploading, downloading and
// disconnecting revealed to the test.
type secretRun struct {
log string
passwords [][]byte // the password and mailbox password
keyPassword []byte
sessionTokens [][]byte // every access and refresh token issued
storageTokens [][]byte // every block upload and download token
nodeSecrets [][]byte // node passphrases and content session keys
}
// runSignedInSession signs in with a password, uploads a 5 MiB file,
// refreshes the session, downloads files and disconnects, with rclone's
// log captured with dump.
func runSignedInSession(t *testing.T, dump fs.DumpFlags) secretRun {
ctx := context.Background()
const password, mailboxPassword = "password-Hunter2-3f9c1a", "mailbox-Hunter2-7b2d4e"
srv := protontest.New(t)
u := srv.AddTwoPasswordUser("user", password, mailboxPassword)
stored := u.SeedFile(u.RootID(), "stored.bin", patternedContent(blockSize+10, 11), time.Now())
damaged := u.SeedFile(u.RootID(), "damaged.bin", patternedContent(100, 12), time.Now())
u.Corrupt(damaged, "block-hash")
m := newLockedMap(configmap.Simple{
"endpoint": srv.URL(),
"username": "user",
"password": obscure.MustObscure(password),
"mailbox_password": obscure.MustObscure(mailboxPassword),
"original_file_size": "true",
})
capture := captureLog(t, dump)
f, err := protondrive.NewFs(ctx, "secrets", "", m)
require.NoError(t, err)
content := []byte(random.String(5 << 20))
uploaded, err := operations.Copy(ctx, f, nil, "upload.bin", object.NewMemoryObject("upload.bin", time.Now(), content))
require.NoError(t, err)
uid, _ := m.Get("client_uid")
srv.ExpireAccessToken(uid)
f.(fs.DirCacheFlusher).DirCacheFlush()
for _, name := range []string{"upload.bin", "stored.bin"} {
o, err := f.NewObject(ctx, name)
require.NoError(t, err)
_, err = readAll(ctx, o)
require.NoError(t, err, name)
}
o, err := f.NewObject(ctx, "damaged.bin")
require.NoError(t, err)
_, err = readAll(ctx, o)
require.Error(t, err)
require.NoError(t, f.Features().Disconnect(ctx))
run := secretRun{
log: capture.String(),
passwords: [][]byte{[]byte(password), []byte(mailboxPassword)},
keyPassword: []byte(u.KeyPassword()),
}
// Every token issued, including those never saved.
for _, token := range srv.IssuedSecrets(protontest.SessionToken) {
run.sessionTokens = append(run.sessionTokens, []byte(token))
}
for _, key := range []string{"client_access_token", "client_refresh_token"} {
saved := m.values(key)
require.NotEmpty(t, saved, key)
for _, token := range saved {
if token != "" {
require.Contains(t, run.sessionTokens, []byte(token), "%s isn't one the server issued", key)
}
}
}
for _, token := range srv.IssuedSecrets(protontest.StorageToken) {
run.storageTokens = append(run.storageTokens, []byte(token))
}
require.NotEmpty(t, run.storageTokens)
for _, id := range []string{uploaded.(fs.IDer).ID(), stored, damaged} {
passphrase, sessionKey := u.NodeSecrets(id)
run.nodeSecrets = append(run.nodeSecrets, passphrase, sessionKey)
}
require.Contains(t, run.log, "refreshing session", "debug output not captured")
return run
}
// TestNoSecretsInLogs checks no secret reaches rclone's log at debug
// level across sign-in, upload, download and Disconnect.
func TestDriveRequirementsLogged(t *testing.T) {
ctx := context.Background()
remote, srv, u := setupFakeRemote(t)
u.SeedFile(u.RootID(), "a.txt", []byte("a"), time.Now())
srv.SetDriveRequirements("min-version=1.2.3", "crypto=v2")
capture := captureLog(t, 0)
f := newFakeFs(t, remote, "")
for range 3 {
mustList(ctx, t, f, "")
}
srv.SetDriveRequirements("min-version=2.0.0")
for range 2 {
_, err := f.Features().About(ctx)
require.NoError(t, err)
}
log := capture.String()
first := `DEBUG : protondrive: Proton announces drive requirements: "min-version=1.2.3, crypto=v2"`
assert.Equal(t, 1, strings.Count(log, first), "%q logged other than once in:\n%s", first, log)
second := `DEBUG : protondrive: Proton announces drive requirements: "min-version=2.0.0"`
assert.Equal(t, 1, strings.Count(log, second), "%q logged other than once in:\n%s", second, log)
}
func TestNoSecretsInLogs(t *testing.T) {
t.Run("debug", func(t *testing.T) {
run := runSignedInSession(t, 0)
assertNoSecrets(t, run.log, "password", run.passwords...)
assertNoSecrets(t, run.log, "key password", run.keyPassword)
assertNoSecrets(t, run.log, "session token", run.sessionTokens...)
assertNoSecrets(t, run.log, "pm-storage-token", run.storageTokens...)
assertNoSecrets(t, run.log, "node secret", run.nodeSecrets...)
})
// --dump headers shows the headers fshttp doesn't redact, of
// which pm-storage-token and x-pm-uid are Proton's, but never the
// Authorization header with the access token. --dump bodies shows
// the tokens in sign-in and refresh responses, as spec section 7
// says, so isn't checked.
t.Run("dump headers", func(t *testing.T) {
run := runSignedInSession(t, fs.DumpHeaders)
require.Contains(t, run.log, "HTTP REQUEST", "headers not dumped")
assertNoSecrets(t, run.log, "password", run.passwords...)
assertNoSecrets(t, run.log, "key password", run.keyPassword)
assertNoSecrets(t, run.log, "session token", run.sessionTokens...)
assertNoSecrets(t, run.log, "node secret", run.nodeSecrets...)
})
}
// allValues returns every value m held or was set to, by key.
func allValues(m *lockedMap) map[string][]string {
m.mu.Lock()
defer m.mu.Unlock()
all := map[string][]string{}
for k, v := range m.m {
all[k] = append(all[k], v)
}
for k, vs := range m.set {
all[k] = append(all[k], vs...)
}
return all
}
// TestConfigHoldsNoPasswordAfterBrowserSignIn checks browser sign-in
// leaves no password in the config, and logs none of its secrets.
func TestConfigHoldsNoPasswordAfterBrowserSignIn(t *testing.T) {
ctx := context.Background()
const password = "browser-Hunter2-9e8d7c"
srv := protontest.New(t)
u := srv.AddUser("user", password)
m := newLockedMap(configmap.Simple{"endpoint": srv.URL()})
capture := captureLog(t, 0)
var signInURL string
require.NoError(t, protondrive.ConfigBrowserSignIn(ctx, "browser", m, func(shown string) {
signInURL = shown
require.NoError(t, srv.ApproveFork(shown, u))
}))
_, err := protondrive.NewFs(ctx, "browser", "", m)
require.NoError(t, err, "the session works")
for _, key := range []string{"password", "mailbox_password"} {
assert.Empty(t, m.values(key), "%s set", key)
}
for key, values := range allValues(m) {
for _, v := range values {
assert.NotContains(t, v, password, "%s holds the password", key)
if v != "" {
revealed, err := obscure.Reveal(v)
assert.False(t, err == nil && strings.Contains(revealed, password), "%s holds the password obscured", key)
}
}
}
log := capture.String()
fragment := signInURL[strings.Index(signInURL, "#")+1:]
assert.NotContains(t, log, fragment, "the sign-in URL's secret is logged")
var secrets [][]byte
for _, secret := range srv.IssuedSecrets() {
secrets = append(secrets, []byte(secret))
}
assertNoSecrets(t, log, "issued secret", secrets...)
assertNoSecrets(t, log, "key password", []byte(u.KeyPassword()))
}
// TestPasswordStoredObscured checks rclone config, given the password
// in plain text, stores it obscured and signs in with it, writing no
// password to the config itself.
func TestPasswordStoredObscured(t *testing.T) {
ctx := context.Background()
const password, mailboxPassword = "stored-Hunter2-1a2b3c", "stored-mailbox-4d5e6f"
srv := protontest.New(t)
srv.AddTwoPasswordUser("user", password, mailboxPassword)
oldPath, oldData := config.GetConfigPath(), config.Data()
path := filepath.Join(t.TempDir(), "rclone.conf")
require.NoError(t, config.SetConfigPath(path))
t.Cleanup(func() {
// SetData does nothing without a config path.
config.SetData(oldData)
assert.True(t, config.Data() == oldData, "the config storage isn't restored")
assert.NoError(t, config.SetConfigPath(oldPath))
})
configfile.Install()
// As "rclone config create obscured protondrive ... --obscure".
opt := config.UpdateRemoteOpt{Obscure: true, NonInteractive: true}
out, err := config.CreateRemote(ctx, "obscured", "protondrive", rc.Params{
"endpoint": srv.URL(),
"username": "user",
"password": password,
"mailbox_password": mailboxPassword,
}, opt)
for range 5 {
require.NoError(t, err)
if out == nil || out.State == "" {
break
}
require.Equal(t, "choose", out.State, "unexpected question: %+v", out.Option)
out, err = config.UpdateRemote(ctx, "obscured", rc.Params{}, config.UpdateRemoteOpt{Continue: true, NonInteractive: true, State: out.State, Result: "false"})
}
require.True(t, out == nil || out.State == "", "config didn't finish")
for key, plain := range map[string]string{"password": password, "mailbox_password": mailboxPassword} {
stored, ok := config.FileGetValue("obscured", key)
require.True(t, ok, key)
assert.NotEqual(t, plain, stored, key)
revealed, err := obscure.Reveal(stored)
require.NoError(t, err, key)
assert.Equal(t, plain, revealed, key)
}
uid, _ := config.FileGetValue("obscured", "client_uid")
assert.NotEmpty(t, uid, "not signed in")
file, err := os.ReadFile(path)
require.NoError(t, err)
assert.NotContains(t, string(file), password)
assert.NotContains(t, string(file), mailboxPassword)
}