Files
rclone/backend/protondrive/session_internal_test.go
T
Lucas WintherandClaude Opus 5.5 6ec49842c4 protondrive: load and unlock account keys
Load the user and addresses and unlock their keys, one unlock at a time
across all sessions so concurrent sign-ins don't multiply peak memory.
Address key passphrases are taken from their Token only when the user
key's signature on it verifies, as the SDK requires. Other users' public
keys are fetched once per account and cached, an email without a Proton
address having no keys.

Password sign-in now derives the key password from the salt of the
primary user key rather than the first salt, which is wrong for accounts
whose user keys have different salts. The SDK uses the first salt; it
remains the fallback when no salt matches.

The fake server gives each user real Curve25519 user and address keys,
and serves GET /core/v4/users, /core/v4/addresses and /core/v4/keys/all.

gopenpgp v3 moves to a direct dependency.

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

525 lines
17 KiB
Go

package protondrive
import (
"bytes"
"context"
"encoding/base64"
"errors"
"net/http"
"net/url"
"regexp"
"strings"
"sync"
"testing"
"time"
"github.com/pquerna/otp/totp"
"github.com/rclone/rclone/backend/protondrive/api"
"github.com/rclone/rclone/backend/protondrive/protontest"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/lib/rest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
testAppVersion = "external-drive-rclone@1.77.0-stable"
refreshRoute = "POST /auth/v4/refresh"
)
// appVersionGrammar is Proton's x-pm-appversion grammar with the name
// fixed to rclone and the channel required.
var appVersionGrammar = regexp.MustCompile(`^external-drive-rclone@[0-9]+\.[0-9]+\.[0-9]+-(stable|beta|alpha)(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$`)
func TestAppVersionFromRcloneVersion(t *testing.T) {
for _, test := range []struct {
in string
want string
}{
{"v1.77.0", "external-drive-rclone@1.77.0-stable"},
{"1.77.0", "external-drive-rclone@1.77.0-stable"},
{"v1.77.0-DEV", "external-drive-rclone@1.77.0-alpha"},
{"v1.77.0-beta.10754.448d7361c", "external-drive-rclone@1.77.0-beta+10754.448d7361c"},
{"v1.77.0-beta.10754.448d7361c.fix/proton_drive", "external-drive-rclone@1.77.0-beta+10754.448d7361c.fix-proton-drive"},
{"v1.77.0-beta", "external-drive-rclone@1.77.0-beta"},
{"v1.77.0-rc1", "external-drive-rclone@1.77.0-alpha"},
{"garbage", "external-drive-rclone@1.0.0-stable"},
{"", "external-drive-rclone@1.0.0-stable"},
{"v1.77", "external-drive-rclone@1.0.0-stable"},
} {
got := appVersionFromRcloneVersion(test.in)
assert.Equal(t, test.want, got, "input %q", test.in)
assert.Regexp(t, appVersionGrammar, got, "input %q", test.in)
}
}
// headerRecorder records the headers of every request it sends.
type headerRecorder struct {
mu sync.Mutex
headers []http.Header
next http.RoundTripper
}
func (h *headerRecorder) RoundTrip(req *http.Request) (*http.Response, error) {
h.mu.Lock()
h.headers = append(h.headers, req.Header.Clone())
h.mu.Unlock()
return h.next.RoundTrip(req)
}
// newTestSession signs a new user in to srv and returns a session using
// a store holding its credentials.
func newTestSession(t *testing.T, srv *protontest.Server) (*session, *memoryStore, protontest.Session) {
t.Helper()
tokens := srv.NewSession(srv.AddUser("user", "pass"))
store := &memoryStore{creds: credentials{
UID: tokens.UID,
AccessToken: tokens.AccessToken,
RefreshToken: tokens.RefreshToken,
KeyPassword: "key-pass",
}}
return newSession(srv.Client(), srv.URL(), testAppVersion, store), store, tokens
}
// authCall makes an authenticated test call.
func authCall(ctx context.Context, s *session) error {
var out struct {
UserID string `json:"UserID"`
}
_, err := s.call(ctx, &rest.Opts{Method: "GET", Path: "/tests/auth"}, nil, &out)
if err == nil && out.UserID == "" {
return errors.New("no UserID in response")
}
return err
}
func TestSessionHeaders(t *testing.T) {
srv := protontest.New(t)
tokens := srv.NewSession(srv.AddUser("user", "pass"))
rec := &headerRecorder{next: srv.Client().Transport}
client := &http.Client{Transport: rec}
store := &memoryStore{creds: credentials{UID: tokens.UID, AccessToken: tokens.AccessToken, RefreshToken: tokens.RefreshToken}}
s := newSession(client, srv.URL(), testAppVersion, store)
require.NoError(t, authCall(context.Background(), s))
_, err := s.callUnauthenticated(context.Background(), &rest.Opts{Method: "GET", Path: "/tests/ping"}, nil, nil)
require.NoError(t, err)
require.Len(t, rec.headers, 2)
auth, unauth := rec.headers[0], rec.headers[1]
assert.Equal(t, tokens.UID, auth.Get("x-pm-uid"))
assert.Equal(t, "Bearer "+tokens.AccessToken, auth.Get("Authorization"))
for _, h := range []http.Header{auth, unauth} {
assert.Equal(t, testAppVersion, h.Get("x-pm-appversion"))
assert.Equal(t, "application/vnd.protonmail.v1+json", h.Get("Accept"))
assert.Empty(t, h.Get("x-pm-drive-sdk-version"))
}
assert.Empty(t, unauth.Get("x-pm-uid"))
assert.Empty(t, unauth.Get("Authorization"))
}
func TestSessionUnauthenticatedNoRefresh(t *testing.T) {
srv := protontest.New(t)
s, _, _ := newTestSession(t, srv)
_, err := s.callUnauthenticated(context.Background(), &rest.Opts{Method: "GET", Path: "/tests/auth"}, nil, nil)
var apiErr *api.Error
require.ErrorAs(t, err, &apiErr)
assert.Equal(t, http.StatusUnauthorized, apiErr.Status)
assert.Zero(t, srv.Requests()[refreshRoute])
}
func TestSessionRefreshOn401(t *testing.T) {
srv := protontest.New(t)
s, store, tokens := newTestSession(t, srv)
srv.ExpireAccessToken(tokens.UID)
require.NoError(t, authCall(context.Background(), s))
assert.Equal(t, 1, srv.Requests()[refreshRoute])
assert.Equal(t, 2, srv.Requests()["GET /tests/auth"])
saved := store.Load()
assert.Equal(t, tokens.UID, saved.UID)
assert.NotEqual(t, tokens.AccessToken, saved.AccessToken)
assert.NotEqual(t, tokens.RefreshToken, saved.RefreshToken)
assert.Equal(t, "key-pass", saved.KeyPassword)
// The new tokens are used without another refresh.
require.NoError(t, authCall(context.Background(), s))
assert.Equal(t, 1, srv.Requests()[refreshRoute])
}
func TestSessionRefreshResendsBody(t *testing.T) {
srv := protontest.New(t)
s, _, tokens := newTestSession(t, srv)
type echo struct {
Echo string `json:"Echo"`
}
opts := &rest.Opts{Method: "POST", Path: "/tests/echo"}
srv.ExpireAccessToken(tokens.UID)
var out echo
_, err := s.call(context.Background(), opts, &echo{Echo: "request"}, &out)
require.NoError(t, err)
assert.Equal(t, "request", out.Echo)
srv.ExpireAccessToken(tokens.UID)
out = echo{}
bodyOpts := *opts
bodyOpts.Body = bytes.NewReader([]byte(`{"Echo":"body"}`))
_, err = s.call(context.Background(), &bodyOpts, nil, &out)
require.NoError(t, err)
assert.Equal(t, "body", out.Echo)
assert.Equal(t, 2, srv.Requests()[refreshRoute])
}
func TestSessionRefreshSingleFlight(t *testing.T) {
srv := protontest.New(t)
s, _, tokens := newTestSession(t, srv)
srv.ExpireAccessToken(tokens.UID)
var wg sync.WaitGroup
errs := make([]error, 20)
for i := range errs {
wg.Go(func() {
errs[i] = authCall(context.Background(), s)
})
}
wg.Wait()
for i, err := range errs {
assert.NoError(t, err, "call %d", i)
}
assert.Equal(t, 1, srv.Requests()[refreshRoute])
}
func TestSessionRefreshRereadsStore(t *testing.T) {
srv := protontest.New(t)
a, store, tokens := newTestSession(t, srv)
b := newSession(srv.Client(), srv.URL(), testAppVersion, store)
srv.ExpireAccessToken(tokens.UID)
require.NoError(t, authCall(context.Background(), a))
assert.Equal(t, 1, srv.Requests()[refreshRoute])
// b still holds the rotated tokens, so its first call gets 401 and
// adopts a's tokens from the store instead of reusing its refresh
// token.
require.NoError(t, authCall(context.Background(), b))
assert.Equal(t, 1, srv.Requests()[refreshRoute])
assert.Equal(t, 4, srv.Requests()["GET /tests/auth"])
}
func TestSessionRefreshTwoSessionsConcurrent(t *testing.T) {
srv := protontest.New(t)
a, store, tokens := newTestSession(t, srv)
b := newSession(srv.Client(), srv.URL(), testAppVersion, store)
// Holding each refresh makes both sessions post the same refresh
// token before either saves the new one.
srv.Inject(protontest.Fault{Method: "POST", Pattern: "/auth/v4/refresh", Delay: 200 * time.Millisecond})
srv.ExpireAccessToken(tokens.UID)
var wg sync.WaitGroup
errs := make([]error, 2)
for i, s := range []*session{a, b} {
wg.Go(func() {
errs[i] = authCall(context.Background(), s)
})
}
wg.Wait()
for i, err := range errs {
assert.NoError(t, err, "session %d", i)
}
assert.Equal(t, 2, srv.Requests()[refreshRoute], "both sessions posted the refresh token")
// The stored credentials work in a fresh session.
c := newSession(srv.Client(), srv.URL(), testAppVersion, store)
require.NoError(t, authCall(context.Background(), c))
assert.Equal(t, 2, srv.Requests()[refreshRoute])
}
func TestSessionRevoked(t *testing.T) {
srv := protontest.New(t)
s, store, tokens := newTestSession(t, srv)
s.adoptWait = 50 * time.Millisecond
before := store.Load()
srv.RevokeSession(tokens.UID)
err := authCall(context.Background(), s)
require.Error(t, err)
assert.ErrorIs(t, err, errSessionExpired)
assert.True(t, fserrors.IsFatalError(err), "error is fatal: %v", err)
assert.Contains(t, err.Error(), `rclone config reconnect`)
assert.Equal(t, before, store.Load(), "credentials kept")
assert.Equal(t, 1, srv.Requests()[refreshRoute])
// Further calls fail the same way without retrying the refresh.
err = authCall(context.Background(), s)
assert.ErrorIs(t, err, errSessionExpired)
assert.Equal(t, 1, srv.Requests()[refreshRoute])
assert.Equal(t, before, store.Load(), "credentials kept")
}
func TestSessionServerTime(t *testing.T) {
srv := protontest.New(t)
srv.SetClockSkew(3 * time.Hour)
s, _, _ := newTestSession(t, srv)
assert.True(t, s.serverTime().IsZero())
require.NoError(t, authCall(context.Background(), s))
assert.WithinDuration(t, time.Now().Add(3*time.Hour), s.serverTime(), 5*time.Second)
}
func TestSessionAPIError(t *testing.T) {
for _, status := range []int{http.StatusUnprocessableEntity, http.StatusOK} {
srv := protontest.New(t)
s, _, _ := newTestSession(t, srv)
srv.Inject(protontest.Fault{Pattern: "/tests/auth", Times: 1, Status: status, Code: api.CodeAlreadyExists})
err := authCall(context.Background(), s)
var apiErr *api.Error
require.ErrorAs(t, err, &apiErr, "status %d", status)
assert.Equal(t, status, apiErr.Status)
assert.Equal(t, api.CodeAlreadyExists, apiErr.Code)
assert.Zero(t, srv.Requests()[refreshRoute])
}
}
// newLoginSession returns a session for srv with an empty store.
func newLoginSession(srv *protontest.Server) (*session, *memoryStore) {
store := &memoryStore{}
return newSession(srv.Client(), srv.URL(), testAppVersion, store), store
}
// noTwoFA is a twoFA callback for accounts without 2FA.
func noTwoFA() (string, error) {
return "", errors.New("unexpected 2FA prompt")
}
// requireSignedIn checks store holds complete credentials for a working
// session whose key password derives from keyPassword and u's key salt.
func requireSignedIn(t *testing.T, s *session, store *memoryStore, u *protontest.User, keyPassword string) {
t.Helper()
saved := store.Load()
require.NotEmpty(t, saved.UID)
require.NotEmpty(t, saved.AccessToken)
require.NotEmpty(t, saved.RefreshToken)
want, err := computeKeyPassword([]byte(keyPassword), u.KeySalt)
require.NoError(t, err)
assert.Equal(t, string(want), saved.KeyPassword)
assert.Equal(t, saved, s.current())
require.NoError(t, authCall(context.Background(), s))
}
func TestLoginSRP(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddUser("user", "correct password")
s, store := newLoginSession(srv)
err := s.loginSRP(context.Background(), "user", "wrong password", "", noTwoFA)
require.Error(t, err)
assert.Equal(t, credentials{}, store.Load(), "nothing stored")
assert.Equal(t, credentials{}, s.current())
require.NoError(t, s.loginSRP(context.Background(), "user", "correct password", "", noTwoFA))
requireSignedIn(t, s, store, u, "correct password")
}
func TestLoginSRPSaltOfPrimaryKey(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddUser("user", "pass")
oldSalt := u.KeySalt
u.AddUserKey()
require.NotEqual(t, oldSalt, u.KeySalt)
// The salts list the old key first; the primary key's salt is second.
s, store := newLoginSession(srv)
require.NoError(t, s.loginSRP(context.Background(), "user", "pass", "", noTwoFA))
requireSignedIn(t, s, store, u, "pass")
assert.Equal(t, u.KeyPassword(), store.Load().KeyPassword)
a, err := loadAccount(context.Background(), s, []byte(store.Load().KeyPassword))
require.NoError(t, err)
a.close()
}
func TestPrimaryKeySalt(t *testing.T) {
keys := []api.UserKey{{ID: "old", Primary: 0}, {ID: "new", Primary: 1}}
salts := []api.KeySalt{{ID: "old", KeySalt: "old-salt"}, {ID: "new", KeySalt: "new-salt"}}
salt, ok := primaryKeySalt(keys, salts)
assert.True(t, ok)
assert.Equal(t, "new-salt", salt)
salt, ok = primaryKeySalt(keys, []api.KeySalt{{ID: "other", KeySalt: "first"}, {ID: "x", KeySalt: "second"}})
assert.True(t, ok)
assert.Equal(t, "first", salt, "falls back to the first salt")
salt, ok = primaryKeySalt(nil, salts)
assert.True(t, ok)
assert.Equal(t, "old-salt", salt)
_, ok = primaryKeySalt(keys, nil)
assert.False(t, ok)
}
func TestLoginSRPBadServerProof(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddUser("user", "pass")
srv.CorruptServerProof(u)
s, store := newLoginSession(srv)
err := s.loginSRP(context.Background(), "user", "pass", "", noTwoFA)
require.Error(t, err)
assert.Contains(t, err.Error(), "server proof verification")
assert.Equal(t, credentials{}, store.Load(), "nothing stored")
assert.Equal(t, credentials{}, s.current())
}
func TestLoginSRPPasswords(t *testing.T) {
t.Parallel()
for _, password := range []string{
"with space ",
`quo"te'`,
"пароль-密码",
strings.Repeat("abcdefghij", 10),
} {
t.Run(password, func(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddUser("user", password)
s, store := newLoginSession(srv)
require.NoError(t, s.loginSRP(context.Background(), "user", password, "", noTwoFA))
requireSignedIn(t, s, store, u, password)
})
}
}
func TestLoginSRPMailboxPassword(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddTwoPasswordUser("user", "login password", "mailbox password")
s, store := newLoginSession(srv)
require.NoError(t, s.loginSRP(context.Background(), "user", "login password", "mailbox password", noTwoFA))
requireSignedIn(t, s, store, u, "mailbox password")
// Without the mailbox password the key password can't be derived.
s, store = newLoginSession(srv)
err := s.loginSRP(context.Background(), "user", "login password", "", noTwoFA)
require.Error(t, err)
assert.Contains(t, err.Error(), "mailbox_password")
assert.Equal(t, credentials{}, store.Load())
}
func TestLoginSRPTOTP(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddUser("user", "pass")
secret := u.EnableTOTP()
calls := 0
s, store := newLoginSession(srv)
require.NoError(t, s.loginSRP(context.Background(), "user", "pass", "", func() (string, error) {
calls++
return totp.GenerateCode(secret, time.Now())
}))
assert.Equal(t, 1, calls)
requireSignedIn(t, s, store, u, "pass")
calls = 0
s, store = newLoginSession(srv)
err := s.loginSRP(context.Background(), "user", "pass", "", func() (string, error) {
calls++
return "000000x", nil
})
require.Error(t, err)
assert.Equal(t, 1, calls)
assert.Equal(t, credentials{}, store.Load())
}
func TestLoginSRPCaptcha(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddUser("user", "pass")
srv.RequireCaptcha(u)
s, store := newLoginSession(srv)
err := s.loginSRP(context.Background(), "user", "pass", "", noTwoFA)
require.ErrorIs(t, err, errCaptcha)
assert.Contains(t, err.Error(), "rclone config reconnect")
assert.Equal(t, credentials{}, store.Load())
}
func TestForkLogin(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
u := srv.AddUser("user", "pass")
s, store := newLoginSession(srv)
f, err := s.forkStart(context.Background())
require.NoError(t, err)
assert.NotEmpty(t, f.Selector)
assert.Len(t, f.key, 32)
prefix := "https://account.proton.me/desktop/login?app=drive&pv=3#payload="
require.True(t, strings.HasPrefix(f.URL, prefix), f.URL)
payload, err := url.QueryUnescape(strings.TrimPrefix(f.URL, prefix))
require.NoError(t, err)
assert.Equal(t, "0:"+f.UserCode+":"+base64.StdEncoding.EncodeToString(f.key)+":external-drive", payload)
go func() {
time.Sleep(50 * time.Millisecond)
assert.NoError(t, srv.ApproveFork(f.URL, u))
}()
require.NoError(t, s.forkPoll(context.Background(), f, 10*time.Millisecond, 10*time.Second))
requireSignedIn(t, s, store, u, "pass")
}
func TestForkLoginTimeout(t *testing.T) {
srv := protontest.New(t)
s, store := newLoginSession(srv)
f, err := s.forkStart(context.Background())
require.NoError(t, err)
start := time.Now()
err = s.forkPoll(context.Background(), f, 10*time.Millisecond, 100*time.Millisecond)
require.Error(t, err)
assert.GreaterOrEqual(t, time.Since(start), 100*time.Millisecond)
assert.Less(t, time.Since(start), 5*time.Second)
assert.Greater(t, srv.Requests()["GET /auth/v4/sessions/forks/{selector}"], 1)
assert.Equal(t, credentials{}, store.Load())
}
func TestForkLoginCancel(t *testing.T) {
srv := protontest.New(t)
s, store := newLoginSession(srv)
f, err := s.forkStart(context.Background())
require.NoError(t, err)
ctx, cancel := context.WithCancel(context.Background())
time.AfterFunc(50*time.Millisecond, cancel)
start := time.Now()
err = s.forkPoll(ctx, f, 10*time.Millisecond, 10*time.Minute)
assert.ErrorIs(t, err, context.Canceled)
assert.Less(t, time.Since(start), 5*time.Second)
assert.Equal(t, credentials{}, store.Load())
}
func TestLogout(t *testing.T) {
t.Parallel()
srv := protontest.New(t)
srv.AddUser("user", "pass")
s, store := newLoginSession(srv)
require.NoError(t, s.loginSRP(context.Background(), "user", "pass", "", noTwoFA))
before := store.Load()
require.NoError(t, s.logout(context.Background()))
assert.Equal(t, credentials{}, store.Load())
assert.ErrorIs(t, authCall(context.Background(), s), errSessionExpired)
// The server ended the session too.
old := newSession(srv.Client(), srv.URL(), testAppVersion, &memoryStore{creds: before})
old.adoptWait = 0
assert.ErrorIs(t, authCall(context.Background(), old), errSessionExpired)
}