From ea41704ade154521dc0dfd9cf46a73acb0ba4438 Mon Sep 17 00:00:00 2001 From: Lucas Winther Date: Wed, 11 Nov 2026 10:33:43 +0100 Subject: [PATCH] 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 --- backend/protondrive/api/types.go | 15 + backend/protondrive/protontest/auth.go | 143 +++++++++ backend/protondrive/protontest/auth_test.go | 74 +++++ backend/protondrive/protontest/server.go | 5 + backend/protondrive/session.go | 321 +++++++++++++++++++ backend/protondrive/session_internal_test.go | 251 +++++++++++++++ docs/plans/001-protondrive-tier1.md | 15 +- 7 files changed, 818 insertions(+), 6 deletions(-) create mode 100644 backend/protondrive/protontest/auth.go create mode 100644 backend/protondrive/protontest/auth_test.go create mode 100644 backend/protondrive/session.go create mode 100644 backend/protondrive/session_internal_test.go diff --git a/backend/protondrive/api/types.go b/backend/protondrive/api/types.go index 7c1c1c014..4fd336456 100644 --- a/backend/protondrive/api/types.go +++ b/backend/protondrive/api/types.go @@ -59,3 +59,18 @@ type Error struct { func (e *Error) Error() string { return fmt.Sprintf("%s (Code=%d, Status=%d)", e.Message, e.Code, e.Status) } + +// AuthRefreshRequest is the body of POST /auth/v4/refresh. +type AuthRefreshRequest struct { + ResponseType string `json:"ResponseType"` // always "token" + GrantType string `json:"GrantType"` // always "refresh_token" + RefreshToken string `json:"RefreshToken"` +} + +// AuthRefreshResponse is the response to POST /auth/v4/refresh. +type AuthRefreshResponse struct { + Code int `json:"Code"` + UID string `json:"UID"` + AccessToken string `json:"AccessToken"` + RefreshToken string `json:"RefreshToken"` +} diff --git a/backend/protondrive/protontest/auth.go b/backend/protondrive/protontest/auth.go new file mode 100644 index 000000000..b52559f6b --- /dev/null +++ b/backend/protondrive/protontest/auth.go @@ -0,0 +1,143 @@ +package protontest + +import ( + "crypto/rand" + "encoding/hex" + "encoding/json" + "net/http" + "strings" + + "github.com/rclone/rclone/backend/protondrive/api" +) + +// User is an account on the fake server. +type User struct { + ID string + Username string + Password string + MailboxPassword string +} + +// Session holds the tokens of a signed in session. +type Session struct { + UID string + AccessToken string + RefreshToken string +} + +// session is the server side state of a Session. +type session struct { + Session + user *User + expired bool // access token no longer accepted +} + +// randomID returns a random hex string. +func randomID() string { + b := make([]byte, 16) + _, _ = rand.Read(b) + return hex.EncodeToString(b) +} + +// registerAuth registers the session routes. +func (s *Server) registerAuth() { + s.handle("POST", "/auth/v4/refresh", s.handleRefresh) + s.handleAuth("GET", "/tests/auth", func(w http.ResponseWriter, r *http.Request, u *User) { + writeJSON(w, http.StatusOK, map[string]any{"Code": api.CodeOK, "UserID": u.ID}) + }) + s.handleAuth("POST", "/tests/echo", func(w http.ResponseWriter, r *http.Request, u *User) { + var body struct{ Echo string } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: "+err.Error()) + return + } + writeJSON(w, http.StatusOK, map[string]any{"Code": api.CodeOK, "Echo": body.Echo}) + }) +} + +// AddUser creates an account whose mailbox password is its password. +func (s *Server) AddUser(username, password string) *User { + u := &User{ + ID: randomID(), + Username: username, + Password: password, + MailboxPassword: password, + } + s.mu.Lock() + defer s.mu.Unlock() + s.users[username] = u + return u +} + +// NewSession signs u in and returns the new session's tokens. +func (s *Server) NewSession(u *User) Session { + sess := &session{ + Session: Session{UID: randomID(), AccessToken: randomID(), RefreshToken: randomID()}, + user: u, + } + s.mu.Lock() + defer s.mu.Unlock() + s.sessions[sess.UID] = sess + return sess.Session +} + +// ExpireAccessToken makes the access token of session uid return 401 +// until the session is refreshed. +func (s *Server) ExpireAccessToken(uid string) { + s.mu.Lock() + defer s.mu.Unlock() + if sess := s.sessions[uid]; sess != nil { + sess.expired = true + } +} + +// RevokeSession ends session uid, so neither its access token nor its +// refresh token is accepted. +func (s *Server) RevokeSession(uid string) { + s.mu.Lock() + defer s.mu.Unlock() + delete(s.sessions, uid) +} + +// handleAuth registers h for an authenticated route. Requests without +// a valid x-pm-uid and bearer access token get HTTP 401. +func (s *Server) handleAuth(method, pattern string, h func(w http.ResponseWriter, r *http.Request, u *User)) { + s.handle(method, pattern, func(w http.ResponseWriter, r *http.Request) { + token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") + s.mu.Lock() + sess := s.sessions[r.Header.Get("x-pm-uid")] + valid := ok && sess != nil && !sess.expired && sess.AccessToken == token + s.mu.Unlock() + if !valid { + writeError(w, http.StatusUnauthorized, 401, "protontest: invalid access token") + return + } + h(w, r, sess.user) + }) +} + +// handleRefresh rotates the tokens of the session named by x-pm-uid. +// Refresh tokens are single use. +func (s *Server) handleRefresh(w http.ResponseWriter, r *http.Request) { + var req api.AuthRefreshRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.ResponseType != "token" || req.GrantType != "refresh_token" { + writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: bad refresh request") + return + } + s.mu.Lock() + defer s.mu.Unlock() + sess := s.sessions[r.Header.Get("x-pm-uid")] + if sess == nil || req.RefreshToken == "" || sess.RefreshToken != req.RefreshToken { + writeError(w, http.StatusUnprocessableEntity, api.CodeRefreshTokenInvalid, "protontest: invalid refresh token") + return + } + sess.AccessToken = randomID() + sess.RefreshToken = randomID() + sess.expired = false + writeJSON(w, http.StatusOK, &api.AuthRefreshResponse{ + Code: api.CodeOK, + UID: sess.UID, + AccessToken: sess.AccessToken, + RefreshToken: sess.RefreshToken, + }) +} diff --git a/backend/protondrive/protontest/auth_test.go b/backend/protondrive/protontest/auth_test.go new file mode 100644 index 000000000..156080240 --- /dev/null +++ b/backend/protondrive/protontest/auth_test.go @@ -0,0 +1,74 @@ +package protontest + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "testing" + + "github.com/rclone/rclone/backend/protondrive/api" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// refresh calls POST /auth/v4/refresh for uid with refreshToken. +func refresh(t *testing.T, s *Server, uid, refreshToken string) (*http.Response, []byte) { + t.Helper() + body, err := json.Marshal(&api.AuthRefreshRequest{ResponseType: "token", GrantType: "refresh_token", RefreshToken: refreshToken}) + require.NoError(t, err) + req, err := http.NewRequest("POST", s.URL()+"/auth/v4/refresh", bytes.NewReader(body)) + require.NoError(t, err) + req.Header.Set("x-pm-appversion", testAppVersion) + req.Header.Set("x-pm-uid", uid) + resp, err := s.Client().Do(req) + require.NoError(t, err) + defer func() { _ = resp.Body.Close() }() + out, err := io.ReadAll(resp.Body) + require.NoError(t, err) + return resp, out +} + +func authed(t *testing.T, s *Server, sess Session) int { + t.Helper() + resp, _ := do(t, s, "GET", "/tests/auth", map[string]string{ + "x-pm-appversion": testAppVersion, + "x-pm-uid": sess.UID, + "Authorization": "Bearer " + sess.AccessToken, + }) + return resp.StatusCode +} + +func TestAuth(t *testing.T) { + s := New(t) + u := s.AddUser("user", "pass") + assert.Equal(t, "pass", u.MailboxPassword) + sess := s.NewSession(u) + + assert.Equal(t, http.StatusOK, authed(t, s, sess)) + assert.Equal(t, http.StatusUnauthorized, authed(t, s, Session{UID: sess.UID, AccessToken: "wrong"})) + assert.Equal(t, http.StatusUnauthorized, authed(t, s, Session{UID: "unknown", AccessToken: sess.AccessToken})) + + s.ExpireAccessToken(sess.UID) + assert.Equal(t, http.StatusUnauthorized, authed(t, s, sess)) + + resp, body := refresh(t, s, sess.UID, sess.RefreshToken) + require.Equal(t, http.StatusOK, resp.StatusCode, "body: %s", body) + var out api.AuthRefreshResponse + require.NoError(t, json.Unmarshal(body, &out)) + assert.Equal(t, sess.UID, out.UID) + next := Session{UID: out.UID, AccessToken: out.AccessToken, RefreshToken: out.RefreshToken} + assert.Equal(t, http.StatusOK, authed(t, s, next)) + assert.Equal(t, http.StatusUnauthorized, authed(t, s, sess), "old access token") + + // Refresh tokens are single use. + resp, body = refresh(t, s, sess.UID, sess.RefreshToken) + assert.Equal(t, http.StatusUnprocessableEntity, resp.StatusCode) + assert.Equal(t, api.CodeRefreshTokenInvalid, decodeError(t, body).Code) + + s.RevokeSession(sess.UID) + assert.Equal(t, http.StatusUnauthorized, authed(t, s, next)) + resp, body = refresh(t, s, next.UID, next.RefreshToken) + assert.Equal(t, http.StatusUnprocessableEntity, resp.StatusCode) + assert.Equal(t, api.CodeRefreshTokenInvalid, decodeError(t, body).Code) +} diff --git a/backend/protondrive/protontest/server.go b/backend/protondrive/protontest/server.go index fad16e971..645264c69 100644 --- a/backend/protondrive/protontest/server.go +++ b/backend/protondrive/protontest/server.go @@ -64,6 +64,8 @@ type Server struct { requests map[string]int // count per "METHOD pattern" faults []*fault clockSkew time.Duration + users map[string]*User // by username + sessions map[string]*session // by UID } // New starts a fake server which is closed when the test ends. @@ -71,10 +73,13 @@ func New(t testing.TB) *Server { s := &Server{ mux: http.NewServeMux(), requests: make(map[string]int), + users: make(map[string]*User), + sessions: make(map[string]*session), } s.handle("GET", "/tests/ping", func(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]int{"Code": api.CodeOK}) }) + s.registerAuth() s.srv = httptest.NewServer(http.HandlerFunc(s.serveHTTP)) t.Cleanup(s.srv.Close) return s diff --git a/backend/protondrive/session.go b/backend/protondrive/session.go new file mode 100644 index 000000000..3f1addce9 --- /dev/null +++ b/backend/protondrive/session.go @@ -0,0 +1,321 @@ +package protondrive + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "maps" + "net/http" + "regexp" + "strings" + "sync" + "time" + + "github.com/rclone/rclone/backend/protondrive/api" + "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/fserrors" + "github.com/rclone/rclone/lib/rest" +) + +// errSessionExpired is returned when the session can no longer be +// refreshed and the user must sign in again. +var errSessionExpired = errors.New(`session expired: run "rclone config reconnect remote:"`) + +var ( + // rcloneVersionRe splits an rclone version into its number and suffix. + rcloneVersionRe = regexp.MustCompile(`^v?([0-9]+\.[0-9]+\.[0-9]+)(?:-(.*))?$`) + + // invalidBuildCharsRe matches characters not allowed in a semver + // build identifier. + invalidBuildCharsRe = regexp.MustCompile(`[^0-9A-Za-z-]+`) +) + +// appVersionFromRcloneVersion returns the x-pm-appversion for the +// rclone version v, as external-drive-rclone@-. +// +// Releases map to stable, betas to beta with their build number as +// build metadata, and anything else to alpha. An unparsable version +// maps to 1.0.0-stable. +func appVersionFromRcloneVersion(v string) string { + const prefix = "external-drive-rclone@" + m := rcloneVersionRe.FindStringSubmatch(strings.TrimSpace(v)) + if m == nil { + return prefix + "1.0.0-stable" + } + number, suffix := m[1], m[2] + switch { + case suffix == "": + return prefix + number + "-stable" + case suffix == "beta": + return prefix + number + "-beta" + case strings.HasPrefix(suffix, "beta."): + var build []string + for _, id := range strings.Split(strings.TrimPrefix(suffix, "beta."), ".") { + id = strings.Trim(invalidBuildCharsRe.ReplaceAllString(id, "-"), "-") + if id != "" { + build = append(build, id) + } + } + if len(build) == 0 { + return prefix + number + "-beta" + } + return prefix + number + "-beta+" + strings.Join(build, ".") + default: + return prefix + number + "-alpha" + } +} + +// credentials are the saved tokens of a session. +type credentials struct { + UID string + AccessToken string + RefreshToken string + KeyPassword string // salted password which unlocks the user keys +} + +// credentialStore persists credentials, possibly shared with other +// sessions and processes. +type credentialStore interface { + Load() credentials + Save(credentials) +} + +// memoryStore is a credentialStore held in memory. +type memoryStore struct { + mu sync.Mutex + creds credentials +} + +// Load returns the stored credentials. +func (m *memoryStore) Load() credentials { + m.mu.Lock() + defer m.mu.Unlock() + return m.creds +} + +// Save replaces the stored credentials. +func (m *memoryStore) Save(c credentials) { + m.mu.Lock() + defer m.mu.Unlock() + m.creds = c +} + +// session makes API calls with a Proton session, refreshing its tokens +// when they expire. +type session struct { + srv *rest.Client + store credentialStore + + refreshMu sync.Mutex // held while refreshing, so one refresh runs at a time + + mu sync.Mutex + creds credentials + deadRefresh string // refresh token the server rejected + serverDate time.Time // Date of the last response + serverDateLocal time.Time // local time serverDate was received +} + +// newSession returns a session for the API at baseURL using the +// credentials in store. +func newSession(client *http.Client, baseURL, appVersion string, store credentialStore) *session { + s := &session{ + srv: rest.NewClient(client).SetRoot(baseURL), + store: store, + creds: store.Load(), + } + s.srv.SetHeader("x-pm-appversion", appVersion) + s.srv.SetHeader("Accept", "application/vnd.protonmail.v1+json") + s.srv.SetErrorHandler(errorHandler) + return s +} + +// errorHandler decodes an unsuccessful response into an *api.Error. +func errorHandler(resp *http.Response) error { + body, err := rest.ReadBody(resp) + apiErr := &api.Error{Status: resp.StatusCode} + if err == nil { + _ = json.Unmarshal(body, apiErr) + } + if apiErr.Message == "" { + apiErr.Message = resp.Status + } + return apiErr +} + +// current returns the credentials in use. +func (s *session) current() credentials { + s.mu.Lock() + defer s.mu.Unlock() + return s.creds +} + +// serverTime returns the server's clock: the Date of the last response +// advanced by the local time elapsed since. It is zero before the +// first response. +func (s *session) serverTime() time.Time { + s.mu.Lock() + defer s.mu.Unlock() + if s.serverDate.IsZero() { + return time.Time{} + } + return s.serverDate.Add(time.Since(s.serverDateLocal)) +} + +// call makes an authenticated API call with rest.Client.CallJSON +// semantics. +// +// An unsuccessful HTTP status or a response Code outside 1000-1999 is +// returned as an *api.Error. On HTTP 401 the session is refreshed and +// the call retried once, so opts.Body, if set, must be an io.Seeker to +// be retried. If the session can't be refreshed the error wraps +// errSessionExpired. +func (s *session) call(ctx context.Context, opts *rest.Opts, request, response any) (*http.Response, error) { + creds := s.current() + resp, err := s.do(ctx, opts, request, response, &creds) + var apiErr *api.Error + if !errors.As(err, &apiErr) || apiErr.Status != http.StatusUnauthorized { + return resp, err + } + if refreshErr := s.refresh(ctx, creds.AccessToken); refreshErr != nil { + return resp, refreshErr + } + if opts.Body != nil { + seeker, ok := opts.Body.(io.Seeker) + if !ok { + return resp, err + } + if _, seekErr := seeker.Seek(0, io.SeekStart); seekErr != nil { + return resp, fmt.Errorf("rewind request body: %w", seekErr) + } + } + creds = s.current() + return s.do(ctx, opts, request, response, &creds) +} + +// callUnauthenticated makes an API call like call but without the +// session's credentials and without refreshing. +func (s *session) callUnauthenticated(ctx context.Context, opts *rest.Opts, request, response any) (*http.Response, error) { + return s.do(ctx, opts, request, response, nil) +} + +// do makes one API call, authenticated with creds if not nil. +func (s *session) do(ctx context.Context, opts *rest.Opts, request, response any, creds *credentials) (*http.Response, error) { + if creds != nil { + opts = opts.Copy() + opts.ExtraHeaders = maps.Clone(opts.ExtraHeaders) + if opts.ExtraHeaders == nil { + opts.ExtraHeaders = make(map[string]string, 2) + } + opts.ExtraHeaders["x-pm-uid"] = creds.UID + opts.ExtraHeaders["Authorization"] = "Bearer " + creds.AccessToken + } + var body json.RawMessage + resp, err := s.srv.CallJSON(ctx, opts, request, &body) + if resp != nil { + s.observeDate(resp.Header.Get("Date")) + } + if err != nil || opts.NoResponse { + return resp, err + } + var result struct { + Code int `json:"Code"` + } + if err := json.Unmarshal(body, &result); err != nil { + return resp, fmt.Errorf("decode response: %w", err) + } + // A body without a Code is not a Proton envelope, so is passed on. + if result.Code != 0 && result.Code/1000 != 1 { + apiErr := &api.Error{Status: resp.StatusCode} + _ = json.Unmarshal(body, apiErr) + return resp, apiErr + } + if response != nil { + if err := json.Unmarshal(body, response); err != nil { + return resp, fmt.Errorf("decode response: %w", err) + } + } + return resp, nil +} + +// observeDate records the server's clock from a Date header. +func (s *session) observeDate(date string) { + t, err := http.ParseTime(date) + if err != nil { + return + } + s.mu.Lock() + defer s.mu.Unlock() + s.serverDate = t + s.serverDateLocal = time.Now() +} + +// refresh replaces the access token rejected with a working one. +// +// It uses tokens another goroutine or another user of the store has +// already refreshed if there are any, since refresh tokens are single +// use. Otherwise it asks the server, saving the new tokens to the +// store. Credentials are never removed from the store, because another +// process may have just saved new ones. +func (s *session) refresh(ctx context.Context, rejected string) error { + s.refreshMu.Lock() + defer s.refreshMu.Unlock() + + cur := s.current() + if cur.AccessToken != rejected { + return nil + } + if stored := s.store.Load(); stored.RefreshToken != "" && stored.RefreshToken != cur.RefreshToken { + fs.Debugf(nil, "protondrive: using session tokens refreshed elsewhere") + s.setCredentials(stored) + return nil + } + s.mu.Lock() + dead := cur.RefreshToken == "" || cur.RefreshToken == s.deadRefresh + s.mu.Unlock() + if dead { + return fserrors.FatalError(errSessionExpired) + } + + fs.Debugf(nil, "protondrive: refreshing session") + var out api.AuthRefreshResponse + _, err := s.do(ctx, &rest.Opts{Method: "POST", Path: "/auth/v4/refresh"}, &api.AuthRefreshRequest{ + ResponseType: "token", + GrantType: "refresh_token", + RefreshToken: cur.RefreshToken, + }, &out, &cur) + if err != nil { + // As the SDK does, treat a client error other than rate + // limiting as the refresh token being rejected. + var apiErr *api.Error + if errors.As(err, &apiErr) && apiErr.Status >= 400 && apiErr.Status < 500 && apiErr.Status != http.StatusTooManyRequests { + s.mu.Lock() + s.deadRefresh = cur.RefreshToken + s.mu.Unlock() + return fserrors.FatalError(fmt.Errorf("%w: %w", errSessionExpired, err)) + } + return fmt.Errorf("refresh session: %w", err) + } + if out.AccessToken == "" { + return errors.New("refresh session: no access token in response") + } + next := cur + next.AccessToken = out.AccessToken + if out.UID != "" { + next.UID = out.UID + } + if out.RefreshToken != "" { + next.RefreshToken = out.RefreshToken + } + s.setCredentials(next) + s.store.Save(next) + return nil +} + +// setCredentials replaces the credentials in use. +func (s *session) setCredentials(c credentials) { + s.mu.Lock() + defer s.mu.Unlock() + s.creds = c +} diff --git a/backend/protondrive/session_internal_test.go b/backend/protondrive/session_internal_test.go new file mode 100644 index 000000000..617348c1b --- /dev/null +++ b/backend/protondrive/session_internal_test.go @@ -0,0 +1,251 @@ +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]) + } +} diff --git a/docs/plans/001-protondrive-tier1.md b/docs/plans/001-protondrive-tier1.md index f0a633cda..72bb1f3ed 100644 --- a/docs/plans/001-protondrive-tier1.md +++ b/docs/plans/001-protondrive-tier1.md @@ -198,7 +198,10 @@ a test in the task shown. - Route `POST /auth/v4/refresh`: single-use refresh tokens; a reused or unknown token returns HTTP 422 code 10013. - Every authenticated route returns HTTP 401 for an unknown or expired - access token. + access token. Later tasks register them with the unexported + `func (s *Server) handleAuth(method, pattern string, h func(w http.ResponseWriter, r *http.Request, u *User))`. + - Test routes `GET /tests/auth` (returns `UserID`) and `POST /tests/echo` + (returns the `Echo` field of the body), both authenticated. - Produces (`protondrive`): - `type credentials struct { UID, AccessToken, RefreshToken, KeyPassword string }` - `type credentialStore interface { Load() credentials; Save(credentials) }` @@ -219,7 +222,7 @@ a test in the task shown. Reference: `incubating/account/js/src/apiClient.ts`, `cli/src/api/serverTimeHook.ts`. -- [ ] **Step 1: Write failing tests**: +- [x] **Step 1: Write failing tests**: - `TestAppVersionFromRcloneVersion` table: `v1.77.0` -> `external-drive-rclone@1.77.0-stable`; `v1.77.0-DEV` -> `...@1.77.0-alpha`; `v1.77.0-beta.10754.448d7361c` -> @@ -241,12 +244,12 @@ Reference: `incubating/account/js/src/apiClient.ts`, `cli/src/api/serverTimeHook `serverTime()` is within 5s of now+3h. - `TestSessionAPIError`: a faulted 422 code 2500 surfaces as `*api.Error` with `Status == 422`, `Code == 2500`. -- [ ] **Step 2: Run** `go test ./backend/protondrive/ -run 'TestSession|TestAppVersion'` - expect FAIL. -- [ ] **Step 3: Implement.** Refresh is guarded by a mutex; inside it, +- [x] **Step 2: Run** `go test ./backend/protondrive/ -run 'TestSession|TestAppVersion'` - expect FAIL. +- [x] **Step 3: Implement.** Refresh is guarded by a mutex; inside it, `store.Load()` first and compare the refresh token with the one in memory before calling the server. -- [ ] **Step 4: Run** the verification commands - expect PASS. -- [ ] **Step 5: Commit** `protondrive: add session with safe token refresh`. +- [x] **Step 4: Run** the verification commands - expect PASS. +- [x] **Step 5: Commit** `protondrive: add session with safe token refresh`. ### Task 3: Sign-in - SRP password login and browser fork login