diff --git a/backend/protondrive/fake_test.go b/backend/protondrive/fake_test.go index 9fd213d49..7943dfc10 100644 --- a/backend/protondrive/fake_test.go +++ b/backend/protondrive/fake_test.go @@ -66,8 +66,6 @@ func TestIntegrationFake(t *testing.T) { if *fstest.RemoteName != "" { t.Skip("skipping as -remote is set") } - // TODO: remove once the backend has an endpoint option. - t.Skip("the backend cannot be pointed at the fake server yet") remoteName, _, _ := setupFakeRemote(t) fstests.Run(t, &fstests.Opt{ RemoteName: remoteName, diff --git a/backend/protondrive/protondrive.go b/backend/protondrive/protondrive.go index 54f40d81e..bfcfa276c 100644 --- a/backend/protondrive/protondrive.go +++ b/backend/protondrive/protondrive.go @@ -1,22 +1,25 @@ -// Package protondrive implements the Proton Drive backend +// Package protondrive implements the Proton Drive backend. +// +// The rclone-facing Fs and Object live in this file; the files beside +// it are a client of the Proton Drive API which follows Proton's Drive +// SDK, last checked against its tag js/v0.23.0. This file contains no +// cryptography and no API routes, and the client knows nothing of +// fs.Fs or fs.Object. package protondrive import ( "context" + "encoding/base64" "errors" "fmt" "io" "path" - "regexp" "strings" + "sync" "time" - "github.com/coreos/go-semver/semver" - protonDriveAPI "github.com/rclone/Proton-API-Bridge" - "github.com/rclone/go-proton-api" - "github.com/pquerna/otp/totp" - + "github.com/rclone/rclone/backend/protondrive/api" "github.com/rclone/rclone/fs" "github.com/rclone/rclone/fs/config" "github.com/rclone/rclone/fs/config/configmap" @@ -25,39 +28,39 @@ import ( "github.com/rclone/rclone/fs/fserrors" "github.com/rclone/rclone/fs/fshttp" "github.com/rclone/rclone/fs/hash" + "github.com/rclone/rclone/fs/list" "github.com/rclone/rclone/lib/dircache" "github.com/rclone/rclone/lib/encoder" - "github.com/rclone/rclone/lib/pacer" - "github.com/rclone/rclone/lib/readers" + "github.com/rclone/rclone/lib/random" ) -/* -- dirCache operates on relative path to root -- path sanitization - - rule of thumb: sanitize before use, but store things as-is - - the paths cached in dirCache are after sanitizing - - the remote/dir passed in aren't, and are stored as-is -*/ - const ( - minSleep = 10 * time.Millisecond - maxSleep = 2 * time.Second - decayConstant = 2 // bigger for slower decay, exponential - clientUIDKey = "client_uid" clientAccessTokenKey = "client_access_token" clientRefreshTokenKey = "client_refresh_token" clientSaltedKeyPassKey = "client_salted_key_pass" + draftClientUIDKey = "draft_client_uid" + + // defaultEndpoint is the Proton Drive API. + defaultEndpoint = "https://drive-api.proton.me" + + // thirdPartyNotice is the statement Proton requires of apps which + // sign in to it. + thirdPartyNotice = "rclone is a third-party application not officially supported by Proton." + + // forkPollInterval and forkPollTimeout pace waiting for a browser + // sign-in. + forkPollInterval = 3 * time.Second + forkPollTimeout = 10 * time.Minute ) var ( - errCanNotUploadFileWithUnknownSize = errors.New("proton Drive can't upload files with unknown size") - errCanNotPurgeRootDirectory = errors.New("can't purge root directory") - protonDriveInvalidVersionChars = regexp.MustCompile(`[^0-9A-Za-z.+-]+`) + errCanNotPurgeRootDirectory = errors.New("can't purge root directory") + errCanNotRemoveRootDirectory = errors.New("can't remove root directory") - // for the auth/deauth handler - _mapper configmap.Mapper - _saltedKeyPass string + // errNeedTwoFA is returned by the second factor callback of a + // password sign-in in Config which has no code yet. + errNeedTwoFA = errors.New("two-factor authentication code needed") ) // Register with Fs @@ -66,21 +69,25 @@ func init() { Name: "protondrive", Description: "Proton Drive", NewFs: NewFs, + Config: Config, Options: []fs.Option{{ - Name: "username", - Help: `The username of your proton account`, - Required: true, + Name: "username", + Help: `The username of your Proton account. + +Only needed to sign in with a password. Signing in with a web browser, +which "rclone config" offers, needs neither username nor password.`, }, { - Name: "password", - Help: "The password of your proton account.", - Required: true, + Name: "password", + Help: `The password of your Proton account. + +Only needed to sign in with a password.`, IsPassword: true, }, { Name: "mailbox_password", - Help: `The mailbox password of your two-password proton account. + Help: `The mailbox password of your two-password Proton account. -For more information regarding the mailbox password, please check the -following official knowledge base article: +For more information regarding the mailbox password, please check the +following official knowledge base article: https://proton.me/support/the-difference-between-the-mailbox-password-and-login-password `, IsPassword: true, @@ -91,7 +98,7 @@ https://proton.me/support/the-difference-between-the-mailbox-password-and-login- The value can also be provided with --protondrive-2fa=000000 -The 2FA code of your proton drive account if the account is set up with +The 2FA code of your proton drive account if the account is set up with two-factor authentication`, Required: false, }, { @@ -100,7 +107,7 @@ two-factor authentication`, The value can also be provided with --protondrive-otp-secret-key=ABCDEFGHIJKLMNOPQRSTUVWXYZ234567 -The OTP secret key of your proton drive account if the account is set up with +The OTP secret key of your proton drive account if the account is set up with two-factor authentication`, Required: false, Sensitive: true, @@ -144,62 +151,83 @@ two-factor authentication`, }, { Name: "original_file_size", Help: `Return the file size before encryption - -The size of the encrypted file will be different from (bigger than) the -original file size. Unless there is a reason to return the file size -after encryption is performed, otherwise, set this option to true, as -features like Open() which will need to be supplied with original content + +The size of the encrypted file will be different from (bigger than) the +original file size. Unless there is a reason to return the file size +after encryption is performed, otherwise, set this option to true, as +features like Open() which will need to be supplied with original content size, will fail to operate properly`, Advanced: true, Default: true, }, { Name: "app_version", - Help: `The app version string + Help: `The app version string - The app version string identifies the client that is currently performing - the API request. Third-party Proton Drive integrations should use the form - external-drive-@. If this option is left empty, rclone - derives a compliant value from its own version. This value is sent with - every API request; the option itself is optional.`, +The app version string identifies the client to Proton with every API +request. If it is left empty, rclone derives the value Proton asks of it +from its own version. Leave it empty: Proton may block a client which +sends a wrong or someone else's app version.`, Advanced: true, }, { Name: "replace_existing_draft", - Help: `Create a new revision when filename conflict is detected + Help: `Replace a draft another client left when uploading -When a file upload is cancelled or failed before completion, a draft will be -created and the subsequent upload of the same file to the same location will be -reported as a conflict. +When an upload is cancelled or fails, it may leave a draft behind, and +another upload of the same file to the same place sees a conflict. Drafts +this remote left are always replaced. -The value can also be set by --protondrive-replace-existing-draft=true +If this is set, a draft left by another client is replaced too and the +upload goes ahead. If another client is uploading the same file at the +same time, its upload fails. -If the option is set to true, the draft will be replaced and then the upload -operation will restart. If there are other clients also uploading at the same -file location at the same time, the behavior is currently unknown. Need to set -to true for integration tests. -If the option is set to false, an error "a draft exist - usually this means a -file is being uploaded at another client, or, there was a failed upload attempt" -will be returned, and no upload will happen.`, +If this is not set, such an upload fails with an error saying another +client is uploading the file.`, Advanced: true, Default: false, }, { Name: "enable_caching", Help: `Caches the files and folders metadata to reduce API calls -Notice: If you are mounting ProtonDrive as a VFS, please disable this feature, -as the current implementation doesn't update or clear the cache when there are -external changes. +Notice: If you are mounting ProtonDrive as a VFS, please disable this feature, +as the current implementation doesn't update or clear the cache when there are +external changes. -The files and folders on ProtonDrive are represented as links with keyrings, -which can be cached to improve performance and be friendly to the API server. - -The cache is currently built for the case when the rclone is the only instance -performing operations to the mount point. The event system, which is the proton -API system that provides visibility of what has changed on the drive, is yet -to be implemented, so updates from other clients won’t be reflected in the -cache. Thus, if there are concurrent clients accessing the same mount point, -then we might have a problem with caching the stale data.`, +The cache holds decrypted file and folder metadata in memory, which saves +API calls and decryption. Changes made by other clients are not seen while +it holds an entry, so if other clients change the same files at the same +time, rclone may act on out of date metadata.`, Advanced: true, Default: true, + }, { + Name: "upload_concurrency", + Help: `The number of blocks of one file uploaded at once + +Files are uploaded in blocks of 4 MiB, each held in memory while it is +uploaded. Values above 5, Proton's limit, are lowered to 5.`, + Advanced: true, + Default: defaultUploadConcurrency, + }, { + Name: "ignore_signature_errors", + Help: `Read files whose signatures can't be verified + +Proton signs file content and keys. By default a file whose signature +doesn't verify can't be read. If this is set, rclone logs an error and +reads it anyway, which may be needed for files uploaded by old or +third-party clients.`, + Advanced: true, + Default: false, + }, { + Name: draftClientUIDKey, + Help: "Identifies the drafts of this remote (internal use only)", + Advanced: true, + Sensitive: true, + Hide: fs.OptionHideBoth, + }, { + Name: "endpoint", + Help: "The Proton Drive API endpoint (for tests only)", + Advanced: true, + Default: defaultEndpoint, + Hide: fs.OptionHideBoth, }}, }) } @@ -213,76 +241,165 @@ type Options struct { OtpSecretKey string `config:"otp_secret_key"` // advanced - Enc encoder.MultiEncoder `config:"encoding"` - ReportOriginalSize bool `config:"original_file_size"` - AppVersion string `config:"app_version"` - ReplaceExistingDraft bool `config:"replace_existing_draft"` - EnableCaching bool `config:"enable_caching"` + Enc encoder.MultiEncoder `config:"encoding"` + ReportOriginalSize bool `config:"original_file_size"` + AppVersion string `config:"app_version"` + ReplaceExistingDraft bool `config:"replace_existing_draft"` + EnableCaching bool `config:"enable_caching"` + UploadConcurrency int `config:"upload_concurrency"` + IgnoreSignatureErrors bool `config:"ignore_signature_errors"` + DraftClientUID string `config:"draft_client_uid"` + Endpoint string `config:"endpoint"` } // Fs represents a remote proton drive type Fs struct { - name string // name of this remote - // Notice that for ProtonDrive, it's attached under rootLink (usually /root) - root string // the path we are working on. - opt Options // parsed config options - ci *fs.ConfigInfo // global config - features *fs.Features // optional features - pacer *fs.Pacer // pacer for API calls - dirCache *dircache.DirCache // Map of directory path to directory id - protonDrive *protonDriveAPI.ProtonDrive // the Proton API bridging library + name string // name of this remote + root string // the path we are working on + opt Options // parsed config options + features *fs.Features // optional features + c *client // Proton Drive API client + dirCache *dircache.DirCache // map of directory path to folder ID + closeOnce *sync.Once // closes c once } -// Object describes an object +// Object describes a file type Object struct { - fs *Fs // what this object is part of - remote string // The remote path (relative to the fs.root) - size int64 // size of the object (on server, after encryption) - originalSize *int64 // size of the object (after decryption) - digests *string // object original content - blockSizes []int64 // the block sizes of the encrypted file - modTime time.Time // modification time of the object - createdTime time.Time // creation time of the object - id string // ID of the object - mimetype string // mimetype of the file - - link *proton.Link // link data on proton server + fs *Fs // what this object is part of + remote string // the remote path + n *node // the file; nil until uploaded } -// shouldRetry returns a boolean as to whether this err deserves to be -// retried. It returns the err as a convenience +// configStore keeps the credentials of a session in the config of a +// remote. // -// 429 rate-limit and 503 responses are retried inside go-proton-api's resty -// layer (see catchTooManyRequests / catchRetryAfter) using the Retry-After -// header, so we do not retry them again here. -func shouldRetry(ctx context.Context, err error) (bool, error) { - if fserrors.ContextError(ctx, &err) { - return false, err - } - if err == nil { - return false, nil - } - if apiErr, ok := errors.AsType[*proton.APIError](err); ok { - // Code 200501 is a generic Drive operation-failure code. Proton also - // returns it with an HTTP 422 for permanent validation failures (for - // example a content key packet that cannot be verified, or an upload - // format the account is not enabled for), which must NOT be retried - - // doing so spins the pacer until the operation times out. Only retry it - // when it is not a permanent client (4xx) error. - if apiErr.Code == 200501 && (apiErr.Status < 400 || apiErr.Status >= 500) { - fs.Debugf(nil, "Retrying transient storage block error: %v", err) - return true, err - } - // Server errors. 503 is already handled by the SDK; retry the rest. - if apiErr.Status >= 500 && apiErr.Status < 600 && apiErr.Status != 503 { - return true, err - } - return false, err - } - return fserrors.ShouldRetry(err), err +// The key password is kept base64 encoded, as earlier versions of the +// backend kept it. +type configStore struct { + mu sync.Mutex + m configmap.Mapper + + // saved is what Save last wrote, and shadowed what the mapper held + // just before. A value the mapper still reads as shadowed is hidden + // by one which takes precedence over the config file, as from the + // environment, so Load returns the saved value instead. + saved *credentials + shadowed credentials } -//------------------------------------------------------------------------------ +// Load returns the credentials currently in the config. A key password +// which can't be decoded is returned empty. +func (s *configStore) Load() credentials { + s.mu.Lock() + defer s.mu.Unlock() + creds := s.read() + if s.saved == nil { + return creds + } + for _, f := range []struct{ read, shadowed, saved *string }{ + {&creds.UID, &s.shadowed.UID, &s.saved.UID}, + {&creds.AccessToken, &s.shadowed.AccessToken, &s.saved.AccessToken}, + {&creds.RefreshToken, &s.shadowed.RefreshToken, &s.saved.RefreshToken}, + {&creds.KeyPassword, &s.shadowed.KeyPassword, &s.saved.KeyPassword}, + } { + if *f.read == *f.shadowed { + *f.read = *f.saved + } + } + return creds +} + +// read returns the credentials in the mapper. +func (s *configStore) read() credentials { + get := func(key string) string { + v, _ := s.m.Get(key) + return v + } + creds := credentials{ + UID: get(clientUIDKey), + AccessToken: get(clientAccessTokenKey), + RefreshToken: get(clientRefreshTokenKey), + } + if keyPass, err := base64.StdEncoding.DecodeString(get(clientSaltedKeyPassKey)); err == nil { + creds.KeyPassword = string(keyPass) + } + return creds +} + +// Save writes c to the config. +func (s *configStore) Save(c credentials) { + s.mu.Lock() + defer s.mu.Unlock() + s.shadowed = s.read() + s.m.Set(clientUIDKey, c.UID) + s.m.Set(clientAccessTokenKey, c.AccessToken) + s.m.Set(clientRefreshTokenKey, c.RefreshToken) + s.m.Set(clientSaltedKeyPassKey, base64.StdEncoding.EncodeToString([]byte(c.KeyPassword))) + s.saved = &c +} + +// errorOp is the kind of operation an error is translated for. +type errorOp int + +const ( + opObject errorOp = iota // an operation on a file + opDir // an operation on a directory + opMkdir // making a directory + opMove // moving a file + opCopy // copying a file + opDirMove // moving a directory +) + +// translateError returns err from the client as the error rclone +// expects of the operation op. +func translateError(err error, op errorOp) error { + if err == nil { + return nil + } + switch { + case errors.Is(err, errIntegrity), errors.Is(err, errUploadMismatch): + return fserrors.NoRetryError(err) + case errors.Is(err, errUploadSuperseded): + // The upload landed; doing it again would only replace the + // other client's newer revision. + return fserrors.NoRetryError(err) + case errors.Is(err, errUploadOutcomeUnknown): + // An immediate retry could upload a revision which already + // committed. A later pass of a sync reads the file first, so + // may still retry. + return fserrors.NoLowLevelRetryError(err) + } + code := apiErrorCode(err) + switch { + case errors.Is(err, errNotFound) || code == api.CodeNotExists: + if op == opDir || op == opDirMove { + return fs.ErrorDirNotFound + } + return fs.ErrorObjectNotFound + case errors.Is(err, errExists): + switch op { + case opMkdir: + return nil + case opMove: + return fs.ErrorCantMove + case opCopy: + return fs.ErrorCantCopy + case opDirMove: + return fs.ErrorDirExists + } + return err + } + switch code { + case api.CodeInsufficientQuota, api.CodeInsufficientSpace, api.CodeMaxFileSizeForFreeUser, + api.CodeMaxPublicEditModeForFreeUser, api.CodeTooManyChildren, api.CodeNestingTooDeep: + return fserrors.NoRetryError(err) + case api.CodeInvalidRequirements, api.CodeAppVersionBad: + return fserrors.FatalError(fmt.Errorf("this version of rclone is no longer accepted by Proton: upgrade rclone: %w", err)) + } + return err +} + +// ------------------------------------------------------------ // Name of the remote (as passed into NewFs) func (f *Fs) Name() string { @@ -291,12 +408,12 @@ func (f *Fs) Name() string { // Root of the remote (as passed into NewFs) func (f *Fs) Root() string { - return f.opt.Enc.ToStandardPath(f.root) + return f.root } // String converts this Fs to a string func (f *Fs) String() string { - return fmt.Sprintf("proton drive root link ID '%s'", f.root) + return fmt.Sprintf("Proton Drive root '%s'", f.root) } // Features returns the optional features of this Fs @@ -304,317 +421,231 @@ func (f *Fs) Features() *fs.Features { return f.features } -// run all the dir/remote through this -func (f *Fs) sanitizePath(_path string) string { - _path = path.Clean(_path) - if _path == "." || _path == "/" { - return "" +// parseOptions reads the options from m, revealing the obscured ones. +func parseOptions(m configmap.Mapper) (*Options, error) { + opt := new(Options) + if err := configstruct.Set(m, opt); err != nil { + return nil, err } - - return f.opt.Enc.FromStandardPath(_path) -} - -func getConfigMap(m configmap.Mapper) (uid, accessToken, refreshToken, saltedKeyPass string, ok bool) { - if accessToken, ok = m.Get(clientAccessTokenKey); !ok { - return - } - - if uid, ok = m.Get(clientUIDKey); !ok { - return - } - - if refreshToken, ok = m.Get(clientRefreshTokenKey); !ok { - return - } - - if saltedKeyPass, ok = m.Get(clientSaltedKeyPassKey); !ok { - return - } - _saltedKeyPass = saltedKeyPass - - // empty strings are considered "ok" by m.Get, which is not true business-wise - ok = accessToken != "" && uid != "" && refreshToken != "" && saltedKeyPass != "" - - return -} - -func setConfigMap(m configmap.Mapper, uid, accessToken, refreshToken, saltedKeyPass string) { - m.Set(clientUIDKey, uid) - m.Set(clientAccessTokenKey, accessToken) - m.Set(clientRefreshTokenKey, refreshToken) - m.Set(clientSaltedKeyPassKey, saltedKeyPass) - _saltedKeyPass = saltedKeyPass -} - -func clearConfigMap(m configmap.Mapper) { - setConfigMap(m, "", "", "", "") - _saltedKeyPass = "" -} - -func authHandler(auth proton.Auth) { - // fs.Debugf("authHandler called") - setConfigMap(_mapper, auth.UID, auth.AccessToken, auth.RefreshToken, _saltedKeyPass) -} - -func deAuthHandler() { - // fs.Debugf("deAuthHandler called") - clearConfigMap(_mapper) -} - -func protonDriveAppVersionFromRcloneVersion(version string) string { - const fallback = "external-drive-rclone@1.0.0-stable" - - version = strings.TrimSpace(strings.TrimPrefix(version, "v")) - version = protonDriveInvalidVersionChars.ReplaceAllString(version, "-") - if version == "" { - return fallback - } - - parsedVersion, err := semver.NewVersion(version) - if err != nil { - return fallback - } - - appVersion := fmt.Sprintf( - "external-drive-rclone@%d.%d.%d", - parsedVersion.Major, - parsedVersion.Minor, - parsedVersion.Patch, - ) - - metadataParts := protonDriveMetadataParts(parsedVersion.Metadata) - preRelease := strings.ToLower(string(parsedVersion.PreRelease)) - - switch { - case preRelease == "": - return protonDriveJoinAppVersion(appVersion, "-stable", metadataParts) - case preRelease == "dev": - return protonDriveJoinAppVersion(appVersion, "-dev", metadataParts) - case preRelease == "beta" || strings.HasPrefix(preRelease, "beta."): - betaSuffix, betaMetadataParts := protonDriveBetaSuffixAndMetadata(preRelease) - return protonDriveJoinAppVersion(appVersion, betaSuffix, append(betaMetadataParts, metadataParts...)) - default: - return fallback - } -} - -func protonDriveMetadataParts(metadata string) []string { - if metadata == "" { - return nil - } - - parts := strings.Split(metadata, ".") - out := make([]string, 0, len(parts)) - for _, part := range parts { - if part != "" { - out = append(out, part) + for _, p := range []struct { + what string + value *string + }{ + {"password", &opt.Password}, + {"mailbox password", &opt.MailboxPassword}, + {"OTP secret key", &opt.OtpSecretKey}, + } { + if *p.value == "" { + continue } - } - return out -} - -func protonDriveBetaSuffixAndMetadata(preRelease string) (suffix string, metadata []string) { - suffix = "-beta" - remainder := strings.TrimPrefix(strings.TrimPrefix(preRelease, "beta"), ".") - if remainder == "" { - return suffix, nil - } - - parts := protonDriveMetadataParts(remainder) - i := 0 - for i < len(parts) && isDecimalString(parts[i]) { - suffix += "." + parts[i] - i++ - } - return suffix, parts[i:] -} - -func protonDriveJoinAppVersion(appVersion, suffix string, metadata []string) string { - version := appVersion + suffix - if len(metadata) != 0 { - version += "+" + strings.Join(metadata, ".") - } - return version -} - -func isDecimalString(value string) bool { - if value == "" { - return false - } - for _, r := range value { - if r < '0' || r > '9' { - return false - } - } - return true -} - -// protonLogger adapts rclone's fs.Debugf/Logf/Errorf into the -// resty.Logger / common.Logger shape expected by Proton-API-Bridge and -// go-proton-api so that library output participates in -v / -vv levels -// and is captured by --log-file. -type protonLogger struct{ f *Fs } - -func (l protonLogger) Errorf(format string, v ...any) { fs.Errorf(l.f, format, v...) } -func (l protonLogger) Warnf(format string, v ...any) { fs.Logf(l.f, format, v...) } -func (l protonLogger) Debugf(format string, v ...any) { fs.Debugf(l.f, format, v...) } - -func newProtonDrive(ctx context.Context, f *Fs, opt *Options, m configmap.Mapper) (*protonDriveAPI.ProtonDrive, error) { - config := protonDriveAPI.NewDefaultConfig() - config.AppVersion = opt.AppVersion - if config.AppVersion == "" { - config.AppVersion = protonDriveAppVersionFromRcloneVersion(fs.Version) - } - config.UserAgent = f.ci.UserAgent // opt.UserAgent - - // Route HTTP through rclone's transport so global flags such as - // --dump headers, --no-check-certificate, --user-agent, --bind, - // --ca-cert and --header all take effect against Proton Drive. - config.Transport = fshttp.NewTransport(ctx) - - // Route bridge and go-proton-api log output through rclone's - // logging system so it honours -v / -vv and --log-file. - config.Logger = protonLogger{f: f} - - config.ReplaceExistingDraft = opt.ReplaceExistingDraft - config.EnableCaching = opt.EnableCaching - - // let's see if we have the cached access credential - uid, accessToken, refreshToken, saltedKeyPass, hasUseReusableLoginCredentials := getConfigMap(m) - _saltedKeyPass = saltedKeyPass - - if hasUseReusableLoginCredentials { - fs.Debugf(f, "Has cached credentials") - config.UseReusableLogin = true - - config.ReusableCredential.UID = uid - config.ReusableCredential.AccessToken = accessToken - config.ReusableCredential.RefreshToken = refreshToken - config.ReusableCredential.SaltedKeyPass = saltedKeyPass - - protonDrive /* credential will be nil since access credentials are passed in */, _, err := protonDriveAPI.NewProtonDrive(ctx, config, authHandler, deAuthHandler) + revealed, err := obscure.Reveal(*p.value) if err != nil { - fs.Debugf(f, "Cached credential doesn't work, clearing and using the fallback login method") - // clear the access token on failure - clearConfigMap(m) - - fs.Debugf(f, "couldn't initialize a new proton drive instance using cached credentials: %v", err) - // we fallback to username+password login -> don't throw an error here - // return nil, fmt.Errorf("couldn't initialize a new proton drive instance: %w", err) - } else { - fs.Debugf(f, "Used cached credential to initialize the ProtonDrive API") - return protonDrive, nil + return nil, fmt.Errorf("couldn't decrypt %s: %w", p.what, err) } + *p.value = revealed } + return opt, nil +} - // if not, let's try to log the user in using username and password (and 2FA if required) - fs.Debugf(f, "Using username and password to log in") - config.UseReusableLogin = false - config.FirstLoginCredential.Username = opt.Username - config.FirstLoginCredential.Password = opt.Password - config.FirstLoginCredential.MailboxPassword = opt.MailboxPassword - // if 2FA code is provided, use it; otherwise, generate one using the OTP secret key if provided - config.FirstLoginCredential.TwoFA = opt.TwoFA - if opt.TwoFA == "" && opt.OtpSecretKey != "" { - code, err := totp.GenerateCode(opt.OtpSecretKey, time.Now()) - if err != nil { - return nil, fmt.Errorf("couldn't generate 2FA code: %w", err) - } - config.FirstLoginCredential.TwoFA = code +// newConfigSession returns a session keeping its credentials in m. +func newConfigSession(ctx context.Context, m configmap.Mapper, opt *Options) *session { + endpoint := opt.Endpoint + if endpoint == "" { + endpoint = defaultEndpoint } - protonDrive, auth, err := protonDriveAPI.NewProtonDrive(ctx, config, authHandler, deAuthHandler) + appVersion := opt.AppVersion + if appVersion == "" { + appVersion = appVersionFromRcloneVersion(fs.Version) + } + return newSession(fshttp.NewClient(ctx), strings.TrimSuffix(endpoint, "/"), appVersion, &configStore{m: m}) +} + +// passwordSignIn signs s in with the username and password of opt, +// taking a second factor from twoFA, else the 2fa option, else a code +// generated from the OTP secret key. +func passwordSignIn(ctx context.Context, s *session, opt *Options, twoFA string) error { + return s.loginSRP(ctx, opt.Username, opt.Password, opt.MailboxPassword, func() (string, error) { + switch { + case twoFA != "": + return twoFA, nil + case opt.TwoFA != "": + return opt.TwoFA, nil + case opt.OtpSecretKey != "": + // The code is checked against the server's clock. + now := s.serverTime() + if now.IsZero() { + now = time.Now() + } + code, err := totp.GenerateCode(opt.OtpSecretKey, now) + if err != nil { + return "", fmt.Errorf("couldn't generate 2FA code: %w", err) + } + return code, nil + } + return "", errNeedTwoFA + }) +} + +// connect returns a client for the saved session of s, signing in with +// the username and password of opt if there is no usable session. +func connect(ctx context.Context, name string, s *session, opt *Options) (*client, error) { + copt := clientOptions{ + UploadConcurrency: opt.UploadConcurrency, + ReplaceExistingDraft: opt.ReplaceExistingDraft, + EnableCaching: opt.EnableCaching, + IgnoreSignatureErrors: opt.IgnoreSignatureErrors, + DraftClientUID: opt.DraftClientUID, + } + canSignIn := opt.Username != "" && opt.Password != "" + reconnect := fmt.Sprintf(`run "rclone config reconnect %s:"`, name) + saved := s.current() + if saved.UID != "" && saved.AccessToken != "" && saved.RefreshToken != "" && saved.KeyPassword != "" { + c, err := newClient(ctx, s, copt) + switch { + case err == nil: + return c, nil + case !errors.Is(err, errSessionExpired): + return nil, err + case !canSignIn: + return nil, fserrors.FatalError(fmt.Errorf("the saved session can't be used: %s: %w", reconnect, err)) + } + fs.Debugf(nil, "protondrive: the saved session has expired") + } else if !canSignIn { + return nil, fserrors.FatalError(fmt.Errorf("not signed in and no username and password set: %s", reconnect)) + } + fs.Debugf(nil, "protondrive: signing in with username and password") + if err := passwordSignIn(ctx, s, opt, ""); err != nil { + if errors.Is(err, errNeedTwoFA) { + return nil, fmt.Errorf("the account needs a two-factor authentication code: set otp_secret_key or %s", reconnect) + } + return nil, err + } + return newClient(ctx, s, copt) +} + +// Config signs a remote in, with a web browser or a password. +func Config(ctx context.Context, name string, m configmap.Mapper, in fs.ConfigIn) (*fs.ConfigOut, error) { + return configure(ctx, name, m, in, signInOptions{ + showURL: showSignInURL, + pollInterval: forkPollInterval, + pollTimeout: forkPollTimeout, + }) +} + +// signInOptions configure a browser sign-in. +type signInOptions struct { + showURL func(signInURL string) // shows the sign-in page to the user + pollInterval time.Duration // how often to check whether the user signed in + pollTimeout time.Duration // how long to wait for the user to sign in +} + +// showSignInURL shows the user the browser sign-in page signInURL. +// +// It is printed rather than logged as it holds a secret. +func showSignInURL(signInURL string) { + fmt.Printf("Open this link in a web browser, on any device, and sign in to Proton:\n\n%s\n\nWaiting for the sign-in to complete...\n", signInURL) +} + +// configure runs the Config state machine, with signIn configuring a +// browser sign-in. +func configure(ctx context.Context, name string, m configmap.Mapper, in fs.ConfigIn, signIn signInOptions) (*fs.ConfigOut, error) { + opt, err := parseOptions(m) if err != nil { - return nil, fmt.Errorf("couldn't initialize a new proton drive instance: %w", err) + return nil, err } + hasPassword := opt.Username != "" && opt.Password != "" + switch in.State { + case "": + return fs.ConfigConfirm("choose", !hasPassword, "config_browser_sign_in", `Sign in with a web browser? - fs.Debugf(f, "Used username and password to initialize the ProtonDrive API") - setConfigMap(m, auth.UID, auth.AccessToken, auth.RefreshToken, auth.SaltedKeyPass) +`+thirdPartyNotice+` - return protonDrive, nil +Choose yes to sign in on Proton's sign-in page, on any device; rclone +never sees your password. Choose no to sign in with the username and +password set above.`) + case "choose": + if in.Result == "true" { + return fs.ConfigGoto("browser") + } + return fs.ConfigGoto("password") + case "browser": + s := newConfigSession(ctx, m, opt) + fork, err := s.forkStart(ctx) + if err != nil { + return nil, err + } + signIn.showURL(fork.URL) + if err := s.forkPoll(ctx, fork, signIn.pollInterval, signIn.pollTimeout); err != nil { + return nil, err + } + return nil, nil + case "password", "password_2fa": + if !hasPassword { + return fs.ConfigError("", "Password sign-in needs the username and password options set.") + } + twoFA := "" + if in.State == "password_2fa" { + twoFA = strings.TrimSpace(in.Result) + } + s := newConfigSession(ctx, m, opt) + err := passwordSignIn(ctx, s, opt, twoFA) + if errors.Is(err, errNeedTwoFA) { + return fs.ConfigInput("password_2fa", "config_2fa", "Two-factor authentication code") + } + if err != nil { + return nil, err + } + return nil, nil + } + return nil, fmt.Errorf("unknown state %q", in.State) } // NewFs constructs an Fs from the path, container:path func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) { - // pacer is not used in NewFs() - _mapper = m - - // Parse config into Options struct - opt := new(Options) - err := configstruct.Set(m, opt) + opt, err := parseOptions(m) if err != nil { return nil, err } - if opt.Password != "" { - var err error - opt.Password, err = obscure.Reveal(opt.Password) - if err != nil { - return nil, fmt.Errorf("couldn't decrypt password: %w", err) - } + if opt.UploadConcurrency > maxUploadConcurrency { + fs.Logf(nil, "protondrive: upload_concurrency %d is more than Proton allows: using %d", opt.UploadConcurrency, maxUploadConcurrency) + opt.UploadConcurrency = maxUploadConcurrency + } + if opt.DraftClientUID == "" { + // Saved before any upload, so drafts this remote leaves can be + // told apart from other clients' by later runs. + opt.DraftClientUID = random.String(32) + m.Set(draftClientUIDKey, opt.DraftClientUID) } - if opt.MailboxPassword != "" { - var err error - opt.MailboxPassword, err = obscure.Reveal(opt.MailboxPassword) - if err != nil { - return nil, fmt.Errorf("couldn't decrypt mailbox password: %w", err) - } + c, err := connect(ctx, name, newConfigSession(ctx, m, opt), opt) + if err != nil { + return nil, err } - if opt.OtpSecretKey != "" { - var err error - opt.OtpSecretKey, err = obscure.Reveal(opt.OtpSecretKey) - if err != nil { - return nil, fmt.Errorf("couldn't decrypt OtpSecretKey: %w", err) - } - } - - ci := fs.GetConfig(ctx) - root = strings.Trim(root, "/") - f := &Fs{ - name: name, - root: root, - opt: *opt, - ci: ci, - pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))), + name: name, + root: root, + opt: *opt, + c: c, + closeOnce: new(sync.Once), } - f.features = (&fs.Features{ ReadMimeType: true, CanHaveEmptyDirectories: true, - /* can't have multiple threads downloading - The raw file is split into equally-sized (currently 4MB, but it might change in the future, say to 8MB, 16MB, etc.) blocks, except the last one which might be smaller than 4MB. - Each block is encrypted separately, where the size and sha1 after the encryption is performed on the block is added to the metadata of the block, but the original block size and sha1 is not in the metadata. - We can make assumption and implement the chunker, but for now, we would rather be safe about it, and let the block being concurrently downloaded and decrypted in the background, to speed up the download operation! - */ - NoMultiThreading: true, }).Fill(ctx, f) - protonDrive, err := newProtonDrive(ctx, f, opt, m) - if err != nil { - return nil, err - } - f.protonDrive = protonDrive - - root = f.sanitizePath(root) - f.dirCache = dircache.New( - root, /* root folder path */ - protonDrive.MainShare.LinkID, /* real root ID is the root folder, since we can't go past this folder */ - f, - ) + f.dirCache = dircache.New(root, c.rootID(), f) err = f.dirCache.FindRoot(ctx, false) if err != nil { - // if the root directory is not found, the initialization will still work - // but if it's other kinds of error, then we raise it if err != fs.ErrorDirNotFound { - return nil, fmt.Errorf("couldn't initialize a new root remote: %w", err) + _ = f.Shutdown(ctx) + return nil, fmt.Errorf("couldn't find the root: %w", err) } - - // Assume it is a file (taken and modified from box.go) + // Assume it is a file newRoot, remote := dircache.SplitPath(root) tempF := *f - tempF.dirCache = dircache.New(newRoot, protonDrive.MainShare.LinkID, &tempF) + tempF.dirCache = dircache.New(newRoot, c.rootID(), &tempF) tempF.root = newRoot // Make new Fs which is the parent err = tempF.dirCache.FindRoot(ctx, false) @@ -622,12 +653,13 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e // No root so return old f return f, nil } - _, err := tempF.newObject(ctx, remote) + _, err := tempF.NewObject(ctx, remote) if err != nil { if err == fs.ErrorObjectNotFound { // File doesn't exist so return old f return f, nil } + _ = f.Shutdown(ctx) return nil, err } f.features.Fill(ctx, &tempF) @@ -639,109 +671,65 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e // return an error with an fs which points to the parent return f, fs.ErrorIsFile } - return f, nil } -//------------------------------------------------------------------------------ - -// CleanUp deletes all files currently in trash -func (f *Fs) CleanUp(ctx context.Context) error { - return f.pacer.Call(func() (bool, error) { - err := f.protonDrive.EmptyTrash(ctx) - return shouldRetry(ctx, err) - }) +// newObjectWithNode returns an Object at remote for the file n. +func (f *Fs) newObjectWithNode(remote string, n *node) *Object { + return &Object{fs: f, remote: remote, n: n} } // NewObject finds the Object at remote. If it can't be found -// it returns the error ErrorObjectNotFound. -// -// If remote points to a directory then it should return -// ErrorIsDir if possible without doing any extra work, -// otherwise ErrorObjectNotFound. +// it returns the error fs.ErrorObjectNotFound. func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) { - return f.newObject(ctx, remote) -} - -func (f *Fs) getObjectLink(ctx context.Context, remote string) (*proton.Link, error) { - // attempt to locate the file - leaf, folderLinkID, err := f.dirCache.FindPath(ctx, f.sanitizePath(remote), false) + leaf, directoryID, err := f.dirCache.FindPath(ctx, remote, false) if err != nil { if err == fs.ErrorDirNotFound { - // parent folder of the file not found, we for sure can't find the file return nil, fs.ErrorObjectNotFound } - // other error has occurred return nil, err } - - var link *proton.Link - if err = f.pacer.Call(func() (bool, error) { - link, err = f.protonDrive.SearchByNameInActiveFolderByID(ctx, folderLinkID, leaf, true, false, proton.LinkStateActive) - return shouldRetry(ctx, err) - }); err != nil { - return nil, err - } - if link == nil { // both link and err are nil, file not found - return nil, fs.ErrorObjectNotFound - } - - return link, nil -} - -// readMetaDataForLink reads the metadata from the remote -func (f *Fs) readMetaDataForLink(ctx context.Context, link *proton.Link) (*protonDriveAPI.FileSystemAttrs, error) { - var fileSystemAttrs *protonDriveAPI.FileSystemAttrs - var err error - if err = f.pacer.Call(func() (bool, error) { - fileSystemAttrs, err = f.protonDrive.GetActiveRevisionAttrs(ctx, link) - return shouldRetry(ctx, err) - }); err != nil { - return nil, err - } - - return fileSystemAttrs, nil -} - -// Return an Object from a path and link -// -// If it can't be found it returns the error fs.ErrorObjectNotFound. -func (f *Fs) newObjectWithLink(ctx context.Context, remote string, link *proton.Link) (fs.Object, error) { - o := &Object{ - fs: f, - remote: remote, - } - - o.id = link.LinkID - o.size = link.Size - o.modTime = time.Unix(link.ModifyTime, 0) - o.createdTime = time.Unix(link.CreateTime, 0) - o.mimetype = link.MIMEType - o.link = link - - fileSystemAttrs, err := o.fs.readMetaDataForLink(ctx, link) + n, err := f.c.findChild(ctx, directoryID, f.opt.Enc.FromStandardName(leaf)) if err != nil { - return nil, err + return nil, translateError(err, opObject) } - if fileSystemAttrs != nil { - o.modTime = fileSystemAttrs.ModificationTime - o.originalSize = &fileSystemAttrs.Size - o.blockSizes = fileSystemAttrs.BlockSizes - o.digests = &fileSystemAttrs.Digests + if n.IsFolder { + return nil, fs.ErrorIsDir } - - return o, nil + return f.newObjectWithNode(remote, n), nil } -// Return an Object from a path only -// -// If it can't be found it returns the error fs.ErrorObjectNotFound. -func (f *Fs) newObject(ctx context.Context, remote string) (fs.Object, error) { - link, err := f.getObjectLink(ctx, remote) - if err != nil { - return nil, err +// FindLeaf finds a directory of name leaf in the folder with ID pathID +func (f *Fs) FindLeaf(ctx context.Context, pathID, leaf string) (pathIDOut string, found bool, err error) { + n, err := f.c.findChild(ctx, pathID, f.opt.Enc.FromStandardName(leaf)) + if errors.Is(err, errNotFound) { + return "", false, nil } - return f.newObjectWithLink(ctx, remote, link) + if err != nil { + return "", false, translateError(err, opDir) + } + if !n.IsFolder { + return "", false, nil + } + return n.ID, true, nil +} + +// CreateDir makes a directory with pathID as parent and name leaf +func (f *Fs) CreateDir(ctx context.Context, pathID, leaf string) (newID string, err error) { + name := f.opt.Enc.FromStandardName(leaf) + n, err := f.c.createFolder(ctx, pathID, name, time.Now()) + if errors.Is(err, errExists) { + // Another client, or a call whose response was lost, may have + // made the folder. + if existing, findErr := f.c.findChild(ctx, pathID, name); findErr == nil && existing.IsFolder { + return existing.ID, nil + } + return "", err + } + if err != nil { + return "", translateError(err, opDir) + } + return n.ID, nil } // List the objects and directories in dir into entries. The @@ -753,178 +741,112 @@ func (f *Fs) newObject(ctx context.Context, remote string) (fs.Object, error) { // // This should return ErrDirNotFound if the directory isn't // found. -// Notice that this function is expensive since everything on proton is encrypted -// So having a remote with 10k files, during operations like sync, might take a while and lots of bandwidth! -func (f *Fs) List(ctx context.Context, dir string) (fs.DirEntries, error) { - folderLinkID, err := f.dirCache.FindDir(ctx, f.sanitizePath(dir), false) // will handle ErrDirNotFound here +func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) { + return list.WithListP(ctx, dir, f) +} + +// ListP lists the objects and directories of the Fs starting +// from dir non recursively into out. +// +// dir should be "" to start from the root, and should not +// have trailing slashes. +// +// This should return ErrDirNotFound if the directory isn't +// found. +// +// It should call callback for each tranche of entries read. +// These need not be returned in any particular order. If +// callback returns an error then the listing will stop +// immediately. +func (f *Fs) ListP(ctx context.Context, dir string, callback fs.ListRCallback) error { + list := list.NewHelper(callback) + directoryID, err := f.dirCache.FindDir(ctx, dir, false) if err != nil { - return nil, err + return err } - - var foldersAndFiles []*protonDriveAPI.ProtonDirectoryData - if err = f.pacer.Call(func() (bool, error) { - foldersAndFiles, err = f.protonDrive.ListDirectory(ctx, folderLinkID) - return shouldRetry(ctx, err) - }); err != nil { - return nil, err - } - - entries := make(fs.DirEntries, 0) - for i := range foldersAndFiles { - remote := path.Join(dir, f.opt.Enc.ToStandardName(foldersAndFiles[i].Name)) - - if foldersAndFiles[i].IsFolder { - f.dirCache.Put(remote, foldersAndFiles[i].Link.LinkID) - d := fs.NewDir(remote, time.Unix(foldersAndFiles[i].Link.ModifyTime, 0)).SetID(foldersAndFiles[i].Link.LinkID) - entries = append(entries, d) - } else { - obj, err := f.newObjectWithLink(ctx, remote, foldersAndFiles[i].Link) - if err != nil { - return nil, err + err = f.c.listChildren(ctx, directoryID, func(nodes []*node) error { + for _, n := range nodes { + remote := path.Join(dir, f.opt.Enc.ToStandardName(n.Name)) + var entry fs.DirEntry + if n.IsFolder { + f.dirCache.Put(remote, n.ID) + entry = fs.NewDir(remote, n.modTime()).SetID(n.ID) + } else { + entry = f.newObjectWithNode(remote, n) + } + if err := list.Add(entry); err != nil { + return err } - entries = append(entries, obj) } + return nil + }) + if err != nil { + return translateError(err, opDir) } - - return entries, nil + return list.Flush() } -// FindLeaf finds a directory of name leaf in the folder with ID pathID +// Put the object // -// This should be implemented by the backend and will be called by the -// dircache package when appropriate. -func (f *Fs) FindLeaf(ctx context.Context, pathID, leaf string) (string, bool, error) { - /* f.opt.Enc.FromStandardName(leaf) not required since the DirCache only process sanitized path */ - - var link *proton.Link - var err error - if err = f.pacer.Call(func() (bool, error) { - link, err = f.protonDrive.SearchByNameInActiveFolderByID(ctx, pathID, leaf, false, true, proton.LinkStateActive) - return shouldRetry(ctx, err) - }); err != nil { - return "", false, err - } - if link == nil { - return "", false, nil - } - - return link.LinkID, true, nil -} - -// CreateDir makes a directory with pathID as parent and name leaf +// Copy the reader in to the new object which is returned. // -// This should be implemented by the backend and will be called by the -// dircache package when appropriate. -func (f *Fs) CreateDir(ctx context.Context, pathID, leaf string) (string, error) { - /* f.opt.Enc.FromStandardName(leaf) not required since the DirCache only process sanitized path */ - - var newID string - var err error - if err = f.pacer.Call(func() (bool, error) { - newID, err = f.protonDrive.CreateNewFolderByID(ctx, pathID, leaf) - return shouldRetry(ctx, err) - }); err != nil { - return "", err - } - - return newID, err -} - -// Put in to the remote path with the modTime given of the given size -// -// When called from outside an Fs by rclone, src.Size() will always be >= 0. -// But for unknown-sized objects (indicated by src.Size() == -1), Put should either -// return an error or upload it properly (rather than e.g. calling panic). -// -// May create the object even if it returns an error - if so -// will return the object and the error, otherwise will return -// nil and the error +// The new object may have been created if an error is returned func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) { - size := src.Size() - if size < 0 { - return nil, errCanNotUploadFileWithUnknownSize - } - - existingObj, err := f.NewObject(ctx, src.Remote()) + existing, err := f.NewObject(ctx, src.Remote()) switch err { case nil: - // object is found, we add an revision to it - return existingObj, existingObj.Update(ctx, in, src, options...) + return existing, existing.Update(ctx, in, src, options...) case fs.ErrorObjectNotFound: - // object not found, so we need to create it - remote := src.Remote() - size := src.Size() - modTime := src.ModTime(ctx) - - obj, err := f.createObject(ctx, remote, modTime, size) - if err != nil { + o := &Object{fs: f, remote: src.Remote()} + if err := o.Update(ctx, in, src, options...); err != nil { return nil, err } - return obj, obj.Update(ctx, in, src, options...) + return o, nil default: - // real error caught return nil, err } } -// Creates from the parameters passed in a half finished Object which -// must have setMetaData called on it -// -// Returns the object, leaf, directoryID and error. -// -// Used to create new objects -func (f *Fs) createObject(ctx context.Context, remote string, modTime time.Time, size int64) (*Object, error) { - // ˇ-------ˇ filename - // e.g. /root/a/b/c/test.txt - // ^~~~~~~~~~~^ dirPath - - // Create the directory for the object if it doesn't exist - _, _, err := f.dirCache.FindPath(ctx, f.sanitizePath(remote), true) - if err != nil { - return nil, err - } - - // Temporary Object under construction - obj := &Object{ - fs: f, - remote: remote, - size: size, - originalSize: nil, - id: "", - modTime: modTime, - mimetype: "", - link: nil, - } - return obj, nil +// PutStream uploads to the remote path with the modTime given of indeterminate size +func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) { + return f.Put(ctx, in, src, options...) } // Mkdir makes the directory (container, bucket) // // Shouldn't return an error if it already exists func (f *Fs) Mkdir(ctx context.Context, dir string) error { - _, err := f.dirCache.FindDir(ctx, f.sanitizePath(dir), true) + _, err := f.dirCache.FindDir(ctx, dir, true) return err } -// Rmdir removes the directory (container, bucket) if empty +// Rmdir deletes the directory dir by moving it to the trash // -// Return an error if it doesn't exist or isn't empty +// Returns an error if it isn't empty func (f *Fs) Rmdir(ctx context.Context, dir string) error { - folderLinkID, err := f.dirCache.FindDir(ctx, f.sanitizePath(dir), false) - if err == fs.ErrorDirNotFound { - return fmt.Errorf("[Rmdir] cannot find LinkID for dir %s (%s)", dir, f.sanitizePath(dir)) - } else if err != nil { + directoryID, err := f.dirCache.FindDir(ctx, dir, false) + if err != nil { return err } - - if err = f.pacer.Call(func() (bool, error) { - err = f.protonDrive.MoveFolderToTrashByID(ctx, folderLinkID, true) - return shouldRetry(ctx, err) - }); err != nil { - return err + if directoryID == f.c.rootID() { + return errCanNotRemoveRootDirectory } - - f.dirCache.FlushDir(f.sanitizePath(dir)) + err = f.c.listChildren(ctx, directoryID, func(nodes []*node) error { + if len(nodes) > 0 { + return fs.ErrorDirectoryNotEmpty + } + return nil + }) + if errors.Is(err, fs.ErrorDirectoryNotEmpty) { + return fs.ErrorDirectoryNotEmpty + } + if err != nil { + return translateError(err, opDir) + } + if err := f.c.trash(ctx, directoryID); err != nil { + return translateError(err, opDir) + } + f.dirCache.FlushDir(dir) return nil } @@ -933,12 +855,179 @@ func (f *Fs) Precision() time.Duration { return time.Second } -// DirCacheFlush an optional interface to flush internal directory cache -// DirCacheFlush resets the directory cache - used in testing -// as an optional interface +// Copy src to this remote using server-side copy operations. +// +// This is stored with the remote path given. +// +// It returns the destination Object and a possible error. +// +// Will only be called if src.Fs().Name() == f.Name() +// +// If it isn't possible then return fs.ErrorCantCopy +func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object, error) { + srcObj, ok := src.(*Object) + if !ok || srcObj.n == nil { + fs.Debugf(src, "Can't copy - not same remote type") + return nil, fs.ErrorCantCopy + } + n, err := f.c.getNode(ctx, srcObj.n.ID) + if err != nil { + return nil, translateError(err, opObject) + } + leaf, directoryID, err := f.dirCache.FindPath(ctx, remote, true) + if err != nil { + return nil, err + } + copied, err := f.c.copyNode(ctx, n, directoryID, f.opt.Enc.FromStandardName(leaf)) + if err != nil { + return nil, translateError(err, opCopy) + } + return f.newObjectWithNode(remote, copied), nil +} + +// Purge deletes all the files and the directory dir by moving it to +// the trash +// +// Returns an error if it doesn't exist +func (f *Fs) Purge(ctx context.Context, dir string) error { + if path.Join(f.root, dir) == "" { + return errCanNotPurgeRootDirectory + } + directoryID, err := f.dirCache.FindDir(ctx, dir, false) + if err != nil { + return err + } + if directoryID == f.c.rootID() { + return errCanNotPurgeRootDirectory + } + if err := f.c.trash(ctx, directoryID); err != nil { + return translateError(err, opDir) + } + f.dirCache.FlushDir(dir) + return nil +} + +// CleanUp empties the trash +func (f *Fs) CleanUp(ctx context.Context) error { + return translateError(f.c.emptyTrash(ctx), opDir) +} + +// Move src to this remote using server-side move operations. +// +// This is stored with the remote path given. +// +// It returns the destination Object and a possible error. +// +// Will only be called if src.Fs().Name() == f.Name() +// +// If it isn't possible then return fs.ErrorCantMove +func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object, error) { + srcObj, ok := src.(*Object) + if !ok || srcObj.n == nil { + fs.Debugf(src, "Can't move - not same remote type") + return nil, fs.ErrorCantMove + } + n, err := f.c.getNode(ctx, srcObj.n.ID) + if err != nil { + return nil, translateError(err, opObject) + } + leaf, directoryID, err := f.dirCache.FindPath(ctx, remote, true) + if err != nil { + return nil, err + } + if err := f.moveNode(ctx, n, directoryID, f.opt.Enc.FromStandardName(leaf)); err != nil { + return nil, translateError(err, opMove) + } + srcObj.fs.forget(f, n.ID, n.ParentID, directoryID) + moved, err := f.c.getNode(ctx, n.ID) + if err != nil { + return nil, translateError(err, opObject) + } + return f.newObjectWithNode(remote, moved), nil +} + +// forget drops node id and the listings of parentIDs from the cache of +// f after dst changed them, unless dst shares f's client, which then +// already has. +func (f *Fs) forget(dst *Fs, id string, parentIDs ...string) { + if f.c != dst.c { + f.c.forget(id, parentIDs...) + } +} + +// moveNode moves n into folder parentID as name, renaming it if it is +// already in that folder. +func (f *Fs) moveNode(ctx context.Context, n *node, parentID, name string) error { + if n.ParentID != parentID { + return f.c.move(ctx, n, parentID, name) + } + if n.Name == name { + return nil + } + return f.c.rename(ctx, n, name) +} + +// About gets quota information +func (f *Fs) About(ctx context.Context) (*fs.Usage, error) { + used, total, err := f.c.about(ctx) + if err != nil { + return nil, translateError(err, opDir) + } + free := max(total-used, 0) + return &fs.Usage{ + Total: &total, + Used: &used, + Free: &free, + }, nil +} + +// DirMove moves src, srcRemote to this remote at dstRemote +// using server-side move operations. +// +// Will only be called if src.Fs().Name() == f.Name() +// +// If it isn't possible then return fs.ErrorCantDirMove +// +// If destination exists then return fs.ErrorDirExists +func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string) error { + srcFs, ok := src.(*Fs) + if !ok { + fs.Debugf(srcFs, "Can't move directory - not same remote type") + return fs.ErrorCantDirMove + } + srcID, _, _, dstDirectoryID, dstLeaf, err := f.dirCache.DirMove(ctx, srcFs.dirCache, srcFs.root, srcRemote, f.root, dstRemote) + if err != nil { + return err + } + n, err := f.c.getNode(ctx, srcID) + if err != nil { + return translateError(err, opDirMove) + } + if err := f.moveNode(ctx, n, dstDirectoryID, f.opt.Enc.FromStandardName(dstLeaf)); err != nil { + return translateError(err, opDirMove) + } + srcFs.forget(f, n.ID, n.ParentID, dstDirectoryID) + srcFs.dirCache.FlushDir(srcRemote) + return nil +} + +// Disconnect signs the session out and removes it from the config +func (f *Fs) Disconnect(ctx context.Context) error { + return f.c.s.logout(ctx) +} + +// DirCacheFlush resets the directory cache - used in testing as an +// optional interface func (f *Fs) DirCacheFlush() { f.dirCache.ResetRoot() - f.protonDrive.ClearCache() + f.c.cache.clear() +} + +// Shutdown releases the keys and caches of the Fs, which must not be +// used afterwards +func (f *Fs) Shutdown(ctx context.Context) error { + f.closeOnce.Do(f.c.close) + return nil } // Hashes returns the supported hash types of the filesystem @@ -946,30 +1035,6 @@ func (f *Fs) Hashes() hash.Set { return hash.Set(hash.SHA1) } -// About gets quota information -func (f *Fs) About(ctx context.Context) (*fs.Usage, error) { - var user *proton.User - var err error - if err = f.pacer.Call(func() (bool, error) { - user, err = f.protonDrive.About(ctx) - return shouldRetry(ctx, err) - }); err != nil { - return nil, err - } - - total := user.MaxSpace - used := user.UsedSpace - free := total - used - - usage := &fs.Usage{ - Total: &total, - Used: &used, - Free: &free, - } - - return usage, nil -} - // ------------------------------------------------------------ // Fs returns the parent Fs @@ -990,52 +1055,36 @@ func (o *Object) Remote() string { return o.remote } -// Hash returns the hashes of an object +// Hash returns the SHA-1 of the object's content which its uploader +// recorded, or "" if it isn't known func (o *Object) Hash(ctx context.Context, t hash.Type) (string, error) { if t != hash.SHA1 { return "", hash.ErrUnsupported } - - if o.digests != nil { - return strings.ToLower(*o.digests), nil - } - - // sha1 not cached: we fetch and try to obtain the sha1 of the link - fileSystemAttrs, err := o.fs.protonDrive.GetActiveRevisionAttrsByID(ctx, o.ID()) - if err != nil { - return "", err - } - - if fileSystemAttrs == nil || fileSystemAttrs.Digests == "" { - fs.Debugf(o, "file sha1 digest missing") + if o.n == nil { return "", nil } - return fileSystemAttrs.Digests, nil + return o.n.sha1(), nil } // Size returns the size of an object in bytes func (o *Object) Size() int64 { - if o.fs.opt.ReportOriginalSize { - // if ReportOriginalSize is set, we will generate an error when the original size failed to be parsed - // this is crucial as features like Open() will need to use the proper size to operate the seek/range operator - if o.originalSize != nil { - return *o.originalSize - } - - fs.Debugf(o, "Original file size missing") + if o.n == nil { + return -1 } - return o.size + return o.n.size(o.fs.opt.ReportOriginalSize) } // ModTime returns the modification time of the object -// -// It attempts to read the objects mtime and if that isn't present the -// LastModified returned in the http headers func (o *Object) ModTime(ctx context.Context) time.Time { - return o.modTime + if o.n == nil { + return time.Time{} + } + return o.n.modTime() } -// SetModTime sets the modification time of the local fs object +// SetModTime is not supported: the modification time is part of the +// uploaded revision func (o *Object) SetModTime(ctx context.Context, modTime time.Time) error { return fs.ErrorCantSetModTime } @@ -1047,237 +1096,108 @@ func (o *Object) Storable() bool { // Open opens the file for read. Call Close() on the returned io.ReadCloser func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadCloser, error) { - fs.FixRangeOption(options, o.Size()) + if o.n == nil { + return nil, fs.ErrorObjectNotFound + } + size := o.Size() + fs.FixRangeOption(options, size) var offset, limit int64 = 0, -1 - for _, option := range options { // if the caller passes in nil for options, it will become array of nil + for _, option := range options { switch x := option.(type) { case *fs.SeekOption: offset = x.Offset case *fs.RangeOption: - offset, limit = x.Decode(o.Size()) + offset, limit = x.Decode(size) default: if option.Mandatory() { fs.Logf(o, "Unsupported mandatory option: %v", option) } } } - - // download and decrypt the file - var reader io.ReadCloser - var fileSystemAttrs *protonDriveAPI.FileSystemAttrs - var sizeOnServer int64 - var err error - if err = o.fs.pacer.Call(func() (bool, error) { - reader, sizeOnServer, fileSystemAttrs, err = o.fs.protonDrive.DownloadFileByID(ctx, o.id, offset) - return shouldRetry(ctx, err) - }); err != nil { - return nil, err + rc, err := o.fs.c.open(ctx, o.n, offset, limit) + if err != nil { + return nil, translateError(err, opObject) } - - if fileSystemAttrs != nil { - o.originalSize = &fileSystemAttrs.Size - o.modTime = fileSystemAttrs.ModificationTime - o.digests = &fileSystemAttrs.Digests - o.blockSizes = fileSystemAttrs.BlockSizes - } else { - fs.Debugf(o, "fileSystemAttrs is nil: using fallback size, and now digests and blocksizes available") - o.originalSize = &sizeOnServer - o.size = sizeOnServer - o.digests = nil - o.blockSizes = nil - } - - retReader := io.NopCloser(reader) // the NewLimitedReadCloser will deal with the limit - - // deal with limit - return readers.NewLimitedReadCloser(retReader, limit), nil + return rc, nil } -// Update in to the object with the modTime given of the given size +// Update the object with the contents of the io.Reader, modTime and size // -// When called from outside an Fs by rclone, src.Size() will always be >= 0. -// But for unknown-sized objects (indicated by src.Size() == -1), Upload should either -// return an error or update the object properly (rather than e.g. calling panic). +// If the object exists, its content becomes a new revision of it. func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error { - size := src.Size() - if size < 0 { - return errCanNotUploadFileWithUnknownSize + r := uploadRequest{ + In: in, + Size: src.Size(), + ModTime: src.ModTime(ctx), + MIMEType: fs.MimeType(ctx, src), } - - remote := o.Remote() - leaf, folderLinkID, err := o.fs.dirCache.FindPath(ctx, o.fs.sanitizePath(remote), true) - if err != nil { - return err + if srcFs := src.Fs(); srcFs != nil && srcFs.Hashes().Contains(hash.SHA1) { + r.SHA1, _ = src.Hash(ctx, hash.SHA1) } - - modTime := src.ModTime(ctx) - var linkID string - var fileSystemAttrs *proton.RevisionXAttrCommon - if err = o.fs.pacer.CallNoRetry(func() (bool, error) { - linkID, fileSystemAttrs, err = o.fs.protonDrive.UploadFileByReader(ctx, folderLinkID, leaf, modTime, in, 0) - return shouldRetry(ctx, err) - }); err != nil { - return err - } - - var sha1Hash string - if val, ok := fileSystemAttrs.Digests["SHA1"]; ok { - sha1Hash = val + if o.n != nil { + n, err := o.fs.c.getNode(ctx, o.n.ID) + if err != nil { + return translateError(err, opObject) + } + r.Existing = n } else { - sha1Hash = "" + leaf, directoryID, err := o.fs.dirCache.FindPath(ctx, o.remote, true) + if err != nil { + return err + } + r.ParentID, r.Name = directoryID, o.fs.opt.Enc.FromStandardName(leaf) } - - o.id = linkID - o.originalSize = &fileSystemAttrs.Size - // The server stores modtimes with second precision so truncate - // here too to keep the in-memory modtime identical to the one a - // fresh listing returns. - o.modTime = modTime.Truncate(time.Second) - o.blockSizes = fileSystemAttrs.BlockSizes - o.digests = &sha1Hash - - return nil -} - -// Remove an object -func (o *Object) Remove(ctx context.Context) error { - return o.fs.pacer.Call(func() (bool, error) { - err := o.fs.protonDrive.MoveFileToTrashByID(ctx, o.id) - return shouldRetry(ctx, err) - }) -} - -// ID returns the ID of the Object if known, or "" if not -func (o *Object) ID() string { - return o.id -} - -// Purge all files in the directory specified -// -// Implement this if you have a way of deleting all the files -// quicker than just running Remove() on the result of List() -// -// Return an error if it doesn't exist -func (f *Fs) Purge(ctx context.Context, dir string) error { - root := path.Join(f.root, dir) - if root == "" { - // we can't remove the root directory, but we can list the directory and delete every folder and file in here - return errCanNotPurgeRootDirectory - } - - folderLinkID, err := f.dirCache.FindDir(ctx, f.sanitizePath(dir), false) + n, err := o.fs.c.upload(ctx, r) if err != nil { - return err + return translateError(err, opObject) } - - if err = f.pacer.Call(func() (bool, error) { - err = f.protonDrive.MoveFolderToTrashByID(ctx, folderLinkID, false) - return shouldRetry(ctx, err) - }); err != nil { - return err - } - - f.dirCache.FlushDir(dir) + o.n = n return nil } +// Remove the object by moving it to the trash +func (o *Object) Remove(ctx context.Context) error { + if o.n == nil { + return fs.ErrorObjectNotFound + } + err := o.fs.c.trash(ctx, o.n.ID) + if errors.Is(err, errNotFound) { + // Already gone. + return nil + } + return translateError(err, opObject) +} + // MimeType of an Object if known, "" otherwise func (o *Object) MimeType(ctx context.Context) string { - return o.mimetype + if o.n == nil { + return "" + } + return o.n.MIMEType } -// Disconnect the current user -func (f *Fs) Disconnect(ctx context.Context) error { - return f.pacer.Call(func() (bool, error) { - err := f.protonDrive.Logout(ctx) - return shouldRetry(ctx, err) - }) -} - -// Move src to this remote using server-side move operations. -// -// This is stored with the remote path given. -// -// It returns the destination Object and a possible error. -// -// Will only be called if src.Fs().Name() == f.Name() -// -// If it isn't possible then return fs.ErrorCantMove -func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object, error) { - srcObj, ok := src.(*Object) - if !ok { - fs.Debugf(src, "Can't move - not same remote type") - return nil, fs.ErrorCantMove +// ID returns the ID of the Object if known, or "" if not +func (o *Object) ID() string { + if o.n == nil { + return "" } - - // check if the remote (dst) exists - _, err := f.NewObject(ctx, remote) - if err != nil { - if err != fs.ErrorObjectNotFound { - return nil, err - } - // object is indeed not found - } else { - // object at the dst exists - return nil, fs.ErrorCantMove - } - - // attempt the move - dstLeaf, dstDirectoryID, err := f.dirCache.FindPath(ctx, f.sanitizePath(remote), true) - if err != nil { - return nil, err - } - if err = f.pacer.Call(func() (bool, error) { - err = f.protonDrive.MoveFileByID(ctx, srcObj.id, dstDirectoryID, dstLeaf) - return shouldRetry(ctx, err) - }); err != nil { - return nil, err - } - - f.dirCache.FlushDir(f.sanitizePath(src.Remote())) - - return f.NewObject(ctx, remote) -} - -// DirMove moves src, srcRemote to this remote at dstRemote -// using server-side move operations. -// -// Will only be called if src.Fs().Name() == f.Name() -// -// If it isn't possible then return fs.ErrorCantDirMove -// -// If destination exists then return fs.ErrorDirExists -func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string) error { - srcFs, ok := src.(*Fs) - if !ok { - fs.Debugf(srcFs, "Can't move directory - not same remote type") - return fs.ErrorCantDirMove - } - - srcID, _, _, dstDirectoryID, dstLeaf, err := f.dirCache.DirMove(ctx, srcFs.dirCache, f.sanitizePath(srcFs.root), f.sanitizePath(srcRemote), f.sanitizePath(f.root), f.sanitizePath(dstRemote)) - if err != nil { - return err - } - - if err = f.pacer.Call(func() (bool, error) { - err = f.protonDrive.MoveFolderByID(ctx, srcID, dstDirectoryID, dstLeaf) - return shouldRetry(ctx, err) - }); err != nil { - return err - } - - srcFs.dirCache.FlushDir(f.sanitizePath(srcRemote)) - - return nil + return o.n.ID } // Check the interfaces are satisfied var ( _ fs.Fs = (*Fs)(nil) + _ fs.Purger = (*Fs)(nil) + _ fs.Copier = (*Fs)(nil) _ fs.Mover = (*Fs)(nil) _ fs.DirMover = (*Fs)(nil) - _ fs.DirCacheFlusher = (*Fs)(nil) + _ fs.PutStreamer = (*Fs)(nil) + _ fs.ListPer = (*Fs)(nil) + _ fs.CleanUpper = (*Fs)(nil) _ fs.Abouter = (*Fs)(nil) + _ fs.Disconnecter = (*Fs)(nil) + _ fs.Shutdowner = (*Fs)(nil) + _ fs.DirCacheFlusher = (*Fs)(nil) _ fs.Object = (*Object)(nil) _ fs.MimeTyper = (*Object)(nil) _ fs.IDer = (*Object)(nil) diff --git a/backend/protondrive/protondrive_internal_test.go b/backend/protondrive/protondrive_internal_test.go index 651d848e3..3bd17075b 100644 --- a/backend/protondrive/protondrive_internal_test.go +++ b/backend/protondrive/protondrive_internal_test.go @@ -2,96 +2,365 @@ package protondrive import ( "context" + "encoding/base64" "errors" "fmt" - "regexp" + "strings" "testing" + "time" - "github.com/rclone/go-proton-api" + "github.com/pquerna/otp/totp" + "github.com/rclone/rclone/backend/protondrive/api" + "github.com/rclone/rclone/backend/protondrive/protontest" + "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/config/configmap" + "github.com/rclone/rclone/fs/config/obscure" + "github.com/rclone/rclone/fs/fserrors" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) -var protonDriveAppVersionPattern = regexp.MustCompile(`(?i)^external-drive(-[a-z_]+)+@[0-9]+\.[0-9]+\.[0-9]+(\.[0-9]+)?-((stable|beta|RC|alpha)(([.-]?\d+)*)?)?([.-]?dev)?(\+.*)?$`) +func TestTranslateError(t *testing.T) { + apiErr := func(code int) error { + return fmt.Errorf("call: %w", &api.Error{Status: 422, Code: code, Message: "proton says no"}) + } + notFound := fmt.Errorf("get node: %w", errNotFound) + exists := fmt.Errorf("create: %w", errExists) + other := errors.New("other") -func TestProtonDriveAppVersionFromRcloneVersion(t *testing.T) { - testCases := []struct { - name string - rcloneVersion string - want string + for _, test := range []struct { + name string + err error + op errorOp + want error // compared with ==, if set + check func(t *testing.T, got error) }{ - { - name: "release", - rcloneVersion: "v1.73.5", - want: "external-drive-rclone@1.73.5-stable", - }, - { - name: "dev build", - rcloneVersion: "v1.74.0-DEV", - want: "external-drive-rclone@1.74.0-dev", - }, - { - name: "beta build with extra metadata", - rcloneVersion: "v1.74.0-beta.9519.990f33f2a.fix-protondrive-sdk-2026", - want: "external-drive-rclone@1.74.0-beta.9519+990f33f2a.fix-protondrive-sdk-2026", - }, - { - name: "beta build with unsanitized branch name", - rcloneVersion: "v1.74.0-beta.9519.990f33f2a.fix/protondrive-sdk-2026", - want: "external-drive-rclone@1.74.0-beta.9519+990f33f2a.fix-protondrive-sdk-2026", - }, - { - name: "invalid version falls back to stable", - rcloneVersion: "not-a-version", - want: "external-drive-rclone@1.0.0-stable", - }, - } - - for _, testCase := range testCases { - t.Run(testCase.name, func(t *testing.T) { - got := protonDriveAppVersionFromRcloneVersion(testCase.rcloneVersion) - - if got != testCase.want { - t.Fatalf("unexpected app version: got %q, want %q", got, testCase.want) - } - if !protonDriveAppVersionPattern.MatchString(got) { - t.Fatalf("app version %q does not match Proton pattern", got) - } - }) - } -} - -func TestShouldRetry(t *testing.T) { - ctx := context.Background() - cancelledCtx, cancel := context.WithCancel(ctx) - cancel() - - apiErr := func(status int, code proton.Code) error { - return &proton.APIError{Status: status, Code: code, Message: "test"} - } - - for _, tc := range []struct { - name string - ctx context.Context - err error - wantRetry bool - }{ - {"nil error", ctx, nil, false}, - {"cancelled context", cancelledCtx, errors.New("some error"), false}, - {"permanent validation error Code=200501 Status=422 (not retried)", ctx, apiErr(422, 200501), false}, - {"transient storage block error Code=200501 Status=500 (retried)", ctx, apiErr(500, 200501), true}, - {"server error Status=500", ctx, apiErr(500, 0), true}, - {"server error Status=502", ctx, apiErr(502, 0), true}, - {"server error Status=504", ctx, apiErr(504, 0), true}, - {"server error Status=503 (handled by SDK, not retried here)", ctx, apiErr(503, 0), false}, - {"rate limit Status=429 (handled by SDK, not retried here)", ctx, apiErr(429, 0), false}, - {"client error Status=400", ctx, apiErr(400, 0), false}, - {"client error Status=404", ctx, apiErr(404, 0), false}, - {"wrapped API error retried via errors.As", ctx, fmt.Errorf("wrapped: %w", apiErr(500, 0)), true}, - {"non-API error falls back to fserrors.ShouldRetry", ctx, errors.New("plain error"), false}, + {name: "nil", err: nil, op: opObject, want: nil}, + {name: "not found object", err: notFound, op: opObject, want: fs.ErrorObjectNotFound}, + {name: "not found dir", err: notFound, op: opDir, want: fs.ErrorDirNotFound}, + {name: "code 2501 object", err: apiErr(api.CodeNotExists), op: opObject, want: fs.ErrorObjectNotFound}, + {name: "code 2501 dir", err: apiErr(api.CodeNotExists), op: opDir, want: fs.ErrorDirNotFound}, + {name: "exists mkdir", err: exists, op: opMkdir, want: nil}, + {name: "exists move", err: exists, op: opMove, want: fs.ErrorCantMove}, + {name: "exists copy", err: exists, op: opCopy, want: fs.ErrorCantCopy}, + {name: "exists dirmove", err: exists, op: opDirMove, want: fs.ErrorDirExists}, + {name: "exists object", err: exists, op: opObject, check: func(t *testing.T, got error) { + assert.ErrorIs(t, got, errExists) + }}, + {name: "other unchanged", err: other, op: opObject, want: other}, } { - t.Run(tc.name, func(t *testing.T) { - gotRetry, _ := shouldRetry(tc.ctx, tc.err) - assert.Equal(t, tc.wantRetry, gotRetry) + t.Run(test.name, func(t *testing.T) { + got := translateError(test.err, test.op) + if test.check != nil { + test.check(t, got) + return + } + assert.Equal(t, test.want, got) }) } + + for _, code := range []int{ + api.CodeInsufficientQuota, api.CodeInsufficientSpace, api.CodeMaxFileSizeForFreeUser, + api.CodeMaxPublicEditModeForFreeUser, api.CodeTooManyChildren, api.CodeNestingTooDeep, + } { + t.Run(fmt.Sprintf("code %d no retry", code), func(t *testing.T) { + got := translateError(apiErr(code), opObject) + assert.True(t, fserrors.IsNoRetryError(got)) + assert.False(t, fserrors.IsFatalError(got)) + assert.Contains(t, got.Error(), "proton says no") + }) + } + for _, code := range []int{api.CodeInvalidRequirements, api.CodeAppVersionBad} { + t.Run(fmt.Sprintf("code %d fatal", code), func(t *testing.T) { + got := translateError(apiErr(code), opObject) + assert.True(t, fserrors.IsFatalError(got)) + assert.Contains(t, got.Error(), "upgrade rclone") + assert.Contains(t, got.Error(), "proton says no") + }) + } + for _, err := range []error{errIntegrity, errUploadMismatch, errUploadSuperseded} { + t.Run(err.Error()+" no retry", func(t *testing.T) { + got := translateError(fmt.Errorf("op: %w", err), opObject) + assert.True(t, fserrors.IsNoRetryError(got)) + assert.ErrorIs(t, got, err) + }) + } + t.Run("outcome unknown no low level retry", func(t *testing.T) { + got := translateError(fmt.Errorf("op: %w", errUploadOutcomeUnknown), opObject) + assert.True(t, fserrors.IsNoLowLevelRetryError(got)) + assert.False(t, fserrors.IsNoRetryError(got)) + assert.ErrorIs(t, got, errUploadOutcomeUnknown) + }) +} + +// sessionConfig returns the config keys of a v1.76 remote holding a new +// saved session of u, pointed at srv. +func sessionConfig(srv *protontest.Server, u *protontest.User) configmap.Simple { + sess := srv.NewSession(u) + return configmap.Simple{ + "type": "protondrive", + "username": "", + "password": "", + "mailbox_password": "", + "2fa": "", + "otp_secret_key": "", + "client_uid": sess.UID, + "client_access_token": sess.AccessToken, + "client_refresh_token": sess.RefreshToken, + "client_salted_key_pass": base64.StdEncoding.EncodeToString([]byte(u.KeyPassword())), + "encoding": "Slash,LeftSpace,RightSpace,InvalidUtf8,Dot", + "original_file_size": "true", + "app_version": "", + "replace_existing_draft": "false", + "enable_caching": "true", + // Not a v1.76 key, but the only way to reach the fake. + "endpoint": srv.URL(), + } +} + +// newTestFs returns an Fs for the config m, shut down when the test ends. +func newTestFs(t *testing.T, m configmap.Mapper) *Fs { + t.Helper() + f, err := NewFs(context.Background(), "test", "", m) + require.NoError(t, err) + t.Cleanup(func() { _ = f.(*Fs).Shutdown(context.Background()) }) + return f.(*Fs) +} + +// authRequests returns the auth requests made to srv. +func authRequests(srv *protontest.Server) []string { + var out []string + for route := range srv.Requests() { + if strings.Contains(route, "/auth") { + out = append(out, route) + } + } + return out +} + +func TestOptionsBackwardsCompatible(t *testing.T) { + srv := protontest.New(t) + u := srv.AddUser("user", "pass") + m := sessionConfig(srv, u) + want := m["client_access_token"] + f := newTestFs(t, m) + + _, err := f.List(context.Background(), "") + require.NoError(t, err) + assert.Empty(t, authRequests(srv), "a saved session must be used without signing in") + assert.Equal(t, want, m["client_access_token"]) + assert.Len(t, m["draft_client_uid"], 32, "draft_client_uid is generated and saved") + assert.True(t, f.opt.ReportOriginalSize) + assert.True(t, f.opt.EnableCaching) +} + +func TestNewFsPasswordFallback(t *testing.T) { + srv := protontest.New(t) + u := srv.AddUser("user", "pass") + m := sessionConfig(srv, u) + m["username"] = "user" + m["password"] = obscure.MustObscure("pass") + oldUID := m["client_uid"] + srv.RevokeSession(oldUID) + + f := newTestFs(t, m) + _, err := f.List(context.Background(), "") + require.NoError(t, err) + assert.NotEqual(t, oldUID, m["client_uid"]) + assert.NotEmpty(t, m["client_access_token"]) + assert.NotEmpty(t, m["client_refresh_token"]) + keyPass, err := base64.StdEncoding.DecodeString(m["client_salted_key_pass"]) + require.NoError(t, err) + assert.Equal(t, u.KeyPassword(), string(keyPass)) + assert.Equal(t, 1, srv.Requests()["POST /core/v4/auth"]) +} + +func TestNewFsPasswordFallbackTOTP(t *testing.T) { + srv := protontest.New(t) + u := srv.AddUser("user", "pass") + secret := u.EnableTOTP() + m := sessionConfig(srv, u) + for _, k := range []string{"client_uid", "client_access_token", "client_refresh_token", "client_salted_key_pass"} { + m[k] = "" + } + m["username"] = "user" + m["password"] = obscure.MustObscure("pass") + m["otp_secret_key"] = obscure.MustObscure(secret) + + newTestFs(t, m) + assert.NotEmpty(t, m["client_uid"]) + assert.Equal(t, 1, srv.Requests()["POST /core/v4/auth/2fa"]) +} + +func TestNewFsNoCredentials(t *testing.T) { + srv := protontest.New(t) + u := srv.AddUser("user", "pass") + + t.Run("none saved", func(t *testing.T) { + m := configmap.Simple{"endpoint": srv.URL()} + _, err := NewFs(context.Background(), "myremote", "", m) + require.Error(t, err) + assert.Contains(t, err.Error(), `rclone config reconnect myremote:`) + }) + t.Run("revoked", func(t *testing.T) { + m := sessionConfig(srv, u) + srv.RevokeSession(m["client_uid"]) + _, err := NewFs(context.Background(), "myremote", "", m) + require.Error(t, err) + assert.Contains(t, err.Error(), `rclone config reconnect myremote:`) + }) + t.Run("undecodable key password", func(t *testing.T) { + m := sessionConfig(srv, u) + m["client_salted_key_pass"] = "not base64!" + _, err := NewFs(context.Background(), "myremote", "", m) + require.Error(t, err) + assert.Contains(t, err.Error(), `rclone config reconnect myremote:`) + }) +} + +func TestTwoRemotesIsolated(t *testing.T) { + ctx := context.Background() + srv := protontest.New(t) + u1 := srv.AddUser("user1", "pass1") + u2 := srv.AddUser("user2", "pass2") + m1, m2 := sessionConfig(srv, u1), sessionConfig(srv, u2) + uid1, uid2 := m1["client_uid"], m2["client_uid"] + f1, f2 := newTestFs(t, m1), newTestFs(t, m2) + require.NoError(t, f1.Mkdir(ctx, "one")) + require.NoError(t, f2.Mkdir(ctx, "two")) + + // Make both sessions refresh, saving new tokens. + srv.ExpireAccessToken(uid1) + srv.ExpireAccessToken(uid2) + f1.DirCacheFlush() + f2.DirCacheFlush() + entries1, err := f1.List(ctx, "") + require.NoError(t, err) + entries2, err := f2.List(ctx, "") + require.NoError(t, err) + + require.Len(t, entries1, 1) + assert.Equal(t, "one", entries1[0].Remote()) + require.Len(t, entries2, 1) + assert.Equal(t, "two", entries2[0].Remote()) + assert.Equal(t, uid1, m1["client_uid"]) + assert.Equal(t, uid2, m2["client_uid"]) + for _, k := range []string{"client_uid", "client_access_token", "client_refresh_token", "client_salted_key_pass", "draft_client_uid"} { + assert.NotEqual(t, m1[k], m2[k], k) + } +} + +// configAnswers drives configure through its states, answering each +// question by its state from answers, and returns the questions asked. +func configAnswers(t *testing.T, m configmap.Mapper, signIn signInOptions, answers map[string]string) []*fs.ConfigOut { + t.Helper() + var asked []*fs.ConfigOut + in := fs.ConfigIn{} + for range 10 { + out, err := configure(context.Background(), "test", m, in, signIn) + require.NoError(t, err) + if out == nil { + return asked + } + require.Empty(t, out.Error) + in = fs.ConfigIn{State: out.State} + if out.Option != nil { + asked = append(asked, out) + answer, ok := answers[out.State] + require.True(t, ok, "unexpected question in state %q: %s", out.State, out.Option.Help) + in.Result = answer + } + } + t.Fatal("config didn't finish") + return nil +} + +// requireSession checks m holds a working session of u on srv. +func requireSession(t *testing.T, srv *protontest.Server, m configmap.Simple, u *protontest.User) { + t.Helper() + keyPass, err := base64.StdEncoding.DecodeString(m["client_salted_key_pass"]) + require.NoError(t, err) + assert.Equal(t, u.KeyPassword(), string(keyPass)) + srv.ResetRequests() + newTestFs(t, m) + assert.Empty(t, authRequests(srv)) +} + +func TestConfigBrowser(t *testing.T) { + srv := protontest.New(t) + u := srv.AddUser("user", "pass") + m := configmap.Simple{"endpoint": srv.URL()} + var shown string + signIn := signInOptions{ + pollInterval: 10 * time.Millisecond, + pollTimeout: 10 * time.Second, + showURL: func(signInURL string) { + shown = signInURL + require.NoError(t, srv.ApproveFork(signInURL, u)) + }, + } + + asked := configAnswers(t, m, signIn, map[string]string{"choose": "true"}) + require.Len(t, asked, 1) + assert.Contains(t, asked[0].Option.Help, "rclone is a third-party application not officially supported by Proton.") + assert.Equal(t, true, asked[0].Option.Default) + assert.True(t, strings.HasPrefix(shown, forkSignInURL), shown) + requireSession(t, srv, m, u) +} + +func TestConfigPassword(t *testing.T) { + srv := protontest.New(t) + + t.Run("no 2fa", func(t *testing.T) { + u := srv.AddUser("user", "pass") + m := configmap.Simple{"endpoint": srv.URL(), "username": "user", "password": obscure.MustObscure("pass")} + asked := configAnswers(t, m, signInOptions{}, map[string]string{"choose": "false"}) + require.Len(t, asked, 1) + assert.Equal(t, false, asked[0].Option.Default, "password sign-in is the default when a password is set") + requireSession(t, srv, m, u) + }) + t.Run("2fa asked", func(t *testing.T) { + u := srv.AddUser("user2fa", "pass") + secret := u.EnableTOTP() + m := configmap.Simple{"endpoint": srv.URL(), "username": "user2fa", "password": obscure.MustObscure("pass")} + code, err := totp.GenerateCode(secret, time.Now()) + require.NoError(t, err) + asked := configAnswers(t, m, signInOptions{}, map[string]string{"choose": "false", "password_2fa": code}) + require.Len(t, asked, 2) + requireSession(t, srv, m, u) + assert.Empty(t, m["2fa"], "the 2FA code is not saved") + }) + t.Run("no password", func(t *testing.T) { + m := configmap.Simple{"endpoint": srv.URL()} + out, err := configure(context.Background(), "test", m, fs.ConfigIn{State: "password"}, signInOptions{}) + require.NoError(t, err) + require.NotNil(t, out) + assert.NotEmpty(t, out.Error) + }) +} + +func TestConfigStore(t *testing.T) { + creds := credentials{UID: "uid", AccessToken: "access", RefreshToken: "refresh", KeyPassword: "key\x00pass"} + + t.Run("round trip", func(t *testing.T) { + m := configmap.Simple{} + s := &configStore{m: m} + s.Save(creds) + assert.Equal(t, base64.StdEncoding.EncodeToString([]byte(creds.KeyPassword)), m[clientSaltedKeyPassKey]) + assert.Equal(t, creds, s.Load()) + // Another user of the config saves newer tokens. + m[clientRefreshTokenKey] = "newer" + assert.Equal(t, "newer", s.Load().RefreshToken) + }) + t.Run("overridden", func(t *testing.T) { + // Values from the environment or the command line take + // precedence over the config file the store saves to. + env := configmap.Simple{clientUIDKey: "old uid", clientAccessTokenKey: "old access", clientRefreshTokenKey: "old refresh"} + file := configmap.Simple{} + m := configmap.New().AddGetter(env, configmap.PriorityNormal).AddGetter(file, configmap.PriorityConfig).AddSetter(file) + s := &configStore{m: m} + assert.Equal(t, "old refresh", s.Load().RefreshToken) + s.Save(creds) + assert.Equal(t, creds, s.Load(), "saved credentials must not be shadowed by spent ones") + }) } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9c372d9a5..f2f31e5dc 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -37,8 +37,36 @@ leaves out. Update in the same commit as any structural change. - cgo use differs per release target (the `cgo` and `build_flags` columns of the matrix in `.github/workflows/build.yml`), so a backend cannot assume cgo. +## `backend/protondrive` + +A native client of the Proton Drive API, following Proton's Drive SDK +(spec: `docs/specs/001-protondrive-tier1.md`). + +| File | Responsibility | +|---|---| +| `protondrive.go` | `Fs`, `Object`, options, `Config` sign-in, dircache glue, `translateError` | +| `session.go` | SRP and browser (session fork) sign-in, token refresh, app version | +| `account.go` | User and address keys, public-key lookups | +| `crypto.go` | Every OpenPGP operation | +| `nodes.go` | The `client`: volume bootstrap, pacing, listing, folder/rename/move/copy/trash | +| `cache.go` | In-memory node and listing cache | +| `upload.go`, `download.go` | Block pipelines | +| `api/` | Wire types | +| `protontest/` | Fake Proton server, imported by tests only; never imports the backend | + +- **The seam:** `protondrive.go` holds no cryptography and no API routes; + the other files never take or return `fs.Fs`/`fs.Object`. +- No package-level mutable state except `unlockMu` (key unlocking is + serialised across `Fs` instances). Each `Fs` has its own client, session + and cache; credentials go through a per-`Fs` `configStore` over the + remote's config. +- `fake_test.go` runs the full `fstests` contract suite against + `protontest` through the hidden `endpoint` option, on every + `go test`; `protondrive_test.go` is the live suite (`TestProtonDrive:`). + ## Known rough edges -- `backend/protondrive` depends on the forks `github.com/rclone/Proton-API-Bridge` - and `github.com/rclone/go-proton-api` (`go.mod`). See `docs/specs/`. +- `backend/protondrive` tests still import `github.com/rclone/go-proton-api` + for differential crypto tests, and `go.mod` still lists + `github.com/rclone/Proton-API-Bridge`; both go in plan Task 19. - See `docs/TODO.md` for host tooling gaps. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 1815eb44c..51a18cf6a 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -5,6 +5,28 @@ it with a new one that links back. One entry per decision a future maintainer would otherwise have to reverse-engineer. No index: `grep -n '^## ' docs/DECISIONS.md` lists every entry. +## 2026-11-11 - Proton Drive backend runs on its own client + +**Status:** accepted +**Context:** The backend sat on `rclone/Proton-API-Bridge` and +`rclone/go-proton-api`, which share credentials through package globals, +write files the official clients can't always read, and can't be tested +without a live account (spec 001). +**Decision:** `protondrive.go` was rewritten on the native client built in +plan Tasks 2-12, keeping every option name and meaning and reading v1.76 +saved sessions without signing in again. `Config` offers browser sign-in +(default unless a username and password are already set, so existing +scripted setups keep using them) and password sign-in. An upload whose +commit outcome can't be known is a no-low-level-retry error: an immediate +retry could add a revision that already landed, while a later sync pass +reads the destination first. +**Alternatives:** Patching the bridge (globals and crypto stay outside the +tree); keeping browser sign-in the default even with a password set +(non-interactive `config create` would wait on a browser). +**Consequences:** The full contract suite runs hermetically against +`protontest`. Several `Fs` of one account in one process each cache +separately until events land (spec 6.2). + ## 2026-11-11 - Fork agent tooling is appended, not merged, into upstream files **Status:** accepted diff --git a/docs/TODO.md b/docs/TODO.md index 9b4b7120a..d5c649055 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -59,6 +59,20 @@ Small, specific, independently actionable. Remove only when actually done. bad verifier token, a missing block and a stale `CurrentRevisionID` (the fake uses 422 / 2000, which the spec maps to "upgrade rclone"). +- [ ] protondrive: `Rmdir` checks emptiness with `listChildren`, which + leaves out Proton Docs/Sheets, drafts and unreadable nodes, so a folder + holding only those is trashed (recoverable from the trash). Needs a raw + child count from the client. +- [ ] protondrive: several `Fs` of one account in one process each have + their own node cache; only Move/DirMove sources are invalidated across + them. Events (spec 6.2) fix this. +- [ ] protondrive: `go mod tidy` would drop `github.com/rclone/Proton-API-Bridge` + from `go.mod` now (no Go file imports it; the differential tests import + only `go-proton-api`). Left in place for Task 19, which removes both. +- [ ] protondrive: browser sign-in in `rclone config` waits up to 10 minutes + polling; a non-interactive `config create` without username and password + waits the same. + - [ ] Propose a CI check for this fork: `AGENTS.md`, `CLAUDE.md`, `GEMINI.md` and the `docs/` agent files exist, and `AGENTS.md` is at most 150 lines. - [ ] Upstream CI (`.github/workflows/build.yml`) is gated on diff --git a/docs/plans/001-protondrive-tier1.md b/docs/plans/001-protondrive-tier1.md index 362e6ee73..1808df94d 100644 --- a/docs/plans/001-protondrive-tier1.md +++ b/docs/plans/001-protondrive-tier1.md @@ -1085,7 +1085,7 @@ Decisions: **The differential tests still import the old libraries**, so they remain in `go.mod` after this task; their removal is Task 19. -- [ ] **Step 1: Write failing tests** in `protondrive_internal_test.go`: +- [x] **Step 1: Write failing tests** in `protondrive_internal_test.go`: `TestTranslateError` table for every mapping above; `TestOptionsBackwardsCompatible`: a `configmap.Simple` holding exactly the keys of a v1.76 config (list in Global Constraints) builds an `Fs` @@ -1099,13 +1099,13 @@ Decisions: `TestConfigBrowser` and `TestConfigPassword`: drive `Config` through its states with `fs.ConfigIn` results; the browser state's text contains the third-party notice. -- [ ] **Step 2: Run** - expect FAIL. -- [ ] **Step 3: Rewrite `protondrive.go`.** -- [ ] **Step 4: Run** `go test -race ./backend/protondrive/ -run TestIntegrationFake -v 2>&1 | tail -40`. +- [x] **Step 2: Run** - expect FAIL. +- [x] **Step 3: Rewrite `protondrive.go`.** +- [x] **Step 4: Run** `go test -race ./backend/protondrive/ -run TestIntegrationFake -v 2>&1 | tail -40`. Fix failures in the new code (never by weakening the fake or skipping a test) until the suite passes. Then the four verification commands, and `go build ./...`. -- [ ] **Step 5: Commit** `protondrive: rewrite the backend on a native client following Proton's SDK`. +- [x] **Step 5: Commit** `protondrive: rewrite the backend on a native client following Proton's SDK`. ### Task 15: Regression tests for known failures