Files
rclone/backend/protondrive/security_test.go
T
Lucas WintherandClaude Opus 5.5 e7e43095d8 protondrive: restore the config storage even when rclone's config is in memory
The password test's cleanup restored the config path before the
storage, and setting the storage does nothing while the path is empty,
so with an in-memory config the storage was left behind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:10:25 +01:00

731 lines
27 KiB
Go
Raw 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/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,
}}
// 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("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", (*protontest.User).ForgeShareCreator},
{"root folder signed by another user", (*protontest.User).ForgeRootSigner},
} {
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)
}
})
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))
}
}
})
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.
func captureLog(t *testing.T, dump fs.DumpFlags) *logCapture {
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
}
// 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 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)
}