build / windows (push) Skipped
build / other_os (push) Skipped
build / mac_amd64 (push) Skipped
build / mac_arm64 (push) Skipped
build / linux (push) Skipped
build / go1.26 (push) Skipped
build / linux_386 (push) Skipped
build / lint (push) Skipped
build / android-all (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/386 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/amd64 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm/v6 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm/v7 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm64 (push) Skipped
Build & Push Docker Images / Merge & Push Final Docker Image (push) Waiting for needed jobs
Replace Proton-API-Bridge and go-proton-api with a client in backend/protondrive written against Proton's current Drive API, following the behaviour of Proton's official Drive SDK: - volume-based and v2 routes only - upload block verification, signed manifests and extended attributes - current content encryption (v4 node keys, v6 PKESK, SEIPDv2) - browser (session fork) sign-in, with username and password still supported - the volume's change events, used to keep the metadata cache current and for ChangeNotify, polled at most every 30 s - an in-memory fake Proton server (protontest) so the tests run without an account Uses ProtonMail/gopenpgp/v3 and ProtonMail/go-srp directly; no cgo. Written with heavy AI assistance (Claude Code). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
597 lines
20 KiB
Go
597 lines
20 KiB
Go
package protondrive
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/base64"
|
|
"errors"
|
|
"io"
|
|
"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
|
|
s.reconnect = `run "rclone config reconnect myremote:"`
|
|
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 myremote:`)
|
|
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.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())
|
|
srv.ResetRequests()
|
|
err := authCall(context.Background(), s)
|
|
assert.ErrorIs(t, err, errNotSignedIn)
|
|
assert.True(t, fserrors.IsFatalError(err))
|
|
assert.Empty(t, srv.Requests(), "no request is sent without a session")
|
|
|
|
// 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)
|
|
}
|
|
|
|
func TestCallDuringLogout(t *testing.T) {
|
|
t.Parallel()
|
|
ctx := context.Background()
|
|
srv := protontest.New(t)
|
|
s, _, _ := newTestSession(t, srv)
|
|
// The call is rejected only after the session has signed out.
|
|
srv.Inject(protontest.Fault{Method: "GET", Pattern: "/tests/auth", Times: 1, Status: http.StatusUnauthorized, Delay: 500 * time.Millisecond})
|
|
errc := make(chan error, 1)
|
|
go func() { errc <- authCall(ctx, s) }()
|
|
require.Eventually(t, func() bool { return srv.Requests()["GET /tests/auth"] == 1 }, 5*time.Second, 5*time.Millisecond)
|
|
require.NoError(t, s.logout(ctx))
|
|
|
|
err := <-errc
|
|
assert.ErrorIs(t, err, errNotSignedIn)
|
|
assert.Equal(t, 1, srv.Requests()["GET /tests/auth"], "retried without credentials")
|
|
assert.Zero(t, srv.Requests()[refreshRoute])
|
|
}
|
|
|
|
func TestRefreshDuringLogout(t *testing.T) {
|
|
t.Parallel()
|
|
ctx := context.Background()
|
|
srv := protontest.New(t)
|
|
tokens := srv.NewSession(srv.AddUser("user", "pass"))
|
|
refreshing, release := make(chan struct{}), make(chan struct{})
|
|
// The refresh succeeds, but its answer arrives only after the
|
|
// session has signed out.
|
|
client := &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
|
if r.URL.Path != "/auth/v4/refresh" {
|
|
return srv.Client().Transport.RoundTrip(r)
|
|
}
|
|
close(refreshing)
|
|
<-release
|
|
body := `{"Code":1000,"UID":"` + tokens.UID + `","AccessToken":"new-access","RefreshToken":"new-refresh"}`
|
|
return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"application/json"}}, Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
|
|
})}
|
|
store := &memoryStore{creds: credentials{UID: tokens.UID, AccessToken: tokens.AccessToken, RefreshToken: tokens.RefreshToken, KeyPassword: "key-pass"}}
|
|
s := newSession(client, srv.URL(), testAppVersion, store)
|
|
srv.Inject(protontest.Fault{Method: "GET", Pattern: "/tests/auth", Times: 1, Status: http.StatusUnauthorized})
|
|
|
|
errc := make(chan error, 1)
|
|
go func() { errc <- authCall(ctx, s) }()
|
|
<-refreshing
|
|
logoutErr := make(chan error, 1)
|
|
go func() { logoutErr <- s.logout(ctx) }()
|
|
require.Eventually(t, func() bool { return srv.Requests()["DELETE /core/v4/auth"] == 1 }, 5*time.Second, 5*time.Millisecond)
|
|
close(release)
|
|
require.NoError(t, <-logoutErr)
|
|
assert.Error(t, <-errc, "the call succeeded with tokens refreshed after signing out")
|
|
|
|
assert.Equal(t, credentials{}, store.Load(), "tokens saved after signing out")
|
|
assert.Equal(t, credentials{}, s.current())
|
|
}
|
|
|
|
func TestRefreshTransientErrorRetried(t *testing.T) {
|
|
for _, status := range []int{http.StatusServiceUnavailable, http.StatusRequestTimeout} {
|
|
t.Run(http.StatusText(status), func(t *testing.T) {
|
|
c, srv, _ := newTestClient(t)
|
|
ctx := context.Background()
|
|
srv.ExpireAccessToken(c.s.current().UID)
|
|
srv.Inject(protontest.Fault{Method: "POST", Pattern: "/auth/v4/refresh", Status: status, Times: 1})
|
|
_, _, err := c.about(ctx)
|
|
require.NoError(t, err, "a %d on the refresh wasn't retried", status)
|
|
assert.Equal(t, 2, srv.Requests()["POST /auth/v4/refresh"])
|
|
})
|
|
}
|
|
}
|