Files
rclone/backend/protondrive/session_internal_test.go
T
Lucas WintherandClaude Opus 5.5 ea41704ade protondrive: add session with safe token refresh
Add the session used for authenticated API calls: it sends x-pm-uid,
the bearer token, x-pm-appversion and the Proton Accept header, decodes
failures into api.Error, and on HTTP 401 refreshes the tokens and
retries once. Refresh is single-flight, first adopts tokens another
session saved to the shared store, and on a rejected refresh token
returns a fatal "session expired" error without clearing the stored
credentials or retrying the refresh. The session also tracks the
server's clock from the Date header.

The app version maps development builds to the "alpha" channel, as
Proton's x-pm-appversion grammar has no "dev" channel.

The fake server gains users, sessions, single-use refresh tokens and
401 for invalid access tokens on authenticated routes.

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

252 lines
8.4 KiB
Go

package protondrive
import (
"bytes"
"context"
"errors"
"net/http"
"regexp"
"sync"
"testing"
"time"
"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 TestSessionRevoked(t *testing.T) {
srv := protontest.New(t)
s, store, tokens := newTestSession(t, srv)
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])
}
}