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>
322 lines
9.3 KiB
Go
322 lines
9.3 KiB
Go
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@<semver>-<channel>.
|
|
//
|
|
// 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
|
|
}
|