package protondrive import ( "context" "crypto/rand" "crypto/subtle" "encoding/base64" "encoding/json" "errors" "fmt" "io" "maps" "net/http" "net/url" "regexp" "strings" "sync" "time" "github.com/ProtonMail/go-srp" "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") // errNotSignedIn is returned by an authenticated call of a session // which has no credentials, as after signing out. var errNotSignedIn = errors.New("not signed in") // errCaptcha is returned by password sign-in when Proton asks for human // verification, which only its sign-in page can do. var errCaptcha = errors.New("password sign-in needs a CAPTCHA solved") const ( // srpBitLength is the bit length of Proton's SRP modulus. srpBitLength = 2048 // forkClientID identifies rclone to Proton's sign-in page. forkClientID = "external-drive" // forkSignInURL is the sign-in page for session forks, followed by // the escaped payload. forkSignInURL = "https://account.proton.me/desktop/login?app=drive&pv=3#payload=" ) 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 adoptWait time.Duration // how long a rejected refresh waits for the store to change unlockHook func() // if set, called by loadAccount while unlockMu is held; for tests reconnect string // if set, ends errors which need the user to sign in again, saying how 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 requirements string // x-pm-drive-requirements last logged } // 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 { own := *client own.CheckRedirect = checkRedirect s := &session{ srv: rest.NewClient(&own).SetRoot(baseURL), store: store, adoptWait: 3 * time.Second, 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 } // checkRedirect follows a redirect as Go's HTTP client does by // default, except that a block's storage token and the session's UID // aren't sent on to another host: Go drops only standard credential // headers such as Authorization. func checkRedirect(req *http.Request, via []*http.Request) error { if len(via) >= 10 { return errors.New("stopped after 10 redirects") } if req.URL.Host != via[0].URL.Host { req.Header.Del("pm-storage-token") req.Header.Del("x-pm-uid") } return nil } // 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. Without credentials it returns // errNotSignedIn and sends nothing. 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() if creds.UID == "" { return nil, s.signInNeeded(errNotSignedIn) } 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 { // Not the 401's response, so that a retry is decided by the // refresh's error. return nil, 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() if creds.UID == "" { // Signed out while the call was made. return resp, s.signInNeeded(errNotSignedIn) } 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")) s.observeRequirements(resp.Header.Values("x-pm-drive-requirements")) } 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() } // maxRequirementsLog bounds the x-pm-drive-requirements text logged. const maxRequirementsLog = 1024 // observeRequirements logs at debug level the x-pm-drive-requirements // header values of a response, by which Proton announces requirements // it will enforce, when they differ from those last logged. func (s *session) observeRequirements(values []string) { if len(values) == 0 { return } v := strings.Join(values, ", ") if len(v) > maxRequirementsLog { v = v[:maxRequirementsLog] } s.mu.Lock() changed := v != s.requirements s.requirements = v s.mu.Unlock() if changed { fs.Debugf(nil, "protondrive: Proton announces drive requirements: %q", v) } } // 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. If the server rejects the refresh token, it waits up to // s.adoptWait for another user of the store to save new tokens before // returning errSessionExpired. 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 s.signInNeeded(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, or a timeout, 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 && apiErr.Status != http.StatusRequestTimeout { // Another user of the store may have spent the same refresh // token and not saved its replacement yet. if stored, ok := s.waitForStoredRefresh(ctx, cur.RefreshToken); ok { fs.Debugf(nil, "protondrive: using session tokens refreshed elsewhere") s.setCredentials(stored) return nil } s.mu.Lock() s.deadRefresh = cur.RefreshToken s.mu.Unlock() return s.signInNeeded(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 } // signInNeeded returns err, which the user can only fix by signing in // again, as a fatal error ending with s.reconnect. func (s *session) signInNeeded(err error) error { if s.reconnect != "" { err = fmt.Errorf("%w: %s", err, s.reconnect) } return fserrors.FatalError(err) } // waitForStoredRefresh polls the store for up to s.adoptWait for a // refresh token other than spent and returns those credentials. It // returns false if none appears or ctx is done. func (s *session) waitForStoredRefresh(ctx context.Context, spent string) (credentials, bool) { const step = 50 * time.Millisecond deadline := time.Now().Add(s.adoptWait) for { if stored := s.store.Load(); stored.RefreshToken != "" && stored.RefreshToken != spent { return stored, true } if !time.Now().Before(deadline) { return credentials{}, false } select { case <-ctx.Done(): return credentials{}, false case <-time.After(min(step, time.Until(deadline))): } } } // setCredentials replaces the credentials in use. func (s *session) setCredentials(c credentials) { s.mu.Lock() defer s.mu.Unlock() s.creds = c } // signInError marks a human verification error as errCaptcha. func signInError(err error) error { var apiErr *api.Error if errors.As(err, &apiErr) && apiErr.Code == api.CodeHumanVerification { return fmt.Errorf("sign in: %w: %w", errCaptcha, err) } return fmt.Errorf("sign in: %w", err) } // saveCredentials makes c the credentials in use and saves them to the store. func (s *session) saveCredentials(c credentials) { s.setCredentials(c) s.store.Save(c) } // loginSRP signs in with a username and password using SRP, saving the // new credentials to the store only if sign-in succeeds. // // The key password derives from mailboxPassword if set, else from // password. twoFA is called for a TOTP code only if the account needs // one. A request for human verification returns an error wrapping // errCaptcha. func (s *session) loginSRP(ctx context.Context, username, password, mailboxPassword string, twoFA func() (string, error)) (err error) { var info api.AuthInfoResponse _, err = s.callUnauthenticated(ctx, &rest.Opts{Method: "POST", Path: "/core/v4/auth/info"}, &api.AuthInfoRequest{ Intent: "Proton", Username: username, }, &info) if err != nil { return signInError(err) } if info.Modulus == "" || info.ServerEphemeral == "" || info.SRPSession == "" { return errors.New("sign in: incomplete SRP challenge") } srpAuth, err := srp.NewAuth(info.Version, username, []byte(password), info.Salt, info.Modulus, info.ServerEphemeral) if err != nil { return fmt.Errorf("sign in: %w", err) } proofs, err := srpAuth.GenerateProofs(srpBitLength) if err != nil { return fmt.Errorf("sign in: %w", err) } var auth api.AuthResponse _, err = s.callUnauthenticated(ctx, &rest.Opts{Method: "POST", Path: "/core/v4/auth"}, &api.AuthRequest{ Username: username, ClientEphemeral: base64.StdEncoding.EncodeToString(proofs.ClientEphemeral), ClientProof: base64.StdEncoding.EncodeToString(proofs.ClientProof), SRPSession: info.SRPSession, PersistentCookies: 1, Payload: map[string]string{}, }, &auth) if err != nil { return signInError(err) } serverProof, err := base64.StdEncoding.DecodeString(auth.ServerProof) if err != nil || subtle.ConstantTimeCompare(serverProof, proofs.ExpectedServerProof) != 1 { return errors.New("sign in: server proof verification failed") } creds := credentials{UID: auth.UID, AccessToken: auth.AccessToken, RefreshToken: auth.RefreshToken} if creds.UID == "" || creds.AccessToken == "" || creds.RefreshToken == "" { return errors.New("sign in: no session tokens in response") } defer func() { if err != nil { // Don't leave a half signed in session behind. _, _ = s.do(ctx, &rest.Opts{Method: "DELETE", Path: "/core/v4/auth"}, nil, nil, &creds) } }() if auth.TwoFA.Enabled != 0 { if auth.TwoFA.Enabled&api.TwoFATOTP == 0 { return errors.New("sign in: password sign-in supports only TOTP two-factor authentication: choose browser sign-in") } if twoFA == nil { return errors.New("sign in: a two-factor authentication code is required") } var code string code, err = twoFA() if err != nil { return fmt.Errorf("sign in: %w", err) } _, err = s.do(ctx, &rest.Opts{Method: "POST", Path: "/core/v4/auth/2fa"}, &api.Auth2FARequest{TwoFactorCode: code}, nil, &creds) if err != nil { return fmt.Errorf("sign in: two-factor authentication: %w", err) } } keyPassword := password if mailboxPassword != "" { keyPassword = mailboxPassword } else if auth.PasswordMode == api.PasswordModeTwo { return errors.New("sign in: the account has a separate mailbox password: set mailbox_password") } var user api.UserResponse if _, err = s.do(ctx, &rest.Opts{Method: "GET", Path: "/core/v4/users"}, nil, &user, &creds); err != nil { return fmt.Errorf("sign in: get user: %w", err) } var salts api.KeySaltsResponse if _, err = s.do(ctx, &rest.Opts{Method: "GET", Path: "/core/v4/keys/salts"}, nil, &salts, &creds); err != nil { return fmt.Errorf("sign in: get key salts: %w", err) } salt, ok := primaryKeySalt(user.User.Keys, salts.KeySalts) if !ok { return errors.New("sign in: no key salt for the account") } salted, err := computeKeyPassword([]byte(keyPassword), salt) if err != nil { return fmt.Errorf("sign in: %w", err) } creds.KeyPassword = string(salted) s.saveCredentials(creds) return nil } // primaryKeySalt returns the salt of the primary user key in keys. // // The SDK uses the first salt, which is wrong for an account whose // user keys have different salts, so the first salt is only the // fallback when none matches the primary key. func primaryKeySalt(keys []api.UserKey, salts []api.KeySalt) (string, bool) { for _, key := range keys { if key.Primary != 1 { continue } for _, salt := range salts { if salt.ID == key.ID { return salt.KeySalt, true } } } if len(salts) == 0 { return "", false } return salts[0].KeySalt, true } // forkRequest is a pending browser sign-in. type forkRequest struct { UserCode string // code shown on the sign-in page Selector string // polls the fork for the new session URL string // sign-in page for the user to open key []byte // AES-256 key the page encrypts the key password with } // forkStart starts a browser sign-in by requesting a session fork. func (s *session) forkStart(ctx context.Context) (*forkRequest, error) { var out api.ForkInitResponse if _, err := s.callUnauthenticated(ctx, &rest.Opts{Method: "GET", Path: "/auth/v4/sessions/forks"}, nil, &out); err != nil { return nil, fmt.Errorf("browser sign-in: %w", err) } if out.UserCode == "" || out.Selector == "" { return nil, errors.New("browser sign-in: no fork in response") } key := make([]byte, 32) if _, err := rand.Read(key); err != nil { return nil, fmt.Errorf("browser sign-in: %w", err) } payload := "0:" + out.UserCode + ":" + base64.StdEncoding.EncodeToString(key) + ":" + forkClientID return &forkRequest{ UserCode: out.UserCode, Selector: out.Selector, // The SDK escapes the payload with encodeURIComponent, which // QueryEscape matches for the characters a payload contains. URL: forkSignInURL + url.QueryEscape(payload), key: key, }, nil } // forkPoll waits for the user to complete the browser sign-in f, // polling every interval for up to timeout, then saves the new // credentials to the store. func (s *session) forkPoll(ctx context.Context, f *forkRequest, interval, timeout time.Duration) error { pollCtx, cancel := context.WithTimeout(ctx, timeout) defer cancel() stopped := func() error { if err := ctx.Err(); err != nil { return err } return fmt.Errorf("browser sign-in: not completed within %v", timeout) } opts := &rest.Opts{Method: "GET", Path: "/auth/v4/sessions/forks/" + url.PathEscape(f.Selector)} ticker := time.NewTicker(interval) defer ticker.Stop() for { select { case <-pollCtx.Done(): return stopped() case <-ticker.C: } var out api.ForkStatusResponse _, err := s.callUnauthenticated(pollCtx, opts, nil, &out) var apiErr *api.Error if errors.As(err, &apiErr) && apiErr.Status == http.StatusUnprocessableEntity { // The fork isn't approved yet. continue } if err != nil { if pollCtx.Err() != nil { return stopped() } return fmt.Errorf("browser sign-in: %w", err) } keyPassword, err := decryptForkPayload(out.Payload, f.key) if err != nil { return fmt.Errorf("browser sign-in: %w", err) } creds := credentials{UID: out.UID, AccessToken: out.AccessToken, RefreshToken: out.RefreshToken, KeyPassword: keyPassword} if creds.UID == "" || creds.AccessToken == "" || creds.RefreshToken == "" { return errors.New("browser sign-in: no session tokens in response") } s.saveCredentials(creds) return nil } } // logout ends the session on the server and removes the credentials // from the session and the store, so neither can be used again. func (s *session) logout(ctx context.Context) error { var err error if s.current().UID != "" { _, err = s.call(ctx, &rest.Opts{Method: "DELETE", Path: "/core/v4/auth"}, nil, nil) if errors.Is(err, errSessionExpired) { err = nil } } // A refresh in flight would otherwise save its new tokens after // these are removed. s.refreshMu.Lock() s.saveCredentials(credentials{}) s.refreshMu.Unlock() if err != nil { return fmt.Errorf("sign out: %w", err) } return nil }