Compare commits
126
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0bdbcde6b | ||
|
|
c0cef5e872 | ||
|
|
ee3c3e894f | ||
|
|
10fcd4e697 | ||
|
|
2a13b4ee0a | ||
|
|
db6527e506 | ||
|
|
5ad00fc4bd | ||
|
|
9a56a13555 | ||
|
|
216f06b925 | ||
|
|
5daa3e9504 | ||
|
|
e60d2f97ad | ||
|
|
aa8ceb2940 | ||
|
|
02bbeea992 | ||
|
|
ec1eb597b1 | ||
|
|
14dc9c5dba | ||
|
|
ef9fa40182 | ||
|
|
dd30f78d43 | ||
|
|
0d4fb17328 | ||
|
|
049cf6d47d | ||
|
|
a16cfc97ba | ||
|
|
8eb770e707 | ||
|
|
3188ae57b8 | ||
|
|
bc57967ea4 | ||
|
|
b339a0512b | ||
|
|
d8eddff1f9 | ||
|
|
65258f9036 | ||
|
|
8c9ed04aa6 | ||
|
|
4d0869df6e | ||
|
|
a6779f3d79 | ||
|
|
66196f7f22 | ||
|
|
9fa8061fec | ||
|
|
a91c06503d | ||
|
|
9ac0cc272b | ||
|
|
288ace1d0a | ||
|
|
f627902517 | ||
|
|
cf7904cb51 | ||
|
|
eccd97d75a | ||
|
|
dd0a994ea4 | ||
|
|
588da96492 | ||
|
|
c5e537e3aa | ||
|
|
3f8764db81 | ||
|
|
597e3f31bd | ||
|
|
44d913c0c8 | ||
|
|
ae1ca5c2c0 | ||
|
|
b0ef5f6a6e | ||
|
|
2033adc32a | ||
|
|
644dd73528 | ||
|
|
060195ce54 | ||
|
|
9622aff8f7 | ||
|
|
f42d8291c2 | ||
|
|
64c536e441 | ||
|
|
4cf147ab08 | ||
|
|
d55dd62ffd | ||
|
|
e49f3350ab | ||
|
|
2a4eec17a8 | ||
|
|
ba96467b69 | ||
|
|
d4bf037dbb | ||
|
|
c1258b0494 | ||
|
|
380979edc6 | ||
|
|
5ed5d9586b | ||
|
|
5af030df0a | ||
|
|
d4bf998f7b | ||
|
|
450535fcdf | ||
|
|
43cd60e59f | ||
|
|
cdad8ce1f3 | ||
|
|
41893f019f | ||
|
|
95487b2ff9 | ||
|
|
86fe420a86 | ||
|
|
9fe38b74cb | ||
|
|
c7c1c401c4 | ||
|
|
571b965e2f | ||
|
|
d6d2026dd0 | ||
|
|
f7010de4ed | ||
|
|
448d7361c8 | ||
|
|
cbc8c3fbd9 | ||
|
|
65d4b73a44 | ||
|
|
d459c3f992 | ||
|
|
82cb84b201 | ||
|
|
7d9963121a | ||
|
|
98d4e8f369 | ||
|
|
ea9f816061 | ||
|
|
dfbe3ae1d0 | ||
|
|
6a4b77208e | ||
|
|
e982ff3666 | ||
|
|
53b2d7aaf2 | ||
|
|
17ebd339da | ||
|
|
e3c400f583 | ||
|
|
5c5a3199d7 | ||
|
|
37b306d5d1 | ||
|
|
b000741c98 | ||
|
|
c0bf21991e | ||
|
|
9aba8e4e41 | ||
|
|
8d0b08d125 | ||
|
|
2fc95aef84 | ||
|
|
0c6e76b6b3 | ||
|
|
b2dc0e3931 | ||
|
|
544758e553 | ||
|
|
7b29032d4d | ||
|
|
b4659519df | ||
|
|
866e7ac577 | ||
|
|
f6ca72fabb | ||
|
|
a3c6bb2a32 | ||
|
|
7c60060d4c | ||
|
|
2b4cb5f85b | ||
|
|
84bdebae77 | ||
|
|
c7a34b80d3 | ||
|
|
5ecc9f685b | ||
|
|
545936b681 | ||
|
|
1a319f2191 | ||
|
|
5930441699 | ||
|
|
bbf4a983d7 | ||
|
|
cf93478f87 | ||
|
|
b3d0b38694 | ||
|
|
3ca4fd99b6 | ||
|
|
5c143c89bf | ||
|
|
d1c54c4e5d | ||
|
|
2ff2bfee8f | ||
|
|
2fb0f2c58c | ||
|
|
5795966909 | ||
|
|
334e7046e3 | ||
|
|
89f2a613ab | ||
|
|
2b1eabe992 | ||
|
|
47fb4879a4 | ||
|
|
e74889ec87 | ||
|
|
c9a5f106a4 | ||
|
|
918f5a68ee |
No files matched your search
+15
-12
@@ -37,7 +37,7 @@ jobs:
|
||||
include:
|
||||
- job_name: linux
|
||||
os: ubuntu-latest
|
||||
go: '~1.27.3'
|
||||
go: '~1.27.4'
|
||||
gotags: cmount
|
||||
build_flags: '-include "^linux/"'
|
||||
check: true
|
||||
@@ -48,14 +48,14 @@ jobs:
|
||||
|
||||
- job_name: linux_386
|
||||
os: ubuntu-latest
|
||||
go: '~1.27.3'
|
||||
go: '~1.27.4'
|
||||
goarch: 386
|
||||
gotags: cmount
|
||||
quicktest: true
|
||||
|
||||
- job_name: mac_amd64
|
||||
os: macos-latest
|
||||
go: '~1.27.3'
|
||||
go: '~1.27.4'
|
||||
gotags: 'cmount'
|
||||
build_flags: '-include "^darwin/amd64" -cgo'
|
||||
quicktest: true
|
||||
@@ -64,14 +64,14 @@ jobs:
|
||||
|
||||
- job_name: mac_arm64
|
||||
os: macos-latest
|
||||
go: '~1.27.3'
|
||||
go: '~1.27.4'
|
||||
gotags: 'cmount'
|
||||
build_flags: '-include "^darwin/arm64" -cgo -macos-arch arm64 -cgo-cflags=-I/usr/local/include -cgo-ldflags=-L/usr/local/lib'
|
||||
deploy: true
|
||||
|
||||
- job_name: windows
|
||||
os: windows-latest
|
||||
go: '~1.27.3'
|
||||
go: '~1.27.4'
|
||||
gotags: cmount
|
||||
cgo: '0'
|
||||
build_flags: '-include "^windows/"'
|
||||
@@ -81,14 +81,14 @@ jobs:
|
||||
|
||||
- job_name: other_os
|
||||
os: ubuntu-latest
|
||||
go: '~1.27.3'
|
||||
go: '~1.27.4'
|
||||
build_flags: '-exclude "^(windows/|darwin/|linux/)"'
|
||||
compile_all: true
|
||||
deploy: true
|
||||
|
||||
- job_name: go1.26
|
||||
os: ubuntu-latest
|
||||
go: '~1.26.10'
|
||||
go: '~1.26.11'
|
||||
quicktest: true
|
||||
racequicktest: true
|
||||
|
||||
@@ -177,9 +177,12 @@ jobs:
|
||||
# https://github.com/Homebrew/brew/issues/15621#issuecomment-1619266788
|
||||
# https://github.com/orgs/Homebrew/discussions/4612#discussioncomment-6319008
|
||||
unset HOMEBREW_NO_INSTALL_FROM_API
|
||||
brew untap --force homebrew/core
|
||||
brew untap --force homebrew/cask
|
||||
brew untap --force aws/tap
|
||||
# brew untap fails if the tap isn't installed, which varies between runner images
|
||||
for tap in homebrew/core homebrew/cask aws/tap; do
|
||||
if brew tap | grep -qx "$tap"; then
|
||||
brew untap --force "$tap"
|
||||
fi
|
||||
done
|
||||
brew update
|
||||
brew install --cask macfuse
|
||||
brew install git-annex git-annex-remote-rclone
|
||||
@@ -284,7 +287,7 @@ jobs:
|
||||
id: setup-go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '~1.27.3'
|
||||
go-version: '~1.27.4'
|
||||
check-latest: true
|
||||
cache: false
|
||||
|
||||
@@ -399,7 +402,7 @@ jobs:
|
||||
id: setup-go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '~1.27.3'
|
||||
go-version: '~1.27.4'
|
||||
# Caching is handled explicitly below to share the module cache
|
||||
# with the other jobs - see the build job for the rationale.
|
||||
cache: false
|
||||
|
||||
@@ -19,5 +19,6 @@ Thumbs.db
|
||||
__pycache__
|
||||
.DS_Store
|
||||
resource_windows_*.syso
|
||||
/librclone.h
|
||||
.devcontainer
|
||||
/cmd/bisync/testdata/bisync_vscode_debuggers_launch.json
|
||||
Generated
+7688
-2672
File diff suppressed because it is too large.
Load diff
Generated
+5730
-1334
File diff suppressed because it is too large.
Load diff
@@ -285,7 +285,7 @@ endif
|
||||
|
||||
# Fetch the binary builds from GitHub actions
|
||||
fetch_binaries:
|
||||
rclone -P sync --exclude "/testbuilds/**" --delete-excluded $(BETA_UPLOAD) build/
|
||||
rclone -P sync --exclude "/testbuilds/**" --exclude "/index.{html,json}" --delete-excluded $(BETA_UPLOAD) build/
|
||||
|
||||
serve: website
|
||||
cd docs && hugo server --logLevel info -w --disableFastRender --ignoreCache
|
||||
|
||||
@@ -24,6 +24,7 @@ directories to and from different cloud storage providers.
|
||||
## Storage providers
|
||||
|
||||
- 1Fichier [:page_facing_up:](https://rclone.org/fichier/)
|
||||
- Abrha Storage [:page_facing_up:](https://rclone.org/s3/#abrhastorage)
|
||||
- Akamai Netstorage [:page_facing_up:](https://rclone.org/netstorage/)
|
||||
- Alibaba Cloud (Aliyun) Object Storage System (OSS) [:page_facing_up:](https://rclone.org/s3/#alibaba-oss)
|
||||
- Amazon S3 [:page_facing_up:](https://rclone.org/s3/)
|
||||
@@ -62,6 +63,7 @@ directories to and from different cloud storage providers.
|
||||
- Hetzner Object Storage [:page_facing_up:](https://rclone.org/s3/#hetzner)
|
||||
- Hetzner Storage Box [:page_facing_up:](https://rclone.org/sftp/#hetzner-storage-box)
|
||||
- HiDrive [:page_facing_up:](https://rclone.org/hidrive/)
|
||||
- Hippius [:page_facing_up:](https://rclone.org/s3/#hippius)
|
||||
- Hitachi Content Platform (HCP) [:page_facing_up:](https://rclone.org/s3/#hcp)
|
||||
- HTTP [:page_facing_up:](https://rclone.org/http/)
|
||||
- Huawei Cloud Object Storage Service(OBS) [:page_facing_up:](https://rclone.org/s3/#huawei-obs)
|
||||
@@ -73,6 +75,8 @@ directories to and from different cloud storage providers.
|
||||
- Jottacloud [:page_facing_up:](https://rclone.org/jottacloud/)
|
||||
- IBM COS S3 [:page_facing_up:](https://rclone.org/s3/#ibm-cos-s3)
|
||||
- Impossible Cloud [:page_facing_up:](https://rclone.org/s3/#impossible-cloud)
|
||||
- Infomaniak Swiss Backup (S3) [:page_facing_up:](https://rclone.org/s3/#infomaniak)
|
||||
- Infomaniak Swiss Backup (Swift) [:page_facing_up:](https://rclone.org/swift/)
|
||||
- Intercolo Object Storage [:page_facing_up:](https://rclone.org/s3/#intercolo)
|
||||
- IONOS Cloud [:page_facing_up:](https://rclone.org/s3/#ionos)
|
||||
- kDrive [:page_facing_up:](https://rclone.org/kdrive/)
|
||||
@@ -91,6 +95,7 @@ directories to and from different cloud storage providers.
|
||||
- Microsoft Azure Files Storage [:page_facing_up:](https://rclone.org/azurefiles/)
|
||||
- Microsoft OneDrive [:page_facing_up:](https://rclone.org/onedrive/)
|
||||
- Minio [:page_facing_up:](https://rclone.org/s3/#minio)
|
||||
- Neon Object Storage [:page_facing_up:](https://rclone.org/s3/#neon)
|
||||
- Nextcloud [:page_facing_up:](https://rclone.org/webdav/#nextcloud)
|
||||
- Blomp Cloud Storage [:page_facing_up:](https://rclone.org/swift/)
|
||||
- OpenDrive [:page_facing_up:](https://rclone.org/opendrive/)
|
||||
|
||||
+7
-3
@@ -32,10 +32,14 @@ This file describes how to make the various kinds of releases
|
||||
- git commit -a -v -m "Version v1.XX.0"
|
||||
- make check # if this fails, fix, git commit --amend and run it again
|
||||
- make retag # moves the tag onto the Version commit
|
||||
- git push origin # without --follow-tags so it doesn't push the tag if it fails
|
||||
- git push origin # without --follow-tags so it doesn't push the tag yet
|
||||
- Wait for the GitHub actions build of master to complete and check it is
|
||||
green - this is the first time CI sees any commits which were only local,
|
||||
such as security fixes, so it must pass before the tag is pushed
|
||||
- if it fails: fix, git commit, make retag, git push origin and wait again
|
||||
- git push --follow-tags origin
|
||||
- \# Wait for the GitHub builds to complete then...
|
||||
- \# Don't commit anything until after make upload_github as these steps
|
||||
- \# Wait for the GitHub builds of the tag to complete then...
|
||||
- \# Don't commit or push anything until after make upload_github as these steps
|
||||
use the tag on HEAD to find the version
|
||||
- make fetch_binaries
|
||||
- make tarball
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
package all_test
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/constant"
|
||||
"go/types"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
_ "github.com/rclone/rclone/backend/all"
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/tools/go/packages"
|
||||
)
|
||||
|
||||
// dynamicConfigKeys lists the config keys which are computed at
|
||||
// runtime so can't be checked statically, by package and expression.
|
||||
//
|
||||
// These are still checked at runtime by the config file setter.
|
||||
var dynamicConfigKeys = map[string]map[string]bool{
|
||||
"github.com/rclone/rclone/backend/sftp": {
|
||||
`fmt.Sprintf("%vsum_command", hashType)`: true,
|
||||
},
|
||||
}
|
||||
|
||||
// backendPackage returns the import path of the package which
|
||||
// registered ri.
|
||||
func backendPackage(ri *fs.RegInfo) string {
|
||||
name := runtime.FuncForPC(reflect.ValueOf(ri.NewFs).Pointer()).Name()
|
||||
// name is like "github.com/rclone/rclone/backend/drive.NewFs" or
|
||||
// "github.com/rclone/rclone/backend/drive.init.func1"
|
||||
slash := strings.LastIndex(name, "/")
|
||||
if dot := strings.Index(name[slash:], "."); dot >= 0 {
|
||||
name = name[:slash+dot]
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
// isConfigmapSetter returns true if t is a configmap type which
|
||||
// saves config (but not configmap.Simple which is just a map).
|
||||
func isConfigmapSetter(t types.Type) bool {
|
||||
if p, ok := t.(*types.Pointer); ok {
|
||||
t = p.Elem()
|
||||
}
|
||||
n, ok := t.(*types.Named)
|
||||
if !ok || n.Obj().Pkg() == nil {
|
||||
return false
|
||||
}
|
||||
return n.Obj().Pkg().Path() == "github.com/rclone/rclone/fs/config/configmap" && n.Obj().Name() != "Simple"
|
||||
}
|
||||
|
||||
// configKeyArg returns the argument holding the config key if call
|
||||
// saves config, or nil if it doesn't.
|
||||
func configKeyArg(info *types.Info, call *ast.CallExpr) (keyArg ast.Expr, isPutToken bool) {
|
||||
sel, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
switch sel.Sel.Name {
|
||||
case "Set":
|
||||
if tv, ok := info.Types[sel.X]; ok && len(call.Args) == 2 && isConfigmapSetter(tv.Type) {
|
||||
return call.Args[0], false
|
||||
}
|
||||
case "PutToken":
|
||||
if obj := info.Uses[sel.Sel]; obj != nil && obj.Pkg() != nil && obj.Pkg().Path() == "github.com/rclone/rclone/lib/oauthutil" {
|
||||
return nil, true
|
||||
}
|
||||
case "ConfigFileSet", "FileSetValue", "SetValueAndSave":
|
||||
if len(call.Args) == 3 {
|
||||
return call.Args[1], false
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// TestConfigKeysHaveOptions checks that every config key a backend
|
||||
// saves is one of its config options.
|
||||
//
|
||||
// Keys with no option aren't redacted by "rclone config redacted" and
|
||||
// can't be set with flags or environment variables.
|
||||
func TestConfigKeysHaveOptions(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping in short mode as it type checks all the backends")
|
||||
}
|
||||
|
||||
// Find the option names for each backend package
|
||||
options := map[string]map[string]bool{}
|
||||
for _, ri := range fs.Registry {
|
||||
pkg := backendPackage(ri)
|
||||
if options[pkg] == nil {
|
||||
options[pkg] = map[string]bool{}
|
||||
}
|
||||
for _, opt := range ri.Options {
|
||||
options[pkg][opt.Name] = true
|
||||
}
|
||||
}
|
||||
|
||||
cfg := &packages.Config{
|
||||
Mode: packages.NeedName | packages.NeedFiles | packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo,
|
||||
Dir: "../..",
|
||||
}
|
||||
pkgs, err := packages.Load(cfg, "./backend/...")
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, pkgs)
|
||||
|
||||
checked := 0
|
||||
for _, pkg := range pkgs {
|
||||
for _, e := range pkg.Errors {
|
||||
t.Errorf("%s: %v", pkg.PkgPath, e)
|
||||
}
|
||||
for _, file := range pkg.Syntax {
|
||||
ast.Inspect(file, func(n ast.Node) bool {
|
||||
call, ok := n.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
keyArg, isPutToken := configKeyArg(pkg.TypesInfo, call)
|
||||
var key string
|
||||
switch {
|
||||
case isPutToken:
|
||||
key = "token"
|
||||
case keyArg == nil:
|
||||
return true
|
||||
default:
|
||||
tv := pkg.TypesInfo.Types[keyArg]
|
||||
if tv.Value == nil || tv.Value.Kind() != constant.String {
|
||||
expr := types.ExprString(keyArg)
|
||||
assert.True(t, dynamicConfigKeys[pkg.PkgPath][expr], "%v: config key %s isn't a constant - add it to dynamicConfigKeys if this is intended", pkg.Fset.Position(call.Pos()), expr)
|
||||
return true
|
||||
}
|
||||
key = constant.StringVal(tv.Value)
|
||||
}
|
||||
checked++
|
||||
assert.True(t, options[pkg.PkgPath][key], "%v: config key %q has no config option in %s", pkg.Fset.Position(call.Pos()), key, pkg.PkgPath)
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
// Make sure the search is finding things
|
||||
assert.Greater(t, checked, 50)
|
||||
}
|
||||
@@ -91,6 +91,9 @@ func New(ctx context.Context, wrappedFs fs.Fs, remote, prefix, root string) (fs.
|
||||
WriteMimeType: false,
|
||||
BucketBased: false,
|
||||
CanHaveEmptyDirectories: true,
|
||||
// Open can't seek within an entry, so each chunk of a
|
||||
// multi-thread download would read the entry from the start
|
||||
NoMultiThreading: true,
|
||||
}).Fill(ctx, f).Mask(ctx, wrappedFs).WrapsFs(f, wrappedFs)
|
||||
|
||||
if singleObject {
|
||||
|
||||
@@ -79,7 +79,7 @@ This is required and is the name of the share to access.
|
||||
Help: `Upload chunk size.
|
||||
|
||||
Note that this is stored in memory and there may be up to
|
||||
"--transfers" * "--azurefile-upload-concurrency" chunks stored at once
|
||||
"--transfers" * "--azurefiles-upload-concurrency" chunks stored at once
|
||||
in memory.`,
|
||||
Default: defaultChunkSize,
|
||||
Advanced: true,
|
||||
@@ -95,7 +95,7 @@ links and these uploads do not fully utilize your bandwidth, then
|
||||
increasing this may help to speed up the transfers.
|
||||
|
||||
Note that chunks are stored in memory and there may be up to
|
||||
"--transfers" * "--azurefile-upload-concurrency" chunks stored at once
|
||||
"--transfers" * "--azurefiles-upload-concurrency" chunks stored at once
|
||||
in memory.`,
|
||||
Default: 16,
|
||||
Advanced: true,
|
||||
|
||||
+2
-2
@@ -277,7 +277,7 @@ See: [rclone backend lifecycle](#lifecycle) for setting lifecycles after bucket
|
||||
Name: "sse_customer_key",
|
||||
Help: `To use SSE-C, you may provide the secret encryption key encoded in a UTF-8 compatible string to encrypt/decrypt your data
|
||||
|
||||
Alternatively you can provide --sse-customer-key-base64.`,
|
||||
Alternatively you can provide --b2-sse-customer-key-base64.`,
|
||||
Advanced: true,
|
||||
Examples: []fs.OptionExample{{
|
||||
Value: "",
|
||||
@@ -288,7 +288,7 @@ Alternatively you can provide --sse-customer-key-base64.`,
|
||||
Name: "sse_customer_key_base64",
|
||||
Help: `To use SSE-C, you may provide the secret encryption key encoded in Base64 format to encrypt/decrypt your data
|
||||
|
||||
Alternatively you can provide --sse-customer-key.`,
|
||||
Alternatively you can provide --b2-sse-customer-key.`,
|
||||
Advanced: true,
|
||||
Examples: []fs.OptionExample{{
|
||||
Value: "",
|
||||
|
||||
@@ -44,6 +44,8 @@ const (
|
||||
heuristicBytes = 1048576
|
||||
minCompressionRatio = 1.1
|
||||
|
||||
defaultCompressionLevel = sgzip.DefaultCompression
|
||||
|
||||
gzFileExt = ".gz"
|
||||
zstdFileExt = ".zst"
|
||||
metaFileExt = ".json"
|
||||
@@ -107,8 +109,11 @@ ZSTD (levels 0 to 4):
|
||||
|
||||
Notes:
|
||||
- Choose GZIP for wide compatibility; ZSTD for better speed/ratio tradeoffs.
|
||||
- Negative gzip levels: -2 = Huffman-only, -1 = default (≈ level 5).`,
|
||||
Required: true,
|
||||
- Negative gzip levels: -2 = Huffman-only, -1 = default (≈ level 5).
|
||||
- The default level is -1 which selects the default level of the
|
||||
compression mode, equivalent to level 5 for gzip and level 2 for zstd.`,
|
||||
Default: defaultCompressionLevel,
|
||||
Advanced: true,
|
||||
}, {
|
||||
Name: "ram_cache_limit",
|
||||
Help: `Some remotes don't allow the upload of files with unknown size.
|
||||
@@ -225,9 +230,17 @@ func NewFs(ctx context.Context, name, rpath string, m configmap.Mapper) (fs.Fs,
|
||||
|
||||
switch compressionMode {
|
||||
case Gzip:
|
||||
if err := validateGzipLevel(opt.CompressionLevel); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
modeHandler = &gzipModeHandler{}
|
||||
case Zstd:
|
||||
modeHandler = &zstdModeHandler{}
|
||||
level, err := resolveZstdLevel(opt.CompressionLevel)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
opt.CompressionLevel = level
|
||||
modeHandler = &zstdModeHandler{level: level}
|
||||
case Uncompressed:
|
||||
modeHandler = &uncompressedModeHandler{}
|
||||
default:
|
||||
|
||||
@@ -2,16 +2,27 @@
|
||||
package compress
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/buengese/sgzip"
|
||||
"github.com/klauspost/compress/zstd"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
_ "github.com/rclone/rclone/backend/drive"
|
||||
_ "github.com/rclone/rclone/backend/local"
|
||||
_ "github.com/rclone/rclone/backend/s3"
|
||||
_ "github.com/rclone/rclone/backend/swift"
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/config/configmap"
|
||||
"github.com/rclone/rclone/fs/object"
|
||||
"github.com/rclone/rclone/fstest"
|
||||
"github.com/rclone/rclone/fstest/fstests"
|
||||
)
|
||||
@@ -138,7 +149,6 @@ func TestRemoteGzip(t *testing.T) {
|
||||
{Name: name, Key: "type", Value: "compress"},
|
||||
{Name: name, Key: "remote", Value: tempdir},
|
||||
{Name: name, Key: "mode", Value: "gzip"},
|
||||
{Name: name, Key: "level", Value: "-1"},
|
||||
}
|
||||
opt.QuickTestOK = true
|
||||
fstests.Run(t, &opt)
|
||||
@@ -157,8 +167,111 @@ func TestRemoteZstd(t *testing.T) {
|
||||
{Name: name, Key: "type", Value: "compress"},
|
||||
{Name: name, Key: "remote", Value: tempdir},
|
||||
{Name: name, Key: "mode", Value: "zstd"},
|
||||
{Name: name, Key: "level", Value: "2"},
|
||||
}
|
||||
opt.QuickTestOK = true
|
||||
fstests.Run(t, &opt)
|
||||
}
|
||||
|
||||
// newTestCompressFs makes a compress Fs wrapping an in-memory remote.
|
||||
func newTestCompressFs(t *testing.T, name, mode, level string) (*Fs, error) {
|
||||
info, err := fs.Find("compress")
|
||||
require.NoError(t, err)
|
||||
config := configmap.Simple{
|
||||
"remote": ":memory:" + name,
|
||||
"mode": mode,
|
||||
}
|
||||
if level != "" {
|
||||
config["level"] = level
|
||||
}
|
||||
m := fs.ConfigMap("", info.Options, "", config)
|
||||
f, err := NewFs(context.Background(), "compress", "", m)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return f.(*Fs), nil
|
||||
}
|
||||
|
||||
// TestCompressionLevel checks that the default level is applied for
|
||||
// both modes and that levels outside the supported range are rejected.
|
||||
func TestCompressionLevel(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mode string
|
||||
level string
|
||||
want int
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "gzip default", mode: "gzip", want: sgzip.DefaultCompression},
|
||||
{name: "zstd default", mode: "zstd", want: defaultZstdLevel},
|
||||
{name: "zstd off", mode: "zstd", level: "0", want: 0},
|
||||
{name: "zstd fastest", mode: "zstd", level: "1", want: int(zstd.SpeedFastest)},
|
||||
{name: "zstd best", mode: "zstd", level: "4", want: int(zstd.SpeedBestCompression)},
|
||||
{name: "zstd too high", mode: "zstd", level: "5", wantErr: true},
|
||||
{name: "zstd negative", mode: "zstd", level: "-2", wantErr: true},
|
||||
{name: "gzip too high", mode: "gzip", level: "10", wantErr: true},
|
||||
{name: "gzip too low", mode: "gzip", level: "-3", wantErr: true},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
f, err := newTestCompressFs(t, strings.ReplaceAll(test.name, " ", "-"), test.mode, test.level)
|
||||
if test.wantErr {
|
||||
require.Error(t, err)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, test.want, f.opt.CompressionLevel)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// putAndRead puts data through a compress Fs and reads it back,
|
||||
// returning the stored data object.
|
||||
func putAndRead(t *testing.T, f *Fs, content []byte) *Object {
|
||||
ctx := context.Background()
|
||||
src := object.NewStaticObjectInfo("file.txt", time.Now(), int64(len(content)), true, nil, f)
|
||||
o, err := f.Put(ctx, bytes.NewReader(content), src)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(len(content)), o.Size())
|
||||
|
||||
newO, err := f.NewObject(ctx, "file.txt")
|
||||
require.NoError(t, err)
|
||||
rc, err := newO.Open(ctx)
|
||||
require.NoError(t, err)
|
||||
got, err := io.ReadAll(rc)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, rc.Close())
|
||||
assert.Equal(t, content, got)
|
||||
return o.(*Object)
|
||||
}
|
||||
|
||||
// TestDefaultLevelCompresses checks that leaving the level unset still
|
||||
// compresses data with both modes.
|
||||
func TestDefaultLevelCompresses(t *testing.T) {
|
||||
content := bytes.Repeat([]byte("the quick brown fox jumps over the lazy dog "), 200)
|
||||
for _, test := range []struct {
|
||||
mode string
|
||||
suffix string
|
||||
}{
|
||||
{mode: "gzip", suffix: gzFileExt},
|
||||
{mode: "zstd", suffix: zstdFileExt},
|
||||
} {
|
||||
t.Run(test.mode, func(t *testing.T) {
|
||||
f, err := newTestCompressFs(t, "default-level-"+test.mode, test.mode, "")
|
||||
require.NoError(t, err)
|
||||
o := putAndRead(t, f, content)
|
||||
assert.Less(t, o.Object.Size(), int64(len(content)))
|
||||
assert.True(t, strings.HasSuffix(o.Object.Remote(), test.suffix), o.Object.Remote())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestZstdLevelOff checks that level 0 stores the file uncompressed.
|
||||
func TestZstdLevelOff(t *testing.T) {
|
||||
content := bytes.Repeat([]byte("the quick brown fox jumps over the lazy dog "), 200)
|
||||
f, err := newTestCompressFs(t, "zstd-level-off", "zstd", "0")
|
||||
require.NoError(t, err)
|
||||
o := putAndRead(t, f, content)
|
||||
assert.Equal(t, Uncompressed, o.meta.Mode)
|
||||
assert.Equal(t, int64(len(content)), o.Object.Size())
|
||||
assert.True(t, strings.HasSuffix(o.Object.Remote(), uncompressedFileExt), o.Object.Remote())
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/buengese/sgzip"
|
||||
@@ -16,6 +17,15 @@ import (
|
||||
"github.com/rclone/rclone/fs/hash"
|
||||
)
|
||||
|
||||
// validateGzipLevel checks the compression level is in the range
|
||||
// supported by sgzip.
|
||||
func validateGzipLevel(level int) error {
|
||||
if level < sgzip.ConstantCompression || level > sgzip.BestCompression {
|
||||
return fmt.Errorf("invalid gzip compression level %d: must be between %d and %d", level, sgzip.ConstantCompression, sgzip.BestCompression)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// gzipModeHandler implements compressionModeHandler for gzip
|
||||
type gzipModeHandler struct{}
|
||||
|
||||
@@ -107,10 +117,11 @@ func (g *gzipModeHandler) putCompress(
|
||||
// Compress the file
|
||||
pipeReader, pipeWriter := io.Pipe()
|
||||
|
||||
resultsGzip := make(chan compressionResult[sgzip.GzipMetadata])
|
||||
resultsGzip := make(chan compressionResult[sgzip.GzipMetadata], 1)
|
||||
go func() {
|
||||
gz, err := sgzip.NewWriterLevel(pipeWriter, f.opt.CompressionLevel)
|
||||
if err != nil {
|
||||
_ = pipeWriter.CloseWithError(err)
|
||||
resultsGzip <- compressionResult[sgzip.GzipMetadata]{err: err, meta: sgzip.GzipMetadata{}}
|
||||
close(resultsGzip)
|
||||
return
|
||||
@@ -150,6 +161,9 @@ func (g *gzipModeHandler) putCompress(
|
||||
// Transfer the data
|
||||
o, err := f.rcat(ctx, makeDataName(src.Remote(), src.Size(), f.mode), io.NopCloser(wrappedIn), src.ModTime(ctx), options)
|
||||
if err != nil {
|
||||
// Close the pipe reader so the compression goroutine doesn't
|
||||
// block writing to it.
|
||||
_ = pipeReader.CloseWithError(err)
|
||||
if o != nil {
|
||||
if removeErr := o.Remove(ctx); removeErr != nil {
|
||||
fs.Errorf(o, "Failed to remove partially transferred object: %v", removeErr)
|
||||
|
||||
@@ -123,7 +123,7 @@ func TestIsCompressible(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
for name, handler := range map[string]compressionModeHandler{
|
||||
"gzip": &gzipModeHandler{},
|
||||
"zstd": &zstdModeHandler{},
|
||||
"zstd": &zstdModeHandler{level: defaultZstdLevel},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
ok, err := handler.isCompressible(bytes.NewReader(compressible), 0)
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/klauspost/compress/zstd"
|
||||
@@ -16,12 +17,39 @@ import (
|
||||
"github.com/rclone/rclone/fs/hash"
|
||||
)
|
||||
|
||||
const (
|
||||
// defaultZstdLevel is used when the level option is left at its
|
||||
// default of -1, which only has a meaning for gzip.
|
||||
defaultZstdLevel = int(zstd.SpeedDefault)
|
||||
minZstdLevel = 0
|
||||
maxZstdLevel = int(zstd.SpeedBestCompression)
|
||||
)
|
||||
|
||||
// resolveZstdLevel converts the compression level from the shared level
|
||||
// option into a zstd level. The option defaults to -1 which means the
|
||||
// default level for the selected compression mode. Level 0 disables
|
||||
// compression entirely.
|
||||
func resolveZstdLevel(level int) (int, error) {
|
||||
if level == defaultCompressionLevel {
|
||||
return defaultZstdLevel, nil
|
||||
}
|
||||
if level < minZstdLevel || level > maxZstdLevel {
|
||||
return 0, fmt.Errorf("invalid zstd compression level %d: must be between %d and %d", level, minZstdLevel, maxZstdLevel)
|
||||
}
|
||||
return level, nil
|
||||
}
|
||||
|
||||
// zstdModeHandler implements compressionModeHandler for zstd
|
||||
type zstdModeHandler struct{}
|
||||
type zstdModeHandler struct {
|
||||
level int
|
||||
}
|
||||
|
||||
// isCompressible checks the compression ratio of the provided data and returns true if the ratio exceeds
|
||||
// the configured threshold
|
||||
func (z *zstdModeHandler) isCompressible(r io.Reader, compressionMode int) (bool, error) {
|
||||
if z.level == 0 {
|
||||
return false, nil
|
||||
}
|
||||
var b countingDiscard
|
||||
var n int64
|
||||
w, err := NewWriterSzstd(&b, zstd.WithEncoderLevel(zstd.SpeedDefault))
|
||||
@@ -107,10 +135,11 @@ func (z *zstdModeHandler) putCompress(
|
||||
// Compress the file
|
||||
pipeReader, pipeWriter := io.Pipe()
|
||||
|
||||
resultsZstd := make(chan compressionResult[SzstdMetadata])
|
||||
resultsZstd := make(chan compressionResult[SzstdMetadata], 1)
|
||||
go func() {
|
||||
writer, err := NewWriterSzstd(pipeWriter, zstd.WithEncoderLevel(zstd.EncoderLevel(f.opt.CompressionLevel)))
|
||||
writer, err := NewWriterSzstd(pipeWriter, zstd.WithEncoderLevel(zstd.EncoderLevel(z.level)))
|
||||
if err != nil {
|
||||
_ = pipeWriter.CloseWithError(err)
|
||||
resultsZstd <- compressionResult[SzstdMetadata]{err: err}
|
||||
close(resultsZstd)
|
||||
return
|
||||
@@ -144,6 +173,12 @@ func (z *zstdModeHandler) putCompress(
|
||||
|
||||
o, err := f.rcat(ctx, makeDataName(src.Remote(), src.Size(), f.mode), io.NopCloser(wrappedIn), src.ModTime(ctx), options)
|
||||
if err != nil {
|
||||
// Close the pipe reader so the compression goroutine doesn't
|
||||
// block writing to it.
|
||||
_ = pipeReader.CloseWithError(err)
|
||||
if o != nil {
|
||||
_ = o.Remove(ctx)
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
|
||||
@@ -568,7 +568,7 @@ recommended usage is using the flag form --drive-size-as-quota when
|
||||
doing rclone ls/lsl/lsf/lsjson/etc only.
|
||||
|
||||
If you do use this flag for syncing (not recommended) then you will
|
||||
need to use --ignore size also.`,
|
||||
need to use --ignore-size also.`,
|
||||
Advanced: true,
|
||||
Hide: fs.OptionHideConfigurator,
|
||||
}, {
|
||||
@@ -3908,6 +3908,10 @@ It copies the drive file with ID given to the path (an rclone path which
|
||||
will be passed internally to rclone copyto). The ID and path pairs can be
|
||||
repeated.
|
||||
|
||||
A path without a remote name, such as dir/file.txt, is a local path, so the
|
||||
file is copied to the local disk. To copy within the drive, include the
|
||||
remote, as in drive:dir/file.txt.
|
||||
|
||||
The path should end with a / to indicate copy the file as named to
|
||||
this directory. If it doesn't end with a / then the last path
|
||||
component will be used as the file name.
|
||||
@@ -3932,6 +3936,10 @@ rclone backend moveid drive: ID1 path1 ID2 path2
|
||||
It moves the drive file with ID given to the path (an rclone path which
|
||||
will be passed internally to rclone moveto).
|
||||
|
||||
A path without a remote name, such as dir/file.txt, is a local path, so the
|
||||
file is moved to the local disk and removed from the drive. To move within
|
||||
the drive, include the remote, as in drive:dir/file.txt.
|
||||
|
||||
The path should end with a / to indicate move the file as named to
|
||||
this directory. If it doesn't end with a / then the last path
|
||||
component will be used as the file name.
|
||||
|
||||
@@ -67,76 +67,21 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
|
||||
|
||||
o.size = size
|
||||
|
||||
// Offset and Count for range download
|
||||
var offset int64
|
||||
var count int64
|
||||
fs.FixRangeOption(options, o.size)
|
||||
for _, option := range options {
|
||||
switch x := option.(type) {
|
||||
case *fs.RangeOption:
|
||||
offset, count = x.Decode(o.size)
|
||||
if count < 0 {
|
||||
count = o.size - offset
|
||||
}
|
||||
case *fs.SeekOption:
|
||||
offset = x.Offset
|
||||
count = o.size
|
||||
default:
|
||||
if option.Mandatory() {
|
||||
fs.Logf(o, "Unsupported mandatory option: %v", option)
|
||||
}
|
||||
}
|
||||
opts := rest.Opts{
|
||||
Method: "GET",
|
||||
RootURL: directLink,
|
||||
Options: options,
|
||||
}
|
||||
|
||||
// Wrap the response body to handle offset and count
|
||||
var reader io.ReadCloser
|
||||
var resp *http.Response
|
||||
err = o.fs.pacer.Call(func() (bool, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", directLink, nil)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("failed to create download request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := o.fs.client.Do(req)
|
||||
if err != nil {
|
||||
return shouldRetry(err), fmt.Errorf("failed to download file: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
defer func() {
|
||||
if err := resp.Body.Close(); err != nil {
|
||||
fs.Logf(nil, "Failed to close response body: %v", err)
|
||||
}
|
||||
}()
|
||||
return false, fmt.Errorf("failed to download file: HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
if offset > 0 {
|
||||
_, err = io.CopyN(io.Discard, resp.Body, offset)
|
||||
if err != nil {
|
||||
_ = resp.Body.Close()
|
||||
return false, fmt.Errorf("failed to skip offset: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if count > 0 {
|
||||
reader = struct {
|
||||
io.Reader
|
||||
io.Closer
|
||||
}{
|
||||
Reader: io.LimitReader(resp.Body, count),
|
||||
Closer: resp.Body,
|
||||
}
|
||||
} else {
|
||||
reader = resp.Body
|
||||
}
|
||||
|
||||
return false, nil
|
||||
resp, err = o.fs.srv.Call(ctx, &opts)
|
||||
return shouldRetry(err), err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("failed to download file: %w", err)
|
||||
}
|
||||
|
||||
return reader, nil
|
||||
return resp.Body, nil
|
||||
}
|
||||
|
||||
// Update updates the object with new data
|
||||
|
||||
+95
-9
@@ -34,6 +34,7 @@ func init() {
|
||||
Name: "filen",
|
||||
Description: "Filen",
|
||||
NewFs: NewFs,
|
||||
Config: Config,
|
||||
Options: []fs.Option{
|
||||
{
|
||||
Name: "email",
|
||||
@@ -51,11 +52,14 @@ func init() {
|
||||
Name: "api_key",
|
||||
Help: `API Key for your Filen account
|
||||
|
||||
Get this using the Filen CLI export-api-key command
|
||||
Leave blank normally. Rclone fetches this when it logs in to your
|
||||
account and saves it in the config file.
|
||||
|
||||
If you need to set it yourself, get it using the Filen CLI export-api-key command
|
||||
You can download the Filen CLI from https://github.com/FilenCloudDienste/filen-cli`,
|
||||
Required: true,
|
||||
IsPassword: true,
|
||||
Sensitive: true,
|
||||
Advanced: true,
|
||||
},
|
||||
{
|
||||
Name: "upload_concurrency",
|
||||
@@ -105,6 +109,75 @@ this may help to speed up the transfers.`,
|
||||
})
|
||||
}
|
||||
|
||||
// internalPassword is the password which marks a config as holding
|
||||
// the account keys directly rather than deriving them from a password
|
||||
const internalPassword = "INTERNAL"
|
||||
|
||||
// noTwoFactorCode is the code the Filen API expects from accounts
|
||||
// which don't have two-factor authentication enabled
|
||||
const noTwoFactorCode = "XXXXXX"
|
||||
|
||||
// Config logs in to Filen and saves the API key in the config
|
||||
//
|
||||
// It does nothing if the config already has an API key or has no
|
||||
// email and password to log in with.
|
||||
func Config(ctx context.Context, name string, m configmap.Mapper, configIn fs.ConfigIn) (*fs.ConfigOut, error) {
|
||||
email, _ := m.Get("email")
|
||||
password, err := revealOption(m, "password")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch configIn.State {
|
||||
case "":
|
||||
apiKey, err := revealOption(m, "api_key")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if apiKey != "" || email == "" || password == "" || password == internalPassword {
|
||||
return nil, nil
|
||||
}
|
||||
return fs.ConfigInputOptional("login", "config_2fa", `Two-factor authentication code
|
||||
|
||||
Leave blank if two-factor authentication is not enabled on your account.`)
|
||||
case "login":
|
||||
_, err := login(ctx, email, password, configIn.Result, m)
|
||||
return nil, err
|
||||
}
|
||||
return nil, fmt.Errorf("unknown state %q", configIn.State)
|
||||
}
|
||||
|
||||
// revealOption returns the unobscured value of the config option key
|
||||
//
|
||||
// It returns "" if the option is unset.
|
||||
func revealOption(m configmap.Getter, key string) (string, error) {
|
||||
value, _ := m.Get(key)
|
||||
if value == "" {
|
||||
return "", nil
|
||||
}
|
||||
value, err := obscure.Reveal(value)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to reveal %s: %w", key, err)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// login logs in to Filen and saves the API key in m
|
||||
//
|
||||
// twoFactorCode should be empty for accounts which don't have
|
||||
// two-factor authentication enabled.
|
||||
func login(ctx context.Context, email, password, twoFactorCode string, m configmap.Mapper) (*sdk.Filen, error) {
|
||||
if twoFactorCode == "" {
|
||||
twoFactorCode = noTwoFactorCode
|
||||
}
|
||||
filen, err := sdk.New(ctx, email, password, twoFactorCode)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("login failed: %w", err)
|
||||
}
|
||||
m.Set("api_key", obscure.MustObscure(filen.Client.APIKey))
|
||||
return filen, nil
|
||||
}
|
||||
|
||||
// NewFs constructs a Fs at the path root
|
||||
func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {
|
||||
opt := new(Options)
|
||||
@@ -118,13 +191,16 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to reveal password: %w", err)
|
||||
}
|
||||
apiKey, err := obscure.Reveal(opt.APIKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to reveal api key: %w", err)
|
||||
apiKey := opt.APIKey
|
||||
if apiKey != "" {
|
||||
apiKey, err = obscure.Reveal(apiKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to reveal api key: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
var filen *sdk.Filen
|
||||
if password == "INTERNAL" {
|
||||
if password == internalPassword {
|
||||
tsconfig := sdk.TSConfig{
|
||||
Email: opt.Email,
|
||||
MasterKeys: strings.Split(opt.MasterKeys, "|"),
|
||||
@@ -138,6 +214,13 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else if apiKey == "" {
|
||||
// Logins are rate limited so save the API key to avoid
|
||||
// logging in again on the next run.
|
||||
filen, err = login(ctx, opt.Email, password, "", m)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w - if two-factor authentication is enabled run \"rclone config reconnect %s:\"", err, name)
|
||||
}
|
||||
} else {
|
||||
filen, err = sdk.NewWithAPIKey(ctx, opt.Email, password, apiKey)
|
||||
if err != nil {
|
||||
@@ -171,6 +254,7 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
|
||||
WriteMimeType: true,
|
||||
CanHaveEmptyDirectories: true,
|
||||
ChunkWriterDoesntSeek: true,
|
||||
CaseInsensitive: true,
|
||||
}).Fill(ctx, fileSystem)
|
||||
|
||||
fileSystem.root = Directory{
|
||||
@@ -845,7 +929,7 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
||||
return nil, err
|
||||
}
|
||||
defer f.filen.Unlock()
|
||||
if oldParentPath == newParentPath {
|
||||
if sdk.NamesEqual(oldParentPath, newParentPath) {
|
||||
err = f.rename(ctx, obj.file, newPath, newName)
|
||||
} else if newName == oldName {
|
||||
err = f.move(ctx, obj.file, newPath, newParentPath)
|
||||
@@ -1020,7 +1104,9 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
|
||||
return fs.ErrorDirNotFound
|
||||
}
|
||||
|
||||
if dstDir != nil {
|
||||
// Filen names are case-insensitive, so for a case-only rename
|
||||
// the destination is found and is the source directory itself
|
||||
if dstDir != nil && dstDir.GetUUID() != srcDirInt.GetUUID() {
|
||||
return fs.ErrorDirExists
|
||||
}
|
||||
|
||||
@@ -1040,7 +1126,7 @@ func (f *Fs) dirMoveEntireDir(ctx context.Context, srcDir *types.Directory, oldP
|
||||
var err error
|
||||
if oldPath == newPath {
|
||||
return fs.ErrorDirExists
|
||||
} else if oldParentPath == newParentPath {
|
||||
} else if sdk.NamesEqual(oldParentPath, newParentPath) {
|
||||
err = f.rename(ctx, srcDir, newPath, newName)
|
||||
} else if newName == oldName {
|
||||
err = f.move(ctx, srcDir, newPath, newParentPath)
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package filen
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/config/configmap"
|
||||
"github.com/rclone/rclone/fs/config/obscure"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestConfig(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("AsksFor2FAWithoutAPIKey", func(t *testing.T) {
|
||||
m := configmap.Simple{
|
||||
"email": "user@example.com",
|
||||
"password": obscure.MustObscure("secret"),
|
||||
}
|
||||
out, err := Config(ctx, "test", m, fs.ConfigIn{})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, out)
|
||||
assert.Equal(t, "login", out.State)
|
||||
require.NotNil(t, out.Option)
|
||||
assert.Equal(t, "config_2fa", out.Option.Name)
|
||||
assert.False(t, out.Option.Required)
|
||||
})
|
||||
|
||||
t.Run("AsksFor2FAWithBlankedAPIKey", func(t *testing.T) {
|
||||
m := configmap.Simple{
|
||||
"email": "user@example.com",
|
||||
"password": obscure.MustObscure("secret"),
|
||||
"api_key": obscure.MustObscure(""),
|
||||
}
|
||||
out, err := Config(ctx, "test", m, fs.ConfigIn{})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, out)
|
||||
assert.Equal(t, "login", out.State)
|
||||
})
|
||||
|
||||
t.Run("DoneWithoutCredentials", func(t *testing.T) {
|
||||
for _, m := range []configmap.Simple{
|
||||
{},
|
||||
{"email": "user@example.com"},
|
||||
{"password": obscure.MustObscure("secret")},
|
||||
} {
|
||||
out, err := Config(ctx, "test", m, fs.ConfigIn{})
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, out)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("DoneWithAPIKey", func(t *testing.T) {
|
||||
m := configmap.Simple{
|
||||
"email": "user@example.com",
|
||||
"password": obscure.MustObscure("secret"),
|
||||
"api_key": obscure.MustObscure("key"),
|
||||
}
|
||||
out, err := Config(ctx, "test", m, fs.ConfigIn{})
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, out)
|
||||
})
|
||||
|
||||
t.Run("DoneWithInternalPassword", func(t *testing.T) {
|
||||
m := configmap.Simple{
|
||||
"email": "user@example.com",
|
||||
"password": obscure.MustObscure("INTERNAL"),
|
||||
}
|
||||
out, err := Config(ctx, "test", m, fs.ConfigIn{})
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, out)
|
||||
})
|
||||
|
||||
t.Run("UnknownState", func(t *testing.T) {
|
||||
_, err := Config(ctx, "test", configmap.Simple{}, fs.ConfigIn{State: "bogus"})
|
||||
assert.ErrorContains(t, err, `unknown state "bogus"`)
|
||||
})
|
||||
}
|
||||
@@ -133,6 +133,25 @@ So for |concurrency 3| you'd use |--checkers 2 --transfers 2
|
||||
Help: "Use LIST -a to force listing of hidden files and folders. This will disable the use of MLSD.",
|
||||
Default: false,
|
||||
Advanced: true,
|
||||
}, {
|
||||
Name: "trust_pasv_ip",
|
||||
Help: `Trust the IP address in the server's PASV reply.
|
||||
|
||||
By default rclone ignores the IP address in the PASV reply and
|
||||
makes the data connection to the same host as the control
|
||||
connection. Enable this option to trust the IP address in the
|
||||
PASV reply instead, which is needed for servers whose PASV reply
|
||||
legitimately points at a different host than the control
|
||||
connection.
|
||||
|
||||
The default is false to prevent a malicious server making direct
|
||||
connections to other hosts on your network.
|
||||
|
||||
Try this option if transfers hang or fail with connection-refused
|
||||
errors after upgrading to >= v1.76.0.
|
||||
`,
|
||||
Default: false,
|
||||
Advanced: true,
|
||||
}, {
|
||||
Name: "idle_timeout",
|
||||
Default: fs.Duration(60 * time.Second),
|
||||
@@ -268,6 +287,7 @@ type Options struct {
|
||||
DisableUTF8 bool `config:"disable_utf8"`
|
||||
WritingMDTM bool `config:"writing_mdtm"`
|
||||
ForceListHidden bool `config:"force_list_hidden"`
|
||||
TrustPasvIP bool `config:"trust_pasv_ip"`
|
||||
IdleTimeout fs.Duration `config:"idle_timeout"`
|
||||
CloseTimeout fs.Duration `config:"close_timeout"`
|
||||
ShutTimeout fs.Duration `config:"shut_timeout"`
|
||||
@@ -522,6 +542,9 @@ func (f *Fs) ftpConnection(ctx context.Context) (c *ftp.ServerConn, err error) {
|
||||
if f.opt.DisableEPSV {
|
||||
ftpConfig = append(ftpConfig, ftp.DialWithDisabledEPSV(true))
|
||||
}
|
||||
if f.opt.TrustPasvIP {
|
||||
ftpConfig = append(ftpConfig, ftp.DialWithTrustPasvIP(true))
|
||||
}
|
||||
if f.opt.DisableMLSD {
|
||||
ftpConfig = append(ftpConfig, ftp.DialWithDisabledMLSD(true))
|
||||
}
|
||||
|
||||
@@ -63,7 +63,8 @@ The headers are only sent to the host in the configured URL. If the
|
||||
server redirects to another host (including a subdomain or a different
|
||||
port) the headers are not sent to it, or to any further hop in that
|
||||
redirect chain. When headers are set, a redirect from https to http is
|
||||
refused as it would send them in cleartext.`,
|
||||
refused as it would send them in cleartext, even with
|
||||
--allow-https-downgrade.`,
|
||||
Default: fs.CommaSepList{},
|
||||
Advanced: true,
|
||||
}, {
|
||||
@@ -315,8 +316,9 @@ func (f *Fs) httpConnection(ctx context.Context, opt *Options) (isFile bool, err
|
||||
}
|
||||
|
||||
client := fshttp.NewClient(ctx)
|
||||
// Without configured headers keep the default policy which
|
||||
// public mirrors that redirect from https to http rely on.
|
||||
// Without configured headers keep the default policy so
|
||||
// --allow-https-downgrade can follow public mirrors that
|
||||
// redirect from https to http.
|
||||
if len(opt.Headers) > 0 {
|
||||
client.CheckRedirect = checkRedirect(opt)
|
||||
}
|
||||
|
||||
@@ -688,7 +688,7 @@ func TestRedirectRefusesHTTPSDowngrade(t *testing.T) {
|
||||
|
||||
// open makes a remote pointing at ts with or without headers
|
||||
// and opens file.txt on it
|
||||
open := func(t *testing.T, withHeaders bool) (io.ReadCloser, error) {
|
||||
open := func(t *testing.T, withHeaders, allowDowngrade bool) (io.ReadCloser, error) {
|
||||
configfile.Install()
|
||||
m := configmap.Simple{
|
||||
"type": "http",
|
||||
@@ -700,6 +700,7 @@ func TestRedirectRefusesHTTPSDowngrade(t *testing.T) {
|
||||
}
|
||||
ctx, ci := fs.AddConfig(context.Background())
|
||||
ci.InsecureSkipVerify = true
|
||||
ci.AllowHTTPSDowngrade = allowDowngrade
|
||||
f, err := NewFs(ctx, remoteName, "", m)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -711,13 +712,25 @@ func TestRedirectRefusesHTTPSDowngrade(t *testing.T) {
|
||||
|
||||
t.Run("WithHeaders", func(t *testing.T) {
|
||||
// Headers could leak so the downgrade must be refused
|
||||
_, err := open(t, true)
|
||||
_, err := open(t, true, false)
|
||||
require.ErrorIs(t, err, rest.ErrHTTPSDowngrade)
|
||||
})
|
||||
|
||||
t.Run("WithHeadersAllowDowngrade", func(t *testing.T) {
|
||||
// Headers could leak so the downgrade is refused even when allowed
|
||||
_, err := open(t, true, true)
|
||||
require.ErrorIs(t, err, rest.ErrHTTPSDowngrade)
|
||||
})
|
||||
|
||||
t.Run("WithoutHeaders", func(t *testing.T) {
|
||||
// Nothing to leak so the downgrade is followed
|
||||
fd, err := open(t, false)
|
||||
// The transport refuses downgrades by default
|
||||
_, err := open(t, false, false)
|
||||
require.ErrorIs(t, err, rest.ErrHTTPSDowngrade)
|
||||
})
|
||||
|
||||
t.Run("WithoutHeadersAllowDowngrade", func(t *testing.T) {
|
||||
// Nothing to leak so the downgrade is followed when allowed
|
||||
fd, err := open(t, false, true)
|
||||
require.NoError(t, err)
|
||||
data, err := io.ReadAll(fd)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -25,6 +25,15 @@ const (
|
||||
authEndpoint = "https://idmsa.apple.com/appleauth/auth"
|
||||
)
|
||||
|
||||
type endpoints struct{ base, setup, auth string }
|
||||
|
||||
func endpointsForDomain(domain string) endpoints {
|
||||
if strings.EqualFold(domain, "iCloud.com.cn") {
|
||||
return endpoints{"https://www.icloud.com.cn", "https://setup.icloud.com.cn/setup/ws/1", "https://idmsa.apple.com.cn/appleauth/auth"}
|
||||
}
|
||||
return endpoints{baseEndpoint, setupEndpoint, authEndpoint}
|
||||
}
|
||||
|
||||
// Webservice keys in AccountInfo.Webservices map
|
||||
const (
|
||||
WsDrive = "drivews"
|
||||
@@ -126,16 +135,16 @@ func (c *Client) Authenticate(ctx context.Context) error {
|
||||
func (c *Client) authenticateSession(ctx context.Context) error {
|
||||
// Skip /validate round-trip when saved session has cookies + service endpoints
|
||||
// Native client behavior: use cached session, reauth lazily on 401/421
|
||||
if c.Session.Cookies != nil && len(c.Session.AccountInfo.Webservices) > 0 {
|
||||
if len(c.Session.Cookies) > 0 && len(c.Session.AccountInfo.Webservices) > 0 {
|
||||
fs.Debugf(nil, "iclouddrive: reusing saved session")
|
||||
return nil
|
||||
}
|
||||
// Try loading cached service endpoints to avoid /validate round-trip (~5s)
|
||||
if c.Session.Cookies != nil && c.loadCachedWebservices() {
|
||||
if len(c.Session.Cookies) > 0 && c.loadCachedWebservices() {
|
||||
fs.Debugf(nil, "iclouddrive: reusing session with cached endpoints")
|
||||
return nil
|
||||
}
|
||||
if c.Session.Cookies != nil {
|
||||
if len(c.Session.Cookies) > 0 {
|
||||
if err := c.Session.ValidateSession(ctx); err == nil {
|
||||
fs.Debugf(nil, "iclouddrive: valid session, no need to reauth")
|
||||
c.saveCachedWebservices()
|
||||
@@ -145,24 +154,29 @@ func (c *Client) authenticateSession(ctx context.Context) error {
|
||||
}
|
||||
|
||||
fs.Debugf(nil, "iclouddrive: authenticating")
|
||||
err := c.Session.SignIn(ctx, c.appleID, c.password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// If 2FA is required, skip AuthWithToken - caller must complete 2FA first
|
||||
if c.Session.Requires2FA() {
|
||||
return nil
|
||||
}
|
||||
|
||||
err = c.Session.AuthWithToken(ctx)
|
||||
if err == nil {
|
||||
c.saveCachedWebservices()
|
||||
if c.sessionSaveCallback != nil {
|
||||
c.sessionSaveCallback(c.Session)
|
||||
for range 2 {
|
||||
if err := c.Session.SignIn(ctx, c.appleID, c.password); err != nil {
|
||||
return err
|
||||
}
|
||||
// The caller completes 2FA before accountLogin.
|
||||
if c.Session.Requires2FA() {
|
||||
return nil
|
||||
}
|
||||
err := c.Session.AuthWithToken(ctx)
|
||||
if err == nil {
|
||||
c.saveCachedWebservices()
|
||||
if c.sessionSaveCallback != nil {
|
||||
c.sessionSaveCallback(c.Session)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !errors.Is(err, ErrDomainChanged) {
|
||||
return err
|
||||
}
|
||||
c.Session.Cookies = nil
|
||||
c.Session.AccountInfo = AccountInfo{}
|
||||
}
|
||||
return err
|
||||
return errors.New("iCloud account domain changed repeatedly")
|
||||
}
|
||||
|
||||
// loadCachedWebservices loads service endpoints from disk cache
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
@@ -30,6 +31,7 @@ type Session struct {
|
||||
Scnt string `json:"scnt"`
|
||||
SessionID string `json:"session_id"`
|
||||
AccountCountry string `json:"account_country"`
|
||||
DomainToUse string `json:"domain_to_use,omitempty"`
|
||||
TrustToken string `json:"trust_token"`
|
||||
ClientID string `json:"client_id"`
|
||||
AuthAttributes string `json:"auth_attributes"`
|
||||
@@ -42,6 +44,18 @@ type Session struct {
|
||||
needs2FA bool `json:"-"` // set when SRP signin returns 409
|
||||
}
|
||||
|
||||
// SetDomainToUse selects the endpoints named by Apple's account login response.
|
||||
func (s *Session) SetDomainToUse(domain string) error {
|
||||
if !strings.EqualFold(domain, "iCloud.com.cn") {
|
||||
return fmt.Errorf("unsupported iCloud account domain %q", domain)
|
||||
}
|
||||
s.DomainToUse = "iCloud.com.cn"
|
||||
s.srv.SetRoot(s.endpoints().base)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Session) endpoints() endpoints { return endpointsForDomain(s.DomainToUse) }
|
||||
|
||||
// srpInitResponse is the server response from /auth/signin/init
|
||||
type srpInitResponse struct {
|
||||
Iteration int `json:"iteration"`
|
||||
@@ -220,6 +234,7 @@ func (s *Session) Requires2FA() bool {
|
||||
|
||||
// SignIn performs SRP-based authentication against Apple's idmsa endpoint
|
||||
func (s *Session) SignIn(ctx context.Context, appleID, password string) error {
|
||||
s.needs2FA = false
|
||||
// Step 1: Initialize the auth session
|
||||
if err := s.authStart(ctx); err != nil {
|
||||
return fmt.Errorf("authStart: %w", err)
|
||||
@@ -285,7 +300,7 @@ func (s *Session) authStart(ctx context.Context) error {
|
||||
params.Set("skVersion", "7")
|
||||
params.Set("iframeId", frameTag)
|
||||
params.Set("client_id", s.ClientID)
|
||||
params.Set("redirect_uri", "https://www.icloud.com")
|
||||
params.Set("redirect_uri", s.endpoints().base)
|
||||
params.Set("response_type", "code")
|
||||
params.Set("response_mode", "web_message")
|
||||
params.Set("state", frameTag)
|
||||
@@ -299,7 +314,7 @@ func (s *Session) authStart(ctx context.Context) error {
|
||||
"Accept": "*/*",
|
||||
"User-Agent": iCloudUserAgent,
|
||||
},
|
||||
RootURL: authEndpoint,
|
||||
RootURL: s.endpoints().auth,
|
||||
NoResponse: true,
|
||||
}
|
||||
|
||||
@@ -333,7 +348,7 @@ func (s *Session) authFederate(ctx context.Context, accountName string) error {
|
||||
Path: "/federate",
|
||||
Parameters: url.Values{"isRememberMeEnabled": {"true"}},
|
||||
ExtraHeaders: s.getSRPAuthHeaders(),
|
||||
RootURL: authEndpoint,
|
||||
RootURL: s.endpoints().auth,
|
||||
Body: body,
|
||||
NoResponse: true,
|
||||
}
|
||||
@@ -368,7 +383,7 @@ func (s *Session) authSRPInit(ctx context.Context, aBase64, accountName string)
|
||||
Method: "POST",
|
||||
Path: "/signin/init",
|
||||
ExtraHeaders: s.getSRPAuthHeaders(),
|
||||
RootURL: authEndpoint,
|
||||
RootURL: s.endpoints().auth,
|
||||
Body: body,
|
||||
}
|
||||
|
||||
@@ -408,7 +423,7 @@ func (s *Session) authSRPComplete(ctx context.Context, accountName, m1Base64, m2
|
||||
Path: "/signin/complete",
|
||||
Parameters: url.Values{"isRememberMeEnabled": {"true"}},
|
||||
ExtraHeaders: s.getSRPAuthHeaders(),
|
||||
RootURL: authEndpoint,
|
||||
RootURL: s.endpoints().auth,
|
||||
IgnoreStatus: true,
|
||||
Body: body,
|
||||
}
|
||||
@@ -417,7 +432,7 @@ func (s *Session) authSRPComplete(ctx context.Context, accountName, m1Base64, m2
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
|
||||
s.extractHeaders(resp)
|
||||
@@ -428,7 +443,7 @@ func (s *Session) authSRPComplete(ctx context.Context, accountName, m1Base64, m2
|
||||
return nil
|
||||
case http.StatusConflict:
|
||||
// 409 = 2FA required
|
||||
fs.Debugf(nil, "iclouddrive: SRP sign in requires 2FA, response: %s", respBody)
|
||||
fs.Debugf(nil, "iclouddrive: SRP sign in requires 2FA")
|
||||
s.needs2FA = true
|
||||
return nil
|
||||
case http.StatusPreconditionFailed:
|
||||
@@ -438,7 +453,7 @@ func (s *Session) authSRPComplete(ctx context.Context, accountName, m1Base64, m2
|
||||
case http.StatusForbidden:
|
||||
return fmt.Errorf("sign in failed: incorrect username or password")
|
||||
default:
|
||||
return fmt.Errorf("sign in failed: %s: %s", resp.Status, respBody)
|
||||
return fmt.Errorf("sign in failed: %s", resp.Status)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -452,7 +467,7 @@ func (s *Session) authRepairComplete(ctx context.Context) error {
|
||||
Method: "POST",
|
||||
Path: "/repair/complete",
|
||||
ExtraHeaders: s.getSRPAuthHeaders(),
|
||||
RootURL: authEndpoint,
|
||||
RootURL: s.endpoints().auth,
|
||||
IgnoreStatus: true,
|
||||
NoResponse: true,
|
||||
Body: body,
|
||||
@@ -471,14 +486,14 @@ func (s *Session) authRepairComplete(ctx context.Context) error {
|
||||
|
||||
// getAuthOrigin returns the origin URL for auth requests
|
||||
// Supports both global (idmsa.apple.com) and China (idmsa.apple.com.cn) endpoints
|
||||
func getAuthOrigin() string {
|
||||
return strings.TrimSuffix(authEndpoint, "/appleauth/auth")
|
||||
func (s *Session) getAuthOrigin() string {
|
||||
return strings.TrimSuffix(s.endpoints().auth, "/appleauth/auth")
|
||||
}
|
||||
|
||||
// getSRPAuthHeaders returns headers needed for SRP auth requests
|
||||
func (s *Session) getSRPAuthHeaders() map[string]string {
|
||||
frameTag := "auth-" + s.FrameID
|
||||
authOrigin := getAuthOrigin()
|
||||
authOrigin := s.getAuthOrigin()
|
||||
headers := map[string]string{
|
||||
"Accept": "application/json",
|
||||
"Content-Type": "application/json",
|
||||
@@ -488,7 +503,7 @@ func (s *Session) getSRPAuthHeaders() map[string]string {
|
||||
"X-Apple-Widget-Key": s.ClientID,
|
||||
"X-Apple-OAuth-Client-Id": s.ClientID,
|
||||
"X-Apple-OAuth-Client-Type": "firstPartyAuth",
|
||||
"X-Apple-OAuth-Redirect-URI": "https://www.icloud.com",
|
||||
"X-Apple-OAuth-Redirect-URI": s.endpoints().base,
|
||||
"X-Apple-OAuth-Require-Grant-Code": "true",
|
||||
"X-Apple-OAuth-Response-Mode": "web_message",
|
||||
"X-Apple-OAuth-Response-Type": "code",
|
||||
@@ -526,21 +541,38 @@ func (s *Session) AuthWithToken(ctx context.Context) error {
|
||||
opts := rest.Opts{
|
||||
Method: "POST",
|
||||
Path: "/accountLogin",
|
||||
ExtraHeaders: GetCommonHeaders(map[string]string{}),
|
||||
RootURL: setupEndpoint,
|
||||
ExtraHeaders: s.getCommonHeaders(nil),
|
||||
RootURL: s.endpoints().setup,
|
||||
IgnoreStatus: true,
|
||||
Body: body,
|
||||
}
|
||||
|
||||
resp, err := s.Request(ctx, opts, nil, &s.AccountInfo)
|
||||
var login struct {
|
||||
AccountInfo
|
||||
DomainToUse string `json:"domainToUse"`
|
||||
}
|
||||
resp, err := s.Request(ctx, opts, nil, &login)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fs.Debugf(nil, "iclouddrive: accountLogin response cookies: %v", cookieDebugSummaries(resp.Cookies()))
|
||||
fs.Debugf(nil, "iclouddrive: session cookie jar after accountLogin: %v", cookieJarDebugSummaries(s.Cookies))
|
||||
|
||||
return nil
|
||||
switch resp.StatusCode {
|
||||
case http.StatusOK:
|
||||
s.AccountInfo = login.AccountInfo
|
||||
fs.Debugf(nil, "iclouddrive: accountLogin response cookies: %v", cookieDebugSummaries(resp.Cookies()))
|
||||
fs.Debugf(nil, "iclouddrive: session cookie jar after accountLogin: %v", cookieJarDebugSummaries(s.Cookies))
|
||||
return nil
|
||||
case http.StatusFound:
|
||||
if err := s.SetDomainToUse(login.DomainToUse); err != nil {
|
||||
return err
|
||||
}
|
||||
return ErrDomainChanged
|
||||
default:
|
||||
return fmt.Errorf("accountLogin returned HTTP %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// ErrDomainChanged indicates that Apple requires authentication on another iCloud domain.
|
||||
var ErrDomainChanged = errors.New("iCloud account domain changed")
|
||||
|
||||
type pcsService struct {
|
||||
wsKey string
|
||||
appName string
|
||||
@@ -608,7 +640,7 @@ func (s *Session) acquirePCSCookiesFor(ctx context.Context, appName string, cook
|
||||
Method: "POST",
|
||||
Path: "/requestPCS",
|
||||
ExtraHeaders: s.GetHeaders(map[string]string{}),
|
||||
RootURL: setupEndpoint,
|
||||
RootURL: s.endpoints().setup,
|
||||
Body: body,
|
||||
}
|
||||
var pcsResp struct {
|
||||
@@ -651,7 +683,7 @@ func (s *Session) RequestPushNotification(ctx context.Context) error {
|
||||
Method: "PUT",
|
||||
Path: "/verify/trusteddevice/securitycode",
|
||||
ExtraHeaders: s.GetAuthHeaders(map[string]string{}),
|
||||
RootURL: authEndpoint,
|
||||
RootURL: s.endpoints().auth,
|
||||
NoResponse: true,
|
||||
}
|
||||
|
||||
@@ -671,7 +703,7 @@ func (s *Session) Validate2FACode(ctx context.Context, code string) error {
|
||||
Method: "POST",
|
||||
Path: "/verify/trusteddevice/securitycode",
|
||||
ExtraHeaders: s.GetAuthHeaders(map[string]string{}),
|
||||
RootURL: authEndpoint,
|
||||
RootURL: s.endpoints().auth,
|
||||
Body: body,
|
||||
NoResponse: true,
|
||||
}
|
||||
@@ -717,7 +749,7 @@ func (s *Session) GetAuthState(ctx context.Context) (*AuthStateResponse, error)
|
||||
Method: "GET",
|
||||
Path: "",
|
||||
ExtraHeaders: s.GetAuthHeaders(map[string]string{}),
|
||||
RootURL: authEndpoint,
|
||||
RootURL: s.endpoints().auth,
|
||||
ContentLength: new(int64(0)),
|
||||
}
|
||||
// Use srv.Call directly to capture the raw response body for debugging
|
||||
@@ -777,7 +809,7 @@ func (s *Session) RequestSMSCode(ctx context.Context, phoneID int, mode string)
|
||||
Method: "PUT",
|
||||
Path: "/verify/phone",
|
||||
ExtraHeaders: s.GetAuthHeaders(map[string]string{}),
|
||||
RootURL: authEndpoint,
|
||||
RootURL: s.endpoints().auth,
|
||||
Body: body,
|
||||
NoResponse: true,
|
||||
}
|
||||
@@ -803,7 +835,7 @@ func (s *Session) ValidateSMSCode(ctx context.Context, code string, phoneID int,
|
||||
Method: "POST",
|
||||
Path: "/verify/phone/securitycode",
|
||||
ExtraHeaders: s.GetAuthHeaders(map[string]string{}),
|
||||
RootURL: authEndpoint,
|
||||
RootURL: s.endpoints().auth,
|
||||
Body: body,
|
||||
NoResponse: true,
|
||||
}
|
||||
@@ -826,7 +858,7 @@ func (s *Session) TrustSession(ctx context.Context) error {
|
||||
Method: "GET",
|
||||
Path: "/2sv/trust",
|
||||
ExtraHeaders: s.GetAuthHeaders(map[string]string{}),
|
||||
RootURL: authEndpoint,
|
||||
RootURL: s.endpoints().auth,
|
||||
NoResponse: true,
|
||||
ContentLength: new(int64(0)),
|
||||
}
|
||||
@@ -845,7 +877,7 @@ func (s *Session) ValidateSession(ctx context.Context) error {
|
||||
Method: "POST",
|
||||
Path: "/validate",
|
||||
ExtraHeaders: s.GetHeaders(map[string]string{}),
|
||||
RootURL: setupEndpoint,
|
||||
RootURL: s.endpoints().setup,
|
||||
ContentLength: new(int64(0)),
|
||||
}
|
||||
_, err := s.Request(ctx, opts, nil, &s.AccountInfo)
|
||||
@@ -867,7 +899,7 @@ func (s *Session) GetAuthHeaders(overwrite map[string]string) map[string]string
|
||||
|
||||
// GetHeaders returns the authentication headers required for a request
|
||||
func (s *Session) GetHeaders(overwrite map[string]string) map[string]string {
|
||||
headers := GetCommonHeaders(map[string]string{})
|
||||
headers := s.getCommonHeaders(map[string]string{})
|
||||
headers["Cookie"] = s.GetCookieString()
|
||||
maps.Copy(headers, overwrite)
|
||||
return headers
|
||||
@@ -892,12 +924,12 @@ func (s *Session) GetCookieString() string {
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// GetCommonHeaders generates common HTTP headers with optional overwrite
|
||||
func GetCommonHeaders(overwrite map[string]string) map[string]string {
|
||||
// getCommonHeaders generates common HTTP headers with optional overwrite
|
||||
func (s *Session) getCommonHeaders(overwrite map[string]string) map[string]string {
|
||||
headers := map[string]string{
|
||||
"Content-Type": "application/json",
|
||||
"Origin": baseEndpoint,
|
||||
"Referer": fmt.Sprintf("%s/", baseEndpoint),
|
||||
"Origin": s.endpoints().base,
|
||||
"Referer": fmt.Sprintf("%s/", s.endpoints().base),
|
||||
"User-Agent": iCloudUserAgent,
|
||||
}
|
||||
maps.Copy(headers, overwrite)
|
||||
|
||||
@@ -1,13 +1,125 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/rclone/rclone/lib/rest"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) }
|
||||
|
||||
func TestAccountLoginDomainRedirect(t *testing.T) {
|
||||
var hosts, origins []string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "/setup/ws/1/accountLogin", r.URL.Path)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusFound)
|
||||
_, _ = w.Write([]byte(`{"domainToUse":"iCloud.com.cn"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
serverURL, err := url.Parse(server.URL)
|
||||
require.NoError(t, err)
|
||||
s := NewSession()
|
||||
s.srv = rest.NewClient(&http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
hosts = append(hosts, req.URL.Host)
|
||||
origins = append(origins, req.Header.Get("Origin"))
|
||||
copied := req.Clone(req.Context())
|
||||
copied.URL.Scheme = serverURL.Scheme
|
||||
copied.URL.Host = serverURL.Host
|
||||
return http.DefaultTransport.RoundTrip(copied)
|
||||
})})
|
||||
require.ErrorIs(t, s.AuthWithToken(context.Background()), ErrDomainChanged)
|
||||
assert.Equal(t, []string{"setup.icloud.com"}, hosts)
|
||||
assert.Equal(t, []string{"https://www.icloud.com"}, origins)
|
||||
assert.Equal(t, "iCloud.com.cn", s.DomainToUse)
|
||||
assert.Empty(t, s.AccountInfo.Webservices)
|
||||
}
|
||||
|
||||
func TestValidateCodeCanChangeDomain(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, validationPath string
|
||||
validate func(*Session) error
|
||||
}{
|
||||
{"trusted device", "/appleauth/auth/verify/trusteddevice/securitycode", func(s *Session) error {
|
||||
return s.Validate2FACode(context.Background(), "000000")
|
||||
}},
|
||||
{"SMS", "/appleauth/auth/verify/phone/securitycode", func(s *Session) error {
|
||||
return s.ValidateSMSCode(context.Background(), "000000", 1, "sms")
|
||||
}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var paths []string
|
||||
s := NewSession()
|
||||
s.srv = rest.NewClient(&http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
paths = append(paths, req.URL.Path)
|
||||
status, body := http.StatusOK, ""
|
||||
if req.URL.Path == "/setup/ws/1/accountLogin" {
|
||||
status, body = http.StatusFound, `{"domainToUse":"iCloud.com.cn"}`
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: status,
|
||||
Header: http.Header{"Content-Type": {"application/json"}},
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
Request: req,
|
||||
}, nil
|
||||
})})
|
||||
require.ErrorIs(t, tc.validate(s), ErrDomainChanged)
|
||||
assert.Equal(t, []string{tc.validationPath, "/appleauth/auth/2sv/trust", "/setup/ws/1/accountLogin"}, paths)
|
||||
assert.Equal(t, "iCloud.com.cn", s.DomainToUse)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionEndpoints(t *testing.T) {
|
||||
s := NewSession()
|
||||
assert.Equal(t, endpoints{baseEndpoint, setupEndpoint, authEndpoint}, s.endpoints())
|
||||
assert.Equal(t, "https://www.icloud.com", s.getCommonHeaders(nil)["Origin"])
|
||||
assert.Equal(t, "https://idmsa.apple.com", s.getSRPAuthHeaders()["Origin"])
|
||||
require.NoError(t, s.SetDomainToUse("iCloud.com.cn"))
|
||||
assert.Equal(t, "https://setup.icloud.com.cn/setup/ws/1", s.endpoints().setup)
|
||||
assert.Equal(t, "https://idmsa.apple.com.cn", s.getSRPAuthHeaders()["Origin"])
|
||||
assert.Equal(t, "https://idmsa.apple.com.cn/", s.getSRPAuthHeaders()["Referer"])
|
||||
assert.Equal(t, "https://www.icloud.com.cn/", s.getCommonHeaders(nil)["Referer"])
|
||||
assert.Equal(t, "https://www.icloud.com.cn", s.getSRPAuthHeaders()["X-Apple-OAuth-Redirect-URI"])
|
||||
require.Error(t, s.SetDomainToUse("example.com"))
|
||||
assert.Equal(t, "iCloud.com.cn", s.DomainToUse)
|
||||
data, err := json.Marshal(s)
|
||||
require.NoError(t, err)
|
||||
var restored Session
|
||||
require.NoError(t, json.Unmarshal(data, &restored))
|
||||
assert.Equal(t, s.endpoints(), restored.endpoints())
|
||||
}
|
||||
|
||||
func TestAuthStartRedirectURI(t *testing.T) {
|
||||
for _, tc := range []struct{ domain, want string }{
|
||||
{"", "https://www.icloud.com"},
|
||||
{"iCloud.com.cn", "https://www.icloud.com.cn"},
|
||||
} {
|
||||
t.Run(tc.domain, func(t *testing.T) {
|
||||
s := NewSession()
|
||||
if tc.domain != "" {
|
||||
require.NoError(t, s.SetDomainToUse(tc.domain))
|
||||
}
|
||||
s.srv = rest.NewClient(&http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
assert.Equal(t, tc.want, req.URL.Query().Get("redirect_uri"))
|
||||
return &http.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: make(http.Header), Body: io.NopCloser(strings.NewReader("")), Request: req}, nil
|
||||
})})
|
||||
require.NoError(t, s.authStart(context.Background()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractHeadersMergesCookies(t *testing.T) {
|
||||
s := NewSession()
|
||||
s.Cookies = []*http.Cookie{{Name: "existing", Value: "old"}}
|
||||
|
||||
+103
-27
@@ -35,6 +35,7 @@ type configAuthState struct {
|
||||
SessionToken string `json:"t"`
|
||||
ClientID string `json:"c"`
|
||||
AccountCountry string `json:"ac"`
|
||||
DomainToUse string `json:"d,omitempty"`
|
||||
Phones []smsPhone `json:"p,omitempty"`
|
||||
}
|
||||
|
||||
@@ -53,6 +54,7 @@ func saveAuthSession(m configmap.Mapper, s *api.Session, phones []smsPhone) {
|
||||
SessionToken: s.SessionToken,
|
||||
ClientID: s.ClientID,
|
||||
AccountCountry: s.AccountCountry,
|
||||
DomainToUse: s.DomainToUse,
|
||||
Phones: phones,
|
||||
}
|
||||
data, err := json.Marshal(st)
|
||||
@@ -79,7 +81,7 @@ func loadAuthSession(m configmap.Mapper) (*configAuthState, error) {
|
||||
return &st, nil
|
||||
}
|
||||
|
||||
func restoreAuthSession(icloud *api.Client, st *configAuthState) {
|
||||
func restoreAuthSession(icloud *api.Client, st *configAuthState) error {
|
||||
icloud.Session.Scnt = st.Scnt
|
||||
icloud.Session.SessionID = st.SessionID
|
||||
icloud.Session.AuthAttributes = st.AuthAttributes
|
||||
@@ -87,6 +89,10 @@ func restoreAuthSession(icloud *api.Client, st *configAuthState) {
|
||||
icloud.Session.SessionToken = st.SessionToken
|
||||
icloud.Session.ClientID = st.ClientID
|
||||
icloud.Session.AccountCountry = st.AccountCountry
|
||||
if st.DomainToUse != "" {
|
||||
return icloud.Session.SetDomainToUse(st.DomainToUse)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// resumeConfigClient recreates an API client and restores session state saved
|
||||
@@ -100,7 +106,9 @@ func resumeConfigClient(m configmap.Mapper, appleid, password, trustToken, clien
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
restoreAuthSession(icloud, st)
|
||||
if err := restoreAuthSession(icloud, st); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return icloud, st, nil
|
||||
}
|
||||
|
||||
@@ -108,11 +116,29 @@ func resumeConfigClient(m configmap.Mapper, appleid, password, trustToken, clien
|
||||
// after successful 2FA validation
|
||||
func saveAuthCredentials(m configmap.Mapper, icloud *api.Client, name string) {
|
||||
m.Set(configTrustToken, icloud.Session.TrustToken)
|
||||
saveSessionRegion(m, icloud.Session)
|
||||
m.Set(configCookies, icloud.Session.GetCookieString())
|
||||
m.Set(configAuthSession, "")
|
||||
api.ClearCacheDir(name)
|
||||
}
|
||||
|
||||
func setSessionRegion(session *api.Session, region string) error {
|
||||
switch region {
|
||||
case "", regionGlobal:
|
||||
return nil
|
||||
case regionChina:
|
||||
return session.SetDomainToUse("iCloud.com.cn")
|
||||
default:
|
||||
return fmt.Errorf("unsupported iCloud region %q", region)
|
||||
}
|
||||
}
|
||||
|
||||
func saveSessionRegion(m configmap.Mapper, session *api.Session) {
|
||||
if session.DomainToUse != "" {
|
||||
m.Set(configRegion, regionChina)
|
||||
}
|
||||
}
|
||||
|
||||
// triggerSMSFlow handles phone selection and SMS triggering
|
||||
// Single phone: triggers SMS immediately, returns code prompt
|
||||
// Multiple phones: saves session + phone list, returns phone picker
|
||||
@@ -148,6 +174,49 @@ func triggerSMSFlow(ctx context.Context, icloud *api.Client, phones []api.Truste
|
||||
return fs.ConfigChooseExclusiveFixed("2fa_sms_select", "config_2fa_phone", "Select phone number for SMS verification", items)
|
||||
}
|
||||
|
||||
func finishConfigAuthentication(ctx context.Context, name string, m configmap.Mapper, icloud *api.Client) (*fs.ConfigOut, error) {
|
||||
m.Set(configCookies, icloud.Session.GetCookieString())
|
||||
saveSessionRegion(m, icloud.Session)
|
||||
if icloud.Session.Requires2FA() {
|
||||
authState, err := icloud.Session.GetAuthState(ctx)
|
||||
if err == nil && authState.NoTrustedDevices && len(authState.TrustedPhoneNumbers) > 0 {
|
||||
return triggerSMSFlow(ctx, icloud, authState.TrustedPhoneNumbers, m)
|
||||
}
|
||||
// Explicitly request push to trusted devices - required for iOS 26.4+
|
||||
// where the SRP 409 no longer auto-pushes. GET /appleauth/auth above
|
||||
// may also trigger a push (cosmetic double on pre-26.4, harmless)
|
||||
if err := icloud.Session.RequestPushNotification(ctx); err != nil {
|
||||
fs.Debugf(nil, "iclouddrive: push notification request failed (SMS fallback available): %v", err)
|
||||
} else {
|
||||
fs.Debugf(nil, "iclouddrive: push notification requested to trusted devices")
|
||||
}
|
||||
// Save session state so 2fa_do can validate without re-authenticating
|
||||
// Push codes are account-scoped so session reuse is not strictly required,
|
||||
// but it avoids a redundant SRP roundtrip and a second push on pre-26.4
|
||||
saveAuthSession(m, icloud.Session, nil)
|
||||
return fs.ConfigInput("2fa_do", "config_2fa", "Two-factor authentication: enter your 2FA code or type 'sms' for a text message")
|
||||
}
|
||||
saveAuthCredentials(m, icloud, name)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func retryConfigDomain(ctx context.Context, name string, m configmap.Mapper, previous *api.Client, appleid, password, clientID string) (*fs.ConfigOut, error) {
|
||||
domain := previous.Session.DomainToUse
|
||||
saveSessionRegion(m, previous.Session)
|
||||
m.Set(configAuthSession, "")
|
||||
icloud, err := api.New(appleid, password, previous.Session.TrustToken, clientID, nil, nil, "_config", "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := icloud.Session.SetDomainToUse(domain); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := icloud.Authenticate(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return finishConfigAuthentication(ctx, name, m, icloud)
|
||||
}
|
||||
|
||||
const (
|
||||
configService = "service"
|
||||
|
||||
@@ -229,6 +298,18 @@ func init() {
|
||||
Required: false,
|
||||
Sensitive: true,
|
||||
Hide: fs.OptionHideBoth,
|
||||
}, {
|
||||
Name: configRegion,
|
||||
Help: "Region for iCloud accounts. China Mainland (GCBD) accounts are normally detected automatically.",
|
||||
Advanced: true,
|
||||
Default: regionGlobal,
|
||||
Examples: []fs.OptionExample{{
|
||||
Value: regionGlobal,
|
||||
Help: "Global (automatically detects China Mainland accounts).",
|
||||
}, {
|
||||
Value: regionChina,
|
||||
Help: "China Mainland (GCBD).",
|
||||
}},
|
||||
}, {
|
||||
Name: configCookies,
|
||||
Help: "Session cookies.",
|
||||
@@ -236,6 +317,11 @@ func init() {
|
||||
Advanced: false,
|
||||
Sensitive: true,
|
||||
Hide: fs.OptionHideBoth,
|
||||
}, {
|
||||
Name: configAuthSession,
|
||||
Help: "Authentication session in progress - set automatically.",
|
||||
Sensitive: true,
|
||||
Hide: fs.OptionHideBoth,
|
||||
}, {
|
||||
Name: configClientID,
|
||||
Help: "Client ID for iCloud API access.",
|
||||
@@ -273,6 +359,7 @@ func Config(ctx context.Context, name string, m configmap.Mapper, config fs.Conf
|
||||
trustToken, _ := m.Get(configTrustToken)
|
||||
cookieRaw, _ := m.Get(configCookies)
|
||||
clientID, _ := m.Get(configClientID)
|
||||
region, _ := m.Get(configRegion)
|
||||
cookies := ReadCookies(cookieRaw)
|
||||
|
||||
switch {
|
||||
@@ -284,34 +371,13 @@ func Config(ctx context.Context, name string, m configmap.Mapper, config fs.Conf
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := setSessionRegion(icloud.Session, region); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := icloud.Authenticate(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m.Set(configCookies, icloud.Session.GetCookieString())
|
||||
if icloud.Session.Requires2FA() {
|
||||
// Check if user has no trusted devices - auto-trigger SMS if so
|
||||
authState, err := icloud.Session.GetAuthState(ctx)
|
||||
if err == nil && authState.NoTrustedDevices && len(authState.TrustedPhoneNumbers) > 0 {
|
||||
return triggerSMSFlow(ctx, icloud, authState.TrustedPhoneNumbers, m)
|
||||
}
|
||||
// Explicitly request push to trusted devices - required for iOS 26.4+
|
||||
// where the SRP 409 no longer auto-pushes. GET /appleauth/auth above
|
||||
// may also trigger a push (cosmetic double on pre-26.4, harmless)
|
||||
if err := icloud.Session.RequestPushNotification(ctx); err != nil {
|
||||
fs.Debugf(nil, "iclouddrive: push notification request failed (SMS fallback available): %v", err)
|
||||
} else {
|
||||
fs.Debugf(nil, "iclouddrive: push notification requested to trusted devices")
|
||||
}
|
||||
// Save session state so 2fa_do can validate without re-authenticating
|
||||
// Push codes are account-scoped so session reuse is not strictly required,
|
||||
// but it avoids a redundant SRP roundtrip and a second push on pre-26.4
|
||||
saveAuthSession(m, icloud.Session, nil)
|
||||
return fs.ConfigInput("2fa_do", "config_2fa", "Two-factor authentication: enter your 2FA code or type 'sms' for a text message")
|
||||
}
|
||||
// Auth succeeded without 2FA - save updated credentials and clear stale cache
|
||||
m.Set(configTrustToken, icloud.Session.TrustToken)
|
||||
api.ClearCacheDir(name)
|
||||
return nil, nil
|
||||
return finishConfigAuthentication(ctx, name, m, icloud)
|
||||
|
||||
case config.State == "2fa_do":
|
||||
code := config.Result
|
||||
@@ -338,6 +404,9 @@ func Config(ctx context.Context, name string, m configmap.Mapper, config fs.Conf
|
||||
}
|
||||
|
||||
if err := icloud.Session.Validate2FACode(ctx, code); err != nil {
|
||||
if errors.Is(err, api.ErrDomainChanged) {
|
||||
return retryConfigDomain(ctx, name, m, icloud, appleid, password, clientID)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
saveAuthCredentials(m, icloud, name)
|
||||
@@ -397,6 +466,9 @@ func Config(ctx context.Context, name string, m configmap.Mapper, config fs.Conf
|
||||
}
|
||||
|
||||
if err := icloud.Session.ValidateSMSCode(ctx, code, phoneID, mode); err != nil {
|
||||
if errors.Is(err, api.ErrDomainChanged) {
|
||||
return retryConfigDomain(ctx, name, m, icloud, appleid, password, clientID)
|
||||
}
|
||||
m.Set(configAuthSession, "")
|
||||
return nil, err
|
||||
}
|
||||
@@ -433,6 +505,7 @@ func newICloudClient(ctx context.Context, name string, m configmap.Mapper, pcsWS
|
||||
|
||||
callback := func(session *api.Session) {
|
||||
m.Set(configCookies, session.GetCookieString())
|
||||
saveSessionRegion(m, session)
|
||||
}
|
||||
|
||||
icloud, err := api.New(
|
||||
@@ -448,6 +521,9 @@ func newICloudClient(ctx context.Context, name string, m configmap.Mapper, pcsWS
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if err := setSessionRegion(icloud.Session, opt.Region); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
if err := icloud.Authenticate(ctx); err != nil {
|
||||
return nil, nil, err
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
//go:build !plan9 && !solaris
|
||||
|
||||
package iclouddrive
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/rclone/rclone/backend/iclouddrive/api"
|
||||
"github.com/rclone/rclone/fs/config/configmap"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestConfigAuthSessionKeepsRegion(t *testing.T) {
|
||||
m := configmap.Simple{}
|
||||
s := api.NewSession()
|
||||
require.NoError(t, s.SetDomainToUse("iCloud.com.cn"))
|
||||
saveAuthSession(m, s, nil)
|
||||
client, _, err := resumeConfigClient(m, "", "", "", "", nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "iCloud.com.cn", client.Session.DomainToUse)
|
||||
saveAuthCredentials(m, client, t.Name())
|
||||
assert.Equal(t, regionChina, m[configRegion])
|
||||
assert.Empty(t, m[configAuthSession])
|
||||
}
|
||||
|
||||
func TestConfigRegion(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
region, domain, savedRegion string
|
||||
}{
|
||||
{"", "", ""},
|
||||
{regionGlobal, "", ""},
|
||||
{regionChina, "iCloud.com.cn", regionChina},
|
||||
} {
|
||||
t.Run(tc.region, func(t *testing.T) {
|
||||
m := configmap.Simple{}
|
||||
s := api.NewSession()
|
||||
require.NoError(t, setSessionRegion(s, tc.region))
|
||||
assert.Equal(t, tc.domain, s.DomainToUse)
|
||||
saveSessionRegion(m, s)
|
||||
if tc.savedRegion == "" {
|
||||
assert.NotContains(t, m, configRegion)
|
||||
} else {
|
||||
assert.Equal(t, tc.savedRegion, m[configRegion])
|
||||
}
|
||||
})
|
||||
}
|
||||
require.Error(t, setSessionRegion(api.NewSession(), "invalid"))
|
||||
}
|
||||
|
||||
func TestGlobalAuthDoesNotSaveRegion(t *testing.T) {
|
||||
m := configmap.Simple{}
|
||||
client, err := api.New("", "", "", "", nil, nil, t.Name(), "")
|
||||
require.NoError(t, err)
|
||||
saveAuthCredentials(m, client, t.Name())
|
||||
assert.NotContains(t, m, configRegion)
|
||||
}
|
||||
@@ -41,6 +41,9 @@ const (
|
||||
configClientID = "client_id"
|
||||
configCookies = "cookies"
|
||||
configTrustToken = "trust_token"
|
||||
configRegion = "region"
|
||||
regionGlobal = "global"
|
||||
regionChina = "china"
|
||||
|
||||
minSleep = 10 * time.Millisecond
|
||||
maxSleep = 2 * time.Second
|
||||
@@ -52,6 +55,7 @@ type Options struct {
|
||||
AppleID string `config:"apple_id"`
|
||||
Password string `config:"password"`
|
||||
TrustToken string `config:"trust_token"`
|
||||
Region string `config:"region"`
|
||||
Cookies string `config:"cookies"`
|
||||
ClientID string `config:"client_id"`
|
||||
Enc encoder.MultiEncoder `config:"encoding"`
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/rclone/rclone/fs/config"
|
||||
"github.com/rclone/rclone/fs/config/configmap"
|
||||
"github.com/rclone/rclone/fs/config/configstruct"
|
||||
"github.com/rclone/rclone/fs/fshttp"
|
||||
"github.com/rclone/rclone/fs/hash"
|
||||
"github.com/rclone/rclone/lib/encoder"
|
||||
"github.com/rclone/rclone/lib/pacer"
|
||||
@@ -188,6 +189,7 @@ type Fs struct {
|
||||
features *fs.Features // optional features
|
||||
ik *client.ImageKit // ImageKit client
|
||||
pacer *fs.Pacer // pacer for API calls
|
||||
srv *http.Client // client for downloads from the URL endpoint
|
||||
}
|
||||
|
||||
// Object describes a ImageKit file
|
||||
@@ -224,6 +226,7 @@ func NewFs(ctx context.Context, name string, root string, m configmap.Mapper) (f
|
||||
name: name,
|
||||
opt: *opt,
|
||||
ik: ik,
|
||||
srv: fshttp.NewClient(ctx),
|
||||
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
||||
}
|
||||
|
||||
@@ -630,8 +633,10 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
|
||||
return nil, err
|
||||
}
|
||||
|
||||
client := &http.Client{}
|
||||
req, _ := http.NewRequest("GET", url, nil)
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if partialContent {
|
||||
if count > 0 {
|
||||
req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+count-1))
|
||||
@@ -639,11 +644,15 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
|
||||
req.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset))
|
||||
}
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
resp, err := o.fs.srv.Do(req)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent {
|
||||
_ = resp.Body.Close()
|
||||
return nil, fmt.Errorf("failed to download %q: %s", o.remote, resp.Status)
|
||||
}
|
||||
|
||||
end := resp.ContentLength
|
||||
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package imagekit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rclone/rclone/backend/imagekit/client"
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/fshttp"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const testContent = "0123456789"
|
||||
|
||||
func newOpenTestObject(t *testing.T, srv *httptest.Server, path string) *Object {
|
||||
ctx := context.Background()
|
||||
ik, err := client.New(ctx, client.NewParams{
|
||||
URLEndpoint: srv.URL,
|
||||
PublicKey: "public",
|
||||
PrivateKey: "private",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
isPrivateFile := false
|
||||
return &Object{
|
||||
fs: &Fs{
|
||||
ik: ik,
|
||||
srv: fshttp.NewClient(ctx),
|
||||
},
|
||||
remote: "file.txt",
|
||||
file: client.File{
|
||||
URL: srv.URL + path,
|
||||
IsPrivateFile: &isPrivateFile,
|
||||
Size: uint64(len(testContent)),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenHTTPStatus(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/file.txt":
|
||||
http.ServeContent(w, r, "file.txt", time.Time{}, strings.NewReader(testContent))
|
||||
case "/missing.txt":
|
||||
http.Error(w, "<html>Not Found</html>", http.StatusNotFound)
|
||||
default:
|
||||
http.Error(w, "<html>Bad Gateway</html>", http.StatusBadGateway)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
ctx := context.Background()
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
path string
|
||||
options []fs.OpenOption
|
||||
want string
|
||||
wantErr string
|
||||
}{
|
||||
{name: "OK", path: "/file.txt", want: testContent},
|
||||
{name: "Range", path: "/file.txt", options: []fs.OpenOption{&fs.RangeOption{Start: 2, End: 4}}, want: "234"},
|
||||
{name: "NotFound", path: "/missing.txt", wantErr: "404 Not Found"},
|
||||
{name: "BadGateway", path: "/error.txt", wantErr: "502 Bad Gateway"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
o := newOpenTestObject(t, srv, test.path)
|
||||
in, err := o.Open(ctx, test.options...)
|
||||
if test.wantErr != "" {
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), test.wantErr)
|
||||
assert.Nil(t, in)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
got, err := io.ReadAll(in)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, in.Close())
|
||||
assert.Equal(t, test.want, string(got))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -634,6 +634,27 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (_ fs.Objec
|
||||
"x-archive-filemeta-rclone-update-track": updateTracker,
|
||||
}
|
||||
|
||||
mdata, err := fs.GetMetadataOptions(ctx, f, src, fs.MetadataAsOpenOptions(ctx))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if mdata != nil {
|
||||
// IA ignores file metadata headers with the COPY directive.
|
||||
headers["x-amz-metadata-directive"] = "REPLACE"
|
||||
}
|
||||
for key, value := range mdata {
|
||||
key = strings.ToLower(key)
|
||||
if key == "mtime" {
|
||||
key = "rclone-mtime"
|
||||
} else if strings.HasPrefix(key, "rclone-") {
|
||||
// Keep the new copy tracker and mapped mtime, not the source internals.
|
||||
continue
|
||||
} else if _, readOnly := roMetadataKey[key]; readOnly {
|
||||
continue
|
||||
}
|
||||
headers["x-archive-filemeta-"+key] = value
|
||||
}
|
||||
|
||||
// make a PUT request at (IAS3)/:item/:path without body
|
||||
var resp *http.Response
|
||||
opts := rest.Opts{
|
||||
|
||||
@@ -101,6 +101,11 @@ func init() {
|
||||
Advanced: true,
|
||||
Sensitive: true,
|
||||
Hide: fs.OptionHideBoth,
|
||||
}, {
|
||||
Name: rclone_config.ConfigToken,
|
||||
Help: "OAuth Access Token as a JSON blob - set automatically.",
|
||||
Sensitive: true,
|
||||
Hide: fs.OptionHideBoth,
|
||||
}, {
|
||||
Name: "skip_hash_validation",
|
||||
Default: true,
|
||||
@@ -131,6 +136,16 @@ func init() {
|
||||
encoder.EncodeRightPeriod |
|
||||
encoder.EncodeDot |
|
||||
encoder.EncodeCrLf,
|
||||
}, {
|
||||
Name: "2fa_code",
|
||||
Help: "Two-factor authentication code used during setup - set automatically.",
|
||||
Sensitive: true,
|
||||
Hide: fs.OptionHideBoth,
|
||||
}, {
|
||||
Name: "bucket",
|
||||
Help: "Bucket ID - set automatically.",
|
||||
Sensitive: true,
|
||||
Hide: fs.OptionHideBoth,
|
||||
}},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -50,7 +50,8 @@ const (
|
||||
defaultMountpoint = "Archive"
|
||||
jfsURL = "https://jfs.jottacloud.com/jfs/"
|
||||
apiURL = "https://api.jottacloud.com/"
|
||||
wwwURL = "https://www.jottacloud.com/"
|
||||
contentURL = "https://content.jottacloud.com/"
|
||||
webAppURL = "https://app.jottacloud.com/"
|
||||
cachePrefix = "rclone-jcmd5-"
|
||||
configDevice = "device"
|
||||
configMountpoint = "mountpoint"
|
||||
@@ -58,6 +59,9 @@ const (
|
||||
configClientID = "client_id"
|
||||
configClientSecret = "client_secret"
|
||||
configUsername = "username"
|
||||
configPassword = "password"
|
||||
configAuthCode = "auth_code"
|
||||
configVersionKey = "configVersion"
|
||||
configVersion = 1
|
||||
|
||||
defaultTokenURL = "https://id.jottacloud.com/auth/realms/jottacloud/protocol/openid-connect/token"
|
||||
@@ -170,6 +174,39 @@ func init() {
|
||||
encoder.EncodeWin | // :?"*<>|
|
||||
encoder.EncodeInvalidUtf8 |
|
||||
encoder.EncodePercent),
|
||||
}, {
|
||||
Name: configDevice,
|
||||
Help: "Device to use.\n\nLeave blank to use the default device \"" + defaultDevice + "\".",
|
||||
Advanced: true,
|
||||
Hide: fs.OptionHideConfigurator,
|
||||
}, {
|
||||
Name: configMountpoint,
|
||||
Help: "Mountpoint to use.\n\nLeave blank to use the default mountpoint \"" + defaultMountpoint + "\".",
|
||||
Advanced: true,
|
||||
Hide: fs.OptionHideConfigurator,
|
||||
}, {
|
||||
Name: configVersionKey,
|
||||
Help: "Config version - set automatically.",
|
||||
Hide: fs.OptionHideBoth,
|
||||
}, {
|
||||
Name: configTokenURL,
|
||||
Help: "Token server URL - set automatically.",
|
||||
Hide: fs.OptionHideBoth,
|
||||
}, {
|
||||
Name: configUsername,
|
||||
Help: "Username (e-mail address) - set automatically.",
|
||||
Sensitive: true,
|
||||
Hide: fs.OptionHideBoth,
|
||||
}, {
|
||||
Name: configPassword,
|
||||
Help: "Password used during legacy setup - set automatically.",
|
||||
IsPassword: true,
|
||||
Hide: fs.OptionHideBoth,
|
||||
}, {
|
||||
Name: configAuthCode,
|
||||
Help: "Verification code used during legacy setup - set automatically.",
|
||||
Sensitive: true,
|
||||
Hide: fs.OptionHideBoth,
|
||||
}}...),
|
||||
})
|
||||
}
|
||||
@@ -207,7 +244,7 @@ used. You will be asked for your account's username and password.`,
|
||||
// Jump to next state according to config chosen
|
||||
return fs.ConfigGoto(conf.Result)
|
||||
case "standard": // configure a jottacloud backend using the modern JottaCli token based authentication
|
||||
m.Set("configVersion", fmt.Sprint(configVersion))
|
||||
m.Set(configVersionKey, fmt.Sprint(configVersion))
|
||||
return fs.ConfigInput("standard_token", "config_login_token", `Personal login token.
|
||||
Generate it from the account security settings in the web interface of your
|
||||
service, for the official service on https://www.jottacloud.com/web/secure.`)
|
||||
@@ -256,7 +293,7 @@ service, for the official service on https://www.jottacloud.com/web/secure.`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get authentication provider configuration: %w", err)
|
||||
}
|
||||
m.Set("configVersion", fmt.Sprint(configVersion))
|
||||
m.Set(configVersionKey, fmt.Sprint(configVersion))
|
||||
m.Set(configClientID, service.clientID)
|
||||
m.Set(configClientSecret, "")
|
||||
m.Set(configTokenURL, wellKnown.TokenEndpoint)
|
||||
@@ -270,9 +307,9 @@ service, for the official service on https://www.jottacloud.com/web/secure.`)
|
||||
},
|
||||
})
|
||||
case "legacy": // configure a jottacloud backend using legacy authentication
|
||||
m.Set("configVersion", fmt.Sprint(legacyConfigVersion))
|
||||
m.Set(configVersionKey, fmt.Sprint(legacyConfigVersion))
|
||||
return fs.ConfigConfirm("legacy_api", false, "config_machine_specific", `Do you want to create a machine specific API key?
|
||||
Rclone has it's own Jottacloud API KEY which works fine as long as one
|
||||
Rclone has its own Jottacloud API KEY which works fine as long as one
|
||||
only uses rclone on a single machine. When you want to use rclone with
|
||||
this account on more than one machine it's recommended to create a
|
||||
machine specific API key. These keys can NOT be shared between
|
||||
@@ -286,25 +323,25 @@ machines.`)
|
||||
}
|
||||
m.Set(configClientID, deviceRegistration.ClientID)
|
||||
m.Set(configClientSecret, obscure.MustObscure(deviceRegistration.ClientSecret))
|
||||
fs.Debugf(nil, "Got clientID %q and clientSecret %q", deviceRegistration.ClientID, deviceRegistration.ClientSecret)
|
||||
fs.Debugf(nil, "Got clientID %q and clientSecret %s", deviceRegistration.ClientID, fs.RedactValue(fs.GetConfig(ctx), deviceRegistration.ClientSecret))
|
||||
}
|
||||
return fs.ConfigInput("legacy_username", "config_username", "Username (e-mail address) of your account.")
|
||||
case "legacy_username":
|
||||
m.Set(configUsername, conf.Result)
|
||||
return fs.ConfigPassword("legacy_password", "config_password", "Password of your account. This is only used in setup, it will not be stored.")
|
||||
case "legacy_password":
|
||||
m.Set("password", conf.Result)
|
||||
m.Set("auth_code", "")
|
||||
m.Set(configPassword, conf.Result)
|
||||
m.Set(configAuthCode, "")
|
||||
return fs.ConfigGoto("legacy_do_auth")
|
||||
case "legacy_auth_code":
|
||||
authCode := strings.ReplaceAll(conf.Result, "-", "") // remove any "-" contained in the code so we have a 6 digit number
|
||||
m.Set("auth_code", authCode)
|
||||
m.Set(configAuthCode, authCode)
|
||||
return fs.ConfigGoto("legacy_do_auth")
|
||||
case "legacy_do_auth":
|
||||
username, _ := m.Get(configUsername)
|
||||
password, _ := m.Get("password")
|
||||
password, _ := m.Get(configPassword)
|
||||
password = obscure.MustReveal(password)
|
||||
authCode, _ := m.Get("auth_code")
|
||||
authCode, _ := m.Get(configAuthCode)
|
||||
|
||||
srv := rest.NewClient(fshttp.NewClient(ctx))
|
||||
clientID, _ := m.Get(configClientID)
|
||||
@@ -327,8 +364,8 @@ machines.`)
|
||||
if err == errAuthCodeRequired {
|
||||
return fs.ConfigInput("legacy_auth_code", "config_auth_code", "Verification code.\nThis account uses 2 factor authentication you will receive a verification code via SMS.")
|
||||
}
|
||||
m.Set("password", "")
|
||||
m.Set("auth_code", "")
|
||||
m.Set(configPassword, "")
|
||||
m.Set(configAuthCode, "")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get oauth token: %w", err)
|
||||
}
|
||||
@@ -916,7 +953,8 @@ func grantTypeFilter(req *http.Request) {
|
||||
func getOAuthClient(ctx context.Context, name string, m configmap.Mapper) (oAuthClient *http.Client, ts *oauthutil.TokenSource, err error) {
|
||||
// Check config version
|
||||
var ver int
|
||||
version, ok := m.Get("configVersion")
|
||||
version, _ := m.Get(configVersionKey)
|
||||
ok := version != ""
|
||||
if ok {
|
||||
ver, err = strconv.Atoi(version)
|
||||
if err != nil {
|
||||
@@ -936,7 +974,7 @@ func getOAuthClient(ctx context.Context, name string, m configmap.Mapper) (oAuth
|
||||
if ver == configVersion {
|
||||
oauthConfig.ClientID = defaultClientID
|
||||
// if custom endpoints are set use them else stick with defaults
|
||||
if tokenURL, ok := m.Get(configTokenURL); ok {
|
||||
if tokenURL, _ := m.Get(configTokenURL); tokenURL != "" {
|
||||
oauthConfig.TokenURL = tokenURL
|
||||
// jottacloud is weird. we need to use the tokenURL as authURL
|
||||
oauthConfig.AuthURL = tokenURL
|
||||
@@ -1670,12 +1708,12 @@ func (f *Fs) PublicLink(ctx context.Context, remote string, expire fs.Duration,
|
||||
return "", errors.New("couldn't create public link - no uri received")
|
||||
}
|
||||
if result.PublicSharePath != "" {
|
||||
webLink := joinPath(wwwURL, result.PublicSharePath)
|
||||
webLink := joinPath(webAppURL, result.PublicSharePath)
|
||||
fs.Debugf(nil, "Web link: %s", webLink)
|
||||
} else {
|
||||
fs.Debugf(nil, "No web link received")
|
||||
}
|
||||
directLink := joinPath(wwwURL, fmt.Sprintf("opin/io/downloadPublic/%s/%s", f.user, result.PublicURI))
|
||||
directLink := joinPath(contentURL, fmt.Sprintf("opin/io/downloadPublic/%s/%s", f.user, result.PublicURI))
|
||||
fs.Debugf(nil, "Direct link: %s", directLink)
|
||||
return directLink, nil
|
||||
}
|
||||
|
||||
@@ -73,9 +73,10 @@ func init() {
|
||||
IsPassword: true,
|
||||
Required: true,
|
||||
}, {
|
||||
Name: "web_token",
|
||||
Help: "Web API login token - set automatically.",
|
||||
Hide: fs.OptionHideBoth,
|
||||
Name: "web_token",
|
||||
Help: "Web API login token - set automatically.",
|
||||
Hide: fs.OptionHideBoth,
|
||||
Sensitive: true,
|
||||
}},
|
||||
}
|
||||
fs.Register(fsi)
|
||||
|
||||
+65
-15
@@ -960,13 +960,13 @@ func (f *Fs) MkdirMetadata(ctx context.Context, dir string, metadata fs.Metadata
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fi, err := f.lstat(localPath)
|
||||
fi, err := f.lstatRoot(localPath)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
err := f.Mkdir(ctx, dir)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mkdir metadata: failed make directory: %w", err)
|
||||
}
|
||||
fi, err = f.lstat(localPath)
|
||||
fi, err = f.lstatRoot(localPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mkdir metadata: failed to read info: %w", err)
|
||||
}
|
||||
@@ -998,20 +998,34 @@ func (f *Fs) MkdirMetadata(ctx context.Context, dir string, metadata fs.Metadata
|
||||
// Rmdir removes the directory
|
||||
//
|
||||
// If it isn't empty it will return an error
|
||||
func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
||||
func (f *Fs) Rmdir(ctx context.Context, dir string) (err error) {
|
||||
localPath, err := f.localPath(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if fi, err := os.Stat(localPath); err != nil {
|
||||
// When translating symlinks go through os.Root so a symlink planted at
|
||||
// any parent can't redirect the removal out of the destination, and
|
||||
// don't follow the leaf as a symlink is a file in this mode. The root
|
||||
// itself is the trusted destination and is removed directly.
|
||||
stat, removeFn, chmod := os.Stat, os.Remove, os.Chmod
|
||||
if f.opt.TranslateSymlinks && localPath != f.root {
|
||||
var root *os.Root
|
||||
root, localPath, err = f.osRoot(localPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer fs.CheckClose(root, &err)
|
||||
stat, removeFn, chmod = root.Lstat, root.Remove, root.Chmod
|
||||
}
|
||||
if fi, err := stat(localPath); err != nil {
|
||||
return err
|
||||
} else if !fi.IsDir() {
|
||||
return fs.ErrorIsFile
|
||||
}
|
||||
err = os.Remove(localPath)
|
||||
err = removeFn(localPath)
|
||||
if runtime.GOOS == "windows" && errors.Is(err, iofs.ErrPermission) { // https://github.com/golang/go/issues/26295
|
||||
if os.Chmod(localPath, 0o600) == nil {
|
||||
err = os.Remove(localPath)
|
||||
if chmod(localPath, 0o600) == nil {
|
||||
err = removeFn(localPath)
|
||||
}
|
||||
}
|
||||
return err
|
||||
@@ -1188,9 +1202,14 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
|
||||
return fs.ErrorDirExists
|
||||
}
|
||||
|
||||
// Create parent of destination
|
||||
// Create parent of destination. The root itself is the trusted
|
||||
// destination so its parent, which lies outside it, is created directly.
|
||||
dstParentPath := filepath.Dir(dstPath)
|
||||
err = file.MkdirAll(dstParentPath, 0777)
|
||||
if dstPath == f.root {
|
||||
err = file.MkdirAll(dstParentPath, 0777)
|
||||
} else {
|
||||
err = f.mkdirAll(dstParentPath)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1607,10 +1626,26 @@ func (f *Fs) mkdirAll(localPath string) (err error) {
|
||||
return root.MkdirAll(rel, 0777)
|
||||
}
|
||||
|
||||
// openFile opens localPath for writing. When translating symlinks it goes
|
||||
// through os.Root so a symlink planted at the path, or at any parent, is never
|
||||
// followed out of the destination. The returned file is independent of the
|
||||
// root, which is closed before returning.
|
||||
// lstatRoot returns the info for localPath without following a symlink at
|
||||
// the leaf. When translating symlinks it goes through os.Root so a symlink
|
||||
// planted at any parent can't make a path outside the destination look like
|
||||
// it exists, which would let its metadata be written there.
|
||||
func (f *Fs) lstatRoot(localPath string) (fi os.FileInfo, err error) {
|
||||
if !f.opt.TranslateSymlinks {
|
||||
return f.lstat(localPath)
|
||||
}
|
||||
root, rel, err := f.osRoot(localPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer fs.CheckClose(root, &err)
|
||||
return root.Lstat(rel)
|
||||
}
|
||||
|
||||
// openFile opens localPath with the given flags and perm. When translating
|
||||
// symlinks it goes through os.Root so a symlink planted at the path, or at any
|
||||
// parent, is never followed out of the destination. The returned file is
|
||||
// independent of the root, which is closed before returning.
|
||||
func (f *Fs) openFile(localPath string, flags int, perm os.FileMode) (fi *os.File, err error) {
|
||||
if !f.opt.TranslateSymlinks {
|
||||
return file.OpenFile(localPath, flags, perm)
|
||||
@@ -1679,6 +1714,21 @@ func (f *Fs) chtimes(localPath string, atime, mtime time.Time) (err error) {
|
||||
return root.Chtimes(rel, atime, mtime)
|
||||
}
|
||||
|
||||
// remove removes the file, symlink or empty directory at localPath. When
|
||||
// translating symlinks it goes through os.Root so a symlink planted at any
|
||||
// parent can't redirect the removal out of the destination.
|
||||
func (f *Fs) remove(localPath string) (err error) {
|
||||
if !f.opt.TranslateSymlinks {
|
||||
return remove(localPath, os.Remove)
|
||||
}
|
||||
root, rel, err := f.osRoot(localPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer fs.CheckClose(root, &err)
|
||||
return remove(rel, root.Remove)
|
||||
}
|
||||
|
||||
// mkdirAll makes all the directories needed to store the object
|
||||
func (o *Object) mkdirAll() error {
|
||||
return o.fs.mkdirAll(filepath.Dir(o.path))
|
||||
@@ -1803,7 +1853,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
||||
|
||||
if err != nil {
|
||||
fs.Logf(o, "Removing partially written file on error: %v", err)
|
||||
if removeErr := os.Remove(o.path); removeErr != nil {
|
||||
if removeErr := o.fs.remove(o.path); removeErr != nil {
|
||||
fs.Errorf(o, "Failed to remove partially written file: %v", removeErr)
|
||||
}
|
||||
return err
|
||||
@@ -1951,7 +2001,7 @@ func (o *Object) lstat() error {
|
||||
// Remove an object
|
||||
func (o *Object) Remove(ctx context.Context) error {
|
||||
o.clearHashCache()
|
||||
return remove(o.path)
|
||||
return o.fs.remove(o.path)
|
||||
}
|
||||
|
||||
// Metadata returns metadata for an object
|
||||
|
||||
@@ -560,6 +560,115 @@ func TestDirBTimeThroughPlantedSymlinkBlocked(t *testing.T) {
|
||||
require.Equal(t, before, readBTime(), "btime escaped through planted symlink to %q", evilDir)
|
||||
}
|
||||
|
||||
// TestMkdirMetadataThroughPlantedSymlinkBlocked checks MkdirMetadata can't
|
||||
// be fooled into treating a directory outside the root, reached through a
|
||||
// planted symlink, as the directory to apply metadata to.
|
||||
func TestMkdirMetadataThroughPlantedSymlinkBlocked(t *testing.T) {
|
||||
skipIfNoSymlinks(t)
|
||||
ctx := context.Background()
|
||||
|
||||
evil := t.TempDir()
|
||||
evilDir := filepath.Join(evil, "secret.d")
|
||||
require.NoError(t, os.Mkdir(evilDir, 0700))
|
||||
require.NoError(t, os.Mkdir(filepath.Join(evilDir, "sub"), 0700))
|
||||
|
||||
r := fstest.NewRun(t)
|
||||
f := r.Flocal.(*Fs)
|
||||
linksMode(f)
|
||||
|
||||
// Control: an existing in-tree directory is found as normal.
|
||||
require.NoError(t, f.Mkdir(ctx, "sub"))
|
||||
_, err := f.MkdirMetadata(ctx, "sub", nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
// The planted symlink dst/pwn -> outside, faithfully reproduced by --links.
|
||||
require.NoError(t, putLink(ctx, f, "pwn", evilDir))
|
||||
|
||||
// "pwn/sub" exists outside the root but must not be found through the
|
||||
// planted symlink, and must not be created there either.
|
||||
_, err = f.MkdirMetadata(ctx, "pwn/sub", nil)
|
||||
require.Error(t, err, "finding a directory through a planted symlink should be refused")
|
||||
_, err = f.MkdirMetadata(ctx, "pwn/new", nil)
|
||||
require.Error(t, err, "making a directory through a planted symlink should be refused")
|
||||
_, err = os.Lstat(filepath.Join(evilDir, "new"))
|
||||
require.True(t, os.IsNotExist(err), "a directory escaped the destination into %q", evilDir)
|
||||
}
|
||||
|
||||
// TestRemoveThroughPlantedSymlinkBlocked checks Remove and Rmdir can't
|
||||
// delete anything outside the root through a planted symlink.
|
||||
func TestRemoveThroughPlantedSymlinkBlocked(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
// os.Root.Symlink makes a file symlink to a directory outside
|
||||
// the root, which Windows can't traverse, so the planted link
|
||||
// can't reach the outside files.
|
||||
t.Skip("planted directory symlinks can't be traversed on Windows")
|
||||
}
|
||||
skipIfNoSymlinks(t)
|
||||
ctx := context.Background()
|
||||
|
||||
evil := t.TempDir()
|
||||
evilFile := filepath.Join(evil, "secret.txt")
|
||||
require.NoError(t, os.WriteFile(evilFile, []byte("keep me"), 0600))
|
||||
evilDir := filepath.Join(evil, "secret.d")
|
||||
require.NoError(t, os.Mkdir(evilDir, 0700))
|
||||
|
||||
r := fstest.NewRun(t)
|
||||
f := r.Flocal.(*Fs)
|
||||
linksMode(f)
|
||||
|
||||
// Control: in-tree removals work as normal.
|
||||
require.NoError(t, putFile(ctx, f, "file.txt", "data"))
|
||||
o, err := f.NewObject(ctx, "file.txt")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, o.Remove(ctx))
|
||||
require.NoError(t, f.Mkdir(ctx, "dir"))
|
||||
require.NoError(t, f.Rmdir(ctx, "dir"))
|
||||
|
||||
// The planted symlink dst/pwn -> outside, faithfully reproduced by --links.
|
||||
require.NoError(t, putLink(ctx, f, "pwn", evil))
|
||||
|
||||
// Removing the outside file and directory named through the planted
|
||||
// symlink must be refused.
|
||||
o, err = f.NewObject(ctx, "pwn/secret.txt")
|
||||
require.NoError(t, err)
|
||||
err = o.Remove(ctx)
|
||||
require.Error(t, err, "removing through a planted symlink should be refused")
|
||||
_, err = os.Lstat(evilFile)
|
||||
require.NoError(t, err, "a file was removed outside the destination at %q", evilFile)
|
||||
|
||||
err = f.Rmdir(ctx, "pwn/secret.d")
|
||||
require.Error(t, err, "removing a directory through a planted symlink should be refused")
|
||||
_, err = os.Lstat(evilDir)
|
||||
require.NoError(t, err, "a directory was removed outside the destination at %q", evilDir)
|
||||
}
|
||||
|
||||
// TestDirMoveThroughPlantedSymlinkBlocked checks DirMove can't move a
|
||||
// directory out of the root through a planted symlink.
|
||||
func TestDirMoveThroughPlantedSymlinkBlocked(t *testing.T) {
|
||||
skipIfNoSymlinks(t)
|
||||
ctx := context.Background()
|
||||
|
||||
evil := t.TempDir()
|
||||
|
||||
r := fstest.NewRun(t)
|
||||
f := r.Flocal.(*Fs)
|
||||
linksMode(f)
|
||||
|
||||
// Control: an in-tree directory move works as normal.
|
||||
require.NoError(t, f.Mkdir(ctx, "dir"))
|
||||
require.NoError(t, f.DirMove(ctx, f, "dir", "sub/moved"))
|
||||
|
||||
// The planted symlink dst/pwn -> outside, faithfully reproduced by --links.
|
||||
require.NoError(t, putLink(ctx, f, "pwn", evil))
|
||||
|
||||
err := f.DirMove(ctx, f, "sub/moved", "pwn/moved")
|
||||
require.Error(t, err, "moving a directory through a planted symlink should be refused")
|
||||
_, err = os.Lstat(filepath.Join(evil, "moved"))
|
||||
require.True(t, os.IsNotExist(err), "a directory escaped the destination into %q", evil)
|
||||
_, err = os.Lstat(filepath.Join(f.root, "sub", "moved"))
|
||||
require.NoError(t, err, "the directory should still be in the destination")
|
||||
}
|
||||
|
||||
// TestEncodingEscapeBlocked checks that a name from a malicious source can't
|
||||
// be decoded into path syntax which writes outside the destination.
|
||||
func TestEncodingEscapeBlocked(t *testing.T) {
|
||||
|
||||
@@ -2,9 +2,7 @@
|
||||
|
||||
package local
|
||||
|
||||
import "os"
|
||||
|
||||
// Removes name, retrying on a sharing violation
|
||||
func remove(name string) error {
|
||||
return os.Remove(name)
|
||||
// remove removes name with removeFn, retrying on a sharing violation
|
||||
func remove(name string, removeFn func(string) error) error {
|
||||
return removeFn(name)
|
||||
}
|
||||
@@ -38,7 +38,7 @@ func TestRemove(t *testing.T) {
|
||||
require.NoError(t, fd.Close())
|
||||
})
|
||||
// delete the open file
|
||||
err = remove(name)
|
||||
err = remove(name, os.Remove)
|
||||
require.NoError(t, err)
|
||||
// check it no longer exists
|
||||
assert.False(t, exists())
|
||||
|
||||
@@ -10,12 +10,12 @@ import (
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// Removes name, retrying on a sharing violation
|
||||
func remove(name string) (err error) {
|
||||
// remove removes name with removeFn, retrying on a sharing violation
|
||||
func remove(name string, removeFn func(string) error) (err error) {
|
||||
const maxTries = 10
|
||||
var sleepTime = 1 * time.Millisecond
|
||||
for i := range maxTries {
|
||||
err = os.Remove(name)
|
||||
err = removeFn(name)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
|
||||
+26
-2
@@ -4,6 +4,7 @@ package local
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
@@ -95,6 +96,11 @@ func (o *Object) setXattr(metadata fs.Metadata) (err error) {
|
||||
if !xattrSupported || o.fs.xattrSupported.Load() == 0 {
|
||||
return nil
|
||||
}
|
||||
// When translating symlinks (-l/--links) write the xattrs through a
|
||||
// descriptor opened under os.Root so a symlink planted in the destination
|
||||
// can't redirect the write outside it (CWE-59). A translated link is
|
||||
// itself the leaf, so it keeps the non-following path based write.
|
||||
var fd *os.File
|
||||
for k, value := range metadata {
|
||||
k = strings.ToLower(k)
|
||||
if _, found := systemMetadataInfo[k]; found {
|
||||
@@ -102,9 +108,27 @@ func (o *Object) setXattr(metadata fs.Metadata) (err error) {
|
||||
}
|
||||
k = xattrPrefix + k
|
||||
v := []byte(value)
|
||||
if o.fs.opt.FollowSymlinks {
|
||||
switch {
|
||||
case o.fs.opt.TranslateSymlinks && !o.translatedLink:
|
||||
if fd == nil {
|
||||
fd, err = o.fs.openFile(o.path, os.O_RDONLY, 0)
|
||||
if os.IsPermission(err) {
|
||||
// A write only file can't be opened for reading but its
|
||||
// owner may still set xattrs on it, so try opening it for
|
||||
// writing instead (which can't succeed for a directory).
|
||||
if wfd, werr := o.fs.openFile(o.path, os.O_WRONLY, 0); werr == nil {
|
||||
fd, err = wfd, nil
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open for xattr: %w", err)
|
||||
}
|
||||
defer fs.CheckClose(fd, &err)
|
||||
}
|
||||
err = xattr.FSet(fd, k, v)
|
||||
case o.fs.opt.FollowSymlinks:
|
||||
err = xattr.Set(o.path, k, v)
|
||||
} else {
|
||||
default:
|
||||
err = xattr.LSet(o.path, k, v)
|
||||
}
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
//go:build !openbsd && !plan9
|
||||
|
||||
package local
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/pkg/xattr"
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fstest"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestXattrThroughPlantedSymlinkBlocked checks user metadata (xattrs)
|
||||
// can't be written outside the root through a planted symlink with
|
||||
// --links, while in-tree writes still work.
|
||||
func TestXattrThroughPlantedSymlinkBlocked(t *testing.T) {
|
||||
if !xattrSupported {
|
||||
t.Skip("xattrs not supported on this OS")
|
||||
}
|
||||
skipIfNoSymlinks(t)
|
||||
ctx := context.Background()
|
||||
|
||||
r := fstest.NewRun(t)
|
||||
f := r.Flocal.(*Fs)
|
||||
linksMode(f)
|
||||
|
||||
metadata := fs.Metadata{
|
||||
"pwned": "attacker-controlled-value",
|
||||
}
|
||||
|
||||
// Control: an in-tree directory gets the xattr as normal.
|
||||
_, err := f.MkdirMetadata(ctx, "sub", metadata)
|
||||
require.NoError(t, err)
|
||||
if f.xattrSupported.Load() == 0 {
|
||||
t.Skip("xattrs not supported on this filesystem")
|
||||
}
|
||||
v, err := xattr.LGet(filepath.Join(f.root, "sub"), "user.pwned")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "attacker-controlled-value", string(v))
|
||||
|
||||
// A directory outside the destination, with a pre-existing child,
|
||||
// whose xattrs the attacker targets.
|
||||
evil := t.TempDir()
|
||||
evilDir := filepath.Join(evil, "secret.d")
|
||||
require.NoError(t, os.Mkdir(evilDir, 0700))
|
||||
evilSub := filepath.Join(evilDir, "sub")
|
||||
require.NoError(t, os.Mkdir(evilSub, 0700))
|
||||
|
||||
// The planted symlink dst/pwn -> outside, faithfully reproduced by --links.
|
||||
require.NoError(t, putLink(ctx, f, "pwn", evilDir))
|
||||
|
||||
// The source now presents "pwn/sub" as a directory with attacker-chosen
|
||||
// user metadata. Applying it must not reach through the planted symlink.
|
||||
_, err = f.MkdirMetadata(ctx, "pwn/sub", metadata)
|
||||
require.Error(t, err, "applying metadata through a planted symlink should be refused")
|
||||
|
||||
_, err = xattr.LGet(evilSub, "user.pwned")
|
||||
require.Error(t, err, "xattr escaped through planted symlink to %q", evilSub)
|
||||
}
|
||||
|
||||
// TestXattrWriteOnlyFile checks user metadata can still be set on a
|
||||
// write-only file with --links, where the confined open can't read it.
|
||||
func TestXattrWriteOnlyFile(t *testing.T) {
|
||||
if !xattrSupported {
|
||||
t.Skip("xattrs not supported on this OS")
|
||||
}
|
||||
skipIfNoSymlinks(t)
|
||||
ctx := context.Background()
|
||||
|
||||
r := fstest.NewRun(t)
|
||||
f := r.Flocal.(*Fs)
|
||||
linksMode(f)
|
||||
|
||||
require.NoError(t, putFile(ctx, f, "wo.txt", "write only"))
|
||||
path := filepath.Join(f.root, "wo.txt")
|
||||
require.NoError(t, os.Chmod(path, 0200))
|
||||
|
||||
obj, err := f.NewObject(ctx, "wo.txt")
|
||||
require.NoError(t, err)
|
||||
o := obj.(*Object)
|
||||
err = o.setXattr(fs.Metadata{"potato": "chips"})
|
||||
require.NoError(t, err)
|
||||
if f.xattrSupported.Load() == 0 {
|
||||
t.Skip("xattrs not supported on this filesystem")
|
||||
}
|
||||
// Reading xattrs needs read permission
|
||||
require.NoError(t, os.Chmod(path, 0600))
|
||||
v, err := xattr.LGet(path, "user.potato")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "chips", string(v))
|
||||
}
|
||||
@@ -208,6 +208,24 @@ func (d Du) GetName() xml.Name {
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// apiHeaders are the NetStorage API request headers which carry the
|
||||
// account name, the request signature and the signed action. They must
|
||||
// not be forwarded when a redirect leaves the configured host.
|
||||
//
|
||||
// The action header is sent uncanonicalised, hence the "*" prefix.
|
||||
var apiHeaders = []string{"X-Akamai-ACS-Auth-Data", "X-Akamai-ACS-Auth-Sign", "*X-Akamai-ACS-Action"}
|
||||
|
||||
// newClient makes the http client used for all NetStorage requests.
|
||||
//
|
||||
// The signer adds the API headers to every request, so the client
|
||||
// strips them on cross host redirects and refuses an HTTPS to HTTP
|
||||
// downgrade.
|
||||
func newClient(ctx context.Context) *http.Client {
|
||||
client := fshttp.NewClient(ctx)
|
||||
client.CheckRedirect = rest.StripHeadersOnCrossHostRedirectFn(apiHeaders...)
|
||||
return client
|
||||
}
|
||||
|
||||
// NewFs creates a new Fs object from the name and root. It connects to
|
||||
// the host specified in the config file.
|
||||
//
|
||||
@@ -240,7 +258,7 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client := fshttp.NewClient(ctx)
|
||||
client := newClient(ctx)
|
||||
|
||||
f := &Fs{
|
||||
name: name,
|
||||
|
||||
@@ -4,12 +4,17 @@ import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/config/configmap"
|
||||
"github.com/rclone/rclone/fs/config/obscure"
|
||||
"github.com/rclone/rclone/fs/object"
|
||||
"github.com/rclone/rclone/lib/rest"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@@ -59,3 +64,142 @@ func TestListResumeCannotChangeHost(t *testing.T) {
|
||||
assert.Equal(t, 1, listRequests, "list request sent to the configured host")
|
||||
assert.Equal(t, 0, requests, "request sent to the other host")
|
||||
}
|
||||
|
||||
// apiTestHeaders is a deliberately literal copy of apiHeaders, without
|
||||
// the "*" prefix, so that a header dropped from the production list
|
||||
// shows up as a leak in the cross host tests rather than silently
|
||||
// losing coverage.
|
||||
var apiTestHeaders = []string{"X-Akamai-ACS-Auth-Data", "X-Akamai-ACS-Auth-Sign", "X-Akamai-ACS-Action"}
|
||||
|
||||
// statXML is a minimal stat response saying the root is a directory
|
||||
const statXML = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<stat directory="/dir"><file type="dir" name="dir" mtime="1"/></stat>`
|
||||
|
||||
// newTestFs makes an Fs via NewFs pointing at serverURL.
|
||||
//
|
||||
// NewFs makes a stat request for the root and treats any failure as
|
||||
// the root not existing, so callers check what the servers received
|
||||
// or make a further request rather than relying on its error.
|
||||
func newTestFs(ctx context.Context, t *testing.T, serverURL string) *Fs {
|
||||
u, err := url.Parse(serverURL)
|
||||
require.NoError(t, err)
|
||||
m := configmap.Simple{
|
||||
"type": "netstorage",
|
||||
"protocol": u.Scheme,
|
||||
"host": u.Host + "/dir",
|
||||
"account": "test-account",
|
||||
"secret": obscure.MustObscure("test-secret"),
|
||||
}
|
||||
f, err := NewFs(ctx, "netstorage-test", "", m)
|
||||
require.NoError(t, err)
|
||||
return f.(*Fs)
|
||||
}
|
||||
|
||||
// assertAPIHeaders checks all the API headers are present (want) or
|
||||
// absent (!want) in r.
|
||||
func assertAPIHeaders(t *testing.T, r *http.Request, want bool) {
|
||||
for _, header := range apiTestHeaders {
|
||||
if want {
|
||||
assert.NotEmpty(t, r.Header.Get(header), "%s should be sent", header)
|
||||
} else {
|
||||
assert.Empty(t, r.Header.Get(header), "%s should have been stripped", header)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestRedirectStripsAPIHeadersOnCrossHost checks the API headers are
|
||||
// sent to the configured host but not to another host it redirects to.
|
||||
func TestRedirectStripsAPIHeadersOnCrossHost(t *testing.T) {
|
||||
var otherHits atomic.Int32
|
||||
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
otherHits.Add(1)
|
||||
assertAPIHeaders(t, r, false)
|
||||
_, _ = w.Write([]byte(statXML))
|
||||
}))
|
||||
defer other.Close()
|
||||
|
||||
var originHits atomic.Int32
|
||||
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
originHits.Add(1)
|
||||
assertAPIHeaders(t, r, true)
|
||||
http.Redirect(w, r, other.URL+r.URL.Path, http.StatusTemporaryRedirect)
|
||||
}))
|
||||
defer origin.Close()
|
||||
|
||||
newTestFs(context.Background(), t, origin.URL)
|
||||
assert.Equal(t, int32(1), originHits.Load())
|
||||
assert.Equal(t, int32(1), otherHits.Load())
|
||||
}
|
||||
|
||||
// TestUploadStripsAPIHeadersOnCrossHost checks an upload, which
|
||||
// carries the API headers on the PUT as well as in the trailers, does
|
||||
// not send them to another host the configured host redirects to.
|
||||
func TestUploadStripsAPIHeadersOnCrossHost(t *testing.T) {
|
||||
var otherHits atomic.Int32
|
||||
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
otherHits.Add(1)
|
||||
assertAPIHeaders(t, r, false)
|
||||
_, _ = w.Write([]byte(statXML))
|
||||
}))
|
||||
defer other.Close()
|
||||
|
||||
var originHits atomic.Int32
|
||||
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
originHits.Add(1)
|
||||
assertAPIHeaders(t, r, true)
|
||||
http.Redirect(w, r, other.URL+r.URL.Path, http.StatusMovedPermanently)
|
||||
}))
|
||||
defer origin.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
f := newTestFs(ctx, t, origin.URL)
|
||||
o := &Object{fs: f, remote: "file"}
|
||||
src := object.NewStaticObjectInfo("file", time.Now(), 4, true, nil, f)
|
||||
err := o.netStorageUploadRequest(ctx, strings.NewReader("data"), src)
|
||||
require.NoError(t, err)
|
||||
// NewFs stat, PUT and the stat after the upload
|
||||
assert.Equal(t, int32(3), originHits.Load())
|
||||
assert.Equal(t, int32(3), otherHits.Load())
|
||||
}
|
||||
|
||||
// TestRedirectKeepsAPIHeadersOnSameHost checks the API headers are
|
||||
// still sent after a redirect which stays on the configured host.
|
||||
func TestRedirectKeepsAPIHeadersOnSameHost(t *testing.T) {
|
||||
var hits atomic.Int32
|
||||
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits.Add(1)
|
||||
assertAPIHeaders(t, r, true)
|
||||
if !strings.HasSuffix(r.URL.Path, "/moved") {
|
||||
http.Redirect(w, r, r.URL.Path+"/moved", http.StatusTemporaryRedirect)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(statXML))
|
||||
}))
|
||||
defer origin.Close()
|
||||
|
||||
newTestFs(context.Background(), t, origin.URL)
|
||||
assert.Equal(t, int32(2), hits.Load())
|
||||
}
|
||||
|
||||
// TestRedirectRefusesHTTPSDowngrade checks a redirect from HTTPS to
|
||||
// plaintext HTTP is not followed.
|
||||
func TestRedirectRefusesHTTPSDowngrade(t *testing.T) {
|
||||
var targetHits atomic.Int32
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
targetHits.Add(1)
|
||||
_, _ = w.Write([]byte(statXML))
|
||||
}))
|
||||
defer target.Close()
|
||||
|
||||
origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, target.URL+r.URL.Path, http.StatusTemporaryRedirect)
|
||||
}))
|
||||
defer origin.Close()
|
||||
|
||||
ctx, ci := fs.AddConfig(context.Background())
|
||||
ci.InsecureSkipVerify = true
|
||||
f := newTestFs(ctx, t, origin.URL)
|
||||
_, err := f.netStorageStatRequest(ctx, f.url(""), true)
|
||||
require.ErrorIs(t, err, rest.ErrHTTPSDowngrade)
|
||||
assert.Equal(t, int32(0), targetHits.Load())
|
||||
}
|
||||
+273
-40
@@ -41,6 +41,7 @@ import (
|
||||
"github.com/rclone/rclone/lib/oauthutil"
|
||||
"github.com/rclone/rclone/lib/pacer"
|
||||
"github.com/rclone/rclone/lib/rest"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -844,19 +845,33 @@ type Options struct {
|
||||
|
||||
// Fs represents a remote OneDrive
|
||||
type Fs struct {
|
||||
name string // name of this remote
|
||||
root string // the path we are working on
|
||||
opt Options // parsed options
|
||||
ci *fs.ConfigInfo // global config
|
||||
features *fs.Features // optional features
|
||||
srv *rest.Client // the connection to the OneDrive server
|
||||
unAuth *rest.Client // no authentication connection to the OneDrive server
|
||||
dirCache *dircache.DirCache // Map of directory path to directory id
|
||||
pacer *fs.Pacer // pacer for API calls
|
||||
tokenRenewer *oauthutil.Renew // renew the token on expiry
|
||||
driveID string // ID to use for querying Microsoft Graph
|
||||
driveType string // https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/drive
|
||||
hashType hash.Type // type of the hash we are using
|
||||
name string // name of this remote
|
||||
root string // the path we are working on
|
||||
opt Options // parsed options
|
||||
ci *fs.ConfigInfo // global config
|
||||
features *fs.Features // optional features
|
||||
srv *rest.Client // the connection to the OneDrive server
|
||||
unAuth *rest.Client // no authentication connection to the OneDrive server
|
||||
dirCache *dircache.DirCache // Map of directory path to directory id
|
||||
pacer *fs.Pacer // pacer for API calls
|
||||
tokenRenewer *oauthutil.Renew // renew the token on expiry
|
||||
tokenSource *oauthutil.TokenSource // source of the API token
|
||||
sharePoint *sharePointClients // authenticated clients for SharePoint hosts
|
||||
driveID string // ID to use for querying Microsoft Graph
|
||||
driveType string // https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/drive
|
||||
hashType hash.Type // type of the hash we are using
|
||||
}
|
||||
|
||||
// sharePointClients holds the clients authenticated for SharePoint hosts
|
||||
type sharePointClients struct {
|
||||
mu sync.Mutex
|
||||
hosts map[string]sharePointAuth
|
||||
}
|
||||
|
||||
// sharePointAuth is a client authenticated for a SharePoint host
|
||||
type sharePointAuth struct {
|
||||
client *rest.Client
|
||||
tokenSource oauth2.TokenSource
|
||||
}
|
||||
|
||||
// Object describes a OneDrive object
|
||||
@@ -1076,6 +1091,154 @@ func errorHandler(resp *http.Response) error {
|
||||
return errResponse
|
||||
}
|
||||
|
||||
// errPreauthRetired explains an authentication failure on a URL which
|
||||
// SharePoint used to return pre-authenticated.
|
||||
var errPreauthRetired = errors.New("SharePoint refused to authenticate a request - Microsoft is retiring pre-authenticated (tempauth) URLs, see https://rclone.org/onedrive/#pre-authenticated-urls")
|
||||
|
||||
// sharePointDomains are the domains of SharePoint Online in the
|
||||
// different Microsoft clouds
|
||||
var sharePointDomains = []string{".sharepoint.com", ".sharepoint.us", ".sharepoint-mil.us", ".sharepoint.cn", ".sharepoint.de"}
|
||||
|
||||
// stripTempauth removes the tempauth parameter from the URLs the API
|
||||
// returns, which simulates the retirement of pre-authenticated URLs
|
||||
// in tests.
|
||||
var stripTempauth = false
|
||||
|
||||
// returnedURL processes a URL returned by the API before use
|
||||
func returnedURL(rawURL string) string {
|
||||
if !stripTempauth {
|
||||
return rawURL
|
||||
}
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return rawURL
|
||||
}
|
||||
q := u.Query()
|
||||
q.Del("tempauth")
|
||||
u.RawQuery = q.Encode()
|
||||
return u.String()
|
||||
}
|
||||
|
||||
// urlAuth says how a URL returned by the API is authenticated
|
||||
type urlAuth int
|
||||
|
||||
const (
|
||||
urlAuthNone urlAuth = iota // call without authentication
|
||||
urlAuthAPI // call with the API token
|
||||
urlAuthSharePoint // call with a token for the SharePoint host
|
||||
)
|
||||
|
||||
// apiHost returns the host the API calls made with f.srv go to.
|
||||
func (f *Fs) apiHost() string {
|
||||
endpoint := graphAPIEndpoint[f.opt.Region]
|
||||
if f.opt.TenantURL != "" {
|
||||
endpoint = f.opt.TenantURL
|
||||
}
|
||||
u, err := url.Parse(endpoint)
|
||||
if err != nil || u.Scheme != "https" {
|
||||
return ""
|
||||
}
|
||||
return u.Host
|
||||
}
|
||||
|
||||
// urlAuthFor returns how to authenticate a URL returned by the API,
|
||||
// such as an upload session or an async job monitor.
|
||||
//
|
||||
// Pre-authenticated URLs fail if they are sent an Authorization
|
||||
// header and tokens must not be sent to other hosts, so only HTTPS
|
||||
// URLs without tempauth on the API host or a SharePoint host are
|
||||
// authenticated.
|
||||
func (f *Fs) urlAuthFor(rawURL string) urlAuth {
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil || u.Scheme != "https" || u.Query().Has("tempauth") {
|
||||
return urlAuthNone
|
||||
}
|
||||
if apiHost := f.apiHost(); apiHost != "" && strings.EqualFold(u.Host, apiHost) {
|
||||
return urlAuthAPI
|
||||
}
|
||||
if isSharePointHost(u.Hostname()) {
|
||||
return urlAuthSharePoint
|
||||
}
|
||||
return urlAuthNone
|
||||
}
|
||||
|
||||
// isSharePointHost returns true if host is in a SharePoint Online domain.
|
||||
func isSharePointHost(host string) bool {
|
||||
host = strings.ToLower(host)
|
||||
for _, domain := range sharePointDomains {
|
||||
if strings.HasSuffix(host, domain) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// checkSharePointRedirect stops the SharePoint token being sent to a
|
||||
// host which isn't SharePoint, as the token is added to every request
|
||||
// the client makes.
|
||||
func checkSharePointRedirect(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 10 {
|
||||
return errors.New("stopped after 10 redirects")
|
||||
}
|
||||
if req.URL.Scheme != "https" || !isSharePointHost(req.URL.Hostname()) {
|
||||
return fmt.Errorf("refusing to send a SharePoint token on a redirect to %s://%s", req.URL.Scheme, req.URL.Host)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// clientForURL returns the client to call a URL returned by the API with.
|
||||
func (f *Fs) clientForURL(ctx context.Context, rawURL string) (*rest.Client, error) {
|
||||
switch f.urlAuthFor(rawURL) {
|
||||
case urlAuthAPI:
|
||||
return f.srv, nil
|
||||
case urlAuthSharePoint:
|
||||
u, _ := url.Parse(rawURL)
|
||||
return f.sharePointClient(ctx, u.Host)
|
||||
}
|
||||
return f.unAuth, nil
|
||||
}
|
||||
|
||||
// sharePointClient returns a client authenticated for the SharePoint
|
||||
// host, which upload session and async job monitor URLs need once
|
||||
// they are no longer pre-authenticated.
|
||||
//
|
||||
// The token is got from the existing credentials, which Entra ID
|
||||
// allows for SharePoint as the user has consented to the Graph file
|
||||
// scopes.
|
||||
func (f *Fs) sharePointClient(ctx context.Context, host string) (*rest.Client, error) {
|
||||
if f.tokenSource == nil || f.sharePoint == nil {
|
||||
return nil, fmt.Errorf("%w: no credentials to get a SharePoint token with", errPreauthRetired)
|
||||
}
|
||||
host = strings.ToLower(host)
|
||||
f.sharePoint.mu.Lock()
|
||||
defer f.sharePoint.mu.Unlock()
|
||||
sp, ok := f.sharePoint.hosts[host]
|
||||
if !ok {
|
||||
tokenSource := f.tokenSource.ScopedTokenSource([]string{"https://" + host + "/.default"})
|
||||
client := oauth2.NewClient(oauthutil.Context(ctx, fshttp.NewClient(ctx)), tokenSource)
|
||||
client.CheckRedirect = checkSharePointRedirect
|
||||
sp = sharePointAuth{client: rest.NewClient(client), tokenSource: tokenSource}
|
||||
f.sharePoint.hosts[host] = sp
|
||||
fs.Debugf(f, "Using a SharePoint token for %s", host)
|
||||
}
|
||||
// Get the token now so failures are reported before the client is used
|
||||
if _, err := sp.tokenSource.Token(); err != nil {
|
||||
return nil, fmt.Errorf("%w: failed to get a SharePoint token: %w", errPreauthRetired, err)
|
||||
}
|
||||
return sp.client, nil
|
||||
}
|
||||
|
||||
// checkPreauthRetired adds an explanation to a 401 error from a URL
|
||||
// returned by the API which needs a SharePoint token, as these were
|
||||
// pre-authenticated until Microsoft retired them.
|
||||
func (f *Fs) checkPreauthRetired(rawURL string, resp *http.Response, err error) error {
|
||||
if err == nil || resp == nil || resp.StatusCode != http.StatusUnauthorized ||
|
||||
f.driveType == driveTypePersonal || errors.Is(err, errPreauthRetired) || f.urlAuthFor(rawURL) != urlAuthSharePoint {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("%w: %w", errPreauthRetired, err)
|
||||
}
|
||||
|
||||
func checkUploadChunkSize(cs fs.SizeSuffix) error {
|
||||
const minChunkSize = fs.SizeSuffixBase
|
||||
if cs%chunkSizeMultiple != 0 {
|
||||
@@ -1144,16 +1307,18 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
|
||||
|
||||
ci := fs.GetConfig(ctx)
|
||||
f := &Fs{
|
||||
name: name,
|
||||
root: root,
|
||||
opt: *opt,
|
||||
ci: ci,
|
||||
driveID: opt.DriveID,
|
||||
driveType: opt.DriveType,
|
||||
srv: rest.NewClient(oAuthClient).SetRoot(rootURL),
|
||||
unAuth: rest.NewClient(client).SetRoot(rootURL),
|
||||
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
||||
hashType: QuickXorHashType,
|
||||
name: name,
|
||||
root: root,
|
||||
opt: *opt,
|
||||
ci: ci,
|
||||
driveID: opt.DriveID,
|
||||
driveType: opt.DriveType,
|
||||
srv: rest.NewClient(oAuthClient).SetRoot(rootURL),
|
||||
tokenSource: ts,
|
||||
sharePoint: &sharePointClients{hosts: make(map[string]sharePointAuth)},
|
||||
unAuth: rest.NewClient(client).SetRoot(rootURL),
|
||||
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
||||
hashType: QuickXorHashType,
|
||||
}
|
||||
f.features = (&fs.Features{
|
||||
CaseInsensitive: true,
|
||||
@@ -1725,17 +1890,25 @@ func (f *Fs) waitForJob(ctx context.Context, location string, o *Object) error {
|
||||
var resp *http.Response
|
||||
var err error
|
||||
var body []byte
|
||||
var redirected bool
|
||||
err = f.pacer.Call(func() (bool, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, location, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// The monitor URL needs no authentication, but it should still
|
||||
// go through the configured transport and honour ctx
|
||||
resp, err = f.unAuth.Do(req)
|
||||
client, err := f.clientForURL(ctx, location)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
resp, err = client.Do(req)
|
||||
if err != nil {
|
||||
return fserrors.ShouldRetry(err), err
|
||||
}
|
||||
redirected = resp.Request.URL.String() != req.URL.String()
|
||||
if resp.StatusCode == http.StatusUnauthorized {
|
||||
_ = resp.Body.Close()
|
||||
return false, f.checkPreauthRetired(location, resp, fmt.Errorf("async job monitor: HTTP error %s", resp.Status))
|
||||
}
|
||||
body, err = rest.ReadBody(resp)
|
||||
return fserrors.ShouldRetry(err), err
|
||||
})
|
||||
@@ -1748,6 +1921,11 @@ func (f *Fs) waitForJob(ctx context.Context, location string, o *Object) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("async status result not JSON: %q: %w", body, err)
|
||||
}
|
||||
// An authenticated monitor redirects to the new item when the
|
||||
// job has finished instead of returning its status
|
||||
if status.Status == "" && redirected {
|
||||
status.Status = "completed"
|
||||
}
|
||||
|
||||
switch status.Status {
|
||||
case "failed":
|
||||
@@ -1847,7 +2025,7 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (dst fs.Obj
|
||||
}
|
||||
|
||||
// read location header
|
||||
location := resp.Header.Get("Location")
|
||||
location := returnedURL(resp.Header.Get("Location"))
|
||||
if location == "" {
|
||||
return nil, errors.New("didn't receive location header in copy response")
|
||||
}
|
||||
@@ -1858,6 +2036,10 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (dst fs.Obj
|
||||
fs.Debugf(src, "Server-side copy failed - file not shared between drives")
|
||||
return nil, fs.ErrorCantCopy
|
||||
}
|
||||
if errors.Is(err, errPreauthRetired) {
|
||||
fs.Debugf(src, "Server-side copy can't be monitored - copying another way: %v", err)
|
||||
return nil, fs.ErrorCantCopy
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -2532,16 +2714,23 @@ func (o *Object) openContentPrefer(ctx context.Context, options ...fs.OpenOption
|
||||
return o.openWithRedirect(ctx, &opts)
|
||||
}
|
||||
|
||||
// openWithRedirect downloads via /content style endpoints that 302 to a preauthenticated URL.
|
||||
// openWithRedirect downloads via /content style endpoints that 302 to
|
||||
// a download URL, which is pre-authenticated or needs a SharePoint
|
||||
// token.
|
||||
func (o *Object) openWithRedirect(ctx context.Context, opts *rest.Opts) (in io.ReadCloser, err error) {
|
||||
var resp *http.Response
|
||||
// Make a note of the redirect target as we need to call it without Auth
|
||||
// Make a note of the redirect target as it needs different auth
|
||||
var redirectReq *http.Request
|
||||
opts.CheckRedirect = func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 10 {
|
||||
return errors.New("stopped after 10 redirects")
|
||||
}
|
||||
// Preauthenticated download URLs must not carry the Graph Authorization header.
|
||||
if stripTempauth {
|
||||
if u, err := url.Parse(returnedURL(req.URL.String())); err == nil {
|
||||
req.URL = u
|
||||
}
|
||||
}
|
||||
// Download URLs must not carry the Graph Authorization header.
|
||||
req.Header.Del("Authorization")
|
||||
// Keep Prefer on the redirect when forcing infected download; some SharePoint
|
||||
// endpoints honor it only on the final download request.
|
||||
@@ -2580,17 +2769,24 @@ func (o *Object) openWithRedirect(ctx context.Context, opts *rest.Opts) (in io.R
|
||||
return nil, err
|
||||
}
|
||||
if redirectReq != nil {
|
||||
redirectURL := redirectReq.URL.String()
|
||||
var client *rest.Client
|
||||
client, err = o.fs.clientForURL(ctx, redirectURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = o.fs.pacer.Call(func() (bool, error) {
|
||||
resp, err = o.fs.unAuth.Do(redirectReq)
|
||||
resp, err = client.Do(redirectReq)
|
||||
if err != nil {
|
||||
return shouldRetry(ctx, resp, err)
|
||||
}
|
||||
// unAuth.Do does not check status; treat non-2xx as failure so a malware
|
||||
// Do does not check status; treat non-2xx as failure so a malware
|
||||
// JSON body is not written out as file content.
|
||||
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
|
||||
_ = resp.Body.Close()
|
||||
err = fmt.Errorf("HTTP error %d (%s) %s", resp.StatusCode, resp.Status, strings.TrimSpace(string(body)))
|
||||
err = o.fs.checkPreauthRetired(redirectURL, resp, err)
|
||||
if strings.Contains(string(body), "malwareDetected") || resp.Header.Get("X-Virus-Infected") != "" {
|
||||
err = malwareDownloadError(o.fs.opt.AVOverride, err)
|
||||
}
|
||||
@@ -2612,7 +2808,19 @@ func (o *Object) openWithRedirect(ctx context.Context, opts *rest.Opts) (in io.R
|
||||
// Overwrite size with actual size since size readings from Onedrive is unreliable.
|
||||
o.size = resp.ContentLength
|
||||
}
|
||||
return resp.Body, err
|
||||
return o.checkRange(resp, opts.Options)
|
||||
}
|
||||
|
||||
// checkRange returns the body of a download, checking it is the range
|
||||
// requested in options.
|
||||
func (o *Object) checkRange(resp *http.Response, options []fs.OpenOption) (in io.ReadCloser, err error) {
|
||||
// The size isn't passed as it is unreliable on OneDrive
|
||||
err = rest.CheckContentRange(resp, options, -1)
|
||||
if err != nil {
|
||||
_ = resp.Body.Close()
|
||||
return nil, err
|
||||
}
|
||||
return resp.Body, nil
|
||||
}
|
||||
|
||||
// malwareDownloadError formats an error when the server blocks a malware-flagged file.
|
||||
@@ -2652,12 +2860,16 @@ func (o *Object) getPosition(ctx context.Context, url string) (pos int64, err er
|
||||
}
|
||||
var info api.UploadFragmentResponse
|
||||
var resp *http.Response
|
||||
client, err := o.fs.clientForURL(ctx, url)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
err = o.fs.pacer.Call(func() (bool, error) {
|
||||
resp, err = o.fs.srv.CallJSON(ctx, &opts, nil, &info)
|
||||
resp, err = client.CallJSON(ctx, &opts, nil, &info)
|
||||
return shouldRetry(ctx, resp, err)
|
||||
})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
return 0, o.fs.checkPreauthRetired(url, resp, err)
|
||||
}
|
||||
if len(info.NextExpectedRanges) != 1 {
|
||||
return 0, fmt.Errorf("bad number of ranges in upload position: %v", info.NextExpectedRanges)
|
||||
@@ -2681,6 +2893,10 @@ func (o *Object) uploadFragment(ctx context.Context, url string, start int64, to
|
||||
var resp *http.Response
|
||||
var body []byte
|
||||
skip := int64(0)
|
||||
client, err := o.fs.clientForURL(ctx, url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = o.fs.pacer.Call(func() (bool, error) {
|
||||
toSend := chunkSize - skip
|
||||
opts := rest.Opts{
|
||||
@@ -2692,7 +2908,7 @@ func (o *Object) uploadFragment(ctx context.Context, url string, start int64, to
|
||||
Options: options,
|
||||
}
|
||||
_, _ = chunk.Seek(skip, io.SeekStart)
|
||||
resp, err = o.fs.unAuth.Call(ctx, &opts)
|
||||
resp, err = client.Call(ctx, &opts)
|
||||
if err != nil && resp != nil && resp.StatusCode == http.StatusRequestedRangeNotSatisfiable {
|
||||
fs.Debugf(o, "Received 416 error - reading current position from server: %v", err)
|
||||
pos, posErr := o.getPosition(ctx, url)
|
||||
@@ -2731,7 +2947,7 @@ func (o *Object) uploadFragment(ctx context.Context, url string, start int64, to
|
||||
}
|
||||
return false, nil
|
||||
})
|
||||
return info, err
|
||||
return info, o.fs.checkPreauthRetired(url, resp, err)
|
||||
}
|
||||
|
||||
// cancelUploadSession cancels an upload session
|
||||
@@ -2742,11 +2958,15 @@ func (o *Object) cancelUploadSession(ctx context.Context, url string) (err error
|
||||
NoResponse: true,
|
||||
}
|
||||
var resp *http.Response
|
||||
client, err := o.fs.clientForURL(ctx, url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = o.fs.pacer.Call(func() (bool, error) {
|
||||
resp, err = o.fs.unAuth.Call(ctx, &opts)
|
||||
resp, err = client.Call(ctx, &opts)
|
||||
return shouldRetry(ctx, resp, err)
|
||||
})
|
||||
return
|
||||
return o.fs.checkPreauthRetired(url, resp, err)
|
||||
}
|
||||
|
||||
// uploadMultipart uploads a file using multipart upload
|
||||
@@ -2764,7 +2984,20 @@ func (o *Object) uploadMultipart(ctx context.Context, in io.Reader, src fs.Objec
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
uploadURL := session.UploadURL
|
||||
uploadURL := returnedURL(session.UploadURL)
|
||||
|
||||
// Check a session which needs SharePoint authentication can get it
|
||||
// before reading any data, so it can be uploaded in a single part
|
||||
// instead if it can't.
|
||||
if o.fs.urlAuthFor(uploadURL) == urlAuthSharePoint {
|
||||
if _, err = o.getPosition(ctx, uploadURL); err != nil {
|
||||
if !errors.Is(err, errPreauthRetired) || size >= int64(maxSinglePartSize) {
|
||||
return nil, err
|
||||
}
|
||||
fs.Debugf(o, "Uploading in a single part as the upload session can't be used: %v", err)
|
||||
return o.uploadSinglepart(ctx, in, src, options...)
|
||||
}
|
||||
}
|
||||
|
||||
// Cancel the session if something went wrong
|
||||
defer atexit.OnError(&err, func() {
|
||||
|
||||
@@ -3,6 +3,7 @@ package onedrive
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -44,6 +45,10 @@ const (
|
||||
// https://learn.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_invite?view=odsp-graph-online#http-request-1
|
||||
)
|
||||
|
||||
func init() {
|
||||
flag.BoolVar(&stripTempauth, "strip-tempauth", false, "Remove tempauth from URLs the API returns to simulate the retirement of pre-authenticated URLs")
|
||||
}
|
||||
|
||||
// TestMain drives the tests
|
||||
func TestMain(m *testing.M) {
|
||||
fstest.TestMain(m)
|
||||
@@ -818,3 +823,49 @@ func TestWaitForJobCancel(t *testing.T) {
|
||||
t.Fatal("waitForJob did not return after the context was cancelled")
|
||||
}
|
||||
}
|
||||
|
||||
// TestWaitForJobUnauthorized checks that a monitor URL which refuses
|
||||
// the request fails straight away instead of polling until the timeout.
|
||||
func TestWaitForJobUnauthorized(t *testing.T) {
|
||||
var polls atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
polls.Add(1)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"error": map[string]any{"code": "unauthenticated", "message": "no token"}})
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
f, _ := newChangeNotifyTestFs(t, http.NotFoundHandler())
|
||||
f.unAuth = rest.NewClient(fshttp.NewClient(context.Background()))
|
||||
f.driveType = driveTypeBusiness
|
||||
|
||||
err := f.waitForJob(context.Background(), server.URL+"/monitor", &Object{remote: "file.txt"})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "401")
|
||||
assert.Equal(t, int32(1), polls.Load())
|
||||
}
|
||||
|
||||
// TestWaitForJobRedirectCompleted checks that a monitor which
|
||||
// redirects to the new item, as it does when authenticated, is taken
|
||||
// to mean the job has finished.
|
||||
func TestWaitForJobRedirectCompleted(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/monitor":
|
||||
http.Redirect(w, r, "/item", http.StatusSeeOther)
|
||||
case "/item":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = fmt.Fprint(w, `{"id":"newid","name":"file.txt","size":5,"file":{}}`)
|
||||
default:
|
||||
t.Errorf("unexpected request %s", r.URL)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
f, _ := newChangeNotifyTestFs(t, http.NotFoundHandler())
|
||||
f.unAuth = rest.NewClient(fshttp.NewClient(context.Background()))
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
err := f.waitForJob(ctx, server.URL+"/monitor", &Object{remote: "file.txt", hasMetaData: true})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -13,11 +14,14 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/config/configmap"
|
||||
"github.com/rclone/rclone/fs/object"
|
||||
"github.com/rclone/rclone/lib/oauthutil"
|
||||
"github.com/rclone/rclone/lib/pacer"
|
||||
"github.com/rclone/rclone/lib/rest"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// fragmentServer is a fake OneDrive upload session which records the
|
||||
@@ -66,6 +70,8 @@ func (s *fragmentServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
_, _ = fmt.Fprintf(w, `{"nextExpectedRanges":["%d-%d"]}`, len(s.received), s.size-1)
|
||||
case r.Method == "DELETE" && r.URL.Path == "/upload":
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
default:
|
||||
s.t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
@@ -118,3 +124,327 @@ func TestUploadMultipartSkip(t *testing.T) {
|
||||
assert.Equal(t, 2, s.fragments)
|
||||
assert.Equal(t, 3, s.attempts, "expected one 416, a partial re-send and the final fragment")
|
||||
}
|
||||
|
||||
// TestURLAuthFor checks that tokens are only sent to HTTPS URLs on
|
||||
// the API host or a SharePoint host which aren't pre-authenticated.
|
||||
func TestURLAuthFor(t *testing.T) {
|
||||
const tenant = "https://contoso-my.sharepoint.com/_api"
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
region string
|
||||
tenantURL string
|
||||
url string
|
||||
want urlAuth
|
||||
}{
|
||||
{"graph", "global", "", "https://graph.microsoft.com/v1.0/drives/x/items/y/uploadSession", urlAuthAPI},
|
||||
{"graph case", "global", "", "https://Graph.Microsoft.com/v1.0/monitor/abc", urlAuthAPI},
|
||||
{"graph tempauth", "global", "", "https://graph.microsoft.com/v1.0/upload?tempauth=abc", urlAuthNone},
|
||||
{"graph http", "global", "", "http://graph.microsoft.com/v1.0/upload", urlAuthNone},
|
||||
{"graph other region", "global", "", "https://graph.microsoft.us/v1.0/upload", urlAuthNone},
|
||||
{"graph us", "us", "", "https://graph.microsoft.us/v1.0/upload", urlAuthAPI},
|
||||
{"graph lookalike", "global", "", "https://graph.microsoft.com.example.com/upload", urlAuthNone},
|
||||
{"sharepoint tempauth", "global", "", "https://contoso-my.sharepoint.com/_api/v2.0/upload?guid=x&tempauth=abc", urlAuthNone},
|
||||
{"sharepoint", "global", "", "https://contoso-my.sharepoint.com/_api/v2.0/upload?guid=x", urlAuthSharePoint},
|
||||
{"sharepoint case", "global", "", "https://Contoso.SharePoint.com/_api/v2.0/monitor/abc", urlAuthSharePoint},
|
||||
{"sharepoint us", "us", "", "https://contoso.sharepoint.us/_api/v2.0/upload", urlAuthSharePoint},
|
||||
{"sharepoint cn", "cn", "", "https://contoso.sharepoint.cn/_api/v2.0/upload", urlAuthSharePoint},
|
||||
{"sharepoint http", "global", "", "http://contoso-my.sharepoint.com/_api/v2.0/upload", urlAuthNone},
|
||||
{"sharepoint lookalike", "global", "", "https://contoso.sharepoint.com.example.com/upload", urlAuthNone},
|
||||
{"sharepoint suffix only", "global", "", "https://evilsharepoint.com/upload", urlAuthNone},
|
||||
{"personal", "global", "", "https://api.onedrive.com/rup/abc", urlAuthNone},
|
||||
{"personal upload", "global", "", "https://my.microsoftpersonalcontent.com/personal/abc/_api/v2.0/drive/items/x/uploadSession", urlAuthNone},
|
||||
{"unparseable", "global", "", "https://graph.microsoft.com/%zz", urlAuthNone},
|
||||
{"tenant", "global", tenant, "https://contoso-my.sharepoint.com/_api/v2.0/monitor/abc", urlAuthAPI},
|
||||
{"tenant tempauth", "global", tenant, "https://contoso-my.sharepoint.com/_api/v2.0/upload?tempauth=abc", urlAuthNone},
|
||||
{"tenant graph", "global", tenant, "https://graph.microsoft.com/v1.0/upload", urlAuthNone},
|
||||
{"tenant other sharepoint", "global", tenant, "https://contoso.sharepoint.com/_api/v2.0/upload", urlAuthSharePoint},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := &Fs{}
|
||||
f.opt.Region = tc.region
|
||||
f.opt.TenantURL = tc.tenantURL
|
||||
assert.Equal(t, tc.want, f.urlAuthFor(tc.url))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckSharePointRedirect checks the SharePoint token is only
|
||||
// sent on redirects to SharePoint over HTTPS.
|
||||
func TestCheckSharePointRedirect(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
url string
|
||||
ok bool
|
||||
}{
|
||||
{"https://contoso-my.sharepoint.com/download.aspx", true},
|
||||
{"https://205807-ipv4v6.gr.global.aa-rt.sharepoint.com/download.aspx?tempauth=x", true},
|
||||
{"https://contoso.sharepoint.us/download.aspx", true},
|
||||
{"http://contoso-my.sharepoint.com/download.aspx", false},
|
||||
{"https://contoso.sharepoint.com.example.com/download.aspx", false},
|
||||
{"https://graph.microsoft.com/v1.0/me", false},
|
||||
{"https://example.com/", false},
|
||||
} {
|
||||
req, err := http.NewRequest("GET", tc.url, nil)
|
||||
require.NoError(t, err)
|
||||
err = checkSharePointRedirect(req, nil)
|
||||
if tc.ok {
|
||||
assert.NoError(t, err, tc.url)
|
||||
} else {
|
||||
assert.Error(t, err, tc.url)
|
||||
}
|
||||
}
|
||||
req, err := http.NewRequest("GET", "https://contoso-my.sharepoint.com/", nil)
|
||||
require.NoError(t, err)
|
||||
assert.Error(t, checkSharePointRedirect(req, make([]*http.Request, 10)), "too many redirects")
|
||||
}
|
||||
|
||||
// TestCheckPreauthRetired checks which 401 errors get the explanation.
|
||||
func TestCheckPreauthRetired(t *testing.T) {
|
||||
const sharePointURL = "https://contoso-my.sharepoint.com/_api/v2.0/upload?guid=x"
|
||||
errBase := errors.New("HTTP error 401")
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
driveType string
|
||||
url string
|
||||
status int
|
||||
want bool
|
||||
}{
|
||||
{"sharepoint 401", driveTypeBusiness, sharePointURL, http.StatusUnauthorized, true},
|
||||
{"library 401", driveTypeSharepoint, sharePointURL, http.StatusUnauthorized, true},
|
||||
{"personal 401", driveTypePersonal, sharePointURL, http.StatusUnauthorized, false},
|
||||
{"sharepoint 403", driveTypeBusiness, sharePointURL, http.StatusForbidden, false},
|
||||
{"tempauth 401", driveTypeBusiness, sharePointURL + "&tempauth=abc", http.StatusUnauthorized, false},
|
||||
{"graph 401", driveTypeBusiness, "https://graph.microsoft.com/v1.0/upload", http.StatusUnauthorized, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := &Fs{driveType: tc.driveType}
|
||||
f.opt.Region = "global"
|
||||
err := f.checkPreauthRetired(tc.url, &http.Response{StatusCode: tc.status}, errBase)
|
||||
assert.ErrorIs(t, err, errBase)
|
||||
assert.Equal(t, tc.want, errors.Is(err, errPreauthRetired), "err = %v", err)
|
||||
})
|
||||
}
|
||||
f := &Fs{driveType: driveTypeBusiness}
|
||||
assert.NoError(t, f.checkPreauthRetired(sharePointURL, &http.Response{StatusCode: http.StatusUnauthorized}, nil))
|
||||
assert.ErrorIs(t, f.checkPreauthRetired(sharePointURL, nil, errBase), errBase)
|
||||
}
|
||||
|
||||
// TestSharePointClient checks that the client for a SharePoint host
|
||||
// is authenticated with a token for that host got from the existing
|
||||
// refresh token, which is fetched once and not stored.
|
||||
func TestSharePointClient(t *testing.T) {
|
||||
var scopes []string
|
||||
var auths []string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/token":
|
||||
_ = r.ParseForm()
|
||||
assert.Equal(t, "refresh_token", r.PostForm.Get("grant_type"))
|
||||
assert.Equal(t, "refresh", r.PostForm.Get("refresh_token"))
|
||||
scopes = append(scopes, r.PostForm.Get("scope"))
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = fmt.Fprint(w, `{"access_token":"sharepoint_token","token_type":"Bearer","expires_in":3600}`)
|
||||
case "/upload":
|
||||
auths = append(auths, r.Header.Get("Authorization"))
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = fmt.Fprint(w, `{"nextExpectedRanges":["0-"]}`)
|
||||
case "/redirect":
|
||||
http.Redirect(w, r, "/upload", http.StatusFound)
|
||||
default:
|
||||
t.Errorf("unexpected request %s %s", r.Method, r.URL)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
storedToken := `{"access_token":"graph_token","token_type":"Bearer","refresh_token":"refresh","expiry":"2099-01-01T00:00:00Z"}`
|
||||
m := configmap.Simple{"token": storedToken}
|
||||
ctx := context.Background()
|
||||
_, ts, err := oauthutil.NewClientWithBaseClient(ctx, "remote", m, &oauthutil.Config{
|
||||
ClientID: "client_id",
|
||||
ClientSecret: "client_secret",
|
||||
TokenURL: server.URL + "/token",
|
||||
}, server.Client())
|
||||
require.NoError(t, err)
|
||||
f := &Fs{tokenSource: ts, sharePoint: &sharePointClients{hosts: make(map[string]sharePointAuth)}}
|
||||
|
||||
for range 2 {
|
||||
client, err := f.sharePointClient(ctx, "Contoso-my.sharepoint.com")
|
||||
require.NoError(t, err)
|
||||
_, err = client.Call(ctx, &rest.Opts{Method: "GET", RootURL: server.URL + "/upload"})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
assert.Equal(t, []string{"https://contoso-my.sharepoint.com/.default"}, scopes, "token should be fetched once for the host")
|
||||
assert.Equal(t, []string{"Bearer sharepoint_token", "Bearer sharepoint_token"}, auths)
|
||||
assert.Equal(t, storedToken, m["token"], "the stored token must not change")
|
||||
|
||||
// The token isn't sent on a redirect to a host which isn't SharePoint
|
||||
client, err := f.sharePointClient(ctx, "contoso-my.sharepoint.com")
|
||||
require.NoError(t, err)
|
||||
_, err = client.Call(ctx, &rest.Opts{Method: "GET", RootURL: server.URL + "/redirect"})
|
||||
assert.ErrorContains(t, err, "refusing to send a SharePoint token")
|
||||
assert.Len(t, auths, 2)
|
||||
|
||||
// Without credentials there is no client and the error explains why
|
||||
_, err = (&Fs{}).sharePointClient(ctx, "contoso-my.sharepoint.com")
|
||||
assert.ErrorIs(t, err, errPreauthRetired)
|
||||
}
|
||||
|
||||
// TestUploadSessionFallback checks that an upload session which needs
|
||||
// SharePoint authentication which can't be got is replaced by a single
|
||||
// part upload before any data is read.
|
||||
func TestUploadSessionFallback(t *testing.T) {
|
||||
content := bytes.Repeat([]byte("onedrive"), 1024)
|
||||
var requests []string
|
||||
var uploaded []byte
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests = append(requests, r.Method+" "+r.URL.Path)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case r.Method == "POST" && r.URL.Path == "/root/createUploadSession":
|
||||
_, _ = fmt.Fprint(w, `{"uploadUrl":"https://contoso-my.sharepoint.com/_api/v2.0/upload?guid=x","nextExpectedRanges":["0-"]}`)
|
||||
case r.Method == "PUT" && r.URL.Path == "/root/content":
|
||||
var err error
|
||||
uploaded, err = io.ReadAll(r.Body)
|
||||
require.NoError(t, err)
|
||||
_, _ = fmt.Fprintf(w, `{"id":"fake-id","name":"remote","size":%d,"file":{}}`, len(uploaded))
|
||||
case r.Method == "PATCH":
|
||||
_, _ = fmt.Fprintf(w, `{"id":"fake-id","name":"remote","size":%d,"file":{}}`, len(uploaded))
|
||||
default:
|
||||
t.Errorf("unexpected request %s %s", r.Method, r.URL)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
client := rest.NewClient(server.Client()).SetRoot(server.URL)
|
||||
f := &Fs{
|
||||
ci: fs.GetConfig(context.Background()),
|
||||
srv: client,
|
||||
unAuth: client,
|
||||
driveType: driveTypeBusiness,
|
||||
pacer: fs.NewPacer(context.Background(), pacer.NewDefault(pacer.MinSleep(time.Millisecond), pacer.MaxSleep(10*time.Millisecond))),
|
||||
}
|
||||
f.opt.Region = "global"
|
||||
f.opt.ChunkSize = fs.SizeSuffix(len(content) / 2)
|
||||
o := &Object{fs: f}
|
||||
|
||||
src := object.NewStaticObjectInfo("remote", time.Now(), int64(len(content)), true, nil, nil)
|
||||
_, err := o.uploadMultipart(context.Background(), bytes.NewReader(content), src)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, content, uploaded)
|
||||
assert.Equal(t, []string{"POST /root/createUploadSession", "PUT /root/content"}, requests[:2])
|
||||
}
|
||||
|
||||
// redirectTransport sends every request to the test server, so URLs
|
||||
// on other hosts can be tested.
|
||||
type redirectTransport struct {
|
||||
server *httptest.Server
|
||||
}
|
||||
|
||||
func (t redirectTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
req = req.Clone(req.Context())
|
||||
req.URL.Scheme = "http"
|
||||
req.URL.Host = t.server.Listener.Addr().String()
|
||||
return t.server.Client().Transport.RoundTrip(req)
|
||||
}
|
||||
|
||||
// newDownloadTest returns an Object which downloads content from a
|
||||
// server which handles the /content call with contentHandler and
|
||||
// serves download.aspx with Range support, recording the
|
||||
// Authorization header of each download.
|
||||
func newDownloadTest(t *testing.T, content []byte, contentHandler http.HandlerFunc) (o *Object, auths *[]string) {
|
||||
auths = new([]string)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/items/fake/content":
|
||||
contentHandler(w, r)
|
||||
case "/download.aspx":
|
||||
*auths = append(*auths, r.Header.Get("Authorization"))
|
||||
http.ServeContent(w, r, "", time.Time{}, bytes.NewReader(content))
|
||||
default:
|
||||
t.Errorf("unexpected request %s %s", r.Method, r.URL)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
transport := redirectTransport{server: server}
|
||||
sharePointToken := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: "sharepoint_token"})
|
||||
sharePointHTTP := &http.Client{Transport: &oauth2.Transport{Source: sharePointToken, Base: transport}}
|
||||
f := &Fs{
|
||||
ci: fs.GetConfig(context.Background()),
|
||||
srv: rest.NewClient(server.Client()).SetRoot(server.URL),
|
||||
unAuth: rest.NewClient(&http.Client{Transport: transport}),
|
||||
driveType: driveTypeBusiness,
|
||||
tokenSource: &oauthutil.TokenSource{},
|
||||
sharePoint: &sharePointClients{hosts: map[string]sharePointAuth{
|
||||
"contoso-my.sharepoint.com": {client: rest.NewClient(sharePointHTTP), tokenSource: sharePointToken},
|
||||
}},
|
||||
pacer: fs.NewPacer(context.Background(), pacer.NewDefault(pacer.MinSleep(time.Millisecond), pacer.MaxSleep(10*time.Millisecond))),
|
||||
}
|
||||
f.opt.Region = "global"
|
||||
return &Object{fs: f, id: "fake", size: int64(len(content))}, auths
|
||||
}
|
||||
|
||||
// TestOpenRedirectAuth checks that downloads are redirected to a
|
||||
// pre-authenticated URL without authentication and to a SharePoint
|
||||
// URL with a SharePoint token.
|
||||
func TestOpenRedirectAuth(t *testing.T) {
|
||||
content := []byte("0123456789abcdefghij")
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
location string
|
||||
wantAuth string
|
||||
}{
|
||||
{"tempauth", "https://contoso-my.sharepoint.com/download.aspx?UniqueId=x&tempauth=v1.secret", ""},
|
||||
{"sharepoint", "https://contoso-my.sharepoint.com/download.aspx?UniqueId=x", "Bearer sharepoint_token"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
o, auths := newDownloadTest(t, content, func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, test.location, http.StatusFound)
|
||||
})
|
||||
in, err := o.Open(context.Background(), &fs.RangeOption{Start: 5, End: 9})
|
||||
require.NoError(t, err)
|
||||
got, err := io.ReadAll(in)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, in.Close())
|
||||
assert.Equal(t, "56789", string(got))
|
||||
assert.Equal(t, []string{test.wantAuth}, *auths)
|
||||
})
|
||||
}
|
||||
|
||||
// Without credentials the error explains why
|
||||
o, auths := newDownloadTest(t, content, func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "https://contoso-my.sharepoint.com/download.aspx?UniqueId=x", http.StatusFound)
|
||||
})
|
||||
o.fs.tokenSource = nil
|
||||
_, err := o.Open(context.Background())
|
||||
assert.ErrorIs(t, err, errPreauthRetired)
|
||||
assert.Empty(t, *auths)
|
||||
}
|
||||
|
||||
// TestOpenRangeCheck checks that a download which doesn't return the
|
||||
// requested range is an error rather than wrong data.
|
||||
func TestOpenRangeCheck(t *testing.T) {
|
||||
content := []byte("0123456789abcdefghij")
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
handler http.HandlerFunc
|
||||
wantErr error
|
||||
}{
|
||||
{"ignored", func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write(content)
|
||||
}, fs.ErrorRangeIgnored},
|
||||
{"wrong range", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Range", "bytes 0-4/20")
|
||||
w.WriteHeader(http.StatusPartialContent)
|
||||
_, _ = w.Write(content[:5])
|
||||
}, nil},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
o, _ := newDownloadTest(t, content, test.handler)
|
||||
_, err := o.Open(context.Background(), &fs.RangeOption{Start: 5, End: 9})
|
||||
require.Error(t, err)
|
||||
if test.wantErr != nil {
|
||||
assert.ErrorIs(t, err, test.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -126,6 +126,10 @@ func shouldRetry(ctx context.Context, resp *http.Response, err error) (bool, err
|
||||
if ociError.GetCode() == "RequestTimeout" {
|
||||
return true, err
|
||||
}
|
||||
// Parallel part uploads can collide on the same object
|
||||
if ociError.GetHTTPStatusCode() == http.StatusConflict && ociError.GetCode() == "ConcurrentObjectUpdate" {
|
||||
return true, err
|
||||
}
|
||||
}
|
||||
// Ok, not an oci error, check for generic failure conditions
|
||||
return fserrors.ShouldRetry(err) || fserrors.ShouldRetryHTTP(resp, retryErrorCodes), err
|
||||
|
||||
@@ -102,3 +102,34 @@ func TestGzipEncoding(t *testing.T) {
|
||||
assert.Equal(t, "", md5sum)
|
||||
})
|
||||
}
|
||||
|
||||
// serviceError is a minimal common.ServiceError for shouldRetry
|
||||
type serviceError struct {
|
||||
status int
|
||||
code string
|
||||
}
|
||||
|
||||
func (e serviceError) Error() string { return e.code }
|
||||
func (e serviceError) GetHTTPStatusCode() int { return e.status }
|
||||
func (e serviceError) GetMessage() string { return e.code }
|
||||
func (e serviceError) GetCode() string { return e.code }
|
||||
func (e serviceError) GetOpcRequestID() string { return "" }
|
||||
|
||||
func TestShouldRetryServiceError(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
for _, test := range []struct {
|
||||
status int
|
||||
code string
|
||||
want bool
|
||||
}{
|
||||
{http.StatusConflict, "ConcurrentObjectUpdate", true},
|
||||
{http.StatusConflict, "BucketAlreadyExists", false},
|
||||
{http.StatusRequestTimeout, "RequestTimeout", true},
|
||||
{http.StatusNotFound, "ObjectNotFound", false},
|
||||
} {
|
||||
err := serviceError{status: test.status, code: test.code}
|
||||
retry, gotErr := shouldRetry(ctx, nil, err)
|
||||
assert.Equal(t, test.want, retry, test.code)
|
||||
assert.Equal(t, error(err), gotErr)
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ const (
|
||||
var commandHelp = []fs.CommandHelp{{
|
||||
Name: operationRename,
|
||||
Short: "change the name of an object.",
|
||||
Long: `This command can be used to rename a object.
|
||||
Long: `This command can be used to rename an object.
|
||||
|
||||
Usage example:
|
||||
|
||||
|
||||
@@ -314,6 +314,7 @@ needed. For more information, see Using Your Own Keys for Server-Side Encryption
|
||||
Value: "",
|
||||
Help: "None",
|
||||
}},
|
||||
Sensitive: true,
|
||||
}, {
|
||||
Name: "sse_customer_key_sha256",
|
||||
Help: `If using SSE-C, The optional header that specifies the base64-encoded SHA256 hash of the encryption
|
||||
@@ -324,6 +325,7 @@ Server-Side Encryption (https://docs.cloud.oracle.com/Content/Object/Tasks/using
|
||||
Value: "",
|
||||
Help: "None",
|
||||
}},
|
||||
Sensitive: true,
|
||||
}, {
|
||||
Name: "sse_kms_key_id",
|
||||
Help: `if using your own master key in vault, this header specifies the
|
||||
@@ -335,6 +337,7 @@ Please note only one of sse_customer_key_file|sse_customer_key|sse_kms_key_id is
|
||||
Value: "",
|
||||
Help: "None",
|
||||
}},
|
||||
Sensitive: true,
|
||||
}, {
|
||||
Name: "sse_customer_algorithm",
|
||||
Help: `If using SSE-C, the optional header that specifies "AES256" as the encryption algorithm.
|
||||
|
||||
@@ -21,7 +21,6 @@ import (
|
||||
"github.com/rclone/rclone/backend/pikpak/api"
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/config/configmap"
|
||||
"github.com/rclone/rclone/fs/fserrors"
|
||||
"github.com/rclone/rclone/lib/multipart"
|
||||
"github.com/rclone/rclone/lib/rest"
|
||||
)
|
||||
@@ -541,7 +540,6 @@ type CaptchaTokenSource struct {
|
||||
m configmap.Mapper
|
||||
opt *Options
|
||||
token *api.CaptchaToken
|
||||
ctx context.Context
|
||||
rst *pikpakClient
|
||||
}
|
||||
|
||||
@@ -560,7 +558,6 @@ func newCaptchaTokenSource(ctx context.Context, opt *Options, m configmap.Mapper
|
||||
m: m,
|
||||
opt: opt,
|
||||
token: token,
|
||||
ctx: ctx,
|
||||
rst: newPikpakClient(getClient(ctx, opt), opt),
|
||||
}
|
||||
}
|
||||
@@ -581,7 +578,7 @@ func (cts *CaptchaTokenSource) requestToken(ctx context.Context, req *api.Captch
|
||||
return
|
||||
}
|
||||
|
||||
func (cts *CaptchaTokenSource) refreshToken(opts *rest.Opts) (string, error) {
|
||||
func (cts *CaptchaTokenSource) refreshToken(ctx context.Context, opts *rest.Opts) (string, error) {
|
||||
oldToken := ""
|
||||
if cts.token != nil {
|
||||
oldToken = cts.token.CaptchaToken
|
||||
@@ -593,7 +590,7 @@ func (cts *CaptchaTokenSource) refreshToken(opts *rest.Opts) (string, error) {
|
||||
action = fmt.Sprintf("%s:%s", opts.Method, u.Path)
|
||||
}
|
||||
req := newCaptchaTokenRequest(action, oldToken, cts.opt)
|
||||
if err := cts.requestToken(cts.ctx, req); err != nil {
|
||||
if err := cts.requestToken(ctx, req); err != nil {
|
||||
return "", fmt.Errorf("failed to retrieve captcha token from api: %w", err)
|
||||
}
|
||||
|
||||
@@ -614,13 +611,18 @@ func (cts *CaptchaTokenSource) Invalidate() {
|
||||
}
|
||||
|
||||
// Token returns a valid captcha token
|
||||
func (cts *CaptchaTokenSource) Token(opts *rest.Opts) (string, error) {
|
||||
//
|
||||
// ctx is the context of the request needing the token, not the one the Fs was
|
||||
// created with: reusing a long-lived context here means one cancelled context
|
||||
// (e.g. at Fs creation) fails every later refresh with "context canceled" and
|
||||
// the mount never recovers.
|
||||
func (cts *CaptchaTokenSource) Token(ctx context.Context, opts *rest.Opts) (string, error) {
|
||||
cts.mu.Lock()
|
||||
defer cts.mu.Unlock()
|
||||
if cts.token.Valid() {
|
||||
return cts.token.CaptchaToken, nil
|
||||
}
|
||||
return cts.refreshToken(opts)
|
||||
return cts.refreshToken(ctx, opts)
|
||||
}
|
||||
|
||||
// pikpakClient wraps rest.Client with a handle of captcha token
|
||||
@@ -667,9 +669,12 @@ func (c *pikpakClient) SetCaptchaTokener(ctx context.Context, m configmap.Mapper
|
||||
|
||||
func (c *pikpakClient) CallJSON(ctx context.Context, opts *rest.Opts, request any, response any) (resp *http.Response, err error) {
|
||||
if c.captcha != nil {
|
||||
token, err := c.captcha.Token(opts)
|
||||
token, err := c.captcha.Token(ctx, opts)
|
||||
if err != nil || token == "" {
|
||||
return nil, fserrors.FatalError(fmt.Errorf("couldn't get captcha token: %v", err))
|
||||
// Not fatal: a failed fetch used to be final for the whole process,
|
||||
// leaving a running mount broken until it was restarted. Let the
|
||||
// normal retry machinery handle it.
|
||||
return nil, fmt.Errorf("couldn't get captcha token: %v", err)
|
||||
}
|
||||
if opts.ExtraHeaders == nil {
|
||||
opts.ExtraHeaders = make(map[string]string)
|
||||
|
||||
@@ -193,6 +193,16 @@ func init() {
|
||||
Help: "Device ID used for authorization.",
|
||||
Advanced: true,
|
||||
Sensitive: true,
|
||||
}, {
|
||||
Name: "captcha_token",
|
||||
Help: "Captcha token - set automatically.",
|
||||
Hide: fs.OptionHideBoth,
|
||||
Sensitive: true,
|
||||
}, {
|
||||
Name: config.ConfigToken,
|
||||
Help: "OAuth Access Token as a JSON blob - set automatically.",
|
||||
Hide: fs.OptionHideBoth,
|
||||
Sensitive: true,
|
||||
}, {
|
||||
Name: "user_agent",
|
||||
Default: defaultUserAgent,
|
||||
|
||||
@@ -6,11 +6,15 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/rclone/rclone/backend/pikpak/api"
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/config/configmap"
|
||||
"github.com/rclone/rclone/lib/pacer"
|
||||
"github.com/rclone/rclone/lib/rest"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@@ -183,3 +187,48 @@ func TestOpenHTTPStatus(t *testing.T) {
|
||||
assert.Equal(t, int32(1), closed.Load())
|
||||
})
|
||||
}
|
||||
|
||||
// TestCaptchaTokenRefreshUsesCallerContext pins the fix for a mount that wedged
|
||||
// permanently: the token source used to keep the ctx the Fs was created with, so
|
||||
// one cancelled ctx there made every later refresh fail with "context canceled",
|
||||
// and the failed fetch was wrapped in fserrors.FatalError so nothing retried.
|
||||
func TestCaptchaTokenRefreshUsesCallerContext(t *testing.T) {
|
||||
var sawCanceled atomic.Bool
|
||||
client := &http.Client{Transport: roundTripperFunc(func(r *http.Request) (*http.Response, error) {
|
||||
sawCanceled.Store(r.Context().Err() != nil)
|
||||
// behave like a real transport: a cancelled context fails the request
|
||||
if err := r.Context().Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"captcha_token":"fresh","expires_in":300}`)),
|
||||
Request: r,
|
||||
}, nil
|
||||
})}
|
||||
m := configmap.Simple{}
|
||||
cts := &CaptchaTokenSource{
|
||||
m: m,
|
||||
opt: &Options{},
|
||||
token: &api.CaptchaToken{},
|
||||
rst: newPikpakClient(client, &Options{}),
|
||||
}
|
||||
opts := &rest.Opts{Method: "GET", RootURL: "https://example.invalid/drive/v1/about"}
|
||||
|
||||
// a cancelled request context must fail this call only
|
||||
cancelled, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_, err := cts.Token(cancelled, opts)
|
||||
require.Error(t, err)
|
||||
require.True(t, sawCanceled.Load(), "request should carry the cancelled caller context")
|
||||
|
||||
// ... and the next call with a live context must recover
|
||||
token, err := cts.Token(context.Background(), opts)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "fresh", token)
|
||||
assert.False(t, sawCanceled.Load(), "request should carry the caller context, not a stored one")
|
||||
value, ok := m.Get("captcha_token")
|
||||
assert.True(t, ok)
|
||||
assert.Contains(t, value, "fresh")
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
package protondrive
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"sync"
|
||||
|
||||
"github.com/ProtonMail/gopenpgp/v3/crypto"
|
||||
"github.com/rclone/rclone/backend/protondrive/api"
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/lib/rest"
|
||||
)
|
||||
|
||||
// unlockMu is held while unlocking account keys. Unlocking is memory
|
||||
// hungry, so unlocks for different sessions run one at a time.
|
||||
var unlockMu sync.Mutex
|
||||
|
||||
// address is one of the user's addresses with its unlocked keys.
|
||||
type address struct {
|
||||
ID string
|
||||
Email string
|
||||
keyRing *crypto.KeyRing // unlocked address keys in the server's order, primary first
|
||||
publicKR *crypto.KeyRing // the public parts of keyRing
|
||||
primaryKeyID string // ID of the first key of keyRing
|
||||
}
|
||||
|
||||
// account is the signed in user's unlocked keys and addresses.
|
||||
type account struct {
|
||||
userKR *crypto.KeyRing // unlocked user keys
|
||||
addresses []*address // the primary address is first
|
||||
|
||||
mu sync.Mutex
|
||||
foreign map[string]*publicKeyLookup // public keys of other users by emailKey
|
||||
}
|
||||
|
||||
// publicKeyLookup is a fetch of another user's public keys, done when
|
||||
// done is closed.
|
||||
type publicKeyLookup struct {
|
||||
done chan struct{}
|
||||
keyRing *crypto.KeyRing
|
||||
err error
|
||||
}
|
||||
|
||||
// loadAccount fetches the user and addresses of the session and unlocks
|
||||
// their keys with keyPassword.
|
||||
//
|
||||
// User keys which don't unlock are skipped, but an error is returned
|
||||
// if none unlocks or if the primary address has no key which unlocks.
|
||||
// Other addresses without a key which unlocks are left out.
|
||||
func loadAccount(ctx context.Context, s *session, keyPassword []byte) (*account, error) {
|
||||
var user api.UserResponse
|
||||
if _, err := s.call(ctx, &rest.Opts{Method: "GET", Path: "/core/v4/users"}, nil, &user); err != nil {
|
||||
return nil, fmt.Errorf("load account: get user: %w", err)
|
||||
}
|
||||
var addrs api.AddressesResponse
|
||||
// The SDK fetches only the first page of 50 addresses.
|
||||
opts := &rest.Opts{Method: "GET", Path: "/core/v4/addresses", Parameters: url.Values{"Page": {"0"}, "PageSize": {"50"}}}
|
||||
if _, err := s.call(ctx, opts, nil, &addrs); err != nil {
|
||||
return nil, fmt.Errorf("load account: get addresses: %w", err)
|
||||
}
|
||||
if len(addrs.Addresses) == 0 {
|
||||
return nil, errors.New("load account: the account has no addresses")
|
||||
}
|
||||
|
||||
unlockMu.Lock()
|
||||
defer unlockMu.Unlock()
|
||||
if s.unlockHook != nil {
|
||||
s.unlockHook()
|
||||
}
|
||||
a := &account{foreign: make(map[string]*publicKeyLookup)}
|
||||
var err error
|
||||
a.userKR, err = unlockUserKeys(user.User.Keys, keyPassword)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load account: unlock user keys: %w", err)
|
||||
}
|
||||
var verifyTime int64
|
||||
if t := s.serverTime(); !t.IsZero() {
|
||||
verifyTime = t.Unix()
|
||||
}
|
||||
for i, addr := range addrs.Addresses {
|
||||
kr, primaryKeyID, err := unlockAddressKeys(addr.Keys, keyPassword, a.userKR, verifyTime)
|
||||
var publicKR *crypto.KeyRing
|
||||
if err == nil {
|
||||
publicKR, err = publicKeyRing(kr)
|
||||
}
|
||||
if err != nil {
|
||||
if i == 0 {
|
||||
a.close()
|
||||
return nil, fmt.Errorf("load account: unlock keys of primary address: %w", err)
|
||||
}
|
||||
fs.Debugf(nil, "protondrive: skipping address %s: %v", addr.ID, err)
|
||||
continue
|
||||
}
|
||||
a.addresses = append(a.addresses, &address{ID: addr.ID, Email: addr.Email, keyRing: kr, publicKR: publicKR, primaryKeyID: primaryKeyID})
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// errKeyPassword is returned when no user key unlocks with the key
|
||||
// password.
|
||||
var errKeyPassword = errors.New("no user key unlocks, is the password right?")
|
||||
|
||||
// unlockUserKeys returns a key ring of the active user keys which
|
||||
// unlock with keyPassword. It wraps errKeyPassword if none does.
|
||||
func unlockUserKeys(keys []api.UserKey, keyPassword []byte) (*crypto.KeyRing, error) {
|
||||
kr, err := crypto.NewKeyRing(nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var lastErr error
|
||||
for _, k := range keys {
|
||||
if k.Active == 0 {
|
||||
continue
|
||||
}
|
||||
unlocked, err := unlockKey(k.PrivateKey, keyPassword)
|
||||
if err == nil {
|
||||
if err = kr.AddKey(unlocked); err != nil {
|
||||
unlocked.ClearPrivateParams()
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
fs.Debugf(nil, "protondrive: can't unlock user key %s: %v", k.ID, err)
|
||||
lastErr = err
|
||||
}
|
||||
}
|
||||
if kr.CountEntities() == 0 {
|
||||
if lastErr == nil {
|
||||
return nil, errors.New("no active user key")
|
||||
}
|
||||
return nil, fmt.Errorf("%w: %w", errKeyPassword, lastErr)
|
||||
}
|
||||
return kr, nil
|
||||
}
|
||||
|
||||
// unlockAddressKeys returns a key ring of the active address keys
|
||||
// which unlock, in the order given, and the ID of the first of them.
|
||||
//
|
||||
// A key with a Token is locked with the passphrase in it, encrypted to
|
||||
// and signed by the user keys in userKR; the signature is checked as
|
||||
// at verifyTime (Unix seconds, or now if zero). A key without a Token
|
||||
// is locked with keyPassword.
|
||||
func unlockAddressKeys(keys []api.AddressKey, keyPassword []byte, userKR *crypto.KeyRing, verifyTime int64) (kr *crypto.KeyRing, firstID string, err error) {
|
||||
kr, err = crypto.NewKeyRing(nil)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
var lastErr error
|
||||
for _, k := range keys {
|
||||
if k.Active == 0 {
|
||||
continue
|
||||
}
|
||||
unlocked, err := unlockAddressKey(k, keyPassword, userKR, verifyTime)
|
||||
if err == nil {
|
||||
if err = kr.AddKey(unlocked); err != nil {
|
||||
unlocked.ClearPrivateParams()
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
fs.Debugf(nil, "protondrive: can't unlock address key %s: %v", k.ID, err)
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
if firstID == "" {
|
||||
firstID = k.ID
|
||||
}
|
||||
}
|
||||
if kr.CountEntities() == 0 {
|
||||
if lastErr == nil {
|
||||
return nil, "", errors.New("no active address key")
|
||||
}
|
||||
return nil, "", fmt.Errorf("no address key unlocks: %w", lastErr)
|
||||
}
|
||||
return kr, firstID, nil
|
||||
}
|
||||
|
||||
// unlockAddressKey unlocks one address key as unlockAddressKeys does.
|
||||
func unlockAddressKey(k api.AddressKey, keyPassword []byte, userKR *crypto.KeyRing, verifyTime int64) (*crypto.Key, error) {
|
||||
if k.Token == "" {
|
||||
return unlockKey(k.PrivateKey, keyPassword)
|
||||
}
|
||||
dh, err := crypto.PGP().Decryption().DecryptionKeys(userKR).New()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res, err := dh.Decrypt([]byte(k.Token), crypto.Armor)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decrypt token: %w", err)
|
||||
}
|
||||
passphrase := res.Bytes()
|
||||
defer clear(passphrase)
|
||||
vb := crypto.PGP().Verify().VerificationKeys(userKR)
|
||||
if verifyTime != 0 {
|
||||
vb = vb.VerifyTime(verifyTime)
|
||||
}
|
||||
vh, err := vb.New()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// As the SDK does, refuse a token without a valid signature.
|
||||
verified, err := vh.VerifyDetached(passphrase, []byte(k.Signature), crypto.Armor)
|
||||
if err == nil {
|
||||
err = verified.SignatureError()
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("verify token: %w", err)
|
||||
}
|
||||
return unlockKey(k.PrivateKey, passphrase)
|
||||
}
|
||||
|
||||
// unlockKey returns the armored private key unlocked with passphrase.
|
||||
func unlockKey(armored string, passphrase []byte) (*crypto.Key, error) {
|
||||
locked, err := crypto.NewKeyFromArmored(armored)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return locked.Unlock(passphrase)
|
||||
}
|
||||
|
||||
// signingKeyRing returns a key ring holding only the first key of the
|
||||
// address, which the SDK calls the primary address key.
|
||||
func (a *address) signingKeyRing() (*crypto.KeyRing, error) {
|
||||
return crypto.NewKeyRing(a.keyRing.GetKeys()[0])
|
||||
}
|
||||
|
||||
// primary returns the primary address.
|
||||
func (a *account) primary() *address {
|
||||
return a.addresses[0]
|
||||
}
|
||||
|
||||
// byID returns the address with the ID id, or nil.
|
||||
func (a *account) byID(id string) *address {
|
||||
for _, addr := range a.addresses {
|
||||
if addr.ID == id {
|
||||
return addr
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// emailKey returns email with ASCII letters lowercased, which is how
|
||||
// emails are compared: Proton treats addresses case-insensitively, but
|
||||
// Unicode case folding would let a non-ASCII letter, such as the Kelvin
|
||||
// sign, stand for an ASCII one.
|
||||
func emailKey(email string) string {
|
||||
b := []byte(email)
|
||||
for i, c := range b {
|
||||
if 'A' <= c && c <= 'Z' {
|
||||
b[i] = c + 'a' - 'A'
|
||||
}
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// byEmail returns the address email, compared as emailKey does, or
|
||||
// nil.
|
||||
func (a *account) byEmail(email string) *address {
|
||||
key := emailKey(email)
|
||||
for _, addr := range a.addresses {
|
||||
if emailKey(addr.Email) == key {
|
||||
return addr
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// owns reports whether email is one of the account's addresses whose
|
||||
// keys it holds, compared as emailKey does.
|
||||
func (a *account) owns(email string) bool {
|
||||
return a.byEmail(email) != nil
|
||||
}
|
||||
|
||||
// apiCaller makes an API call with the semantics of session.call,
|
||||
// without returning the response; client.apiCall is one which paces
|
||||
// and retries.
|
||||
type apiCaller func(ctx context.Context, opts *rest.Opts, request, response any) error
|
||||
|
||||
// publicKeys returns the public keys of the address email, which the
|
||||
// caller must not modify.
|
||||
//
|
||||
// The keys of the user's own addresses, in any ASCII case, come from
|
||||
// the account, never the server. Other users' keys are fetched once
|
||||
// per emailKey and kept for the life of the account; an email without
|
||||
// a Proton address has an empty key ring.
|
||||
func (a *account) publicKeys(ctx context.Context, call apiCaller, email string) (*crypto.KeyRing, error) {
|
||||
if addr := a.byEmail(email); addr != nil {
|
||||
return addr.publicKR, nil
|
||||
}
|
||||
key := emailKey(email)
|
||||
for {
|
||||
a.mu.Lock()
|
||||
l := a.foreign[key]
|
||||
fetcher := l == nil
|
||||
if fetcher {
|
||||
l = &publicKeyLookup{done: make(chan struct{})}
|
||||
a.foreign[key] = l
|
||||
a.mu.Unlock()
|
||||
l.keyRing, l.err = fetchPublicKeys(ctx, call, email)
|
||||
if l.err != nil {
|
||||
// Let the next caller try again.
|
||||
a.forgetLookup(key, l)
|
||||
}
|
||||
close(l.done)
|
||||
} else {
|
||||
a.mu.Unlock()
|
||||
}
|
||||
select {
|
||||
case <-l.done:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
if !fetcher && ctx.Err() == nil && (errors.Is(l.err, context.Canceled) || errors.Is(l.err, context.DeadlineExceeded)) {
|
||||
// The fetching caller gave up, which says nothing of
|
||||
// this one.
|
||||
a.forgetLookup(key, l)
|
||||
continue
|
||||
}
|
||||
return l.keyRing, l.err
|
||||
}
|
||||
}
|
||||
|
||||
// forgetLookup forgets the lookup l of the keys of key, if it is still
|
||||
// the one in use.
|
||||
func (a *account) forgetLookup(key string, l *publicKeyLookup) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.foreign[key] == l {
|
||||
delete(a.foreign, key)
|
||||
}
|
||||
}
|
||||
|
||||
// publicKeyRing returns the public parts of the keys in kr.
|
||||
func publicKeyRing(kr *crypto.KeyRing) (*crypto.KeyRing, error) {
|
||||
pub, err := crypto.NewKeyRing(nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, key := range kr.GetKeys() {
|
||||
pk, err := key.ToPublic()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := pub.AddKey(pk); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return pub, nil
|
||||
}
|
||||
|
||||
// fetchPublicKeys fetches the public keys of the Proton address email
|
||||
// with call.
|
||||
func fetchPublicKeys(ctx context.Context, call apiCaller, email string) (*crypto.KeyRing, error) {
|
||||
kr, err := crypto.NewKeyRing(nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out api.PublicKeysResponse
|
||||
opts := &rest.Opts{Method: "GET", Path: "/core/v4/keys/all", Parameters: url.Values{"Email": {email}, "InternalOnly": {"1"}}}
|
||||
err = call(ctx, opts, nil, &out)
|
||||
var apiErr *api.Error
|
||||
if errors.As(err, &apiErr) && (apiErr.Code == api.CodeAddressMissing || apiErr.Code == api.CodeDomainExternal) {
|
||||
return kr, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get public keys of %s: %w", email, err)
|
||||
}
|
||||
for _, k := range out.Address.Keys {
|
||||
key, err := crypto.NewKeyFromArmored(k.PublicKey)
|
||||
if err == nil {
|
||||
err = kr.AddKey(key)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("public key of %s: %w", email, err)
|
||||
}
|
||||
}
|
||||
return kr, nil
|
||||
}
|
||||
|
||||
// close clears the private key material of the account.
|
||||
func (a *account) close() {
|
||||
if a.userKR != nil {
|
||||
a.userKR.ClearPrivateParams()
|
||||
}
|
||||
for _, addr := range a.addresses {
|
||||
addr.keyRing.ClearPrivateParams()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
package protondrive
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/ProtonMail/gopenpgp/v3/crypto"
|
||||
"github.com/rclone/rclone/backend/protondrive/protontest"
|
||||
"github.com/rclone/rclone/lib/rest"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// newAccountSession returns a session for a new session of u.
|
||||
func newAccountSession(srv *protontest.Server, u *protontest.User) *session {
|
||||
tokens := srv.NewSession(u)
|
||||
store := &memoryStore{creds: credentials{
|
||||
UID: tokens.UID,
|
||||
AccessToken: tokens.AccessToken,
|
||||
RefreshToken: tokens.RefreshToken,
|
||||
KeyPassword: u.KeyPassword(),
|
||||
}}
|
||||
return newSession(srv.Client(), srv.URL(), testAppVersion, store)
|
||||
}
|
||||
|
||||
// sessionCaller returns an apiCaller making unpaced calls with s.
|
||||
func sessionCaller(s *session) apiCaller {
|
||||
return func(ctx context.Context, opts *rest.Opts, request, response any) error {
|
||||
_, err := s.call(ctx, opts, request, response)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// decryptWith decrypts the armored message with kr.
|
||||
func decryptWith(t *testing.T, kr *crypto.KeyRing, armored string) string {
|
||||
t.Helper()
|
||||
dh, err := crypto.PGP().Decryption().DecryptionKeys(kr).New()
|
||||
require.NoError(t, err)
|
||||
res, err := dh.Decrypt([]byte(armored), crypto.Armor)
|
||||
require.NoError(t, err)
|
||||
return string(res.Bytes())
|
||||
}
|
||||
|
||||
func TestLoadAccount(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
u.AddAddress("alias@proton.test")
|
||||
s := newAccountSession(srv, u)
|
||||
|
||||
a, err := loadAccount(context.Background(), s, []byte(u.KeyPassword()))
|
||||
require.NoError(t, err)
|
||||
defer a.close()
|
||||
|
||||
require.NotNil(t, a.userKR)
|
||||
require.Len(t, a.addresses, 2)
|
||||
primary := a.primary()
|
||||
require.NotNil(t, primary)
|
||||
assert.Equal(t, u.Email(), primary.Email)
|
||||
assert.NotEmpty(t, primary.ID)
|
||||
assert.Same(t, primary, a.byID(primary.ID))
|
||||
assert.Same(t, primary, a.byEmail(u.Email()))
|
||||
assert.Nil(t, a.byID("unknown"))
|
||||
assert.Nil(t, a.byEmail("unknown@proton.test"))
|
||||
|
||||
for _, email := range []string{u.Email(), "alias@proton.test"} {
|
||||
addr := a.byEmail(email)
|
||||
require.NotNil(t, addr, email)
|
||||
assert.Equal(t, "secret for "+email, decryptWith(t, addr.keyRing, u.EncryptToAddress(email, []byte("secret for "+email))))
|
||||
}
|
||||
// The address keys are distinct.
|
||||
dh, err := crypto.PGP().Decryption().DecryptionKeys(primary.keyRing).New()
|
||||
require.NoError(t, err)
|
||||
_, err = dh.Decrypt([]byte(u.EncryptToAddress("alias@proton.test", []byte("x"))), crypto.Armor)
|
||||
assert.Error(t, err, "primary address key decrypted a message for the alias")
|
||||
}
|
||||
|
||||
func TestLoadAccountTwoPassword(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddTwoPasswordUser("user", "login", "mailbox")
|
||||
want, err := computeKeyPassword([]byte("mailbox"), u.KeySalt)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, string(want), u.KeyPassword())
|
||||
|
||||
a, err := loadAccount(context.Background(), newAccountSession(srv, u), want)
|
||||
require.NoError(t, err)
|
||||
a.close()
|
||||
}
|
||||
|
||||
func TestLoadAccountWrongKeyPassword(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
s := newAccountSession(srv, u)
|
||||
|
||||
for _, keyPassword := range [][]byte{[]byte("wrong"), nil} {
|
||||
a, err := loadAccount(context.Background(), s, keyPassword)
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, a)
|
||||
assert.Contains(t, err.Error(), "unlock user keys")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadAccountRotatedUserKey(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
u.AddUserKey()
|
||||
|
||||
// The old user key no longer unlocks with the key password, which
|
||||
// must not stop the account loading.
|
||||
a, err := loadAccount(context.Background(), newAccountSession(srv, u), []byte(u.KeyPassword()))
|
||||
require.NoError(t, err)
|
||||
defer a.close()
|
||||
assert.Equal(t, "msg", decryptWith(t, a.primary().keyRing, u.EncryptToAddress(u.Email(), []byte("msg"))))
|
||||
}
|
||||
|
||||
func TestLoadAccountBadAddressKeySignature(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
empty bool
|
||||
}{
|
||||
{"impostor", false},
|
||||
{"empty", true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
|
||||
// On the primary address the account doesn't load.
|
||||
u := srv.AddUser("user", "pass")
|
||||
srv.CorruptAddressKeySignature(u, u.Email(), test.empty)
|
||||
a, err := loadAccount(context.Background(), newAccountSession(srv, u), []byte(u.KeyPassword()))
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, a)
|
||||
assert.Contains(t, err.Error(), "verify token")
|
||||
|
||||
// A secondary address is left out.
|
||||
u = srv.AddUser("user2", "pass")
|
||||
u.AddAddress("alias@proton.test")
|
||||
srv.CorruptAddressKeySignature(u, "alias@proton.test", test.empty)
|
||||
a, err = loadAccount(context.Background(), newAccountSession(srv, u), []byte(u.KeyPassword()))
|
||||
require.NoError(t, err)
|
||||
defer a.close()
|
||||
assert.Nil(t, a.byEmail("alias@proton.test"))
|
||||
assert.Len(t, a.addresses, 1)
|
||||
assert.Equal(t, u.Email(), a.primary().Email)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadAccountSerialised(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
s := newAccountSession(srv, u)
|
||||
|
||||
var active, peak, calls atomic.Int32
|
||||
s.unlockHook = func() {
|
||||
n := active.Add(1)
|
||||
for {
|
||||
p := peak.Load()
|
||||
if n <= p || peak.CompareAndSwap(p, n) {
|
||||
break
|
||||
}
|
||||
}
|
||||
calls.Add(1)
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
active.Add(-1)
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for range 16 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
a, err := loadAccount(context.Background(), s, []byte(u.KeyPassword()))
|
||||
if assert.NoError(t, err) {
|
||||
a.close()
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
assert.Equal(t, int32(16), calls.Load())
|
||||
assert.Equal(t, int32(1), peak.Load(), "unlocks overlapped")
|
||||
}
|
||||
|
||||
func TestAccountClose(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
a, err := loadAccount(context.Background(), newAccountSession(srv, u), []byte(u.KeyPassword()))
|
||||
require.NoError(t, err)
|
||||
a.close()
|
||||
|
||||
for _, kr := range []*crypto.KeyRing{a.userKR, a.primary().keyRing} {
|
||||
for _, key := range kr.GetKeys() {
|
||||
assert.False(t, key.IsPrivate(), "private key material left after close")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicKeysCached(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
other := srv.AddUser("other", "pass")
|
||||
s := newAccountSession(srv, u)
|
||||
a, err := loadAccount(context.Background(), s, []byte(u.KeyPassword()))
|
||||
require.NoError(t, err)
|
||||
defer a.close()
|
||||
otherAccount, err := loadAccount(context.Background(), newAccountSession(srv, other), []byte(other.KeyPassword()))
|
||||
require.NoError(t, err)
|
||||
defer otherAccount.close()
|
||||
|
||||
const route = "GET /core/v4/keys/all"
|
||||
srv.ResetRequests()
|
||||
for range 5 {
|
||||
kr, err := a.publicKeys(context.Background(), sessionCaller(s), other.Email())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, kr.CountEntities())
|
||||
assert.False(t, kr.GetKeys()[0].IsPrivate())
|
||||
// A message encrypted to the key decrypts with other's address key.
|
||||
eh, err := crypto.PGP().Encryption().Recipients(kr).New()
|
||||
require.NoError(t, err)
|
||||
msg, err := eh.Encrypt([]byte("hello"))
|
||||
require.NoError(t, err)
|
||||
armored, err := msg.ArmorBytes()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "hello", decryptWith(t, otherAccount.primary().keyRing, string(armored)))
|
||||
}
|
||||
assert.Equal(t, 1, srv.Requests()[route])
|
||||
|
||||
srv.ResetRequests()
|
||||
var first *crypto.KeyRing
|
||||
for range 5 {
|
||||
kr, err := a.publicKeys(context.Background(), sessionCaller(s), u.Email())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, kr.CountEntities())
|
||||
assert.False(t, kr.GetKeys()[0].IsPrivate())
|
||||
if first == nil {
|
||||
first = kr
|
||||
}
|
||||
assert.Same(t, first, kr, "the own address's public keys are built again")
|
||||
}
|
||||
assert.Zero(t, srv.Requests()[route])
|
||||
|
||||
// An email without a Proton account has no keys, and that is cached too.
|
||||
for range 3 {
|
||||
kr, err := a.publicKeys(context.Background(), sessionCaller(s), "nobody@example.com")
|
||||
require.NoError(t, err)
|
||||
assert.Zero(t, kr.CountEntities())
|
||||
}
|
||||
assert.Equal(t, 1, srv.Requests()[route])
|
||||
|
||||
// Case variants share a lookup, and an own address in any case
|
||||
// never reaches the server.
|
||||
srv.ResetRequests()
|
||||
for _, email := range []string{"OTHER@proton.test", "Other@Proton.Test", strings.ToUpper(u.Email())} {
|
||||
_, err := a.publicKeys(context.Background(), sessionCaller(s), email)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
assert.Zero(t, srv.Requests()[route])
|
||||
}
|
||||
|
||||
func TestPublicKeysErrorNotCached(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
other := srv.AddUser("other", "pass")
|
||||
s := newAccountSession(srv, u)
|
||||
a, err := loadAccount(context.Background(), s, []byte(u.KeyPassword()))
|
||||
require.NoError(t, err)
|
||||
defer a.close()
|
||||
|
||||
srv.Inject(protontest.Fault{Pattern: "/core/v4/keys/all", Times: 1, Status: 500})
|
||||
_, err = a.publicKeys(context.Background(), sessionCaller(s), other.Email())
|
||||
require.Error(t, err)
|
||||
kr, err := a.publicKeys(context.Background(), sessionCaller(s), other.Email())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, kr.CountEntities())
|
||||
}
|
||||
|
||||
func TestSameEmail(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
a, b string
|
||||
same bool
|
||||
}{
|
||||
{"user@proton.me", "user@proton.me", true},
|
||||
{"User@Proton.Me", "uSER@pROTON.mE", true},
|
||||
{"user@proton.me", "user@proton.mee", false},
|
||||
// Unicode case folding would match these to ASCII letters.
|
||||
{"kim@proton.me", "\u212aim@proton.me", false},
|
||||
{"sam@proton.me", "\u017fam@proton.me", false},
|
||||
{"élan@proton.me", "Élan@proton.me", false},
|
||||
} {
|
||||
assert.Equal(t, tc.same, emailKey(tc.a) == emailKey(tc.b), "%q %q", tc.a, tc.b)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublicKeysWaiterRetries checks a caller waiting for another's
|
||||
// fetch of the same keys fetches them itself if the other gave up,
|
||||
// rather than failing with the other's context error.
|
||||
func TestPublicKeysWaiterRetries(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
other := srv.AddUser("other", "pass")
|
||||
s := newAccountSession(srv, u)
|
||||
a, err := loadAccount(context.Background(), s, []byte(u.KeyPassword()))
|
||||
require.NoError(t, err)
|
||||
defer a.close()
|
||||
|
||||
// The lookup as a waiter sees it once the fetching caller's
|
||||
// context ended.
|
||||
l := &publicKeyLookup{done: make(chan struct{}), err: context.Canceled}
|
||||
close(l.done)
|
||||
a.mu.Lock()
|
||||
a.foreign[emailKey(other.Email())] = l
|
||||
a.mu.Unlock()
|
||||
kr, err := a.publicKeys(context.Background(), sessionCaller(s), other.Email())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, kr.CountEntities())
|
||||
}
|
||||
@@ -0,0 +1,705 @@
|
||||
// Package api has the type definitions for the Proton Drive API.
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Response codes returned in the Code field of every API response.
|
||||
//
|
||||
// The names follow ErrorCode in the Proton Drive SDK
|
||||
// (client/js/src/internal/apiService/errorCodes.ts) unless noted.
|
||||
const (
|
||||
CodeOK = 1000
|
||||
CodeOKMany = 1001
|
||||
CodeOKAsync = 1002
|
||||
CodeInvalidRequirements = 2000
|
||||
CodeInvalidValue = 2001
|
||||
CodeNotEnoughPermissions = 2011
|
||||
CodeNotEnoughPermissionsToGrantPermissions = 2026
|
||||
CodeAlreadyExists = 2500
|
||||
CodeNotExists = 2501
|
||||
CodeInsufficientQuota = 200001
|
||||
CodeInsufficientSpace = 200002
|
||||
CodeMaxFileSizeForFreeUser = 200003
|
||||
CodeMaxPublicEditModeForFreeUser = 200004
|
||||
CodeInsufficientVolumeQuota = 200100
|
||||
CodeInsufficientDeviceQuota = 200101
|
||||
CodeAlreadyMemberOfShareInVolumeWithAnotherAddress = 200201
|
||||
CodeTooManyChildren = 200300
|
||||
CodeNestingTooDeep = 200301
|
||||
CodeInsufficientInvitationQuota = 200600
|
||||
CodeInsufficientShareQuota = 200601
|
||||
CodeInsufficientShareJoinedQuota = 200602
|
||||
CodeInsufficientBookmarksQuota = 200800
|
||||
|
||||
// CodeFeatureBlocked is returned when a feature is disabled,
|
||||
// rate-limited or blocked because of abuse (driveTypes.ts).
|
||||
CodeFeatureBlocked = 2028
|
||||
// CodeAppVersionMissing is returned when the request has no app
|
||||
// version (go-proton-api AppVersionMissingCode).
|
||||
CodeAppVersionMissing = 5001
|
||||
// CodeAppVersionBad is returned when the app version is no longer
|
||||
// accepted: "You need to update this app" (coreTypes.ts,
|
||||
// go-proton-api AppVersionBadCode).
|
||||
CodeAppVersionBad = 5003
|
||||
// CodeInvalidSection is returned when a request header such as
|
||||
// x-pm-appversion is malformed.
|
||||
CodeInvalidSection = 2064
|
||||
// CodePasswordWrong is returned when the login credentials are
|
||||
// incorrect (go-proton-api PasswordWrong).
|
||||
CodePasswordWrong = 8002
|
||||
// CodeHumanVerification is returned when a CAPTCHA must be solved.
|
||||
CodeHumanVerification = 9001
|
||||
// CodeRefreshTokenInvalid is returned when the refresh token is
|
||||
// rejected and the session must be established again.
|
||||
CodeRefreshTokenInvalid = 10013
|
||||
// CodeAddressMissing is returned by GET /core/v4/keys/all when no
|
||||
// Proton address has the email (account accountApi.ts).
|
||||
CodeAddressMissing = 33102
|
||||
// CodeDomainExternal is returned by GET /core/v4/keys/all when the
|
||||
// email's domain is not hosted by Proton (account accountApi.ts).
|
||||
CodeDomainExternal = 33103
|
||||
)
|
||||
|
||||
// Error is the body of an unsuccessful API response.
|
||||
type Error struct {
|
||||
Status int `json:"-"` // HTTP status of the response
|
||||
Code int `json:"Code"` // Proton response code
|
||||
Message string `json:"Error"` // human readable message
|
||||
Details json.RawMessage `json:"Details,omitempty"` // request specific details
|
||||
}
|
||||
|
||||
// Error returns the message with its code and HTTP status.
|
||||
func (e *Error) Error() string {
|
||||
return fmt.Sprintf("%s (Code=%d, Status=%d)", e.Message, e.Code, e.Status)
|
||||
}
|
||||
|
||||
// AuthRefreshRequest is the body of POST /auth/v4/refresh.
|
||||
type AuthRefreshRequest struct {
|
||||
ResponseType string `json:"ResponseType"` // always "token"
|
||||
GrantType string `json:"GrantType"` // always "refresh_token"
|
||||
RefreshToken string `json:"RefreshToken"`
|
||||
}
|
||||
|
||||
// AuthRefreshResponse is the response to POST /auth/v4/refresh.
|
||||
type AuthRefreshResponse struct {
|
||||
Code int `json:"Code"`
|
||||
UID string `json:"UID"`
|
||||
AccessToken string `json:"AccessToken"`
|
||||
RefreshToken string `json:"RefreshToken"`
|
||||
}
|
||||
|
||||
// AuthInfoRequest is the body of POST /core/v4/auth/info.
|
||||
type AuthInfoRequest struct {
|
||||
Intent string `json:"Intent"` // always "Proton"
|
||||
Username string `json:"Username"`
|
||||
}
|
||||
|
||||
// AuthInfoResponse is the response to POST /core/v4/auth/info: the
|
||||
// server's SRP challenge.
|
||||
type AuthInfoResponse struct {
|
||||
Code int `json:"Code"`
|
||||
Version int `json:"Version"` // SRP password hashing version
|
||||
Modulus string `json:"Modulus"` // signed base64 SRP modulus
|
||||
ServerEphemeral string `json:"ServerEphemeral"` // base64
|
||||
Salt string `json:"Salt"` // base64 SRP salt
|
||||
SRPSession string `json:"SRPSession"`
|
||||
Username string `json:"Username"`
|
||||
}
|
||||
|
||||
// AuthRequest is the body of POST /core/v4/auth.
|
||||
type AuthRequest struct {
|
||||
Username string `json:"Username"`
|
||||
ClientEphemeral string `json:"ClientEphemeral"` // base64
|
||||
ClientProof string `json:"ClientProof"` // base64
|
||||
SRPSession string `json:"SRPSession"`
|
||||
PersistentCookies int `json:"PersistentCookies"`
|
||||
Payload map[string]string `json:"Payload"`
|
||||
}
|
||||
|
||||
// Values of TwoFAInfo.Enabled, which may be combined.
|
||||
const (
|
||||
TwoFATOTP = 1
|
||||
TwoFAFIDO2 = 2
|
||||
)
|
||||
|
||||
// Values of AuthResponse.PasswordMode.
|
||||
const (
|
||||
PasswordModeOne = 1 // the login password also unlocks the keys
|
||||
PasswordModeTwo = 2 // a separate mailbox password unlocks the keys
|
||||
)
|
||||
|
||||
// TwoFAInfo describes the second factors an account requires.
|
||||
type TwoFAInfo struct {
|
||||
Enabled int `json:"Enabled"` // bitmask of TwoFATOTP and TwoFAFIDO2
|
||||
}
|
||||
|
||||
// AuthResponse is the response to POST /core/v4/auth.
|
||||
type AuthResponse struct {
|
||||
Code int `json:"Code"`
|
||||
UID string `json:"UID"`
|
||||
UserID string `json:"UserID"`
|
||||
AccessToken string `json:"AccessToken"`
|
||||
RefreshToken string `json:"RefreshToken"`
|
||||
TokenType string `json:"TokenType"`
|
||||
ServerProof string `json:"ServerProof"` // base64
|
||||
Scopes []string `json:"Scopes"`
|
||||
PasswordMode int `json:"PasswordMode"`
|
||||
TwoFA TwoFAInfo `json:"2FA"`
|
||||
}
|
||||
|
||||
// Auth2FARequest is the body of POST /core/v4/auth/2fa.
|
||||
type Auth2FARequest struct {
|
||||
TwoFactorCode string `json:"TwoFactorCode"`
|
||||
}
|
||||
|
||||
// KeySalt is the salt of one user key's password.
|
||||
type KeySalt struct {
|
||||
ID string `json:"ID"` // user key ID
|
||||
KeySalt string `json:"KeySalt"` // base64
|
||||
}
|
||||
|
||||
// KeySaltsResponse is the response to GET /core/v4/keys/salts.
|
||||
type KeySaltsResponse struct {
|
||||
Code int `json:"Code"`
|
||||
KeySalts []KeySalt `json:"KeySalts"`
|
||||
}
|
||||
|
||||
// ForkInitResponse is the response to GET /auth/v4/sessions/forks.
|
||||
type ForkInitResponse struct {
|
||||
Code int `json:"Code"`
|
||||
Selector string `json:"Selector"`
|
||||
UserCode string `json:"UserCode"`
|
||||
}
|
||||
|
||||
// ForkStatusResponse is the response to GET
|
||||
// /auth/v4/sessions/forks/{selector} once the user has signed in.
|
||||
type ForkStatusResponse struct {
|
||||
Code int `json:"Code"`
|
||||
Payload string `json:"Payload"` // base64 AES-256-GCM encrypted key password
|
||||
UID string `json:"UID"`
|
||||
AccessToken string `json:"AccessToken"`
|
||||
RefreshToken string `json:"RefreshToken"`
|
||||
}
|
||||
|
||||
// UserKey is one of the user's keys.
|
||||
type UserKey struct {
|
||||
ID string `json:"ID"`
|
||||
Version int `json:"Version"`
|
||||
PrivateKey string `json:"PrivateKey"` // armored, locked with the key password
|
||||
Primary int `json:"Primary"` // 1 for the primary key
|
||||
Active int `json:"Active"` // 0 for a key which must not be unlocked
|
||||
}
|
||||
|
||||
// User is the account of the signed in user.
|
||||
type User struct {
|
||||
ID string `json:"ID"`
|
||||
Name string `json:"Name"`
|
||||
Email string `json:"Email"`
|
||||
Keys []UserKey `json:"Keys"`
|
||||
|
||||
UsedSpace int64 `json:"UsedSpace"` // bytes used by all products
|
||||
MaxSpace int64 `json:"MaxSpace"` // bytes of storage all products share
|
||||
}
|
||||
|
||||
// UserResponse is the response to GET /core/v4/users.
|
||||
type UserResponse struct {
|
||||
Code int `json:"Code"`
|
||||
User User `json:"User"`
|
||||
}
|
||||
|
||||
// AddressKey is one of an address's keys.
|
||||
type AddressKey struct {
|
||||
ID string `json:"ID"`
|
||||
Version int `json:"Version"`
|
||||
PrivateKey string `json:"PrivateKey"` // armored, locked with the passphrase in Token
|
||||
// Token is the armored key passphrase encrypted to the user key,
|
||||
// or empty for a legacy key locked with the key password.
|
||||
Token string `json:"Token"`
|
||||
Signature string `json:"Signature"` // armored detached signature of the passphrase by the user key
|
||||
Primary int `json:"Primary"` // 1 for the primary key
|
||||
Active int `json:"Active"` // 0 for a key which must not be unlocked
|
||||
Flags int `json:"Flags"` // bitmap of key usages
|
||||
}
|
||||
|
||||
// Address is one of the user's email addresses.
|
||||
type Address struct {
|
||||
ID string `json:"ID"`
|
||||
Email string `json:"Email"`
|
||||
Status int `json:"Status"` // 0 disabled, 1 enabled, 2 deleting
|
||||
Type int `json:"Type"` // 1 original, 2 alias, 3 custom, 4 premium, 5 external
|
||||
Priority int `json:"Priority"` // order of the addresses, lowest first
|
||||
Keys []AddressKey `json:"Keys"`
|
||||
}
|
||||
|
||||
// AddressesResponse is the response to GET /core/v4/addresses.
|
||||
type AddressesResponse struct {
|
||||
Code int `json:"Code"`
|
||||
Addresses []Address `json:"Addresses"`
|
||||
}
|
||||
|
||||
// PublicKey is a public key of an address.
|
||||
type PublicKey struct {
|
||||
PublicKey string `json:"PublicKey"` // armored
|
||||
Primary int `json:"Primary"` // 1 for the primary key
|
||||
Flags int `json:"Flags"` // bitmap of key usages
|
||||
Source int `json:"Source"` // 0 for internal keys
|
||||
}
|
||||
|
||||
// PublicKeysResponse is the response to GET /core/v4/keys/all.
|
||||
type PublicKeysResponse struct {
|
||||
Code int `json:"Code"`
|
||||
Address struct {
|
||||
Keys []PublicKey `json:"Keys"`
|
||||
} `json:"Address"`
|
||||
}
|
||||
|
||||
// Link types, as Link.Type encodes them.
|
||||
const (
|
||||
LinkTypeFolder = 1
|
||||
LinkTypeFile = 2
|
||||
LinkTypeAlbum = 3
|
||||
)
|
||||
|
||||
// Link states, as Link.State encodes them.
|
||||
const (
|
||||
LinkStateDraft = 0
|
||||
LinkStateActive = 1
|
||||
LinkStateTrashed = 2
|
||||
)
|
||||
|
||||
// Volume is the summary of a volume in PrimaryRootShareResponseDto.
|
||||
type Volume struct {
|
||||
VolumeID string `json:"VolumeID"`
|
||||
UsedSpace int64 `json:"UsedSpace"`
|
||||
}
|
||||
|
||||
// Share is a share with its key, as ShareDto.
|
||||
type Share struct {
|
||||
ShareID string `json:"ShareID"`
|
||||
CreatorEmail string `json:"CreatorEmail"`
|
||||
Key string `json:"Key"` // armored share key, locked with the passphrase
|
||||
Passphrase string `json:"Passphrase"` // armored, encrypted to the address key
|
||||
PassphraseSignature string `json:"PassphraseSignature"` // armored detached signature by the creator
|
||||
AddressID string `json:"AddressID"` // address whose key decrypts the passphrase
|
||||
}
|
||||
|
||||
// Link is the metadata every node has, as LinkDto. Strings the API
|
||||
// sends as null are empty.
|
||||
type Link struct {
|
||||
LinkID string `json:"LinkID"`
|
||||
Type int `json:"Type"` // LinkTypeFolder, LinkTypeFile or LinkTypeAlbum
|
||||
ParentLinkID string `json:"ParentLinkID"` // empty for a root
|
||||
State int `json:"State"` // LinkStateDraft, LinkStateActive or LinkStateTrashed
|
||||
CreateTime int64 `json:"CreateTime"` // Unix seconds
|
||||
ModifyTime int64 `json:"ModifyTime"` // Unix seconds
|
||||
TrashTime int64 `json:"TrashTime"` // Unix seconds, 0 unless trashed
|
||||
Name string `json:"Name"` // armored, encrypted to the parent key
|
||||
NameHash string `json:"NameHash"` // lower-case hex lookup hash; empty for a root
|
||||
NodeKey string `json:"NodeKey"` // armored, locked with the node passphrase
|
||||
NodePassphrase string `json:"NodePassphrase"`
|
||||
NodePassphraseSignature string `json:"NodePassphraseSignature"`
|
||||
SignatureEmail string `json:"SignatureEmail"` // signer of the key and attributes; empty if anonymous
|
||||
NameSignatureEmail string `json:"NameSignatureEmail"` // signer of the name; empty if anonymous
|
||||
ThirdParty bool `json:"ThirdParty"`
|
||||
Sdk bool `json:"Sdk"`
|
||||
}
|
||||
|
||||
// Folder is the folder part of a node's metadata, as FolderDto.
|
||||
type Folder struct {
|
||||
NodeHashKey string `json:"NodeHashKey"` // armored, encrypted to the node key
|
||||
XAttr string `json:"XAttr"` // armored extended attributes; may be empty
|
||||
IsImported bool `json:"IsImported"`
|
||||
}
|
||||
|
||||
// ActiveRevision is the summary of a file's active revision, as
|
||||
// ActiveRevisionDto.
|
||||
type ActiveRevision struct {
|
||||
RevisionID string `json:"RevisionID"`
|
||||
CreateTime int64 `json:"CreateTime"` // Unix seconds
|
||||
EncryptedSize int64 `json:"EncryptedSize"`
|
||||
ChecksumVerified bool `json:"ChecksumVerified"`
|
||||
ManifestSignature string `json:"ManifestSignature"` // armored
|
||||
XAttr string `json:"XAttr"` // armored extended attributes; may be empty
|
||||
SignatureEmail string `json:"SignatureEmail"` // signer of the revision; empty if anonymous
|
||||
IsImported bool `json:"IsImported"`
|
||||
ThirdParty bool `json:"ThirdParty"`
|
||||
Sdk bool `json:"Sdk"`
|
||||
}
|
||||
|
||||
// File is the file part of a node's metadata, as FileDto.
|
||||
type File struct {
|
||||
ActiveRevision *ActiveRevision `json:"ActiveRevision"` // nil for a draft
|
||||
TotalEncryptedSize int64 `json:"TotalEncryptedSize"`
|
||||
ContentKeyPacket string `json:"ContentKeyPacket"` // base64
|
||||
MediaType string `json:"MediaType"`
|
||||
ContentKeyPacketSignature string `json:"ContentKeyPacketSignature"` // armored; may be empty
|
||||
}
|
||||
|
||||
// LinkDetails is a node's metadata, as FileDetailsDto and
|
||||
// FolderDetailsDto.
|
||||
type LinkDetails struct {
|
||||
Link Link `json:"Link"`
|
||||
Folder *Folder `json:"Folder"` // set for a folder
|
||||
File *File `json:"File"` // set for a file
|
||||
}
|
||||
|
||||
// MyFilesResponse is the response to GET /drive/v2/shares/my-files, as
|
||||
// PrimaryRootShareResponseDto.
|
||||
type MyFilesResponse struct {
|
||||
Code int `json:"Code"`
|
||||
Volume Volume `json:"Volume"`
|
||||
Share Share `json:"Share"`
|
||||
Link LinkDetails `json:"Link"` // the root folder
|
||||
}
|
||||
|
||||
// CreateVolumeRequest is the body of POST /drive/volumes, as
|
||||
// CreateVolumeRequestDto without the deprecated names.
|
||||
type CreateVolumeRequest struct {
|
||||
AddressID string `json:"AddressID"`
|
||||
AddressKeyID string `json:"AddressKeyID"` // the primary key of AddressID
|
||||
ShareKey string `json:"ShareKey"`
|
||||
SharePassphrase string `json:"SharePassphrase"`
|
||||
SharePassphraseSignature string `json:"SharePassphraseSignature"`
|
||||
FolderName string `json:"FolderName"`
|
||||
FolderKey string `json:"FolderKey"`
|
||||
FolderPassphrase string `json:"FolderPassphrase"`
|
||||
FolderPassphraseSignature string `json:"FolderPassphraseSignature"`
|
||||
FolderHashKey string `json:"FolderHashKey"`
|
||||
}
|
||||
|
||||
// ShareReference identifies the main share of a volume and its root,
|
||||
// as ShareReferenceResponseDto.
|
||||
type ShareReference struct {
|
||||
ShareID string `json:"ShareID"`
|
||||
LinkID string `json:"LinkID"`
|
||||
}
|
||||
|
||||
// VolumeDetails is a volume, as VolumeResponseDto.
|
||||
type VolumeDetails struct {
|
||||
ID string `json:"ID"`
|
||||
VolumeID string `json:"VolumeID"`
|
||||
UsedSpace int64 `json:"UsedSpace"`
|
||||
State int `json:"State"`
|
||||
Share ShareReference `json:"Share"`
|
||||
}
|
||||
|
||||
// VolumeResponse is the response to POST /drive/volumes and GET
|
||||
// /drive/volumes/{volumeID}, as GetVolumeResponseDto.
|
||||
type VolumeResponse struct {
|
||||
Code int `json:"Code"`
|
||||
Volume VolumeDetails `json:"Volume"`
|
||||
}
|
||||
|
||||
// LinksRequest is the body of POST /drive/v2/volumes/{volumeID}/links
|
||||
// and /drive/v2/volumes/{volumeID}/trash_multiple, as LinkIDsRequestDto.
|
||||
type LinksRequest struct {
|
||||
LinkIDs []string `json:"LinkIDs"`
|
||||
}
|
||||
|
||||
// LinksResponse is the response to POST
|
||||
// /drive/v2/volumes/{volumeID}/links, as LoadLinkDetailsResponseDto.
|
||||
// Unknown IDs are left out.
|
||||
type LinksResponse struct {
|
||||
Code int `json:"Code"`
|
||||
Links []LinkDetails `json:"Links"`
|
||||
}
|
||||
|
||||
// ChildrenResponse is the response to GET
|
||||
// /drive/v2/volumes/{volumeID}/folders/{linkID}/children, as
|
||||
// ListChildrenResponseDto.
|
||||
type ChildrenResponse struct {
|
||||
Code int `json:"Code"`
|
||||
LinkIDs []string `json:"LinkIDs"`
|
||||
AnchorID string `json:"AnchorID"` // pass as AnchorID for the next page
|
||||
More bool `json:"More"`
|
||||
}
|
||||
|
||||
// CreateFolderRequest is the body of POST
|
||||
// /drive/v2/volumes/{volumeID}/folders, as CreateFolderDto with the
|
||||
// SignatureEmail the SDK sends in place of SignatureAddress.
|
||||
type CreateFolderRequest struct {
|
||||
ParentLinkID string `json:"ParentLinkID"`
|
||||
NodeKey string `json:"NodeKey"`
|
||||
NodeHashKey string `json:"NodeHashKey"`
|
||||
NodePassphrase string `json:"NodePassphrase"`
|
||||
NodePassphraseSignature string `json:"NodePassphraseSignature"`
|
||||
SignatureEmail string `json:"SignatureEmail"`
|
||||
Name string `json:"Name"`
|
||||
Hash string `json:"Hash"`
|
||||
XAttr string `json:"XAttr,omitempty"`
|
||||
}
|
||||
|
||||
// CreateFolderResponse is the response to POST
|
||||
// /drive/v2/volumes/{volumeID}/folders, as CreateFolderResponseDto.
|
||||
type CreateFolderResponse struct {
|
||||
Code int `json:"Code"`
|
||||
Folder struct {
|
||||
ID string `json:"ID"`
|
||||
} `json:"Folder"`
|
||||
}
|
||||
|
||||
// RenameRequest is the body of PUT
|
||||
// /drive/v2/volumes/{volumeID}/links/{linkID}/rename, as
|
||||
// RenameLinkRequestDto.
|
||||
type RenameRequest struct {
|
||||
Name string `json:"Name"` // reusing the session key of the current name
|
||||
Hash string `json:"Hash"`
|
||||
NameSignatureEmail string `json:"NameSignatureEmail"`
|
||||
OriginalHash string `json:"OriginalHash"` // current name hash, which must match
|
||||
}
|
||||
|
||||
// MoveRequest is the body of PUT
|
||||
// /drive/v2/volumes/{volumeID}/links/{linkID}/move, as
|
||||
// MoveLinkV2RequestDto.
|
||||
//
|
||||
// NodePassphraseSignature and SignatureEmail are given if and only if
|
||||
// the node's key is anonymous (has no SignatureEmail).
|
||||
type MoveRequest struct {
|
||||
ParentLinkID string `json:"ParentLinkID"`
|
||||
NodePassphrase string `json:"NodePassphrase"` // reusing the session key of the current passphrase
|
||||
NodePassphraseSignature string `json:"NodePassphraseSignature,omitempty"`
|
||||
SignatureEmail string `json:"SignatureEmail,omitempty"`
|
||||
Name string `json:"Name"` // reusing the session key of the current name
|
||||
NameSignatureEmail string `json:"NameSignatureEmail"`
|
||||
Hash string `json:"Hash"`
|
||||
OriginalHash string `json:"OriginalHash"` // current name hash, which must match
|
||||
}
|
||||
|
||||
// CopyRequest is the body of POST
|
||||
// /drive/volumes/{volumeID}/links/{linkID}/copy, as CopyLinkRequestDto.
|
||||
// The server copies everything else of the node.
|
||||
//
|
||||
// NodePassphraseSignature and SignatureEmail are given if and only if
|
||||
// the node's key is anonymous (has no SignatureEmail).
|
||||
type CopyRequest struct {
|
||||
Name string `json:"Name"` // reusing the session key of the current name
|
||||
NodePassphrase string `json:"NodePassphrase"` // reusing the session key of the current passphrase
|
||||
Hash string `json:"Hash"`
|
||||
TargetVolumeID string `json:"TargetVolumeID"`
|
||||
TargetParentLinkID string `json:"TargetParentLinkID"`
|
||||
NameSignatureEmail string `json:"NameSignatureEmail"`
|
||||
NodePassphraseSignature string `json:"NodePassphraseSignature,omitempty"`
|
||||
SignatureEmail string `json:"SignatureEmail,omitempty"`
|
||||
}
|
||||
|
||||
// CopyResponse is the response to POST
|
||||
// /drive/volumes/{volumeID}/links/{linkID}/copy, as CopyLinkResponseDto.
|
||||
type CopyResponse struct {
|
||||
Code int `json:"Code"`
|
||||
LinkID string `json:"LinkID"` // the new node
|
||||
}
|
||||
|
||||
// LinkResult is the outcome for one link of a request on many.
|
||||
type LinkResult struct {
|
||||
LinkID string `json:"LinkID"`
|
||||
Response struct {
|
||||
Code int `json:"Code"`
|
||||
Error string `json:"Error"`
|
||||
} `json:"Response"`
|
||||
}
|
||||
|
||||
// MultiLinkResponse is the response to a request on many links, such
|
||||
// as POST /drive/v2/volumes/{volumeID}/trash_multiple, as
|
||||
// MultiResponsesPerLinkFactory.
|
||||
type MultiLinkResponse struct {
|
||||
Code int `json:"Code"`
|
||||
Responses []LinkResult `json:"Responses"`
|
||||
}
|
||||
|
||||
// RevisionResponse is the response to GET
|
||||
// /drive/v2/volumes/{volumeID}/files/{linkID}/revisions/{revisionID},
|
||||
// as GetRevisionResponseDto.
|
||||
type RevisionResponse struct {
|
||||
Code int `json:"Code"`
|
||||
Revision Revision `json:"Revision"`
|
||||
}
|
||||
|
||||
// Revision is a revision of a file with a page of its blocks, as
|
||||
// DetailedRevisionResponseDto.
|
||||
type Revision struct {
|
||||
ID string `json:"ID"`
|
||||
ManifestSignature string `json:"ManifestSignature"` // armored
|
||||
Size int64 `json:"Size"` // encrypted size
|
||||
State int `json:"State"`
|
||||
XAttr string `json:"XAttr"` // armored extended attributes; may be empty
|
||||
Blocks []Block `json:"Blocks"`
|
||||
Thumbnails []Thumbnail `json:"Thumbnails"`
|
||||
SignatureEmail string `json:"SignatureEmail"` // signer of the manifest; empty if anonymous
|
||||
CreateTime int64 `json:"CreateTime"` // Unix seconds
|
||||
}
|
||||
|
||||
// Block is a block of a revision with the URL to download it, as
|
||||
// BlockResponseDto.
|
||||
type Block struct {
|
||||
Index int `json:"Index"` // from 1
|
||||
Hash string `json:"Hash"` // base64 SHA-256 of the encrypted block
|
||||
Token string `json:"Token"` // send as pm-storage-token
|
||||
BareURL string `json:"BareURL"` // storage URL of the block
|
||||
}
|
||||
|
||||
// Thumbnail is a thumbnail of a revision, as ThumbnailResponseDto.
|
||||
type Thumbnail struct {
|
||||
ThumbnailID string `json:"ThumbnailID"`
|
||||
Type int `json:"Type"`
|
||||
Hash string `json:"Hash"` // base64 SHA-256 of the encrypted thumbnail
|
||||
Size int64 `json:"Size"`
|
||||
}
|
||||
|
||||
// ConflictDetails are the Details of a CodeAlreadyExists error from
|
||||
// creating a node, naming the node which has the name.
|
||||
type ConflictDetails struct {
|
||||
ConflictLinkID string `json:"ConflictLinkID"`
|
||||
ConflictRevisionID string `json:"ConflictRevisionID"` // active revision; empty for a draft or folder
|
||||
ConflictDraftRevisionID string `json:"ConflictDraftRevisionID"` // draft revision; empty if none
|
||||
ConflictDraftClientUID string `json:"ConflictDraftClientUID"` // ClientUID of the draft revision's creator
|
||||
}
|
||||
|
||||
// CreateFileRequest is the body of POST
|
||||
// /drive/v2/volumes/{volumeID}/files, as CreateFileDto: a draft file.
|
||||
type CreateFileRequest struct {
|
||||
ParentLinkID string `json:"ParentLinkID"`
|
||||
Name string `json:"Name"`
|
||||
Hash string `json:"Hash"`
|
||||
MIMEType string `json:"MIMEType"`
|
||||
ClientUID *string `json:"ClientUID"` // identifies the creator's drafts; null if none
|
||||
IntendedUploadSize *int64 `json:"IntendedUploadSize"` // rounded size for an early quota check; null if unknown
|
||||
NodeKey string `json:"NodeKey"`
|
||||
NodePassphrase string `json:"NodePassphrase"`
|
||||
NodePassphraseSignature string `json:"NodePassphraseSignature"`
|
||||
ContentKeyPacket string `json:"ContentKeyPacket"` // base64
|
||||
ContentKeyPacketSignature string `json:"ContentKeyPacketSignature"` // armored, by the node key
|
||||
SignatureAddress string `json:"SignatureAddress"` // signer of the name and passphrase
|
||||
}
|
||||
|
||||
// CreateFileResponse is the response to POST
|
||||
// /drive/v2/volumes/{volumeID}/files, as CreateDraftFileResponseDto.
|
||||
type CreateFileResponse struct {
|
||||
Code int `json:"Code"`
|
||||
File struct {
|
||||
ID string `json:"ID"`
|
||||
RevisionID string `json:"RevisionID"` // the draft revision
|
||||
} `json:"File"`
|
||||
}
|
||||
|
||||
// CreateRevisionRequest is the body of POST
|
||||
// /drive/v2/volumes/{volumeID}/files/{linkID}/revisions, as
|
||||
// CreateRevisionRequestDto: a draft revision of an active file.
|
||||
type CreateRevisionRequest struct {
|
||||
CurrentRevisionID string `json:"CurrentRevisionID"` // the active revision, which must match
|
||||
ClientUID *string `json:"ClientUID"`
|
||||
IntendedUploadSize *int64 `json:"IntendedUploadSize"`
|
||||
}
|
||||
|
||||
// CreateRevisionResponse is the response to POST
|
||||
// /drive/v2/volumes/{volumeID}/files/{linkID}/revisions.
|
||||
type CreateRevisionResponse struct {
|
||||
Code int `json:"Code"`
|
||||
Revision struct {
|
||||
ID string `json:"ID"`
|
||||
} `json:"Revision"`
|
||||
}
|
||||
|
||||
// VerificationResponse is the response to GET
|
||||
// /drive/v2/volumes/{volumeID}/links/{linkID}/revisions/{revisionID}/verification,
|
||||
// as VerificationData.
|
||||
type VerificationResponse struct {
|
||||
Code int `json:"Code"`
|
||||
VerificationCode string `json:"VerificationCode"` // base64
|
||||
ContentKeyPacket string `json:"ContentKeyPacket"` // base64
|
||||
}
|
||||
|
||||
// BlockUploadRequest is the body of POST /drive/blocks, as
|
||||
// RequestUploadInput without its deprecated fields.
|
||||
type BlockUploadRequest struct {
|
||||
AddressID string `json:"AddressID"` // address signing the blocks
|
||||
VolumeID string `json:"VolumeID"`
|
||||
LinkID string `json:"LinkID"`
|
||||
RevisionID string `json:"RevisionID"`
|
||||
BlockList []BlockUploadInfo `json:"BlockList"`
|
||||
ThumbnailList []struct{} `json:"ThumbnailList"`
|
||||
}
|
||||
|
||||
// BlockUploadInfo is a block to upload, as RequestUploadBlockInput
|
||||
// without its deprecated Size and Hash, which the SDK doesn't send.
|
||||
type BlockUploadInfo struct {
|
||||
Index int `json:"Index"` // from 1, consecutive
|
||||
EncSignature string `json:"EncSignature"` // armored signature of the plaintext, encrypted
|
||||
Verifier BlockVerifier `json:"Verifier"`
|
||||
}
|
||||
|
||||
// BlockVerifier proves a block was encrypted with the right key.
|
||||
type BlockVerifier struct {
|
||||
Token string `json:"Token"` // base64 verification code XOR the start of the encrypted block
|
||||
}
|
||||
|
||||
// BlockUploadResponse is the response to POST /drive/blocks, as
|
||||
// RequestUploadResponse.
|
||||
type BlockUploadResponse struct {
|
||||
Code int `json:"Code"`
|
||||
UploadLinks []UploadLink `json:"UploadLinks"`
|
||||
}
|
||||
|
||||
// UploadLink is the storage URL to upload a block to, as BlockURL.
|
||||
type UploadLink struct {
|
||||
Index int `json:"Index"`
|
||||
BareURL string `json:"BareURL"`
|
||||
Token string `json:"Token"` // send as pm-storage-token
|
||||
}
|
||||
|
||||
// CommitRevisionRequest is the body of PUT
|
||||
// /drive/v2/volumes/{volumeID}/files/{linkID}/revisions/{revisionID},
|
||||
// as CommitRevisionDto without its deprecated fields.
|
||||
type CommitRevisionRequest struct {
|
||||
ManifestSignature string `json:"ManifestSignature"` // armored, of the block hashes in order
|
||||
SignatureAddress string `json:"SignatureAddress"` // signer of the manifest, blocks and attributes
|
||||
XAttr string `json:"XAttr"` // armored extended attributes
|
||||
ChecksumVerified bool `json:"ChecksumVerified"` // whether the SHA1 matched the source's
|
||||
Photo *struct{} `json:"Photo"` // always null outside the photo volume
|
||||
}
|
||||
|
||||
// Volume event types, as Event.EventType encodes them.
|
||||
const (
|
||||
EventDelete = 0 // deleted for good, or no longer accessible
|
||||
EventCreate = 1
|
||||
EventUpdate = 2 // new revision committed
|
||||
EventUpdateMetadata = 3 // renamed, moved, trashed or restored
|
||||
)
|
||||
|
||||
// LatestEventResponse is the response to GET
|
||||
// /drive/volumes/{volumeID}/events/latest, as LatestEventIDResponseDto.
|
||||
type LatestEventResponse struct {
|
||||
Code int `json:"Code"`
|
||||
EventID string `json:"EventID"`
|
||||
}
|
||||
|
||||
// EventLink is the link an event is about, as EventLinkDataDto, in its
|
||||
// state when the events are read rather than when the change was made.
|
||||
type EventLink struct {
|
||||
LinkID string `json:"LinkID"`
|
||||
ParentLinkID string `json:"ParentLinkID"` // empty if null or missing
|
||||
IsShared bool `json:"IsShared"`
|
||||
IsTrashed bool `json:"IsTrashed"`
|
||||
}
|
||||
|
||||
// Event is a change to a link of a volume, as EventV2ResponseDto. It
|
||||
// names the link but not its name or type.
|
||||
type Event struct {
|
||||
EventID string `json:"EventID"`
|
||||
EventType int `json:"EventType"` // EventDelete etc
|
||||
Link EventLink `json:"Link"`
|
||||
}
|
||||
|
||||
// EventsResponse is the response to GET
|
||||
// /drive/v2/volumes/{volumeID}/events/{eventID}, as
|
||||
// ListEventsV2ResponseDto without the sharing fields: the events after
|
||||
// an event ID, oldest first.
|
||||
type EventsResponse struct {
|
||||
Code int `json:"Code"`
|
||||
Events []Event `json:"Events"`
|
||||
EventID string `json:"EventID"` // pass as the event ID of the next call
|
||||
More bool `json:"More"` // whether more events follow EventID
|
||||
Refresh bool `json:"Refresh"` // the event ID asked for is unknown or too old: EventID is the newest
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
package protondrive_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rclone/rclone/backend/protondrive/protontest"
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/config"
|
||||
"github.com/rclone/rclone/fs/object"
|
||||
"github.com/rclone/rclone/fs/operations"
|
||||
fssync "github.com/rclone/rclone/fs/sync"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Routes counted by the request budgets.
|
||||
const (
|
||||
linksRoute = "POST /drive/v2/volumes/{volumeID}/links"
|
||||
revisionDraftRoute = "POST /drive/v2/volumes/{volumeID}/files/{linkID}/revisions"
|
||||
verifierRoute = "GET /drive/v2/volumes/{volumeID}/links/{linkID}/revisions/{revisionID}/verification"
|
||||
blockURLsRoute = "POST /drive/blocks"
|
||||
blockPutRoute = "POST /storage/upload/{token}"
|
||||
commitRoute = "PUT /drive/v2/volumes/{volumeID}/files/{linkID}/revisions/{revisionID}"
|
||||
createFolderRoute = "POST /drive/v2/volumes/{volumeID}/folders"
|
||||
latestEventRoute = "GET /drive/volumes/{volumeID}/events/latest"
|
||||
eventsRoute = "GET /drive/v2/volumes/{volumeID}/events/{eventID}"
|
||||
)
|
||||
|
||||
// TestMain runs the tests, then fails the run if any of them, through
|
||||
// any fake server, requested a removed share-scoped route.
|
||||
//
|
||||
// The config file is RCLONE_CONFIG's, as on rclone's command line,
|
||||
// whichever tests run: only fstest.Initialise would apply it, so the
|
||||
// default config, which may hold a real Proton remote, would be read.
|
||||
func TestMain(m *testing.M) {
|
||||
if path, ok := os.LookupEnv("RCLONE_CONFIG"); ok {
|
||||
if err := config.SetConfigPath(path); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "FAIL: RCLONE_CONFIG: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
code := m.Run()
|
||||
if legacy := protontest.LegacyRequests(); len(legacy) > 0 {
|
||||
fmt.Fprintf(os.Stderr, "FAIL: TestBudgetNoLegacyRoutes: removed share-scoped routes were requested: %v\n", legacy)
|
||||
code = 1
|
||||
}
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
// totalRequests returns the sum of the counts in requests.
|
||||
func totalRequests(requests map[string]int) int {
|
||||
n := 0
|
||||
for _, count := range requests {
|
||||
n += count
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// withoutEvents returns requests without the events routes, which
|
||||
// the Fs requests on its own schedule; TestBudgetEvents checks them.
|
||||
func withoutEvents(requests map[string]int) map[string]int {
|
||||
delete(requests, latestEventRoute)
|
||||
delete(requests, eventsRoute)
|
||||
return requests
|
||||
}
|
||||
|
||||
// ceilDiv returns n/d rounded up.
|
||||
func ceilDiv(n, d int) int {
|
||||
return (n + d - 1) / d
|
||||
}
|
||||
|
||||
// childPages returns the number of child ID pages the fake returns for
|
||||
// a folder of n children with page size pageSize: at least one.
|
||||
func childPages(n, pageSize int) int {
|
||||
return max(1, ceilDiv(n, pageSize))
|
||||
}
|
||||
|
||||
// seedFiles seeds n small files into folder parentID.
|
||||
func seedFiles(u *protontest.User, parentID string, n int) {
|
||||
for i := range n {
|
||||
u.SeedFile(parentID, fmt.Sprintf("file%03d.txt", i), []byte(fmt.Sprintf("file %d", i)), time.Now())
|
||||
}
|
||||
}
|
||||
|
||||
// budgetSizes are the folder sizes the listing budgets are checked at:
|
||||
// around the metadata batch of 100 and the child page of 150.
|
||||
var budgetSizes = []int{0, 1, 100, 101, 250}
|
||||
|
||||
// budgetPageSize is the child ID page size the listing budgets use.
|
||||
const budgetPageSize = 150
|
||||
|
||||
// seedBudgetFolders seeds a folder "nN" of N files for each of sizes.
|
||||
func seedBudgetFolders(srv *protontest.Server, u *protontest.User, sizes []int) {
|
||||
srv.SetChildrenPageSize(budgetPageSize)
|
||||
for _, n := range sizes {
|
||||
seedFiles(u, u.SeedFolder(u.RootID(), fmt.Sprintf("n%d", n)), n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBudgetList checks listing a folder of N files costs one request
|
||||
// per page of child IDs and one per batch of 100 nodes, within spec
|
||||
// 9.4's P + ceil(N/100) + 1. The Fs is rooted at the folder, so finding
|
||||
// it is part of NewFs.
|
||||
//
|
||||
// A second listing costs nothing with enable_caching at its default,
|
||||
// and with it off costs the same as the first, no more. The latter is
|
||||
// checked at the sizes which differ in kind - empty, one batch, several
|
||||
// pages and batches - to save time.
|
||||
//
|
||||
// Measured, per route (children pages + links batches):
|
||||
// N=0: 1+0, N=1: 1+1, N=100: 1+1, N=101: 1+2, N=250: 2+3 - exactly
|
||||
// P + ceil(N/100), so the bound is that, without the spec's +1. Warm: 0
|
||||
// at every N; with caching off the second listing repeats the first.
|
||||
func TestBudgetList(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
remote, srv, u := setupFakeRemote(t)
|
||||
seedBudgetFolders(srv, u, budgetSizes)
|
||||
list := func(t *testing.T, f fs.Fs, n int) map[string]int {
|
||||
t.Helper()
|
||||
srv.ResetRequests()
|
||||
entries, err := f.List(ctx, "")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, entries, n)
|
||||
return withoutEvents(srv.Requests())
|
||||
}
|
||||
for _, n := range budgetSizes {
|
||||
t.Run(fmt.Sprint(n), func(t *testing.T) {
|
||||
root := fmt.Sprintf("n%d", n)
|
||||
f := newFakeFs(t, remote, root)
|
||||
cold := list(t, f, n)
|
||||
pages, batches := childPages(n, budgetPageSize), ceilDiv(n, 100)
|
||||
assert.LessOrEqual(t, cold[childrenRoute], pages, "%v", cold)
|
||||
assert.LessOrEqual(t, cold[linksRoute], batches, "%v", cold)
|
||||
assert.LessOrEqual(t, totalRequests(cold), pages+batches, "%v", cold)
|
||||
|
||||
assert.Empty(t, list(t, f, n), "warm listing")
|
||||
|
||||
if n == 100 || n == 101 {
|
||||
return
|
||||
}
|
||||
t.Setenv(fakeEnvPrefix+"ENABLE_CACHING", "false")
|
||||
uncached := newFakeFs(t, remote, root)
|
||||
assert.Equal(t, cold, list(t, uncached, n), "first listing without caching")
|
||||
assert.Equal(t, cold, list(t, uncached, n), "second listing without caching")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestBudgetNoopSync checks a cold sync of a tree already in sync, by
|
||||
// size and modification time and by --checksum, lists each folder once
|
||||
// and transfers nothing: SHA-1s come from the metadata.
|
||||
//
|
||||
// For D = 6 folders (the root and 5 below it) and N = 200 files (40 per
|
||||
// folder), the plan's bound is 2*D + ceil(N/100) + 5 = 19. Measured, per
|
||||
// route, either way: 6 children pages + 6 links batches = 12, one page
|
||||
// and one batch per folder, as no folder has more than 100 children.
|
||||
// The bound is that: 2*D.
|
||||
func TestBudgetNoopSync(t *testing.T) {
|
||||
const (
|
||||
folders = 5
|
||||
filesPerFolder = 40
|
||||
budget = 2 * (folders + 1)
|
||||
)
|
||||
remote, srv, u := setupFakeRemote(t)
|
||||
local := t.TempDir()
|
||||
modTime := time.Now().Add(-time.Hour).Truncate(time.Second)
|
||||
for d := range folders {
|
||||
dir := fmt.Sprintf("dir%d", d)
|
||||
id := u.SeedFolder(u.RootID(), dir)
|
||||
require.NoError(t, os.Mkdir(filepath.Join(local, dir), 0o777))
|
||||
for i := range filesPerFolder {
|
||||
name := fmt.Sprintf("file%02d.txt", i)
|
||||
content := []byte(fmt.Sprintf("content of %s/%s", dir, name))
|
||||
u.SeedFile(id, name, content, modTime)
|
||||
p := filepath.Join(local, dir, name)
|
||||
require.NoError(t, os.WriteFile(p, content, 0o666))
|
||||
require.NoError(t, os.Chtimes(p, modTime, modTime))
|
||||
}
|
||||
}
|
||||
|
||||
for _, checksum := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("checksum=%v", checksum), func(t *testing.T) {
|
||||
ctx, ci := fs.AddConfig(context.Background())
|
||||
ci.CheckSum = checksum
|
||||
src, err := fs.NewFs(ctx, local)
|
||||
require.NoError(t, err)
|
||||
f := newFakeFs(t, remote, "")
|
||||
srv.ResetRequests()
|
||||
require.NoError(t, fssync.Sync(ctx, f, src, false))
|
||||
|
||||
got := withoutEvents(srv.Requests())
|
||||
assert.LessOrEqual(t, totalRequests(got), budget, "%v", got)
|
||||
assert.Zero(t, blockTransfers(got), "%v", got)
|
||||
assert.Zero(t, got[draftRoute]+got[revisionDraftRoute], "drafts created: %v", got)
|
||||
for route := range got {
|
||||
assert.NotContains(t, route, "/revisions/", "file content read: %v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestBudgetNewObject checks finding a file three folders deep, cold,
|
||||
// costs one listing, a children page and a links batch, per folder on
|
||||
// its path.
|
||||
//
|
||||
// The plan's bound is 2 per level + 1 = 7 for three levels. Measured
|
||||
// for a/b/c/file.txt, per route: 4 children pages + 4 links batches =
|
||||
// 8, as the root is listed too - it is a fourth folder on the path,
|
||||
// and Proton has no route to look a child up by name. The bound is 2
|
||||
// per folder listed: 2*4.
|
||||
func TestBudgetNewObject(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
remote, srv, u := setupFakeRemote(t)
|
||||
parent := u.RootID()
|
||||
for _, name := range []string{"a", "b", "c"} {
|
||||
seedFiles(u, parent, 3)
|
||||
parent = u.SeedFolder(parent, name)
|
||||
}
|
||||
u.SeedFile(parent, "file.txt", []byte("deep"), time.Now())
|
||||
|
||||
f := newFakeFs(t, remote, "")
|
||||
srv.ResetRequests()
|
||||
o, err := f.NewObject(ctx, "a/b/c/file.txt")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(4), o.Size())
|
||||
|
||||
got := withoutEvents(srv.Requests())
|
||||
const listed = 4 // the root, a, b and c
|
||||
assert.LessOrEqual(t, got[childrenRoute], listed, "%v", got)
|
||||
assert.LessOrEqual(t, got[linksRoute], listed, "%v", got)
|
||||
assert.LessOrEqual(t, totalRequests(got), 2*listed, "%v", got)
|
||||
}
|
||||
|
||||
// TestBudgetUpload checks the requests of uploading new files to a
|
||||
// folder: one listing of the folder to check the name is free, the
|
||||
// first time only, then per file a draft, its verification code, at
|
||||
// most one block URL request per block, one PUT per block, the commit
|
||||
// and one read of the committed node.
|
||||
//
|
||||
// Measured, per route, into a folder of 3 files:
|
||||
//
|
||||
// small.txt, cold: children 1 + links 1 (the listing), draft 1,
|
||||
// verifier 1, block URLs 1, block PUTs 1, commit 1, links 1 = 8
|
||||
// big.bin, 3 blocks: draft 1, verifier 1, block URLs 1-3 (as blocks
|
||||
// are ready), block PUTs 3, commit 1, links 1 = 8-10
|
||||
// again.txt: as small.txt without the listing = 6
|
||||
func TestBudgetUpload(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
remote, srv, u := setupFakeRemote(t)
|
||||
seedFiles(u, u.SeedFolder(u.RootID(), "dir"), 3)
|
||||
f := newFakeFs(t, remote, "dir")
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
size int
|
||||
blocks int
|
||||
listed bool // the folder is listed to check the name is free
|
||||
}{
|
||||
{"small.txt", 5, 1, true},
|
||||
{"big.bin", 2*blockSize + 5, 3, false},
|
||||
{"again.txt", 5, 1, false},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
srv.ResetRequests()
|
||||
content := patternedContent(test.size, 1)
|
||||
_, err := operations.Copy(ctx, f, nil, test.name, object.NewMemoryObject(test.name, time.Now(), content))
|
||||
require.NoError(t, err)
|
||||
|
||||
got := withoutEvents(srv.Requests())
|
||||
listing := 0
|
||||
if test.listed {
|
||||
listing = 2 // a children page and a links batch
|
||||
assert.Equal(t, 1, got[childrenRoute], "%v", got)
|
||||
} else {
|
||||
assert.Zero(t, got[childrenRoute], "folder listed again: %v", got)
|
||||
}
|
||||
assert.Equal(t, 1, got[draftRoute], "%v", got)
|
||||
assert.Equal(t, 1, got[verifierRoute], "%v", got)
|
||||
assert.GreaterOrEqual(t, got[blockURLsRoute], 1, "%v", got)
|
||||
assert.LessOrEqual(t, got[blockURLsRoute], test.blocks, "%v", got)
|
||||
assert.Equal(t, test.blocks, got[blockPutRoute], "%v", got)
|
||||
assert.Equal(t, 1, got[commitRoute], "%v", got)
|
||||
assert.Equal(t, listing/2+1, got[linksRoute], "%v", got)
|
||||
assert.LessOrEqual(t, totalRequests(got), listing+4+2*test.blocks, "%v", got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestBudgetMkdir checks making folders side by side lists their
|
||||
// parent once, to check the first name is free, and then costs one
|
||||
// request per folder.
|
||||
//
|
||||
// Measured, per route, into a folder of 3 files: x: children 1 +
|
||||
// links 1 + create 1 = 3; y and z: create 1 each.
|
||||
func TestBudgetMkdir(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
remote, srv, u := setupFakeRemote(t)
|
||||
seedFiles(u, u.SeedFolder(u.RootID(), "dir"), 3)
|
||||
f := newFakeFs(t, remote, "dir")
|
||||
srv.ResetRequests()
|
||||
for _, name := range []string{"x", "y", "z"} {
|
||||
require.NoError(t, f.Mkdir(ctx, name))
|
||||
}
|
||||
got := withoutEvents(srv.Requests())
|
||||
assert.Equal(t, map[string]int{childrenRoute: 1, linksRoute: 1, createFolderRoute: 3}, got)
|
||||
|
||||
entries, err := f.List(ctx, "")
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, entries, 6, "the cached listing holds the new folders")
|
||||
}
|
||||
|
||||
// TestBudgetEvents checks the volume events cost nothing while the Fs
|
||||
// caches nothing, and once it does, one request for the start cursor
|
||||
// and then at most one poll per events_min_interval, 1s here.
|
||||
func TestBudgetEvents(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
remote, srv, u := setupFakeRemote(t)
|
||||
seedFiles(u, u.SeedFolder(u.RootID(), "dir"), 3)
|
||||
f := newFakeFs(t, remote, "")
|
||||
srv.ResetRequests()
|
||||
time.Sleep(3 * time.Second)
|
||||
got := srv.Requests()
|
||||
assert.Zero(t, got[latestEventRoute]+got[eventsRoute], "idle: %v", got)
|
||||
|
||||
_, err := f.List(ctx, "dir")
|
||||
require.NoError(t, err)
|
||||
start := time.Now()
|
||||
time.Sleep(3 * time.Second)
|
||||
got = srv.Requests()
|
||||
elapsed := time.Since(start)
|
||||
assert.Equal(t, 1, got[latestEventRoute], "%v", got)
|
||||
assert.GreaterOrEqual(t, got[eventsRoute], 1, "%v", got)
|
||||
assert.LessOrEqual(t, got[eventsRoute], int(elapsed/time.Second), "%v", got)
|
||||
}
|
||||
|
||||
// TestBudgetNoLegacyRoutes checks a run of everyday operations requests
|
||||
// no removed share-scoped route. TestMain checks the same of every
|
||||
// test in the package, through every fake server.
|
||||
func TestBudgetNoLegacyRoutes(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
remote, srv, u := setupFakeRemote(t)
|
||||
seedFiles(u, u.SeedFolder(u.RootID(), "dir"), 3)
|
||||
f := newFakeFs(t, remote, "")
|
||||
o, err := operations.Copy(ctx, f, nil, "dir/new.txt", object.NewMemoryObject("dir/new.txt", time.Now(), []byte("new")))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "new", readObject(t, o))
|
||||
_, err = operations.Move(ctx, f, nil, "moved/new.txt", o)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, operations.Purge(ctx, f, "dir"))
|
||||
_, err = f.List(ctx, "moved")
|
||||
require.NoError(t, err)
|
||||
_, err = f.Features().About(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
for route := range srv.Requests() {
|
||||
if strings.Contains(route, "/drive/shares/") {
|
||||
assert.Equal(t, "GET /drive/shares/{shareID}", route)
|
||||
}
|
||||
}
|
||||
assert.Empty(t, protontest.LegacyRequests())
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
package protondrive
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// nodeCache holds decrypted nodes and folder listings in memory.
|
||||
//
|
||||
// A nil nodeCache, as newNodeCache returns when caching is disabled,
|
||||
// holds nothing: its lookups miss and its updates do nothing. Cached
|
||||
// nodes are shared and must not be modified.
|
||||
type nodeCache struct {
|
||||
mu sync.Mutex
|
||||
nodes map[string]*node // by ID
|
||||
listings map[string][]string // IDs of the complete listing of a folder, by folder ID
|
||||
fetching map[string]*fetchState // folders being listed from the server, by folder ID
|
||||
used atomic.Int64 // when the cache was last read or filled, in Unix nanoseconds
|
||||
|
||||
// onFill, if set, is called without mu held when the cache gains
|
||||
// its first entry, from empty. It is read without mu, so it must
|
||||
// be set before the cache is shared.
|
||||
onFill func()
|
||||
}
|
||||
|
||||
// fetchState tracks the listings of a folder being fetched, so that
|
||||
// one which began before a change to the folder's children isn't
|
||||
// cached over it.
|
||||
type fetchState struct {
|
||||
count int // listings in progress
|
||||
changes uint64 // changes to the folder's children since the first began
|
||||
}
|
||||
|
||||
// newNodeCache returns an empty cache, or nil if enabled is false.
|
||||
func newNodeCache(enabled bool) *nodeCache {
|
||||
if !enabled {
|
||||
return nil
|
||||
}
|
||||
return &nodeCache{
|
||||
nodes: make(map[string]*node),
|
||||
listings: make(map[string][]string),
|
||||
fetching: make(map[string]*fetchState),
|
||||
}
|
||||
}
|
||||
|
||||
// get returns the node id, or nil if it isn't cached.
|
||||
func (c *nodeCache) get(id string) *node {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
c.touch()
|
||||
return c.peek(id)
|
||||
}
|
||||
|
||||
// peek is get, but doesn't count as a use of the cache: it is for the
|
||||
// cache's own upkeep.
|
||||
func (c *nodeCache) peek(id string) *node {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.nodes[id]
|
||||
}
|
||||
|
||||
// touch records that the cache is in use now.
|
||||
func (c *nodeCache) touch() {
|
||||
c.used.Store(time.Now().UnixNano())
|
||||
}
|
||||
|
||||
// unusedFor returns how long ago the cache was last read or filled; a
|
||||
// nil cache, or one never used, counts as used now.
|
||||
func (c *nodeCache) unusedFor() time.Duration {
|
||||
if c == nil {
|
||||
return 0
|
||||
}
|
||||
used := c.used.Load()
|
||||
if used == 0 {
|
||||
return 0
|
||||
}
|
||||
return time.Since(time.Unix(0, used))
|
||||
}
|
||||
|
||||
// put caches n, replacing any node with its ID. If the cached node had
|
||||
// another parent, the listings of both parents are forgotten.
|
||||
func (c *nodeCache) put(n *node) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
c.touch()
|
||||
c.mu.Lock()
|
||||
defer c.filled(c.emptyLocked())
|
||||
defer c.mu.Unlock()
|
||||
if old := c.nodes[n.ID]; old != nil && old.ParentID != n.ParentID {
|
||||
c.childrenChangedLocked(old.ParentID)
|
||||
c.childrenChangedLocked(n.ParentID)
|
||||
}
|
||||
c.nodes[n.ID] = n
|
||||
}
|
||||
|
||||
// children returns the cached listing of folder parentID. It reports
|
||||
// false if the listing, or any node in it, isn't cached.
|
||||
func (c *nodeCache) children(parentID string) ([]*node, bool) {
|
||||
if c == nil {
|
||||
return nil, false
|
||||
}
|
||||
c.touch()
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
ids, ok := c.listings[parentID]
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
out := make([]*node, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
n := c.nodes[id]
|
||||
if n == nil {
|
||||
return nil, false
|
||||
}
|
||||
out = append(out, n)
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
|
||||
// setChildren caches nodes as the complete listing of folder parentID,
|
||||
// and each of the nodes. The listings of other parents a node was
|
||||
// cached under are forgotten.
|
||||
func (c *nodeCache) setChildren(parentID string, nodes []*node) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
c.touch()
|
||||
c.mu.Lock()
|
||||
defer c.filled(c.emptyLocked())
|
||||
defer c.mu.Unlock()
|
||||
c.setChildrenLocked(parentID, nodes)
|
||||
}
|
||||
|
||||
// setChildrenLocked is setChildren with c.mu held.
|
||||
func (c *nodeCache) setChildrenLocked(parentID string, nodes []*node) {
|
||||
ids := make([]string, len(nodes))
|
||||
for i, n := range nodes {
|
||||
ids[i] = n.ID
|
||||
if old := c.nodes[n.ID]; old != nil && old.ParentID != parentID {
|
||||
c.childrenChangedLocked(old.ParentID)
|
||||
}
|
||||
c.nodes[n.ID] = n
|
||||
}
|
||||
c.listings[parentID] = ids
|
||||
}
|
||||
|
||||
// startFetch records that a listing of folder parentID is being read
|
||||
// from the server and returns the token to pass to endFetch, which
|
||||
// must be called.
|
||||
func (c *nodeCache) startFetch(parentID string) (token uint64) {
|
||||
if c == nil {
|
||||
return 0
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
st := c.fetching[parentID]
|
||||
if st == nil {
|
||||
st = &fetchState{}
|
||||
c.fetching[parentID] = st
|
||||
}
|
||||
st.count++
|
||||
return st.changes
|
||||
}
|
||||
|
||||
// endFetch ends a listing of folder parentID begun by startFetch with
|
||||
// token. If complete is set, nodes are cached as the listing, unless
|
||||
// the folder's children changed since it began, when what it read may
|
||||
// be out of date.
|
||||
func (c *nodeCache) endFetch(parentID string, token uint64, nodes []*node, complete bool) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
c.touch()
|
||||
c.mu.Lock()
|
||||
defer c.filled(c.emptyLocked())
|
||||
defer c.mu.Unlock()
|
||||
st := c.fetching[parentID]
|
||||
if complete && st.changes == token {
|
||||
c.setChildrenLocked(parentID, nodes)
|
||||
}
|
||||
st.count--
|
||||
if st.count == 0 {
|
||||
delete(c.fetching, parentID)
|
||||
}
|
||||
}
|
||||
|
||||
// childrenChangedLocked forgets the listing of folder parentID, and
|
||||
// marks its listings being fetched as out of date. c.mu must be held.
|
||||
func (c *nodeCache) childrenChangedLocked(parentID string) {
|
||||
delete(c.listings, parentID)
|
||||
if st := c.fetching[parentID]; st != nil {
|
||||
st.changes++
|
||||
}
|
||||
}
|
||||
|
||||
// add caches n, a node new to its parent, and adds it to the cached
|
||||
// listing of its parent, if there is one.
|
||||
func (c *nodeCache) add(n *node) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
c.touch()
|
||||
c.mu.Lock()
|
||||
defer c.filled(c.emptyLocked())
|
||||
defer c.mu.Unlock()
|
||||
if old := c.nodes[n.ID]; old != nil && old.ParentID != n.ParentID {
|
||||
c.childrenChangedLocked(old.ParentID)
|
||||
c.childrenChangedLocked(n.ParentID)
|
||||
}
|
||||
c.nodes[n.ID] = n
|
||||
if st := c.fetching[n.ParentID]; st != nil {
|
||||
st.changes++
|
||||
}
|
||||
if ids, ok := c.listings[n.ParentID]; ok && !slices.Contains(ids, n.ID) {
|
||||
c.listings[n.ParentID] = append(ids, n.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// invalidate forgets the node id, its listing if it is a folder, and
|
||||
// the listing of its parent.
|
||||
func (c *nodeCache) invalidate(id string) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if n := c.nodes[id]; n != nil {
|
||||
c.childrenChangedLocked(n.ParentID)
|
||||
} else {
|
||||
// Its parent is unknown, and any listing being fetched may
|
||||
// hold it.
|
||||
for _, st := range c.fetching {
|
||||
st.changes++
|
||||
}
|
||||
}
|
||||
delete(c.nodes, id)
|
||||
c.childrenChangedLocked(id)
|
||||
}
|
||||
|
||||
// invalidateTree forgets the node id, the listing of its parent, and
|
||||
// the node, listing and descendants of everything below it: the
|
||||
// descendants of a folder deleted or moved are cached under paths they
|
||||
// no longer have.
|
||||
func (c *nodeCache) invalidateTree(id string) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if n := c.nodes[id]; n != nil {
|
||||
c.childrenChangedLocked(n.ParentID)
|
||||
} else {
|
||||
// Its parent is unknown, and any listing being fetched may
|
||||
// hold it.
|
||||
for _, st := range c.fetching {
|
||||
st.changes++
|
||||
}
|
||||
}
|
||||
// Descendants may be cached without their parent's listing, so
|
||||
// they are found by parent ID. Every node a listing names is
|
||||
// cached, so the listings add none.
|
||||
children := make(map[string][]string)
|
||||
for childID, n := range c.nodes {
|
||||
children[n.ParentID] = append(children[n.ParentID], childID)
|
||||
}
|
||||
// Visited IDs end the walk of a cycle a hostile server reported.
|
||||
visited := map[string]bool{id: true}
|
||||
pending := []string{id}
|
||||
for len(pending) > 0 {
|
||||
next := pending[len(pending)-1]
|
||||
pending = pending[:len(pending)-1]
|
||||
delete(c.nodes, next)
|
||||
c.childrenChangedLocked(next)
|
||||
for _, childID := range children[next] {
|
||||
if !visited[childID] {
|
||||
visited[childID] = true
|
||||
pending = append(pending, childID)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// invalidateChildren forgets the listing of folder parentID, but not
|
||||
// the nodes in it.
|
||||
func (c *nodeCache) invalidateChildren(parentID string) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.childrenChangedLocked(parentID)
|
||||
}
|
||||
|
||||
// clear forgets everything.
|
||||
func (c *nodeCache) clear() {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
clear(c.nodes)
|
||||
clear(c.listings)
|
||||
for _, st := range c.fetching {
|
||||
st.changes++
|
||||
}
|
||||
}
|
||||
|
||||
// empty reports whether nothing is cached. A nil cache is empty.
|
||||
func (c *nodeCache) empty() bool {
|
||||
if c == nil {
|
||||
return true
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.emptyLocked()
|
||||
}
|
||||
|
||||
// emptyLocked is empty with c.mu held.
|
||||
func (c *nodeCache) emptyLocked() bool {
|
||||
return len(c.nodes) == 0 && len(c.listings) == 0
|
||||
}
|
||||
|
||||
// filled calls onFill if the cache was empty before an update, as
|
||||
// wasEmpty says, and holds something now. c.mu must not be held.
|
||||
func (c *nodeCache) filled(wasEmpty bool) {
|
||||
if wasEmpty && c.onFill != nil && !c.empty() {
|
||||
c.onFill()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
package protondrive
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNodeCacheDisabled(t *testing.T) {
|
||||
c := newNodeCache(false)
|
||||
require.Nil(t, c)
|
||||
n := &node{ID: "a", ParentID: "root"}
|
||||
c.put(n)
|
||||
c.setChildren("root", []*node{n})
|
||||
assert.Nil(t, c.get("a"))
|
||||
_, ok := c.children("root")
|
||||
assert.False(t, ok)
|
||||
c.invalidate("a")
|
||||
c.invalidateChildren("root")
|
||||
c.invalidateTree("root")
|
||||
c.clear()
|
||||
}
|
||||
|
||||
func TestNodeCache(t *testing.T) {
|
||||
c := newNodeCache(true)
|
||||
dir := &node{ID: "dir", ParentID: "root", IsFolder: true}
|
||||
file := &node{ID: "file", ParentID: "dir"}
|
||||
|
||||
assert.Nil(t, c.get("dir"))
|
||||
_, ok := c.children("root")
|
||||
assert.False(t, ok)
|
||||
|
||||
c.setChildren("root", []*node{dir})
|
||||
c.setChildren("dir", []*node{file})
|
||||
assert.Same(t, dir, c.get("dir"))
|
||||
assert.Same(t, file, c.get("file"))
|
||||
got, ok := c.children("dir")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, []*node{file}, got)
|
||||
|
||||
// An empty listing is a listing.
|
||||
c.setChildren("empty", nil)
|
||||
got, ok = c.children("empty")
|
||||
assert.True(t, ok)
|
||||
assert.Empty(t, got)
|
||||
|
||||
// put replaces the node in the listing.
|
||||
renamed := &node{ID: "file", ParentID: "dir", Name: "new"}
|
||||
c.put(renamed)
|
||||
got, ok = c.children("dir")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, []*node{renamed}, got)
|
||||
|
||||
// put of a node with another parent forgets both listings.
|
||||
c.setChildren("other", nil)
|
||||
moved := &node{ID: "file", ParentID: "other"}
|
||||
c.put(moved)
|
||||
assert.Same(t, moved, c.get("file"))
|
||||
_, ok = c.children("dir")
|
||||
assert.False(t, ok)
|
||||
_, ok = c.children("other")
|
||||
assert.False(t, ok)
|
||||
_, ok = c.children("root")
|
||||
assert.True(t, ok)
|
||||
c.setChildren("dir", []*node{renamed})
|
||||
|
||||
// invalidate forgets the node and its parent's listing.
|
||||
c.invalidate("file")
|
||||
assert.Nil(t, c.get("file"))
|
||||
_, ok = c.children("dir")
|
||||
assert.False(t, ok)
|
||||
_, ok = c.children("root")
|
||||
assert.True(t, ok)
|
||||
|
||||
// and a folder's own listing.
|
||||
c.setChildren("dir", []*node{file})
|
||||
c.invalidate("dir")
|
||||
_, ok = c.children("dir")
|
||||
assert.False(t, ok)
|
||||
_, ok = c.children("root")
|
||||
assert.False(t, ok)
|
||||
assert.Same(t, file, c.get("file"))
|
||||
|
||||
c.setChildren("dir", []*node{file})
|
||||
c.invalidateChildren("dir")
|
||||
_, ok = c.children("dir")
|
||||
assert.False(t, ok)
|
||||
assert.Same(t, file, c.get("file"))
|
||||
|
||||
c.setChildren("dir", []*node{file})
|
||||
c.clear()
|
||||
assert.Nil(t, c.get("file"))
|
||||
_, ok = c.children("dir")
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
func TestNodeCacheAdd(t *testing.T) {
|
||||
c := newNodeCache(true)
|
||||
a := &node{ID: "a", ParentID: "dir"}
|
||||
b := &node{ID: "b", ParentID: "dir"}
|
||||
|
||||
// Without a listing of its parent, only the node is cached.
|
||||
c.add(a)
|
||||
assert.Same(t, a, c.get("a"))
|
||||
_, ok := c.children("dir")
|
||||
assert.False(t, ok)
|
||||
|
||||
c.setChildren("dir", []*node{a})
|
||||
c.add(b)
|
||||
got, ok := c.children("dir")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, []*node{a, b}, got)
|
||||
|
||||
// A node already listed is replaced, not listed twice.
|
||||
b2 := &node{ID: "b", ParentID: "dir", Name: "new"}
|
||||
c.add(b2)
|
||||
got, ok = c.children("dir")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, []*node{a, b2}, got)
|
||||
|
||||
newNodeCache(false).add(a)
|
||||
}
|
||||
|
||||
func TestNodeCacheFetch(t *testing.T) {
|
||||
a := &node{ID: "a", ParentID: "dir"}
|
||||
listed := func(c *nodeCache) bool {
|
||||
_, ok := c.children("dir")
|
||||
return ok
|
||||
}
|
||||
|
||||
c := newNodeCache(true)
|
||||
token := c.startFetch("dir")
|
||||
c.endFetch("dir", token, []*node{a}, true)
|
||||
assert.True(t, listed(c), "unchanged")
|
||||
assert.Empty(t, c.fetching)
|
||||
|
||||
c = newNodeCache(true)
|
||||
token = c.startFetch("dir")
|
||||
c.endFetch("dir", token, []*node{a}, false)
|
||||
assert.False(t, listed(c), "incomplete")
|
||||
assert.Empty(t, c.fetching)
|
||||
|
||||
for name, change := range map[string]func(c *nodeCache){
|
||||
"add": func(c *nodeCache) { c.add(&node{ID: "b", ParentID: "dir"}) },
|
||||
"invalidate child": func(c *nodeCache) { c.invalidate("a") },
|
||||
"invalidate unknown": func(c *nodeCache) { c.invalidate("unknown") },
|
||||
"invalidate folder": func(c *nodeCache) { c.invalidate("dir") },
|
||||
"invalidateChildren": func(c *nodeCache) { c.invalidateChildren("dir") },
|
||||
"put moved in": func(c *nodeCache) { c.put(&node{ID: "other", ParentID: "dir"}) },
|
||||
"put moved out": func(c *nodeCache) { c.put(&node{ID: "a", ParentID: "elsewhere"}) },
|
||||
"clear": func(c *nodeCache) { c.clear() },
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
c := newNodeCache(true)
|
||||
c.put(a)
|
||||
c.put(&node{ID: "other", ParentID: "elsewhere"})
|
||||
first := c.startFetch("dir")
|
||||
second := c.startFetch("dir")
|
||||
change(c)
|
||||
c.endFetch("dir", first, []*node{a}, true)
|
||||
assert.False(t, listed(c), "first listing cached after a change")
|
||||
// A fetch begun after the change is cached.
|
||||
third := c.startFetch("dir")
|
||||
c.endFetch("dir", second, []*node{a}, true)
|
||||
assert.False(t, listed(c), "second listing cached after a change")
|
||||
c.endFetch("dir", third, []*node{a}, true)
|
||||
assert.True(t, listed(c))
|
||||
assert.Empty(t, c.fetching, "fetch state kept")
|
||||
})
|
||||
}
|
||||
|
||||
// Changes elsewhere don't matter.
|
||||
c = newNodeCache(true)
|
||||
c.put(&node{ID: "x", ParentID: "other"})
|
||||
token = c.startFetch("dir")
|
||||
c.add(&node{ID: "y", ParentID: "other"})
|
||||
c.invalidate("x")
|
||||
c.invalidateChildren("other")
|
||||
c.endFetch("dir", token, []*node{a}, true)
|
||||
assert.True(t, listed(c))
|
||||
|
||||
var disabled *nodeCache
|
||||
disabled.endFetch("dir", disabled.startFetch("dir"), nil, true)
|
||||
}
|
||||
|
||||
func TestInvalidateTree(t *testing.T) {
|
||||
c := newNodeCache(true)
|
||||
c.setChildren("root", []*node{
|
||||
{ID: "dir", ParentID: "root", IsFolder: true},
|
||||
{ID: "keep", ParentID: "root"},
|
||||
})
|
||||
c.setChildren("dir", []*node{
|
||||
{ID: "sub", ParentID: "dir", IsFolder: true},
|
||||
{ID: "file", ParentID: "dir"},
|
||||
})
|
||||
c.setChildren("sub", []*node{{ID: "deep", ParentID: "sub"}})
|
||||
// A descendant cached without its parent's listing.
|
||||
c.put(&node{ID: "lone", ParentID: "sub"})
|
||||
c.setChildren("elsewhere", []*node{{ID: "x", ParentID: "elsewhere"}})
|
||||
|
||||
dirFetch := c.startFetch("dir")
|
||||
subFetch := c.startFetch("sub")
|
||||
otherFetch := c.startFetch("elsewhere")
|
||||
c.invalidateTree("dir")
|
||||
|
||||
for _, id := range []string{"dir", "sub", "file", "deep", "lone"} {
|
||||
assert.Nil(t, c.get(id), id)
|
||||
}
|
||||
for _, id := range []string{"root", "dir", "sub"} {
|
||||
_, ok := c.listings[id]
|
||||
assert.False(t, ok, "listing %s kept", id)
|
||||
}
|
||||
assert.NotNil(t, c.get("keep"))
|
||||
assert.NotNil(t, c.get("x"))
|
||||
_, ok := c.children("elsewhere")
|
||||
assert.True(t, ok)
|
||||
|
||||
// Listings of the tree in flight aren't cached; others are.
|
||||
c.endFetch("dir", dirFetch, []*node{{ID: "file", ParentID: "dir"}}, true)
|
||||
c.endFetch("sub", subFetch, []*node{{ID: "deep", ParentID: "sub"}}, true)
|
||||
c.endFetch("elsewhere", otherFetch, []*node{{ID: "x", ParentID: "elsewhere"}}, true)
|
||||
_, ok = c.children("dir")
|
||||
assert.False(t, ok)
|
||||
_, ok = c.children("sub")
|
||||
assert.False(t, ok)
|
||||
_, ok = c.children("elsewhere")
|
||||
assert.True(t, ok)
|
||||
assert.Empty(t, c.fetching)
|
||||
|
||||
// An unknown folder: its cached children go, and every listing in
|
||||
// flight may hold it.
|
||||
c = newNodeCache(true)
|
||||
c.setChildren("ghost", []*node{{ID: "child", ParentID: "ghost"}})
|
||||
c.put(&node{ID: "y", ParentID: "other"})
|
||||
token := c.startFetch("other")
|
||||
c.invalidateTree("ghost")
|
||||
assert.Nil(t, c.get("child"))
|
||||
assert.NotNil(t, c.get("y"))
|
||||
c.endFetch("other", token, []*node{{ID: "y", ParentID: "other"}}, true)
|
||||
_, ok = c.children("other")
|
||||
assert.False(t, ok)
|
||||
|
||||
// A cycle, as a hostile server could report, ends.
|
||||
c = newNodeCache(true)
|
||||
c.put(&node{ID: "a", ParentID: "b", IsFolder: true})
|
||||
c.put(&node{ID: "b", ParentID: "a", IsFolder: true})
|
||||
c.invalidateTree("a")
|
||||
assert.True(t, c.empty())
|
||||
}
|
||||
|
||||
func TestNodeCacheEmpty(t *testing.T) {
|
||||
var disabled *nodeCache
|
||||
assert.True(t, disabled.empty())
|
||||
|
||||
c := newNodeCache(true)
|
||||
assert.True(t, c.empty())
|
||||
c.put(&node{ID: "a", ParentID: "root"})
|
||||
assert.False(t, c.empty())
|
||||
c.invalidate("a")
|
||||
assert.True(t, c.empty())
|
||||
|
||||
// An empty listing is something cached.
|
||||
c.setChildren("root", nil)
|
||||
assert.False(t, c.empty())
|
||||
c.clear()
|
||||
assert.True(t, c.empty())
|
||||
|
||||
// Listings in flight aren't.
|
||||
token := c.startFetch("root")
|
||||
assert.True(t, c.empty())
|
||||
c.endFetch("root", token, nil, false)
|
||||
}
|
||||
|
||||
// TestNodeCacheSetChildrenMoved checks a listing holding a node cached
|
||||
// under another parent forgets the other parent's listing, as put does.
|
||||
func TestNodeCacheSetChildrenMoved(t *testing.T) {
|
||||
t.Parallel()
|
||||
c := newNodeCache(true)
|
||||
c.setChildren("a", []*node{{ID: "x", ParentID: "a"}, {ID: "y", ParentID: "a"}})
|
||||
token := c.startFetch("a")
|
||||
c.setChildren("b", []*node{{ID: "x", ParentID: "b"}})
|
||||
_, ok := c.children("a")
|
||||
assert.False(t, ok, "the old parent's listing still holds the node")
|
||||
got, ok := c.children("b")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "b", got[0].ParentID)
|
||||
c.endFetch("a", token, []*node{{ID: "x", ParentID: "a"}}, true)
|
||||
_, ok = c.children("a")
|
||||
assert.False(t, ok, "a listing of the old parent begun before is cached")
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,786 @@
|
||||
package protondrive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"github.com/ProtonMail/gopenpgp/v3/crypto"
|
||||
"github.com/rclone/rclone/backend/protondrive/api"
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/lib/pool"
|
||||
"github.com/rclone/rclone/lib/rest"
|
||||
)
|
||||
|
||||
var (
|
||||
// errIntegrity is returned when a file's content doesn't match
|
||||
// what its uploader signed or claimed.
|
||||
errIntegrity = errors.New("integrity check failed")
|
||||
|
||||
// errBlockHash is returned when a block doesn't match its hash
|
||||
// however many times it is downloaded.
|
||||
errBlockHash = errors.New("block hash mismatch")
|
||||
|
||||
// errDownloadClosed is returned by Read after Close.
|
||||
errDownloadClosed = errors.New("download closed")
|
||||
)
|
||||
|
||||
// signatureHint ends an error for a signature which fails, telling the
|
||||
// user how to read the file anyway.
|
||||
const signatureHint = "set ignore_signature_errors to read the file anyway"
|
||||
|
||||
const (
|
||||
// defaultBlockSize is the plaintext size of every block but the
|
||||
// last of a file the client uploads.
|
||||
defaultBlockSize = 4 << 20
|
||||
|
||||
// blocksPerPage is the most blocks one revision request lists.
|
||||
blocksPerPage = 20
|
||||
|
||||
// maxBlockSize is the largest block accepted, encrypted or
|
||||
// decrypted.
|
||||
maxBlockSize = 8 << 20
|
||||
|
||||
// blockAttempts is how many times a block whose hash doesn't match
|
||||
// is downloaded.
|
||||
blockAttempts = 3
|
||||
|
||||
// downloadAhead is the most blocks of one download fetched or
|
||||
// waiting to be read, besides the one being read.
|
||||
downloadAhead = 4
|
||||
|
||||
// minUnclaimedBlockSize bounds the blocks of a file which doesn't
|
||||
// record its block sizes: there are at most its encrypted size over
|
||||
// this, plus one.
|
||||
minUnclaimedBlockSize = 1 << 20
|
||||
|
||||
// maxFileBlocks is the most blocks a file may list: 2 TiB in
|
||||
// 4 MiB blocks, beyond any one file the largest Proton plan, of a
|
||||
// few TB in all, could hold. A full read holds the metadata of
|
||||
// every block until the manifest is checked, so this bounds how
|
||||
// many whatever the server claims: about 250-350 MiB at the cap
|
||||
// with realistic tokens and URLs. Their length isn't bounded.
|
||||
maxFileBlocks = 1 << 19
|
||||
|
||||
// contentKeyFallbackUntil is the Unix time until which a content
|
||||
// key packet may be signed by any of the account's address keys,
|
||||
// as in the SDK.
|
||||
contentKeyFallbackUntil = 1672531200 // 2023-01-01
|
||||
)
|
||||
|
||||
// open returns a reader of limit bytes of the content of file n from
|
||||
// offset, or to the end if limit < 0.
|
||||
//
|
||||
// A read from offset 0 to the end lists every block and checks the
|
||||
// manifest signature before releasing any byte: if it fails, the first
|
||||
// Read returns errIntegrity, unless IgnoreSignatureErrors is set, when
|
||||
// it is logged. A ranged read checks each block against its listed
|
||||
// hash but can't check the manifest. A node key or content key
|
||||
// signature which fails is errIntegrity from open, on the same terms.
|
||||
// The reader must be closed.
|
||||
func (c *client) open(ctx context.Context, n *node, offset, limit int64) (io.ReadCloser, error) {
|
||||
return c.openRead(ctx, n, offset, limit, offset == 0 && limit < 0)
|
||||
}
|
||||
|
||||
// openWhole is open for limit bytes from offset 0 of a range which
|
||||
// covers the whole file, checked as a full read is.
|
||||
func (c *client) openWhole(ctx context.Context, n *node, limit int64) (io.ReadCloser, error) {
|
||||
return c.openRead(ctx, n, 0, limit, true)
|
||||
}
|
||||
|
||||
// openRead is open, listing every block and checking the manifest
|
||||
// before releasing any byte if full is set, which needs offset 0.
|
||||
func (c *client) openRead(ctx context.Context, n *node, offset, limit int64, full bool) (io.ReadCloser, error) {
|
||||
if n.IsFolder || n.link == nil || n.link.File == nil || n.RevisionID == "" {
|
||||
return nil, fmt.Errorf("open %q: not a file with content", n.Name)
|
||||
}
|
||||
if offset < 0 {
|
||||
return nil, fmt.Errorf("open %q: negative offset %d", n.Name, offset)
|
||||
}
|
||||
sk, err := c.contentKey(n, "reading")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open %q: %w", n.Name, err)
|
||||
}
|
||||
var sizes []int64
|
||||
if n.X != nil {
|
||||
sizes = n.X.BlockSizes
|
||||
}
|
||||
full = full && offset == 0
|
||||
if len(sizes) > c.maxFileBlocks {
|
||||
return nil, fmt.Errorf("open %q: %w: %d blocks recorded, more than %d blocks", n.Name, errIntegrity, len(sizes), c.maxFileBlocks)
|
||||
}
|
||||
if sizes != nil {
|
||||
var total int64
|
||||
for i, size := range sizes {
|
||||
// Bounding each size bounds the total too.
|
||||
if size > maxBlockSize {
|
||||
return nil, fmt.Errorf("open %q: %w: block %d recorded as %d bytes", n.Name, errIntegrity, i+1, size)
|
||||
}
|
||||
total += size
|
||||
}
|
||||
switch {
|
||||
case full:
|
||||
// A full read always lists the blocks, to reach the
|
||||
// manifest.
|
||||
case offset >= total:
|
||||
limit = 0
|
||||
case limit >= 0:
|
||||
limit = min(limit, total-offset)
|
||||
}
|
||||
}
|
||||
if limit == 0 {
|
||||
return io.NopCloser(bytes.NewReader(nil)), nil
|
||||
}
|
||||
// Without recorded block sizes only the sizes learnt by earlier
|
||||
// reads tell which block holds offset, as old clients didn't all
|
||||
// write 4 MiB blocks, so the read starts at the last block they
|
||||
// reach and discards the bytes before offset.
|
||||
first, skip, last := 1, offset, -1
|
||||
var startHash []byte
|
||||
switch {
|
||||
case sizes != nil:
|
||||
first, skip = blockAt(sizes, offset)
|
||||
if limit > 0 && !full {
|
||||
last, _ = blockAt(sizes, offset+limit-1)
|
||||
}
|
||||
case !full:
|
||||
first, skip, last, startHash = c.learnt.locate(n.RevisionID, offset, limit)
|
||||
}
|
||||
maxBlocks := len(sizes)
|
||||
if sizes == nil {
|
||||
maxBlocks = int(min(n.EncryptedSize/minUnclaimedBlockSize+1, 1<<30))
|
||||
}
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
r := &blockReader{
|
||||
c: c,
|
||||
n: n,
|
||||
sk: sk,
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
slots: make(chan chan blockResult, downloadAhead),
|
||||
sizes: sizes,
|
||||
startHash: startHash,
|
||||
skip: skip,
|
||||
remaining: limit,
|
||||
}
|
||||
r.wg.Add(1)
|
||||
go r.list(first, last, maxBlocks, full)
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// blockAt returns the index, from 1, of the block holding plaintext
|
||||
// offset pos of a file with block sizes sizes, and the offset of pos in
|
||||
// it.
|
||||
func blockAt(sizes []int64, pos int64) (index int, offset int64) {
|
||||
for i, size := range sizes {
|
||||
if pos < size {
|
||||
return i + 1, pos
|
||||
}
|
||||
pos -= size
|
||||
}
|
||||
return len(sizes) + 1, pos
|
||||
}
|
||||
|
||||
// contentKey returns the content session key of file n for op,
|
||||
// "reading" or "updating", checking its signature as the SDK's
|
||||
// decryptContentKeyPacket does, except that a missing signature fails
|
||||
// too: anyone with the node's public key can make a content key packet.
|
||||
//
|
||||
// An unverified node key or content key is errIntegrity unless
|
||||
// IgnoreSignatureErrors is set, when it is logged once per node and op:
|
||||
// whoever made the key could read what is written with it and make up
|
||||
// the content read.
|
||||
func (c *client) contentKey(n *node, op string) (*crypto.SessionKey, error) {
|
||||
hint := signatureHint
|
||||
if op != "reading" {
|
||||
hint = "set ignore_signature_errors to update the file anyway"
|
||||
}
|
||||
if n.keys.unverified != nil {
|
||||
if !c.opt.IgnoreSignatureErrors {
|
||||
return nil, fmt.Errorf("node key: %w: %w: %s", errIntegrity, n.keys.unverified, hint)
|
||||
}
|
||||
c.reportUnverified(op, n, "")
|
||||
}
|
||||
f := n.link.File
|
||||
now := c.s.serverTime()
|
||||
sk, verifyErr, err := decryptContentKey(f.ContentKeyPacket, f.ContentKeyPacketSignature, n.keys.keyRing, n.keyVerifyKR, now)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if verifyErr != nil && !isNotSigned(verifyErr) && n.CreateTime.Unix() <= contentKeyFallbackUntil {
|
||||
// Old clients signed with an address key, and a rename or
|
||||
// move could change the node's signer without signing the
|
||||
// content key packet again.
|
||||
krs := make([]*crypto.KeyRing, 0, len(c.acct.addresses))
|
||||
for _, addr := range c.acct.addresses {
|
||||
krs = append(krs, addr.keyRing)
|
||||
}
|
||||
if allKR, err := joinKeyRings(krs...); err == nil && verifyDetached(sk.Key, f.ContentKeyPacketSignature, allKR, now) == nil {
|
||||
fs.Debugf(nil, "protondrive: %q (ID %s): content key signed by another address of the account", n.Name, n.ID)
|
||||
verifyErr = nil
|
||||
}
|
||||
}
|
||||
if verifyErr != nil {
|
||||
verifyErr = fmt.Errorf("content key: %w: %w", errIntegrity, verifyErr)
|
||||
if !c.opt.IgnoreSignatureErrors {
|
||||
return nil, fmt.Errorf("%w: %s", verifyErr, hint)
|
||||
}
|
||||
c.reportOnce("content key "+op, n.ID, func() {
|
||||
fs.Errorf(nil, "protondrive: %s %q (ID %s): %v", op, n.Name, n.ID, verifyErr)
|
||||
})
|
||||
}
|
||||
return sk, nil
|
||||
}
|
||||
|
||||
// revisionBlocks returns the active revision of file n with at most
|
||||
// pageSize of its blocks from block index from.
|
||||
func (c *client) revisionBlocks(ctx context.Context, n *node, from, pageSize int) (*api.Revision, error) {
|
||||
opts := &rest.Opts{
|
||||
Method: "GET",
|
||||
Path: c.volumePath("/drive/v2/volumes", "files", n.ID, "revisions", n.RevisionID),
|
||||
Parameters: url.Values{
|
||||
"FromBlockIndex": {strconv.Itoa(from)},
|
||||
"PageSize": {strconv.Itoa(pageSize)},
|
||||
},
|
||||
}
|
||||
var resp api.RevisionResponse
|
||||
if err := c.apiCall(ctx, opts, nil, &resp); err != nil {
|
||||
return nil, fmt.Errorf("list blocks: %w", err)
|
||||
}
|
||||
return &resp.Revision, nil
|
||||
}
|
||||
|
||||
// blockURL returns block index of file n with a new download URL.
|
||||
func (c *client) blockURL(ctx context.Context, n *node, index int) (api.Block, error) {
|
||||
rev, err := c.revisionBlocks(ctx, n, index, 1)
|
||||
if err != nil {
|
||||
return api.Block{}, err
|
||||
}
|
||||
if len(rev.Blocks) == 0 || rev.Blocks[0].Index != index {
|
||||
return api.Block{}, fmt.Errorf("list blocks: block %d is missing", index)
|
||||
}
|
||||
return rev.Blocks[0], nil
|
||||
}
|
||||
|
||||
// downloadBlock returns the encrypted block at bareURL, which token
|
||||
// unlocks, and its SHA-256. The block must be closed.
|
||||
func (c *client) downloadBlock(ctx context.Context, bareURL, token string) (enc *pool.RW, sum []byte, err error) {
|
||||
c.downloadTokens.Get()
|
||||
defer c.downloadTokens.Put()
|
||||
opts := &rest.Opts{
|
||||
Method: "GET",
|
||||
RootURL: bareURL,
|
||||
// The storage host gets the block's token, never the
|
||||
// session's credentials, which only session.call adds.
|
||||
ExtraHeaders: map[string]string{"pm-storage-token": token},
|
||||
}
|
||||
err = c.pacedCall(ctx, c.storagePacer, func() (*http.Response, error) {
|
||||
if enc != nil {
|
||||
_ = enc.Close()
|
||||
}
|
||||
enc = pool.NewRW(pool.Global())
|
||||
resp, err := c.s.srv.Call(ctx, opts)
|
||||
if err != nil {
|
||||
return resp, err
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.ContentLength > maxBlockSize {
|
||||
return nil, fmt.Errorf("block is larger than %d bytes", maxBlockSize)
|
||||
}
|
||||
h := sha256.New()
|
||||
size, err := enc.ReadFrom(io.TeeReader(io.LimitReader(resp.Body, maxBlockSize+1), h))
|
||||
if err != nil {
|
||||
return resp, err
|
||||
}
|
||||
if size > maxBlockSize {
|
||||
return nil, fmt.Errorf("block is larger than %d bytes", maxBlockSize)
|
||||
}
|
||||
sum = h.Sum(nil)
|
||||
return resp, nil
|
||||
})
|
||||
if err != nil {
|
||||
if enc != nil {
|
||||
_ = enc.Close()
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
return enc, sum, nil
|
||||
}
|
||||
|
||||
// blockResult is the outcome of a block of a download, or its end.
|
||||
type blockResult struct {
|
||||
index int
|
||||
hash []byte // the block's SHA-256
|
||||
plain *pool.RW // the decrypted block; nil on error or at the end
|
||||
err error
|
||||
end bool // no more blocks follow; err is the verdict on the file
|
||||
}
|
||||
|
||||
// blockReader reads a range of a file, fetching blocks ahead of the
|
||||
// reader in the background.
|
||||
type blockReader struct {
|
||||
c *client
|
||||
n *node
|
||||
sk *crypto.SessionKey
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
slots chan chan blockResult // results to read, in order
|
||||
wg sync.WaitGroup // the lister and the fetches
|
||||
sizes []int64 // claimed plaintext block sizes; nil if not recorded
|
||||
// startHash is the hash the first block had when its size was
|
||||
// learnt, if it was.
|
||||
startHash []byte
|
||||
|
||||
mu sync.Mutex // held by Read and Close
|
||||
cur *pool.RW // block being read
|
||||
skip int64 // bytes to discard before the range, from the first block on
|
||||
remaining int64 // bytes left to read; negative for all
|
||||
err error // returned by every Read once set
|
||||
closed bool
|
||||
}
|
||||
|
||||
// list lists the blocks first to last (to the end if last < 0) and
|
||||
// fetches them, then sends the end of the download. If verify is set,
|
||||
// the list having started at the first block, it lists every block and
|
||||
// checks the manifest before fetching any.
|
||||
//
|
||||
// A list of more than maxBlocks blocks is an error.
|
||||
func (r *blockReader) list(first, last, maxBlocks int, verify bool) {
|
||||
defer r.wg.Done()
|
||||
end := make(chan blockResult, 1)
|
||||
end <- blockResult{end: true, err: r.listBlocks(first, last, maxBlocks, verify)}
|
||||
select {
|
||||
case r.slots <- end:
|
||||
case <-r.ctx.Done():
|
||||
}
|
||||
}
|
||||
|
||||
// listedBlock is a block of the list with its decoded hash.
|
||||
type listedBlock struct {
|
||||
block api.Block
|
||||
hash []byte
|
||||
}
|
||||
|
||||
// listBlocks does the work of list, returning the verdict on the file.
|
||||
func (r *blockReader) listBlocks(first, last, maxBlocks int, verify bool) error {
|
||||
var (
|
||||
hashes [][]byte
|
||||
listed []listedBlock // blocks waiting for the manifest check, if verify
|
||||
manifest string
|
||||
signer string
|
||||
index = first
|
||||
firstPage = true
|
||||
)
|
||||
for {
|
||||
pageSize := blocksPerPage
|
||||
if last > 0 {
|
||||
pageSize = min(pageSize, last-index+1)
|
||||
}
|
||||
rev, err := r.c.revisionBlocks(r.ctx, r.n, index, pageSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if firstPage && verify {
|
||||
manifest, signer = rev.ManifestSignature, rev.SignatureEmail
|
||||
// As in the SDK, the manifest starts with the thumbnails.
|
||||
for _, th := range rev.Thumbnails {
|
||||
hash, err := decodeBlockHash(th.Hash)
|
||||
if err != nil {
|
||||
return fmt.Errorf("thumbnail: %w", err)
|
||||
}
|
||||
hashes = append(hashes, hash)
|
||||
}
|
||||
}
|
||||
firstPage = false
|
||||
if len(rev.Blocks) == 0 {
|
||||
break
|
||||
}
|
||||
for _, b := range rev.Blocks {
|
||||
switch {
|
||||
case index > r.c.maxFileBlocks:
|
||||
return fmt.Errorf("%w: more than %d blocks listed, more than any file can have", errIntegrity, r.c.maxFileBlocks)
|
||||
case b.Index != index:
|
||||
return fmt.Errorf("%w: block %d listed where block %d belongs", errIntegrity, b.Index, index)
|
||||
case index > maxBlocks && r.sizes != nil:
|
||||
return fmt.Errorf("%w: more blocks listed than the %d the file records", errIntegrity, maxBlocks)
|
||||
case index > maxBlocks:
|
||||
return fmt.Errorf("%w: more blocks listed than the file's encrypted size of %d allows", errIntegrity, r.n.EncryptedSize)
|
||||
}
|
||||
hash, err := decodeBlockHash(b.Hash)
|
||||
if err != nil {
|
||||
return fmt.Errorf("block %d: %w", index, err)
|
||||
}
|
||||
if index == first && r.startHash != nil && !bytes.Equal(hash, r.startHash) {
|
||||
// The sizes placing the range came from another block
|
||||
// list of the same revision.
|
||||
return fmt.Errorf("%w: block %d listed with another hash than when it was read before", errIntegrity, index)
|
||||
}
|
||||
if verify {
|
||||
// Nothing is released before the manifest vouches for
|
||||
// every block's hash and place.
|
||||
hashes = append(hashes, hash)
|
||||
listed = append(listed, listedBlock{block: b, hash: hash})
|
||||
} else if !r.fetch(b, hash) {
|
||||
return r.ctx.Err()
|
||||
}
|
||||
if index == last {
|
||||
return nil
|
||||
}
|
||||
index++
|
||||
}
|
||||
}
|
||||
if r.sizes != nil && index <= len(r.sizes) {
|
||||
return fmt.Errorf("%w: %d blocks listed of the %d the file records", errIntegrity, index-1, len(r.sizes))
|
||||
}
|
||||
if !verify {
|
||||
return nil
|
||||
}
|
||||
if err := r.verifyManifest(hashes, manifest, signer); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, lb := range listed {
|
||||
if !r.fetch(lb.block, lb.hash) {
|
||||
return r.ctx.Err()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// decodeBlockHash returns the base64 SHA-256 hash.
|
||||
func decodeBlockHash(b64 string) ([]byte, error) {
|
||||
hash, err := base64.StdEncoding.DecodeString(b64)
|
||||
if err == nil && len(hash) != sha256.Size {
|
||||
err = fmt.Errorf("%d bytes long", len(hash))
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bad hash: %w", err)
|
||||
}
|
||||
return hash, nil
|
||||
}
|
||||
|
||||
// verifyManifest checks the manifest signature of the file's block
|
||||
// hashes against the keys of signer, or the node key if it is empty.
|
||||
func (r *blockReader) verifyManifest(hashes [][]byte, manifest, signer string) error {
|
||||
verifyKR, err := r.c.verifyKeys(r.ctx, signer, r.n.keys.keyRing)
|
||||
if err != nil {
|
||||
return fmt.Errorf("verify manifest: %w", err)
|
||||
}
|
||||
err = verifyManifest(hashes, manifest, verifyKR, r.c.s.serverTime())
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
err = fmt.Errorf("%w: %w", errIntegrity, err)
|
||||
if !r.c.opt.IgnoreSignatureErrors {
|
||||
return fmt.Errorf("%w: %s", err, signatureHint)
|
||||
}
|
||||
fs.Errorf(nil, "protondrive: %q (ID %s): %v", r.n.Name, r.n.ID, err)
|
||||
return nil
|
||||
}
|
||||
|
||||
// fetch queues block b, whose SHA-256 is hash, for the reader and
|
||||
// fetches it in the background. It returns false if the download is
|
||||
// cancelled first.
|
||||
func (r *blockReader) fetch(b api.Block, hash []byte) bool {
|
||||
slot := make(chan blockResult, 1)
|
||||
select {
|
||||
case r.slots <- slot:
|
||||
case <-r.ctx.Done():
|
||||
return false
|
||||
}
|
||||
r.wg.Add(1)
|
||||
go func() {
|
||||
defer r.wg.Done()
|
||||
slot <- r.fetchBlock(b, hash)
|
||||
}()
|
||||
return true
|
||||
}
|
||||
|
||||
// fetchBlock downloads and decrypts block b, whose SHA-256 is hash,
|
||||
// requesting a new URL after a 404 (once) or a hash mismatch.
|
||||
func (r *blockReader) fetchBlock(b api.Block, hash []byte) blockResult {
|
||||
index := b.Index
|
||||
refetched := false
|
||||
for attempt := 1; ; {
|
||||
plain, err := r.fetchOnce(b, hash)
|
||||
var apiErr *api.Error
|
||||
switch {
|
||||
case err == nil:
|
||||
return blockResult{index: index, hash: hash, plain: plain}
|
||||
case r.ctx.Err() != nil:
|
||||
return blockResult{index: index, err: r.ctx.Err()}
|
||||
case errors.As(err, &apiErr) && apiErr.Status == http.StatusNotFound && !refetched:
|
||||
// The URL may have expired.
|
||||
refetched = true
|
||||
case errors.Is(err, errBlockHash) && attempt < blockAttempts:
|
||||
// The bytes may have been damaged on the way.
|
||||
attempt++
|
||||
default:
|
||||
return blockResult{index: index, err: fmt.Errorf("block %d: %w", index, err)}
|
||||
}
|
||||
fs.Debugf(nil, "protondrive: %q (ID %s): block %d: %v: retrying with a new URL", r.n.Name, r.n.ID, index, err)
|
||||
// hash stays the listed one, which the manifest covers.
|
||||
if b, err = r.c.blockURL(r.ctx, r.n, index); err != nil {
|
||||
return blockResult{index: index, err: fmt.Errorf("block %d: %w", index, err)}
|
||||
}
|
||||
if relisted, err := decodeBlockHash(b.Hash); err != nil || !bytes.Equal(relisted, hash) {
|
||||
return blockResult{index: index, err: fmt.Errorf("block %d: %w: listed again with another hash", index, errIntegrity)}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fetchOnce downloads block b and checks it against hash and its
|
||||
// claimed size, returning it decrypted.
|
||||
func (r *blockReader) fetchOnce(b api.Block, hash []byte) (*pool.RW, error) {
|
||||
enc, sum, err := r.c.downloadBlock(r.ctx, b.BareURL, b.Token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = enc.Close() }()
|
||||
if !bytes.Equal(sum, hash) {
|
||||
return nil, errBlockHash
|
||||
}
|
||||
dec, err := blockDecrypter(enc, r.sk)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
plain := pool.NewRW(pool.Global())
|
||||
size, err := plain.ReadFrom(io.LimitReader(dec, maxBlockSize+1))
|
||||
switch {
|
||||
case err != nil:
|
||||
err = fmt.Errorf("decrypt block: %w", err)
|
||||
case size > maxBlockSize:
|
||||
err = fmt.Errorf("block decrypts to more than %d bytes", maxBlockSize)
|
||||
case r.sizes != nil && size != r.sizes[b.Index-1]:
|
||||
err = fmt.Errorf("%w: block is %d bytes, the file records %d", errIntegrity, size, r.sizes[b.Index-1])
|
||||
}
|
||||
if err != nil {
|
||||
_ = plain.Close()
|
||||
return nil, err
|
||||
}
|
||||
return plain, nil
|
||||
}
|
||||
|
||||
// Read reads the range of the file.
|
||||
func (r *blockReader) Read(p []byte) (int, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
for {
|
||||
switch {
|
||||
case r.closed:
|
||||
return 0, errDownloadClosed
|
||||
case r.err != nil:
|
||||
return 0, r.err
|
||||
case r.remaining == 0:
|
||||
return 0, io.EOF
|
||||
}
|
||||
if r.cur == nil {
|
||||
if err := r.next(); err != nil {
|
||||
r.err = err
|
||||
r.cancel()
|
||||
}
|
||||
continue
|
||||
}
|
||||
if r.remaining > 0 && int64(len(p)) > r.remaining {
|
||||
p = p[:r.remaining]
|
||||
}
|
||||
n, err := r.cur.Read(p)
|
||||
if n > 0 {
|
||||
if r.remaining > 0 {
|
||||
r.remaining -= int64(n)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
if err != nil && err != io.EOF {
|
||||
r.err = err
|
||||
continue
|
||||
}
|
||||
_ = r.cur.Close()
|
||||
r.cur = nil
|
||||
}
|
||||
}
|
||||
|
||||
// next makes the next block holding bytes of the range current,
|
||||
// returning io.EOF at the end.
|
||||
func (r *blockReader) next() error {
|
||||
for {
|
||||
var slot chan blockResult
|
||||
select {
|
||||
case slot = <-r.slots:
|
||||
case <-r.ctx.Done():
|
||||
return r.ctx.Err()
|
||||
}
|
||||
res := <-slot
|
||||
switch {
|
||||
case res.err != nil && r.ctx.Err() != nil:
|
||||
return r.ctx.Err()
|
||||
case res.err != nil:
|
||||
return res.err
|
||||
case res.end:
|
||||
return io.EOF
|
||||
}
|
||||
if r.sizes == nil {
|
||||
if err := r.c.learnt.learn(r.n.RevisionID, res.index, res.hash, res.plain.Size()); err != nil {
|
||||
_ = res.plain.Close()
|
||||
return err
|
||||
}
|
||||
}
|
||||
if size := res.plain.Size(); r.skip > 0 && r.skip >= size {
|
||||
r.skip -= size
|
||||
_ = res.plain.Close()
|
||||
continue
|
||||
}
|
||||
if r.skip > 0 {
|
||||
if _, err := res.plain.Seek(r.skip, io.SeekStart); err != nil {
|
||||
_ = res.plain.Close()
|
||||
return err
|
||||
}
|
||||
r.skip = 0
|
||||
}
|
||||
r.cur = res.plain
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Close stops the download and frees its buffers. It may be called
|
||||
// more than once.
|
||||
func (r *blockReader) Close() error {
|
||||
r.cancel()
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.closed {
|
||||
return nil
|
||||
}
|
||||
r.closed = true
|
||||
r.wg.Wait()
|
||||
if r.cur != nil {
|
||||
_ = r.cur.Close()
|
||||
r.cur = nil
|
||||
}
|
||||
// Every queued slot has its result now.
|
||||
for {
|
||||
select {
|
||||
case slot := <-r.slots:
|
||||
if res := <-slot; res.plain != nil {
|
||||
_ = res.plain.Close()
|
||||
}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// check interfaces
|
||||
var _ io.ReadCloser = (*blockReader)(nil)
|
||||
|
||||
const (
|
||||
// learntRevisions and learntBlocks bound the block sizes a client
|
||||
// learns: of at most this many revisions, and this many blocks in
|
||||
// all, about 2.5 MiB.
|
||||
learntRevisions = 16
|
||||
learntBlocks = 1 << 16
|
||||
)
|
||||
|
||||
// learntBlock is the plaintext size of a block read, with its hash.
|
||||
type learntBlock struct {
|
||||
hash [sha256.Size]byte
|
||||
size int64
|
||||
}
|
||||
|
||||
// blockSizeCache holds the plaintext sizes of the blocks, from the
|
||||
// first on, read of revisions which don't record their block sizes, so
|
||||
// a later ranged read, as each chunk of a multi-thread copy is, can
|
||||
// start at the block holding its offset. The zero value is empty.
|
||||
type blockSizeCache struct {
|
||||
mu sync.Mutex
|
||||
revs map[string][]learntBlock // by revision ID
|
||||
order []string // revision IDs, oldest first
|
||||
blocks int // learnt in all
|
||||
}
|
||||
|
||||
// locate returns where a read of limit bytes (to the end if negative)
|
||||
// from offset of revision id starts, as for blockReader: the first
|
||||
// block, the bytes of it to skip, the last block or -1 if not known,
|
||||
// and the hash the first block had when its size was learnt, or nil if
|
||||
// it wasn't.
|
||||
func (b *blockSizeCache) locate(id string, offset, limit int64) (first int, skip int64, last int, startHash []byte) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
blocks := b.revs[id]
|
||||
first, skip, last = len(blocks)+1, offset, -1
|
||||
for i, lb := range blocks {
|
||||
if skip < lb.size {
|
||||
first = i + 1
|
||||
startHash = slices.Clone(lb.hash[:])
|
||||
break
|
||||
}
|
||||
skip -= lb.size
|
||||
}
|
||||
if first > len(blocks) || limit <= 0 {
|
||||
return first, skip, last, startHash
|
||||
}
|
||||
end := skip + limit - 1
|
||||
for i := first - 1; i < len(blocks); i++ {
|
||||
if end < blocks[i].size {
|
||||
return first, skip, i + 1, startHash
|
||||
}
|
||||
end -= blocks[i].size
|
||||
}
|
||||
return first, skip, last, startHash
|
||||
}
|
||||
|
||||
// learn records that block index of revision id, whose SHA-256 is hash,
|
||||
// is size bytes. A block learnt before with another hash or size is
|
||||
// errIntegrity: the server listed two blocks for one place.
|
||||
func (b *blockSizeCache) learn(id string, index int, hash []byte, size int64) error {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
blocks, ok := b.revs[id]
|
||||
if index <= len(blocks) {
|
||||
if lb := blocks[index-1]; !bytes.Equal(lb.hash[:], hash) || lb.size != size {
|
||||
return fmt.Errorf("%w: block %d listed with another hash than when it was read before", errIntegrity, index)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if index != len(blocks)+1 || len(hash) != sha256.Size {
|
||||
return nil
|
||||
}
|
||||
if !ok {
|
||||
if b.revs == nil {
|
||||
b.revs = make(map[string][]learntBlock)
|
||||
}
|
||||
for len(b.order) >= learntRevisions {
|
||||
b.forgetOldest()
|
||||
}
|
||||
b.order = append(b.order, id)
|
||||
}
|
||||
for b.blocks >= learntBlocks && len(b.order) > 1 && b.order[0] != id {
|
||||
b.forgetOldest()
|
||||
}
|
||||
if b.blocks >= learntBlocks {
|
||||
return nil
|
||||
}
|
||||
lb := learntBlock{size: size}
|
||||
copy(lb.hash[:], hash)
|
||||
b.revs[id] = append(blocks, lb)
|
||||
b.blocks++
|
||||
return nil
|
||||
}
|
||||
|
||||
// forgetOldest drops the revision learnt first.
|
||||
func (b *blockSizeCache) forgetOldest() {
|
||||
b.blocks -= len(b.revs[b.order[0]])
|
||||
delete(b.revs, b.order[0])
|
||||
b.order = b.order[1:]
|
||||
}
|
||||
@@ -0,0 +1,883 @@
|
||||
package protondrive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"math"
|
||||
"math/rand/v2"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/ProtonMail/go-crypto/openpgp/packet"
|
||||
"github.com/rclone/rclone/backend/protondrive/protontest"
|
||||
"github.com/rclone/rclone/lib/pacer"
|
||||
"github.com/rclone/rclone/lib/pool"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
storagePattern = "GET /storage/blocks/{id}"
|
||||
revisionPattern = "GET /drive/v2/volumes/{volumeID}/files/{linkID}/revisions/{revisionID}"
|
||||
|
||||
// bigSize is the size of a file of three blocks, the last partial.
|
||||
bigSize = 9<<20 + 123
|
||||
)
|
||||
|
||||
// testContent returns n bytes of reproducible random content.
|
||||
func testContent(n int) []byte {
|
||||
r := rand.New(rand.NewPCG(uint64(n), 1))
|
||||
b := make([]byte, n)
|
||||
for i := range b {
|
||||
b[i] = byte(r.Uint32())
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// seedFile seeds file name with content in the root of u and returns
|
||||
// its node as c reads it.
|
||||
func seedFile(t *testing.T, c *client, u *protontest.User, name string, content []byte) *node {
|
||||
t.Helper()
|
||||
return getTestNode(t, c, u.SeedFile(u.RootID(), name, content, time.Now()))
|
||||
}
|
||||
|
||||
// getTestNode returns node id as c reads it.
|
||||
func getTestNode(t *testing.T, c *client, id string) *node {
|
||||
t.Helper()
|
||||
n, err := c.getNode(context.Background(), id)
|
||||
require.NoError(t, err)
|
||||
return n
|
||||
}
|
||||
|
||||
// withoutBlockSizes returns a copy of n whose extended attributes
|
||||
// don't record its block sizes, as some old clients wrote them.
|
||||
func withoutBlockSizes(n *node) *node {
|
||||
cp := *n
|
||||
cp.X = nil
|
||||
return &cp
|
||||
}
|
||||
|
||||
// readRange opens n at offset for limit bytes and reads it to the end.
|
||||
func readRange(t *testing.T, c *client, n *node, offset, limit int64) ([]byte, error) {
|
||||
t.Helper()
|
||||
rc, err := c.open(context.Background(), n, offset, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data, err := io.ReadAll(rc)
|
||||
require.NoError(t, rc.Close())
|
||||
return data, err
|
||||
}
|
||||
|
||||
// roundTripFunc is an http.RoundTripper calling itself.
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
// RoundTrip calls f.
|
||||
func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
return f(r)
|
||||
}
|
||||
|
||||
// newTestClientTransport returns a client for a new session of u whose
|
||||
// requests go through the transport wrap returns.
|
||||
func newTestClientTransport(t testing.TB, srv *protontest.Server, u *protontest.User, opt clientOptions, wrap func(next http.RoundTripper) http.RoundTripper) *client {
|
||||
t.Helper()
|
||||
base := newAccountSession(srv, u)
|
||||
s := newSession(&http.Client{Transport: wrap(srv.Client().Transport)}, srv.URL(), testAppVersion, base.store)
|
||||
c, err := newClient(context.Background(), s, opt)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(c.close)
|
||||
return c
|
||||
}
|
||||
|
||||
// leakBaseline returns the goroutine count and pool buffers in use with
|
||||
// no idle connections, for requireNoLeaks.
|
||||
func leakBaseline(srv *protontest.Server) (goroutines, buffers int) {
|
||||
srv.Client().CloseIdleConnections()
|
||||
return runtime.NumGoroutine(), pool.Global().InUse()
|
||||
}
|
||||
|
||||
// requireNoLeaks fails the test unless the goroutine count returns to
|
||||
// goroutines within 2s and the pool buffers in use are back to buffers.
|
||||
func requireNoLeaks(t *testing.T, srv *protontest.Server, goroutines, buffers int) {
|
||||
t.Helper()
|
||||
require.Eventually(t, func() bool {
|
||||
srv.Client().CloseIdleConnections()
|
||||
return runtime.NumGoroutine() <= goroutines
|
||||
}, 2*time.Second, 20*time.Millisecond, "goroutines left running")
|
||||
assert.Equal(t, buffers, pool.Global().InUse(), "pool buffers not returned")
|
||||
}
|
||||
|
||||
func TestDownloadSizes(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, _, u := newTestClient(t)
|
||||
for _, size := range []int{0, 1, 4<<20 - 1, 4 << 20, 4<<20 + 1, 8 << 20, bigSize} {
|
||||
t.Run(strconv.Itoa(size), func(t *testing.T) {
|
||||
content := testContent(size)
|
||||
n := seedFile(t, c, u, "f"+strconv.Itoa(size), content)
|
||||
data, err := readRange(t, c, n, 0, -1)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, bytes.Equal(content, data), "content differs")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadRanges(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, srv, u := newTestClient(t)
|
||||
content := testContent(bigSize)
|
||||
claimed := seedFile(t, c, u, "big", content)
|
||||
unrecorded := withoutBlockSizes(claimed)
|
||||
for _, tc := range []struct {
|
||||
offset, limit int64
|
||||
blocks int // blocks fetched with the block sizes claimed
|
||||
}{
|
||||
{0, -1, 3},
|
||||
{0, 1, 1},
|
||||
{0, 0, 0},
|
||||
{4<<20 - 1, 2, 2},
|
||||
{4 << 20, -1, 2},
|
||||
{bigSize - 1, -1, 1},
|
||||
{bigSize, -1, 0},
|
||||
{8 << 20, 100, 1},
|
||||
{bigSize - 10, 100, 1},
|
||||
} {
|
||||
want := content[tc.offset:]
|
||||
if tc.limit >= 0 {
|
||||
want = want[:min(tc.limit, int64(len(want)))]
|
||||
}
|
||||
for _, v := range []struct {
|
||||
name string
|
||||
n *node
|
||||
}{{"claimed", claimed}, {"unrecorded", unrecorded}} {
|
||||
t.Run(v.name+"/"+strconv.FormatInt(tc.offset, 10)+"+"+strconv.FormatInt(tc.limit, 10), func(t *testing.T) {
|
||||
srv.ResetRequests()
|
||||
data, err := readRange(t, c, v.n, tc.offset, tc.limit)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, bytes.Equal(want, data), "got %d bytes, want %d", len(data), len(want))
|
||||
fetched := srv.Requests()[storagePattern]
|
||||
if v.n == claimed {
|
||||
assert.Equal(t, tc.blocks, fetched, "blocks fetched")
|
||||
return
|
||||
}
|
||||
// The block sizes learnt by the first, full, read
|
||||
// place the range; blocks past it may be fetched ahead
|
||||
// before the reader is closed.
|
||||
assert.GreaterOrEqual(t, fetched, tc.blocks, "blocks fetched")
|
||||
assert.LessOrEqual(t, fetched, 3, "blocks fetched")
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadRangesUnrecordedBlockSizes(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, _, u := newTestClient(t)
|
||||
const size = 6<<20 + 5
|
||||
content := testContent(size)
|
||||
// Blocks of 1 MiB, which a reader assuming 4 MiB blocks would
|
||||
// place wrongly.
|
||||
n := getTestNode(t, c, u.SeedFileInBlocks(u.RootID(), "small-blocks", content, 1<<20))
|
||||
require.Nil(t, n.X.BlockSizes)
|
||||
for _, tc := range []struct{ offset, limit int64 }{
|
||||
{0, -1},
|
||||
{0, 3 << 20},
|
||||
{10, 100},
|
||||
{1<<20 - 3, 10},
|
||||
{4<<20 + 10, 100},
|
||||
{4<<20 + 10, -1},
|
||||
{2<<20 + 7, 3 << 20},
|
||||
{size - 1, -1},
|
||||
{size, -1},
|
||||
} {
|
||||
t.Run(strconv.FormatInt(tc.offset, 10)+"+"+strconv.FormatInt(tc.limit, 10), func(t *testing.T) {
|
||||
want := content[tc.offset:]
|
||||
if tc.limit >= 0 {
|
||||
want = want[:min(tc.limit, int64(len(want)))]
|
||||
}
|
||||
data, err := readRange(t, c, n, tc.offset, tc.limit)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, bytes.Equal(want, data), "got %d bytes, want %d", len(data), len(want))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadChunksUnrecordedBlockSizes(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, srv, u := newTestClient(t)
|
||||
const (
|
||||
blocks = 32
|
||||
chunk = 4 << 20
|
||||
blockBytes = 1 << 20
|
||||
)
|
||||
content := testContent(blocks * blockBytes)
|
||||
id := u.SeedFileInBlocks(u.RootID(), "chunks", content, blockBytes)
|
||||
n := getTestNode(t, c, id)
|
||||
require.Nil(t, n.X.BlockSizes)
|
||||
|
||||
// A multi-thread copy opens each chunk as a range of its own.
|
||||
srv.ResetRequests()
|
||||
for offset := int64(0); offset < int64(len(content)); offset += chunk {
|
||||
data, err := readRange(t, c, n, offset, chunk)
|
||||
require.NoError(t, err)
|
||||
require.True(t, bytes.Equal(content[offset:offset+chunk], data), "chunk at %d", offset)
|
||||
}
|
||||
fetched := srv.Requests()[storagePattern]
|
||||
t.Logf("%d blocks fetched for %d chunks of a file of %d blocks", fetched, len(content)/chunk, blocks)
|
||||
// Reading each chunk from the first block would fetch about
|
||||
// blocks^2/(2*blocks per chunk) = 128; each chunk may fetch up to
|
||||
// downloadAhead blocks past its end.
|
||||
assert.LessOrEqual(t, fetched, blocks+len(content)/chunk*downloadAhead, "chunks read from the first block")
|
||||
|
||||
// Once the sizes are known, a range fetches only its own blocks.
|
||||
srv.ResetRequests()
|
||||
data, err := readRange(t, c, n, 10*blockBytes+5, 2*blockBytes)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, content[10*blockBytes+5:12*blockBytes+5], data)
|
||||
assert.Equal(t, 3, srv.Requests()[storagePattern], "blocks fetched")
|
||||
|
||||
// A block list which changed since then is an integrity error.
|
||||
u.Corrupt(id, "swap-blocks")
|
||||
_, err = readRange(t, c, n, 5, 10)
|
||||
require.ErrorIs(t, err, errIntegrity)
|
||||
assert.Contains(t, err.Error(), "listed with another hash")
|
||||
}
|
||||
|
||||
func TestDownloadLegacyFile(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, _, u := newTestClient(t)
|
||||
content := testContent(5<<20 + 7)
|
||||
n := getTestNode(t, c, u.SeedLegacyFile(u.RootID(), "legacy", content))
|
||||
data, err := readRange(t, c, n, 0, -1)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, bytes.Equal(content, data), "content differs")
|
||||
data, err = readRange(t, c, n, 4<<20+3, 10)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, content[4<<20+3:4<<20+13], data)
|
||||
}
|
||||
|
||||
func TestDownloadManifestSigners(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, srv, u := newTestClient(t)
|
||||
other := srv.AddUser("other", "pass")
|
||||
content := testContent(1000)
|
||||
for name, id := range map[string]string{
|
||||
"other user": u.SeedFileSignedBy(other, u.RootID(), "other", content, time.Now()),
|
||||
"anonymous": u.SeedAnonymousFile(u.RootID(), "anonymous", content, time.Now()),
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
data, err := readRange(t, c, getTestNode(t, c, id), 0, -1)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, content, data)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadContentKey(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
const second = "second@proton.test"
|
||||
u.AddAddress(second)
|
||||
c := newTestClientFor(t, srv, u, clientOptions{})
|
||||
ignoring := newTestClientFor(t, srv, u, clientOptions{IgnoreSignatureErrors: true})
|
||||
before2023 := time.Date(2022, 6, 1, 0, 0, 0, 0, time.UTC)
|
||||
content := testContent(1000)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
signer string
|
||||
created time.Time
|
||||
ok bool
|
||||
}{
|
||||
{"unsigned", "", time.Now(), false},
|
||||
{"unsigned before 2023", "", before2023, false},
|
||||
{"signer address", u.Email(), time.Now(), true},
|
||||
{"other address before 2023", second, before2023, true},
|
||||
{"other address after 2023", second, time.Now(), false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
id := u.SeedFileContentKeySignedBy(tc.signer, tc.created, u.RootID(), tc.name, content)
|
||||
data, err := readRange(t, c, getTestNode(t, c, id), 0, -1)
|
||||
if !tc.ok {
|
||||
require.ErrorIs(t, err, errIntegrity)
|
||||
assert.Contains(t, err.Error(), "ignore_signature_errors")
|
||||
data, err = readRange(t, ignoring, getTestNode(t, ignoring, id), 0, -1)
|
||||
}
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, content, data)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadNodeKeySignature(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, srv, u := newTestClient(t)
|
||||
content := testContent(1000)
|
||||
id := u.SeedFile(u.RootID(), "f", content, time.Now())
|
||||
u.Corrupt(id, "passphrase-signature")
|
||||
n := getTestNode(t, c, id)
|
||||
|
||||
data, err := readRange(t, c, n, 0, -1)
|
||||
require.ErrorIs(t, err, errIntegrity)
|
||||
assert.Contains(t, err.Error(), "ignore_signature_errors")
|
||||
assert.Empty(t, data)
|
||||
_, err = readRange(t, c, n, 10, 10)
|
||||
require.ErrorIs(t, err, errIntegrity, "a ranged read")
|
||||
|
||||
ignoring := newTestClientFor(t, srv, u, clientOptions{IgnoreSignatureErrors: true})
|
||||
data, err = readRange(t, ignoring, getTestNode(t, ignoring, id), 0, -1)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, content, data)
|
||||
}
|
||||
|
||||
func TestDownloadBlockHashMismatch(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, srv, u := newTestClient(t)
|
||||
n := seedFile(t, c, u, "f", testContent(1<<20))
|
||||
u.Corrupt(n.ID, "block-hash")
|
||||
srv.ResetRequests()
|
||||
data, err := readRange(t, c, n, 0, -1)
|
||||
require.ErrorIs(t, err, errBlockHash)
|
||||
assert.Empty(t, data)
|
||||
assert.Equal(t, 3, srv.Requests()[storagePattern], "block attempts")
|
||||
// The listing page, the empty page ending the list and a new URL
|
||||
// for each retry.
|
||||
assert.Equal(t, 4, srv.Requests()[revisionPattern])
|
||||
}
|
||||
|
||||
func TestDownloadSwappedBlocks(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, _, u := newTestClient(t)
|
||||
n := seedFile(t, c, u, "f", testContent(bigSize))
|
||||
u.Corrupt(n.ID, "swap-blocks")
|
||||
_, err := readRange(t, c, n, 0, -1)
|
||||
require.ErrorIs(t, err, errIntegrity)
|
||||
}
|
||||
|
||||
func TestDownloadTruncatedBlocks(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, _, u := newTestClient(t)
|
||||
n := seedFile(t, c, u, "f", testContent(bigSize))
|
||||
u.Corrupt(n.ID, "truncate-blocks")
|
||||
_, err := readRange(t, c, n, 0, -1)
|
||||
require.ErrorIs(t, err, errIntegrity)
|
||||
// Without block sizes, only the manifest shows the loss.
|
||||
_, err = readRange(t, c, withoutBlockSizes(n), 0, -1)
|
||||
require.ErrorIs(t, err, errIntegrity)
|
||||
}
|
||||
|
||||
func TestDownloadBadManifest(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, srv, u := newTestClient(t)
|
||||
content := testContent(bigSize)
|
||||
n := seedFile(t, c, u, "f", content)
|
||||
u.Corrupt(n.ID, "manifest")
|
||||
|
||||
data, err := readRange(t, c, n, 0, -1)
|
||||
require.ErrorIs(t, err, errIntegrity)
|
||||
assert.Contains(t, err.Error(), "ignore_signature_errors")
|
||||
assert.Empty(t, data, "no byte comes before the verdict")
|
||||
|
||||
// A ranged read can't check the manifest.
|
||||
data, err = readRange(t, c, n, 0, 100)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, content[:100], data)
|
||||
|
||||
ignoring := newTestClientFor(t, srv, u, clientOptions{IgnoreSignatureErrors: true})
|
||||
data, err = readRange(t, ignoring, getTestNode(t, ignoring, n.ID), 0, -1)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, bytes.Equal(content, data), "content differs")
|
||||
}
|
||||
|
||||
func TestDownloadEmptyFileBadManifest(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, _, u := newTestClient(t)
|
||||
n := seedFile(t, c, u, "empty", nil)
|
||||
u.Corrupt(n.ID, "manifest")
|
||||
_, err := readRange(t, c, n, 0, -1)
|
||||
require.ErrorIs(t, err, errIntegrity)
|
||||
}
|
||||
|
||||
func TestDownloadStorage404Refetch(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, srv, u := newTestClient(t)
|
||||
content := testContent(1 << 20)
|
||||
n := seedFile(t, c, u, "f", content)
|
||||
|
||||
srv.Inject(protontest.Fault{Pattern: "/storage/blocks/{id}", Status: http.StatusNotFound, Times: 1})
|
||||
srv.ResetRequests()
|
||||
data, err := readRange(t, c, n, 0, -1)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, content, data)
|
||||
assert.Equal(t, 2, srv.Requests()[storagePattern])
|
||||
// The listing page, the new URL and the empty page ending the list.
|
||||
assert.Equal(t, 3, srv.Requests()[revisionPattern])
|
||||
|
||||
// The URL is requested again only once.
|
||||
srv.Inject(protontest.Fault{Pattern: "/storage/blocks/{id}", Status: http.StatusNotFound})
|
||||
srv.ResetRequests()
|
||||
_, err = readRange(t, c, n, 0, -1)
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, 2, srv.Requests()[storagePattern])
|
||||
}
|
||||
|
||||
func TestDownloadRefetchOtherHash(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, srv, u := newTestClient(t)
|
||||
n := seedFile(t, c, u, "f", testContent(1<<20))
|
||||
|
||||
// The block's URL expires, and the server lists it again with
|
||||
// another block, which the checked manifest doesn't cover. The
|
||||
// delay is the time to corrupt it in, which a loaded machine needs.
|
||||
srv.Inject(protontest.Fault{Pattern: "/storage/blocks/{id}", Status: http.StatusNotFound, Times: 1, Delay: 2 * time.Second})
|
||||
done := make(chan struct{})
|
||||
var data []byte
|
||||
var err error
|
||||
go func() {
|
||||
defer close(done)
|
||||
data, err = readRange(t, c, n, 0, -1)
|
||||
}()
|
||||
require.Eventually(t, func() bool { return srv.Requests()[storagePattern] == 1 }, 5*time.Second, 5*time.Millisecond)
|
||||
u.Corrupt(n.ID, "foreign-block")
|
||||
<-done
|
||||
require.ErrorIs(t, err, errIntegrity)
|
||||
assert.Contains(t, err.Error(), "listed again with another hash")
|
||||
assert.Empty(t, data)
|
||||
}
|
||||
|
||||
func TestDownloadRetries5xx(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, srv, u := newTestClient(t)
|
||||
content := testContent(1 << 20)
|
||||
n := seedFile(t, c, u, "f", content)
|
||||
srv.Inject(protontest.Fault{Pattern: "/storage/blocks/{id}", Status: http.StatusServiceUnavailable, Times: 2})
|
||||
srv.Inject(protontest.Fault{Pattern: "/drive/v2/volumes/{volumeID}/files/{linkID}/revisions/{revisionID}", Status: http.StatusBadGateway, Times: 1})
|
||||
srv.ResetRequests()
|
||||
data, err := readRange(t, c, n, 0, -1)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, content, data)
|
||||
assert.Equal(t, 3, srv.Requests()[storagePattern])
|
||||
}
|
||||
|
||||
func TestDownloadStorageRetryAfter(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, srv, u := newTestClient(t)
|
||||
content := testContent(1000)
|
||||
n := seedFile(t, c, u, "f", content)
|
||||
srv.Inject(protontest.Fault{Pattern: "/storage/blocks/{id}", Status: http.StatusTooManyRequests, RetryAfter: 1, Times: 1})
|
||||
start := time.Now()
|
||||
data, err := readRange(t, c, n, 0, -1)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, content, data)
|
||||
assert.GreaterOrEqual(t, time.Since(start), time.Second)
|
||||
}
|
||||
|
||||
func TestDownloadStorageHeaders(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
var (
|
||||
mu sync.Mutex
|
||||
headers []http.Header
|
||||
)
|
||||
c := newTestClientTransport(t, srv, u, clientOptions{}, func(next http.RoundTripper) http.RoundTripper {
|
||||
return roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if strings.HasPrefix(r.URL.Path, "/storage/") {
|
||||
mu.Lock()
|
||||
headers = append(headers, r.Header.Clone())
|
||||
mu.Unlock()
|
||||
}
|
||||
return next.RoundTrip(r)
|
||||
})
|
||||
})
|
||||
n := seedFile(t, c, u, "f", testContent(4<<20+1))
|
||||
_, err := readRange(t, c, n, 0, -1)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, headers, 2)
|
||||
for _, h := range headers {
|
||||
assert.Empty(t, h.Get("Authorization"))
|
||||
assert.Empty(t, h.Get("x-pm-uid"))
|
||||
assert.NotEmpty(t, h.Get("pm-storage-token"))
|
||||
assert.Equal(t, testAppVersion, h.Get("x-pm-appversion"))
|
||||
}
|
||||
|
||||
// Block URLs on another host, as the real storage host is, get the
|
||||
// same headers. The other host passes requests on to the fake.
|
||||
var other []http.Header
|
||||
storage := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
other = append(other, r.Header.Clone())
|
||||
mu.Unlock()
|
||||
req, err := http.NewRequestWithContext(r.Context(), "GET", srv.URL()+r.URL.Path, nil)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
for _, k := range []string{"pm-storage-token", "x-pm-appversion"} {
|
||||
req.Header.Set(k, r.Header.Get(k))
|
||||
}
|
||||
resp, err := srv.Client().Do(req)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
w.WriteHeader(resp.StatusCode)
|
||||
_, _ = io.Copy(w, resp.Body)
|
||||
}))
|
||||
t.Cleanup(storage.Close)
|
||||
require.NotEqual(t, srv.URL(), storage.URL)
|
||||
moved := newTestClientTransport(t, srv, u, clientOptions{}, func(next http.RoundTripper) http.RoundTripper {
|
||||
return roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
resp, err := next.RoundTrip(r)
|
||||
if err != nil || !strings.Contains(r.URL.Path, "/revisions/") {
|
||||
return resp, err
|
||||
}
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body = bytes.ReplaceAll(body, []byte(srv.URL()+"/storage/"), []byte(storage.URL+"/storage/"))
|
||||
resp.Body = io.NopCloser(bytes.NewReader(body))
|
||||
resp.ContentLength = int64(len(body))
|
||||
resp.Header.Del("Content-Length")
|
||||
return resp, nil
|
||||
})
|
||||
})
|
||||
_, err = readRange(t, moved, getTestNode(t, moved, n.ID), 0, -1)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, other, 2)
|
||||
for _, h := range other {
|
||||
assert.Empty(t, h.Get("Authorization"))
|
||||
assert.Empty(t, h.Get("x-pm-uid"))
|
||||
assert.NotEmpty(t, h.Get("pm-storage-token"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadBlockTooLarge(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
var fetches atomic.Int32
|
||||
c := newTestClientTransport(t, srv, u, clientOptions{}, func(next http.RoundTripper) http.RoundTripper {
|
||||
return roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if !strings.HasPrefix(r.URL.Path, "/storage/") {
|
||||
return next.RoundTrip(r)
|
||||
}
|
||||
fetches.Add(1)
|
||||
// An endless body of unknown length.
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{},
|
||||
Body: io.NopCloser(zeroReader{}),
|
||||
ContentLength: -1,
|
||||
Request: r,
|
||||
}, nil
|
||||
})
|
||||
})
|
||||
n := seedFile(t, c, u, "f", testContent(1000))
|
||||
_, err := readRange(t, c, n, 0, -1)
|
||||
require.ErrorContains(t, err, "larger than")
|
||||
assert.NotErrorIs(t, err, errBlockHash)
|
||||
assert.Equal(t, int32(1), fetches.Load(), "an oversized block is not fetched again")
|
||||
}
|
||||
|
||||
// zeroReader reads zeros forever.
|
||||
type zeroReader struct{}
|
||||
|
||||
// Read fills p with zeros.
|
||||
func (zeroReader) Read(p []byte) (int, error) {
|
||||
clear(p)
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
// endlessBlockList returns a transport wrapper whose revision pages are
|
||||
// all full of copies of the file's first block, renumbered, counting
|
||||
// the pages in pages.
|
||||
func endlessBlockList(pages *atomic.Int32) func(next http.RoundTripper) http.RoundTripper {
|
||||
var (
|
||||
mu sync.Mutex
|
||||
first map[string]any
|
||||
)
|
||||
return func(next http.RoundTripper) http.RoundTripper {
|
||||
return roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
resp, err := next.RoundTrip(r)
|
||||
if err != nil || !strings.Contains(r.URL.Path, "/revisions/") {
|
||||
return resp, err
|
||||
}
|
||||
pages.Add(1)
|
||||
var body map[string]any
|
||||
err = json.NewDecoder(resp.Body).Decode(&body)
|
||||
_ = resp.Body.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rev := body["Revision"].(map[string]any)
|
||||
mu.Lock()
|
||||
if blocks := rev["Blocks"].([]any); first == nil && len(blocks) > 0 {
|
||||
first = blocks[0].(map[string]any)
|
||||
}
|
||||
from, _ := strconv.Atoi(r.URL.Query().Get("FromBlockIndex"))
|
||||
size, _ := strconv.Atoi(r.URL.Query().Get("PageSize"))
|
||||
var blocks []any
|
||||
for i := range size {
|
||||
b := make(map[string]any, len(first))
|
||||
for k, v := range first {
|
||||
b[k] = v
|
||||
}
|
||||
b["Index"] = from + i
|
||||
blocks = append(blocks, b)
|
||||
}
|
||||
mu.Unlock()
|
||||
rev["Blocks"] = blocks
|
||||
data, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp.Body = io.NopCloser(bytes.NewReader(data))
|
||||
resp.ContentLength = int64(len(data))
|
||||
resp.Header.Del("Content-Length")
|
||||
return resp, nil
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadEndlessBlockList(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
var pages atomic.Int32
|
||||
c := newTestClientTransport(t, srv, u, clientOptions{EnableCaching: true}, endlessBlockList(&pages))
|
||||
n := seedFile(t, c, u, "f", testContent(4<<20+1))
|
||||
for name, n := range map[string]*node{"claimed": n, "unrecorded": withoutBlockSizes(n)} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
pages.Store(0)
|
||||
data, err := readRange(t, c, n, 0, -1)
|
||||
require.ErrorIs(t, err, errIntegrity)
|
||||
assert.LessOrEqual(t, len(data), 5*(4<<20))
|
||||
assert.LessOrEqual(t, pages.Load(), int32(2))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadBlockCap(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
var pages atomic.Int32
|
||||
c := newTestClientTransport(t, srv, u, clientOptions{EnableCaching: true}, endlessBlockList(&pages))
|
||||
c.maxFileBlocks = 45
|
||||
n := seedFile(t, c, u, "f", testContent(4<<20+1))
|
||||
|
||||
// The encrypted size, which nothing signs, claims room for many
|
||||
// more blocks than the cap.
|
||||
huge := withoutBlockSizes(n)
|
||||
huge.EncryptedSize = 1 << 50
|
||||
data, err := readRange(t, c, huge, 0, -1)
|
||||
require.ErrorIs(t, err, errIntegrity)
|
||||
assert.Contains(t, err.Error(), "more than 45 blocks")
|
||||
assert.Empty(t, data)
|
||||
assert.LessOrEqual(t, pages.Load(), int32(3), "listed past the cap")
|
||||
|
||||
// Recorded block sizes beyond the cap fail before any request.
|
||||
claims := *n
|
||||
x := *n.X
|
||||
x.BlockSizes = make([]int64, 46)
|
||||
claims.X = &x
|
||||
pages.Store(0)
|
||||
_, err = readRange(t, c, &claims, 0, -1)
|
||||
require.ErrorIs(t, err, errIntegrity)
|
||||
assert.Zero(t, pages.Load())
|
||||
}
|
||||
|
||||
func TestDownloadCloseEarly(t *testing.T) {
|
||||
c, srv, u := newTestClient(t)
|
||||
n := seedFile(t, c, u, "f", testContent(8<<20))
|
||||
goroutines, buffers := leakBaseline(srv)
|
||||
|
||||
rc, err := c.open(context.Background(), n, 0, -1)
|
||||
require.NoError(t, err)
|
||||
buf := make([]byte, 10)
|
||||
_, err = io.ReadFull(rc, buf)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, rc.Close())
|
||||
require.NoError(t, rc.Close())
|
||||
_, err = rc.Read(buf)
|
||||
require.Error(t, err)
|
||||
requireNoLeaks(t, srv, goroutines, buffers)
|
||||
}
|
||||
|
||||
func TestDownloadContextCancel(t *testing.T) {
|
||||
c, srv, u := newTestClient(t)
|
||||
n := seedFile(t, c, u, "f", testContent(8<<20))
|
||||
// One of the blocks takes far longer than the test.
|
||||
srv.Inject(protontest.Fault{Pattern: "/storage/blocks/{id}", Skip: 1, Times: 1, Delay: time.Minute})
|
||||
goroutines, buffers := leakBaseline(srv)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
rc, err := c.open(ctx, n, 0, -1)
|
||||
require.NoError(t, err)
|
||||
time.AfterFunc(200*time.Millisecond, cancel)
|
||||
start := time.Now()
|
||||
data, err := io.ReadAll(rc)
|
||||
require.ErrorIs(t, err, context.Canceled)
|
||||
assert.Less(t, len(data), 8<<20)
|
||||
assert.Less(t, time.Since(start), 10*time.Second)
|
||||
require.NoError(t, rc.Close())
|
||||
requireNoLeaks(t, srv, goroutines, buffers)
|
||||
}
|
||||
|
||||
func TestDownloadHostileBlockSizes(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, _, u := newTestClient(t)
|
||||
small := testContent(1000)
|
||||
big := testContent(4<<20 + 1)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
content []byte
|
||||
sizes []int64
|
||||
}{
|
||||
{"overflowing", small, []int64{math.MaxInt64, 1}},
|
||||
{"above the cap", small, []int64{maxBlockSize + 1}},
|
||||
{"sum too small", big, []int64{1000}},
|
||||
{"too few blocks", big, []int64{4 << 20}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
n := getTestNode(t, c, u.SeedFileClaimingBlockSizes(u.RootID(), tc.name, tc.content, tc.sizes))
|
||||
require.Equal(t, tc.sizes, n.X.BlockSizes)
|
||||
_, err := readRange(t, c, n, 0, -1)
|
||||
require.ErrorIs(t, err, errIntegrity)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// frozenFileDir holds files the old library (go-proton-api v1.0.4 and
|
||||
// Proton-API-Bridge v1.0.5) wrote, as the server stored them, one
|
||||
// directory per format: "legacy" (v3 PKESK content key, SEIPDv1 blocks)
|
||||
// and "v6" (v6 PKESK content key, SEIPDv2 blocks). The old library only
|
||||
// writes v6 content as a revision of a file another client created, so
|
||||
// in "v6" the node key and content key packet with its signature are
|
||||
// SDK-style stand-ins made with plain gopenpgp.
|
||||
const frozenFileDir = "testdata/oldlib/file"
|
||||
|
||||
// frozenFile is a file a client holding Keys stored, with what it
|
||||
// encrypted. In a directory, file.json holds it but Stored, which is
|
||||
// in link.json, revision.json and block-1.bin, block-2.bin...
|
||||
type frozenFile struct {
|
||||
Comment string
|
||||
Email string // address which signed everything, the owner's primary address
|
||||
Keys protontest.FixedKeys
|
||||
Name string
|
||||
ModTime string // as the writer recorded it in the extended attributes
|
||||
Content []byte
|
||||
Stored protontest.StoredFile `json:"-"`
|
||||
}
|
||||
|
||||
// frozenFileParts returns the names of the files of f in a directory
|
||||
// and the values they hold.
|
||||
func frozenFileParts(f *frozenFile) map[string]any {
|
||||
return map[string]any{"file.json": f, "link.json": &f.Stored.Link, "revision.json": &f.Stored.Revision}
|
||||
}
|
||||
|
||||
// blockFileName returns the name of the file holding block i, from 0.
|
||||
func blockFileName(i int) string {
|
||||
return "block-" + strconv.Itoa(i+1) + ".bin"
|
||||
}
|
||||
|
||||
// loadFrozenFile returns the file in dir.
|
||||
func loadFrozenFile(t testing.TB, dir string) frozenFile {
|
||||
t.Helper()
|
||||
var f frozenFile
|
||||
for name, v := range frozenFileParts(&f) {
|
||||
data, err := os.ReadFile(filepath.Join(dir, name))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, json.Unmarshal(data, v), name)
|
||||
}
|
||||
for i := range f.Stored.Revision.Blocks {
|
||||
data, err := os.ReadFile(filepath.Join(dir, blockFileName(i)))
|
||||
require.NoError(t, err)
|
||||
f.Stored.Revision.Blocks[i].Data = data
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
// checkFrozenFile stores f for a user holding its keys and checks that
|
||||
// the client reads its metadata, verifying every signature, and
|
||||
// downloads its content.
|
||||
func checkFrozenFile(t *testing.T, f frozenFile) {
|
||||
t.Helper()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUserWithKeys(f.Email, "pass", f.Keys)
|
||||
c := newTestClientFor(t, srv, u, clientOptions{})
|
||||
n := getTestNode(t, c, u.SeedStoredFile(u.RootID(), f.Stored))
|
||||
assert.Equal(t, f.Name, n.Name)
|
||||
require.NotNil(t, n.X, "extended attributes")
|
||||
modTime, err := time.Parse("2006-01-02T15:04:05-0700", f.ModTime)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, modTime.Equal(n.modTime()), "modification time %v, want %v", n.modTime(), modTime)
|
||||
assert.Equal(t, int64(len(f.Content)), n.size(true))
|
||||
assert.Equal(t, sha1Of(f.Content), n.sha1())
|
||||
data, err := readRange(t, c, n, 0, -1)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, bytes.Equal(f.Content, data), "content differs: %d bytes, want %d", len(data), len(f.Content))
|
||||
assert.Empty(t, c.reported, "problems reported")
|
||||
}
|
||||
|
||||
func TestFrozenFileFixture(t *testing.T) {
|
||||
for format, want := range map[string]struct{ pkesk, seipd int }{"legacy": {3, 1}, "v6": {6, 2}} {
|
||||
t.Run(format, func(t *testing.T) {
|
||||
f := loadFrozenFile(t, filepath.Join(frozenFileDir, format))
|
||||
// The fixture is in the format its directory names.
|
||||
keyPacket, err := base64.StdEncoding.DecodeString(f.Stored.Link.ContentKeyPacket)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, want.pkesk, readPackets(t, keyPacket, 1)[0].(*packet.EncryptedKey).Version, "content key packet")
|
||||
require.NotEmpty(t, f.Stored.Revision.Blocks)
|
||||
for i, b := range f.Stored.Revision.Blocks {
|
||||
assert.Equal(t, want.seipd, readPackets(t, b.Data, 1)[0].(*packet.SymmetricallyEncrypted).Version, "block %d", i+1)
|
||||
}
|
||||
checkFrozenFile(t, f)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestStorageTokenNotRedirected checks a block's storage token isn't
|
||||
// sent on to another host a storage request is redirected to.
|
||||
func TestStorageTokenNotRedirected(t *testing.T) {
|
||||
t.Parallel()
|
||||
got := make(chan http.Header, 2)
|
||||
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
got <- r.Header.Clone()
|
||||
_, _ = w.Write([]byte("block"))
|
||||
}))
|
||||
defer other.Close()
|
||||
storage := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
got <- r.Header.Clone()
|
||||
http.Redirect(w, r, other.URL+"/block", http.StatusFound)
|
||||
}))
|
||||
defer storage.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
c := &client{
|
||||
s: newSession(&http.Client{}, "http://127.0.0.1:1", testAppVersion, &memoryStore{}),
|
||||
storagePacer: newDrivePacer(ctx),
|
||||
downloadTokens: pacer.NewTokenDispenser(1),
|
||||
}
|
||||
enc, _, err := c.downloadBlock(ctx, storage.URL+"/block", "secret-token")
|
||||
require.NoError(t, err)
|
||||
_ = enc.Close()
|
||||
assert.Equal(t, "secret-token", (<-got).Get("pm-storage-token"), "sent to the storage host")
|
||||
assert.Empty(t, (<-got).Get("pm-storage-token"), "sent on to another host")
|
||||
}
|
||||
@@ -0,0 +1,574 @@
|
||||
package protondrive
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/rclone/rclone/backend/protondrive/api"
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/lib/pacer"
|
||||
"github.com/rclone/rclone/lib/rest"
|
||||
)
|
||||
|
||||
const (
|
||||
// minEventsInterval is the shortest time between polls of Proton's
|
||||
// endpoint for events: the SDK's for the user's own volume.
|
||||
minEventsInterval = 30 * time.Second
|
||||
|
||||
// eventsJitter is the most random time added to each wait between
|
||||
// polls, as in the SDK.
|
||||
eventsJitter = time.Second
|
||||
|
||||
// maxEventsBackoff is the longest wait between polls which fail.
|
||||
maxEventsBackoff = 10 * time.Minute
|
||||
|
||||
// maxPendingNodes is the most nodes the poller waits to name.
|
||||
maxPendingNodes = 1000
|
||||
|
||||
// pendingPolls is the number of polls after its change in which a
|
||||
// node not cached then is named if it is cached by then.
|
||||
pendingPolls = 2
|
||||
|
||||
// cacheIdleTime is how long the cache may go unused, with nothing
|
||||
// subscribed, before the poller clears it and so stops polling.
|
||||
cacheIdleTime = 10 * time.Minute
|
||||
)
|
||||
|
||||
// errVolumeGone is returned by the events calls when the volume no
|
||||
// longer exists or can't be reached: no later poll can succeed.
|
||||
var errVolumeGone = errors.New("volume gone")
|
||||
|
||||
// eventChange is a change to a node the volume events report. Events
|
||||
// name the node and its parent but not its name or type, and report its
|
||||
// parent and trash state as they are when read, which may be after
|
||||
// later changes.
|
||||
type eventChange struct {
|
||||
linkID string
|
||||
parentID string // parent when read; empty if not reported
|
||||
kind int // api.EventDelete etc
|
||||
trashed bool // whether the node was in the trash when read
|
||||
}
|
||||
|
||||
// staleNode is what the cache knew of a changed node before the change
|
||||
// was applied.
|
||||
type staleNode struct {
|
||||
id string
|
||||
parentID string // the cached parent; empty unless known
|
||||
name string // empty unless known
|
||||
isDir bool
|
||||
known bool // whether the node was cached
|
||||
|
||||
newParentID string // the parent the change reports; empty if not reported
|
||||
gone bool // whether the change deleted or trashed the node
|
||||
|
||||
late bool // whether the node changed in an earlier poll, before it was cached; see subscribe
|
||||
}
|
||||
|
||||
// latestEventID returns the ID of the newest event of the volume, from
|
||||
// which pollEvents reports the changes made after now. It wraps
|
||||
// errVolumeGone if the volume is gone.
|
||||
func (c *client) latestEventID(ctx context.Context) (string, error) {
|
||||
opts := &rest.Opts{
|
||||
Method: "GET",
|
||||
Path: c.volumePath("/drive/volumes", "events", "latest"),
|
||||
}
|
||||
var resp api.LatestEventResponse
|
||||
if err := c.eventsCall(ctx, opts, &resp); err != nil {
|
||||
return "", eventsError("get latest event", err)
|
||||
}
|
||||
if resp.EventID == "" {
|
||||
return "", errors.New("get latest event: no event ID in the response")
|
||||
}
|
||||
return resp.EventID, nil
|
||||
}
|
||||
|
||||
// maxEventPages is the most pages of events one poll reads; the rest
|
||||
// are read by the next poll.
|
||||
const maxEventPages = 100
|
||||
|
||||
// pollEvents returns the changes after event cursor, oldest first, and
|
||||
// the event ID to poll from next, reading up to maxEventPages pages.
|
||||
//
|
||||
// If the server no longer knows cursor it returns refresh set, no
|
||||
// changes and the newest event ID: anything cached may be out of date.
|
||||
// On error it returns no changes, and the poll should be retried from
|
||||
// cursor. It wraps errVolumeGone if the volume is gone.
|
||||
func (c *client) pollEvents(ctx context.Context, cursor string) (changes []eventChange, next string, refresh bool, err error) {
|
||||
for pages := 1; ; pages++ {
|
||||
opts := &rest.Opts{
|
||||
Method: "GET",
|
||||
Path: c.volumePath("/drive/v2/volumes", "events", cursor),
|
||||
}
|
||||
var page api.EventsResponse
|
||||
if err := c.eventsCall(ctx, opts, &page); err != nil {
|
||||
return nil, "", false, eventsError("list events", err)
|
||||
}
|
||||
if page.EventID == "" {
|
||||
return nil, "", false, errors.New("list events: no event ID in the response")
|
||||
}
|
||||
if page.Refresh {
|
||||
fs.Debugf(nil, "protondrive: events: event %s is no longer known: refreshing", cursor)
|
||||
return nil, page.EventID, true, nil
|
||||
}
|
||||
fs.Debugf(nil, "protondrive: events: %d after %s (more %v)", len(page.Events), cursor, page.More)
|
||||
changes = append(changes, eventChanges(page.Events)...)
|
||||
// As in the SDK, a page without events ends the poll whatever
|
||||
// More says, and so does one which doesn't advance.
|
||||
if page.More && len(page.Events) > 0 && page.EventID == cursor {
|
||||
fs.Debugf(nil, "protondrive: events: page after %s doesn't advance: its events will be read again", cursor)
|
||||
}
|
||||
if !page.More || len(page.Events) == 0 || page.EventID == cursor || pages >= maxEventPages {
|
||||
return changes, page.EventID, false, nil
|
||||
}
|
||||
cursor = page.EventID
|
||||
}
|
||||
}
|
||||
|
||||
// eventsCall makes the events API call opts as apiCall does, but
|
||||
// tries it only once and doesn't wait out a Retry-After: the poller
|
||||
// backs off itself, and the returned error carries the Retry-After for
|
||||
// pacer.IsRetryAfter.
|
||||
func (c *client) eventsCall(ctx context.Context, opts *rest.Opts, response any) error {
|
||||
var retryAfter time.Duration
|
||||
err := c.apiPacer.CallNoRetry(func() (bool, error) {
|
||||
resp, err := c.s.call(ctx, opts, nil, response)
|
||||
retry, err := c.shouldRetry(ctx, resp, err)
|
||||
if wait, ok := pacer.IsRetryAfter(err); ok {
|
||||
// Kept from the pacer, which would hold every call of the
|
||||
// client for it.
|
||||
retryAfter = wait
|
||||
err = errors.Unwrap(err)
|
||||
}
|
||||
return retry, err
|
||||
})
|
||||
if retryAfter > 0 {
|
||||
return pacer.RetryAfterError(err, retryAfter)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// eventsError returns err of the events call what, wrapping
|
||||
// errVolumeGone for API code 2501.
|
||||
func eventsError(what string, err error) error {
|
||||
if apiErrorCode(err) == api.CodeNotExists {
|
||||
return fmt.Errorf("%s: %w: %w", what, errVolumeGone, err)
|
||||
}
|
||||
return fmt.Errorf("%s: %w", what, err)
|
||||
}
|
||||
|
||||
// eventChanges returns the changes events report, leaving out any
|
||||
// which name no node.
|
||||
func eventChanges(events []api.Event) []eventChange {
|
||||
changes := make([]eventChange, 0, len(events))
|
||||
for _, e := range events {
|
||||
if e.Link.LinkID == "" {
|
||||
fs.Debugf(nil, "protondrive: events: ignoring event %q naming no node", e.EventID)
|
||||
continue
|
||||
}
|
||||
changes = append(changes, eventChange{
|
||||
linkID: e.Link.LinkID,
|
||||
parentID: e.Link.ParentLinkID,
|
||||
kind: e.EventType,
|
||||
trashed: e.Link.IsTrashed,
|
||||
})
|
||||
}
|
||||
return changes
|
||||
}
|
||||
|
||||
// applyEvents drops from the cache what changes make out of date, in
|
||||
// order, and returns what it knew of each changed node before: stale[i]
|
||||
// is for changes[i].
|
||||
//
|
||||
// A deleted node, and a folder moved or trashed, goes with everything
|
||||
// cached below it. Another changed node goes with its own listing. The
|
||||
// listings of the node's parents before and after the change go too.
|
||||
func (c *client) applyEvents(changes []eventChange) (stale []staleNode) {
|
||||
stale = make([]staleNode, 0, len(changes))
|
||||
for _, ch := range changes {
|
||||
s := staleNode{id: ch.linkID}
|
||||
n := c.cache.peek(ch.linkID)
|
||||
if n == nil && c.root != nil && ch.linkID == c.root.ID {
|
||||
n = c.root
|
||||
}
|
||||
if n != nil {
|
||||
s = staleNode{id: n.ID, parentID: n.ParentID, name: n.Name, isDir: n.IsFolder, known: true}
|
||||
}
|
||||
s.newParentID = ch.parentID
|
||||
s.gone = ch.kind == api.EventDelete || ch.trashed
|
||||
stale = append(stale, s)
|
||||
|
||||
// The root, the only node without a parent, can't be moved, so
|
||||
// a parent reported for it leaves its descendants' paths alone.
|
||||
moved := s.known && s.parentID != "" && ch.parentID != "" && ch.parentID != s.parentID
|
||||
switch {
|
||||
case ch.kind == api.EventDelete, s.isDir && (moved || ch.trashed):
|
||||
c.cache.invalidateTree(ch.linkID)
|
||||
default:
|
||||
c.cache.invalidate(ch.linkID)
|
||||
}
|
||||
if ch.parentID != "" {
|
||||
c.cache.invalidateChildren(ch.parentID)
|
||||
}
|
||||
}
|
||||
return stale
|
||||
}
|
||||
|
||||
// eventPoller polls the events of a client's volume and applies them
|
||||
// to its cache, while the cache holds anything or anything subscribes.
|
||||
//
|
||||
// It polls from a timer, so no goroutine is left while it waits, and
|
||||
// never more often than its interval. Polls which fail are retried
|
||||
// after Fibonacci multiples of the interval, up to maxEventsBackoff.
|
||||
type eventPoller struct {
|
||||
c *client
|
||||
floor time.Duration // shortest time between polls; 0 disables polling
|
||||
jitter time.Duration // most random time added to each wait: eventsJitter, unless a test lowers it
|
||||
idle time.Duration // how long the cache may go unused before it is cleared: cacheIdleTime, unless a test lowers it
|
||||
|
||||
runMu sync.Mutex // held by the timer's polls and by notifications, so they never overlap
|
||||
pollMu sync.Mutex // held by every poll until it has updated the poller, for stop to wait for
|
||||
|
||||
mu sync.Mutex
|
||||
interval time.Duration // time between polls asked for by setInterval
|
||||
cursor string // event to poll from; empty until the start cursor is fetched
|
||||
failures int // polls failed in a row
|
||||
notBefore time.Time // no poll before this, as the server's Retry-After asked
|
||||
timer *time.Timer // the next poll; nil if none is scheduled
|
||||
running bool // whether a poll of gen is running
|
||||
gen uint64 // polls of an earlier gen, from before stop, do nothing
|
||||
ctx context.Context // context of the polls of gen
|
||||
cancel context.CancelFunc // cancels ctx
|
||||
closed bool // whether polling has stopped for good
|
||||
subs map[int]func(stale []staleNode, refresh bool)
|
||||
nextSub int
|
||||
observer func(stale []staleNode, refresh bool) // called after subs; see observe
|
||||
pending []pendingNode // nodes changed while not cached, oldest first; see subscribe
|
||||
}
|
||||
|
||||
// pendingNode is a node which changed while it wasn't cached.
|
||||
type pendingNode struct {
|
||||
id string
|
||||
polls int // polls left in which to look for it in the cache
|
||||
}
|
||||
|
||||
// newEventPoller returns an idle poller of the events of c, polling no
|
||||
// more often than every floor, or never if floor is 0.
|
||||
func newEventPoller(c *client, floor time.Duration) *eventPoller {
|
||||
return &eventPoller{
|
||||
c: c,
|
||||
floor: floor,
|
||||
jitter: eventsJitter,
|
||||
idle: cacheIdleTime,
|
||||
subs: make(map[int]func([]staleNode, bool)),
|
||||
}
|
||||
}
|
||||
|
||||
// subscribe calls fn after each poll which changed anything, with what
|
||||
// the cache knew of each changed node, or with refresh set if anything
|
||||
// cached may have been out of date and the cache was cleared. Calls are
|
||||
// made one at a time, on a goroutine of the poller's own, never on one
|
||||
// which called wake or filled the cache, and fn must not call the
|
||||
// poller.
|
||||
//
|
||||
// A node which changed while it wasn't cached, in a folder reported,
|
||||
// as one being uploaded may be, is looked for in the cache in each of
|
||||
// the next pendingPolls polls. If it is found it is passed again with
|
||||
// late set, whether or not the poll changed anything.
|
||||
//
|
||||
// It keeps polling going until unsubscribe is called, once wake starts
|
||||
// it. A call already started may still be made, or be running, after
|
||||
// unsubscribe returns.
|
||||
func (p *eventPoller) subscribe(fn func(stale []staleNode, refresh bool)) (unsubscribe func()) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
id := p.nextSub
|
||||
p.nextSub++
|
||||
p.subs[id] = fn
|
||||
return func() {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
delete(p.subs, id)
|
||||
if len(p.subs) == 0 {
|
||||
p.pending = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// addPendingLocked adds to the nodes to look for in the cache those in
|
||||
// stale which weren't cached, if anything subscribes. It forgets the
|
||||
// oldest beyond maxPendingNodes. p.mu must be held.
|
||||
func (p *eventPoller) addPendingLocked(stale []staleNode) {
|
||||
if len(p.subs) == 0 {
|
||||
return
|
||||
}
|
||||
for _, s := range stale {
|
||||
if s.known || s.gone || s.newParentID == "" {
|
||||
continue
|
||||
}
|
||||
p.pending = slices.DeleteFunc(p.pending, func(pn pendingNode) bool { return pn.id == s.id })
|
||||
p.pending = append(p.pending, pendingNode{id: s.id, polls: pendingPolls})
|
||||
}
|
||||
if n := len(p.pending) - maxPendingNodes; n > 0 {
|
||||
p.pending = slices.Delete(p.pending, 0, n)
|
||||
}
|
||||
}
|
||||
|
||||
// resolvePendingLocked returns, with late set, the pending nodes now
|
||||
// cached, and forgets them and those looked for in pendingPolls polls.
|
||||
// p.mu must be held.
|
||||
func (p *eventPoller) resolvePendingLocked() (late []staleNode) {
|
||||
kept := p.pending[:0]
|
||||
for _, pn := range p.pending {
|
||||
if n := p.c.cache.peek(pn.id); n != nil {
|
||||
late = append(late, staleNode{id: n.ID, parentID: n.ParentID, name: n.Name, isDir: n.IsFolder, known: true, late: true})
|
||||
} else if pn.polls > 1 {
|
||||
pn.polls--
|
||||
kept = append(kept, pn)
|
||||
}
|
||||
}
|
||||
clear(p.pending[len(kept):])
|
||||
p.pending = kept
|
||||
return late
|
||||
}
|
||||
|
||||
// observe makes fn be called after each poll which changed anything,
|
||||
// as subscribe does, after the subscribers. Unlike subscribe it doesn't
|
||||
// keep polling going. It replaces any earlier fn; nil removes it.
|
||||
func (p *eventPoller) observe(fn func(stale []staleNode, refresh bool)) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.observer = fn
|
||||
}
|
||||
|
||||
// setInterval sets the time between polls to d, if it is longer than
|
||||
// the shortest the poller allows, from the next poll scheduled.
|
||||
func (p *eventPoller) setInterval(d time.Duration) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.interval = d
|
||||
}
|
||||
|
||||
// wake starts polling if it isn't running and the cache holds anything
|
||||
// or anything subscribes. The first wake fetches the start cursor
|
||||
// before it returns, so every change made afterwards is seen, unless
|
||||
// fetching it failed before, when it is fetched after a backoff. It
|
||||
// doesn't wait for a poll or a notification.
|
||||
func (p *eventPoller) wake() {
|
||||
p.mu.Lock()
|
||||
if p.closed || p.floor <= 0 || p.timer != nil || p.running || !p.wantedLocked() {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if p.ctx == nil {
|
||||
p.ctx, p.cancel = context.WithCancel(context.Background())
|
||||
}
|
||||
if p.cursor != "" || p.failures > 0 {
|
||||
p.scheduleLocked()
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
p.running = true
|
||||
gen, ctx := p.gen, p.ctx
|
||||
p.mu.Unlock()
|
||||
p.poll(ctx, gen, true)
|
||||
}
|
||||
|
||||
// stop stops polling, cancelling a poll in flight and waiting for it to
|
||||
// end, but not for any notification it makes. A later wake starts
|
||||
// polling again, from the cursor, after an interval.
|
||||
func (p *eventPoller) stop() {
|
||||
p.mu.Lock()
|
||||
p.stopLocked()
|
||||
p.mu.Unlock()
|
||||
p.pollMu.Lock()
|
||||
defer p.pollMu.Unlock()
|
||||
}
|
||||
|
||||
// stopLocked is stop with p.mu held.
|
||||
func (p *eventPoller) stopLocked() {
|
||||
p.gen++
|
||||
if p.timer != nil {
|
||||
p.timer.Stop()
|
||||
p.timer = nil
|
||||
}
|
||||
if p.cancel != nil {
|
||||
p.cancel()
|
||||
p.ctx, p.cancel = nil, nil
|
||||
}
|
||||
p.running = false
|
||||
p.pending = nil
|
||||
}
|
||||
|
||||
// close stops polling for good, as stop does.
|
||||
func (p *eventPoller) close() {
|
||||
p.mu.Lock()
|
||||
p.closed = true
|
||||
p.stopLocked()
|
||||
p.mu.Unlock()
|
||||
p.pollMu.Lock()
|
||||
defer p.pollMu.Unlock()
|
||||
}
|
||||
|
||||
// wantedLocked reports whether polling is wanted: the cache holds
|
||||
// anything or anything subscribes. p.mu must be held.
|
||||
func (p *eventPoller) wantedLocked() bool {
|
||||
return len(p.subs) > 0 || !p.c.cache.empty()
|
||||
}
|
||||
|
||||
// scheduleLocked schedules the next poll of the current gen and returns
|
||||
// the wait. p.mu must be held.
|
||||
func (p *eventPoller) scheduleLocked() time.Duration {
|
||||
base := max(p.floor, p.interval)
|
||||
// Fibonacci multiples of base for 1, 2, 3... failures: 1, 1, 2...
|
||||
limit := max(base, maxEventsBackoff)
|
||||
wait := base
|
||||
for a, b, i := base, base, 1; i < p.failures && wait < limit; i++ {
|
||||
a, b = b, a+b
|
||||
wait = a
|
||||
}
|
||||
wait = min(wait, limit)
|
||||
if p.jitter > 0 {
|
||||
wait += rand.N(p.jitter + 1)
|
||||
}
|
||||
wait = max(wait, time.Until(p.notBefore))
|
||||
gen := p.gen
|
||||
p.timer = time.AfterFunc(wait, func() { p.run(gen) })
|
||||
return wait
|
||||
}
|
||||
|
||||
// run is the timer function of a poll scheduled in gen.
|
||||
func (p *eventPoller) run(gen uint64) {
|
||||
p.mu.Lock()
|
||||
if gen != p.gen {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
p.timer = nil
|
||||
if len(p.subs) == 0 && p.c.cache.unusedFor() >= p.idle {
|
||||
fs.Debugf(nil, "protondrive: events: cache unused for %v: clearing it", p.idle)
|
||||
p.c.cache.clear()
|
||||
}
|
||||
if !p.wantedLocked() {
|
||||
// Idle: the cursor is kept for the next wake.
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
p.running = true
|
||||
ctx := p.ctx
|
||||
p.mu.Unlock()
|
||||
p.poll(ctx, gen, false)
|
||||
}
|
||||
|
||||
// poll fetches the start cursor if there is none, else applies the
|
||||
// events since the cursor, and then schedules the next poll if polling
|
||||
// is still wanted. p.running must have been set in gen.
|
||||
//
|
||||
// From wake, inline is set: the caller may hold locks of its own (the
|
||||
// dircache's, VFS's) which subscribers take, so it doesn't wait for
|
||||
// runMu and leaves any notification to a goroutine of its own. Only
|
||||
// the start cursor is fetched then, and no other poll of gen can run.
|
||||
func (p *eventPoller) poll(ctx context.Context, gen uint64, inline bool) {
|
||||
if !inline {
|
||||
p.runMu.Lock()
|
||||
defer p.runMu.Unlock()
|
||||
}
|
||||
p.pollMu.Lock()
|
||||
pollDone := sync.OnceFunc(p.pollMu.Unlock)
|
||||
defer pollDone()
|
||||
p.mu.Lock()
|
||||
cursor := p.cursor
|
||||
p.mu.Unlock()
|
||||
|
||||
var (
|
||||
changes []eventChange
|
||||
next string
|
||||
refresh bool
|
||||
err error
|
||||
)
|
||||
if cursor == "" {
|
||||
next, err = p.c.latestEventID(ctx)
|
||||
} else {
|
||||
changes, next, refresh, err = p.c.pollEvents(ctx, cursor)
|
||||
}
|
||||
|
||||
p.mu.Lock()
|
||||
if gen != p.gen {
|
||||
// Stopped while polling.
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
p.running = false
|
||||
var stale []staleNode
|
||||
gone := errors.Is(err, errVolumeGone)
|
||||
switch {
|
||||
case gone:
|
||||
p.closed = true
|
||||
refresh = true
|
||||
p.c.cache.clear()
|
||||
p.pending = nil
|
||||
case err != nil:
|
||||
p.failures++
|
||||
if wait, ok := pacer.IsRetryAfter(err); ok {
|
||||
p.notBefore = time.Now().Add(wait)
|
||||
}
|
||||
stale = p.resolvePendingLocked()
|
||||
default:
|
||||
p.failures = 0
|
||||
p.cursor = next
|
||||
if refresh {
|
||||
p.c.cache.clear()
|
||||
p.pending = nil
|
||||
break
|
||||
}
|
||||
// Before applying changes, which may drop the nodes again.
|
||||
stale = p.resolvePendingLocked()
|
||||
if len(changes) > 0 {
|
||||
applied := p.c.applyEvents(changes)
|
||||
p.addPendingLocked(applied)
|
||||
stale = append(stale, applied...)
|
||||
}
|
||||
}
|
||||
var wait time.Duration
|
||||
if !p.closed && p.wantedLocked() {
|
||||
wait = p.scheduleLocked()
|
||||
}
|
||||
var subs []func([]staleNode, bool)
|
||||
if refresh || len(stale) > 0 {
|
||||
for _, fn := range p.subs {
|
||||
subs = append(subs, fn)
|
||||
}
|
||||
if p.observer != nil {
|
||||
subs = append(subs, p.observer)
|
||||
}
|
||||
}
|
||||
p.mu.Unlock()
|
||||
|
||||
switch {
|
||||
case gone:
|
||||
fs.Errorf(nil, "protondrive: events: %v: no longer watching for changes", err)
|
||||
case err != nil:
|
||||
fs.Debugf(nil, "protondrive: events: %v: trying again in %v", err, wait)
|
||||
}
|
||||
pollDone()
|
||||
notify := func() {
|
||||
for _, fn := range subs {
|
||||
fn(stale, refresh)
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case len(subs) == 0:
|
||||
case inline:
|
||||
time.AfterFunc(0, func() {
|
||||
p.runMu.Lock()
|
||||
defer p.runMu.Unlock()
|
||||
notify()
|
||||
})
|
||||
default:
|
||||
notify()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,875 @@
|
||||
package protondrive
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rclone/rclone/backend/protondrive/api"
|
||||
"github.com/rclone/rclone/backend/protondrive/protontest"
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/log"
|
||||
"github.com/rclone/rclone/lib/random"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
latestEventRoute = "/drive/volumes/{volumeID}/events/latest"
|
||||
eventsRoute = "/drive/v2/volumes/{volumeID}/events/{eventID}"
|
||||
)
|
||||
|
||||
func TestLatestEventID(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
c, srv, u := newTestClient(t)
|
||||
|
||||
start, err := c.latestEventID(ctx)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, start)
|
||||
assert.Equal(t, 1, srv.Requests()["GET "+latestEventRoute])
|
||||
|
||||
changes, next, refresh, err := c.pollEvents(ctx, start)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, refresh)
|
||||
assert.Empty(t, changes)
|
||||
assert.Equal(t, start, next)
|
||||
|
||||
u.SeedFolder(u.RootID(), "dir")
|
||||
latest, err := c.latestEventID(ctx)
|
||||
require.NoError(t, err)
|
||||
assert.NotEqual(t, start, latest)
|
||||
}
|
||||
|
||||
func TestPollEventsPages(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
c, srv, u := newTestClient(t)
|
||||
srv.SetEventsPageSize(2)
|
||||
start, err := c.latestEventID(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
dir := u.SeedFolder(u.RootID(), "dir")
|
||||
other := u.SeedFolder(u.RootID(), "other")
|
||||
file := u.SeedFile(dir, "file", []byte("x"), time.Now())
|
||||
u.SetParent(file, other)
|
||||
srv.InjectEvent(u, protontest.Event{Type: protontest.EventUpdateMetadata, LinkID: dir, ParentLinkID: u.RootID(), IsTrashed: true})
|
||||
srv.InjectEvent(u, protontest.Event{Type: protontest.EventDelete, LinkID: dir})
|
||||
srv.InjectEvent(u, protontest.Event{Type: protontest.EventUpdate, LinkID: other, ParentLinkID: u.RootID(), IsShared: true})
|
||||
events := srv.Events(u)
|
||||
require.Len(t, events, 7)
|
||||
|
||||
srv.ResetRequests()
|
||||
changes, next, refresh, err := c.pollEvents(ctx, start)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, refresh)
|
||||
want := make([]eventChange, len(events))
|
||||
for i, e := range events {
|
||||
want[i] = eventChange{linkID: e.LinkID, parentID: e.ParentLinkID, kind: e.Type, trashed: e.IsTrashed}
|
||||
}
|
||||
assert.Equal(t, want, changes)
|
||||
assert.Equal(t, 4, srv.Requests()["GET "+eventsRoute], "pages of 2 for 7 events")
|
||||
|
||||
latest, err := c.latestEventID(ctx)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, latest, next)
|
||||
|
||||
changes, again, refresh, err := c.pollEvents(ctx, next)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, refresh)
|
||||
assert.Empty(t, changes)
|
||||
assert.Equal(t, next, again)
|
||||
}
|
||||
|
||||
func TestPollEventsLogsPages(t *testing.T) {
|
||||
logs := captureLogLines(t)
|
||||
ctx := context.Background()
|
||||
oldLevel := log.Handler.SetLevel(slog.LevelDebug)
|
||||
ci := fs.GetConfig(ctx)
|
||||
oldLogLevel := ci.LogLevel
|
||||
ci.LogLevel = fs.LogLevelDebug
|
||||
t.Cleanup(func() {
|
||||
ci.LogLevel = oldLogLevel
|
||||
log.Handler.SetLevel(oldLevel)
|
||||
})
|
||||
c, srv, u := newTestClient(t)
|
||||
srv.SetEventsPageSize(2)
|
||||
start, err := c.latestEventID(ctx)
|
||||
require.NoError(t, err)
|
||||
for _, name := range []string{"a", "b", "c"} {
|
||||
u.SeedFolder(u.RootID(), name)
|
||||
}
|
||||
|
||||
_, next, _, err := c.pollEvents(ctx, start)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, logs.matching("protondrive: events: 2 after "+start+" (more true)"), 1)
|
||||
assert.Len(t, logs.matching("protondrive: events: 1 after ", " (more false)"), 1)
|
||||
assert.Empty(t, logs.matching("after "+next))
|
||||
}
|
||||
|
||||
func TestPollEventsRefresh(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
c, srv, u := newTestClient(t)
|
||||
start, err := c.latestEventID(ctx)
|
||||
require.NoError(t, err)
|
||||
u.SeedFolder(u.RootID(), "dir")
|
||||
srv.ExpireEvents(u)
|
||||
|
||||
changes, next, refresh, err := c.pollEvents(ctx, start)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, refresh)
|
||||
assert.Empty(t, changes)
|
||||
latest, err := c.latestEventID(ctx)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, latest, next)
|
||||
|
||||
// The new cursor is usable.
|
||||
u.SeedFolder(u.RootID(), "after")
|
||||
changes, _, refresh, err = c.pollEvents(ctx, next)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, refresh)
|
||||
assert.Len(t, changes, 1)
|
||||
}
|
||||
|
||||
func TestPollEventsVolumeGone(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
c, srv, _ := newTestClient(t)
|
||||
start, err := c.latestEventID(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
srv.Inject(protontest.Fault{Pattern: eventsRoute, Status: http.StatusUnprocessableEntity, Code: api.CodeNotExists})
|
||||
srv.Inject(protontest.Fault{Pattern: latestEventRoute, Status: http.StatusUnprocessableEntity, Code: api.CodeNotExists})
|
||||
_, next, _, err := c.pollEvents(ctx, start)
|
||||
assert.True(t, errors.Is(err, errVolumeGone), "%v", err)
|
||||
assert.Empty(t, next)
|
||||
_, err = c.latestEventID(ctx)
|
||||
assert.True(t, errors.Is(err, errVolumeGone), "%v", err)
|
||||
|
||||
// Other errors are not the volume gone.
|
||||
c2, srv2, _ := newTestClient(t)
|
||||
srv2.Inject(protontest.Fault{Pattern: latestEventRoute, Status: http.StatusUnprocessableEntity, Code: api.CodeInvalidValue})
|
||||
_, err = c2.latestEventID(ctx)
|
||||
require.Error(t, err)
|
||||
assert.False(t, errors.Is(err, errVolumeGone), "%v", err)
|
||||
}
|
||||
|
||||
func TestPollEventsHostilePages(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
body string
|
||||
wantErr bool
|
||||
changes int
|
||||
next string
|
||||
}{{
|
||||
// As the SDK's fast-forward: an empty page ends the poll.
|
||||
name: "more without events",
|
||||
body: `{"Code":1000,"Events":[],"EventID":"later","More":true}`,
|
||||
next: "later",
|
||||
}, {
|
||||
name: "more without a new ID",
|
||||
body: `{"Code":1000,"Events":[{"EventID":"e","EventType":1,"Link":{"LinkID":"a"}}],"EventID":"start","More":true}`,
|
||||
changes: 1,
|
||||
next: "start",
|
||||
}, {
|
||||
name: "no ID",
|
||||
body: `{"Code":1000,"Events":[],"EventID":"","More":false}`,
|
||||
wantErr: true,
|
||||
}, {
|
||||
name: "refresh without an ID",
|
||||
body: `{"Code":1000,"Events":[],"Refresh":true}`,
|
||||
wantErr: true,
|
||||
}, {
|
||||
name: "event without a link ID",
|
||||
body: `{"Code":1000,"Events":[{"EventID":"e","EventType":0,"Link":{"LinkID":""}}],"EventID":"e"}`,
|
||||
next: "e",
|
||||
}} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
var pages int
|
||||
c := newTestClientTransport(t, srv, u, clientOptions{EnableCaching: true}, func(next http.RoundTripper) http.RoundTripper {
|
||||
return roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if !strings.Contains(r.URL.Path, "/events/") || strings.HasSuffix(r.URL.Path, "/latest") {
|
||||
return next.RoundTrip(r)
|
||||
}
|
||||
pages++
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": {"application/json"}},
|
||||
Body: io.NopCloser(strings.NewReader(test.body)),
|
||||
Request: r,
|
||||
}, nil
|
||||
})
|
||||
})
|
||||
changes, next, _, err := c.pollEvents(ctx, "start")
|
||||
assert.Equal(t, 1, pages)
|
||||
if test.wantErr {
|
||||
assert.Error(t, err)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, changes, test.changes)
|
||||
assert.Equal(t, test.next, next)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPollEventsEndlessPages(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
var pages int
|
||||
c := newTestClientTransport(t, srv, u, clientOptions{EnableCaching: true}, func(next http.RoundTripper) http.RoundTripper {
|
||||
return roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if !strings.Contains(r.URL.Path, "/events/") || strings.HasSuffix(r.URL.Path, "/latest") {
|
||||
return next.RoundTrip(r)
|
||||
}
|
||||
pages++
|
||||
body := fmt.Sprintf(`{"Code":1000,"Events":[{"EventID":"e%d","EventType":2,"Link":{"LinkID":"a"}}],"EventID":"p%d","More":true}`, pages, pages)
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": {"application/json"}},
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
Request: r,
|
||||
}, nil
|
||||
})
|
||||
})
|
||||
changes, next, refresh, err := c.pollEvents(ctx, "start")
|
||||
require.NoError(t, err)
|
||||
assert.False(t, refresh)
|
||||
assert.Equal(t, maxEventPages, pages)
|
||||
assert.Len(t, changes, maxEventPages)
|
||||
assert.Equal(t, fmt.Sprintf("p%d", maxEventPages), next)
|
||||
}
|
||||
|
||||
// eventsTestClient returns a client for no server whose cache holds
|
||||
// root/{dir/{sub/{deep}, file}, top, other/}, with every listing.
|
||||
func eventsTestClient() *client {
|
||||
c := &client{cache: newNodeCache(true), root: &node{ID: "root", IsFolder: true}}
|
||||
c.cache.setChildren("root", []*node{
|
||||
{ID: "dir", ParentID: "root", Name: "dir", IsFolder: true},
|
||||
{ID: "top", ParentID: "root", Name: "top"},
|
||||
{ID: "other", ParentID: "root", Name: "other", IsFolder: true},
|
||||
})
|
||||
c.cache.setChildren("dir", []*node{
|
||||
{ID: "sub", ParentID: "dir", Name: "sub", IsFolder: true},
|
||||
{ID: "file", ParentID: "dir", Name: "file"},
|
||||
})
|
||||
c.cache.setChildren("sub", []*node{{ID: "deep", ParentID: "sub", Name: "deep"}})
|
||||
c.cache.setChildren("other", nil)
|
||||
return c
|
||||
}
|
||||
|
||||
func TestApplyEventsInvalidates(t *testing.T) {
|
||||
t.Parallel()
|
||||
all := []string{"dir", "top", "other", "sub", "file", "deep"}
|
||||
listings := []string{"root", "dir", "sub", "other"}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
change eventChange
|
||||
stale staleNode
|
||||
goneNodes []string
|
||||
goneListings []string
|
||||
}{{
|
||||
name: "delete folder",
|
||||
change: eventChange{linkID: "dir", parentID: "root", kind: api.EventDelete},
|
||||
stale: staleNode{id: "dir", parentID: "root", name: "dir", isDir: true, known: true, newParentID: "root", gone: true},
|
||||
goneNodes: []string{"dir", "sub", "file", "deep"},
|
||||
goneListings: []string{"root", "dir", "sub"},
|
||||
}, {
|
||||
name: "delete without parent",
|
||||
change: eventChange{linkID: "file", kind: api.EventDelete},
|
||||
stale: staleNode{id: "file", parentID: "dir", name: "file", known: true, gone: true},
|
||||
goneNodes: []string{"file"},
|
||||
goneListings: []string{"dir"},
|
||||
}, {
|
||||
name: "delete unknown",
|
||||
change: eventChange{linkID: "gone", kind: api.EventDelete},
|
||||
stale: staleNode{id: "gone", gone: true},
|
||||
goneNodes: nil,
|
||||
goneListings: nil,
|
||||
}, {
|
||||
name: "create",
|
||||
change: eventChange{linkID: "new", parentID: "other", kind: api.EventCreate},
|
||||
stale: staleNode{id: "new", newParentID: "other"},
|
||||
goneListings: []string{"other"},
|
||||
}, {
|
||||
name: "rename file",
|
||||
change: eventChange{linkID: "file", parentID: "dir", kind: api.EventUpdateMetadata},
|
||||
stale: staleNode{id: "file", parentID: "dir", name: "file", known: true, newParentID: "dir"},
|
||||
goneNodes: []string{"file"},
|
||||
goneListings: []string{"dir"},
|
||||
}, {
|
||||
name: "rename folder",
|
||||
change: eventChange{linkID: "sub", parentID: "dir", kind: api.EventUpdate},
|
||||
stale: staleNode{id: "sub", parentID: "dir", name: "sub", isDir: true, known: true, newParentID: "dir"},
|
||||
goneNodes: []string{"sub"},
|
||||
goneListings: []string{"dir", "sub"},
|
||||
}, {
|
||||
name: "move file",
|
||||
change: eventChange{linkID: "file", parentID: "other", kind: api.EventUpdate},
|
||||
stale: staleNode{id: "file", parentID: "dir", name: "file", known: true, newParentID: "other"},
|
||||
goneNodes: []string{"file"},
|
||||
goneListings: []string{"dir", "other"},
|
||||
}, {
|
||||
name: "move folder",
|
||||
change: eventChange{linkID: "dir", parentID: "other", kind: api.EventUpdate},
|
||||
stale: staleNode{id: "dir", parentID: "root", name: "dir", isDir: true, known: true, newParentID: "other"},
|
||||
goneNodes: []string{"dir", "sub", "file", "deep"},
|
||||
goneListings: []string{"root", "dir", "sub", "other"},
|
||||
}, {
|
||||
name: "move unknown in",
|
||||
change: eventChange{linkID: "stranger", parentID: "other", kind: api.EventUpdate},
|
||||
stale: staleNode{id: "stranger", newParentID: "other"},
|
||||
goneListings: []string{"other"},
|
||||
}, {
|
||||
name: "trash file",
|
||||
change: eventChange{linkID: "top", parentID: "root", kind: api.EventUpdate, trashed: true},
|
||||
stale: staleNode{id: "top", parentID: "root", name: "top", known: true, newParentID: "root", gone: true},
|
||||
goneNodes: []string{"top"},
|
||||
goneListings: []string{"root"},
|
||||
}, {
|
||||
name: "trash folder",
|
||||
change: eventChange{linkID: "sub", parentID: "dir", kind: api.EventUpdateMetadata, trashed: true},
|
||||
stale: staleNode{id: "sub", parentID: "dir", name: "sub", isDir: true, known: true, newParentID: "dir", gone: true},
|
||||
goneNodes: []string{"sub", "deep"},
|
||||
goneListings: []string{"dir", "sub"},
|
||||
}, {
|
||||
name: "untrash unknown",
|
||||
change: eventChange{linkID: "back", parentID: "dir", kind: api.EventUpdate},
|
||||
stale: staleNode{id: "back", newParentID: "dir"},
|
||||
goneListings: []string{"dir"},
|
||||
}, {
|
||||
name: "update root",
|
||||
change: eventChange{linkID: "root", kind: api.EventUpdate},
|
||||
stale: staleNode{id: "root", isDir: true, known: true},
|
||||
goneListings: []string{"root"},
|
||||
}, {
|
||||
// The root can't move, so its descendants keep their paths.
|
||||
name: "update root naming a parent",
|
||||
change: eventChange{linkID: "root", parentID: "volume", kind: api.EventUpdate},
|
||||
stale: staleNode{id: "root", isDir: true, known: true, newParentID: "volume"},
|
||||
goneListings: []string{"root"},
|
||||
}, {
|
||||
name: "unknown kind",
|
||||
change: eventChange{linkID: "file", parentID: "dir", kind: 42},
|
||||
stale: staleNode{id: "file", parentID: "dir", name: "file", known: true, newParentID: "dir"},
|
||||
goneNodes: []string{"file"},
|
||||
goneListings: []string{"dir"},
|
||||
}} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
c := eventsTestClient()
|
||||
stale := c.applyEvents([]eventChange{test.change})
|
||||
assert.Equal(t, []staleNode{test.stale}, stale)
|
||||
for _, id := range all {
|
||||
gone := c.cache.get(id) == nil
|
||||
assert.Equal(t, slices.Contains(test.goneNodes, id), gone, "node %s gone", id)
|
||||
}
|
||||
for _, id := range listings {
|
||||
_, ok := c.cache.listings[id]
|
||||
assert.Equal(t, slices.Contains(test.goneListings, id), !ok, "listing %s gone", id)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyEventsSeveral(t *testing.T) {
|
||||
t.Parallel()
|
||||
c := eventsTestClient()
|
||||
stale := c.applyEvents([]eventChange{
|
||||
{linkID: "file", parentID: "dir", kind: api.EventUpdate},
|
||||
{linkID: "file", parentID: "dir", kind: api.EventDelete},
|
||||
{linkID: "top", parentID: "root", kind: api.EventCreate},
|
||||
})
|
||||
assert.Equal(t, []staleNode{
|
||||
{id: "file", parentID: "dir", name: "file", known: true, newParentID: "dir"},
|
||||
{id: "file", newParentID: "dir", gone: true},
|
||||
{id: "top", parentID: "root", name: "top", known: true, newParentID: "root"},
|
||||
}, stale)
|
||||
assert.Nil(t, c.cache.get("file"))
|
||||
assert.Nil(t, c.cache.get("top"))
|
||||
assert.NotNil(t, c.cache.get("deep"))
|
||||
|
||||
// Without a cache the nodes are unknown.
|
||||
c = &client{root: &node{ID: "root", IsFolder: true}}
|
||||
stale = c.applyEvents([]eventChange{{linkID: "file", parentID: "dir", kind: api.EventDelete}})
|
||||
assert.Equal(t, []staleNode{{id: "file", newParentID: "dir", gone: true}}, stale)
|
||||
assert.Empty(t, c.applyEvents(nil))
|
||||
}
|
||||
|
||||
func TestApplyEventsFromFake(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
c, srv, u := newTestClient(t)
|
||||
dir := u.SeedFolder(u.RootID(), "dir")
|
||||
other := u.SeedFolder(u.RootID(), "other")
|
||||
u.SeedFile(dir, "file", []byte("x"), time.Now())
|
||||
listAll(t, c, u.RootID())
|
||||
listAll(t, c, dir)
|
||||
listAll(t, c, other)
|
||||
start, err := c.latestEventID(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Another client moves dir into other.
|
||||
mover := newTestClientFor(t, srv, u, clientOptions{})
|
||||
n, err := mover.getNode(ctx, dir)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, mover.move(ctx, n, other, "dir"))
|
||||
assert.Contains(t, listAll(t, c, u.RootID()), "dir", "cached")
|
||||
changes, _, _, err := c.pollEvents(ctx, start)
|
||||
require.NoError(t, err)
|
||||
stale := c.applyEvents(changes)
|
||||
require.Len(t, stale, 1)
|
||||
assert.Equal(t, staleNode{id: dir, parentID: u.RootID(), name: "dir", isDir: true, known: true, newParentID: other}, stale[0])
|
||||
|
||||
assert.NotContains(t, listAll(t, c, u.RootID()), "dir")
|
||||
assert.Contains(t, listAll(t, c, other), "dir")
|
||||
assert.Contains(t, listAll(t, c, dir), "file")
|
||||
}
|
||||
|
||||
// pollTimes records when a client requested pages of events.
|
||||
type pollTimes struct {
|
||||
mu sync.Mutex
|
||||
times []time.Time
|
||||
}
|
||||
|
||||
// get returns the times recorded so far.
|
||||
func (p *pollTimes) get() []time.Time {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return slices.Clone(p.times)
|
||||
}
|
||||
|
||||
// gaps returns the time between each recorded poll and the next.
|
||||
func (p *pollTimes) gaps() []time.Duration {
|
||||
times := p.get()
|
||||
var out []time.Duration
|
||||
for i := 1; i < len(times); i++ {
|
||||
out = append(out, times[i].Sub(times[i-1]))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Timing of the polling clients: short, so the tests are quick.
|
||||
const (
|
||||
testPollInterval = 200 * time.Millisecond
|
||||
testPollJitter = 50 * time.Millisecond
|
||||
)
|
||||
|
||||
// newPollingClient returns a client with caching enabled which polls
|
||||
// events at least testPollInterval apart, with at most testPollJitter
|
||||
// added, recording when it requests pages of events.
|
||||
func newPollingClient(t *testing.T) (*client, *protontest.Server, *protontest.User, *pollTimes) {
|
||||
t.Helper()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
polls := &pollTimes{}
|
||||
c := newTestClientTransport(t, srv, u, clientOptions{EnableCaching: true, EventsInterval: testPollInterval}, func(next http.RoundTripper) http.RoundTripper {
|
||||
return roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if strings.HasPrefix(r.URL.Path, "/drive/v2/volumes/") && strings.Contains(r.URL.Path, "/events/") {
|
||||
polls.mu.Lock()
|
||||
polls.times = append(polls.times, time.Now())
|
||||
polls.mu.Unlock()
|
||||
}
|
||||
return next.RoundTrip(r)
|
||||
})
|
||||
})
|
||||
c.events.jitter = testPollJitter
|
||||
return c, srv, u, polls
|
||||
}
|
||||
|
||||
// eventRequests returns the requests srv had for the start cursor and
|
||||
// for pages of events.
|
||||
func eventRequests(srv *protontest.Server) (latest, pages int) {
|
||||
got := srv.Requests()
|
||||
return got["GET "+latestEventRoute], got["GET "+eventsRoute]
|
||||
}
|
||||
|
||||
// logLines holds the lines rclone logs while they are captured.
|
||||
type logLines struct {
|
||||
mu sync.Mutex
|
||||
lines []string
|
||||
}
|
||||
|
||||
// matching returns the lines captured so far which contain each of subs.
|
||||
func (l *logLines) matching(subs ...string) []string {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
var out []string
|
||||
for _, line := range l.lines {
|
||||
if !slices.ContainsFunc(subs, func(s string) bool { return !strings.Contains(line, s) }) {
|
||||
out = append(out, line)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// captureLogLines captures rclone's log output at its usual level until
|
||||
// the test ends. Tests using it must not be parallel.
|
||||
func captureLogLines(t *testing.T) *logLines {
|
||||
l := &logLines{}
|
||||
log.Handler.SetOutput(func(level slog.Level, text string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.lines = append(l.lines, text)
|
||||
})
|
||||
t.Cleanup(log.Handler.ResetOutput)
|
||||
return l
|
||||
}
|
||||
|
||||
// addPending makes p wait to name the uncached node id, which a
|
||||
// subscriber must be waiting for.
|
||||
func addPending(p *eventPoller, id string) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.addPendingLocked([]staleNode{{id: id, newParentID: "folder"}})
|
||||
}
|
||||
|
||||
func TestPollerIdleMakesNoRequests(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, srv, u, _ := newPollingClient(t)
|
||||
u.SeedFolder(u.RootID(), "dir")
|
||||
// Nothing is cached and nothing subscribed, so waking does nothing.
|
||||
c.events.wake()
|
||||
time.Sleep(3 * (testPollInterval + testPollJitter))
|
||||
latest, pages := eventRequests(srv)
|
||||
assert.Zero(t, latest+pages, "%v", srv.Requests())
|
||||
}
|
||||
|
||||
func TestPollerPollsWhileCached(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, srv, u, polls := newPollingClient(t)
|
||||
listAll(t, c, u.RootID())
|
||||
latest, pages := eventRequests(srv)
|
||||
assert.Equal(t, 1, latest, "the start cursor is fetched when the cache fills")
|
||||
assert.Zero(t, pages)
|
||||
|
||||
listAll(t, c, u.RootID())
|
||||
time.Sleep(5*testPollInterval + testPollJitter)
|
||||
c.events.stop()
|
||||
latest, pages = eventRequests(srv)
|
||||
assert.Equal(t, 1, latest)
|
||||
assert.GreaterOrEqual(t, pages, 3, "about one poll per interval")
|
||||
assert.LessOrEqual(t, pages, 5, "at most one poll per interval")
|
||||
for _, gap := range polls.gaps() {
|
||||
assert.GreaterOrEqual(t, gap, testPollInterval, "two polls within one interval")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPollerSetInterval(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, _, u, polls := newPollingClient(t)
|
||||
c.events.setInterval(testPollInterval / 2)
|
||||
listAll(t, c, u.RootID())
|
||||
require.Eventually(t, func() bool { return len(polls.get()) >= 2 }, 5*time.Second, 5*time.Millisecond)
|
||||
assert.GreaterOrEqual(t, polls.gaps()[0], testPollInterval, "shorter than the floor")
|
||||
|
||||
c.events.setInterval(3 * testPollInterval)
|
||||
n := len(polls.get())
|
||||
require.Eventually(t, func() bool { return len(polls.get()) >= n+2 }, 5*time.Second, 5*time.Millisecond)
|
||||
c.events.stop()
|
||||
// The poll scheduled before the change waits the old interval.
|
||||
assert.GreaterOrEqual(t, polls.gaps()[n], 3*testPollInterval, "longer than the floor")
|
||||
}
|
||||
|
||||
func TestPollerAppliesOtherClientsChange(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, _, u, _ := newPollingClient(t)
|
||||
dir := u.SeedFolder(u.RootID(), "dir")
|
||||
listAll(t, c, dir)
|
||||
u.SeedFile(dir, "new.txt", []byte("new"), time.Now())
|
||||
assert.NotContains(t, listAll(t, c, dir), "new.txt", "the listing is cached")
|
||||
|
||||
assert.Eventually(t, func() bool {
|
||||
_, ok := listAll(t, c, dir)["new.txt"]
|
||||
return ok
|
||||
}, testPollInterval+testPollJitter+500*time.Millisecond, 10*time.Millisecond, "the new file isn't listed after a poll")
|
||||
}
|
||||
|
||||
func TestPollerRefresh(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, srv, u, polls := newPollingClient(t)
|
||||
var mu sync.Mutex
|
||||
refreshes := 0
|
||||
unsubscribe := c.events.subscribe(func(_ []staleNode, refresh bool) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if refresh {
|
||||
refreshes++
|
||||
}
|
||||
})
|
||||
defer unsubscribe()
|
||||
refreshed := func() int {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return refreshes
|
||||
}
|
||||
listAll(t, c, u.RootID())
|
||||
|
||||
// Just after a poll the next is an interval away, so the cursor is
|
||||
// forgotten before it is used again.
|
||||
require.Eventually(t, func() bool { return len(polls.get()) > 0 }, 2*time.Second, time.Millisecond)
|
||||
u.SeedFolder(u.RootID(), "dir")
|
||||
c.events.runMu.Lock()
|
||||
addPending(c.events, "uncached")
|
||||
srv.ExpireEvents(u)
|
||||
c.events.runMu.Unlock()
|
||||
require.Eventually(t, func() bool { return refreshed() > 0 }, 2*time.Second, time.Millisecond)
|
||||
assert.True(t, c.cache.empty(), "the cache is cleared")
|
||||
assert.Empty(t, c.events.pendingIDs(), "nodes are still pending")
|
||||
|
||||
n := len(polls.get())
|
||||
time.Sleep(3 * (testPollInterval + testPollJitter))
|
||||
assert.Greater(t, len(polls.get()), n, "polling continues")
|
||||
assert.LessOrEqual(t, len(polls.get()), n+3, "polls in a loop")
|
||||
assert.Equal(t, 1, refreshed())
|
||||
|
||||
// The new cursor is used.
|
||||
assert.Contains(t, listAll(t, c, u.RootID()), "dir")
|
||||
u.SeedFolder(u.RootID(), "after")
|
||||
assert.Eventually(t, func() bool {
|
||||
_, ok := listAll(t, c, u.RootID())["after"]
|
||||
return ok
|
||||
}, testPollInterval+testPollJitter+500*time.Millisecond, 10*time.Millisecond)
|
||||
assert.Equal(t, 1, refreshed())
|
||||
}
|
||||
|
||||
// TestPollerBackoff isn't parallel: it counts goroutines and pool
|
||||
// buffers, which other tests share.
|
||||
func TestPollerBackoff(t *testing.T) {
|
||||
c, srv, u, polls := newPollingClient(t)
|
||||
goroutines, buffers := leakBaseline(srv)
|
||||
srv.Inject(protontest.Fault{Pattern: eventsRoute, Status: http.StatusServiceUnavailable, Times: 4})
|
||||
listAll(t, c, u.RootID())
|
||||
|
||||
// Four polls fail, the fifth and sixth succeed.
|
||||
require.Eventually(t, func() bool { return len(polls.get()) >= 6 }, 10*time.Second, 5*time.Millisecond)
|
||||
c.events.stop()
|
||||
gaps := polls.gaps()
|
||||
for i, times := range []int{1, 1, 2, 3, 1} {
|
||||
want := time.Duration(times) * testPollInterval
|
||||
assert.GreaterOrEqual(t, gaps[i], want, "gap %d: %v", i, gaps)
|
||||
assert.Less(t, gaps[i], want+testPollJitter+2*testPollInterval, "gap %d: %v", i, gaps)
|
||||
}
|
||||
requireNoLeaks(t, srv, goroutines, buffers)
|
||||
}
|
||||
|
||||
func TestPollerVolumeGone(t *testing.T) {
|
||||
logs := captureLogLines(t)
|
||||
c, srv, u, _ := newPollingClient(t)
|
||||
var refreshes atomic.Int32
|
||||
unsubscribe := c.events.subscribe(func(_ []staleNode, refresh bool) {
|
||||
if refresh {
|
||||
refreshes.Add(1)
|
||||
}
|
||||
})
|
||||
defer unsubscribe()
|
||||
srv.Inject(protontest.Fault{Pattern: eventsRoute, Status: http.StatusUnprocessableEntity, Code: api.CodeNotExists})
|
||||
addPending(c.events, "uncached")
|
||||
listAll(t, c, u.RootID())
|
||||
require.Eventually(t, c.cache.empty, 2*time.Second, time.Millisecond, "the cache is cleared")
|
||||
assert.Empty(t, c.events.pendingIDs(), "nodes are still pending")
|
||||
|
||||
time.Sleep(2 * (testPollInterval + testPollJitter))
|
||||
listAll(t, c, u.RootID())
|
||||
c.events.wake()
|
||||
time.Sleep(2 * (testPollInterval + testPollJitter))
|
||||
latest, pages := eventRequests(srv)
|
||||
assert.Equal(t, 1, latest)
|
||||
assert.Equal(t, 1, pages, "polling stopped")
|
||||
assert.Len(t, logs.matching("ERROR", "protondrive: events"), 1)
|
||||
assert.Equal(t, int32(1), refreshes.Load())
|
||||
}
|
||||
|
||||
func TestPollerFirstLatestFails(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, srv, u, _ := newPollingClient(t)
|
||||
srv.Inject(protontest.Fault{Pattern: latestEventRoute, Status: http.StatusServiceUnavailable, Times: 1})
|
||||
dir := u.SeedFolder(u.RootID(), "dir")
|
||||
assert.Contains(t, listAll(t, c, u.RootID()), "dir", "the listing fails with the start cursor")
|
||||
|
||||
// The cursor is fetched again and polling goes on.
|
||||
require.Eventually(t, func() bool {
|
||||
_, pages := eventRequests(srv)
|
||||
return pages >= 1
|
||||
}, 5*time.Second, 5*time.Millisecond, "polling doesn't start")
|
||||
listAll(t, c, dir)
|
||||
u.SeedFile(dir, "new.txt", []byte("new"), time.Now())
|
||||
assert.Eventually(t, func() bool {
|
||||
_, ok := listAll(t, c, dir)["new.txt"]
|
||||
return ok
|
||||
}, 5*time.Second, 10*time.Millisecond)
|
||||
}
|
||||
|
||||
// TestPollerFirstLatestRateLimited checks a Retry-After on the start
|
||||
// cursor fetched when the cache fills doesn't hold up the caller, and
|
||||
// delays the next try instead.
|
||||
func TestPollerFirstLatestRateLimited(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, srv, u, _ := newPollingClient(t)
|
||||
srv.Inject(protontest.Fault{Pattern: latestEventRoute, Status: http.StatusTooManyRequests, RetryAfter: 2, Times: 1})
|
||||
start := time.Now()
|
||||
listAll(t, c, u.RootID())
|
||||
assert.Less(t, time.Since(start), time.Second, "the listing waited for the Retry-After")
|
||||
|
||||
require.Eventually(t, func() bool {
|
||||
latest, _ := eventRequests(srv)
|
||||
return latest >= 2
|
||||
}, 10*time.Second, 5*time.Millisecond, "the start cursor isn't fetched again")
|
||||
assert.GreaterOrEqual(t, time.Since(start), 2*time.Second, "tried again before the Retry-After")
|
||||
}
|
||||
|
||||
// TestPollerStopKeepsCursor checks polling resumed after stop goes on
|
||||
// from the cursor, rather than fetching a new one at once, so no two
|
||||
// requests come within an interval.
|
||||
func TestPollerStopKeepsCursor(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, srv, u, polls := newPollingClient(t)
|
||||
listAll(t, c, u.RootID())
|
||||
require.Eventually(t, func() bool { return len(polls.get()) >= 1 }, 5*time.Second, time.Millisecond)
|
||||
c.events.stop()
|
||||
c.cache.clear()
|
||||
|
||||
listAll(t, c, u.RootID())
|
||||
require.Eventually(t, func() bool { return len(polls.get()) >= 3 }, 5*time.Second, time.Millisecond)
|
||||
c.events.stop()
|
||||
latest, _ := eventRequests(srv)
|
||||
assert.Equal(t, 1, latest, "the start cursor is fetched again")
|
||||
for _, gap := range polls.gaps() {
|
||||
assert.GreaterOrEqual(t, gap, testPollInterval, "two polls within one interval")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPollerStopWaitsForPoll checks stop returns only once a poll in
|
||||
// flight has finished, so nothing of it, its logging included, runs
|
||||
// after Shutdown.
|
||||
func TestPollerStopWaitsForPoll(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
held, release := make(chan struct{}, 1), make(chan struct{})
|
||||
c := newTestClientTransport(t, srv, u, clientOptions{EnableCaching: true, EventsInterval: testPollInterval}, func(next http.RoundTripper) http.RoundTripper {
|
||||
return roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
resp, err := next.RoundTrip(r)
|
||||
if strings.HasPrefix(r.URL.Path, "/drive/v2/volumes/") && strings.Contains(r.URL.Path, "/events/") {
|
||||
// The response is in, as if the poll were cancelled
|
||||
// just after it arrived.
|
||||
select {
|
||||
case held <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
<-release
|
||||
}
|
||||
return resp, err
|
||||
})
|
||||
})
|
||||
c.events.jitter = testPollJitter
|
||||
listAll(t, c, u.RootID())
|
||||
select {
|
||||
case <-held:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("no poll")
|
||||
}
|
||||
stopped := make(chan struct{})
|
||||
go func() {
|
||||
c.events.stop()
|
||||
close(stopped)
|
||||
}()
|
||||
select {
|
||||
case <-stopped:
|
||||
t.Error("stop returned while a poll was in flight")
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
}
|
||||
close(release)
|
||||
select {
|
||||
case <-stopped:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("stop didn't return after the poll finished")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPollerIdleCacheCleared checks a cache unused for the idle time is
|
||||
// cleared, which stops polling, unless something subscribes.
|
||||
func TestPollerIdleCacheCleared(t *testing.T) {
|
||||
t.Parallel()
|
||||
const idle = 3 * testPollInterval
|
||||
c, srv, u, polls := newPollingClient(t)
|
||||
c.events.idle = idle
|
||||
u.SeedFolder(u.RootID(), "dir")
|
||||
listAll(t, c, u.RootID())
|
||||
|
||||
// Used, the cache is kept. Other clients' changes aren't use.
|
||||
for range 6 {
|
||||
time.Sleep(testPollInterval)
|
||||
u.SeedFolder(u.RootID(), random.String(8))
|
||||
c.cache.get(u.RootID())
|
||||
}
|
||||
assert.False(t, c.cache.empty(), "cleared while in use")
|
||||
|
||||
require.Eventually(t, c.cache.empty, 2*idle+2*testPollInterval, 5*time.Millisecond, "not cleared")
|
||||
n := len(polls.get())
|
||||
time.Sleep(3 * (testPollInterval + testPollJitter))
|
||||
assert.Equal(t, n, len(polls.get()), "polled after the cache was cleared")
|
||||
|
||||
// The next use refills the cache and polls again, from the cursor.
|
||||
assert.NotEmpty(t, listAll(t, c, u.RootID()))
|
||||
require.Eventually(t, func() bool { return len(polls.get()) > n }, 5*time.Second, 5*time.Millisecond, "polling didn't resume")
|
||||
latest, _ := eventRequests(srv)
|
||||
assert.Equal(t, 1, latest, "the start cursor is fetched again")
|
||||
|
||||
// With a subscriber the cache is kept.
|
||||
unsubscribe := c.events.subscribe(func([]staleNode, bool) {})
|
||||
defer unsubscribe()
|
||||
time.Sleep(2*idle + 2*testPollInterval)
|
||||
assert.False(t, c.cache.empty(), "cleared with a subscriber")
|
||||
}
|
||||
|
||||
// TestPollerNotifiesOutsideCallerLocks checks a subscriber isn't called
|
||||
// on the goroutine which filled the cache, which may hold a lock the
|
||||
// subscriber takes, as a dircache lookup holds the dircache's.
|
||||
func TestPollerNotifiesOutsideCallerLocks(t *testing.T) {
|
||||
t.Parallel()
|
||||
c, srv, u, _ := newPollingClient(t)
|
||||
var callerLock sync.Mutex
|
||||
notified := make(chan bool, 1)
|
||||
unsubscribe := c.events.subscribe(func(_ []staleNode, refresh bool) {
|
||||
callerLock.Lock()
|
||||
defer callerLock.Unlock()
|
||||
notified <- refresh
|
||||
})
|
||||
defer unsubscribe()
|
||||
srv.Inject(protontest.Fault{Pattern: latestEventRoute, Status: http.StatusUnprocessableEntity, Code: api.CodeNotExists})
|
||||
|
||||
done := make(chan struct{})
|
||||
callerLock.Lock()
|
||||
go func() {
|
||||
defer close(done)
|
||||
defer callerLock.Unlock()
|
||||
listAll(t, c, u.RootID())
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("deadlock: the subscriber was called inside the cache fill")
|
||||
}
|
||||
select {
|
||||
case refresh := <-notified:
|
||||
assert.True(t, refresh)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the subscriber wasn't notified")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package protondrive
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/config/configmap"
|
||||
)
|
||||
|
||||
// ConfigBrowserSignIn runs the browser sign-in of rclone config for
|
||||
// remote name on m, handing the sign-in page to approve instead of
|
||||
// printing it.
|
||||
func ConfigBrowserSignIn(ctx context.Context, name string, m configmap.Mapper, approve func(signInURL string)) error {
|
||||
out, err := configure(ctx, name, m, fs.ConfigIn{State: "browser"}, signInOptions{
|
||||
showURL: approve,
|
||||
pollInterval: 10 * time.Millisecond,
|
||||
pollTimeout: 10 * time.Second,
|
||||
})
|
||||
if err == nil && out != nil {
|
||||
err = fmt.Errorf("config stopped in state %q", out.State)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package protondrive_test
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rclone/rclone/backend/protondrive"
|
||||
"github.com/rclone/rclone/backend/protondrive/api"
|
||||
"github.com/rclone/rclone/backend/protondrive/protontest"
|
||||
"github.com/rclone/rclone/fstest"
|
||||
"github.com/rclone/rclone/fstest/fstests"
|
||||
"github.com/rclone/rclone/lib/random"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// fakeEnvPrefix starts the environment variables configuring the
|
||||
// TestProtonDriveFake: remote.
|
||||
const fakeEnvPrefix = "RCLONE_CONFIG_TESTPROTONDRIVEFAKE_"
|
||||
|
||||
// setupFakeRemote starts a fake Proton server with one user and
|
||||
// configures the TestProtonDriveFake: remote, through environment
|
||||
// variables, with a saved session of that user. It polls events every
|
||||
// second, as the remote protonfake configures does.
|
||||
func setupFakeRemote(t *testing.T) (remoteName string, srv *protontest.Server, user *protontest.User) {
|
||||
srv = protontest.New(t)
|
||||
user = srv.AddUser("user", "pass")
|
||||
sess := srv.NewSession(user)
|
||||
t.Setenv(fakeEnvPrefix+"TYPE", "protondrive")
|
||||
t.Setenv(fakeEnvPrefix+"ENDPOINT", srv.URL())
|
||||
t.Setenv(fakeEnvPrefix+"CLIENT_UID", sess.UID)
|
||||
t.Setenv(fakeEnvPrefix+"CLIENT_ACCESS_TOKEN", sess.AccessToken)
|
||||
t.Setenv(fakeEnvPrefix+"CLIENT_REFRESH_TOKEN", sess.RefreshToken)
|
||||
// The config holds the salted key password base64 encoded.
|
||||
t.Setenv(fakeEnvPrefix+"CLIENT_SALTED_KEY_PASS", base64.StdEncoding.EncodeToString([]byte(user.KeyPassword())))
|
||||
t.Setenv(fakeEnvPrefix+"DRAFT_CLIENT_UID", random.String(32))
|
||||
t.Setenv(fakeEnvPrefix+"EVENTS_MIN_INTERVAL", "1s")
|
||||
return "TestProtonDriveFake:", srv, user
|
||||
}
|
||||
|
||||
// TestSetupFakeRemote checks the configured session is accepted by the
|
||||
// fake server.
|
||||
func TestSetupFakeRemote(t *testing.T) {
|
||||
remoteName, srv, user := setupFakeRemote(t)
|
||||
assert.Equal(t, "TestProtonDriveFake:", remoteName)
|
||||
assert.Equal(t, "protondrive", os.Getenv(fakeEnvPrefix+"TYPE"))
|
||||
assert.Equal(t, srv.URL(), os.Getenv(fakeEnvPrefix+"ENDPOINT"))
|
||||
assert.NotEmpty(t, os.Getenv(fakeEnvPrefix+"DRAFT_CLIENT_UID"))
|
||||
keyPass, err := base64.StdEncoding.DecodeString(os.Getenv(fakeEnvPrefix + "CLIENT_SALTED_KEY_PASS"))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, user.KeyPassword(), string(keyPass))
|
||||
require.NotEmpty(t, os.Getenv(fakeEnvPrefix+"CLIENT_REFRESH_TOKEN"))
|
||||
|
||||
req, err := http.NewRequest("GET", os.Getenv(fakeEnvPrefix+"ENDPOINT")+"/core/v4/users", nil)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("x-pm-appversion", "external-drive-rclone@1.0.0-stable")
|
||||
req.Header.Set("x-pm-uid", os.Getenv(fakeEnvPrefix+"CLIENT_UID"))
|
||||
req.Header.Set("Authorization", "Bearer "+os.Getenv(fakeEnvPrefix+"CLIENT_ACCESS_TOKEN"))
|
||||
resp, err := srv.Client().Do(req)
|
||||
require.NoError(t, err)
|
||||
_ = resp.Body.Close()
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
}
|
||||
|
||||
// TestIntegrationFake runs integration tests against the fake server.
|
||||
func TestIntegrationFake(t *testing.T) {
|
||||
if *fstest.RemoteName != "" {
|
||||
t.Skip("skipping as -remote is set")
|
||||
}
|
||||
remoteName, srv, _ := setupFakeRemote(t)
|
||||
t.Cleanup(func() {
|
||||
// fstests leaves Fs of the remote behind which go on polling
|
||||
// events, and logging, into later tests. Gone, the volume
|
||||
// stops them for good before the server closes.
|
||||
for _, pattern := range []string{"/drive/volumes/{volumeID}/events/latest", "/drive/v2/volumes/{volumeID}/events/{eventID}"} {
|
||||
srv.Inject(protontest.Fault{Pattern: pattern, Status: http.StatusUnprocessableEntity, Code: api.CodeNotExists})
|
||||
}
|
||||
time.Sleep(3 * time.Second) // an interval of 1s, up to 1s of jitter, and slack
|
||||
})
|
||||
fstests.Run(t, &fstests.Opt{
|
||||
RemoteName: remoteName,
|
||||
NilObject: (*protondrive.Object)(nil),
|
||||
QuickTestOK: true,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
package protondrive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
"unicode/utf16"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/ProtonMail/gopenpgp/v3/crypto"
|
||||
"github.com/rclone/rclone/backend/protondrive/api"
|
||||
"github.com/rclone/rclone/backend/protondrive/protontest"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Fuzz targets for everything which parses bytes the server controls.
|
||||
// Each is seeded from the old library's fixtures in testdata/oldlib and
|
||||
// from payloads the fake server makes, and checks invariants of what
|
||||
// is accepted, not only that nothing panics.
|
||||
|
||||
// oldlibFixture is the part of testdata/oldlib/file.json and
|
||||
// folder.json the fuzz targets use.
|
||||
type oldlibFixture struct {
|
||||
NodeKey string
|
||||
NodePassphrasePlain string
|
||||
NamePlain string
|
||||
ChildName string
|
||||
XAttr string
|
||||
}
|
||||
|
||||
// loadOldlibFixture returns testdata/oldlib/name.
|
||||
func loadOldlibFixture(t testing.TB, name string) oldlibFixture {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile(filepath.Join("testdata/oldlib", name))
|
||||
require.NoError(t, err)
|
||||
var fx oldlibFixture
|
||||
require.NoError(t, json.Unmarshal(data, &fx))
|
||||
return fx
|
||||
}
|
||||
|
||||
// fuzzLinks returns a client for a user of a fake server holding the
|
||||
// keys of the old library's v6 file fixture, the root folder's keys,
|
||||
// and the JSON of a link of each kind the client reads: the fixture
|
||||
// itself, and nodes the fake makes as SDK clients would.
|
||||
func fuzzLinks(f *testing.F) (*client, *nodeKeys, [][]byte) {
|
||||
frozen := loadFrozenFile(f, filepath.Join(frozenFileDir, "v6"))
|
||||
srv := protontest.New(f)
|
||||
u := srv.AddUserWithKeys(frozen.Email, "pass", frozen.Keys)
|
||||
c := newTestClientFor(f, srv, u, clientOptions{})
|
||||
root := u.RootID()
|
||||
ids := []string{
|
||||
u.SeedStoredFile(root, frozen.Stored),
|
||||
u.SeedFolder(root, "folder"),
|
||||
u.SeedFile(root, "file.txt", []byte("content"), time.Now()),
|
||||
u.SeedFile(root, "empty", nil, time.Now()),
|
||||
u.SeedLegacyFile(root, "legacy", []byte("legacy")),
|
||||
u.SeedAnonymousFile(root, "anonymous", []byte("anonymous"), time.Now()),
|
||||
u.SeedAnonymousFolder(root, "anonymous folder"),
|
||||
u.SeedFileClaimingBlockSizes(root, "claims", []byte("claims"), []int64{1, 2, 3}),
|
||||
u.SeedDoc(root, "doc"),
|
||||
}
|
||||
ctx := context.Background()
|
||||
links, err := c.fetchLinks(ctx, ids)
|
||||
require.NoError(f, err)
|
||||
require.Len(f, links, len(ids))
|
||||
var seeds [][]byte
|
||||
for _, d := range links {
|
||||
data, err := json.Marshal(d)
|
||||
require.NoError(f, err)
|
||||
seeds = append(seeds, data)
|
||||
}
|
||||
keys, err := c.folderKeysOf(ctx, root)
|
||||
require.NoError(f, err)
|
||||
return c, keys, seeds
|
||||
}
|
||||
|
||||
func FuzzValidateName(f *testing.F) {
|
||||
for _, name := range []string{
|
||||
loadOldlibFixture(f, "file.json").NamePlain,
|
||||
loadOldlibFixture(f, "folder.json").NamePlain,
|
||||
loadOldlibFixture(f, "folder.json").ChildName,
|
||||
"file.txt", ".", "..", "...", "", "a/b", "/", "a\x00b", " ", "é", "é",
|
||||
strings.Repeat("a", maxNameLength), strings.Repeat("a", maxNameLength+1),
|
||||
strings.Repeat("\U0001F600", maxNameLength/2), strings.Repeat("\U0001F600", maxNameLength/2+1),
|
||||
"\xff\xfe",
|
||||
} {
|
||||
f.Add(name)
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, name string) {
|
||||
if validateName(name) != nil {
|
||||
return
|
||||
}
|
||||
assert.NotEmpty(t, name)
|
||||
assert.True(t, utf8.ValidString(name), "%q", name)
|
||||
assert.NotEqual(t, ".", name)
|
||||
assert.NotEqual(t, "..", name)
|
||||
assert.NotContains(t, name, "/")
|
||||
assert.NotContains(t, name, "\x00")
|
||||
assert.LessOrEqual(t, len(utf16.Encode([]rune(name))), maxNameLength)
|
||||
})
|
||||
}
|
||||
|
||||
func FuzzDecodeLink(f *testing.F) {
|
||||
c, rootKeys, seeds := fuzzLinks(f)
|
||||
for _, seed := range seeds {
|
||||
f.Add(seed)
|
||||
// Hostile values in links which otherwise decrypt.
|
||||
var d api.LinkDetails
|
||||
require.NoError(f, json.Unmarshal(seed, &d))
|
||||
for _, change := range []func(d *api.LinkDetails){
|
||||
func(d *api.LinkDetails) { d.Link.LinkID = "" },
|
||||
func(d *api.LinkDetails) { d.Link.Type = 3 - d.Link.Type },
|
||||
func(d *api.LinkDetails) {
|
||||
if d.File != nil && d.File.ActiveRevision != nil {
|
||||
d.File.ActiveRevision.EncryptedSize = -5
|
||||
}
|
||||
},
|
||||
} {
|
||||
changed := d
|
||||
changed.File = cloneFile(d.File)
|
||||
change(&changed)
|
||||
data, err := json.Marshal(changed)
|
||||
require.NoError(f, err)
|
||||
f.Add(data)
|
||||
}
|
||||
}
|
||||
// Shapes the client can't decrypt.
|
||||
for _, format := range []string{"legacy", "v6"} {
|
||||
data, err := os.ReadFile(filepath.Join(frozenFileDir, format, "link.json"))
|
||||
require.NoError(f, err)
|
||||
f.Add(data)
|
||||
}
|
||||
f.Add([]byte(`{}`))
|
||||
f.Add([]byte(`{"Link":{"LinkID":"x","Type":1,"ParentLinkID":"p"},"Folder":{}}`))
|
||||
ctx := context.Background()
|
||||
f.Fuzz(func(t *testing.T, data []byte) {
|
||||
var d api.LinkDetails
|
||||
if json.Unmarshal(data, &d) != nil {
|
||||
return
|
||||
}
|
||||
n, unreadable, err := c.decryptNode(ctx, &d, rootKeys)
|
||||
if err != nil || unreadable != nil {
|
||||
assert.Nil(t, n)
|
||||
return
|
||||
}
|
||||
require.NotNil(t, n)
|
||||
assert.NotEmpty(t, n.ID)
|
||||
assert.Equal(t, d.Link.LinkID, n.ID)
|
||||
assert.True(t, utf8.ValidString(n.Name), "%q", n.Name)
|
||||
if d.Link.ParentLinkID != "" {
|
||||
assert.NoError(t, validateName(n.Name))
|
||||
}
|
||||
assert.True(t, n.IsFolder == (d.Link.Type == api.LinkTypeFolder))
|
||||
for _, original := range []bool{true, false} {
|
||||
assert.GreaterOrEqual(t, n.size(original), int64(0), "original=%v", original)
|
||||
}
|
||||
if n.X != nil {
|
||||
checkXAttrs(t, n.X)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// cloneFile returns a copy of file, sharing nothing changeable with it.
|
||||
func cloneFile(file *api.File) *api.File {
|
||||
if file == nil {
|
||||
return nil
|
||||
}
|
||||
out := *file
|
||||
if file.ActiveRevision != nil {
|
||||
rev := *file.ActiveRevision
|
||||
out.ActiveRevision = &rev
|
||||
}
|
||||
return &out
|
||||
}
|
||||
|
||||
// checkXAttrs checks the invariants of parsed extended attributes.
|
||||
//
|
||||
// That the block sizes add up to the size isn't one: as in the SDK
|
||||
// neither is checked against the other, and a read checks each block
|
||||
// against its recorded size, so a file whose attributes disagree fails
|
||||
// to read rather than reading wrong.
|
||||
func checkXAttrs(t *testing.T, x *xattrs) {
|
||||
t.Helper()
|
||||
assert.GreaterOrEqual(t, x.Size, int64(0))
|
||||
if x.NoSize {
|
||||
assert.Zero(t, x.Size)
|
||||
}
|
||||
if x.BlockSizes != nil {
|
||||
assert.NotEmpty(t, x.BlockSizes)
|
||||
}
|
||||
for i, size := range x.BlockSizes {
|
||||
assert.Positive(t, size, "block %d", i+1)
|
||||
}
|
||||
if !x.ModTime.IsZero() {
|
||||
assert.Equal(t, time.UTC, x.ModTime.Location())
|
||||
// RFC 3339 years, moved by a zone offset of under a day.
|
||||
assert.True(t, x.ModTime.Year() >= -1 && x.ModTime.Year() <= 10000, "%v", x.ModTime)
|
||||
}
|
||||
assert.NotContains(t, x.Extra, "Common")
|
||||
}
|
||||
|
||||
func FuzzCheckKeyS2K(f *testing.F) {
|
||||
f.Add(unarmor(f, loadOldlibFixture(f, "file.json").NodeKey))
|
||||
now := time.Now()
|
||||
parent, signer := newTestKeyRing(f, now), newTestKeyRing(f, now)
|
||||
_, _, _, keys := testNodeKeys(f, parent, signer, true, now)
|
||||
for _, memExp := range []byte{3, 17, 18, 31} {
|
||||
f.Add(unarmor(f, argon2Locked(f, keys, 1, 1, memExp)))
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, data []byte) {
|
||||
// Whatever the bytes, the check never runs a KDF and never
|
||||
// panics; a key it lets through still parses or fails to.
|
||||
if checkKeyS2K(data) == nil {
|
||||
_, _ = crypto.NewKey(data)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func FuzzDecryptXAttrs(f *testing.F) {
|
||||
fx := loadOldlibFixture(f, "file.json")
|
||||
key, err := unlockKey(fx.NodeKey, []byte(fx.NodePassphrasePlain))
|
||||
require.NoError(f, err)
|
||||
nodeKR, err := crypto.NewKeyRing(key)
|
||||
require.NoError(f, err)
|
||||
now := time.Now()
|
||||
|
||||
// The old library's attributes, encrypted and in plain text.
|
||||
res, _, _, err := decryptMessage(fx.XAttr, nodeKR, nil, now, maxXAttrsSize)
|
||||
require.NoError(f, err)
|
||||
f.Add(fx.XAttr, res.Bytes())
|
||||
// Attributes as the fake writes them for SDK clients.
|
||||
c, _, seeds := fuzzLinks(f)
|
||||
for _, seed := range seeds {
|
||||
var d api.LinkDetails
|
||||
require.NoError(f, json.Unmarshal(seed, &d))
|
||||
if d.File == nil || d.File.ActiveRevision == nil || d.File.ActiveRevision.XAttr == "" {
|
||||
continue
|
||||
}
|
||||
n, err := c.getNode(context.Background(), d.Link.LinkID)
|
||||
require.NoError(f, err)
|
||||
res, _, _, err := decryptMessage(d.File.ActiveRevision.XAttr, n.keys.keyRing, nil, now, maxXAttrsSize)
|
||||
require.NoError(f, err)
|
||||
f.Add("", res.Bytes())
|
||||
}
|
||||
for _, plain := range []string{
|
||||
`{"Common":{"ModificationTime":"2021-09-16T07:40:54+0000","Size":-1,"BlockSizes":[4194304,-1],"Digests":{"SHA1":"x"}}}`,
|
||||
`{"Common":{"Size":1152921504606846976,"BlockSizes":[1152921504606846976,1]}}`,
|
||||
`{"Common":{"ModificationTime":"99999-01-01T00:00:00Z"}}`,
|
||||
`{"Common":{"ModificationTime":"0000-01-01T00:00:00+23:59"}}`,
|
||||
`{"Common":{"BlockSizes":[]},"Media":{"Width":1}}`,
|
||||
`{"Common":{"BlockSizes":[` + strings.Repeat("4194304,", 10000) + `1]}}`,
|
||||
strings.Repeat(`{"Common":`, 20000) + strings.Repeat("}", 20000),
|
||||
`{"Common":` + strings.Repeat("[", 100000) + strings.Repeat("]", 100000) + `}`,
|
||||
} {
|
||||
f.Add("", []byte(plain))
|
||||
}
|
||||
|
||||
f.Fuzz(func(t *testing.T, enc string, plain []byte) {
|
||||
if x, _, err := decryptXAttrs(enc, nodeKR, nodeKR, now); err == nil {
|
||||
checkXAttrs(t, x)
|
||||
}
|
||||
if len(plain) > maxXAttrsSize/2 {
|
||||
return
|
||||
}
|
||||
enc, err := encryptArmored(plain, nil, nodeKR, nodeKR, true, now)
|
||||
require.NoError(t, err)
|
||||
x, verifyErr, err := decryptXAttrs(enc, nodeKR, nodeKR, now)
|
||||
if !utf8.Valid(plain) {
|
||||
assert.Error(t, err)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, verifyErr)
|
||||
checkXAttrs(t, x)
|
||||
})
|
||||
}
|
||||
|
||||
func FuzzDecodeAPIError(f *testing.F) {
|
||||
for _, seed := range []struct {
|
||||
status int
|
||||
body string
|
||||
retryAfter string
|
||||
}{
|
||||
{422, `{"Code":2500,"Error":"A file or folder with that name already exists","Details":{"ConflictLinkID":"abc","ConflictRevisionID":"def"}}`, ""},
|
||||
{422, `{"Code":2501,"Error":"File or folder not found"}`, ""},
|
||||
{429, `{"Code":85131,"Error":"Too many recent API requests"}`, "17"},
|
||||
{429, ``, "Wed, 21 Oct 2015 07:28:00 GMT"},
|
||||
{429, ``, "99999999999999999999999"},
|
||||
{401, `{"Code":401,"Error":"Invalid access token"}`, ""},
|
||||
{400, `{"Code":2064,"Error":"protontest: invalid x-pm-appversion \"x\""}`, ""},
|
||||
{500, `<html>Internal Server Error</html>`, ""},
|
||||
{200, `{"Code":"1000"}`, ""},
|
||||
{0, `{"Error":null,"Details":[1,2,3]}`, "-5"},
|
||||
} {
|
||||
f.Add(seed.status, []byte(seed.body), seed.retryAfter)
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, status int, body []byte, retryAfterValue string) {
|
||||
resp := &http.Response{
|
||||
StatusCode: status,
|
||||
Status: fmt.Sprintf("%d %s", status, http.StatusText(status)),
|
||||
Header: http.Header{"Retry-After": {retryAfterValue}},
|
||||
Body: io.NopCloser(bytes.NewReader(body)),
|
||||
}
|
||||
err := errorHandler(resp)
|
||||
var apiErr *api.Error
|
||||
require.ErrorAs(t, err, &apiErr)
|
||||
assert.Equal(t, status, apiErr.Status)
|
||||
assert.NotEmpty(t, apiErr.Message)
|
||||
assert.NotEmpty(t, err.Error())
|
||||
assert.Equal(t, apiErr.Code, apiErrorCode(err))
|
||||
|
||||
wait := retryAfter(resp)
|
||||
assert.Positive(t, wait)
|
||||
assert.LessOrEqual(t, wait, maxRetryAfter)
|
||||
})
|
||||
}
|
||||
|
||||
func FuzzDecryptForkPayload(f *testing.F) {
|
||||
key := bytes.Repeat([]byte{7}, 32)
|
||||
for _, seed := range []struct{ plain, aad string }{
|
||||
{`{"type":"default","keyPassword":"the-key-password"}`, forkPayloadAAD},
|
||||
{`{"keyPassword":""}`, forkPayloadAAD},
|
||||
{`{"keyPassword":null}`, forkPayloadAAD},
|
||||
{`{"type":"default"}`, forkPayloadAAD},
|
||||
{`not json`, forkPayloadAAD},
|
||||
{`{"keyPassword":"wrong additional data"}`, "other"},
|
||||
} {
|
||||
f.Add(sealForkPayload(f, key, seed.plain, seed.aad))
|
||||
}
|
||||
f.Add("")
|
||||
f.Add("not base64!")
|
||||
f.Add(base64.StdEncoding.EncodeToString(make([]byte, 12)))
|
||||
f.Fuzz(func(t *testing.T, payload string) {
|
||||
keyPassword, err := decryptForkPayload(payload, key)
|
||||
if err != nil {
|
||||
assert.Empty(t, keyPassword)
|
||||
return
|
||||
}
|
||||
// Success only for a payload sealed with key: open it here
|
||||
// independently.
|
||||
blob, err := base64.StdEncoding.DecodeString(payload)
|
||||
require.NoError(t, err)
|
||||
block, err := aes.NewCipher(key)
|
||||
require.NoError(t, err)
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
require.NoError(t, err)
|
||||
require.GreaterOrEqual(t, len(blob), gcm.NonceSize())
|
||||
plain, err := gcm.Open(nil, blob[:gcm.NonceSize()], blob[gcm.NonceSize():], []byte(forkPayloadAAD))
|
||||
require.NoError(t, err, "accepted a payload which doesn't authenticate")
|
||||
var p struct{ KeyPassword *string }
|
||||
require.NoError(t, json.Unmarshal(plain, &p))
|
||||
require.NotNil(t, p.KeyPassword)
|
||||
assert.Equal(t, *p.KeyPassword, keyPassword)
|
||||
})
|
||||
}
|
||||
|
||||
func FuzzDecodeEvents(f *testing.F) {
|
||||
// Pages the fake sends for changes of each kind.
|
||||
srv := protontest.New(f)
|
||||
u := srv.AddUser("user", "pass")
|
||||
var (
|
||||
mu sync.Mutex
|
||||
pages [][]byte
|
||||
)
|
||||
c := newTestClientTransport(f, srv, u, clientOptions{EnableCaching: true}, func(next http.RoundTripper) http.RoundTripper {
|
||||
return roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
resp, err := next.RoundTrip(r)
|
||||
if err != nil || !strings.Contains(r.URL.Path, "/events/") {
|
||||
return resp, err
|
||||
}
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mu.Lock()
|
||||
pages = append(pages, body)
|
||||
mu.Unlock()
|
||||
resp.Body = io.NopCloser(bytes.NewReader(body))
|
||||
return resp, nil
|
||||
})
|
||||
})
|
||||
srv.SetEventsPageSize(3)
|
||||
ctx := context.Background()
|
||||
start, err := c.latestEventID(ctx)
|
||||
require.NoError(f, err)
|
||||
dir := u.SeedFolder(u.RootID(), "dir")
|
||||
file := u.SeedFile(dir, "file", []byte("x"), time.Now())
|
||||
u.SetParent(file, u.RootID())
|
||||
srv.InjectEvent(u, protontest.Event{Type: protontest.EventUpdateMetadata, LinkID: dir, ParentLinkID: u.RootID(), IsTrashed: true})
|
||||
srv.InjectEvent(u, protontest.Event{Type: protontest.EventDelete, LinkID: dir})
|
||||
_, _, _, err = c.pollEvents(ctx, start)
|
||||
require.NoError(f, err)
|
||||
srv.ExpireEvents(u)
|
||||
_, _, _, err = c.pollEvents(ctx, start)
|
||||
require.NoError(f, err)
|
||||
require.NotEmpty(f, pages)
|
||||
for _, page := range pages {
|
||||
f.Add(page)
|
||||
}
|
||||
f.Add([]byte(`{"Code":1000,"Events":[{"EventID":"e","EventType":0,"Link":{"LinkID":"dir","ParentLinkID":null}}],"EventID":"e","More":true}`))
|
||||
f.Add([]byte(`{"Events":[{"EventType":99,"Link":{"LinkID":"root","ParentLinkID":"root","IsTrashed":true}}]}`))
|
||||
f.Add([]byte(`{"Events":[{"EventType":2,"Link":{"LinkID":"a","ParentLinkID":"a"}}]}`))
|
||||
f.Add([]byte(`{"Events":null,"More":1}`))
|
||||
f.Fuzz(func(t *testing.T, data []byte) {
|
||||
var resp api.EventsResponse
|
||||
if json.Unmarshal(data, &resp) != nil {
|
||||
return
|
||||
}
|
||||
c := eventsTestClient()
|
||||
c.cache.put(&node{ID: "a", ParentID: "b", IsFolder: true})
|
||||
c.cache.put(&node{ID: "b", ParentID: "a", IsFolder: true})
|
||||
changes := eventChanges(resp.Events)
|
||||
stale := c.applyEvents(changes)
|
||||
require.Len(t, stale, len(changes))
|
||||
for i, ch := range changes {
|
||||
assert.NotEmpty(t, ch.linkID)
|
||||
assert.Equal(t, ch.linkID, stale[i].id)
|
||||
assert.Nil(t, c.cache.get(ch.linkID), "changed node %s still cached", ch.linkID)
|
||||
}
|
||||
})
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+1076
-881
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,7 @@
|
||||
package protondrive_test
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"testing"
|
||||
|
||||
"github.com/rclone/rclone/backend/protondrive"
|
||||
@@ -9,6 +10,13 @@ import (
|
||||
|
||||
// TestIntegration runs integration tests against the remote
|
||||
func TestIntegration(t *testing.T) {
|
||||
// A golden capture runs with the real config, where this test would
|
||||
// write to and delete from the live remote if -run let it through.
|
||||
for _, name := range []string{"capture", "capture-remote"} {
|
||||
if f := flag.Lookup(name); f != nil && f.Value.String() != "" {
|
||||
t.Skipf("-%s is set: not running integration tests during a golden capture", name)
|
||||
}
|
||||
}
|
||||
fstests.Run(t, &fstests.Opt{
|
||||
RemoteName: "TestProtonDrive:",
|
||||
NilObject: (*protondrive.Object)(nil),
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
package protontest
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/ProtonMail/go-srp"
|
||||
"github.com/ProtonMail/gopenpgp/v3/crypto"
|
||||
"github.com/rclone/rclone/backend/protondrive/api"
|
||||
)
|
||||
|
||||
// userKey is a user key with the password salt which locks it.
|
||||
type userKey struct {
|
||||
id string
|
||||
salt string // base64
|
||||
keyPassword string // derived from the mailbox password and salt
|
||||
armored string // private key locked with keyPassword
|
||||
key *crypto.Key
|
||||
}
|
||||
|
||||
// address is an email address of a user.
|
||||
type address struct {
|
||||
id string
|
||||
email string
|
||||
keys []*addressKey // the primary key is first
|
||||
}
|
||||
|
||||
// addressKey is an address key, locked with a random passphrase which
|
||||
// is stored encrypted to and signed by the primary user key.
|
||||
type addressKey struct {
|
||||
id string
|
||||
passphrase []byte
|
||||
armored string // private key locked with passphrase
|
||||
token string // armored passphrase encrypted to the user key
|
||||
signature string // armored detached signature of passphrase by the user key
|
||||
key *crypto.Key
|
||||
}
|
||||
|
||||
// mustCrypto panics with a message naming what failed if err is not nil.
|
||||
//
|
||||
// Key operations on keys the fake generated itself fail only on a bug.
|
||||
func mustCrypto(what string, err error) {
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("protontest: %s: %v", what, err))
|
||||
}
|
||||
}
|
||||
|
||||
// generateKey returns a new unlocked Curve25519 key for email, which
|
||||
// is fast to generate unlike RSA.
|
||||
func generateKey(name, email string) *crypto.Key {
|
||||
key, err := crypto.PGP().KeyGeneration().AddUserId(name, email).GenerationTime(signTime()).New().GenerateKey()
|
||||
mustCrypto("generate key", err)
|
||||
return key
|
||||
}
|
||||
|
||||
// lockKey returns key armored and locked with passphrase.
|
||||
func lockKey(key *crypto.Key, passphrase []byte) string {
|
||||
locked, err := crypto.PGP().LockKey(key, passphrase)
|
||||
mustCrypto("lock key", err)
|
||||
armored, err := locked.Armor()
|
||||
mustCrypto("armor key", err)
|
||||
return armored
|
||||
}
|
||||
|
||||
// newUserKey returns a new user key for u locked with a key password
|
||||
// derived from u's mailbox password and a new salt.
|
||||
func newUserKey(u *User) *userKey {
|
||||
rawSalt := randomBytes(16)
|
||||
hashed, err := srp.MailboxPassword([]byte(u.MailboxPassword), rawSalt)
|
||||
mustCrypto("hash mailbox password", err)
|
||||
k := &userKey{
|
||||
id: randomID(),
|
||||
salt: base64.StdEncoding.EncodeToString(rawSalt),
|
||||
keyPassword: string(hashed[len(hashed)-31:]),
|
||||
key: generateKey(u.Username, u.Username),
|
||||
}
|
||||
k.armored = lockKey(k.key, []byte(k.keyPassword))
|
||||
return k
|
||||
}
|
||||
|
||||
// newAddress returns a new address with one address key whose
|
||||
// passphrase is encrypted to userKey.
|
||||
func newAddress(email string, userKey *userKey) *address {
|
||||
passphrase := []byte(hex.EncodeToString(randomBytes(32)))
|
||||
key := generateKey(email, email)
|
||||
k := &addressKey{
|
||||
id: randomID(),
|
||||
passphrase: passphrase,
|
||||
armored: lockKey(key, passphrase),
|
||||
key: key,
|
||||
}
|
||||
k.sealPassphrase(userKey)
|
||||
return &address{id: randomID(), email: email, keys: []*addressKey{k}}
|
||||
}
|
||||
|
||||
// sealPassphrase sets the token and signature of k to its passphrase
|
||||
// encrypted to and signed by userKey, as Proton stores it.
|
||||
func (k *addressKey) sealPassphrase(userKey *userKey) {
|
||||
eh, err := crypto.PGP().Encryption().Recipient(userKey.key).New()
|
||||
mustCrypto("address key token", err)
|
||||
msg, err := eh.Encrypt(k.passphrase)
|
||||
mustCrypto("address key token", err)
|
||||
token, err := msg.ArmorBytes()
|
||||
mustCrypto("address key token", err)
|
||||
sh, err := crypto.PGP().Sign().SigningKey(userKey.key).Detached().SignTime(signTime()).New()
|
||||
mustCrypto("address key signature", err)
|
||||
sig, err := sh.Sign(k.passphrase, crypto.Armor)
|
||||
mustCrypto("address key signature", err)
|
||||
k.token, k.signature = string(token), string(sig)
|
||||
}
|
||||
|
||||
// KeyPassword returns the password which unlocks u's primary user key:
|
||||
// the last 31 characters of the bcrypt hash of the mailbox password
|
||||
// and the key salt, as a client derives it.
|
||||
func (u *User) KeyPassword() string {
|
||||
u.srv.mu.Lock()
|
||||
defer u.srv.mu.Unlock()
|
||||
return u.keyPassword
|
||||
}
|
||||
|
||||
// Email returns u's primary address.
|
||||
func (u *User) Email() string {
|
||||
u.srv.mu.Lock()
|
||||
defer u.srv.mu.Unlock()
|
||||
return u.addresses[0].email
|
||||
}
|
||||
|
||||
// AddAddress adds an address with a new address key to u.
|
||||
func (u *User) AddAddress(email string) {
|
||||
u.srv.mu.Lock()
|
||||
primary := u.keys[len(u.keys)-1]
|
||||
u.srv.mu.Unlock()
|
||||
addr := newAddress(email, primary)
|
||||
u.srv.mu.Lock()
|
||||
defer u.srv.mu.Unlock()
|
||||
u.addresses = append(u.addresses, addr)
|
||||
}
|
||||
|
||||
// AddUserKey gives u a new primary user key with a new salt, so
|
||||
// KeySalt and KeyPassword change.
|
||||
//
|
||||
// The old keys are listed before the new one and stay locked with
|
||||
// their old key password, as after a key password change on an account
|
||||
// with legacy keys. The address key passphrases are re-encrypted to the
|
||||
// new key.
|
||||
func (u *User) AddUserKey() {
|
||||
key := newUserKey(u)
|
||||
u.srv.mu.Lock()
|
||||
defer u.srv.mu.Unlock()
|
||||
u.keys = append(u.keys, key)
|
||||
u.KeySalt, u.keyPassword = key.salt, key.keyPassword
|
||||
for _, addr := range u.addresses {
|
||||
for _, k := range addr.keys {
|
||||
k.sealPassphrase(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// CorruptAddressKeySignature replaces the Signature of every key of u's
|
||||
// address email, as a malicious server would: with a valid signature
|
||||
// by an unrelated key, or with nothing if empty is true. AddUserKey
|
||||
// restores the signatures.
|
||||
func (s *Server) CorruptAddressKeySignature(u *User, email string, empty bool) {
|
||||
impostor := generateKey("impostor", "impostor@proton.test")
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
addr := u.addressByEmailLocked(email)
|
||||
if addr == nil {
|
||||
panic("protontest: no address " + email)
|
||||
}
|
||||
for _, k := range addr.keys {
|
||||
if empty {
|
||||
k.signature = ""
|
||||
continue
|
||||
}
|
||||
// Sign the real passphrase, so only the signer is wrong.
|
||||
sh, err := crypto.PGP().Sign().SigningKey(impostor).Detached().SignTime(signTime()).New()
|
||||
mustCrypto("impostor signature", err)
|
||||
sig, err := sh.Sign(k.passphrase, crypto.Armor)
|
||||
mustCrypto("impostor signature", err)
|
||||
k.signature = string(sig)
|
||||
}
|
||||
}
|
||||
|
||||
// EncryptToAddress returns plaintext as an armored message encrypted to
|
||||
// the primary key of u's address email.
|
||||
func (u *User) EncryptToAddress(email string, plaintext []byte) string {
|
||||
u.srv.mu.Lock()
|
||||
addr := u.addressByEmailLocked(email)
|
||||
u.srv.mu.Unlock()
|
||||
if addr == nil {
|
||||
panic("protontest: no address " + email)
|
||||
}
|
||||
eh, err := crypto.PGP().Encryption().Recipient(addr.keys[0].key).New()
|
||||
mustCrypto("encrypt to address", err)
|
||||
msg, err := eh.Encrypt(plaintext)
|
||||
mustCrypto("encrypt to address", err)
|
||||
armored, err := msg.ArmorBytes()
|
||||
mustCrypto("encrypt to address", err)
|
||||
return string(armored)
|
||||
}
|
||||
|
||||
// addressByEmailLocked returns u's address email or nil. srv.mu must
|
||||
// be held.
|
||||
func (u *User) addressByEmailLocked(email string) *address {
|
||||
for _, addr := range u.addresses {
|
||||
if addr.email == email {
|
||||
return addr
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// boolInt returns 1 for true and 0 for false, as the API encodes flags.
|
||||
func boolInt(b bool) int {
|
||||
if b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// registerAccount registers the user, address and public key routes.
|
||||
func (s *Server) registerAccount() {
|
||||
s.handleAuth("GET", "/core/v4/users", s.handleUser)
|
||||
s.handleAuth("GET", "/core/v4/addresses", s.handleAddresses)
|
||||
s.handleAuth("GET", "/core/v4/keys/all", s.handlePublicKeys)
|
||||
}
|
||||
|
||||
// userWithQuota is api.User with the quota fields of Proton's User
|
||||
// schema (coreTypes.ts).
|
||||
type userWithQuota struct {
|
||||
api.User
|
||||
UsedSpace int64
|
||||
MaxSpace int64
|
||||
ProductUsedSpace productUsedSpace
|
||||
}
|
||||
|
||||
// productUsedSpace is the UserUsage schema: used space per product.
|
||||
type productUsedSpace struct {
|
||||
Calendar int64
|
||||
Contact int64
|
||||
Drive int64
|
||||
Mail int64
|
||||
Pass int64
|
||||
Lumo int64
|
||||
}
|
||||
|
||||
// handleUser returns the user, its keys and its quota, all used space
|
||||
// being Drive's.
|
||||
func (s *Server) handleUser(w http.ResponseWriter, r *http.Request, u *User) {
|
||||
s.mu.Lock()
|
||||
user := userWithQuota{
|
||||
User: api.User{ID: u.ID, Name: u.Username, Email: u.addresses[0].email},
|
||||
MaxSpace: DefaultMaxSpace,
|
||||
}
|
||||
for i, key := range u.keys {
|
||||
user.Keys = append(user.Keys, api.UserKey{
|
||||
ID: key.id,
|
||||
Version: 3,
|
||||
PrivateKey: key.armored,
|
||||
Primary: boolInt(i == len(u.keys)-1),
|
||||
Active: 1,
|
||||
})
|
||||
}
|
||||
if u.drive != nil {
|
||||
user.UsedSpace = u.drive.usedSpace()
|
||||
user.ProductUsedSpace.Drive = user.UsedSpace
|
||||
}
|
||||
s.mu.Unlock()
|
||||
writeJSON(w, http.StatusOK, &struct {
|
||||
Code int
|
||||
User userWithQuota
|
||||
}{Code: api.CodeOK, User: user})
|
||||
}
|
||||
|
||||
// handleAddresses returns the user's addresses with their keys.
|
||||
func (s *Server) handleAddresses(w http.ResponseWriter, r *http.Request, u *User) {
|
||||
s.mu.Lock()
|
||||
resp := &api.AddressesResponse{Code: api.CodeOK}
|
||||
for i, addr := range u.addresses {
|
||||
out := api.Address{ID: addr.id, Email: addr.email, Status: 1, Type: 1, Priority: i + 1}
|
||||
for j, key := range addr.keys {
|
||||
out.Keys = append(out.Keys, api.AddressKey{
|
||||
ID: key.id,
|
||||
Version: 3,
|
||||
PrivateKey: key.armored,
|
||||
Token: key.token,
|
||||
Signature: key.signature,
|
||||
Primary: boolInt(j == 0),
|
||||
Active: 1,
|
||||
Flags: 3,
|
||||
})
|
||||
}
|
||||
resp.Addresses = append(resp.Addresses, out)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// handlePublicKeys returns the public keys of the address in the Email
|
||||
// query parameter, or HTTP 422 code 33102 if no user has it.
|
||||
func (s *Server) handlePublicKeys(w http.ResponseWriter, r *http.Request, _ *User) {
|
||||
email := r.URL.Query().Get("Email")
|
||||
if email == "" {
|
||||
writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: no Email")
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
var addr *address
|
||||
if owner := s.keysAs[email]; owner != nil {
|
||||
addr = owner.addresses[0]
|
||||
}
|
||||
for _, u := range s.users {
|
||||
if addr != nil {
|
||||
break
|
||||
}
|
||||
addr = u.addressByEmailLocked(email)
|
||||
}
|
||||
var keys []*addressKey
|
||||
if addr != nil {
|
||||
keys = addr.keys
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if addr == nil {
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeAddressMissing, "protontest: address does not exist")
|
||||
return
|
||||
}
|
||||
resp := &api.PublicKeysResponse{Code: api.CodeOK}
|
||||
for i, key := range keys {
|
||||
pub, err := key.key.GetArmoredPublicKey()
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, 0, "protontest: public key: "+err.Error())
|
||||
return
|
||||
}
|
||||
resp.Address.Keys = append(resp.Address.Keys, api.PublicKey{PublicKey: pub, Primary: boolInt(i == 0), Flags: 3})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
@@ -0,0 +1,555 @@
|
||||
package protontest
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/ProtonMail/go-srp"
|
||||
"github.com/pquerna/otp/totp"
|
||||
"github.com/rclone/rclone/backend/protondrive/api"
|
||||
)
|
||||
|
||||
// signedModulus is a 2048-bit SRP modulus signed by Proton's modulus
|
||||
// key, from go-srp's tests.
|
||||
const signedModulus = `-----BEGIN PGP SIGNED MESSAGE-----
|
||||
Hash: SHA256
|
||||
|
||||
W2z5HBi8RvsfYzZTS7qBaUxxPhsfHJFZpu3Kd6s1JafNrCCH9rfvPLrfuqocxWPgWDH2R8neK7PkNvjxto9TStuY5z7jAzWRvFWN9cQhAKkdWgy0JY6ywVn22+HFpF4cYesHrqFIKUPDMSSIlWjBVmEJZ/MusD44ZT29xcPrOqeZvwtCffKtGAIjLYPZIEbZKnDM1Dm3q2K/xS5h+xdhjnndhsrkwm9U9oyA2wxzSXFL+pdfj2fOdRwuR5nW0J2NFrq3kJjkRmpO/Genq1UW+TEknIWAb6VzJJJA244K/H8cnSx2+nSNZO3bbo6Ys228ruV9A8m6DhxmS+bihN3ttQ==
|
||||
-----BEGIN PGP SIGNATURE-----
|
||||
Version: ProtonMail
|
||||
Comment: https://protonmail.com
|
||||
|
||||
wl4EARYIABAFAlwB1j0JEDUFhcTpUY8mAAD8CgEAnsFnF4cF0uSHKkXa1GIa
|
||||
GO86yMV4zDZEZcDSJo0fgr8A/AlupGN9EdHlsrZLmTA1vhIx+rOgxdEff28N
|
||||
kvNM7qIK
|
||||
=q6vu
|
||||
-----END PGP SIGNATURE-----`
|
||||
|
||||
// srpBits is the bit length of the SRP modulus.
|
||||
const srpBits = 2048
|
||||
|
||||
// forkClientID is the client ID rclone's sign-in URL must carry.
|
||||
const forkClientID = "external-drive"
|
||||
|
||||
// User is an account on the fake server.
|
||||
type User struct {
|
||||
ID string
|
||||
Username string
|
||||
Password string // login password, checked with SRP
|
||||
MailboxPassword string // derives the key password
|
||||
KeySalt string // base64 salt of the primary user key's password
|
||||
|
||||
srv *Server
|
||||
srpSalt []byte
|
||||
|
||||
// Guarded by srv.mu once the user is added.
|
||||
keyPassword string
|
||||
keys []*userKey // the primary key is last
|
||||
addresses []*address // the primary address is first
|
||||
drive *drive // nil until the user has a volume
|
||||
|
||||
verifierOnce sync.Once
|
||||
verifier []byte
|
||||
verifierErr error
|
||||
|
||||
// Guarded by srv.mu.
|
||||
totpSecret string
|
||||
captcha bool
|
||||
corruptProof bool
|
||||
}
|
||||
|
||||
// srpVerifier returns the SRP verifier of u's login password, computing
|
||||
// it on first use since it costs a bcrypt hash.
|
||||
func (u *User) srpVerifier() ([]byte, error) {
|
||||
u.verifierOnce.Do(func() {
|
||||
var auth *srp.Auth
|
||||
auth, u.verifierErr = srp.NewAuthForVerifier([]byte(u.Password), signedModulus, u.srpSalt)
|
||||
if u.verifierErr == nil {
|
||||
u.verifier, u.verifierErr = auth.GenerateVerifier(srpBits)
|
||||
}
|
||||
})
|
||||
return u.verifier, u.verifierErr
|
||||
}
|
||||
|
||||
// EnableTOTP turns on TOTP two-factor authentication for u and returns
|
||||
// the base32 secret to generate codes from.
|
||||
func (u *User) EnableTOTP() (secret string) {
|
||||
key, err := totp.Generate(totp.GenerateOpts{Issuer: "protontest", AccountName: u.Username})
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("protontest: generate TOTP secret: %v", err))
|
||||
}
|
||||
u.srv.mu.Lock()
|
||||
defer u.srv.mu.Unlock()
|
||||
u.totpSecret = key.Secret()
|
||||
return u.totpSecret
|
||||
}
|
||||
|
||||
// srpLogin is an SRP challenge issued by POST /core/v4/auth/info.
|
||||
type srpLogin struct {
|
||||
user *User
|
||||
server *srp.Server
|
||||
}
|
||||
|
||||
// fork is a session fork requested by GET /auth/v4/sessions/forks.
|
||||
type fork struct {
|
||||
userCode string
|
||||
key []byte // encryption key from the sign-in URL, once approved
|
||||
approved *session // child session, once approved
|
||||
}
|
||||
|
||||
// Session holds the tokens of a signed in session.
|
||||
type Session struct {
|
||||
UID string
|
||||
AccessToken string
|
||||
RefreshToken string
|
||||
}
|
||||
|
||||
// session is the server side state of a Session.
|
||||
type session struct {
|
||||
Session
|
||||
user *User
|
||||
expired bool // access token no longer accepted
|
||||
locked bool // waiting for the second factor
|
||||
}
|
||||
|
||||
// randomBytes returns n random bytes.
|
||||
func randomBytes(n int) []byte {
|
||||
b := make([]byte, n)
|
||||
_, _ = rand.Read(b)
|
||||
return b
|
||||
}
|
||||
|
||||
// randomID returns a random hex string.
|
||||
func randomID() string {
|
||||
return hex.EncodeToString(randomBytes(16))
|
||||
}
|
||||
|
||||
// registerAuth registers the session routes.
|
||||
func (s *Server) registerAuth() {
|
||||
s.handle("POST", "/auth/v4/refresh", s.handleRefresh)
|
||||
s.handle("POST", "/core/v4/auth/info", s.handleAuthInfo)
|
||||
s.handle("POST", "/core/v4/auth", s.handleLogin)
|
||||
s.handleSession("POST", "/core/v4/auth/2fa", s.handle2FA)
|
||||
s.handleSession("DELETE", "/core/v4/auth", s.handleLogout)
|
||||
s.handleAuth("GET", "/core/v4/keys/salts", s.handleKeySalts)
|
||||
s.handle("GET", "/auth/v4/sessions/forks", s.handleForkInit)
|
||||
s.handle("GET", "/auth/v4/sessions/forks/{selector}", s.handleForkStatus)
|
||||
s.handleAuth("GET", "/tests/auth", func(w http.ResponseWriter, r *http.Request, u *User) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"Code": api.CodeOK, "UserID": u.ID})
|
||||
})
|
||||
s.handleAuth("POST", "/tests/echo", func(w http.ResponseWriter, r *http.Request, u *User) {
|
||||
var body struct{ Echo string }
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: "+err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"Code": api.CodeOK, "Echo": body.Echo})
|
||||
})
|
||||
}
|
||||
|
||||
// AddUser creates an account whose mailbox password is its password.
|
||||
func (s *Server) AddUser(username, password string) *User {
|
||||
return s.AddTwoPasswordUser(username, password, password)
|
||||
}
|
||||
|
||||
// AddTwoPasswordUser creates an account which signs in with password
|
||||
// and unlocks its keys with mailboxPassword.
|
||||
//
|
||||
// The account has a user key and one address, username itself if it
|
||||
// contains "@" or else username@proton.test, with an address key. Its
|
||||
// drive has a volume, a main share and an empty root folder.
|
||||
func (s *Server) AddTwoPasswordUser(username, password, mailboxPassword string) *User {
|
||||
u := newUser(s, username, password, mailboxPassword)
|
||||
u.drive = s.newDrive(u.addresses[0])
|
||||
s.addUser(u)
|
||||
return u
|
||||
}
|
||||
|
||||
// AddUserWithoutDrive creates an account like AddUser but without a
|
||||
// volume, as a brand-new Proton account is: its my-files route answers
|
||||
// HTTP 422 code 2501 until a client creates the volume.
|
||||
func (s *Server) AddUserWithoutDrive(username, password string) *User {
|
||||
u := newUser(s, username, password, password)
|
||||
s.addUser(u)
|
||||
return u
|
||||
}
|
||||
|
||||
// newUser returns an account with a user key and one address, not yet
|
||||
// added to s.
|
||||
func newUser(s *Server, username, password, mailboxPassword string) *User {
|
||||
u := &User{
|
||||
ID: randomID(),
|
||||
Username: username,
|
||||
Password: password,
|
||||
MailboxPassword: mailboxPassword,
|
||||
srv: s,
|
||||
srpSalt: randomBytes(10),
|
||||
}
|
||||
key := newUserKey(u)
|
||||
u.keys = []*userKey{key}
|
||||
u.KeySalt, u.keyPassword = key.salt, key.keyPassword
|
||||
email := username
|
||||
if !strings.Contains(email, "@") {
|
||||
email += "@proton.test"
|
||||
}
|
||||
u.addresses = []*address{newAddress(email, key)}
|
||||
return u
|
||||
}
|
||||
|
||||
// addUser adds u to s.
|
||||
func (s *Server) addUser(u *User) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.users[u.Username] = u
|
||||
}
|
||||
|
||||
// RequireCaptcha makes password sign-in for u fail with HTTP 422 code
|
||||
// 9001, as when Proton asks for human verification.
|
||||
func (s *Server) RequireCaptcha(u *User) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
u.captcha = true
|
||||
}
|
||||
|
||||
// CorruptServerProof makes password sign-in for u return a server
|
||||
// proof with one byte changed, as an impostor server would.
|
||||
func (s *Server) CorruptServerProof(u *User) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
u.corruptProof = true
|
||||
}
|
||||
|
||||
// NewSession signs u in and returns the new session's tokens.
|
||||
func (s *Server) NewSession(u *User) Session {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.newSessionLocked(u, false).Session
|
||||
}
|
||||
|
||||
// newSessionLocked creates a session for u. s.mu must be held.
|
||||
func (s *Server) newSessionLocked(u *User, locked bool) *session {
|
||||
sess := &session{
|
||||
Session: Session{UID: randomID(), AccessToken: s.newSecretLocked(SessionToken), RefreshToken: s.newSecretLocked(SessionToken)},
|
||||
user: u,
|
||||
locked: locked,
|
||||
}
|
||||
s.sessions[sess.UID] = sess
|
||||
return sess
|
||||
}
|
||||
|
||||
// ApproveFork completes the session fork whose sign-in URL is
|
||||
// signInURL as if u had signed in on Proton's page: the next poll of
|
||||
// the fork returns a new session for u and u's key password encrypted
|
||||
// with the key from the URL.
|
||||
func (s *Server) ApproveFork(signInURL string, u *User) error {
|
||||
parsed, err := url.Parse(signInURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("protontest: parse sign-in URL: %w", err)
|
||||
}
|
||||
payload, ok := strings.CutPrefix(parsed.Fragment, "payload=")
|
||||
parts := strings.Split(payload, ":")
|
||||
if !ok || len(parts) != 4 || parts[0] != "0" || parts[3] != forkClientID {
|
||||
return fmt.Errorf("protontest: bad sign-in URL payload %q", payload)
|
||||
}
|
||||
key, err := base64.StdEncoding.DecodeString(parts[2])
|
||||
if err != nil || len(key) != 32 {
|
||||
return fmt.Errorf("protontest: bad key in sign-in URL payload %q", payload)
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for _, f := range s.forks {
|
||||
if f.userCode == parts[1] {
|
||||
f.key = key
|
||||
f.approved = s.newSessionLocked(u, false)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("protontest: no fork with user code %q", parts[1])
|
||||
}
|
||||
|
||||
// ExpireAccessToken makes the access token of session uid return 401
|
||||
// until the session is refreshed.
|
||||
func (s *Server) ExpireAccessToken(uid string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if sess := s.sessions[uid]; sess != nil {
|
||||
sess.expired = true
|
||||
}
|
||||
}
|
||||
|
||||
// RevokeSession ends session uid, so neither its access token nor its
|
||||
// refresh token is accepted.
|
||||
func (s *Server) RevokeSession(uid string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
delete(s.sessions, uid)
|
||||
}
|
||||
|
||||
// handleAuth registers h for an authenticated route. Requests without
|
||||
// a valid x-pm-uid and bearer access token get HTTP 401, and requests
|
||||
// from a session waiting for its second factor get HTTP 403.
|
||||
func (s *Server) handleAuth(method, pattern string, h func(w http.ResponseWriter, r *http.Request, u *User)) {
|
||||
s.handleSession(method, pattern, func(w http.ResponseWriter, r *http.Request, sess *session) {
|
||||
s.mu.Lock()
|
||||
locked := sess.locked
|
||||
s.mu.Unlock()
|
||||
if locked {
|
||||
writeError(w, http.StatusForbidden, 0, "protontest: second factor required")
|
||||
return
|
||||
}
|
||||
h(w, r, sess.user)
|
||||
})
|
||||
}
|
||||
|
||||
// handleSession registers h for a route which needs a session, which
|
||||
// may be waiting for its second factor. Requests without a valid
|
||||
// x-pm-uid and bearer access token get HTTP 401.
|
||||
func (s *Server) handleSession(method, pattern string, h func(w http.ResponseWriter, r *http.Request, sess *session)) {
|
||||
s.handle(method, pattern, func(w http.ResponseWriter, r *http.Request) {
|
||||
token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
s.mu.Lock()
|
||||
sess := s.sessions[r.Header.Get("x-pm-uid")]
|
||||
valid := ok && sess != nil && !sess.expired && sess.AccessToken == token
|
||||
s.mu.Unlock()
|
||||
if !valid {
|
||||
writeError(w, http.StatusUnauthorized, 401, "protontest: invalid access token")
|
||||
return
|
||||
}
|
||||
h(w, r, sess)
|
||||
})
|
||||
}
|
||||
|
||||
// handleRefresh rotates the tokens of the session named by x-pm-uid.
|
||||
// Refresh tokens are single use.
|
||||
func (s *Server) handleRefresh(w http.ResponseWriter, r *http.Request) {
|
||||
var req api.AuthRefreshRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.ResponseType != "token" || req.GrantType != "refresh_token" {
|
||||
writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: bad refresh request")
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
sess := s.sessions[r.Header.Get("x-pm-uid")]
|
||||
if sess == nil || req.RefreshToken == "" || sess.RefreshToken != req.RefreshToken {
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeRefreshTokenInvalid, "protontest: invalid refresh token")
|
||||
return
|
||||
}
|
||||
sess.AccessToken = s.newSecretLocked(SessionToken)
|
||||
sess.RefreshToken = s.newSecretLocked(SessionToken)
|
||||
sess.expired = false
|
||||
writeJSON(w, http.StatusOK, &api.AuthRefreshResponse{
|
||||
Code: api.CodeOK,
|
||||
UID: sess.UID,
|
||||
AccessToken: sess.AccessToken,
|
||||
RefreshToken: sess.RefreshToken,
|
||||
})
|
||||
}
|
||||
|
||||
// handleAuthInfo issues an SRP challenge for the user named in the
|
||||
// request.
|
||||
func (s *Server) handleAuthInfo(w http.ResponseWriter, r *http.Request) {
|
||||
var req api.AuthInfoRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Intent != "Proton" {
|
||||
writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: bad auth info request")
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
u := s.users[req.Username]
|
||||
s.mu.Unlock()
|
||||
if u == nil {
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodePasswordWrong, "protontest: unknown user")
|
||||
return
|
||||
}
|
||||
verifier, err := u.srpVerifier()
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, 0, "protontest: SRP verifier: "+err.Error())
|
||||
return
|
||||
}
|
||||
server, err := srp.NewServerFromSigned(signedModulus, verifier, srpBits)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, 0, "protontest: SRP server: "+err.Error())
|
||||
return
|
||||
}
|
||||
challenge, err := server.GenerateChallenge()
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, 0, "protontest: SRP challenge: "+err.Error())
|
||||
return
|
||||
}
|
||||
srpSession := randomID()
|
||||
s.mu.Lock()
|
||||
s.srp[srpSession] = &srpLogin{user: u, server: server}
|
||||
s.mu.Unlock()
|
||||
writeJSON(w, http.StatusOK, &api.AuthInfoResponse{
|
||||
Code: api.CodeOK,
|
||||
Version: 4,
|
||||
Modulus: signedModulus,
|
||||
ServerEphemeral: base64.StdEncoding.EncodeToString(challenge),
|
||||
Salt: base64.StdEncoding.EncodeToString(u.srpSalt),
|
||||
SRPSession: srpSession,
|
||||
Username: u.Username,
|
||||
})
|
||||
}
|
||||
|
||||
// handleLogin checks the SRP proof for a challenge and creates a
|
||||
// session, locked until the second factor if the user has TOTP.
|
||||
// Challenges are single use.
|
||||
func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
var req api.AuthRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: bad auth request")
|
||||
return
|
||||
}
|
||||
ephemeral, err1 := base64.StdEncoding.DecodeString(req.ClientEphemeral)
|
||||
proof, err2 := base64.StdEncoding.DecodeString(req.ClientProof)
|
||||
if err := errors.Join(err1, err2); err != nil {
|
||||
writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: bad auth request: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
login := s.srp[req.SRPSession]
|
||||
delete(s.srp, req.SRPSession)
|
||||
if login == nil || login.user.Username != req.Username {
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidValue, "protontest: unknown SRP session")
|
||||
return
|
||||
}
|
||||
u := login.user
|
||||
if u.captcha {
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeHumanVerification, "protontest: human verification required")
|
||||
return
|
||||
}
|
||||
serverProof, err := login.server.VerifyProofs(ephemeral, proof)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodePasswordWrong, "protontest: incorrect login credentials")
|
||||
return
|
||||
}
|
||||
if u.corruptProof {
|
||||
serverProof[0] ^= 1
|
||||
}
|
||||
resp := &api.AuthResponse{
|
||||
Code: api.CodeOK,
|
||||
UserID: u.ID,
|
||||
TokenType: "Bearer",
|
||||
ServerProof: base64.StdEncoding.EncodeToString(serverProof),
|
||||
Scopes: []string{"full"},
|
||||
PasswordMode: api.PasswordModeOne,
|
||||
}
|
||||
if u.MailboxPassword != u.Password {
|
||||
resp.PasswordMode = api.PasswordModeTwo
|
||||
}
|
||||
if u.totpSecret != "" {
|
||||
resp.TwoFA.Enabled = api.TwoFATOTP
|
||||
resp.Scopes = []string{"twofactor"}
|
||||
}
|
||||
sess := s.newSessionLocked(u, u.totpSecret != "")
|
||||
resp.UID, resp.AccessToken, resp.RefreshToken = sess.UID, sess.AccessToken, sess.RefreshToken
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// handle2FA unlocks a session with a TOTP code.
|
||||
func (s *Server) handle2FA(w http.ResponseWriter, r *http.Request, sess *session) {
|
||||
var req api.Auth2FARequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: bad 2FA request")
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
secret := sess.user.totpSecret
|
||||
if secret == "" || !totp.Validate(req.TwoFactorCode, secret) {
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidValue, "protontest: incorrect 2FA code")
|
||||
return
|
||||
}
|
||||
sess.locked = false
|
||||
writeJSON(w, http.StatusOK, map[string]any{"Code": api.CodeOK, "Scopes": []string{"full"}})
|
||||
}
|
||||
|
||||
// handleLogout ends the session.
|
||||
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request, sess *session) {
|
||||
s.mu.Lock()
|
||||
delete(s.sessions, sess.UID)
|
||||
s.mu.Unlock()
|
||||
writeJSON(w, http.StatusOK, map[string]any{"Code": api.CodeOK})
|
||||
}
|
||||
|
||||
// handleKeySalts returns the password salt of each user key.
|
||||
func (s *Server) handleKeySalts(w http.ResponseWriter, r *http.Request, u *User) {
|
||||
resp := &api.KeySaltsResponse{Code: api.CodeOK}
|
||||
s.mu.Lock()
|
||||
for _, key := range u.keys {
|
||||
resp.KeySalts = append(resp.KeySalts, api.KeySalt{ID: key.id, KeySalt: key.salt})
|
||||
}
|
||||
s.mu.Unlock()
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// handleForkInit starts a session fork for a client to sign in with.
|
||||
func (s *Server) handleForkInit(w http.ResponseWriter, r *http.Request) {
|
||||
f := &fork{userCode: strings.ToUpper(hex.EncodeToString(randomBytes(4)))}
|
||||
s.mu.Lock()
|
||||
selector := s.newSecretLocked(ForkSelector)
|
||||
s.forks[selector] = f
|
||||
s.mu.Unlock()
|
||||
writeJSON(w, http.StatusOK, &api.ForkInitResponse{Code: api.CodeOK, Selector: selector, UserCode: f.userCode})
|
||||
}
|
||||
|
||||
// handleForkStatus returns the child session of an approved fork, once,
|
||||
// or HTTP 422 while the fork is waiting for approval.
|
||||
func (s *Server) handleForkStatus(w http.ResponseWriter, r *http.Request) {
|
||||
selector := r.PathValue("selector")
|
||||
s.mu.Lock()
|
||||
f := s.forks[selector]
|
||||
if f == nil || f.approved == nil {
|
||||
s.mu.Unlock()
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidValue, "protontest: fork not ready")
|
||||
return
|
||||
}
|
||||
delete(s.forks, selector)
|
||||
sess := f.approved.Session
|
||||
user := f.approved.user
|
||||
s.mu.Unlock()
|
||||
|
||||
payload, err := sealForkPayload(f.key, user.KeyPassword())
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, 0, "protontest: fork payload: "+err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, &api.ForkStatusResponse{
|
||||
Code: api.CodeOK,
|
||||
Payload: payload,
|
||||
UID: sess.UID,
|
||||
AccessToken: sess.AccessToken,
|
||||
RefreshToken: sess.RefreshToken,
|
||||
})
|
||||
}
|
||||
|
||||
// sealForkPayload encrypts keyPassword for a fork as Proton's sign-in
|
||||
// page does: base64 of nonce, AES-256-GCM ciphertext and tag, with
|
||||
// additional data "fork".
|
||||
func sealForkPayload(key []byte, keyPassword string) (string, error) {
|
||||
plain, err := json.Marshal(map[string]string{"keyPassword": keyPassword})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
nonce := randomBytes(gcm.NonceSize())
|
||||
return base64.StdEncoding.EncodeToString(gcm.Seal(nonce, nonce, plain, []byte("fork"))), nil
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package protontest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/ProtonMail/go-srp"
|
||||
"github.com/pquerna/otp/totp"
|
||||
"github.com/rclone/rclone/backend/protondrive/api"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// refresh calls POST /auth/v4/refresh for uid with refreshToken.
|
||||
func refresh(t *testing.T, s *Server, uid, refreshToken string) (*http.Response, []byte) {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(&api.AuthRefreshRequest{ResponseType: "token", GrantType: "refresh_token", RefreshToken: refreshToken})
|
||||
require.NoError(t, err)
|
||||
req, err := http.NewRequest("POST", s.URL()+"/auth/v4/refresh", bytes.NewReader(body))
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("x-pm-appversion", testAppVersion)
|
||||
req.Header.Set("x-pm-uid", uid)
|
||||
resp, err := s.Client().Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
out, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
return resp, out
|
||||
}
|
||||
|
||||
func authed(t *testing.T, s *Server, sess Session) int {
|
||||
t.Helper()
|
||||
resp, _ := do(t, s, "GET", "/tests/auth", map[string]string{
|
||||
"x-pm-appversion": testAppVersion,
|
||||
"x-pm-uid": sess.UID,
|
||||
"Authorization": "Bearer " + sess.AccessToken,
|
||||
})
|
||||
return resp.StatusCode
|
||||
}
|
||||
|
||||
func TestAuth(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
assert.Equal(t, "pass", u.MailboxPassword)
|
||||
sess := s.NewSession(u)
|
||||
|
||||
assert.Equal(t, http.StatusOK, authed(t, s, sess))
|
||||
assert.Equal(t, http.StatusUnauthorized, authed(t, s, Session{UID: sess.UID, AccessToken: "wrong"}))
|
||||
assert.Equal(t, http.StatusUnauthorized, authed(t, s, Session{UID: "unknown", AccessToken: sess.AccessToken}))
|
||||
|
||||
s.ExpireAccessToken(sess.UID)
|
||||
assert.Equal(t, http.StatusUnauthorized, authed(t, s, sess))
|
||||
|
||||
resp, body := refresh(t, s, sess.UID, sess.RefreshToken)
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, "body: %s", body)
|
||||
var out api.AuthRefreshResponse
|
||||
require.NoError(t, json.Unmarshal(body, &out))
|
||||
assert.Equal(t, sess.UID, out.UID)
|
||||
next := Session{UID: out.UID, AccessToken: out.AccessToken, RefreshToken: out.RefreshToken}
|
||||
assert.Equal(t, http.StatusOK, authed(t, s, next))
|
||||
assert.Equal(t, http.StatusUnauthorized, authed(t, s, sess), "old access token")
|
||||
|
||||
// Refresh tokens are single use.
|
||||
resp, body = refresh(t, s, sess.UID, sess.RefreshToken)
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, resp.StatusCode)
|
||||
assert.Equal(t, api.CodeRefreshTokenInvalid, decodeError(t, body).Code)
|
||||
|
||||
s.RevokeSession(sess.UID)
|
||||
assert.Equal(t, http.StatusUnauthorized, authed(t, s, next))
|
||||
resp, body = refresh(t, s, next.UID, next.RefreshToken)
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, resp.StatusCode)
|
||||
assert.Equal(t, api.CodeRefreshTokenInvalid, decodeError(t, body).Code)
|
||||
}
|
||||
|
||||
// postJSON sends in as JSON to path with the given extra headers and
|
||||
// decodes the response into out, returning the HTTP status.
|
||||
func postJSON(t *testing.T, s *Server, path string, header map[string]string, in, out any) int {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(in)
|
||||
require.NoError(t, err)
|
||||
req, err := http.NewRequest("POST", s.URL()+path, bytes.NewReader(body))
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("x-pm-appversion", testAppVersion)
|
||||
for k, v := range header {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
resp, err := s.Client().Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(out))
|
||||
return resp.StatusCode
|
||||
}
|
||||
|
||||
func TestLoginTOTPLocksSession(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
secret := u.EnableTOTP()
|
||||
|
||||
var info api.AuthInfoResponse
|
||||
require.Equal(t, http.StatusOK, postJSON(t, s, "/core/v4/auth/info", nil, &api.AuthInfoRequest{Intent: "Proton", Username: "user"}, &info))
|
||||
auth, err := srp.NewAuth(info.Version, "user", []byte("pass"), info.Salt, info.Modulus, info.ServerEphemeral)
|
||||
require.NoError(t, err)
|
||||
proofs, err := auth.GenerateProofs(srpBits)
|
||||
require.NoError(t, err)
|
||||
var out api.AuthResponse
|
||||
require.Equal(t, http.StatusOK, postJSON(t, s, "/core/v4/auth", nil, &api.AuthRequest{
|
||||
Username: "user",
|
||||
ClientEphemeral: base64.StdEncoding.EncodeToString(proofs.ClientEphemeral),
|
||||
ClientProof: base64.StdEncoding.EncodeToString(proofs.ClientProof),
|
||||
SRPSession: info.SRPSession,
|
||||
}, &out))
|
||||
assert.Equal(t, base64.StdEncoding.EncodeToString(proofs.ExpectedServerProof), out.ServerProof)
|
||||
assert.Equal(t, api.TwoFATOTP, out.TwoFA.Enabled)
|
||||
sess := Session{UID: out.UID, AccessToken: out.AccessToken, RefreshToken: out.RefreshToken}
|
||||
assert.Equal(t, http.StatusForbidden, authed(t, s, sess))
|
||||
|
||||
headers := map[string]string{"x-pm-uid": sess.UID, "Authorization": "Bearer " + sess.AccessToken}
|
||||
var res api.Error
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, postJSON(t, s, "/core/v4/auth/2fa", headers, &api.Auth2FARequest{TwoFactorCode: "000000x"}, &res))
|
||||
assert.Equal(t, http.StatusForbidden, authed(t, s, sess))
|
||||
|
||||
code, err := totp.GenerateCode(secret, time.Now())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, http.StatusOK, postJSON(t, s, "/core/v4/auth/2fa", headers, &api.Auth2FARequest{TwoFactorCode: code}, &res))
|
||||
assert.Equal(t, http.StatusOK, authed(t, s, sess))
|
||||
|
||||
// SRP challenges are single use.
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, postJSON(t, s, "/core/v4/auth", nil, &api.AuthRequest{
|
||||
Username: "user",
|
||||
ClientEphemeral: base64.StdEncoding.EncodeToString(proofs.ClientEphemeral),
|
||||
ClientProof: base64.StdEncoding.EncodeToString(proofs.ClientProof),
|
||||
SRPSession: info.SRPSession,
|
||||
}, &res))
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// Command protonfake serves a fake Proton Drive API for integration
|
||||
// tests.
|
||||
//
|
||||
// It prints the rclone config of a signed in user with a Drive volume
|
||||
// as key=value lines on stdout, then serves until interrupted.
|
||||
//
|
||||
// go run ./backend/protondrive/protontest/cmd/protonfake -addr 127.0.0.1:0
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"github.com/rclone/rclone/backend/protondrive/protontest"
|
||||
)
|
||||
|
||||
func main() {
|
||||
addr := flag.String("addr", "127.0.0.1:0", "address to listen on")
|
||||
flag.Parse()
|
||||
stop := make(chan struct{})
|
||||
sig := make(chan os.Signal, 1)
|
||||
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
|
||||
go func() {
|
||||
<-sig
|
||||
close(stop)
|
||||
}()
|
||||
if err := run(*addr, os.Stdout, stop); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "protonfake:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// run serves a fake server on addr until stop is closed, after writing
|
||||
// its endpoint and a fresh session's config to out.
|
||||
func run(addr string, out io.Writer, stop <-chan struct{}) error {
|
||||
srv, err := protontest.NewStandalone(addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer srv.Close()
|
||||
user := srv.AddUser("protonfake", "protonfake")
|
||||
sess := srv.NewSession(user)
|
||||
// The config holds the salted key password base64 encoded.
|
||||
keyPass := base64.StdEncoding.EncodeToString([]byte(user.KeyPassword()))
|
||||
// Events are polled every second, so tests see changes quickly.
|
||||
_, err = fmt.Fprintf(out, "endpoint=%s\nclient_uid=%s\nclient_access_token=%s\nclient_refresh_token=%s\nclient_salted_key_pass=%s\nevents_min_interval=1s\ntype=protondrive\n",
|
||||
srv.URL(), sess.UID, sess.AccessToken, sess.RefreshToken, keyPass)
|
||||
if err != nil {
|
||||
return fmt.Errorf("write config: %w", err)
|
||||
}
|
||||
<-stop
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestRun(t *testing.T) {
|
||||
pr, pw := io.Pipe()
|
||||
stop := make(chan struct{})
|
||||
var stopOnce sync.Once
|
||||
stopRun := func() { stopOnce.Do(func() { close(stop) }) }
|
||||
done := make(chan error, 1)
|
||||
finished := make(chan struct{})
|
||||
go func() {
|
||||
defer close(finished)
|
||||
err := run("127.0.0.1:0", pw, stop)
|
||||
_ = pw.Close()
|
||||
done <- err
|
||||
}()
|
||||
// However the test ends, run is stopped and waited for.
|
||||
t.Cleanup(func() {
|
||||
stopRun()
|
||||
_ = pr.Close()
|
||||
<-finished
|
||||
})
|
||||
|
||||
wantKeys := []string{"endpoint", "client_uid", "client_access_token", "client_refresh_token", "client_salted_key_pass", "events_min_interval", "type"}
|
||||
values := make(map[string]string)
|
||||
lines := bufio.NewScanner(pr)
|
||||
for _, key := range wantKeys {
|
||||
require.True(t, lines.Scan(), "missing line for %s", key)
|
||||
k, v, ok := strings.Cut(lines.Text(), "=")
|
||||
require.True(t, ok, "line %q is not key=value", lines.Text())
|
||||
require.Equal(t, key, k)
|
||||
require.NotEmpty(t, v, key)
|
||||
values[k] = v
|
||||
}
|
||||
assert.Equal(t, "protondrive", values["type"])
|
||||
assert.Equal(t, "1s", values["events_min_interval"])
|
||||
assert.False(t, strings.HasSuffix(values["endpoint"], ":0"), "endpoint %q must carry the bound port", values["endpoint"])
|
||||
keyPass, err := base64.StdEncoding.DecodeString(values["client_salted_key_pass"])
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, keyPass, 31, "a key password is the last 31 characters of a bcrypt hash")
|
||||
|
||||
req, err := http.NewRequest("GET", values["endpoint"]+"/core/v4/users", nil)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("x-pm-appversion", "external-drive-rclone@1.0.0-stable")
|
||||
req.Header.Set("x-pm-uid", values["client_uid"])
|
||||
req.Header.Set("Authorization", "Bearer "+values["client_access_token"])
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
_ = resp.Body.Close()
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
stopRun()
|
||||
extra := lines.Scan()
|
||||
assert.False(t, extra, "unexpected output %q", lines.Text())
|
||||
require.NoError(t, <-done)
|
||||
_, err = http.Get(values["endpoint"] + "/tests/ping")
|
||||
assert.Error(t, err, "server still answering after stop")
|
||||
}
|
||||
|
||||
func TestRunBadAddress(t *testing.T) {
|
||||
var out strings.Builder
|
||||
err := run("not an address", &out, make(chan struct{}))
|
||||
assert.Error(t, err)
|
||||
assert.Empty(t, out.String())
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
package protontest
|
||||
|
||||
// The Drive cryptography of the fake, written from Proton's Drive SDK
|
||||
// (client/js/src/crypto/driveCrypto.ts and the nodes, shares and upload
|
||||
// crypto services) independently of the protondrive backend, so a bug
|
||||
// in one is unlikely to be mirrored in the other.
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/ProtonMail/go-crypto/openpgp/packet"
|
||||
"github.com/ProtonMail/gopenpgp/v3/constants"
|
||||
"github.com/ProtonMail/gopenpgp/v3/crypto"
|
||||
"github.com/ProtonMail/gopenpgp/v3/profile"
|
||||
)
|
||||
|
||||
// driveKeyName is the user ID of every node and share key, as the SDK
|
||||
// generates them.
|
||||
const driveKeyName = "Drive key"
|
||||
|
||||
// aeadPGP returns a handle whose keys advertise SEIPDv2 and whose
|
||||
// session-key encryption uses AES-256 GCM, as the SDK's file content
|
||||
// does (openpgp.js aeadProtect with Proton's GCM preference).
|
||||
//
|
||||
// Everything that is not file content goes through encryptArmored,
|
||||
// which never produces SEIPDv2 whatever the recipient advertises.
|
||||
func aeadPGP() *crypto.PGPHandle {
|
||||
p := profile.Default()
|
||||
p.AeadEncryption = &packet.AEADConfig{DefaultMode: packet.AEADModeGCM}
|
||||
return crypto.PGPWithProfile(p)
|
||||
}
|
||||
|
||||
// signTime returns when the fake generates keys and makes signatures: a
|
||||
// day before the local clock, so that what it writes is valid at the
|
||||
// server clock whatever skew within a day a test sets.
|
||||
func signTime() int64 {
|
||||
return time.Now().Add(-24 * time.Hour).Unix()
|
||||
}
|
||||
|
||||
// signTimeOf returns when the fake signs with signer: signTime, or
|
||||
// signer's creation time if later, as for a key a test supplied which
|
||||
// was generated less than a day ago.
|
||||
func signTimeOf(signer *crypto.Key) int64 {
|
||||
return max(signTime(), signer.GetEntity().PrimaryKey.CreationTime.Unix())
|
||||
}
|
||||
|
||||
// newPassphrase returns base64 of 32 random bytes, the SDK's
|
||||
// generatePassphrase.
|
||||
func newPassphrase() []byte {
|
||||
return []byte(base64.StdEncoding.EncodeToString(randomBytes(32)))
|
||||
}
|
||||
|
||||
// lockedKey is a generated key with its passphrase and armored locked
|
||||
// form.
|
||||
type lockedKey struct {
|
||||
key *crypto.Key
|
||||
passphrase []byte
|
||||
armored string
|
||||
}
|
||||
|
||||
// newDriveKey generates a node or share key locked with a new
|
||||
// passphrase. aead makes the key advertise SEIPDv2, as file node keys
|
||||
// do; folder and share keys do not.
|
||||
func newDriveKey(aead bool) lockedKey {
|
||||
pgp := crypto.PGP()
|
||||
if aead {
|
||||
pgp = aeadPGP()
|
||||
}
|
||||
key, err := pgp.KeyGeneration().AddUserId(driveKeyName, "").GenerationTime(signTime()).New().GenerateKey()
|
||||
mustCrypto("generate drive key", err)
|
||||
passphrase := newPassphrase()
|
||||
return lockedKey{key: key, passphrase: passphrase, armored: lockKey(key, passphrase)}
|
||||
}
|
||||
|
||||
// sealedPassphrase is a node or share passphrase as the server stores it.
|
||||
type sealedPassphrase struct {
|
||||
armored string // encrypted to the parent key
|
||||
signature string // armored detached signature of the plaintext
|
||||
}
|
||||
|
||||
// sealPassphrase encrypts passphrase to parent without AEAD and signs it
|
||||
// with signer in a detached signature, the SDK's encryptPassphrase.
|
||||
func sealPassphrase(passphrase []byte, parent, signer *crypto.Key) sealedPassphrase {
|
||||
return sealedPassphrase{
|
||||
armored: encryptArmored(passphrase, parent, nil, false),
|
||||
signature: signArmored(passphrase, signer),
|
||||
}
|
||||
}
|
||||
|
||||
// encryptArmored encrypts data to key without AEAD, signed inline by
|
||||
// signer if not nil, compressed if compress is set.
|
||||
//
|
||||
// Encrypting to recipients picks SEIPDv2 whenever every recipient key
|
||||
// advertises it, as file node keys do, so the session key is generated
|
||||
// and wrapped separately: the SDK's ignoreSEIPDv2FeatureFlag.
|
||||
func encryptArmored(data []byte, key, signer *crypto.Key, compress bool) string {
|
||||
sk, err := crypto.GenerateSessionKeyAlgo(constants.AES256)
|
||||
mustCrypto("session key", err)
|
||||
kh, err := crypto.PGP().Encryption().Recipient(key).New()
|
||||
mustCrypto("encrypt session key", err)
|
||||
keyPacket, err := kh.EncryptSessionKey(sk)
|
||||
mustCrypto("encrypt session key", err)
|
||||
b := crypto.PGP().Encryption().SessionKey(sk)
|
||||
if signer != nil {
|
||||
b = b.SigningKey(signer).SignTime(signTimeOf(signer))
|
||||
}
|
||||
if compress {
|
||||
b = b.Compress()
|
||||
}
|
||||
eh, err := b.New()
|
||||
mustCrypto("encrypt", err)
|
||||
msg, err := eh.Encrypt(data)
|
||||
mustCrypto("encrypt", err)
|
||||
armored, err := crypto.NewPGPMessage(append(keyPacket, msg.DataPacket...)).Armor()
|
||||
mustCrypto("armor message", err)
|
||||
return armored
|
||||
}
|
||||
|
||||
// signArmored returns an armored detached signature of data by signer.
|
||||
func signArmored(data []byte, signer *crypto.Key) string {
|
||||
sh, err := crypto.PGP().Sign().SigningKey(signer).Detached().SignTime(signTimeOf(signer)).New()
|
||||
mustCrypto("sign", err)
|
||||
sig, err := sh.Sign(data, crypto.Armor)
|
||||
mustCrypto("sign", err)
|
||||
return string(sig)
|
||||
}
|
||||
|
||||
// signBinary returns a binary detached signature of data by signer.
|
||||
func signBinary(data []byte, signer *crypto.Key) []byte {
|
||||
sh, err := crypto.PGP().Sign().SigningKey(signer).Detached().SignTime(signTimeOf(signer)).New()
|
||||
mustCrypto("sign", err)
|
||||
sig, err := sh.Sign(data, crypto.Bytes)
|
||||
mustCrypto("sign", err)
|
||||
return sig
|
||||
}
|
||||
|
||||
// newHashKey returns a new folder hash key and its armored form,
|
||||
// encrypted to and signed by nodeKey, the SDK's generateHashKey.
|
||||
func newHashKey(nodeKey *crypto.Key) (hashKey []byte, armored string) {
|
||||
hashKey = newPassphrase()
|
||||
return hashKey, encryptArmored(hashKey, nodeKey, nodeKey, false)
|
||||
}
|
||||
|
||||
// lookupHash returns the hex HMAC-SHA256 of name keyed with the parent
|
||||
// folder's hash key, the SDK's generateLookupHash.
|
||||
func lookupHash(parentHashKey []byte, name string) string {
|
||||
mac := hmac.New(sha256.New, parentHashKey)
|
||||
mac.Write([]byte(name))
|
||||
return hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// contentKey is a file's content session key with its key packet.
|
||||
type contentKey struct {
|
||||
sk *crypto.SessionKey
|
||||
packet string // base64 PKESK to the node key
|
||||
signature string // armored detached signature of the session key by the node key
|
||||
aead bool
|
||||
}
|
||||
|
||||
// newContentKey generates a content session key for nodeKey, the SDK's
|
||||
// generateContentKey. With aead the key packet is a v6 PKESK and blocks
|
||||
// are SEIPDv2; without, the legacy v3 PKESK and SEIPDv1.
|
||||
func newContentKey(nodeKey *crypto.Key, aead bool) contentKey {
|
||||
token := randomBytes(32)
|
||||
sk := crypto.NewSessionKeyFromTokenWithAead(token, constants.AES256, aead)
|
||||
eh, err := crypto.PGP().Encryption().Recipient(nodeKey).New()
|
||||
mustCrypto("content key packet", err)
|
||||
keyPacket, err := eh.EncryptSessionKey(sk)
|
||||
mustCrypto("content key packet", err)
|
||||
return contentKey{
|
||||
sk: sk,
|
||||
packet: base64.StdEncoding.EncodeToString(keyPacket),
|
||||
signature: signArmored(sk.Key, nodeKey),
|
||||
aead: aead,
|
||||
}
|
||||
}
|
||||
|
||||
// pgp returns the handle for encrypting with ck.
|
||||
func (ck contentKey) pgp() *crypto.PGPHandle {
|
||||
if ck.aead {
|
||||
return aeadPGP()
|
||||
}
|
||||
return crypto.PGP()
|
||||
}
|
||||
|
||||
// encryptBlock encrypts one block of plaintext with the content key and
|
||||
// returns the data packet and the armored block signature: a detached
|
||||
// signature by signer encrypted to nodeKey with the content key, the
|
||||
// SDK's encryptBlock.
|
||||
func (ck contentKey) encryptBlock(plain []byte, nodeKey, signer *crypto.Key) (data []byte, encSignature string) {
|
||||
eh, err := ck.pgp().Encryption().SessionKey(ck.sk).New()
|
||||
mustCrypto("encrypt block", err)
|
||||
msg, err := eh.Encrypt(plain)
|
||||
mustCrypto("encrypt block", err)
|
||||
|
||||
sigHandle, err := ck.pgp().Encryption().Recipient(nodeKey).SessionKey(ck.sk).New()
|
||||
mustCrypto("encrypt block signature", err)
|
||||
sigMsg, err := sigHandle.Encrypt(signBinary(plain, signer))
|
||||
mustCrypto("encrypt block signature", err)
|
||||
encSignature, err = sigMsg.Armor()
|
||||
mustCrypto("armor block signature", err)
|
||||
return msg.DataPacket, encSignature
|
||||
}
|
||||
|
||||
// keyRing returns a key ring of keys, which must not be empty.
|
||||
func keyRing(keys ...*crypto.Key) *crypto.KeyRing {
|
||||
kr, err := crypto.NewKeyRing(nil)
|
||||
mustCrypto("key ring", err)
|
||||
for _, k := range keys {
|
||||
mustCrypto("key ring", kr.AddKey(k))
|
||||
}
|
||||
return kr
|
||||
}
|
||||
|
||||
// errSignature wraps every signature verification failure.
|
||||
var errSignature = errors.New("protontest: bad signature")
|
||||
|
||||
// decryptArmored decrypts an armored message with key. If verify is not
|
||||
// nil the embedded signature must be valid for one of its keys at time
|
||||
// at, or now if at is zero.
|
||||
func decryptArmored(armored string, key *crypto.Key, verify *crypto.KeyRing, at time.Time) ([]byte, error) {
|
||||
b := crypto.PGP().Decryption().DecryptionKey(key)
|
||||
if verify != nil {
|
||||
b = b.VerificationKeys(verify)
|
||||
if !at.IsZero() {
|
||||
b = b.VerifyTime(at.Unix())
|
||||
}
|
||||
}
|
||||
dh, err := b.New()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res, err := dh.Decrypt([]byte(armored), crypto.Armor)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if verify != nil {
|
||||
if err := res.SignatureError(); err != nil {
|
||||
return res.Bytes(), fmt.Errorf("%w: %v", errSignature, err)
|
||||
}
|
||||
}
|
||||
return res.Bytes(), nil
|
||||
}
|
||||
|
||||
// verifyDetached checks a detached signature, armored or binary per
|
||||
// encoding, of data against verify at time at, or now if at is zero.
|
||||
func verifyDetached(data, sig []byte, encoding int8, verify *crypto.KeyRing, at time.Time) error {
|
||||
b := crypto.PGP().Verify().VerificationKeys(verify)
|
||||
if !at.IsZero() {
|
||||
b = b.VerifyTime(at.Unix())
|
||||
}
|
||||
vh, err := b.New()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := vh.VerifyDetached(data, sig, encoding)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: %v", errSignature, err)
|
||||
}
|
||||
if err := res.SignatureError(); err != nil {
|
||||
return fmt.Errorf("%w: %v", errSignature, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// unlockFunc unlocks an armored private key with a passphrase.
|
||||
type unlockFunc func(armoredKey string, passphrase []byte) (*crypto.Key, error)
|
||||
|
||||
// unlockDriveKey decrypts a node or share key: the passphrase with
|
||||
// parent, its detached signature against verify, then the key itself
|
||||
// with unlock. A bad signature is returned alongside the unlocked key.
|
||||
// Signatures are checked at time at, or now if it is zero.
|
||||
func unlockDriveKey(armoredKey string, sealed sealedPassphrase, parent *crypto.Key, verify *crypto.KeyRing, unlock unlockFunc, at time.Time) (*crypto.Key, error) {
|
||||
passphrase, err := decryptArmored(sealed.armored, parent, nil, at)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decrypt passphrase: %w", err)
|
||||
}
|
||||
key, err := unlock(armoredKey, passphrase)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unlock key: %w", err)
|
||||
}
|
||||
if err := verifyDetached(passphrase, []byte(sealed.signature), crypto.Armor, verify, at); err != nil {
|
||||
return key, fmt.Errorf("passphrase: %w", err)
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// decryptContentKey decrypts a base64 content key packet with nodeKey
|
||||
// and checks its signature against nodeKey and verify at time at.
|
||||
func decryptContentKey(packet64, signature string, nodeKey *crypto.Key, verify *crypto.KeyRing, at time.Time) (*crypto.SessionKey, error) {
|
||||
keyPacket, err := base64.StdEncoding.DecodeString(packet64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("content key packet: %w", err)
|
||||
}
|
||||
dh, err := crypto.PGP().Decryption().DecryptionKey(nodeKey).New()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sk, err := dh.DecryptSessionKey(keyPacket)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("content key packet: %w", err)
|
||||
}
|
||||
kr := keyRing(nodeKey)
|
||||
for _, k := range verify.GetKeys() {
|
||||
mustCrypto("key ring", kr.AddKey(k))
|
||||
}
|
||||
if err := verifyDetached(sk.Key, []byte(signature), crypto.Armor, kr, at); err != nil {
|
||||
return sk, fmt.Errorf("content key packet: %w", err)
|
||||
}
|
||||
return sk, nil
|
||||
}
|
||||
|
||||
// decryptBlock decrypts a block's data packet with sk and checks its
|
||||
// encrypted signature, decrypted with nodeKey, against verify at time
|
||||
// at.
|
||||
func decryptBlock(data []byte, encSignature string, sk *crypto.SessionKey, nodeKey *crypto.Key, verify *crypto.KeyRing, at time.Time) ([]byte, error) {
|
||||
dh, err := crypto.PGP().Decryption().SessionKey(sk).New()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res, err := dh.Decrypt(data, crypto.Bytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decrypt block: %w", err)
|
||||
}
|
||||
sig, err := decryptArmored(encSignature, nodeKey, nil, at)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decrypt block signature: %w", err)
|
||||
}
|
||||
if err := verifyDetached(res.Bytes(), sig, crypto.Bytes, verify, at); err != nil {
|
||||
return res.Bytes(), fmt.Errorf("block: %w", err)
|
||||
}
|
||||
return res.Bytes(), nil
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,716 @@
|
||||
package protontest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha1"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/ProtonMail/go-crypto/openpgp/armor"
|
||||
"github.com/ProtonMail/go-crypto/openpgp/packet"
|
||||
"github.com/ProtonMail/gopenpgp/v3/crypto"
|
||||
"github.com/rclone/rclone/backend/protondrive/api"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// sessionHeader returns the headers of an authenticated request.
|
||||
func sessionHeader(sess Session) map[string]string {
|
||||
return map[string]string{
|
||||
"x-pm-appversion": testAppVersion,
|
||||
"x-pm-uid": sess.UID,
|
||||
"Authorization": "Bearer " + sess.AccessToken,
|
||||
}
|
||||
}
|
||||
|
||||
// getJSON calls GET path as sess, decodes the response into out if it
|
||||
// is not nil and returns the HTTP status and body.
|
||||
func getJSON(t *testing.T, s *Server, sess Session, path string, out any) (int, []byte) {
|
||||
t.Helper()
|
||||
resp, body := do(t, s, "GET", path, sessionHeader(sess))
|
||||
if out != nil && resp.StatusCode == http.StatusOK {
|
||||
require.NoError(t, json.Unmarshal(body, out), "body: %s", body)
|
||||
}
|
||||
return resp.StatusCode, body
|
||||
}
|
||||
|
||||
// patterned returns content of n bytes which differs per block.
|
||||
func patterned(n int) []byte {
|
||||
b := make([]byte, n)
|
||||
for i := range b {
|
||||
b[i] = byte(i*7 + i/blockSize)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func sha1Hex(b []byte) string {
|
||||
sum := sha1.Sum(b)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func TestSeedAndDump(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
modTime := time.Date(2024, 5, 6, 7, 8, 9, 123e6, time.FixedZone("x", 3600))
|
||||
|
||||
docs := u.SeedFolder(u.RootID(), "Documents")
|
||||
sub := u.SeedFolder(docs, "Sub")
|
||||
empty := u.SeedFile(u.RootID(), "empty.txt", nil, modTime)
|
||||
small := u.SeedFile(docs, "small.bin", []byte("hello"), modTime)
|
||||
exact := u.SeedFile(sub, "exact.bin", patterned(blockSize), modTime)
|
||||
big := u.SeedFile(sub, "big.bin", patterned(2*blockSize+123), modTime)
|
||||
before := time.Now().Truncate(time.Second)
|
||||
legacy := u.SeedLegacyFile(docs, "legacy.txt", []byte("old format"))
|
||||
doc := u.SeedDoc(u.RootID(), "Notes")
|
||||
|
||||
type want struct {
|
||||
id, path string
|
||||
folder bool
|
||||
content []byte
|
||||
hasTime bool
|
||||
}
|
||||
wants := []want{
|
||||
{docs, "Documents", true, nil, false},
|
||||
{sub, "Documents/Sub", true, nil, false},
|
||||
{big, "Documents/Sub/big.bin", false, patterned(2*blockSize + 123), true},
|
||||
{exact, "Documents/Sub/exact.bin", false, patterned(blockSize), true},
|
||||
{legacy, "Documents/legacy.txt", false, []byte("old format"), true},
|
||||
{small, "Documents/small.bin", false, []byte("hello"), true},
|
||||
{doc, "Notes", false, nil, false},
|
||||
{empty, "empty.txt", false, nil, true},
|
||||
}
|
||||
dump := u.Dump()
|
||||
require.Len(t, dump, len(wants))
|
||||
for i, w := range wants {
|
||||
n := dump[i]
|
||||
assert.NoError(t, n.Err, w.path)
|
||||
assert.Equal(t, w.id, n.ID, w.path)
|
||||
assert.Equal(t, w.path, n.Path)
|
||||
assert.Equal(t, w.folder, n.IsFolder, w.path)
|
||||
assert.Equal(t, linkStateActive, n.State, w.path)
|
||||
assert.True(t, bytes.Equal(w.content, n.Content), "%s: content", w.path)
|
||||
switch {
|
||||
case !w.hasTime:
|
||||
assert.True(t, n.ModTime.IsZero(), w.path)
|
||||
assert.Empty(t, n.SHA1, w.path)
|
||||
case w.id == legacy:
|
||||
assert.False(t, n.ModTime.Before(before), w.path)
|
||||
assert.False(t, n.ModTime.After(time.Now()), w.path)
|
||||
assert.Equal(t, sha1Hex(w.content), n.SHA1, w.path)
|
||||
default:
|
||||
assert.True(t, modTime.Equal(n.ModTime), "%s: modtime %v", w.path, n.ModTime)
|
||||
assert.Equal(t, sha1Hex(w.content), n.SHA1, w.path)
|
||||
}
|
||||
}
|
||||
assert.Empty(t, u.Drafts())
|
||||
}
|
||||
|
||||
// packetVersion returns the tag and version byte of the first packet
|
||||
// of a binary OpenPGP message.
|
||||
func packetVersion(t *testing.T, msg []byte) (tag packet.Packet, version byte) {
|
||||
t.Helper()
|
||||
p, err := packet.NewReader(bytes.NewReader(msg)).Next()
|
||||
require.NoError(t, err)
|
||||
switch p := p.(type) {
|
||||
case *packet.EncryptedKey:
|
||||
return p, byte(p.Version)
|
||||
case *packet.SymmetricallyEncrypted:
|
||||
return p, byte(p.Version)
|
||||
}
|
||||
t.Fatalf("unexpected packet %T", p)
|
||||
return nil, 0
|
||||
}
|
||||
|
||||
// dataPacketVersion returns the SEIPD version of an armored message.
|
||||
func dataPacketVersion(t *testing.T, armored string) byte {
|
||||
t.Helper()
|
||||
block, err := armor.Decode(strings.NewReader(armored))
|
||||
require.NoError(t, err)
|
||||
packets := packet.NewReader(block.Body)
|
||||
for {
|
||||
p, err := packets.Next()
|
||||
require.NoError(t, err)
|
||||
if p, ok := p.(*packet.SymmetricallyEncrypted); ok {
|
||||
return byte(p.Version)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedFormats(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
current := u.SeedFile(u.RootID(), "current", []byte("new"), time.Now())
|
||||
legacy := u.SeedLegacyFile(u.RootID(), "legacy", []byte("old"))
|
||||
folder := u.SeedFolder(u.RootID(), "folder")
|
||||
v := u.view()
|
||||
|
||||
for _, tc := range []struct {
|
||||
id string
|
||||
pkesk byte
|
||||
seipd byte
|
||||
aeadKey bool
|
||||
mediaType string
|
||||
blockCount int
|
||||
}{
|
||||
{current, 6, 2, true, "application/octet-stream", 1},
|
||||
{legacy, 3, 1, false, "application/octet-stream", 1},
|
||||
} {
|
||||
l := v.d.links[tc.id]
|
||||
keyPacket, err := base64.StdEncoding.DecodeString(l.contentKeyPacket)
|
||||
require.NoError(t, err)
|
||||
_, version := packetVersion(t, keyPacket)
|
||||
assert.Equal(t, tc.pkesk, version, "content key packet version")
|
||||
rev := l.activeRevision()
|
||||
require.Len(t, rev.blocks, tc.blockCount)
|
||||
_, version = packetVersion(t, rev.blocks[0].data)
|
||||
assert.Equal(t, tc.seipd, version, "block SEIPD version")
|
||||
assert.Equal(t, tc.seipd, dataPacketVersion(t, rev.blocks[0].encSignature), "block signature SEIPD version")
|
||||
assert.Equal(t, tc.mediaType, l.mediaType)
|
||||
|
||||
key, err := crypto.NewKeyFromArmored(l.nodeKey)
|
||||
require.NoError(t, err)
|
||||
sig, err := key.GetEntity().PrimarySelfSignature(time.Now(), nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tc.aeadKey, sig.SEIPDv2, "node key advertises SEIPDv2")
|
||||
|
||||
// Everything but content avoids AEAD whatever the node key
|
||||
// advertises.
|
||||
assert.Equal(t, byte(1), dataPacketVersion(t, l.name), "name")
|
||||
assert.Equal(t, byte(1), dataPacketVersion(t, l.nodePass.armored), "passphrase")
|
||||
assert.Equal(t, byte(1), dataPacketVersion(t, rev.xattr), "extended attributes")
|
||||
}
|
||||
|
||||
l := v.d.links[folder]
|
||||
key, err := crypto.NewKeyFromArmored(l.nodeKey)
|
||||
require.NoError(t, err)
|
||||
sig, err := key.GetEntity().PrimarySelfSignature(time.Now(), nil)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, sig.SEIPDv2, "folder key advertises SEIPDv2")
|
||||
assert.Equal(t, byte(1), dataPacketVersion(t, l.hashKey), "hash key")
|
||||
}
|
||||
|
||||
func TestCorrupt(t *testing.T) {
|
||||
for _, what := range []string{"name", "name-signature", "passphrase-signature", "block-hash", "manifest", "swap-blocks", "truncate-blocks", "block-rollback", "foreign-block"} {
|
||||
t.Run(what, func(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
victim := u.SeedFile(u.RootID(), "victim", patterned(blockSize+10), time.Now())
|
||||
if what == "block-rollback" {
|
||||
u.SeedRevision(victim, patterned(blockSize+20), time.Now())
|
||||
}
|
||||
bystander := u.SeedFile(u.RootID(), "bystander", []byte("fine"), time.Now())
|
||||
u.Corrupt(victim, what)
|
||||
for _, n := range u.Dump() {
|
||||
switch n.ID {
|
||||
case victim:
|
||||
assert.Error(t, n.Err)
|
||||
case bystander:
|
||||
assert.NoError(t, n.Err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBootstrapRoutes(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
sess := s.NewSession(u)
|
||||
|
||||
var myFiles myFilesResponse
|
||||
status, body := getJSON(t, s, sess, "/drive/v2/shares/my-files", &myFiles)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
assert.Equal(t, u.VolumeID(), myFiles.Volume.VolumeID)
|
||||
assert.Equal(t, u.ShareID(), myFiles.Share.ShareID)
|
||||
assert.Equal(t, u.RootID(), myFiles.Link.Link.LinkID)
|
||||
assert.Equal(t, u.Email(), myFiles.Share.CreatorEmail)
|
||||
assert.Nil(t, myFiles.Link.Link.ParentLinkID)
|
||||
|
||||
var volume getVolumeResponse
|
||||
status, body = getJSON(t, s, sess, "/drive/volumes/"+u.VolumeID(), &volume)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
assert.Equal(t, u.ShareID(), volume.Volume.Share.ShareID)
|
||||
assert.Equal(t, u.RootID(), volume.Volume.Share.LinkID)
|
||||
|
||||
var share shareResponse
|
||||
status, body = getJSON(t, s, sess, "/drive/shares/"+u.ShareID(), &share)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
assert.Equal(t, u.RootID(), share.LinkID)
|
||||
assert.Equal(t, myFiles.Share.Key, share.Key)
|
||||
require.NotNil(t, share.AddressID)
|
||||
assert.Equal(t, myFiles.Share.AddressID, *share.AddressID)
|
||||
|
||||
// Another user's IDs are not found.
|
||||
other := s.AddUser("other", "pass")
|
||||
status, body = getJSON(t, s, sess, "/drive/volumes/"+other.VolumeID(), nil)
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, status)
|
||||
assert.Equal(t, api.CodeNotExists, decodeError(t, body).Code)
|
||||
status, _ = getJSON(t, s, sess, "/drive/shares/"+other.ShareID(), nil)
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, status)
|
||||
}
|
||||
|
||||
// keysOf returns the keys of a JSON object.
|
||||
func keysOf(t *testing.T, v any) []string {
|
||||
t.Helper()
|
||||
m, ok := v.(map[string]any)
|
||||
require.True(t, ok, "not an object: %v", v)
|
||||
var keys []string
|
||||
for k := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
// TestWireFieldNames checks the link metadata response carries the
|
||||
// fields the SDK's nodes/apiService.ts reads, by name.
|
||||
func TestWireFieldNames(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
sess := s.NewSession(u)
|
||||
folder := u.SeedFolder(u.RootID(), "folder")
|
||||
file := u.SeedFile(u.RootID(), "file", []byte("x"), time.Now())
|
||||
|
||||
var resp struct{ Links []map[string]any }
|
||||
status := postJSON(t, s, "/drive/v2/volumes/"+u.VolumeID()+"/links", sessionHeader(sess), &linksRequest{LinkIDs: []string{folder, file}}, &resp)
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
require.Len(t, resp.Links, 2)
|
||||
for _, l := range resp.Links {
|
||||
assert.Subset(t, keysOf(t, l), []string{"Link", "Folder", "File", "Sharing", "Membership"})
|
||||
assert.Subset(t, keysOf(t, l["Link"]), []string{
|
||||
"LinkID", "Type", "ParentLinkID", "State", "CreateTime", "ModifyTime", "TrashTime",
|
||||
"Name", "NameHash", "NodeKey", "NodePassphrase", "NodePassphraseSignature",
|
||||
"SignatureEmail", "NameSignatureEmail", "OwnedBy", "ThirdParty", "Sdk",
|
||||
})
|
||||
if l["File"] == nil {
|
||||
assert.Subset(t, keysOf(t, l["Folder"]), []string{"NodeHashKey", "XAttr", "IsImported"})
|
||||
continue
|
||||
}
|
||||
f := l["File"]
|
||||
assert.Subset(t, keysOf(t, f), []string{"ActiveRevision", "TotalEncryptedSize", "ContentKeyPacket", "MediaType", "ContentKeyPacketSignature"})
|
||||
assert.Subset(t, keysOf(t, f.(map[string]any)["ActiveRevision"]), []string{
|
||||
"RevisionID", "CreateTime", "EncryptedSize", "SignatureEmail", "XAttr", "IsImported",
|
||||
"Thumbnails", "ThirdParty", "Sdk", "ManifestSignature",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestChildrenPaging(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
sess := s.NewSession(u)
|
||||
s.SetChildrenPageSize(100)
|
||||
parent := u.SeedFolder(u.RootID(), "parent")
|
||||
want := make(map[string]bool)
|
||||
for i := range 250 {
|
||||
want[u.SeedFolder(parent, fmt.Sprintf("child %03d", i))] = true
|
||||
}
|
||||
trashed := u.SeedFolder(parent, "trashed")
|
||||
s.mu.Lock()
|
||||
u.drive.links[trashed].state = linkStateTrashed
|
||||
s.mu.Unlock()
|
||||
s.ResetRequests()
|
||||
|
||||
got := make(map[string]bool)
|
||||
anchor, pages := "", 0
|
||||
for {
|
||||
path := "/drive/v2/volumes/" + u.VolumeID() + "/folders/" + parent + "/children"
|
||||
if anchor != "" {
|
||||
path += "?AnchorID=" + anchor
|
||||
}
|
||||
var page childrenResponse
|
||||
status, body := getJSON(t, s, sess, path, &page)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
pages++
|
||||
for _, id := range page.LinkIDs {
|
||||
assert.False(t, got[id], "duplicate %s", id)
|
||||
got[id] = true
|
||||
}
|
||||
if !page.More {
|
||||
assert.Nil(t, page.AnchorID)
|
||||
break
|
||||
}
|
||||
require.NotNil(t, page.AnchorID)
|
||||
require.Len(t, page.LinkIDs, 100)
|
||||
anchor = *page.AnchorID
|
||||
}
|
||||
assert.Equal(t, 3, pages)
|
||||
assert.Equal(t, want, got)
|
||||
assert.Equal(t, 3, s.Requests()["GET /drive/v2/volumes/{volumeID}/folders/{linkID}/children"])
|
||||
}
|
||||
|
||||
func TestLinksBatchLimit(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
sess := s.NewSession(u)
|
||||
a := u.SeedFolder(u.RootID(), "a")
|
||||
b := u.SeedFile(u.RootID(), "b", []byte("b"), time.Now())
|
||||
path := "/drive/v2/volumes/" + u.VolumeID() + "/links"
|
||||
|
||||
ids := []string{a, b}
|
||||
for len(ids) < maxLinksPerRequest {
|
||||
ids = append(ids, randomID())
|
||||
}
|
||||
var resp linksResponse
|
||||
require.Equal(t, http.StatusOK, postJSON(t, s, path, sessionHeader(sess), &linksRequest{LinkIDs: ids}, &resp))
|
||||
require.Len(t, resp.Links, 2, "unknown IDs are left out")
|
||||
assert.Equal(t, a, resp.Links[0].Link.LinkID)
|
||||
assert.NotNil(t, resp.Links[0].Folder)
|
||||
assert.Equal(t, b, resp.Links[1].Link.LinkID)
|
||||
require.NotNil(t, resp.Links[1].File)
|
||||
assert.NotNil(t, resp.Links[1].File.ActiveRevision)
|
||||
|
||||
var apiErr api.Error
|
||||
ids = append(ids, randomID())
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, postJSON(t, s, path, sessionHeader(sess), &linksRequest{LinkIDs: ids}, &apiErr))
|
||||
assert.Equal(t, api.CodeInvalidValue, apiErr.Code)
|
||||
}
|
||||
|
||||
// getBlock fetches a block URL with the given storage token, sent
|
||||
// unless empty.
|
||||
func getBlock(t *testing.T, s *Server, bareURL, token string) (int, []byte) {
|
||||
t.Helper()
|
||||
header := map[string]string{"x-pm-appversion": testAppVersion}
|
||||
if token != "" {
|
||||
header["pm-storage-token"] = token
|
||||
}
|
||||
require.True(t, strings.HasPrefix(bareURL, s.URL()+"/"), "block URL %s is not on the test server", bareURL)
|
||||
resp, body := do(t, s, "GET", strings.TrimPrefix(bareURL, s.URL()), header)
|
||||
return resp.StatusCode, body
|
||||
}
|
||||
|
||||
func TestBlockDownloadNeedsToken(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
sess := s.NewSession(u)
|
||||
content := patterned(blockSize + 100)
|
||||
file := u.SeedFile(u.RootID(), "file", content, time.Now())
|
||||
|
||||
var links linksResponse
|
||||
require.Equal(t, http.StatusOK, postJSON(t, s, "/drive/v2/volumes/"+u.VolumeID()+"/links", sessionHeader(sess), &linksRequest{LinkIDs: []string{file}}, &links))
|
||||
revisionPath := "/drive/v2/volumes/" + u.VolumeID() + "/files/" + file + "/revisions/" + links.Links[0].File.ActiveRevision.RevisionID
|
||||
|
||||
var rev revisionResponse
|
||||
status, body := getJSON(t, s, sess, revisionPath+"?NoBlockUrls=true", &rev)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
require.Len(t, rev.Revision.Blocks, 2)
|
||||
for _, b := range rev.Revision.Blocks {
|
||||
assert.Nil(t, b.Token)
|
||||
assert.Nil(t, b.BareURL)
|
||||
}
|
||||
require.NotNil(t, rev.Revision.ManifestSignature)
|
||||
|
||||
status, body = getJSON(t, s, sess, revisionPath+"?PageSize=1&FromBlockIndex=2", &rev)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
require.Len(t, rev.Revision.Blocks, 1)
|
||||
b := rev.Revision.Blocks[0]
|
||||
assert.Equal(t, 2, b.Index)
|
||||
require.NotNil(t, b.Token)
|
||||
require.NotNil(t, b.BareURL)
|
||||
|
||||
status, _ = getBlock(t, s, *b.BareURL, "")
|
||||
assert.Equal(t, http.StatusForbidden, status)
|
||||
status, _ = getBlock(t, s, *b.BareURL, "wrong")
|
||||
assert.Equal(t, http.StatusForbidden, status)
|
||||
status, data := getBlock(t, s, *b.BareURL, *b.Token)
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
sum := sha256.Sum256(data)
|
||||
assert.Equal(t, b.Hash, base64.StdEncoding.EncodeToString(sum[:]))
|
||||
status, _ = getBlock(t, s, s.URL()+"/storage/blocks/unknown", *b.Token)
|
||||
assert.Equal(t, http.StatusNotFound, status)
|
||||
}
|
||||
|
||||
func TestQuota(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
sess := s.NewSession(u)
|
||||
u.SeedFile(u.RootID(), "a", patterned(1000), time.Now())
|
||||
u.SeedFile(u.RootID(), "b", patterned(10), time.Now())
|
||||
|
||||
var want int64
|
||||
v := u.view()
|
||||
for _, l := range v.d.links {
|
||||
for _, r := range l.revisions {
|
||||
want += r.size()
|
||||
}
|
||||
}
|
||||
require.NotZero(t, want)
|
||||
|
||||
var resp struct {
|
||||
User struct {
|
||||
UsedSpace int64
|
||||
MaxSpace int64
|
||||
ProductUsedSpace struct{ Drive int64 }
|
||||
}
|
||||
}
|
||||
status, body := getJSON(t, s, sess, "/core/v4/users", &resp)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
assert.Equal(t, want, resp.User.UsedSpace)
|
||||
assert.Equal(t, want, resp.User.ProductUsedSpace.Drive)
|
||||
assert.Equal(t, DefaultMaxSpace, resp.User.MaxSpace)
|
||||
}
|
||||
|
||||
// volumeBootstrap returns a create volume request for the primary
|
||||
// address of u made as the SDK's generateVolumeBootstrap does.
|
||||
func volumeBootstrap(u *User) *createVolumeRequest {
|
||||
addr := u.addresses[0]
|
||||
addrKey := addr.keys[0].key
|
||||
share := newDriveKey(false)
|
||||
sharePass := sealPassphrase(share.passphrase, addrKey, addrKey)
|
||||
root := newDriveKey(false)
|
||||
rootPass := sealPassphrase(root.passphrase, share.key, addrKey)
|
||||
_, hashKey := newHashKey(root.key)
|
||||
return &createVolumeRequest{
|
||||
AddressID: addr.id,
|
||||
AddressKeyID: &addr.keys[0].id,
|
||||
ShareKey: share.armored,
|
||||
SharePassphrase: sharePass.armored,
|
||||
SharePassphraseSignature: sharePass.signature,
|
||||
FolderName: encryptArmored([]byte("root"), share.key, addrKey, false),
|
||||
FolderKey: root.armored,
|
||||
FolderPassphrase: rootPass.armored,
|
||||
FolderPassphraseSignature: rootPass.signature,
|
||||
FolderHashKey: hashKey,
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountWithoutDrive(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUserWithoutDrive("new", "pass")
|
||||
sess := s.NewSession(u)
|
||||
|
||||
status, body := getJSON(t, s, sess, "/drive/v2/shares/my-files", nil)
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, status)
|
||||
assert.Equal(t, api.CodeNotExists, decodeError(t, body).Code)
|
||||
assert.Equal(t, "Volume not found", decodeError(t, body).Message)
|
||||
|
||||
impostor := generateKey("impostor", "impostor@proton.test")
|
||||
for name, spoil := range map[string]func(req *createVolumeRequest){
|
||||
"share passphrase to another key": func(req *createVolumeRequest) {
|
||||
req.SharePassphrase = encryptArmored([]byte("x"), impostor, nil, false)
|
||||
},
|
||||
"share passphrase signed by another key": func(req *createVolumeRequest) {
|
||||
other := volumeBootstrap(u)
|
||||
req.SharePassphraseSignature = other.SharePassphraseSignature
|
||||
},
|
||||
"folder name missing": func(req *createVolumeRequest) {
|
||||
req.FolderName = ""
|
||||
},
|
||||
"hash key missing": func(req *createVolumeRequest) {
|
||||
req.FolderHashKey = ""
|
||||
},
|
||||
"unknown address": func(req *createVolumeRequest) {
|
||||
req.AddressID = "unknown"
|
||||
},
|
||||
} {
|
||||
req := volumeBootstrap(u)
|
||||
spoil(req)
|
||||
var apiErr api.Error
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, postJSON(t, s, "/drive/volumes", sessionHeader(sess), req, &apiErr), name)
|
||||
assert.Equal(t, api.CodeInvalidValue, apiErr.Code, name)
|
||||
}
|
||||
|
||||
var created getVolumeResponse
|
||||
status = postJSON(t, s, "/drive/volumes", sessionHeader(sess), volumeBootstrap(u), &created)
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
assert.Equal(t, u.VolumeID(), created.Volume.ID)
|
||||
assert.Equal(t, u.ShareID(), created.Volume.Share.ShareID)
|
||||
assert.Equal(t, u.RootID(), created.Volume.Share.LinkID)
|
||||
|
||||
var apiErr api.Error
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, postJSON(t, s, "/drive/volumes", sessionHeader(sess), volumeBootstrap(u), &apiErr))
|
||||
assert.Equal(t, api.CodeAlreadyExists, apiErr.Code)
|
||||
|
||||
var myFiles myFilesResponse
|
||||
status, body = getJSON(t, s, sess, "/drive/v2/shares/my-files", &myFiles)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
assert.Equal(t, u.RootID(), myFiles.Link.Link.LinkID)
|
||||
|
||||
assert.Empty(t, u.Dump())
|
||||
id := u.SeedFile(u.RootID(), "after", []byte("works"), time.Now())
|
||||
dump := u.Dump()
|
||||
require.Len(t, dump, 1)
|
||||
assert.Equal(t, id, dump[0].ID)
|
||||
assert.Equal(t, "after", dump[0].Path)
|
||||
assert.NoError(t, dump[0].Err)
|
||||
}
|
||||
|
||||
// TestBlockBodyIsReadable checks a downloaded block is the exact data
|
||||
// packet that decrypts with the content key.
|
||||
func TestBlockBodyIsReadable(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
sess := s.NewSession(u)
|
||||
file := u.SeedFile(u.RootID(), "file", []byte("block body"), time.Now())
|
||||
v := u.view()
|
||||
l := v.d.links[file]
|
||||
key, err := v.unlock(file)
|
||||
require.NoError(t, err)
|
||||
sk, err := decryptContentKey(l.contentKeyPacket, l.contentKeyPacketSignature, key, keyRing(key), time.Time{})
|
||||
require.NoError(t, err)
|
||||
|
||||
var rev revisionResponse
|
||||
status, body := getJSON(t, s, sess, "/drive/v2/volumes/"+u.VolumeID()+"/files/"+file+"/revisions/"+l.activeRevision().id, &rev)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
b := rev.Revision.Blocks[0]
|
||||
status, data := getBlock(t, s, *b.BareURL, *b.Token)
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
plain, err := decryptBlock(data, *b.EncSignature, sk, key, keyRing(u.addresses[0].keys[0].key), time.Time{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "block body", string(plain))
|
||||
}
|
||||
|
||||
func TestSeedRevision(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
ids := map[string]string{
|
||||
"current": u.SeedFile(u.RootID(), "current", []byte("old"), time.Now()),
|
||||
"legacy": u.SeedLegacyFile(u.RootID(), "legacy", []byte("old")),
|
||||
}
|
||||
content := patterned(blockSize + 5)
|
||||
for name, id := range ids {
|
||||
old := u.view().d.links[id].activeRevision().id
|
||||
rev := u.SeedRevision(id, content, time.Now())
|
||||
l := u.view().d.links[id]
|
||||
assert.Equal(t, rev, l.activeRevision().id, name)
|
||||
require.Len(t, l.revisions, 2, name)
|
||||
assert.Equal(t, old, l.revisions[0].id, name)
|
||||
assert.Equal(t, revisionStateObsolete, l.revisions[0].state, name)
|
||||
}
|
||||
dump := u.Dump()
|
||||
require.Len(t, dump, 2)
|
||||
for _, d := range dump {
|
||||
assert.NoError(t, d.Err, d.Path)
|
||||
assert.True(t, bytes.Equal(content, d.Content), d.Path)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedForgedFolder(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
forged := u.SeedForgedFolder(u.RootID(), "forged")
|
||||
nested := u.SeedAnonymousFolder(forged, "nested")
|
||||
file := u.SeedAnonymousFile(nested, "file", []byte("forged content"), time.Now())
|
||||
for _, n := range u.Dump() {
|
||||
switch n.ID {
|
||||
case forged:
|
||||
assert.Error(t, n.Err, "the forged key's signature verifies")
|
||||
case nested, file:
|
||||
assert.NoError(t, n.Err, n.Path)
|
||||
}
|
||||
if n.ID == file {
|
||||
assert.Equal(t, "forged/nested/file", n.Path)
|
||||
assert.Equal(t, "forged content", string(n.Content))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestForgeShareAndRoot(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
other := s.AddUser("other", "pass")
|
||||
u.ForgeShareCreator(other, other.Email())
|
||||
u.ForgeRootSigner(other, other.Email())
|
||||
v := u.view()
|
||||
assert.Equal(t, other.Email(), v.d.creatorEmail)
|
||||
_, err := v.unlockShare()
|
||||
assert.NoError(t, err, "the share verifies against the other user's key")
|
||||
root := v.d.links[v.d.rootID]
|
||||
assert.Equal(t, other.Email(), root.signatureEmail)
|
||||
_, err = v.unlock(v.d.rootID)
|
||||
assert.NoError(t, err, "the root verifies against the other user's key")
|
||||
id := u.SeedFile(u.RootID(), "file", []byte("x"), time.Now())
|
||||
for _, n := range u.Dump() {
|
||||
if n.ID == id {
|
||||
assert.NoError(t, n.Err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestServeKeysAs(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
other := s.AddUser("other", "pass")
|
||||
sess := s.NewSession(u)
|
||||
s.ServeKeysAs("USER@proton.test", other)
|
||||
var resp api.PublicKeysResponse
|
||||
status, body := getJSON(t, s, sess, "/core/v4/keys/all?Email=USER@proton.test", &resp)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
require.NotEmpty(t, resp.Address.Keys)
|
||||
want, err := other.addresses[0].keys[0].key.GetArmoredPublicKey()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, want, resp.Address.Keys[0].PublicKey)
|
||||
}
|
||||
|
||||
func TestNodeSecrets(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
id := u.SeedFile(u.RootID(), "file", []byte("secret"), time.Now())
|
||||
passphrase, sessionKey := u.NodeSecrets(id)
|
||||
|
||||
v := u.view()
|
||||
l := v.d.links[id]
|
||||
key, err := crypto.NewPrivateKeyFromArmored(l.nodeKey, passphrase)
|
||||
require.NoError(t, err, "the passphrase unlocks the node key")
|
||||
sk, err := decryptContentKey(l.contentKeyPacket, l.contentKeyPacketSignature, key, keyRing(key), time.Time{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, sk.Key, sessionKey)
|
||||
}
|
||||
|
||||
func TestIssuedSecrets(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
sess := s.NewSession(u)
|
||||
file := u.SeedFile(u.RootID(), "file", []byte("x"), time.Now())
|
||||
assert.Equal(t, []string{sess.AccessToken, sess.RefreshToken}, s.IssuedSecrets())
|
||||
|
||||
var rev revisionResponse
|
||||
status, body := getJSON(t, s, sess, "/drive/v2/volumes/"+u.VolumeID()+"/files/"+file+"/revisions/"+u.view().d.links[file].activeRevision().id, &rev)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
token := *rev.Revision.Blocks[0].Token
|
||||
assert.Equal(t, []string{token}, s.IssuedSecrets(StorageToken))
|
||||
assert.Equal(t, []string{sess.AccessToken, sess.RefreshToken}, s.IssuedSecrets(SessionToken))
|
||||
assert.Equal(t, []string{sess.AccessToken, sess.RefreshToken, token}, s.IssuedSecrets())
|
||||
assert.Empty(t, s.IssuedSecrets(ForkSelector))
|
||||
}
|
||||
|
||||
func TestStoredFileRoundTrip(t *testing.T) {
|
||||
s := New(t)
|
||||
addrPass := newPassphrase()
|
||||
root := newDriveKey(false)
|
||||
_, hashKey := newHashKey(root.key)
|
||||
keys := FixedKeys{
|
||||
AddressKey: lockKey(generateKey("fixed", "fixed@proton.test"), addrPass),
|
||||
AddressKeyPassphrase: string(addrPass),
|
||||
RootKey: root.armored,
|
||||
RootKeyPassphrase: string(root.passphrase),
|
||||
RootHashKey: hashKey,
|
||||
}
|
||||
// Two users holding the same keys can read each other's stored files.
|
||||
one := s.AddUserWithKeys("one", "pass", keys)
|
||||
two := s.AddUserWithKeys("two", "pass", keys)
|
||||
content := patterned(blockSize + 5)
|
||||
id := one.SeedFile(one.RootID(), "f", content, time.Now())
|
||||
|
||||
f := one.StoredFile(id)
|
||||
assert.Equal(t, "one@proton.test", f.Link.SignatureEmail)
|
||||
require.Len(t, f.Revision.Blocks, 2)
|
||||
for _, b := range f.Revision.Blocks {
|
||||
sum := sha256.Sum256(b.Data)
|
||||
assert.Equal(t, sum[:], b.Hash)
|
||||
}
|
||||
two.SeedStoredFile(two.RootID(), f)
|
||||
for _, u := range []*User{one, two} {
|
||||
dump := u.Dump()
|
||||
require.Len(t, dump, 1)
|
||||
assert.NoError(t, dump[0].Err)
|
||||
assert.Equal(t, "f", dump[0].Path)
|
||||
assert.True(t, bytes.Equal(content, dump[0].Content))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package protontest
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/rclone/rclone/backend/protondrive/api"
|
||||
)
|
||||
|
||||
// Volume event types as the API encodes them.
|
||||
const (
|
||||
EventDelete = 0
|
||||
EventCreate = 1
|
||||
EventUpdate = 2
|
||||
EventUpdateMetadata = 3
|
||||
)
|
||||
|
||||
// defaultEventsPageSize is the number of events per page unless changed
|
||||
// by SetEventsPageSize.
|
||||
const defaultEventsPageSize = 50
|
||||
|
||||
// Event is a change to a link as the volume events route reports it.
|
||||
// Every change through the API or a test mutator such as SeedFile or
|
||||
// SetParent appends one, as Proton does: Create when a link becomes
|
||||
// active (an upload committed, a folder made or copied), Update when a
|
||||
// new revision is committed or a test mutator changes the link's
|
||||
// content or keys, UpdateMetadata when the link is renamed, moved or
|
||||
// trashed, and Delete for every link emptying the trash removes,
|
||||
// descendants included.
|
||||
//
|
||||
// As on Proton, ParentLinkID, IsShared and IsTrashed are the link's
|
||||
// state when the events are read, not when the change was made: a link
|
||||
// deleted for good has no parent and isn't trashed. Events added by
|
||||
// InjectEvent keep their own fields.
|
||||
type Event struct {
|
||||
Type int
|
||||
LinkID string
|
||||
ParentLinkID string // empty for none
|
||||
IsShared bool
|
||||
IsTrashed bool
|
||||
}
|
||||
|
||||
// loggedEvent is an Event with its ID.
|
||||
type loggedEvent struct {
|
||||
id string
|
||||
Event
|
||||
injected bool // whether Event is reported as given, not with the link's state
|
||||
}
|
||||
|
||||
// eventLog is a volume's events, oldest first.
|
||||
type eventLog struct {
|
||||
entries []loggedEvent
|
||||
latest string // ID of the newest event, or the initial ID
|
||||
cursors map[string]int // events covered by each ID still known
|
||||
}
|
||||
|
||||
// newEventLog returns an empty log with an initial ID.
|
||||
func newEventLog() *eventLog {
|
||||
id := randomID()
|
||||
return &eventLog{latest: id, cursors: map[string]int{id: 0}}
|
||||
}
|
||||
|
||||
// add appends e with a new ID.
|
||||
func (l *eventLog) add(e loggedEvent) {
|
||||
id := randomID()
|
||||
e.id = id
|
||||
l.entries = append(l.entries, e)
|
||||
l.latest = id
|
||||
l.cursors[id] = len(l.entries)
|
||||
}
|
||||
|
||||
// logLink appends an event of type typ for link l.
|
||||
func (d *drive) logLink(typ int, l *link) {
|
||||
d.events.add(loggedEvent{Event: Event{Type: typ, LinkID: l.id}})
|
||||
}
|
||||
|
||||
// reported returns e as the events route reports it now.
|
||||
func (d *drive) reported(e loggedEvent) Event {
|
||||
if e.injected {
|
||||
return e.Event
|
||||
}
|
||||
out := Event{Type: e.Type, LinkID: e.LinkID}
|
||||
if l := d.links[e.LinkID]; l != nil {
|
||||
out.ParentLinkID = l.parentID
|
||||
out.IsTrashed = l.state == linkStateTrashed
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type latestEventResponse struct {
|
||||
EventID string
|
||||
Code int
|
||||
}
|
||||
|
||||
type eventLinkJSON struct {
|
||||
LinkID string
|
||||
ParentLinkID *string
|
||||
IsShared bool
|
||||
IsTrashed bool
|
||||
}
|
||||
|
||||
type eventJSON struct {
|
||||
EventID string
|
||||
EventType int
|
||||
Link eventLinkJSON
|
||||
}
|
||||
|
||||
type invitationJSON struct {
|
||||
LinkID string
|
||||
}
|
||||
|
||||
type eventsResponse struct {
|
||||
Events []eventJSON
|
||||
ConvertibleExternalInvitations []invitationJSON
|
||||
EventID string
|
||||
More bool
|
||||
Refresh bool
|
||||
DisableSdkQuotaChecks bool
|
||||
Code int
|
||||
}
|
||||
|
||||
// registerEvents registers the volume events routes.
|
||||
func (s *Server) registerEvents() {
|
||||
s.handleDrive("GET", "/drive/volumes/{volumeID}/events/latest", s.handleLatestEvent)
|
||||
s.handleDrive("GET", "/drive/v2/volumes/{volumeID}/events/{eventID}", s.handleEvents)
|
||||
}
|
||||
|
||||
// handleLatestEvent returns the ID of the volume's newest event.
|
||||
func (s *Server) handleLatestEvent(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
||||
writeJSON(w, http.StatusOK, &latestEventResponse{EventID: d.events.latest, Code: api.CodeOK})
|
||||
}
|
||||
|
||||
// handleEvents returns a page of the volume's events after an event
|
||||
// ID, or Refresh with the newest ID if that ID is unknown or forgotten.
|
||||
func (s *Server) handleEvents(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
||||
log := d.events
|
||||
resp := &eventsResponse{
|
||||
Events: []eventJSON{},
|
||||
ConvertibleExternalInvitations: []invitationJSON{},
|
||||
EventID: log.latest,
|
||||
Code: api.CodeOK,
|
||||
}
|
||||
start, ok := log.cursors[r.PathValue("eventID")]
|
||||
if !ok {
|
||||
resp.Refresh = true
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
return
|
||||
}
|
||||
end := min(start+s.eventsPageSize, len(log.entries))
|
||||
for _, logged := range log.entries[start:end] {
|
||||
e := d.reported(logged)
|
||||
resp.Events = append(resp.Events, eventJSON{
|
||||
EventID: logged.id,
|
||||
EventType: e.Type,
|
||||
Link: eventLinkJSON{
|
||||
LinkID: e.LinkID,
|
||||
ParentLinkID: nullable(e.ParentLinkID),
|
||||
IsShared: e.IsShared,
|
||||
IsTrashed: e.IsTrashed,
|
||||
},
|
||||
})
|
||||
}
|
||||
if end > start {
|
||||
resp.EventID = log.entries[end-1].id
|
||||
}
|
||||
resp.More = end < len(log.entries)
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// SetEventsPageSize sets the number of events per page of the volume
|
||||
// events route; n of 0 or less restores the default.
|
||||
func (s *Server) SetEventsPageSize(n int) {
|
||||
if n <= 0 {
|
||||
n = defaultEventsPageSize
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.eventsPageSize = n
|
||||
}
|
||||
|
||||
// ExpireEvents forgets every event ID of u's volume but the newest, so
|
||||
// a client polling from an older one is told to refresh.
|
||||
func (s *Server) ExpireEvents(u *User) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
log := u.mustDriveLocked().events
|
||||
log.cursors = map[string]int{log.latest: len(log.entries)}
|
||||
}
|
||||
|
||||
// InjectEvent appends e to the events of u's volume. It is reported
|
||||
// with its own fields, whatever the state of its link when read.
|
||||
func (s *Server) InjectEvent(u *User, e Event) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
u.mustDriveLocked().events.add(loggedEvent{Event: e, injected: true})
|
||||
}
|
||||
|
||||
// Events returns every event of u's volume, oldest first, including
|
||||
// those ExpireEvents forgot, as the events route would report them now.
|
||||
func (s *Server) Events(u *User) []Event {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
d := u.mustDriveLocked()
|
||||
out := make([]Event, 0, len(d.events.entries))
|
||||
for _, e := range d.events.entries {
|
||||
out = append(out, d.reported(e))
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
package protontest
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rclone/rclone/backend/protondrive/api"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// latestEvent returns the start cursor of u's volume as sess.
|
||||
func latestEvent(t *testing.T, s *Server, sess Session, u *User) string {
|
||||
t.Helper()
|
||||
var resp latestEventResponse
|
||||
status, body := getJSON(t, s, sess, "/drive/volumes/"+u.VolumeID()+"/events/latest", &resp)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
require.Equal(t, api.CodeOK, resp.Code)
|
||||
require.NotEmpty(t, resp.EventID)
|
||||
return resp.EventID
|
||||
}
|
||||
|
||||
// eventsPage returns the page of u's volume events after cursor.
|
||||
func eventsPage(t *testing.T, s *Server, sess Session, u *User, cursor string) eventsResponse {
|
||||
t.Helper()
|
||||
var resp eventsResponse
|
||||
status, body := getJSON(t, s, sess, "/drive/v2/volumes/"+u.VolumeID()+"/events/"+cursor, &resp)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
require.Equal(t, api.CodeOK, resp.Code)
|
||||
return resp
|
||||
}
|
||||
|
||||
// eventsSince returns every event of u's volume after cursor, following
|
||||
// More.
|
||||
func eventsSince(t *testing.T, s *Server, sess Session, u *User, cursor string) []eventJSON {
|
||||
t.Helper()
|
||||
var out []eventJSON
|
||||
for {
|
||||
resp := eventsPage(t, s, sess, u, cursor)
|
||||
require.False(t, resp.Refresh)
|
||||
out = append(out, resp.Events...)
|
||||
cursor = resp.EventID
|
||||
if !resp.More {
|
||||
return out
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventsLatestAndPage(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
sess := s.NewSession(u)
|
||||
start := latestEvent(t, s, sess, u)
|
||||
|
||||
resp := eventsPage(t, s, sess, u, start)
|
||||
assert.Empty(t, resp.Events)
|
||||
assert.Equal(t, start, resp.EventID)
|
||||
assert.False(t, resp.More)
|
||||
assert.False(t, resp.Refresh)
|
||||
|
||||
status, body := sendJSON(t, s, sess, "POST", "/drive/v2/volumes/"+u.VolumeID()+"/folders", newFolderRequest(u, u.RootID(), "dir"))
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
var created createFolderResponse
|
||||
require.NoError(t, json.Unmarshal(body, &created))
|
||||
|
||||
resp = eventsPage(t, s, sess, u, start)
|
||||
require.Len(t, resp.Events, 1)
|
||||
e := resp.Events[0]
|
||||
assert.Equal(t, EventCreate, e.EventType)
|
||||
assert.Equal(t, created.Folder.ID, e.Link.LinkID)
|
||||
require.NotNil(t, e.Link.ParentLinkID)
|
||||
assert.Equal(t, u.RootID(), *e.Link.ParentLinkID)
|
||||
assert.False(t, e.Link.IsShared)
|
||||
assert.False(t, e.Link.IsTrashed)
|
||||
assert.NotEqual(t, start, e.EventID)
|
||||
assert.Equal(t, e.EventID, resp.EventID)
|
||||
assert.False(t, resp.More)
|
||||
assert.False(t, resp.Refresh)
|
||||
assert.Equal(t, e.EventID, latestEvent(t, s, sess, u))
|
||||
|
||||
resp = eventsPage(t, s, sess, u, e.EventID)
|
||||
assert.Empty(t, resp.Events)
|
||||
assert.Equal(t, e.EventID, resp.EventID)
|
||||
|
||||
// Field names are Proton's.
|
||||
var raw map[string]any
|
||||
_, body = getJSON(t, s, sess, "/drive/v2/volumes/"+u.VolumeID()+"/events/"+start, &raw)
|
||||
assert.Subset(t, keysOf(t, raw), []string{"Code", "Events", "EventID", "More", "Refresh"})
|
||||
events, ok := raw["Events"].([]any)
|
||||
require.True(t, ok, "body: %s", body)
|
||||
require.Len(t, events, 1)
|
||||
assert.ElementsMatch(t, []string{"EventID", "EventType", "Link"}, keysOf(t, events[0]))
|
||||
assert.ElementsMatch(t, []string{"LinkID", "ParentLinkID", "IsShared", "IsTrashed"}, keysOf(t, events[0].(map[string]any)["Link"]))
|
||||
}
|
||||
|
||||
func TestEventsPerMutation(t *testing.T) {
|
||||
type event struct {
|
||||
Type int
|
||||
LinkID string
|
||||
ParentID string
|
||||
IsTrashed bool
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
// do makes a change and returns the events it expects.
|
||||
do func(t *testing.T, x *renameMoveCopy) []event
|
||||
}{
|
||||
{"create folder", func(t *testing.T, x *renameMoveCopy) []event {
|
||||
status, body := sendJSON(t, x.s, x.sess, "POST", "/drive/v2/volumes/"+x.volume+"/folders", newFolderRequest(x.u, x.a, "new"))
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
var resp createFolderResponse
|
||||
require.NoError(t, json.Unmarshal(body, &resp))
|
||||
return []event{{EventCreate, resp.Folder.ID, x.a, false}}
|
||||
}},
|
||||
{"upload commit", func(t *testing.T, x *renameMoveCopy) []event {
|
||||
up := &uploader{t: t, s: x.s, u: x.u, sess: x.sess, volume: x.volume}
|
||||
f := up.newFileRequest("up")
|
||||
up.create(f)
|
||||
blocks := f.encrypt([]byte("content"))
|
||||
up.uploadAll(f, blocks)
|
||||
status, body := up.commit(f, f.commitRequest(blocks))
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
return []event{{EventCreate, f.linkID, x.u.RootID(), false}}
|
||||
}},
|
||||
{"new revision", func(t *testing.T, x *renameMoveCopy) []event {
|
||||
up := &uploader{t: t, s: x.s, u: x.u, sess: x.sess, volume: x.volume}
|
||||
f := up.newFileRequest("up")
|
||||
up.create(f)
|
||||
blocks := f.encrypt([]byte("one"))
|
||||
up.uploadAll(f, blocks)
|
||||
status, body := up.commit(f, f.commitRequest(blocks))
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
|
||||
current := f.revID
|
||||
uid := testClientUID
|
||||
status, body = up.send("POST", "/drive/v2/volumes/"+x.volume+"/files/"+f.linkID+"/revisions", &createRevisionRequest{CurrentRevisionID: ¤t, ClientUID: &uid})
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
var resp createRevisionResponse
|
||||
require.NoError(t, json.Unmarshal(body, &resp))
|
||||
f.revID = resp.Revision.ID
|
||||
up.loadCode(f)
|
||||
blocks = f.encrypt([]byte("two"))
|
||||
up.uploadAll(f, blocks)
|
||||
status, body = up.commit(f, f.commitRequest(blocks))
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
return []event{
|
||||
{EventCreate, f.linkID, x.u.RootID(), false},
|
||||
{EventUpdate, f.linkID, x.u.RootID(), false},
|
||||
}
|
||||
}},
|
||||
{"rename", func(t *testing.T, x *renameMoveCopy) []event {
|
||||
email, hash, original := x.u.Email(), lookupHash([]byte("k"), "new"), x.hash(x.f)
|
||||
status, body := sendJSON(t, x.s, x.sess, "PUT", "/drive/v2/volumes/"+x.volume+"/links/"+x.f+"/rename",
|
||||
&renameRequest{Name: x.validMsg, Hash: &hash, NameSignatureEmail: &email, OriginalHash: &original})
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
return []event{{EventUpdateMetadata, x.f, x.a, false}}
|
||||
}},
|
||||
{"move", func(t *testing.T, x *renameMoveCopy) []event {
|
||||
email := x.u.Email()
|
||||
status, body := sendJSON(t, x.s, x.sess, "PUT", "/drive/v2/volumes/"+x.volume+"/links/"+x.f+"/move", &moveRequest{
|
||||
Name: x.validMsg, NodePassphrase: x.validMsg, Hash: lookupHash([]byte("k"), "new"),
|
||||
ParentLinkID: x.b, OriginalHash: x.hash(x.f), NameSignatureEmail: &email,
|
||||
})
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
return []event{{EventUpdateMetadata, x.f, x.b, false}}
|
||||
}},
|
||||
{"copy", func(t *testing.T, x *renameMoveCopy) []event {
|
||||
email := x.u.Email()
|
||||
status, body := sendJSON(t, x.s, x.sess, "POST", "/drive/volumes/"+x.volume+"/links/"+x.f+"/copy", ©Request{
|
||||
Name: x.validMsg, NodePassphrase: x.validMsg, Hash: lookupHash([]byte("k"), "copy"),
|
||||
TargetVolumeID: x.volume, TargetParentLinkID: x.b, NameSignatureEmail: &email,
|
||||
})
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
var resp copyResponse
|
||||
require.NoError(t, json.Unmarshal(body, &resp))
|
||||
return []event{{EventCreate, resp.LinkID, x.b, false}}
|
||||
}},
|
||||
{"trash", func(t *testing.T, x *renameMoveCopy) []event {
|
||||
var resp multiResponse
|
||||
status := postJSON(t, x.s, "/drive/v2/volumes/"+x.volume+"/trash_multiple", sessionHeader(x.sess), &linksRequest{LinkIDs: []string{x.f}}, &resp)
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
return []event{{EventUpdateMetadata, x.f, x.a, true}}
|
||||
}},
|
||||
{"create then trash", func(t *testing.T, x *renameMoveCopy) []event {
|
||||
status, body := sendJSON(t, x.s, x.sess, "POST", "/drive/v2/volumes/"+x.volume+"/folders", newFolderRequest(x.u, x.a, "new"))
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
var created createFolderResponse
|
||||
require.NoError(t, json.Unmarshal(body, &created))
|
||||
var resp multiResponse
|
||||
status = postJSON(t, x.s, "/drive/v2/volumes/"+x.volume+"/trash_multiple", sessionHeader(x.sess), &linksRequest{LinkIDs: []string{created.Folder.ID}}, &resp)
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
// Both report the link as it is when read.
|
||||
return []event{{EventCreate, created.Folder.ID, x.a, true}, {EventUpdateMetadata, created.Folder.ID, x.a, true}}
|
||||
}},
|
||||
{"empty trash", func(t *testing.T, x *renameMoveCopy) []event {
|
||||
var resp multiResponse
|
||||
status := postJSON(t, x.s, "/drive/v2/volumes/"+x.volume+"/trash_multiple", sessionHeader(x.sess), &linksRequest{LinkIDs: []string{x.f}}, &resp)
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
status, body := sendJSON(t, x.s, x.sess, "DELETE", "/drive/volumes/"+x.volume+"/trash", nil)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
// A link deleted for good has no parent and isn't trashed.
|
||||
return []event{{EventUpdateMetadata, x.f, "", false}, {EventDelete, x.f, "", false}}
|
||||
}},
|
||||
{"empty trash of a folder", func(t *testing.T, x *renameMoveCopy) []event {
|
||||
var resp multiResponse
|
||||
status := postJSON(t, x.s, "/drive/v2/volumes/"+x.volume+"/trash_multiple", sessionHeader(x.sess), &linksRequest{LinkIDs: []string{x.a}}, &resp)
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
status, body := sendJSON(t, x.s, x.sess, "DELETE", "/drive/volumes/"+x.volume+"/trash", nil)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
return []event{
|
||||
{EventUpdateMetadata, x.a, "", false},
|
||||
{EventDelete, x.a, "", false},
|
||||
{EventDelete, x.f, "", false},
|
||||
{EventDelete, x.anon, "", false},
|
||||
}
|
||||
}},
|
||||
{"delete draft", func(t *testing.T, x *renameMoveCopy) []event {
|
||||
up := &uploader{t: t, s: x.s, u: x.u, sess: x.sess, volume: x.volume}
|
||||
f := up.newFileRequest("draft")
|
||||
up.create(f)
|
||||
var resp multiResponse
|
||||
status := postJSON(t, x.s, "/drive/v2/volumes/"+x.volume+"/delete_multiple", sessionHeader(x.sess), &linksRequest{LinkIDs: []string{f.linkID}}, &resp)
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
require.Equal(t, api.CodeOK, resp.Responses[0].Response.Code)
|
||||
return nil
|
||||
}},
|
||||
{"delete draft revision", func(t *testing.T, x *renameMoveCopy) []event {
|
||||
up := &uploader{t: t, s: x.s, u: x.u, sess: x.sess, volume: x.volume}
|
||||
f := up.newFileRequest("up")
|
||||
up.create(f)
|
||||
blocks := f.encrypt([]byte("one"))
|
||||
up.uploadAll(f, blocks)
|
||||
status, body := up.commit(f, f.commitRequest(blocks))
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
|
||||
current := f.revID
|
||||
uid := testClientUID
|
||||
path := "/drive/v2/volumes/" + x.volume + "/files/" + f.linkID + "/revisions"
|
||||
status, body = up.send("POST", path, &createRevisionRequest{CurrentRevisionID: ¤t, ClientUID: &uid})
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
var resp createRevisionResponse
|
||||
require.NoError(t, json.Unmarshal(body, &resp))
|
||||
status, body = up.send("DELETE", path+"/"+resp.Revision.ID, nil)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
return []event{{EventCreate, f.linkID, x.u.RootID(), false}}
|
||||
}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
x := newRenameMoveCopy(t)
|
||||
start := latestEvent(t, x.s, x.sess, x.u)
|
||||
want := tc.do(t, x)
|
||||
var got []event
|
||||
for _, e := range eventsSince(t, x.s, x.sess, x.u, start) {
|
||||
parent := ""
|
||||
if e.Link.ParentLinkID != nil {
|
||||
parent = *e.Link.ParentLinkID
|
||||
}
|
||||
got = append(got, event{e.EventType, e.Link.LinkID, parent, e.Link.IsTrashed})
|
||||
}
|
||||
assert.Equal(t, want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventsCopyFolder(t *testing.T) {
|
||||
x := newRenameMoveCopy(t)
|
||||
start := latestEvent(t, x.s, x.sess, x.u)
|
||||
email := x.u.Email()
|
||||
status, body := sendJSON(t, x.s, x.sess, "POST", "/drive/volumes/"+x.volume+"/links/"+x.a+"/copy", ©Request{
|
||||
Name: x.validMsg, NodePassphrase: x.validMsg, Hash: lookupHash([]byte("k"), "copy"),
|
||||
TargetVolumeID: x.volume, TargetParentLinkID: x.b, NameSignatureEmail: &email,
|
||||
})
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
var resp copyResponse
|
||||
require.NoError(t, json.Unmarshal(body, &resp))
|
||||
|
||||
// Every link the copy makes is created.
|
||||
events := eventsSince(t, x.s, x.sess, x.u, start)
|
||||
require.Len(t, events, 3)
|
||||
parents := map[string]string{}
|
||||
for _, e := range events {
|
||||
assert.Equal(t, EventCreate, e.EventType)
|
||||
parents[e.Link.LinkID] = *e.Link.ParentLinkID
|
||||
}
|
||||
assert.Equal(t, x.b, parents[resp.LinkID])
|
||||
for id, parent := range parents {
|
||||
if id != resp.LinkID {
|
||||
assert.Equal(t, resp.LinkID, parent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventsPaging(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
sess := s.NewSession(u)
|
||||
s.SetEventsPageSize(2)
|
||||
cursor := latestEvent(t, s, sess, u)
|
||||
var want []string
|
||||
for _, name := range []string{"a", "b", "c", "d", "e"} {
|
||||
want = append(want, u.SeedFolder(u.RootID(), name))
|
||||
}
|
||||
|
||||
var got []string
|
||||
seen := map[string]bool{cursor: true}
|
||||
for i, wantMore := range []bool{true, true, false} {
|
||||
resp := eventsPage(t, s, sess, u, cursor)
|
||||
require.False(t, resp.Refresh)
|
||||
assert.Equal(t, wantMore, resp.More, "call %d", i)
|
||||
require.Len(t, resp.Events, min(2, len(want)-len(got)), "call %d", i)
|
||||
for _, e := range resp.Events {
|
||||
assert.False(t, seen[e.EventID], "duplicate event ID %s", e.EventID)
|
||||
seen[e.EventID] = true
|
||||
got = append(got, e.Link.LinkID)
|
||||
}
|
||||
assert.Equal(t, resp.Events[len(resp.Events)-1].EventID, resp.EventID)
|
||||
cursor = resp.EventID
|
||||
}
|
||||
assert.Equal(t, want, got)
|
||||
assert.Equal(t, cursor, latestEvent(t, s, sess, u))
|
||||
}
|
||||
|
||||
// TestEventsPageSizeDefault checks a page size of 0 or less restores
|
||||
// the default rather than serving empty pages with More set.
|
||||
func TestEventsPageSizeDefault(t *testing.T) {
|
||||
for _, n := range []int{0, -1} {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
sess := s.NewSession(u)
|
||||
s.SetEventsPageSize(n)
|
||||
cursor := latestEvent(t, s, sess, u)
|
||||
id := u.SeedFolder(u.RootID(), "a")
|
||||
resp := eventsPage(t, s, sess, u, cursor)
|
||||
assert.False(t, resp.More, "page size %d", n)
|
||||
require.Len(t, resp.Events, 1, "page size %d", n)
|
||||
assert.Equal(t, id, resp.Events[0].Link.LinkID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventsRefresh(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
sess := s.NewSession(u)
|
||||
old := latestEvent(t, s, sess, u)
|
||||
u.SeedFolder(u.RootID(), "a")
|
||||
s.ExpireEvents(u)
|
||||
newest := latestEvent(t, s, sess, u)
|
||||
assert.NotEqual(t, old, newest)
|
||||
|
||||
resp := eventsPage(t, s, sess, u, old)
|
||||
assert.True(t, resp.Refresh)
|
||||
assert.Equal(t, newest, resp.EventID)
|
||||
assert.Empty(t, resp.Events)
|
||||
|
||||
resp = eventsPage(t, s, sess, u, "unknown")
|
||||
assert.True(t, resp.Refresh)
|
||||
assert.Equal(t, newest, resp.EventID)
|
||||
|
||||
// The newest cursor still works, and so do the ones after it.
|
||||
resp = eventsPage(t, s, sess, u, newest)
|
||||
assert.False(t, resp.Refresh)
|
||||
assert.Empty(t, resp.Events)
|
||||
id := u.SeedFolder(u.RootID(), "b")
|
||||
events := eventsSince(t, s, sess, u, newest)
|
||||
require.Len(t, events, 1)
|
||||
assert.Equal(t, id, events[0].Link.LinkID)
|
||||
}
|
||||
|
||||
func TestEventsVolumeGone(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
sess := s.NewSession(u)
|
||||
cursor := latestEvent(t, s, sess, u)
|
||||
for _, path := range []string{
|
||||
"/drive/volumes/unknown/events/latest",
|
||||
"/drive/v2/volumes/unknown/events/" + cursor,
|
||||
} {
|
||||
status, body := getJSON(t, s, sess, path, nil)
|
||||
requireRejected(t, api.CodeNotExists, status, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventsSeedAppends(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
assert.Empty(t, s.Events(u))
|
||||
dir := u.SeedFolder(u.RootID(), "dir")
|
||||
id := u.SeedFile(u.RootID(), "f", []byte("f"), time.Now())
|
||||
assert.Equal(t, []Event{
|
||||
{Type: EventCreate, LinkID: dir, ParentLinkID: u.RootID()},
|
||||
{Type: EventCreate, LinkID: id, ParentLinkID: u.RootID()},
|
||||
}, s.Events(u))
|
||||
|
||||
u.SeedRevision(id, []byte("g"), time.Now())
|
||||
u.ClaimSize(id, 10)
|
||||
u.Corrupt(id, "name")
|
||||
u.SetParent(id, dir)
|
||||
// Every event reports the link as it is now.
|
||||
assert.Equal(t, []Event{
|
||||
{Type: EventCreate, LinkID: id, ParentLinkID: dir},
|
||||
{Type: EventUpdate, LinkID: id, ParentLinkID: dir},
|
||||
{Type: EventUpdate, LinkID: id, ParentLinkID: dir},
|
||||
{Type: EventUpdate, LinkID: id, ParentLinkID: dir},
|
||||
{Type: EventUpdateMetadata, LinkID: id, ParentLinkID: dir},
|
||||
}, s.Events(u)[1:])
|
||||
u.ForgeRootSigner(u, u.Email())
|
||||
assert.Equal(t, Event{Type: EventUpdate, LinkID: u.RootID()}, s.Events(u)[6])
|
||||
|
||||
// An injected event is served as given, not with its link's state.
|
||||
sess := s.NewSession(u)
|
||||
cursor := latestEvent(t, s, sess, u)
|
||||
s.InjectEvent(u, Event{Type: EventUpdateMetadata, LinkID: dir, IsShared: true, IsTrashed: true})
|
||||
events := eventsSince(t, s, sess, u, cursor)
|
||||
require.Len(t, events, 1)
|
||||
assert.Equal(t, EventUpdateMetadata, events[0].EventType)
|
||||
assert.Equal(t, dir, events[0].Link.LinkID)
|
||||
assert.Nil(t, events[0].Link.ParentLinkID)
|
||||
assert.True(t, events[0].Link.IsShared)
|
||||
assert.True(t, events[0].Link.IsTrashed)
|
||||
assert.Equal(t, Event{Type: EventUpdateMetadata, LinkID: dir, IsShared: true, IsTrashed: true}, s.Events(u)[len(s.Events(u))-1])
|
||||
}
|
||||
@@ -0,0 +1,767 @@
|
||||
package protontest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/ProtonMail/go-crypto/openpgp/armor"
|
||||
"github.com/ProtonMail/go-crypto/openpgp/packet"
|
||||
"github.com/ProtonMail/go-crypto/openpgp/s2k"
|
||||
"github.com/rclone/rclone/backend/protondrive/api"
|
||||
)
|
||||
|
||||
// OpenPGP packet tags checked in client-written values.
|
||||
const (
|
||||
tagPKESK = 1
|
||||
tagSignature = 2
|
||||
tagSecretKey = 5
|
||||
tagSecretSubkey = 7
|
||||
tagSEIPD = 18
|
||||
)
|
||||
|
||||
// s2kUsageSHA1 is the S2K usage octet of a secret key locked with CFB
|
||||
// and a SHA-1 check, as ordinary (not AEAD) key locking writes.
|
||||
const s2kUsageSHA1 = 254
|
||||
|
||||
// Wire types of the mutating routes, named after and shaped like the
|
||||
// schemas in the SDK's driveTypes.ts.
|
||||
|
||||
type createFolderRequest struct {
|
||||
ParentLinkID string
|
||||
NodeKey string
|
||||
NodeHashKey string
|
||||
NodePassphrase string
|
||||
NodePassphraseSignature string
|
||||
SignatureEmail *string
|
||||
Name string
|
||||
Hash string
|
||||
XAttr *string
|
||||
}
|
||||
|
||||
type folderIDJSON struct {
|
||||
ID string
|
||||
}
|
||||
|
||||
type createFolderResponse struct {
|
||||
Folder folderIDJSON
|
||||
Code int
|
||||
}
|
||||
|
||||
type renameRequest struct {
|
||||
Name string
|
||||
Hash *string
|
||||
NameSignatureEmail *string
|
||||
OriginalHash *string
|
||||
}
|
||||
|
||||
type moveRequest struct {
|
||||
Name string
|
||||
NodePassphrase string
|
||||
Hash string
|
||||
ParentLinkID string
|
||||
OriginalHash string
|
||||
NameSignatureEmail *string
|
||||
ContentHash *string
|
||||
NodePassphraseSignature *string
|
||||
SignatureEmail *string
|
||||
}
|
||||
|
||||
type copyRequest struct {
|
||||
Name string
|
||||
NodePassphrase string
|
||||
Hash string
|
||||
TargetVolumeID string
|
||||
TargetParentLinkID string
|
||||
NameSignatureEmail *string
|
||||
NodePassphraseSignature *string
|
||||
SignatureEmail *string
|
||||
}
|
||||
|
||||
type copyResponse struct {
|
||||
LinkID string
|
||||
Code int
|
||||
}
|
||||
|
||||
type codeJSON struct {
|
||||
Code int
|
||||
Error string `json:",omitempty"`
|
||||
}
|
||||
|
||||
type linkResultJSON struct {
|
||||
LinkID string
|
||||
Response codeJSON
|
||||
}
|
||||
|
||||
type multiResponse struct {
|
||||
Code int
|
||||
Responses []linkResultJSON
|
||||
}
|
||||
|
||||
type checkHashesRequest struct {
|
||||
Hashes []string
|
||||
ClientUID []string
|
||||
}
|
||||
|
||||
type pendingHashJSON struct {
|
||||
Hash string
|
||||
RevisionID string
|
||||
LinkID string
|
||||
ClientUID *string
|
||||
}
|
||||
|
||||
type availableHashesResponse struct {
|
||||
AvailableHashes []string
|
||||
PendingHashes []pendingHashJSON
|
||||
Code int
|
||||
}
|
||||
|
||||
type conflictDetailsJSON struct {
|
||||
ConflictLinkID string
|
||||
ConflictRevisionID *string
|
||||
ConflictDraftRevisionID *string
|
||||
ConflictDraftClientUID *string
|
||||
}
|
||||
|
||||
type conflictResponse struct {
|
||||
Code int
|
||||
Error string
|
||||
Details conflictDetailsJSON
|
||||
}
|
||||
|
||||
// registerMutations registers the routes which change a drive.
|
||||
func (s *Server) registerMutations() {
|
||||
s.handleDrive("POST", "/drive/v2/volumes/{volumeID}/folders", s.handleCreateFolder)
|
||||
s.handleDrive("PUT", "/drive/v2/volumes/{volumeID}/links/{linkID}/rename", s.handleRename)
|
||||
s.handleDrive("PUT", "/drive/v2/volumes/{volumeID}/links/{linkID}/move", s.handleMove)
|
||||
s.handleDrive("POST", "/drive/volumes/{volumeID}/links/{linkID}/copy", s.handleCopy)
|
||||
s.handleDrive("POST", "/drive/v2/volumes/{volumeID}/trash_multiple", s.handleTrash)
|
||||
s.handleDrive("DELETE", "/drive/volumes/{volumeID}/trash", s.handleEmptyTrash)
|
||||
s.handleDrive("POST", "/drive/v2/volumes/{volumeID}/links/{linkID}/checkAvailableHashes", s.handleCheckAvailableHashes)
|
||||
}
|
||||
|
||||
// decodeRequest decodes the JSON body of r into v, or answers HTTP 400
|
||||
// and returns false.
|
||||
func decodeRequest(w http.ResponseWriter, r *http.Request, v any) bool {
|
||||
if err := json.NewDecoder(r.Body).Decode(v); err != nil {
|
||||
writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: bad request body: "+err.Error())
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// writeInvalid answers HTTP 422 code 2001 for a request failing check.
|
||||
func writeInvalid(w http.ResponseWriter, err error) {
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidValue, "protontest: "+err.Error())
|
||||
}
|
||||
|
||||
// writeConflict answers HTTP 422 code 2500 for a request whose name
|
||||
// hash is taken by l.
|
||||
func writeConflict(w http.ResponseWriter, l *link) {
|
||||
details := conflictDetailsJSON{ConflictLinkID: l.id}
|
||||
for _, r := range l.revisions {
|
||||
switch r.state {
|
||||
case revisionStateActive:
|
||||
details.ConflictRevisionID = nullable(r.id)
|
||||
case revisionStateDraft:
|
||||
details.ConflictDraftRevisionID = nullable(r.id)
|
||||
details.ConflictDraftClientUID = nullable(r.clientUID)
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusUnprocessableEntity, &conflictResponse{
|
||||
Code: api.CodeAlreadyExists,
|
||||
Error: "A file or folder with that name already exists",
|
||||
Details: details,
|
||||
})
|
||||
}
|
||||
|
||||
// activeLink returns the active link id, or nil.
|
||||
func (d *drive) activeLink(id string) *link {
|
||||
if l := d.links[id]; l != nil && l.state == linkStateActive {
|
||||
return l
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// activeFolder returns the active folder id, or nil.
|
||||
func (d *drive) activeFolder(id string) *link {
|
||||
if l := d.activeLink(id); l != nil && l.typ == linkTypeFolder {
|
||||
return l
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// conflict returns the link other than except in folder parentID
|
||||
// which is not trashed and has the name hash hash, or nil.
|
||||
func (d *drive) conflict(parentID, hash, except string) *link {
|
||||
for _, l := range d.links {
|
||||
if l.parentID == parentID && l.nameHash == hash && l.state != linkStateTrashed && l.id != except {
|
||||
return l
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// within reports whether link id is ancestorID or below it.
|
||||
func (d *drive) within(id, ancestorID string) bool {
|
||||
for l := d.links[id]; l != nil; l = d.links[l.parentID] {
|
||||
if l.id == ancestorID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// inTrash reports whether l or one of its ancestors is trashed.
|
||||
func (d *drive) inTrash(l *link) bool {
|
||||
for ; l != nil; l = d.links[l.parentID] {
|
||||
if l.state == linkStateTrashed {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ownsEmailLocked reports whether email is one of u's addresses.
|
||||
// srv.mu must be held.
|
||||
func (u *User) ownsEmailLocked(email string) bool {
|
||||
return u.addressByEmailLocked(email) != nil
|
||||
}
|
||||
|
||||
// checkHash returns an error unless hash is a lower-case hex SHA-256.
|
||||
func checkHash(hash string) error {
|
||||
if len(hash) != 64 || strings.ToLower(hash) != hash {
|
||||
return fmt.Errorf("hash %q is not lower-case hex SHA-256", hash)
|
||||
}
|
||||
if _, err := hex.DecodeString(hash); err != nil {
|
||||
return fmt.Errorf("hash %q is not lower-case hex SHA-256", hash)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkSigner returns an error unless email is one of u's addresses.
|
||||
func checkSigner(u *User, field string, email *string) error {
|
||||
if email == nil || !u.ownsEmailLocked(*email) {
|
||||
return fmt.Errorf("%s must be an address of the user", field)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkMessages checks every named armored message with checkMessage.
|
||||
func checkMessages(messages map[string]string) error {
|
||||
for field, armored := range messages {
|
||||
if err := checkMessage(armored); err != nil {
|
||||
return fmt.Errorf("%s: %w", field, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkMessage returns an error unless armored is an OpenPGP message of
|
||||
// v3 PKESKs followed by one SEIPDv1 packet.
|
||||
//
|
||||
// Official clients write names, passphrases, hash keys and extended
|
||||
// attributes in that format and not all of them read SEIPDv2 or v6
|
||||
// PKESKs there, whatever the recipient key accepts.
|
||||
func checkMessage(armored string) error {
|
||||
if armored == "" {
|
||||
return errors.New("missing")
|
||||
}
|
||||
block, err := armor.Decode(strings.NewReader(armored))
|
||||
if err != nil {
|
||||
return fmt.Errorf("not armored: %w", err)
|
||||
}
|
||||
if block.Type != "PGP MESSAGE" {
|
||||
return fmt.Errorf("armor type %q, want PGP MESSAGE", block.Type)
|
||||
}
|
||||
packets := packet.NewOpaqueReader(block.Body)
|
||||
keyPackets, dataPackets := 0, 0
|
||||
for {
|
||||
op, err := packets.Next()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("malformed packet: %w", err)
|
||||
}
|
||||
if dataPackets > 0 {
|
||||
return errors.New("packet after the encrypted data")
|
||||
}
|
||||
version := -1
|
||||
if len(op.Contents) > 0 {
|
||||
version = int(op.Contents[0])
|
||||
}
|
||||
switch op.Tag {
|
||||
case tagPKESK:
|
||||
if version != 3 {
|
||||
return fmt.Errorf("v%d PKESK, want v3", version)
|
||||
}
|
||||
keyPackets++
|
||||
case tagSEIPD:
|
||||
if version != 1 {
|
||||
return fmt.Errorf("SEIPDv%d, want SEIPDv1", version)
|
||||
}
|
||||
dataPackets++
|
||||
default:
|
||||
return fmt.Errorf("unexpected packet with tag %d", op.Tag)
|
||||
}
|
||||
}
|
||||
if keyPackets == 0 || dataPackets == 0 {
|
||||
return errors.New("want PKESKs and an encrypted data packet")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkFolderKey returns an error unless armored is a v4 secret key
|
||||
// whose signatures don't advertise AEAD, with every secret key packet
|
||||
// locked with CFB and an iterated and salted S2K, as official clients
|
||||
// generate folder keys. The official web app can't use a node key
|
||||
// locked with Argon2 or AEAD.
|
||||
func checkFolderKey(armored string) error {
|
||||
return checkNodeKey(armored, false)
|
||||
}
|
||||
|
||||
// checkFileKey returns an error unless armored is a v4 secret key
|
||||
// locked as checkFolderKey requires. Unlike a folder key, a file key
|
||||
// advertises AEAD, for its content.
|
||||
func checkFileKey(armored string) error {
|
||||
return checkNodeKey(armored, true)
|
||||
}
|
||||
|
||||
// checkNodeKey does the work of checkFolderKey and checkFileKey; aead
|
||||
// allows the key to advertise AEAD.
|
||||
func checkNodeKey(armored string, aead bool) error {
|
||||
block, err := armor.Decode(strings.NewReader(armored))
|
||||
if err != nil {
|
||||
return fmt.Errorf("not armored: %w", err)
|
||||
}
|
||||
if block.Type != "PGP PRIVATE KEY BLOCK" {
|
||||
return fmt.Errorf("armor type %q, want PGP PRIVATE KEY BLOCK", block.Type)
|
||||
}
|
||||
packets := packet.NewOpaqueReader(block.Body)
|
||||
secretKeys := 0
|
||||
for {
|
||||
op, err := packets.Next()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("malformed packet: %w", err)
|
||||
}
|
||||
switch op.Tag {
|
||||
case tagSecretKey, tagSecretSubkey:
|
||||
if err := checkSecretKeyPacket(op); err != nil {
|
||||
return err
|
||||
}
|
||||
secretKeys++
|
||||
case tagSignature:
|
||||
p, err := op.Parse()
|
||||
sig, ok := p.(*packet.Signature)
|
||||
if err != nil || !ok {
|
||||
return fmt.Errorf("malformed signature: %v", err)
|
||||
}
|
||||
if !aead && (sig.SEIPDv2 || len(sig.PreferredCipherSuites) > 0) {
|
||||
return errors.New("key advertises AEAD (SEIPDv2)")
|
||||
}
|
||||
}
|
||||
}
|
||||
if secretKeys == 0 {
|
||||
return errors.New("no secret key")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkSecretKeyPacket checks one secret key or subkey packet for
|
||||
// checkNodeKey.
|
||||
func checkSecretKeyPacket(op *packet.OpaquePacket) error {
|
||||
if len(op.Contents) == 0 || op.Contents[0] != 4 {
|
||||
return errors.New("not a v4 key")
|
||||
}
|
||||
p, err := op.Parse()
|
||||
pk, ok := p.(*packet.PrivateKey)
|
||||
if err != nil || !ok {
|
||||
return fmt.Errorf("malformed secret key: %v", err)
|
||||
}
|
||||
// The packet starts with the public key body, which a v4 key hashes
|
||||
// after 0x99 and a two-octet length.
|
||||
var pub bytes.Buffer
|
||||
if err := pk.PublicKey.SerializeForHash(&pub); err != nil {
|
||||
return fmt.Errorf("malformed secret key: %w", err)
|
||||
}
|
||||
rest := op.Contents[pub.Len()-3:]
|
||||
if len(rest) < 3 {
|
||||
return errors.New("malformed secret key: truncated")
|
||||
}
|
||||
switch usage := rest[0]; usage {
|
||||
case s2kUsageSHA1:
|
||||
case 0:
|
||||
return errors.New("secret key is not locked")
|
||||
case 253:
|
||||
return errors.New("secret key is locked with AEAD")
|
||||
default:
|
||||
return fmt.Errorf("secret key S2K usage %d, want %d", usage, s2kUsageSHA1)
|
||||
}
|
||||
if mode := s2k.Mode(rest[2]); mode != s2k.IteratedSaltedS2K {
|
||||
return fmt.Errorf("secret key S2K mode %d, want iterated and salted", mode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// keySignature returns the node passphrase signature and its signer
|
||||
// that l has once moved or copied, given the request's sig and email.
|
||||
//
|
||||
// As the SDK's moveNode and copyNode, a request gives them if and only
|
||||
// if l's key is anonymous: an anonymous key is then signed by the
|
||||
// user, and a signed one keeps its signature, as the passphrase is
|
||||
// unchanged.
|
||||
func keySignature(u *User, l *link, sig, email *string) (string, string, error) {
|
||||
if l.signatureEmail != "" {
|
||||
if (sig != nil && *sig != "") || (email != nil && *email != "") {
|
||||
return "", "", errors.New("NodePassphraseSignature and SignatureEmail must not be given for a signed node")
|
||||
}
|
||||
return l.nodePass.signature, l.signatureEmail, nil
|
||||
}
|
||||
if sig == nil || *sig == "" {
|
||||
return "", "", errors.New("NodePassphraseSignature is required for an anonymous node")
|
||||
}
|
||||
if err := checkSigner(u, "SignatureEmail", email); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return *sig, *email, nil
|
||||
}
|
||||
|
||||
// handleCreateFolder creates a folder from key material the client
|
||||
// generated.
|
||||
func (s *Server) handleCreateFolder(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
||||
var req createFolderRequest
|
||||
if !decodeRequest(w, r, &req) {
|
||||
return
|
||||
}
|
||||
parent := d.activeFolder(req.ParentLinkID)
|
||||
if parent == nil {
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Parent folder not found")
|
||||
return
|
||||
}
|
||||
messages := map[string]string{
|
||||
"Name": req.Name,
|
||||
"NodePassphrase": req.NodePassphrase,
|
||||
"NodeHashKey": req.NodeHashKey,
|
||||
}
|
||||
if req.XAttr != nil {
|
||||
messages["XAttr"] = *req.XAttr
|
||||
}
|
||||
err := errors.Join(
|
||||
checkHash(req.Hash),
|
||||
checkSigner(u, "SignatureEmail", req.SignatureEmail),
|
||||
checkMessages(messages),
|
||||
)
|
||||
if err == nil && req.NodePassphraseSignature == "" {
|
||||
err = errors.New("NodePassphraseSignature is required")
|
||||
}
|
||||
if err == nil {
|
||||
err = annotateField("NodeKey", checkFolderKey(req.NodeKey))
|
||||
}
|
||||
if err != nil {
|
||||
writeInvalid(w, err)
|
||||
return
|
||||
}
|
||||
if other := d.conflict(parent.id, req.Hash, ""); other != nil {
|
||||
writeConflict(w, other)
|
||||
return
|
||||
}
|
||||
now := time.Now().Unix()
|
||||
l := &link{
|
||||
id: randomID(),
|
||||
parentID: parent.id,
|
||||
typ: linkTypeFolder,
|
||||
state: linkStateActive,
|
||||
createTime: now,
|
||||
modifyTime: now,
|
||||
name: req.Name,
|
||||
nameHash: req.Hash,
|
||||
nodeKey: req.NodeKey,
|
||||
nodePass: sealedPassphrase{armored: req.NodePassphrase, signature: req.NodePassphraseSignature},
|
||||
signatureEmail: *req.SignatureEmail,
|
||||
nameSignatureEmail: *req.SignatureEmail,
|
||||
hashKey: req.NodeHashKey,
|
||||
}
|
||||
if req.XAttr != nil {
|
||||
l.xattr = *req.XAttr
|
||||
}
|
||||
d.addLink(l)
|
||||
d.logLink(EventCreate, l)
|
||||
s.lagLocked(l.id, nil)
|
||||
writeJSON(w, http.StatusOK, &createFolderResponse{Folder: folderIDJSON{ID: l.id}, Code: api.CodeOK})
|
||||
}
|
||||
|
||||
// annotateField returns err prefixed with field, or nil.
|
||||
func annotateField(field string, err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("%s: %w", field, err)
|
||||
}
|
||||
|
||||
// handleRename renames a link within its folder.
|
||||
func (s *Server) handleRename(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
||||
var req renameRequest
|
||||
if !decodeRequest(w, r, &req) {
|
||||
return
|
||||
}
|
||||
l := d.activeLink(r.PathValue("linkID"))
|
||||
switch {
|
||||
case l == nil:
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "File or folder not found")
|
||||
return
|
||||
case l.parentID == "":
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidRequirements, "protontest: the root can't be renamed")
|
||||
return
|
||||
case req.OriginalHash == nil || *req.OriginalHash != l.nameHash:
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidRequirements, "protontest: OriginalHash doesn't match: the node changed")
|
||||
return
|
||||
}
|
||||
hash := ""
|
||||
if req.Hash != nil {
|
||||
hash = *req.Hash
|
||||
}
|
||||
err := errors.Join(
|
||||
checkHash(hash),
|
||||
checkSigner(u, "NameSignatureEmail", req.NameSignatureEmail),
|
||||
checkMessages(map[string]string{"Name": req.Name}),
|
||||
)
|
||||
if err != nil {
|
||||
writeInvalid(w, err)
|
||||
return
|
||||
}
|
||||
if other := d.conflict(l.parentID, hash, l.id); other != nil {
|
||||
writeConflict(w, other)
|
||||
return
|
||||
}
|
||||
l.name, l.nameHash, l.nameSignatureEmail = req.Name, hash, *req.NameSignatureEmail
|
||||
l.modifyTime = time.Now().Unix()
|
||||
d.logLink(EventUpdateMetadata, l)
|
||||
writeJSON(w, http.StatusOK, &codeJSON{Code: api.CodeOK})
|
||||
}
|
||||
|
||||
// handleMove moves a link to another folder, possibly renaming it.
|
||||
func (s *Server) handleMove(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
||||
var req moveRequest
|
||||
if !decodeRequest(w, r, &req) {
|
||||
return
|
||||
}
|
||||
l := d.activeLink(r.PathValue("linkID"))
|
||||
parent := d.activeFolder(req.ParentLinkID)
|
||||
switch {
|
||||
case l == nil:
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "File or folder not found")
|
||||
return
|
||||
case l.parentID == "":
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidRequirements, "protontest: the root can't be moved")
|
||||
return
|
||||
case parent == nil:
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Parent folder not found")
|
||||
return
|
||||
case d.within(parent.id, l.id):
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidRequirements, "protontest: a folder can't be moved into itself")
|
||||
return
|
||||
case req.OriginalHash != l.nameHash:
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidRequirements, "protontest: OriginalHash doesn't match: the node changed")
|
||||
return
|
||||
}
|
||||
err := errors.Join(
|
||||
checkHash(req.Hash),
|
||||
checkSigner(u, "NameSignatureEmail", req.NameSignatureEmail),
|
||||
checkMessages(map[string]string{"Name": req.Name, "NodePassphrase": req.NodePassphrase}),
|
||||
)
|
||||
if err != nil {
|
||||
writeInvalid(w, err)
|
||||
return
|
||||
}
|
||||
sig, signer, err := keySignature(u, l, req.NodePassphraseSignature, req.SignatureEmail)
|
||||
if err != nil {
|
||||
writeInvalid(w, err)
|
||||
return
|
||||
}
|
||||
if other := d.conflict(parent.id, req.Hash, l.id); other != nil {
|
||||
writeConflict(w, other)
|
||||
return
|
||||
}
|
||||
l.parentID, l.name, l.nameHash, l.nameSignatureEmail = parent.id, req.Name, req.Hash, *req.NameSignatureEmail
|
||||
l.nodePass = sealedPassphrase{armored: req.NodePassphrase, signature: sig}
|
||||
l.signatureEmail = signer
|
||||
l.modifyTime = time.Now().Unix()
|
||||
d.logLink(EventUpdateMetadata, l)
|
||||
writeJSON(w, http.StatusOK, &codeJSON{Code: api.CodeOK})
|
||||
}
|
||||
|
||||
// handleCopy copies a link, and a folder's active descendants, into a
|
||||
// folder. Only the name and passphrase of the copy come from the
|
||||
// client; its key, content and descendants are the server's copies.
|
||||
func (s *Server) handleCopy(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
||||
var req copyRequest
|
||||
if !decodeRequest(w, r, &req) {
|
||||
return
|
||||
}
|
||||
l := d.activeLink(r.PathValue("linkID"))
|
||||
parent := d.activeFolder(req.TargetParentLinkID)
|
||||
switch {
|
||||
case l == nil:
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "File or folder not found")
|
||||
return
|
||||
case l.parentID == "":
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidRequirements, "protontest: the root can't be copied")
|
||||
return
|
||||
case req.TargetVolumeID != d.volumeID:
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Volume not found")
|
||||
return
|
||||
case parent == nil:
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Parent folder not found")
|
||||
return
|
||||
case d.within(parent.id, l.id):
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidRequirements, "protontest: a folder can't be copied into itself")
|
||||
return
|
||||
}
|
||||
err := errors.Join(
|
||||
checkHash(req.Hash),
|
||||
checkSigner(u, "NameSignatureEmail", req.NameSignatureEmail),
|
||||
checkMessages(map[string]string{"Name": req.Name, "NodePassphrase": req.NodePassphrase}),
|
||||
)
|
||||
if err != nil {
|
||||
writeInvalid(w, err)
|
||||
return
|
||||
}
|
||||
sig, signer, err := keySignature(u, l, req.NodePassphraseSignature, req.SignatureEmail)
|
||||
if err != nil {
|
||||
writeInvalid(w, err)
|
||||
return
|
||||
}
|
||||
if other := d.conflict(parent.id, req.Hash, ""); other != nil {
|
||||
writeConflict(w, other)
|
||||
return
|
||||
}
|
||||
c := d.copyLink(l, parent.id, time.Now().Unix())
|
||||
c.name, c.nameHash, c.nameSignatureEmail = req.Name, req.Hash, *req.NameSignatureEmail
|
||||
c.nodePass = sealedPassphrase{armored: req.NodePassphrase, signature: sig}
|
||||
c.signatureEmail = signer
|
||||
s.lagLocked(c.id, nil)
|
||||
writeJSON(w, http.StatusOK, ©Response{LinkID: c.id, Code: api.CodeOK})
|
||||
}
|
||||
|
||||
// copyLink stores and returns a copy of l in folder parentID with its
|
||||
// active revision and, for a folder, copies of its active descendants.
|
||||
// Blocks are shared, as they are immutable.
|
||||
func (d *drive) copyLink(l *link, parentID string, now int64) *link {
|
||||
c := *l
|
||||
c.id, c.parentID = randomID(), parentID
|
||||
c.state, c.createTime, c.modifyTime, c.trashTime = linkStateActive, now, now, 0
|
||||
c.revisions = nil
|
||||
if r := l.activeRevision(); r != nil {
|
||||
rc := *r
|
||||
rc.id = randomID()
|
||||
rc.blocks = slices.Clone(r.blocks)
|
||||
c.revisions = []*revision{&rc}
|
||||
}
|
||||
var children []*link
|
||||
for _, child := range d.links {
|
||||
if child.parentID == l.id && child.state == linkStateActive {
|
||||
children = append(children, child)
|
||||
}
|
||||
}
|
||||
sort.Slice(children, func(i, j int) bool { return children[i].seq < children[j].seq })
|
||||
d.addLink(&c)
|
||||
d.logLink(EventCreate, &c)
|
||||
for _, child := range children {
|
||||
d.copyLink(child, c.id, now)
|
||||
}
|
||||
return &c
|
||||
}
|
||||
|
||||
// handleTrash trashes up to 100 links, answering for each.
|
||||
func (s *Server) handleTrash(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
||||
var req linksRequest
|
||||
if !decodeRequest(w, r, &req) {
|
||||
return
|
||||
}
|
||||
if len(req.LinkIDs) > maxLinksPerRequest {
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidValue, fmt.Sprintf("protontest: %d link IDs, at most %d allowed", len(req.LinkIDs), maxLinksPerRequest))
|
||||
return
|
||||
}
|
||||
now := time.Now().Unix()
|
||||
resp := &multiResponse{Code: api.CodeOKMany, Responses: []linkResultJSON{}}
|
||||
for _, id := range req.LinkIDs {
|
||||
result := linkResultJSON{LinkID: id, Response: codeJSON{Code: api.CodeOK}}
|
||||
l := d.activeLink(id)
|
||||
switch {
|
||||
case l == nil:
|
||||
result.Response = codeJSON{Code: api.CodeNotExists, Error: "File or folder not found"}
|
||||
case l.parentID == "":
|
||||
result.Response = codeJSON{Code: api.CodeInvalidRequirements, Error: "protontest: the root can't be trashed"}
|
||||
default:
|
||||
l.state, l.trashTime, l.modifyTime = linkStateTrashed, now, now
|
||||
d.logLink(EventUpdateMetadata, l)
|
||||
}
|
||||
resp.Responses = append(resp.Responses, result)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// handleEmptyTrash deletes every trashed link with its descendants.
|
||||
func (s *Server) handleEmptyTrash(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
||||
var doomed []*link
|
||||
for _, l := range d.links {
|
||||
if d.inTrash(l) {
|
||||
doomed = append(doomed, l)
|
||||
}
|
||||
}
|
||||
sort.Slice(doomed, func(i, j int) bool { return doomed[i].seq < doomed[j].seq })
|
||||
for _, l := range doomed {
|
||||
d.logLink(EventDelete, l)
|
||||
delete(d.links, l.id)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, &codeJSON{Code: api.CodeOK})
|
||||
}
|
||||
|
||||
// handleCheckAvailableHashes reports which name hashes are free in a
|
||||
// folder, and the drafts holding the others unless they belong to one
|
||||
// of the given ClientUIDs.
|
||||
func (s *Server) handleCheckAvailableHashes(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
||||
var req checkHashesRequest
|
||||
if !decodeRequest(w, r, &req) {
|
||||
return
|
||||
}
|
||||
parent := d.activeFolder(r.PathValue("linkID"))
|
||||
if parent == nil {
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Folder not found")
|
||||
return
|
||||
}
|
||||
resp := &availableHashesResponse{AvailableHashes: []string{}, PendingHashes: []pendingHashJSON{}, Code: api.CodeOK}
|
||||
for _, hash := range req.Hashes {
|
||||
other := d.conflict(parent.id, hash, "")
|
||||
if other == nil {
|
||||
resp.AvailableHashes = append(resp.AvailableHashes, hash)
|
||||
continue
|
||||
}
|
||||
if other.state != linkStateDraft {
|
||||
continue
|
||||
}
|
||||
for _, rev := range other.revisions {
|
||||
if rev.state == revisionStateDraft && !slices.Contains(req.ClientUID, rev.clientUID) {
|
||||
resp.PendingHashes = append(resp.PendingHashes, pendingHashJSON{
|
||||
Hash: hash,
|
||||
RevisionID: rev.id,
|
||||
LinkID: other.id,
|
||||
ClientUID: nullable(rev.clientUID),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
@@ -0,0 +1,542 @@
|
||||
package protontest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/ProtonMail/go-crypto/openpgp/armor"
|
||||
"github.com/ProtonMail/go-crypto/openpgp/packet"
|
||||
"github.com/ProtonMail/go-crypto/openpgp/s2k"
|
||||
"github.com/ProtonMail/gopenpgp/v3/crypto"
|
||||
"github.com/ProtonMail/gopenpgp/v3/profile"
|
||||
"github.com/rclone/rclone/backend/protondrive/api"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// sendJSON sends in as JSON with method to path as sess and returns
|
||||
// the HTTP status and body.
|
||||
func sendJSON(t *testing.T, s *Server, sess Session, method, path string, in any) (int, []byte) {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(in)
|
||||
require.NoError(t, err)
|
||||
req, err := http.NewRequest(method, s.URL()+path, bytes.NewReader(body))
|
||||
require.NoError(t, err)
|
||||
for k, v := range sessionHeader(sess) {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
resp, err := s.Client().Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
out, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
return resp.StatusCode, out
|
||||
}
|
||||
|
||||
// requireRejected fails the test unless the response is HTTP 422 with
|
||||
// code, and its message contains each of want.
|
||||
func requireRejected(t *testing.T, code, status int, body []byte, want ...string) {
|
||||
t.Helper()
|
||||
require.Equal(t, http.StatusUnprocessableEntity, status, "body: %s", body)
|
||||
e := decodeError(t, body)
|
||||
assert.Equal(t, code, e.Code, "body: %s", body)
|
||||
for _, w := range want {
|
||||
assert.Contains(t, e.Message, w)
|
||||
}
|
||||
}
|
||||
|
||||
// newFolderRequest returns a create folder request for name in
|
||||
// parentID made as the SDK's createFolder does.
|
||||
func newFolderRequest(u *User, parentID, name string) *createFolderRequest {
|
||||
v := u.view()
|
||||
parentKey, parentHashKey := v.folderKeys(parentID)
|
||||
node := newDriveKey(false)
|
||||
pass := sealPassphrase(node.passphrase, parentKey, v.addrKey)
|
||||
_, hashKey := newHashKey(node.key)
|
||||
xattr := encryptArmored([]byte(`{"Common":{"ModificationTime":"2024-01-02T03:04:05.000Z"}}`), node.key, v.addrKey, true)
|
||||
return &createFolderRequest{
|
||||
ParentLinkID: parentID,
|
||||
NodeKey: node.armored,
|
||||
NodeHashKey: hashKey,
|
||||
NodePassphrase: pass.armored,
|
||||
NodePassphraseSignature: pass.signature,
|
||||
SignatureEmail: &v.email,
|
||||
Name: encryptArmored([]byte(name), parentKey, v.addrKey, false),
|
||||
Hash: lookupHash(parentHashKey, name),
|
||||
XAttr: &xattr,
|
||||
}
|
||||
}
|
||||
|
||||
// messagePackets returns the packets of an armored message.
|
||||
func messagePackets(t *testing.T, armored string) []*packet.OpaquePacket {
|
||||
t.Helper()
|
||||
block, err := armor.Decode(strings.NewReader(armored))
|
||||
require.NoError(t, err)
|
||||
var out []*packet.OpaquePacket
|
||||
r := packet.NewOpaqueReader(block.Body)
|
||||
for {
|
||||
op, err := r.Next()
|
||||
if err == io.EOF {
|
||||
return out
|
||||
}
|
||||
require.NoError(t, err)
|
||||
out = append(out, op)
|
||||
}
|
||||
}
|
||||
|
||||
// armorPackets returns packets as an armored message.
|
||||
func armorPackets(t *testing.T, packets ...*packet.OpaquePacket) string {
|
||||
t.Helper()
|
||||
var out bytes.Buffer
|
||||
w, err := armor.Encode(&out, "PGP MESSAGE", nil)
|
||||
require.NoError(t, err)
|
||||
for _, op := range packets {
|
||||
require.NoError(t, op.Serialize(w))
|
||||
}
|
||||
require.NoError(t, w.Close())
|
||||
return out.String()
|
||||
}
|
||||
|
||||
// aeadMessages returns messages in the formats clients must not write
|
||||
// for names, passphrases, hash keys and extended attributes, by name.
|
||||
func aeadMessages(t *testing.T) map[string]string {
|
||||
t.Helper()
|
||||
// Encrypting to a file key, which advertises AEAD, gives a v6 PKESK
|
||||
// and SEIPDv2, as gopenpgp does unless told otherwise.
|
||||
eh, err := aeadPGP().Encryption().Recipient(newDriveKey(true).key).New()
|
||||
require.NoError(t, err)
|
||||
msg, err := eh.Encrypt([]byte("value"))
|
||||
require.NoError(t, err)
|
||||
armored, err := msg.Armor()
|
||||
require.NoError(t, err)
|
||||
v6 := messagePackets(t, armored)
|
||||
require.Len(t, v6, 2)
|
||||
require.Equal(t, []byte{6, 2}, []byte{v6[0].Contents[0], v6[1].Contents[0]})
|
||||
v3 := messagePackets(t, encryptArmored([]byte("value"), newDriveKey(false).key, nil, false))
|
||||
require.Len(t, v3, 2)
|
||||
require.Equal(t, []byte{3, 1}, []byte{v3[0].Contents[0], v3[1].Contents[0]})
|
||||
return map[string]string{
|
||||
"v6 PKESK and SEIPDv2": armored,
|
||||
"v3 PKESK and SEIPDv2": armorPackets(t, v3[0], v6[1]),
|
||||
"v6 PKESK and SEIPDv1": armorPackets(t, v6[0], v3[1]),
|
||||
}
|
||||
}
|
||||
|
||||
// lockedWith returns a new v4 node key locked by a handle of p.
|
||||
func lockedWith(t *testing.T, p *profile.Custom) string {
|
||||
t.Helper()
|
||||
key, err := crypto.PGP().KeyGeneration().AddUserId(driveKeyName, "").New().GenerateKey()
|
||||
require.NoError(t, err)
|
||||
locked, err := crypto.PGPWithProfile(p).LockKey(key, newPassphrase())
|
||||
require.NoError(t, err)
|
||||
armored, err := locked.Armor()
|
||||
require.NoError(t, err)
|
||||
return armored
|
||||
}
|
||||
|
||||
func TestCreateFolderFormats(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
sess := s.NewSession(u)
|
||||
path := "/drive/v2/volumes/" + u.VolumeID() + "/folders"
|
||||
post := func(req *createFolderRequest) (int, []byte) {
|
||||
return sendJSON(t, s, sess, "POST", path, req)
|
||||
}
|
||||
|
||||
for variant, bad := range aeadMessages(t) {
|
||||
for field, spoil := range map[string]func(req *createFolderRequest){
|
||||
"Name": func(req *createFolderRequest) { req.Name = bad },
|
||||
"NodePassphrase": func(req *createFolderRequest) { req.NodePassphrase = bad },
|
||||
"NodeHashKey": func(req *createFolderRequest) { req.NodeHashKey = bad },
|
||||
"XAttr": func(req *createFolderRequest) { req.XAttr = &bad },
|
||||
} {
|
||||
t.Run(field+" "+variant, func(t *testing.T) {
|
||||
req := newFolderRequest(u, u.RootID(), "dir")
|
||||
spoil(req)
|
||||
status, body := post(req)
|
||||
requireRejected(t, api.CodeInvalidValue, status, body, field)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
aeadLocked := profile.Default()
|
||||
aeadLocked.AeadKeyEncryption = &packet.AEADConfig{}
|
||||
argon2 := profile.Default()
|
||||
argon2.AeadKeyEncryption = &packet.AEADConfig{}
|
||||
argon2.S2kKeyEncryption = &s2k.Config{S2KMode: s2k.Argon2S2K, Argon2Config: &s2k.Argon2Config{}}
|
||||
salted := profile.Default()
|
||||
salted.S2kKeyEncryption = &s2k.Config{S2KMode: s2k.SaltedS2K, PassphraseIsHighEntropy: true}
|
||||
v6Key, err := crypto.PGPWithProfile(profile.RFC9580()).KeyGeneration().AddUserId(driveKeyName, "").New().GenerateKey()
|
||||
require.NoError(t, err)
|
||||
v6Locked, err := crypto.PGPWithProfile(profile.RFC9580()).LockKey(v6Key, newPassphrase())
|
||||
require.NoError(t, err)
|
||||
v6Armored, err := v6Locked.Armor()
|
||||
require.NoError(t, err)
|
||||
unlocked, err := generateKey(driveKeyName, "").Armor()
|
||||
require.NoError(t, err)
|
||||
for name, tc := range map[string]struct {
|
||||
key string
|
||||
want string
|
||||
}{
|
||||
"advertises AEAD": {newDriveKey(true).armored, "advertises AEAD"},
|
||||
"v6": {v6Armored, "not a v4 key"},
|
||||
"AEAD locked": {lockedWith(t, aeadLocked), "locked with AEAD"},
|
||||
"Argon2": {lockedWith(t, argon2), "locked with AEAD"},
|
||||
"salted S2K": {lockedWith(t, salted), "S2K mode 1"},
|
||||
"not locked": {unlocked, "not locked"},
|
||||
} {
|
||||
t.Run("NodeKey "+name, func(t *testing.T) {
|
||||
req := newFolderRequest(u, u.RootID(), "dir")
|
||||
req.NodeKey = tc.key
|
||||
status, body := post(req)
|
||||
requireRejected(t, api.CodeInvalidValue, status, body, "NodeKey", tc.want)
|
||||
})
|
||||
}
|
||||
|
||||
for name, spoil := range map[string]func(req *createFolderRequest){
|
||||
"no hash key": func(req *createFolderRequest) { req.NodeHashKey = "" },
|
||||
"no signature": func(req *createFolderRequest) { req.NodePassphraseSignature = "" },
|
||||
"bad hash": func(req *createFolderRequest) { req.Hash = "ABC" },
|
||||
"no signature email": func(req *createFolderRequest) { req.SignatureEmail = nil },
|
||||
"someone else's email": func(req *createFolderRequest) { other := "other@proton.test"; req.SignatureEmail = &other },
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
req := newFolderRequest(u, u.RootID(), "dir")
|
||||
spoil(req)
|
||||
status, body := post(req)
|
||||
requireRejected(t, api.CodeInvalidValue, status, body)
|
||||
})
|
||||
}
|
||||
assert.Empty(t, u.Dump())
|
||||
|
||||
req := newFolderRequest(u, u.RootID(), "dir")
|
||||
req.ParentLinkID = "unknown"
|
||||
status, body := post(req)
|
||||
requireRejected(t, api.CodeNotExists, status, body)
|
||||
|
||||
var created createFolderResponse
|
||||
status, body = post(newFolderRequest(u, u.RootID(), "dir"))
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
require.NoError(t, json.Unmarshal(body, &created))
|
||||
dump := u.Dump()
|
||||
require.Len(t, dump, 1)
|
||||
assert.Equal(t, created.Folder.ID, dump[0].ID)
|
||||
assert.Equal(t, "dir", dump[0].Path)
|
||||
assert.NoError(t, dump[0].Err)
|
||||
assert.True(t, time.Date(2024, 1, 2, 3, 4, 5, 0, time.UTC).Equal(dump[0].ModTime))
|
||||
|
||||
// The name hash must be unique among the folder's untrashed nodes.
|
||||
fileID := u.SeedFile(u.RootID(), "file", []byte("x"), time.Now())
|
||||
status, body = post(newFolderRequest(u, u.RootID(), "file"))
|
||||
requireRejected(t, api.CodeAlreadyExists, status, body)
|
||||
var conflict conflictResponse
|
||||
require.NoError(t, json.Unmarshal(body, &conflict))
|
||||
assert.Equal(t, fileID, conflict.Details.ConflictLinkID)
|
||||
require.NotNil(t, conflict.Details.ConflictRevisionID)
|
||||
assert.Equal(t, u.view().d.links[fileID].activeRevision().id, *conflict.Details.ConflictRevisionID)
|
||||
}
|
||||
|
||||
// renameMoveCopy holds a user with folders a and b, a signed file f in
|
||||
// a and an anonymous file anon in a, and a session.
|
||||
type renameMoveCopy struct {
|
||||
s *Server
|
||||
u *User
|
||||
sess Session
|
||||
a, b, f, anon string
|
||||
volume string
|
||||
validMsg, aeadMsg string
|
||||
}
|
||||
|
||||
func newRenameMoveCopy(t *testing.T) *renameMoveCopy {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
x := &renameMoveCopy{s: s, u: u, sess: s.NewSession(u), volume: u.VolumeID()}
|
||||
x.a = u.SeedFolder(u.RootID(), "a")
|
||||
x.b = u.SeedFolder(u.RootID(), "b")
|
||||
x.f = u.SeedFile(x.a, "f", []byte("f"), time.Now())
|
||||
x.anon = u.SeedAnonymousFile(x.a, "anon", []byte("anon"), time.Now())
|
||||
// The fake doesn't decrypt what it is sent, so any message in the
|
||||
// right format will do.
|
||||
x.validMsg = encryptArmored([]byte("value"), newDriveKey(false).key, nil, false)
|
||||
x.aeadMsg = aeadMessages(t)["v6 PKESK and SEIPDv2"]
|
||||
return x
|
||||
}
|
||||
|
||||
// hash returns the stored name hash of link id.
|
||||
func (x *renameMoveCopy) hash(id string) string {
|
||||
return x.u.view().d.links[id].nameHash
|
||||
}
|
||||
|
||||
func TestRenameRules(t *testing.T) {
|
||||
x := newRenameMoveCopy(t)
|
||||
path := func(id string) string { return "/drive/v2/volumes/" + x.volume + "/links/" + id + "/rename" }
|
||||
email := x.u.Email()
|
||||
newHash := lookupHash([]byte("k"), "new")
|
||||
req := func(original string) *renameRequest {
|
||||
return &renameRequest{Name: x.validMsg, Hash: &newHash, NameSignatureEmail: &email, OriginalHash: &original}
|
||||
}
|
||||
|
||||
status, body := sendJSON(t, x.s, x.sess, "PUT", path("unknown"), req(""))
|
||||
requireRejected(t, api.CodeNotExists, status, body)
|
||||
status, body = sendJSON(t, x.s, x.sess, "PUT", path(x.f), req("stale"))
|
||||
requireRejected(t, api.CodeInvalidRequirements, status, body, "OriginalHash")
|
||||
status, body = sendJSON(t, x.s, x.sess, "PUT", path(x.u.RootID()), req(""))
|
||||
requireRejected(t, api.CodeInvalidRequirements, status, body)
|
||||
bad := req(x.hash(x.f))
|
||||
bad.Name = x.aeadMsg
|
||||
status, body = sendJSON(t, x.s, x.sess, "PUT", path(x.f), bad)
|
||||
requireRejected(t, api.CodeInvalidValue, status, body, "Name")
|
||||
taken := req(x.hash(x.f))
|
||||
anonHash := x.hash(x.anon)
|
||||
taken.Hash = &anonHash
|
||||
status, body = sendJSON(t, x.s, x.sess, "PUT", path(x.f), taken)
|
||||
requireRejected(t, api.CodeAlreadyExists, status, body)
|
||||
|
||||
// Renaming to its own name is no conflict.
|
||||
same := req(x.hash(x.f))
|
||||
ownHash := x.hash(x.f)
|
||||
same.Hash = &ownHash
|
||||
status, body = sendJSON(t, x.s, x.sess, "PUT", path(x.f), same)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
status, body = sendJSON(t, x.s, x.sess, "PUT", path(x.f), req(x.hash(x.f)))
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
assert.Equal(t, newHash, x.hash(x.f))
|
||||
}
|
||||
|
||||
func TestMoveRules(t *testing.T) {
|
||||
x := newRenameMoveCopy(t)
|
||||
path := func(id string) string { return "/drive/v2/volumes/" + x.volume + "/links/" + id + "/move" }
|
||||
email := x.u.Email()
|
||||
other := "other@proton.test"
|
||||
sig := "signature"
|
||||
req := func(id, parentID string) *moveRequest {
|
||||
return &moveRequest{
|
||||
Name: x.validMsg,
|
||||
NodePassphrase: x.validMsg,
|
||||
Hash: lookupHash([]byte("k"), "new"),
|
||||
ParentLinkID: parentID,
|
||||
OriginalHash: x.hash(id),
|
||||
NameSignatureEmail: &email,
|
||||
}
|
||||
}
|
||||
sub := x.u.SeedFolder(x.a, "sub")
|
||||
|
||||
for name, tc := range map[string]struct {
|
||||
id string
|
||||
req *moveRequest
|
||||
code int
|
||||
reason string
|
||||
}{
|
||||
"unknown link": {"unknown", req(x.f, x.b), api.CodeNotExists, ""},
|
||||
"unknown parent": {x.f, req(x.f, "unknown"), api.CodeNotExists, ""},
|
||||
"parent is a file": {x.anon, req(x.anon, x.f), api.CodeNotExists, ""},
|
||||
"into itself": {x.a, req(x.a, x.a), api.CodeInvalidRequirements, "into itself"},
|
||||
"into a descendant": {x.a, req(x.a, sub), api.CodeInvalidRequirements, "into itself"},
|
||||
"the root": {x.u.RootID(), req(x.u.RootID(), x.b), api.CodeInvalidRequirements, ""},
|
||||
"stale original hash": {x.f, func() *moveRequest { r := req(x.f, x.b); r.OriginalHash = "stale"; return r }(), api.CodeInvalidRequirements, "OriginalHash"},
|
||||
"AEAD name": {x.f, func() *moveRequest { r := req(x.f, x.b); r.Name = x.aeadMsg; return r }(), api.CodeInvalidValue, "Name"},
|
||||
"AEAD passphrase": {x.f, func() *moveRequest { r := req(x.f, x.b); r.NodePassphrase = x.aeadMsg; return r }(), api.CodeInvalidValue, "NodePassphrase"},
|
||||
"name signed by another": {x.f, func() *moveRequest { r := req(x.f, x.b); r.NameSignatureEmail = &other; return r }(), api.CodeInvalidValue, "NameSignatureEmail"},
|
||||
"signed node re-signed": {x.f, func() *moveRequest {
|
||||
r := req(x.f, x.b)
|
||||
r.NodePassphraseSignature, r.SignatureEmail = &sig, &email
|
||||
return r
|
||||
}(), api.CodeInvalidValue, "must not be given"},
|
||||
"anonymous node unsigned": {x.anon, req(x.anon, x.b), api.CodeInvalidValue, "anonymous"},
|
||||
"anonymous node signed by another": {x.anon, func() *moveRequest {
|
||||
r := req(x.anon, x.b)
|
||||
r.NodePassphraseSignature, r.SignatureEmail = &sig, &other
|
||||
return r
|
||||
}(), api.CodeInvalidValue, "SignatureEmail"},
|
||||
"name taken": {x.f, func() *moveRequest { r := req(x.f, x.a); r.Hash = x.hash(x.anon); return r }(), api.CodeAlreadyExists, ""},
|
||||
} {
|
||||
status, body := sendJSON(t, x.s, x.sess, "PUT", path(tc.id), tc.req)
|
||||
t.Run(name, func(t *testing.T) {
|
||||
requireRejected(t, tc.code, status, body, tc.reason)
|
||||
})
|
||||
}
|
||||
|
||||
// A signed node keeps its passphrase signature; an anonymous one
|
||||
// takes the one given.
|
||||
before := *x.u.view().d.links[x.f]
|
||||
status, body := sendJSON(t, x.s, x.sess, "PUT", path(x.f), req(x.f, x.b))
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
after := x.u.view().d.links[x.f]
|
||||
assert.Equal(t, x.b, after.parentID)
|
||||
assert.Equal(t, before.nodePass.signature, after.nodePass.signature)
|
||||
assert.Equal(t, before.signatureEmail, after.signatureEmail)
|
||||
assert.Equal(t, x.validMsg, after.nodePass.armored)
|
||||
|
||||
r := req(x.anon, x.b)
|
||||
r.Hash = lookupHash([]byte("k"), "anon")
|
||||
r.NodePassphraseSignature, r.SignatureEmail = &sig, &email
|
||||
status, body = sendJSON(t, x.s, x.sess, "PUT", path(x.anon), r)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
anon := x.u.view().d.links[x.anon]
|
||||
assert.Equal(t, sig, anon.nodePass.signature)
|
||||
assert.Equal(t, email, anon.signatureEmail)
|
||||
assert.Equal(t, email, anon.nameSignatureEmail)
|
||||
}
|
||||
|
||||
func TestCopyRules(t *testing.T) {
|
||||
x := newRenameMoveCopy(t)
|
||||
path := func(id string) string { return "/drive/volumes/" + x.volume + "/links/" + id + "/copy" }
|
||||
email := x.u.Email()
|
||||
req := func(parentID string) *copyRequest {
|
||||
return ©Request{
|
||||
Name: x.validMsg,
|
||||
NodePassphrase: x.validMsg,
|
||||
Hash: lookupHash([]byte("k"), "copy"),
|
||||
TargetVolumeID: x.volume,
|
||||
TargetParentLinkID: parentID,
|
||||
NameSignatureEmail: &email,
|
||||
}
|
||||
}
|
||||
status, body := sendJSON(t, x.s, x.sess, "POST", path("unknown"), req(x.b))
|
||||
requireRejected(t, api.CodeNotExists, status, body)
|
||||
wrongVolume := req(x.b)
|
||||
wrongVolume.TargetVolumeID = "unknown"
|
||||
status, body = sendJSON(t, x.s, x.sess, "POST", path(x.f), wrongVolume)
|
||||
requireRejected(t, api.CodeNotExists, status, body)
|
||||
status, body = sendJSON(t, x.s, x.sess, "POST", path(x.a), req(x.a))
|
||||
requireRejected(t, api.CodeInvalidRequirements, status, body, "into itself")
|
||||
status, body = sendJSON(t, x.s, x.sess, "POST", path(x.anon), req(x.b))
|
||||
requireRejected(t, api.CodeInvalidValue, status, body, "anonymous")
|
||||
aead := req(x.b)
|
||||
aead.NodePassphrase = x.aeadMsg
|
||||
status, body = sendJSON(t, x.s, x.sess, "POST", path(x.f), aead)
|
||||
requireRejected(t, api.CodeInvalidValue, status, body, "NodePassphrase")
|
||||
taken := req(x.a)
|
||||
taken.Hash = x.hash(x.f)
|
||||
status, body = sendJSON(t, x.s, x.sess, "POST", path(x.f), taken)
|
||||
requireRejected(t, api.CodeAlreadyExists, status, body)
|
||||
|
||||
status, body = sendJSON(t, x.s, x.sess, "POST", path(x.f), req(x.b))
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
var resp copyResponse
|
||||
require.NoError(t, json.Unmarshal(body, &resp))
|
||||
v := x.u.view()
|
||||
src, cp := v.d.links[x.f], v.d.links[resp.LinkID]
|
||||
require.NotNil(t, cp)
|
||||
assert.Equal(t, x.b, cp.parentID)
|
||||
assert.Equal(t, src.nodeKey, cp.nodeKey)
|
||||
assert.Equal(t, src.contentKeyPacket, cp.contentKeyPacket)
|
||||
assert.Equal(t, src.nodePass.signature, cp.nodePass.signature)
|
||||
assert.NotEqual(t, src.activeRevision().id, cp.activeRevision().id)
|
||||
assert.Equal(t, src.activeRevision().blocks, cp.activeRevision().blocks)
|
||||
}
|
||||
|
||||
func TestTrashAndEmptyTrash(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
sess := s.NewSession(u)
|
||||
dir := u.SeedFolder(u.RootID(), "dir")
|
||||
child := u.SeedFile(dir, "child", []byte("c"), time.Now())
|
||||
kept := u.SeedFile(u.RootID(), "kept", []byte("k"), time.Now())
|
||||
|
||||
var resp multiResponse
|
||||
status := postJSON(t, s, "/drive/v2/volumes/"+u.VolumeID()+"/trash_multiple", sessionHeader(sess),
|
||||
&linksRequest{LinkIDs: []string{dir, "unknown", u.RootID()}}, &resp)
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
assert.Equal(t, api.CodeOKMany, resp.Code)
|
||||
require.Len(t, resp.Responses, 3)
|
||||
assert.Equal(t, linkResultJSON{LinkID: dir, Response: codeJSON{Code: api.CodeOK}}, resp.Responses[0])
|
||||
assert.Equal(t, api.CodeNotExists, resp.Responses[1].Response.Code)
|
||||
assert.NotEmpty(t, resp.Responses[1].Response.Error)
|
||||
assert.Equal(t, api.CodeInvalidRequirements, resp.Responses[2].Response.Code)
|
||||
|
||||
states := map[string]int{}
|
||||
for _, n := range u.Dump() {
|
||||
require.NoError(t, n.Err)
|
||||
states[n.ID] = n.State
|
||||
}
|
||||
assert.Equal(t, map[string]int{dir: linkStateTrashed, child: linkStateActive, kept: linkStateActive}, states)
|
||||
|
||||
status, body := sendJSON(t, s, sess, "DELETE", "/drive/volumes/"+u.VolumeID()+"/trash", nil)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
dump := u.Dump()
|
||||
require.Len(t, dump, 1)
|
||||
assert.Equal(t, kept, dump[0].ID)
|
||||
}
|
||||
|
||||
func TestCheckAvailableHashes(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
sess := s.NewSession(u)
|
||||
root := u.RootID()
|
||||
u.SeedFile(root, "taken", []byte("x"), time.Now())
|
||||
trashed := u.SeedFile(root, "trashed", []byte("x"), time.Now())
|
||||
_, hashKey := u.view().folderKeys(root)
|
||||
draftID, draftRev := randomID(), randomID()
|
||||
s.mu.Lock()
|
||||
d := u.mustDriveLocked()
|
||||
d.links[trashed].state = linkStateTrashed
|
||||
d.addLink(&link{
|
||||
id: draftID,
|
||||
parentID: root,
|
||||
typ: linkTypeFile,
|
||||
state: linkStateDraft,
|
||||
nameHash: lookupHash(hashKey, "draft"),
|
||||
revisions: []*revision{{id: draftRev, state: revisionStateDraft, clientUID: "mine"}},
|
||||
})
|
||||
s.mu.Unlock()
|
||||
|
||||
hashes := []string{lookupHash(hashKey, "free"), lookupHash(hashKey, "taken"), lookupHash(hashKey, "trashed"), lookupHash(hashKey, "draft")}
|
||||
path := "/drive/v2/volumes/" + u.VolumeID() + "/links/" + root + "/checkAvailableHashes"
|
||||
var resp availableHashesResponse
|
||||
require.Equal(t, http.StatusOK, postJSON(t, s, path, sessionHeader(sess), &checkHashesRequest{Hashes: hashes}, &resp))
|
||||
assert.Equal(t, []string{hashes[0], hashes[2]}, resp.AvailableHashes)
|
||||
mine := "mine"
|
||||
assert.Equal(t, []pendingHashJSON{{Hash: hashes[3], RevisionID: draftRev, LinkID: draftID, ClientUID: &mine}}, resp.PendingHashes)
|
||||
|
||||
resp = availableHashesResponse{}
|
||||
require.Equal(t, http.StatusOK, postJSON(t, s, path, sessionHeader(sess), &checkHashesRequest{Hashes: hashes, ClientUID: []string{"mine"}}, &resp))
|
||||
assert.Equal(t, []string{hashes[0], hashes[2]}, resp.AvailableHashes)
|
||||
assert.Empty(t, resp.PendingHashes)
|
||||
|
||||
var apiErr api.Error
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, postJSON(t, s, "/drive/v2/volumes/"+u.VolumeID()+"/links/unknown/checkAvailableHashes", sessionHeader(sess), &checkHashesRequest{}, &apiErr))
|
||||
assert.Equal(t, api.CodeNotExists, apiErr.Code)
|
||||
}
|
||||
|
||||
func TestDumpChecksNameHash(t *testing.T) {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
id := u.SeedFile(u.RootID(), "file", []byte("x"), time.Now())
|
||||
require.NoError(t, u.Dump()[0].Err)
|
||||
s.mu.Lock()
|
||||
u.mustDriveLocked().links[id].nameHash = lookupHash([]byte("other key"), "file")
|
||||
s.mu.Unlock()
|
||||
err := u.Dump()[0].Err
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "name hash")
|
||||
}
|
||||
|
||||
// TestMutationWireNames checks the backend's request types decode into
|
||||
// the fake's without unknown fields.
|
||||
func TestMutationWireNames(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
client any
|
||||
fake any
|
||||
}{
|
||||
{&api.CreateFolderRequest{XAttr: "x"}, &createFolderRequest{}},
|
||||
{&api.RenameRequest{}, &renameRequest{}},
|
||||
{&api.MoveRequest{NodePassphraseSignature: "x", SignatureEmail: "x"}, &moveRequest{}},
|
||||
{&api.CopyRequest{NodePassphraseSignature: "x", SignatureEmail: "x"}, ©Request{}},
|
||||
{&api.LinksRequest{}, &linksRequest{}},
|
||||
{&api.MultiLinkResponse{Responses: []api.LinkResult{{}}}, &multiResponse{}},
|
||||
{&api.CreateFolderResponse{}, &createFolderResponse{}},
|
||||
{&api.CopyResponse{}, ©Response{}},
|
||||
} {
|
||||
data, err := json.Marshal(tc.client)
|
||||
require.NoError(t, err)
|
||||
dec := json.NewDecoder(bytes.NewReader(data))
|
||||
dec.DisallowUnknownFields()
|
||||
assert.NoError(t, dec.Decode(tc.fake), "%T", tc.client)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
// Package protontest is a fake Proton Drive API server for tests.
|
||||
//
|
||||
// It must not import the protondrive backend, whose tests use it.
|
||||
package protontest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/ProtonMail/gopenpgp/v3/crypto"
|
||||
"github.com/rclone/rclone/backend/protondrive/api"
|
||||
)
|
||||
|
||||
var (
|
||||
// appVersionRe is Proton's published x-pm-appversion grammar
|
||||
// (SDK README, "Usage Guidelines") with the name fixed to rclone.
|
||||
appVersionRe = regexp.MustCompile(`^external-drive-rclone@[0-9]+\.[0-9]+\.[0-9]+(-(stable|beta|alpha))?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$`)
|
||||
|
||||
// legacyRouteRe matches the removed share-scoped routes and
|
||||
// everything beneath them.
|
||||
legacyRouteRe = regexp.MustCompile(`^/drive/shares/[^/]+/(links|folders|files|events)(/|$)`)
|
||||
)
|
||||
|
||||
// legacyRequests counts the requests for legacy routes, per "METHOD
|
||||
// path", made to every server in the process, so a test binary can
|
||||
// check none was made after all its tests have run.
|
||||
var legacyRequests = struct {
|
||||
mu sync.Mutex
|
||||
counts map[string]int
|
||||
}{counts: make(map[string]int)}
|
||||
|
||||
// LegacyRequests returns a copy of the count, per "METHOD path", of
|
||||
// the requests for removed share-scoped routes made to every server in
|
||||
// the process since it started. ResetRequests doesn't change it.
|
||||
func LegacyRequests() map[string]int {
|
||||
legacyRequests.mu.Lock()
|
||||
defer legacyRequests.mu.Unlock()
|
||||
out := make(map[string]int, len(legacyRequests.counts))
|
||||
for k, v := range legacyRequests.counts {
|
||||
out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Fault describes a scripted failure for requests to one route.
|
||||
type Fault struct {
|
||||
Method string // HTTP method to match; empty matches any
|
||||
Pattern string // route pattern as registered, e.g. "/tests/ping"
|
||||
Skip int // matching requests let through before faulting
|
||||
Times int // matching requests faulted after Skip; 0 means forever
|
||||
Status int // HTTP status to return; 0 with Drop false only holds the request
|
||||
Code int // Proton code in the error body
|
||||
RetryAfter int // Retry-After header in seconds, if non-zero
|
||||
Drop bool // close the connection instead of responding
|
||||
Delay time.Duration // wait before handling the request
|
||||
Gather bool // hold each faulted request until all Times have arrived
|
||||
AfterHandler bool // run the real handler, then replace its response
|
||||
|
||||
// Hold, if set, makes each faulted request run the real handler on
|
||||
// arrival and get its response only once Hold is closed, so the
|
||||
// response is as of arrival. Held, if set, is sent to once the
|
||||
// response is ready and held.
|
||||
Hold <-chan struct{}
|
||||
Held chan<- struct{}
|
||||
}
|
||||
|
||||
// fault is an injected Fault with the count of requests it has matched.
|
||||
type fault struct {
|
||||
Fault
|
||||
seen int
|
||||
gathered chan struct{} // closed when the last of Times has arrived, if Gather
|
||||
}
|
||||
|
||||
// fires records a matching request and reports whether it is faulted.
|
||||
func (f *fault) fires() bool {
|
||||
f.seen++
|
||||
n := f.seen - f.Skip
|
||||
if f.Gather && n == f.Times {
|
||||
close(f.gathered)
|
||||
}
|
||||
return n > 0 && (f.Times == 0 || n <= f.Times)
|
||||
}
|
||||
|
||||
// Server is a fake Proton API server.
|
||||
type Server struct {
|
||||
srv *httptest.Server
|
||||
mux *http.ServeMux
|
||||
|
||||
mu sync.Mutex
|
||||
requests map[string]int // count per "METHOD pattern"
|
||||
faults []*fault
|
||||
clockSkew time.Duration
|
||||
users map[string]*User // by username
|
||||
sessions map[string]*session // by UID
|
||||
srp map[string]*srpLogin // by SRPSession
|
||||
forks map[string]*fork // by Selector
|
||||
|
||||
childrenPageSize int
|
||||
eventsPageSize int
|
||||
downloads map[string]*download // block URLs by ID
|
||||
unlockedKeys map[string]*crypto.Key // by keyCacheID
|
||||
uploads map[string]*uploadURL // block upload URLs by ID
|
||||
storageUploads int // block uploads in progress
|
||||
storagePeak int // most block uploads in progress at once
|
||||
secrets []issuedSecret // every secret issued, in order
|
||||
keysAs map[string]*User // whose keys GET /core/v4/keys/all serves for an email, overriding the owner's
|
||||
readLag int // reads of a node after a change which don't see it; see SetReadLag
|
||||
readLagView LagView // what lagging reads of a changed node see
|
||||
lagging map[string]*lagView // nodes whose reads lag, by ID
|
||||
|
||||
// driveRequirements is sent as x-pm-drive-requirements headers if
|
||||
// not empty; see SetDriveRequirements.
|
||||
driveRequirements []string
|
||||
}
|
||||
|
||||
// New starts a fake server which is closed when the test ends.
|
||||
func New(t testing.TB) *Server {
|
||||
s := newServer()
|
||||
s.srv = httptest.NewServer(http.HandlerFunc(s.serveHTTP))
|
||||
t.Cleanup(s.Close)
|
||||
return s
|
||||
}
|
||||
|
||||
// NewStandalone starts a fake server listening on addr, such as
|
||||
// "127.0.0.1:0", for use outside tests. Call Close to stop it.
|
||||
func NewStandalone(addr string) (*Server, error) {
|
||||
l, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("protontest: listen: %w", err)
|
||||
}
|
||||
s := newServer()
|
||||
s.srv = httptest.NewUnstartedServer(http.HandlerFunc(s.serveHTTP))
|
||||
_ = s.srv.Listener.Close()
|
||||
s.srv.Listener = l
|
||||
s.srv.Start()
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// newServer returns a server with its routes registered, not yet
|
||||
// listening.
|
||||
func newServer() *Server {
|
||||
s := &Server{
|
||||
mux: http.NewServeMux(),
|
||||
requests: make(map[string]int),
|
||||
users: make(map[string]*User),
|
||||
sessions: make(map[string]*session),
|
||||
srp: make(map[string]*srpLogin),
|
||||
forks: make(map[string]*fork),
|
||||
|
||||
childrenPageSize: defaultChildrenPageSize,
|
||||
eventsPageSize: defaultEventsPageSize,
|
||||
downloads: make(map[string]*download),
|
||||
unlockedKeys: make(map[string]*crypto.Key),
|
||||
uploads: make(map[string]*uploadURL),
|
||||
lagging: make(map[string]*lagView),
|
||||
}
|
||||
s.handle("GET", "/tests/ping", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]int{"Code": api.CodeOK})
|
||||
})
|
||||
s.registerAuth()
|
||||
s.registerAccount()
|
||||
s.registerDrive()
|
||||
return s
|
||||
}
|
||||
|
||||
// Close stops the server and blocks until all its requests are done.
|
||||
func (s *Server) Close() {
|
||||
s.srv.Close()
|
||||
}
|
||||
|
||||
// URL returns the base URL of the server.
|
||||
func (s *Server) URL() string {
|
||||
return s.srv.URL
|
||||
}
|
||||
|
||||
// Client returns an HTTP client configured for the server.
|
||||
func (s *Server) Client() *http.Client {
|
||||
return s.srv.Client()
|
||||
}
|
||||
|
||||
// Requests returns a copy of the request count per "METHOD pattern",
|
||||
// e.g. "GET /drive/v2/volumes/{volumeID}/folders/{linkID}/children".
|
||||
//
|
||||
// Requests for unregistered or legacy routes are counted under their
|
||||
// path.
|
||||
func (s *Server) Requests() map[string]int {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := make(map[string]int, len(s.requests))
|
||||
for k, v := range s.requests {
|
||||
out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ResetRequests zeroes the request counts and the peak of
|
||||
// StorageUploadPeak.
|
||||
func (s *Server) ResetRequests() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
clear(s.requests)
|
||||
s.storagePeak = s.storageUploads
|
||||
}
|
||||
|
||||
// ServeKeysAs makes GET /core/v4/keys/all serve owner's primary
|
||||
// address keys for email, as a hostile server could, whoever owns
|
||||
// email.
|
||||
func (s *Server) ServeKeysAs(email string, owner *User) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.keysAs == nil {
|
||||
s.keysAs = make(map[string]*User)
|
||||
}
|
||||
s.keysAs[email] = owner
|
||||
}
|
||||
|
||||
// SecretKind is a kind of secret the server issues.
|
||||
type SecretKind int
|
||||
|
||||
// Kinds of secret the server issues.
|
||||
const (
|
||||
SessionToken SecretKind = iota + 1 // an access or refresh token
|
||||
ForkSelector // the selector polling a session fork
|
||||
StorageToken // a block upload or download token
|
||||
)
|
||||
|
||||
// issuedSecret is a secret the server handed to a client.
|
||||
type issuedSecret struct {
|
||||
kind SecretKind
|
||||
value string
|
||||
}
|
||||
|
||||
// newSecretLocked returns a new random secret of kind and records it
|
||||
// for IssuedSecrets. s.mu must be held.
|
||||
func (s *Server) newSecretLocked(kind SecretKind) string {
|
||||
secret := randomID()
|
||||
s.secrets = append(s.secrets, issuedSecret{kind: kind, value: secret})
|
||||
return secret
|
||||
}
|
||||
|
||||
// IssuedSecrets returns every secret of the kinds given, or of any kind
|
||||
// if none is, which the server has handed to a client, in order.
|
||||
func (s *Server) IssuedSecrets(kinds ...SecretKind) []string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
var out []string
|
||||
for _, secret := range s.secrets {
|
||||
if len(kinds) == 0 || slices.Contains(kinds, secret.kind) {
|
||||
out = append(out, secret.value)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Inject adds a fault. Faults are checked in the order they were added
|
||||
// and the first one that fires is applied. A Gather fault needs Times.
|
||||
func (s *Server) Inject(f Fault) {
|
||||
if f.Gather && f.Times <= 0 {
|
||||
panic("protontest: a Gather fault needs Times")
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.faults = append(s.faults, &fault{Fault: f, gathered: make(chan struct{})})
|
||||
}
|
||||
|
||||
// SetClockSkew shifts the Date header of every response by d.
|
||||
func (s *Server) SetClockSkew(d time.Duration) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.clockSkew = d
|
||||
}
|
||||
|
||||
// SetDriveRequirements makes every response carry an
|
||||
// x-pm-drive-requirements header with each of values, as Proton
|
||||
// announces upcoming requirements; none if values is empty.
|
||||
func (s *Server) SetDriveRequirements(values ...string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.driveRequirements = values
|
||||
}
|
||||
|
||||
// handle registers h for method and an http.ServeMux path pattern.
|
||||
func (s *Server) handle(method, pattern string, h http.HandlerFunc) {
|
||||
s.mux.HandleFunc(method+" "+pattern, h)
|
||||
}
|
||||
|
||||
// serveHTTP checks, counts and dispatches every request.
|
||||
func (s *Server) serveHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
_, pattern := s.mux.Handler(r)
|
||||
// Registered patterns are "METHOD /path"; keep the path part.
|
||||
_, pattern, _ = strings.Cut(pattern, " ")
|
||||
key := r.Method + " " + pattern
|
||||
if pattern == "" {
|
||||
key = r.Method + " " + r.URL.Path
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
s.requests[key]++
|
||||
w.Header().Set("Date", time.Now().Add(s.clockSkew).UTC().Format(http.TimeFormat))
|
||||
for _, v := range s.driveRequirements {
|
||||
w.Header().Add("x-pm-drive-requirements", v)
|
||||
}
|
||||
if pattern == storageUploadPattern {
|
||||
s.storageUploads++
|
||||
s.storagePeak = max(s.storagePeak, s.storageUploads)
|
||||
defer func() {
|
||||
s.mu.Lock()
|
||||
s.storageUploads--
|
||||
s.mu.Unlock()
|
||||
}()
|
||||
}
|
||||
s.mu.Unlock()
|
||||
|
||||
switch {
|
||||
case legacyRouteRe.MatchString(r.URL.Path):
|
||||
legacyRequests.mu.Lock()
|
||||
legacyRequests.counts[r.Method+" "+r.URL.Path]++
|
||||
legacyRequests.mu.Unlock()
|
||||
writeError(w, http.StatusGone, 0, "protontest: legacy route "+r.URL.Path+" was removed")
|
||||
return
|
||||
case r.Header.Get("x-pm-drive-sdk-version") != "":
|
||||
writeError(w, http.StatusBadRequest, api.CodeInvalidSection, "protontest: x-pm-drive-sdk-version must not be sent")
|
||||
return
|
||||
case !appVersionRe.MatchString(r.Header.Get("x-pm-appversion")):
|
||||
writeError(w, http.StatusBadRequest, api.CodeInvalidSection, fmt.Sprintf("protontest: invalid x-pm-appversion %q", r.Header.Get("x-pm-appversion")))
|
||||
return
|
||||
case pattern == "":
|
||||
writeError(w, http.StatusNotFound, 0, "protontest: no route for "+r.Method+" "+r.URL.Path)
|
||||
return
|
||||
}
|
||||
|
||||
if f := s.activeFault(r.Method, pattern); f != nil {
|
||||
s.serveFault(w, r, f)
|
||||
return
|
||||
}
|
||||
s.mux.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// activeFault records the request against every matching fault and
|
||||
// returns the first one that fires, or nil.
|
||||
func (s *Server) activeFault(method, pattern string) *fault {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
var active *fault
|
||||
for _, f := range s.faults {
|
||||
if f.Pattern != pattern || (f.Method != "" && f.Method != method) {
|
||||
continue
|
||||
}
|
||||
if f.fires() && active == nil {
|
||||
active = f
|
||||
}
|
||||
}
|
||||
return active
|
||||
}
|
||||
|
||||
// serveFault applies f to a request for a registered route.
|
||||
func (s *Server) serveFault(w http.ResponseWriter, r *http.Request, f *fault) {
|
||||
if f.Delay > 0 || f.Gather {
|
||||
// The server notices a client giving up, and cancels the request
|
||||
// context, only once the request body has been read.
|
||||
if body, err := io.ReadAll(r.Body); err == nil {
|
||||
r.Body = io.NopCloser(bytes.NewReader(body))
|
||||
}
|
||||
}
|
||||
if f.Gather {
|
||||
select {
|
||||
case <-f.gathered:
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
if f.Delay > 0 {
|
||||
select {
|
||||
case <-time.After(f.Delay):
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
if f.Hold != nil {
|
||||
rec := httptest.NewRecorder()
|
||||
s.mux.ServeHTTP(rec, r)
|
||||
if f.Held != nil {
|
||||
f.Held <- struct{}{}
|
||||
}
|
||||
select {
|
||||
case <-f.Hold:
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
}
|
||||
for k, v := range rec.Header() {
|
||||
w.Header()[k] = v
|
||||
}
|
||||
w.WriteHeader(rec.Code)
|
||||
_, _ = w.Write(rec.Body.Bytes())
|
||||
return
|
||||
}
|
||||
if f.Status == 0 && !f.Drop {
|
||||
s.mux.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
if f.AfterHandler {
|
||||
s.mux.ServeHTTP(httptest.NewRecorder(), r)
|
||||
}
|
||||
if f.Drop {
|
||||
conn, _, err := http.NewResponseController(w).Hijack()
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("protontest: drop connection: %v", err))
|
||||
}
|
||||
_ = conn.Close()
|
||||
return
|
||||
}
|
||||
if f.RetryAfter > 0 {
|
||||
w.Header().Set("Retry-After", strconv.Itoa(f.RetryAfter))
|
||||
}
|
||||
writeError(w, f.Status, f.Code, "protontest: injected fault")
|
||||
}
|
||||
|
||||
// writeJSON writes v as a JSON response with the given HTTP status.
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
// writeError writes an api.Error response.
|
||||
func writeError(w http.ResponseWriter, status, code int, msg string) {
|
||||
writeJSON(w, status, &api.Error{Code: code, Message: msg})
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
package protontest
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rclone/rclone/backend/protondrive/api"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const testAppVersion = "external-drive-rclone@1.77.0-stable"
|
||||
|
||||
// do sends a request with the given headers and returns the response
|
||||
// and its body.
|
||||
func do(t *testing.T, s *Server, method, path string, header map[string]string) (*http.Response, []byte) {
|
||||
t.Helper()
|
||||
req, err := http.NewRequest(method, s.URL()+path, nil)
|
||||
require.NoError(t, err)
|
||||
for k, v := range header {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
resp, err := s.Client().Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
return resp, body
|
||||
}
|
||||
|
||||
// ping calls GET /tests/ping with a valid app version.
|
||||
func ping(t *testing.T, s *Server) (*http.Response, []byte) {
|
||||
t.Helper()
|
||||
return do(t, s, "GET", "/tests/ping", map[string]string{"x-pm-appversion": testAppVersion})
|
||||
}
|
||||
|
||||
func decodeError(t *testing.T, body []byte) api.Error {
|
||||
t.Helper()
|
||||
var e api.Error
|
||||
require.NoError(t, json.Unmarshal(body, &e), "body: %s", body)
|
||||
return e
|
||||
}
|
||||
|
||||
func TestLegacyRoutesGone(t *testing.T) {
|
||||
s := New(t)
|
||||
for _, path := range []string{
|
||||
"/drive/shares/abc/links/def",
|
||||
"/drive/shares/abc/folders/def/children",
|
||||
"/drive/shares/abc/files",
|
||||
"/drive/shares/abc/events/latest",
|
||||
} {
|
||||
for _, method := range []string{"GET", "POST"} {
|
||||
resp, _ := do(t, s, method, path, map[string]string{"x-pm-appversion": testAppVersion})
|
||||
assert.Equal(t, http.StatusGone, resp.StatusCode, "%s %s", method, path)
|
||||
assert.Equal(t, 1, s.Requests()[method+" "+path], "%s %s counted", method, path)
|
||||
}
|
||||
}
|
||||
|
||||
// The share itself is not a legacy route.
|
||||
resp, _ := do(t, s, "GET", "/drive/shares/abc", map[string]string{"x-pm-appversion": testAppVersion})
|
||||
assert.Equal(t, http.StatusUnauthorized, resp.StatusCode)
|
||||
}
|
||||
|
||||
func TestLegacyRequestsProcessWide(t *testing.T) {
|
||||
before := LegacyRequests()
|
||||
s1, s2 := New(t), New(t)
|
||||
do(t, s1, "GET", "/drive/shares/abc/links/def", map[string]string{"x-pm-appversion": testAppVersion})
|
||||
do(t, s2, "GET", "/drive/shares/abc/links/def", map[string]string{"x-pm-appversion": testAppVersion})
|
||||
do(t, s2, "POST", "/drive/shares/abc/files", nil)
|
||||
do(t, s2, "GET", "/drive/shares/abc", nil)
|
||||
s1.ResetRequests()
|
||||
s2.ResetRequests()
|
||||
|
||||
after := LegacyRequests()
|
||||
assert.Equal(t, before["GET /drive/shares/abc/links/def"]+2, after["GET /drive/shares/abc/links/def"])
|
||||
assert.Equal(t, before["POST /drive/shares/abc/files"]+1, after["POST /drive/shares/abc/files"], "counted whatever its headers")
|
||||
assert.NotContains(t, after, "GET /drive/shares/abc")
|
||||
after["changed"] = 1
|
||||
assert.NotContains(t, LegacyRequests(), "changed", "a copy is returned")
|
||||
}
|
||||
|
||||
func TestUnknownRoute(t *testing.T) {
|
||||
s := New(t)
|
||||
resp, body := do(t, s, "GET", "/core/v4/nothing", map[string]string{"x-pm-appversion": testAppVersion})
|
||||
assert.Equal(t, http.StatusNotFound, resp.StatusCode)
|
||||
assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
|
||||
assert.Contains(t, decodeError(t, body).Message, "GET /core/v4/nothing")
|
||||
}
|
||||
|
||||
func TestAppVersionEnforced(t *testing.T) {
|
||||
s := New(t)
|
||||
for _, version := range []string{
|
||||
"",
|
||||
"web-drive@5.2.0",
|
||||
"external-drive-rclone@1.77.0-dev",
|
||||
"external-drive-other@1.77.0-stable",
|
||||
"external-drive-rclone@1.77-stable",
|
||||
"external-drive-rclone@1.77.0-stable+",
|
||||
} {
|
||||
header := map[string]string{}
|
||||
if version != "" {
|
||||
header["x-pm-appversion"] = version
|
||||
}
|
||||
resp, body := do(t, s, "GET", "/tests/ping", header)
|
||||
assert.Equal(t, http.StatusBadRequest, resp.StatusCode, "version %q", version)
|
||||
assert.Equal(t, api.CodeInvalidSection, decodeError(t, body).Code, "version %q", version)
|
||||
}
|
||||
|
||||
for _, version := range []string{
|
||||
"external-drive-rclone@1.77.0-stable",
|
||||
"external-drive-rclone@1.77.0-beta+abc",
|
||||
"external-drive-rclone@1.77.0-alpha",
|
||||
"external-drive-rclone@1.77.0",
|
||||
"external-drive-rclone@1.77.0-alpha+abc123f.dirty",
|
||||
} {
|
||||
resp, body := do(t, s, "GET", "/tests/ping", map[string]string{"x-pm-appversion": version})
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode, "version %q", version)
|
||||
assert.JSONEq(t, `{"Code":1000}`, string(body), "version %q", version)
|
||||
}
|
||||
|
||||
resp, _ := do(t, s, "GET", "/tests/ping", map[string]string{
|
||||
"x-pm-appversion": testAppVersion,
|
||||
"x-pm-drive-sdk-version": "js@0.23.0",
|
||||
})
|
||||
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
|
||||
}
|
||||
|
||||
func TestFaultInjection(t *testing.T) {
|
||||
t.Run("Times", func(t *testing.T) {
|
||||
s := New(t)
|
||||
s.Inject(Fault{Pattern: "/tests/ping", Times: 2, Status: 429, RetryAfter: 1})
|
||||
for i := range 2 {
|
||||
resp, _ := ping(t, s)
|
||||
assert.Equal(t, http.StatusTooManyRequests, resp.StatusCode, "call %d", i)
|
||||
assert.Equal(t, "1", resp.Header.Get("Retry-After"), "call %d", i)
|
||||
}
|
||||
resp, _ := ping(t, s)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.Empty(t, resp.Header.Get("Retry-After"))
|
||||
})
|
||||
|
||||
t.Run("Skip", func(t *testing.T) {
|
||||
s := New(t)
|
||||
s.Inject(Fault{Pattern: "/tests/ping", Skip: 1, Times: 1, Status: 503, Code: 2028})
|
||||
resp, _ := ping(t, s)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
resp, body := ping(t, s)
|
||||
assert.Equal(t, http.StatusServiceUnavailable, resp.StatusCode)
|
||||
assert.Equal(t, api.CodeFeatureBlocked, decodeError(t, body).Code)
|
||||
resp, _ = ping(t, s)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("Forever", func(t *testing.T) {
|
||||
s := New(t)
|
||||
s.Inject(Fault{Pattern: "/tests/ping", Status: 500})
|
||||
for range 5 {
|
||||
resp, _ := ping(t, s)
|
||||
assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Method", func(t *testing.T) {
|
||||
s := New(t)
|
||||
s.Inject(Fault{Method: "POST", Pattern: "/tests/ping", Status: 500})
|
||||
resp, _ := ping(t, s)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("Drop", func(t *testing.T) {
|
||||
s := New(t)
|
||||
s.Inject(Fault{Pattern: "/tests/ping", Times: 1, Drop: true})
|
||||
req, err := http.NewRequest("GET", s.URL()+"/tests/ping", nil)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("x-pm-appversion", testAppVersion)
|
||||
resp, err := s.Client().Do(req)
|
||||
if err == nil {
|
||||
_ = resp.Body.Close()
|
||||
}
|
||||
require.Error(t, err)
|
||||
resp2, _ := ping(t, s)
|
||||
assert.Equal(t, http.StatusOK, resp2.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("Delay", func(t *testing.T) {
|
||||
s := New(t)
|
||||
s.Inject(Fault{Pattern: "/tests/ping", Times: 1, Delay: 100 * time.Millisecond})
|
||||
start := time.Now()
|
||||
resp, _ := ping(t, s)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.GreaterOrEqual(t, time.Since(start), 100*time.Millisecond)
|
||||
})
|
||||
|
||||
t.Run("Gather", func(t *testing.T) {
|
||||
s := New(t)
|
||||
s.Inject(Fault{Pattern: "/tests/ping", Times: 2, Gather: true})
|
||||
req, err := http.NewRequest("GET", s.URL()+"/tests/ping", nil)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("x-pm-appversion", testAppVersion)
|
||||
first := make(chan int)
|
||||
go func() {
|
||||
resp, err := s.Client().Do(req)
|
||||
if err != nil {
|
||||
first <- 0
|
||||
return
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
first <- resp.StatusCode
|
||||
}()
|
||||
select {
|
||||
case <-first:
|
||||
t.Fatal("first request answered before the second arrived")
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
resp, _ := ping(t, s)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.Equal(t, http.StatusOK, <-first)
|
||||
// Requests after Times are not held.
|
||||
resp, _ = ping(t, s)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("Hold", func(t *testing.T) {
|
||||
s := New(t)
|
||||
n := 0
|
||||
s.handle("GET", "/tests/count", func(w http.ResponseWriter, r *http.Request) {
|
||||
n++
|
||||
writeJSON(w, http.StatusOK, map[string]int{"Code": api.CodeOK, "N": n})
|
||||
})
|
||||
release := make(chan struct{})
|
||||
held := make(chan struct{}, 1)
|
||||
s.Inject(Fault{Pattern: "/tests/count", Times: 1, Hold: release, Held: held})
|
||||
first := make(chan []byte)
|
||||
go func() {
|
||||
_, body := do(t, s, "GET", "/tests/count", map[string]string{"x-pm-appversion": testAppVersion})
|
||||
first <- body
|
||||
}()
|
||||
<-held
|
||||
// The held request was handled on arrival; later ones pass.
|
||||
_, body := do(t, s, "GET", "/tests/count", map[string]string{"x-pm-appversion": testAppVersion})
|
||||
assert.JSONEq(t, `{"Code":1000,"N":2}`, string(body))
|
||||
select {
|
||||
case <-first:
|
||||
t.Fatal("held request answered before release")
|
||||
default:
|
||||
}
|
||||
close(release)
|
||||
assert.JSONEq(t, `{"Code":1000,"N":1}`, string(<-first))
|
||||
})
|
||||
|
||||
t.Run("AfterHandler", func(t *testing.T) {
|
||||
s := New(t)
|
||||
called := 0
|
||||
s.handle("POST", "/tests/commit", func(w http.ResponseWriter, r *http.Request) {
|
||||
called++
|
||||
writeJSON(w, http.StatusOK, map[string]int{"Code": api.CodeOK})
|
||||
})
|
||||
s.Inject(Fault{Pattern: "/tests/commit", Times: 1, Status: 500, AfterHandler: true})
|
||||
resp, body := do(t, s, "POST", "/tests/commit", map[string]string{"x-pm-appversion": testAppVersion})
|
||||
assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
|
||||
assert.NotContains(t, string(body), `"Code":1000`)
|
||||
assert.Equal(t, 1, called)
|
||||
})
|
||||
}
|
||||
|
||||
func TestRequestCounting(t *testing.T) {
|
||||
s := New(t)
|
||||
s.handle("GET", "/tests/volumes/{volumeID}/folders/{linkID}/children", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"Code": api.CodeOK, "Volume": r.PathValue("volumeID")})
|
||||
})
|
||||
header := map[string]string{"x-pm-appversion": testAppVersion}
|
||||
_, body := do(t, s, "GET", "/tests/volumes/v1/folders/l1/children", header)
|
||||
assert.JSONEq(t, `{"Code":1000,"Volume":"v1"}`, string(body))
|
||||
do(t, s, "GET", "/tests/volumes/v2/folders/l2/children", header)
|
||||
ping(t, s)
|
||||
|
||||
assert.Equal(t, map[string]int{
|
||||
"GET /tests/volumes/{volumeID}/folders/{linkID}/children": 2,
|
||||
"GET /tests/ping": 1,
|
||||
}, s.Requests())
|
||||
|
||||
// The returned map is a copy.
|
||||
s.Requests()["GET /tests/ping"] = 99
|
||||
assert.Equal(t, 1, s.Requests()["GET /tests/ping"])
|
||||
|
||||
s.ResetRequests()
|
||||
assert.Empty(t, s.Requests())
|
||||
ping(t, s)
|
||||
assert.Equal(t, map[string]int{"GET /tests/ping": 1}, s.Requests())
|
||||
}
|
||||
|
||||
func TestClockSkew(t *testing.T) {
|
||||
s := New(t)
|
||||
check := func(skew time.Duration) {
|
||||
resp, _ := ping(t, s)
|
||||
date, err := http.ParseTime(resp.Header.Get("Date"))
|
||||
require.NoError(t, err)
|
||||
assert.WithinDuration(t, time.Now().Add(skew), date, 5*time.Second)
|
||||
}
|
||||
check(0)
|
||||
s.SetClockSkew(-2 * time.Hour)
|
||||
check(-2 * time.Hour)
|
||||
s.SetClockSkew(30 * time.Minute)
|
||||
check(30 * time.Minute)
|
||||
}
|
||||
|
||||
func TestErrorJSON(t *testing.T) {
|
||||
e := api.Error{Status: 422, Code: api.CodeAlreadyExists, Message: "exists", Details: json.RawMessage(`{"ConflictLinkID":"x"}`)}
|
||||
b, err := json.Marshal(&e)
|
||||
require.NoError(t, err)
|
||||
assert.JSONEq(t, `{"Code":2500,"Error":"exists","Details":{"ConflictLinkID":"x"}}`, string(b))
|
||||
assert.True(t, strings.Contains(e.Error(), "exists") && strings.Contains(e.Error(), "2500") && strings.Contains(e.Error(), "422"), e.Error())
|
||||
}
|
||||
|
||||
func TestNewStandalone(t *testing.T) {
|
||||
s, err := NewStandalone("127.0.0.1:0")
|
||||
require.NoError(t, err)
|
||||
assert.False(t, strings.HasSuffix(s.URL(), ":0"), "URL %q must carry the bound port", s.URL())
|
||||
resp, _ := ping(t, s)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
s.Close()
|
||||
_, err = s.Client().Get(s.URL() + "/tests/ping")
|
||||
assert.Error(t, err, "server still answering after Close")
|
||||
|
||||
_, err = NewStandalone("not an address")
|
||||
assert.Error(t, err)
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package protontest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"time"
|
||||
|
||||
"github.com/ProtonMail/gopenpgp/v3/crypto"
|
||||
)
|
||||
|
||||
// StoredFile is a file node as the server stores it: the encrypted
|
||||
// metadata and content a client sent, with nothing decrypted.
|
||||
type StoredFile struct {
|
||||
Link StoredLink
|
||||
Revision StoredRevision // the active revision
|
||||
}
|
||||
|
||||
// StoredLink is the encrypted metadata of a file node.
|
||||
type StoredLink struct {
|
||||
Name string // armored, encrypted to the parent key
|
||||
NameHash string
|
||||
NodeKey string // armored, locked with the node passphrase
|
||||
NodePassphrase string // armored, encrypted to the parent key
|
||||
NodePassphraseSignature string
|
||||
SignatureEmail string
|
||||
NameSignatureEmail string
|
||||
MediaType string
|
||||
ContentKeyPacket string // base64
|
||||
ContentKeyPacketSignature string
|
||||
CreateTime int64 // Unix seconds; the time of seeding if zero
|
||||
ModifyTime int64 // Unix seconds; the time of seeding if zero
|
||||
}
|
||||
|
||||
// StoredRevision is a revision of a file node.
|
||||
type StoredRevision struct {
|
||||
ManifestSignature string
|
||||
XAttr string // armored; empty if none
|
||||
SignatureEmail string
|
||||
CreateTime int64 // Unix seconds; the time of seeding if zero
|
||||
Blocks []StoredBlock // in index order, from 1
|
||||
}
|
||||
|
||||
// StoredBlock is an encrypted block of a revision.
|
||||
type StoredBlock struct {
|
||||
Hash []byte // SHA-256 of Data
|
||||
EncSignature string
|
||||
SignatureEmail string
|
||||
Data []byte `json:"-"`
|
||||
}
|
||||
|
||||
// StoredFile returns file id with its active revision as stored. It
|
||||
// panics if id is not a file with an active revision.
|
||||
func (u *User) StoredFile(id string) StoredFile {
|
||||
u.srv.mu.Lock()
|
||||
defer u.srv.mu.Unlock()
|
||||
l := u.mustDriveLocked().links[id]
|
||||
if l == nil || l.typ != linkTypeFile {
|
||||
panic("protontest: no file " + id)
|
||||
}
|
||||
rev := l.activeRevision()
|
||||
if rev == nil {
|
||||
panic("protontest: file " + id + " has no active revision")
|
||||
}
|
||||
f := StoredFile{
|
||||
Link: StoredLink{
|
||||
Name: l.name,
|
||||
NameHash: l.nameHash,
|
||||
NodeKey: l.nodeKey,
|
||||
NodePassphrase: l.nodePass.armored,
|
||||
NodePassphraseSignature: l.nodePass.signature,
|
||||
SignatureEmail: l.signatureEmail,
|
||||
NameSignatureEmail: l.nameSignatureEmail,
|
||||
MediaType: l.mediaType,
|
||||
ContentKeyPacket: l.contentKeyPacket,
|
||||
ContentKeyPacketSignature: l.contentKeyPacketSignature,
|
||||
CreateTime: l.createTime,
|
||||
ModifyTime: l.modifyTime,
|
||||
},
|
||||
Revision: StoredRevision{
|
||||
ManifestSignature: rev.manifestSignature,
|
||||
XAttr: rev.xattr,
|
||||
SignatureEmail: rev.signatureEmail,
|
||||
CreateTime: rev.createTime,
|
||||
},
|
||||
}
|
||||
for _, b := range rev.blocks {
|
||||
f.Revision.Blocks = append(f.Revision.Blocks, StoredBlock{
|
||||
Hash: bytes.Clone(b.hash),
|
||||
EncSignature: b.encSignature,
|
||||
SignatureEmail: b.signatureEmail,
|
||||
Data: bytes.Clone(b.data),
|
||||
})
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
// SeedStoredFile creates a file in parentID from f, stored as given
|
||||
// without any check, and returns its ID. It panics as insertLink does.
|
||||
func (u *User) SeedStoredFile(parentID string, f StoredFile) (id string) {
|
||||
rev := &revision{
|
||||
id: randomID(),
|
||||
state: revisionStateActive,
|
||||
createTime: f.Revision.CreateTime,
|
||||
manifestSignature: f.Revision.ManifestSignature,
|
||||
xattr: f.Revision.XAttr,
|
||||
signatureEmail: f.Revision.SignatureEmail,
|
||||
}
|
||||
for i, b := range f.Revision.Blocks {
|
||||
rev.blocks = append(rev.blocks, &block{
|
||||
index: i + 1,
|
||||
hash: bytes.Clone(b.Hash),
|
||||
data: bytes.Clone(b.Data),
|
||||
encSignature: b.EncSignature,
|
||||
signatureEmail: b.SignatureEmail,
|
||||
})
|
||||
}
|
||||
if rev.createTime == 0 {
|
||||
rev.createTime = time.Now().Unix()
|
||||
}
|
||||
return u.insertLink(parentID, &link{
|
||||
typ: linkTypeFile,
|
||||
name: f.Link.Name,
|
||||
nameHash: f.Link.NameHash,
|
||||
nodeKey: f.Link.NodeKey,
|
||||
nodePass: sealedPassphrase{armored: f.Link.NodePassphrase, signature: f.Link.NodePassphraseSignature},
|
||||
signatureEmail: f.Link.SignatureEmail,
|
||||
nameSignatureEmail: f.Link.NameSignatureEmail,
|
||||
mediaType: f.Link.MediaType,
|
||||
contentKeyPacket: f.Link.ContentKeyPacket,
|
||||
contentKeyPacketSignature: f.Link.ContentKeyPacketSignature,
|
||||
createTime: f.Link.CreateTime,
|
||||
modifyTime: f.Link.ModifyTime,
|
||||
revisions: []*revision{rev},
|
||||
})
|
||||
}
|
||||
|
||||
// StoredFolder is a folder node as the server stores it. Its Link has
|
||||
// no file members.
|
||||
type StoredFolder struct {
|
||||
Link StoredLink
|
||||
HashKey string // armored, encrypted to the node key
|
||||
XAttr string // armored; empty if none
|
||||
}
|
||||
|
||||
// SeedStoredFolder creates a folder in parentID from f, stored as given
|
||||
// without any check, and returns its ID. It panics as insertLink does.
|
||||
func (u *User) SeedStoredFolder(parentID string, f StoredFolder) (id string) {
|
||||
return u.insertLink(parentID, &link{
|
||||
typ: linkTypeFolder,
|
||||
name: f.Link.Name,
|
||||
nameHash: f.Link.NameHash,
|
||||
nodeKey: f.Link.NodeKey,
|
||||
nodePass: sealedPassphrase{armored: f.Link.NodePassphrase, signature: f.Link.NodePassphraseSignature},
|
||||
signatureEmail: f.Link.SignatureEmail,
|
||||
nameSignatureEmail: f.Link.NameSignatureEmail,
|
||||
createTime: f.Link.CreateTime,
|
||||
modifyTime: f.Link.ModifyTime,
|
||||
hashKey: f.HashKey,
|
||||
xattr: f.XAttr,
|
||||
})
|
||||
}
|
||||
|
||||
// FixedKeys is key material for AddUserWithKeys, in place of keys the
|
||||
// fake would generate.
|
||||
type FixedKeys struct {
|
||||
AddressKey string // armored, locked with AddressKeyPassphrase
|
||||
AddressKeyPassphrase string
|
||||
RootKey string // armored root folder node key, locked with RootKeyPassphrase
|
||||
RootKeyPassphrase string
|
||||
RootHashKey string // armored root folder hash key, encrypted to the root key
|
||||
}
|
||||
|
||||
// AddUserWithKeys is AddUser with the primary address key and the root
|
||||
// folder's node key and hash key taken from keys, so that files stored
|
||||
// by a client holding those keys can be seeded with SeedStoredFile. The
|
||||
// user key and share key are generated as usual. It panics if a key
|
||||
// doesn't unlock.
|
||||
func (s *Server) AddUserWithKeys(username, password string, keys FixedKeys) *User {
|
||||
addrKey, err := crypto.NewPrivateKeyFromArmored(keys.AddressKey, []byte(keys.AddressKeyPassphrase))
|
||||
mustCrypto("unlock fixed address key", err)
|
||||
rootKey, err := crypto.NewPrivateKeyFromArmored(keys.RootKey, []byte(keys.RootKeyPassphrase))
|
||||
mustCrypto("unlock fixed root key", err)
|
||||
u := newUser(s, username, password, password)
|
||||
addr := u.addresses[0]
|
||||
k := addr.keys[0]
|
||||
k.passphrase, k.armored, k.key = []byte(keys.AddressKeyPassphrase), keys.AddressKey, addrKey
|
||||
k.sealPassphrase(u.keys[0])
|
||||
root := lockedKey{key: rootKey, passphrase: []byte(keys.RootKeyPassphrase), armored: keys.RootKey}
|
||||
u.drive = s.newDriveWithRoot(addr, root, keys.RootHashKey)
|
||||
s.addUser(u)
|
||||
return u
|
||||
}
|
||||
@@ -0,0 +1,701 @@
|
||||
package protontest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"slices"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/ProtonMail/go-crypto/openpgp/packet"
|
||||
"github.com/ProtonMail/gopenpgp/v3/crypto"
|
||||
"github.com/rclone/rclone/backend/protondrive/api"
|
||||
)
|
||||
|
||||
const (
|
||||
// storageUploadPattern is the route of block uploads.
|
||||
storageUploadPattern = "/storage/upload/{token}"
|
||||
|
||||
// verificationCodeSize is the size of a draft's verification code,
|
||||
// and so of each block's verifier token.
|
||||
verificationCodeSize = 32
|
||||
|
||||
// maxUploadBlockSize is the largest encrypted block accepted.
|
||||
maxUploadBlockSize = 8 << 20
|
||||
|
||||
// intendedSizePrecision is the precision of IntendedUploadSize.
|
||||
intendedSizePrecision = 100_000
|
||||
)
|
||||
|
||||
// pendingBlock is a block of a draft revision requested for upload.
|
||||
type pendingBlock struct {
|
||||
index int
|
||||
encSignature string
|
||||
token []byte // verifier token
|
||||
hash []byte // SHA-256 the client declared; nil if none
|
||||
data []byte // nil until uploaded
|
||||
}
|
||||
|
||||
// uploadURL is a block upload URL issued by /drive/blocks.
|
||||
type uploadURL struct {
|
||||
token string
|
||||
user *User
|
||||
linkID string
|
||||
rev *revision
|
||||
block *pendingBlock
|
||||
expired bool
|
||||
}
|
||||
|
||||
// Wire types of the upload routes, named after and shaped like the
|
||||
// schemas in the SDK's driveTypes.ts.
|
||||
|
||||
type createFileRequest struct {
|
||||
ParentLinkID string
|
||||
Name string
|
||||
Hash string
|
||||
MIMEType string
|
||||
ClientUID *string
|
||||
IntendedUploadSize *int64
|
||||
NodeKey string
|
||||
NodePassphrase string
|
||||
NodePassphraseSignature string
|
||||
ContentKeyPacket string
|
||||
ContentKeyPacketSignature *string
|
||||
SignatureAddress *string
|
||||
}
|
||||
|
||||
type fileResponseJSON struct {
|
||||
ID string
|
||||
RevisionID string
|
||||
ClientUID *string
|
||||
}
|
||||
|
||||
type createFileResponse struct {
|
||||
File fileResponseJSON
|
||||
Code int
|
||||
}
|
||||
|
||||
type createRevisionRequest struct {
|
||||
CurrentRevisionID *string
|
||||
ClientUID *string
|
||||
IntendedUploadSize *int64
|
||||
}
|
||||
|
||||
type revisionIDJSON struct {
|
||||
ID string
|
||||
}
|
||||
|
||||
type createRevisionResponse struct {
|
||||
Revision revisionIDJSON
|
||||
Code int
|
||||
}
|
||||
|
||||
type verificationResponse struct {
|
||||
VerificationCode string
|
||||
ContentKeyPacket string
|
||||
Code int
|
||||
}
|
||||
|
||||
type verifierJSON struct {
|
||||
Token string
|
||||
}
|
||||
|
||||
type blockUploadInput struct {
|
||||
Index int
|
||||
Verifier *verifierJSON
|
||||
EncSignature *string
|
||||
Size *int64
|
||||
Hash *string
|
||||
}
|
||||
|
||||
type blockUploadRequest struct {
|
||||
LinkID string
|
||||
RevisionID string
|
||||
AddressID *string
|
||||
VolumeID *string
|
||||
BlockList []blockUploadInput
|
||||
ThumbnailList []struct{ Type int }
|
||||
}
|
||||
|
||||
type blockURLJSON struct {
|
||||
BareURL string
|
||||
Token string
|
||||
URL string
|
||||
Index int
|
||||
}
|
||||
|
||||
type blockUploadResponse struct {
|
||||
UploadLinks []blockURLJSON
|
||||
ThumbnailLinks []struct{}
|
||||
Code int
|
||||
}
|
||||
|
||||
type commitRevisionRequest struct {
|
||||
ManifestSignature string
|
||||
SignatureAddress *string
|
||||
XAttr *string
|
||||
ChecksumVerified bool
|
||||
Photo *struct{}
|
||||
}
|
||||
|
||||
// registerUpload registers the routes which upload files.
|
||||
func (s *Server) registerUpload() {
|
||||
s.handleDrive("POST", "/drive/v2/volumes/{volumeID}/files", s.handleCreateFile)
|
||||
s.handleDrive("POST", "/drive/v2/volumes/{volumeID}/files/{linkID}/revisions", s.handleCreateRevision)
|
||||
s.handleDrive("GET", "/drive/v2/volumes/{volumeID}/links/{linkID}/revisions/{revisionID}/verification", s.handleVerification)
|
||||
s.handleAuth("POST", "/drive/blocks", s.handleRequestUpload)
|
||||
s.handle("POST", storageUploadPattern, s.handleStorageUpload)
|
||||
s.handleDrive("PUT", "/drive/v2/volumes/{volumeID}/files/{linkID}/revisions/{revisionID}", s.handleCommit)
|
||||
s.handleDrive("DELETE", "/drive/v2/volumes/{volumeID}/files/{linkID}/revisions/{revisionID}", s.handleDeleteRevision)
|
||||
s.handleDrive("POST", "/drive/v2/volumes/{volumeID}/delete_multiple", s.handleDeleteMultiple)
|
||||
}
|
||||
|
||||
// ExpireUploadTokens makes every block upload URL issued so far answer
|
||||
// HTTP 404, as an expired one does.
|
||||
func (s *Server) ExpireUploadTokens() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for _, up := range s.uploads {
|
||||
up.expired = true
|
||||
}
|
||||
}
|
||||
|
||||
// StorageUploadPeak returns the most block uploads that were in
|
||||
// progress at once since the server started or ResetRequests.
|
||||
func (s *Server) StorageUploadPeak() int {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.storagePeak
|
||||
}
|
||||
|
||||
// nowLocked returns the server's clock. srv.mu must be held.
|
||||
func (s *Server) nowLocked() time.Time {
|
||||
return time.Now().Add(s.clockSkew)
|
||||
}
|
||||
|
||||
// newDraftRevision returns a draft revision created by clientUID.
|
||||
func newDraftRevision(clientUID *string) *revision {
|
||||
r := &revision{
|
||||
id: randomID(),
|
||||
state: revisionStateDraft,
|
||||
createTime: time.Now().Unix(),
|
||||
verificationCode: randomBytes(verificationCodeSize),
|
||||
pending: make(map[int]*pendingBlock),
|
||||
}
|
||||
if clientUID != nil {
|
||||
r.clientUID = *clientUID
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// checkIntendedSize returns an error if size, when given, is not
|
||||
// rounded as the SDK rounds it: the server must not learn the size.
|
||||
func checkIntendedSize(size *int64) error {
|
||||
if size == nil {
|
||||
return nil
|
||||
}
|
||||
if *size < 0 || (*size%intendedSizePrecision != 0 && *size != 4095) {
|
||||
return fmt.Errorf("IntendedUploadSize %d is not rounded", *size)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkContentKeyPacket returns an error unless packet64 is the base64
|
||||
// of one v6 PKESK: new content is written in the RFC 9580 format.
|
||||
func checkContentKeyPacket(packet64 string) error {
|
||||
raw, err := base64.StdEncoding.DecodeString(packet64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("not base64: %w", err)
|
||||
}
|
||||
r := packet.NewOpaqueReader(bytes.NewReader(raw))
|
||||
op, err := r.Next()
|
||||
if err != nil {
|
||||
return fmt.Errorf("malformed packet: %w", err)
|
||||
}
|
||||
if op.Tag != tagPKESK || len(op.Contents) == 0 || op.Contents[0] != 6 {
|
||||
return fmt.Errorf("packet with tag %d version %d, want a v6 PKESK", op.Tag, firstByte(op.Contents))
|
||||
}
|
||||
if _, err := r.Next(); err != io.EOF {
|
||||
return errors.New("more than one packet")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// contentKeyVersion returns the version of the PKESK of a stored
|
||||
// content key packet, or -1.
|
||||
func contentKeyVersion(packet64 string) int {
|
||||
raw, err := base64.StdEncoding.DecodeString(packet64)
|
||||
if err != nil {
|
||||
return -1
|
||||
}
|
||||
op, err := packet.NewOpaqueReader(bytes.NewReader(raw)).Next()
|
||||
if err != nil || op.Tag != tagPKESK {
|
||||
return -1
|
||||
}
|
||||
return int(firstByte(op.Contents))
|
||||
}
|
||||
|
||||
// checkBlockFormat returns an error unless data is one SEIPD packet of
|
||||
// version: SEIPDv2 for content whose key packet is a v6 PKESK, SEIPDv1
|
||||
// for a v3 one.
|
||||
func checkBlockFormat(data []byte, version int) error {
|
||||
r := packet.NewOpaqueReader(bytes.NewReader(data))
|
||||
op, err := r.Next()
|
||||
if err != nil {
|
||||
return fmt.Errorf("malformed packet: %w", err)
|
||||
}
|
||||
if op.Tag != tagSEIPD || int(firstByte(op.Contents)) != version {
|
||||
return fmt.Errorf("packet with tag %d version %d, want SEIPDv%d", op.Tag, firstByte(op.Contents), version)
|
||||
}
|
||||
if _, err := r.Next(); err != io.EOF {
|
||||
return errors.New("more than one packet")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// firstByte returns b[0], or 0 if b is empty.
|
||||
func firstByte(b []byte) byte {
|
||||
if len(b) == 0 {
|
||||
return 0
|
||||
}
|
||||
return b[0]
|
||||
}
|
||||
|
||||
// draftRevision returns the draft revision id of file l, or nil.
|
||||
func draftRevision(l *link, id string) *revision {
|
||||
if l == nil || l.typ != linkTypeFile {
|
||||
return nil
|
||||
}
|
||||
for _, r := range l.revisions {
|
||||
if r.id == id && r.state == revisionStateDraft {
|
||||
return r
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// handleCreateFile creates a draft file, with a draft revision, from
|
||||
// key material the client generated.
|
||||
func (s *Server) handleCreateFile(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
||||
var req createFileRequest
|
||||
if !decodeRequest(w, r, &req) {
|
||||
return
|
||||
}
|
||||
parent := d.activeFolder(req.ParentLinkID)
|
||||
if parent == nil {
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Parent folder not found")
|
||||
return
|
||||
}
|
||||
err := errors.Join(
|
||||
checkHash(req.Hash),
|
||||
checkSigner(u, "SignatureAddress", req.SignatureAddress),
|
||||
checkMessages(map[string]string{"Name": req.Name, "NodePassphrase": req.NodePassphrase}),
|
||||
annotateField("ContentKeyPacket", checkContentKeyPacket(req.ContentKeyPacket)),
|
||||
checkIntendedSize(req.IntendedUploadSize),
|
||||
)
|
||||
switch {
|
||||
case err != nil:
|
||||
case req.NodePassphraseSignature == "":
|
||||
err = errors.New("NodePassphraseSignature is required")
|
||||
case req.ContentKeyPacketSignature == nil || *req.ContentKeyPacketSignature == "":
|
||||
err = errors.New("ContentKeyPacketSignature is required")
|
||||
case req.MIMEType == "":
|
||||
err = errors.New("MIMEType is required")
|
||||
default:
|
||||
err = annotateField("NodeKey", checkFileKey(req.NodeKey))
|
||||
}
|
||||
if err != nil {
|
||||
writeInvalid(w, err)
|
||||
return
|
||||
}
|
||||
if other := d.conflict(parent.id, req.Hash, ""); other != nil {
|
||||
writeConflict(w, other)
|
||||
return
|
||||
}
|
||||
now := time.Now().Unix()
|
||||
rev := newDraftRevision(req.ClientUID)
|
||||
l := &link{
|
||||
id: randomID(),
|
||||
parentID: parent.id,
|
||||
typ: linkTypeFile,
|
||||
state: linkStateDraft,
|
||||
createTime: now,
|
||||
modifyTime: now,
|
||||
name: req.Name,
|
||||
nameHash: req.Hash,
|
||||
nodeKey: req.NodeKey,
|
||||
nodePass: sealedPassphrase{armored: req.NodePassphrase, signature: req.NodePassphraseSignature},
|
||||
signatureEmail: *req.SignatureAddress,
|
||||
nameSignatureEmail: *req.SignatureAddress,
|
||||
mediaType: req.MIMEType,
|
||||
contentKeyPacket: req.ContentKeyPacket,
|
||||
contentKeyPacketSignature: *req.ContentKeyPacketSignature,
|
||||
revisions: []*revision{rev},
|
||||
}
|
||||
d.addLink(l)
|
||||
writeJSON(w, http.StatusOK, &createFileResponse{
|
||||
File: fileResponseJSON{ID: l.id, RevisionID: rev.id, ClientUID: nullable(rev.clientUID)},
|
||||
Code: api.CodeOK,
|
||||
})
|
||||
}
|
||||
|
||||
// handleCreateRevision creates a draft revision of an active file whose
|
||||
// active revision is CurrentRevisionID.
|
||||
func (s *Server) handleCreateRevision(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
||||
var req createRevisionRequest
|
||||
if !decodeRequest(w, r, &req) {
|
||||
return
|
||||
}
|
||||
l := d.activeLink(r.PathValue("linkID"))
|
||||
if l == nil || l.typ != linkTypeFile {
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "File not found")
|
||||
return
|
||||
}
|
||||
if err := checkIntendedSize(req.IntendedUploadSize); err != nil {
|
||||
writeInvalid(w, err)
|
||||
return
|
||||
}
|
||||
active := l.activeRevision()
|
||||
if active == nil || req.CurrentRevisionID == nil || *req.CurrentRevisionID != active.id {
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidRequirements, "protontest: CurrentRevisionID is not the active revision: the file changed")
|
||||
return
|
||||
}
|
||||
rev := newDraftRevision(req.ClientUID)
|
||||
l.revisions = append(l.revisions, rev)
|
||||
writeJSON(w, http.StatusOK, &createRevisionResponse{Revision: revisionIDJSON{ID: rev.id}, Code: api.CodeOK})
|
||||
}
|
||||
|
||||
// handleVerification returns the verification code and content key
|
||||
// packet of a draft revision.
|
||||
func (s *Server) handleVerification(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
||||
l := d.links[r.PathValue("linkID")]
|
||||
rev := draftRevision(l, r.PathValue("revisionID"))
|
||||
if rev == nil {
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Revision not found")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, &verificationResponse{
|
||||
VerificationCode: base64.StdEncoding.EncodeToString(rev.verificationCode),
|
||||
ContentKeyPacket: l.contentKeyPacket,
|
||||
Code: api.CodeOK,
|
||||
})
|
||||
}
|
||||
|
||||
// handleRequestUpload issues upload URLs on this server for blocks of a
|
||||
// draft revision. Requesting a block again replaces it, and its URL.
|
||||
func (s *Server) handleRequestUpload(w http.ResponseWriter, r *http.Request, u *User) {
|
||||
var req blockUploadRequest
|
||||
if !decodeRequest(w, r, &req) {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
d := u.drive
|
||||
if d == nil || req.VolumeID == nil || *req.VolumeID != d.volumeID {
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Volume not found")
|
||||
return
|
||||
}
|
||||
l := d.links[req.LinkID]
|
||||
rev := draftRevision(l, req.RevisionID)
|
||||
if rev == nil {
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Revision not found")
|
||||
return
|
||||
}
|
||||
if req.AddressID == nil || !slices.ContainsFunc(u.addresses, func(a *address) bool { return a.id == *req.AddressID }) {
|
||||
writeInvalid(w, errors.New("AddressID must be an address of the user"))
|
||||
return
|
||||
}
|
||||
if len(req.ThumbnailList) > 0 {
|
||||
writeInvalid(w, errors.New("protontest: thumbnails are not supported"))
|
||||
return
|
||||
}
|
||||
blocks := make([]*pendingBlock, 0, len(req.BlockList))
|
||||
for _, in := range req.BlockList {
|
||||
b, err := pendingBlockOf(in)
|
||||
if err != nil {
|
||||
writeInvalid(w, fmt.Errorf("block %d: %w", in.Index, err))
|
||||
return
|
||||
}
|
||||
blocks = append(blocks, b)
|
||||
}
|
||||
resp := &blockUploadResponse{UploadLinks: []blockURLJSON{}, ThumbnailLinks: []struct{}{}, Code: api.CodeOK}
|
||||
for _, b := range blocks {
|
||||
rev.pending[b.index] = b
|
||||
id, token := randomID(), s.newSecretLocked(StorageToken)
|
||||
s.uploads[id] = &uploadURL{token: token, user: u, linkID: l.id, rev: rev, block: b}
|
||||
bareURL := s.URL() + "/storage/upload/" + id
|
||||
resp.UploadLinks = append(resp.UploadLinks, blockURLJSON{BareURL: bareURL, Token: token, URL: bareURL, Index: b.index})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// pendingBlockOf returns the block in an upload request, checked.
|
||||
func pendingBlockOf(in blockUploadInput) (*pendingBlock, error) {
|
||||
b := &pendingBlock{index: in.Index}
|
||||
if in.Index < 1 {
|
||||
return nil, errors.New("field Index must be at least 1")
|
||||
}
|
||||
if in.Verifier == nil {
|
||||
return nil, errors.New("field Verifier is required")
|
||||
}
|
||||
token, err := base64.StdEncoding.DecodeString(in.Verifier.Token)
|
||||
if err != nil || len(token) != verificationCodeSize {
|
||||
return nil, fmt.Errorf("Verifier.Token is not the base64 of %d bytes", verificationCodeSize)
|
||||
}
|
||||
b.token = token
|
||||
if in.EncSignature == nil || *in.EncSignature == "" {
|
||||
return nil, errors.New("EncSignature is required")
|
||||
}
|
||||
b.encSignature = *in.EncSignature
|
||||
if in.Hash != nil {
|
||||
if b.hash, err = base64.StdEncoding.DecodeString(*in.Hash); err != nil || len(b.hash) != sha256.Size {
|
||||
return nil, errors.New("field Hash is not the base64 of a SHA-256")
|
||||
}
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// handleStorageUpload stores the block of a multipart upload to a URL
|
||||
// issued by handleRequestUpload, which carries its pm-storage-token and
|
||||
// none of the session's credentials.
|
||||
func (s *Server) handleStorageUpload(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "" || r.Header.Get("x-pm-uid") != "" {
|
||||
writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: session credentials must not be sent to the storage host")
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
up := s.uploads[r.PathValue("token")]
|
||||
usable := up != nil && !up.expired
|
||||
s.mu.Unlock()
|
||||
switch {
|
||||
case !usable:
|
||||
writeError(w, http.StatusNotFound, api.CodeNotExists, "protontest: no such upload URL, or it expired")
|
||||
return
|
||||
case r.Header.Get("pm-storage-token") != up.token:
|
||||
writeError(w, http.StatusForbidden, api.CodeNotEnoughPermissions, "protontest: missing or wrong pm-storage-token")
|
||||
return
|
||||
}
|
||||
data, err := readBlockPart(r)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: bad block upload: "+err.Error())
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if up.rev.state != revisionStateDraft || up.rev.pending[up.block.index] != up.block {
|
||||
writeError(w, http.StatusNotFound, api.CodeNotExists, "protontest: the block is no longer awaited")
|
||||
return
|
||||
}
|
||||
up.block.data = data
|
||||
writeJSON(w, http.StatusOK, &codeJSON{Code: api.CodeOK})
|
||||
}
|
||||
|
||||
// readBlockPart returns the content of the one part, named Block, of
|
||||
// the multipart body of r.
|
||||
func readBlockPart(r *http.Request) ([]byte, error) {
|
||||
mr, err := r.MultipartReader()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var data []byte
|
||||
for {
|
||||
part, err := mr.NextPart()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if part.FormName() != "Block" || data != nil {
|
||||
return nil, fmt.Errorf("unexpected part %q", part.FormName())
|
||||
}
|
||||
if data, err = io.ReadAll(io.LimitReader(part, maxUploadBlockSize+1)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(data) > maxUploadBlockSize {
|
||||
return nil, fmt.Errorf("block larger than %d bytes", maxUploadBlockSize)
|
||||
}
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return nil, errors.New("no Block part, or it is empty")
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// handleCommit makes a draft revision with every requested block
|
||||
// uploaded the file's active revision, after checking each block's
|
||||
// verifier token and format, the manifest signature over the uploaded
|
||||
// blocks and the extended attributes' format.
|
||||
func (s *Server) handleCommit(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
||||
var req commitRevisionRequest
|
||||
if !decodeRequest(w, r, &req) {
|
||||
return
|
||||
}
|
||||
l := d.links[r.PathValue("linkID")]
|
||||
rev := draftRevision(l, r.PathValue("revisionID"))
|
||||
if rev == nil {
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Revision not found")
|
||||
return
|
||||
}
|
||||
xattr := ""
|
||||
if req.XAttr != nil {
|
||||
xattr = *req.XAttr
|
||||
}
|
||||
err := errors.Join(
|
||||
checkSigner(u, "SignatureAddress", req.SignatureAddress),
|
||||
checkMessages(map[string]string{"XAttr": xattr}),
|
||||
)
|
||||
if err == nil && req.ManifestSignature == "" {
|
||||
err = errors.New("ManifestSignature is required")
|
||||
}
|
||||
if err != nil {
|
||||
writeInvalid(w, err)
|
||||
return
|
||||
}
|
||||
blocks, err := uploadedBlocks(rev, *req.SignatureAddress)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidRequirements, "protontest: "+err.Error())
|
||||
return
|
||||
}
|
||||
var manifest []byte
|
||||
var formatErrs []error
|
||||
version := 1
|
||||
if contentKeyVersion(l.contentKeyPacket) == 6 {
|
||||
version = 2
|
||||
}
|
||||
for _, b := range blocks {
|
||||
manifest = append(manifest, b.hash...)
|
||||
formatErrs = append(formatErrs, annotateField(fmt.Sprintf("block %d", b.index), checkBlockFormat(b.data, version)))
|
||||
}
|
||||
addr := u.addressByEmailLocked(*req.SignatureAddress)
|
||||
keys := make([]*crypto.Key, 0, len(addr.keys))
|
||||
for _, k := range addr.keys {
|
||||
keys = append(keys, k.key)
|
||||
}
|
||||
sigErr := verifyDetached(manifest, []byte(req.ManifestSignature), crypto.Armor, keyRing(keys...), s.nowLocked())
|
||||
if err := errors.Join(append(formatErrs, annotateField("manifest", sigErr))...); err != nil {
|
||||
writeInvalid(w, err)
|
||||
return
|
||||
}
|
||||
before := d.linkDetails(l)
|
||||
event := EventUpdate
|
||||
if l.state == linkStateDraft {
|
||||
event = EventCreate
|
||||
}
|
||||
for _, other := range l.revisions {
|
||||
if other.state == revisionStateActive {
|
||||
other.state = revisionStateObsolete
|
||||
}
|
||||
}
|
||||
now := time.Now().Unix()
|
||||
rev.state, rev.createTime = revisionStateActive, now
|
||||
rev.manifestSignature, rev.xattr, rev.signatureEmail = req.ManifestSignature, xattr, *req.SignatureAddress
|
||||
rev.blocks, rev.pending, rev.verificationCode = blocks, nil, nil
|
||||
l.state, l.modifyTime = linkStateActive, now
|
||||
d.logLink(event, l)
|
||||
s.dropUploadsLocked(rev)
|
||||
s.lagLocked(l.id, &before)
|
||||
writeJSON(w, http.StatusOK, &codeJSON{Code: api.CodeOK})
|
||||
}
|
||||
|
||||
// uploadedBlocks returns the blocks of draft rev, signed by email, after
|
||||
// checking that blocks 1 to n were requested and each uploaded, with the
|
||||
// hash it was declared with, if any, and its verifier token.
|
||||
func uploadedBlocks(rev *revision, email string) ([]*block, error) {
|
||||
indexes := make([]int, 0, len(rev.pending))
|
||||
for i := range rev.pending {
|
||||
indexes = append(indexes, i)
|
||||
}
|
||||
sort.Ints(indexes)
|
||||
blocks := make([]*block, 0, len(indexes))
|
||||
for i, index := range indexes {
|
||||
p := rev.pending[index]
|
||||
switch {
|
||||
case index != i+1:
|
||||
return nil, fmt.Errorf("block %d was not requested", i+1)
|
||||
case p.data == nil:
|
||||
return nil, fmt.Errorf("block %d was not uploaded", index)
|
||||
}
|
||||
sum := sha256.Sum256(p.data)
|
||||
if p.hash != nil && !bytes.Equal(p.hash, sum[:]) {
|
||||
return nil, fmt.Errorf("block %d: declared hash doesn't match the uploaded block", index)
|
||||
}
|
||||
if want := xorPrefix(rev.verificationCode, p.data); !bytes.Equal(p.token, want) {
|
||||
return nil, fmt.Errorf("block %d: verifier token doesn't match the uploaded block", index)
|
||||
}
|
||||
blocks = append(blocks, &block{index: index, hash: sum[:], data: p.data, encSignature: p.encSignature, signatureEmail: email})
|
||||
}
|
||||
return blocks, nil
|
||||
}
|
||||
|
||||
// xorPrefix returns code XOR the start of data, padded with zeros: the
|
||||
// verifier token of a block.
|
||||
func xorPrefix(code, data []byte) []byte {
|
||||
out := make([]byte, len(code))
|
||||
for i := range code {
|
||||
out[i] = code[i]
|
||||
if i < len(data) {
|
||||
out[i] ^= data[i]
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// dropUploadsLocked forgets the upload URLs of rev. srv.mu must be
|
||||
// held.
|
||||
func (s *Server) dropUploadsLocked(rev *revision) {
|
||||
for id, up := range s.uploads {
|
||||
if up.rev == rev {
|
||||
delete(s.uploads, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleDeleteRevision deletes a draft revision.
|
||||
func (s *Server) handleDeleteRevision(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
||||
l := d.links[r.PathValue("linkID")]
|
||||
rev := draftRevision(l, r.PathValue("revisionID"))
|
||||
if rev == nil {
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Draft revision not found")
|
||||
return
|
||||
}
|
||||
l.revisions = slices.DeleteFunc(l.revisions, func(other *revision) bool { return other == rev })
|
||||
s.dropUploadsLocked(rev)
|
||||
writeJSON(w, http.StatusOK, &codeJSON{Code: api.CodeOK})
|
||||
}
|
||||
|
||||
// handleDeleteMultiple permanently deletes up to 100 draft links,
|
||||
// answering for each.
|
||||
func (s *Server) handleDeleteMultiple(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
||||
var req linksRequest
|
||||
if !decodeRequest(w, r, &req) {
|
||||
return
|
||||
}
|
||||
if len(req.LinkIDs) > maxLinksPerRequest {
|
||||
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidValue, fmt.Sprintf("protontest: %d link IDs, at most %d allowed", len(req.LinkIDs), maxLinksPerRequest))
|
||||
return
|
||||
}
|
||||
resp := &multiResponse{Code: api.CodeOKMany, Responses: []linkResultJSON{}}
|
||||
for _, id := range req.LinkIDs {
|
||||
result := linkResultJSON{LinkID: id, Response: codeJSON{Code: api.CodeOK}}
|
||||
l := d.links[id]
|
||||
switch {
|
||||
case l == nil:
|
||||
result.Response = codeJSON{Code: api.CodeNotExists, Error: "File or folder not found"}
|
||||
case l.state != linkStateDraft:
|
||||
result.Response = codeJSON{Code: api.CodeInvalidRequirements, Error: "protontest: only drafts can be deleted"}
|
||||
default:
|
||||
for _, rev := range l.revisions {
|
||||
s.dropUploadsLocked(rev)
|
||||
}
|
||||
delete(d.links, id)
|
||||
}
|
||||
resp.Responses = append(resp.Responses, result)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
package protontest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/ProtonMail/go-crypto/openpgp/packet"
|
||||
"github.com/ProtonMail/go-crypto/openpgp/s2k"
|
||||
"github.com/ProtonMail/gopenpgp/v3/crypto"
|
||||
"github.com/ProtonMail/gopenpgp/v3/profile"
|
||||
"github.com/rclone/rclone/backend/protondrive/api"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const testClientUID = "fake-test-client"
|
||||
|
||||
// uploader uploads files to the root of a user's drive as the SDK
|
||||
// does, step by step, for tests to spoil one step.
|
||||
type uploader struct {
|
||||
t *testing.T
|
||||
s *Server
|
||||
u *User
|
||||
sess Session
|
||||
volume string
|
||||
}
|
||||
|
||||
func newUploader(t *testing.T) *uploader {
|
||||
s := New(t)
|
||||
u := s.AddUser("user", "pass")
|
||||
return &uploader{t: t, s: s, u: u, sess: s.NewSession(u), volume: u.VolumeID()}
|
||||
}
|
||||
|
||||
// fileDraft is a file being uploaded, with its keys.
|
||||
type fileDraft struct {
|
||||
req *createFileRequest
|
||||
node lockedKey
|
||||
ck contentKey
|
||||
signer *crypto.Key
|
||||
linkID string
|
||||
revID string
|
||||
code []byte
|
||||
content []byte
|
||||
}
|
||||
|
||||
// newFileRequest returns a create file request for name in the root
|
||||
// made as the SDK's createDraft does.
|
||||
func (x *uploader) newFileRequest(name string) *fileDraft {
|
||||
v := x.u.view()
|
||||
parentKey, parentHashKey := v.folderKeys(v.d.rootID)
|
||||
node := newDriveKey(true)
|
||||
x.s.rememberKey(node)
|
||||
pass := sealPassphrase(node.passphrase, parentKey, v.addrKey)
|
||||
ck := newContentKey(node.key, true)
|
||||
uid := testClientUID
|
||||
return &fileDraft{
|
||||
req: &createFileRequest{
|
||||
ParentLinkID: v.d.rootID,
|
||||
Name: encryptArmored([]byte(name), parentKey, v.addrKey, false),
|
||||
Hash: lookupHash(parentHashKey, name),
|
||||
MIMEType: "text/plain",
|
||||
ClientUID: &uid,
|
||||
NodeKey: node.armored,
|
||||
NodePassphrase: pass.armored,
|
||||
NodePassphraseSignature: pass.signature,
|
||||
ContentKeyPacket: ck.packet,
|
||||
ContentKeyPacketSignature: &ck.signature,
|
||||
SignatureAddress: &v.email,
|
||||
},
|
||||
node: node,
|
||||
ck: ck,
|
||||
signer: v.addrKey,
|
||||
}
|
||||
}
|
||||
|
||||
// send sends in with method to path as the user.
|
||||
func (x *uploader) send(method, path string, in any) (int, []byte) {
|
||||
return sendJSON(x.t, x.s, x.sess, method, path, in)
|
||||
}
|
||||
|
||||
// create creates the draft of f, failing the test if it can't.
|
||||
func (x *uploader) create(f *fileDraft) {
|
||||
t := x.t
|
||||
status, body := x.send("POST", "/drive/v2/volumes/"+x.volume+"/files", f.req)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
var resp createFileResponse
|
||||
require.NoError(t, json.Unmarshal(body, &resp))
|
||||
f.linkID, f.revID = resp.File.ID, resp.File.RevisionID
|
||||
x.loadCode(f)
|
||||
}
|
||||
|
||||
// loadCode fetches the verification code of f's draft revision.
|
||||
func (x *uploader) loadCode(f *fileDraft) {
|
||||
var ver verificationResponse
|
||||
status, body := getJSON(x.t, x.s, x.sess, "/drive/v2/volumes/"+x.volume+"/links/"+f.linkID+"/revisions/"+f.revID+"/verification", &ver)
|
||||
require.Equal(x.t, http.StatusOK, status, "body: %s", body)
|
||||
code, err := base64.StdEncoding.DecodeString(ver.VerificationCode)
|
||||
require.NoError(x.t, err)
|
||||
require.Len(x.t, code, verificationCodeSize)
|
||||
assert.Equal(x.t, f.ck.packet, ver.ContentKeyPacket)
|
||||
f.code = code
|
||||
}
|
||||
|
||||
// testBlock is an encrypted block with its upload request entry.
|
||||
type testBlock struct {
|
||||
data []byte
|
||||
in blockUploadInput
|
||||
}
|
||||
|
||||
// encrypt encrypts content as f's blocks of blockSize.
|
||||
func (f *fileDraft) encrypt(content []byte) []testBlock {
|
||||
f.content = content
|
||||
var blocks []testBlock
|
||||
for i := 0; i < len(content); i += blockSize {
|
||||
data, encSig := f.ck.encryptBlock(content[i:min(i+blockSize, len(content))], f.node.key, f.signer)
|
||||
blocks = append(blocks, testBlock{data: data, in: blockUploadInput{
|
||||
Index: len(blocks) + 1,
|
||||
Verifier: &verifierJSON{Token: base64.StdEncoding.EncodeToString(xorPrefix(f.code, data))},
|
||||
EncSignature: &encSig,
|
||||
}})
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
// requestURLs requests upload URLs for blocks of f.
|
||||
func (x *uploader) requestURLs(f *fileDraft, blocks []testBlock) (int, []byte, []blockURLJSON) {
|
||||
addressID := x.u.addresses[0].id
|
||||
req := &blockUploadRequest{LinkID: f.linkID, RevisionID: f.revID, AddressID: &addressID, VolumeID: &x.volume}
|
||||
for _, b := range blocks {
|
||||
req.BlockList = append(req.BlockList, b.in)
|
||||
}
|
||||
status, body := x.send("POST", "/drive/blocks", req)
|
||||
var resp blockUploadResponse
|
||||
if status == http.StatusOK {
|
||||
require.NoError(x.t, json.Unmarshal(body, &resp))
|
||||
}
|
||||
return status, body, resp.UploadLinks
|
||||
}
|
||||
|
||||
// putBlock uploads data to link as the SDK does, with extra headers,
|
||||
// and returns the HTTP status.
|
||||
func (x *uploader) putBlock(link blockURLJSON, data []byte, header map[string]string) int {
|
||||
t := x.t
|
||||
var body bytes.Buffer
|
||||
mw := multipart.NewWriter(&body)
|
||||
w, err := mw.CreateFormFile("Block", "blob")
|
||||
require.NoError(t, err)
|
||||
_, err = w.Write(data)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, mw.Close())
|
||||
req, err := http.NewRequest("POST", link.BareURL, &body)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
req.Header.Set("x-pm-appversion", testAppVersion)
|
||||
req.Header.Set("pm-storage-token", link.Token)
|
||||
for k, v := range header {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
resp, err := x.s.Client().Do(req)
|
||||
require.NoError(t, err)
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
return resp.StatusCode
|
||||
}
|
||||
|
||||
// uploadAll requests URLs for blocks and uploads each.
|
||||
func (x *uploader) uploadAll(f *fileDraft, blocks []testBlock) {
|
||||
status, body, links := x.requestURLs(f, blocks)
|
||||
require.Equal(x.t, http.StatusOK, status, "body: %s", body)
|
||||
require.Len(x.t, links, len(blocks))
|
||||
for i, link := range links {
|
||||
require.Equal(x.t, blocks[i].in.Index, link.Index)
|
||||
require.Equal(x.t, http.StatusOK, x.putBlock(link, blocks[i].data, nil))
|
||||
}
|
||||
}
|
||||
|
||||
// commitRequest returns the commit request of f with blocks, as the SDK
|
||||
// makes it.
|
||||
func (f *fileDraft) commitRequest(blocks []testBlock) *commitRevisionRequest {
|
||||
var manifest []byte
|
||||
var sizes []int64
|
||||
for i, b := range blocks {
|
||||
sum := sha256.Sum256(b.data)
|
||||
manifest = append(manifest, sum[:]...)
|
||||
sizes = append(sizes, int64(min(blockSize, len(f.content)-i*blockSize)))
|
||||
}
|
||||
xattr := encryptArmored(newFileXAttr(f.content, sizes, "2024-01-02T03:04:05.000Z"), f.node.key, f.signer, true)
|
||||
return &commitRevisionRequest{
|
||||
ManifestSignature: signArmored(manifest, f.signer),
|
||||
SignatureAddress: f.req.SignatureAddress,
|
||||
XAttr: &xattr,
|
||||
}
|
||||
}
|
||||
|
||||
// commit commits f's draft revision with req.
|
||||
func (x *uploader) commit(f *fileDraft, req *commitRevisionRequest) (int, []byte) {
|
||||
return x.send("PUT", "/drive/v2/volumes/"+x.volume+"/files/"+f.linkID+"/revisions/"+f.revID, req)
|
||||
}
|
||||
|
||||
func TestCreateFileFormats(t *testing.T) {
|
||||
x := newUploader(t)
|
||||
post := func(f *fileDraft) (int, []byte) {
|
||||
return x.send("POST", "/drive/v2/volumes/"+x.volume+"/files", f.req)
|
||||
}
|
||||
for variant, bad := range aeadMessages(t) {
|
||||
for field, spoil := range map[string]func(req *createFileRequest){
|
||||
"Name": func(req *createFileRequest) { req.Name = bad },
|
||||
"NodePassphrase": func(req *createFileRequest) { req.NodePassphrase = bad },
|
||||
} {
|
||||
t.Run(field+" "+variant, func(t *testing.T) {
|
||||
f := x.newFileRequest("f")
|
||||
spoil(f.req)
|
||||
status, body := post(f)
|
||||
requireRejected(t, api.CodeInvalidValue, status, body, field)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
aeadLocked := profile.Default()
|
||||
aeadLocked.AeadKeyEncryption = &packet.AEADConfig{}
|
||||
salted := profile.Default()
|
||||
salted.S2kKeyEncryption = &s2k.Config{S2KMode: s2k.SaltedS2K, PassphraseIsHighEntropy: true}
|
||||
v6Key, err := crypto.PGPWithProfile(profile.RFC9580()).KeyGeneration().AddUserId(driveKeyName, "").New().GenerateKey()
|
||||
require.NoError(t, err)
|
||||
v6Locked, err := crypto.PGPWithProfile(profile.RFC9580()).LockKey(v6Key, newPassphrase())
|
||||
require.NoError(t, err)
|
||||
v6Armored, err := v6Locked.Armor()
|
||||
require.NoError(t, err)
|
||||
for name, tc := range map[string]struct {
|
||||
key string
|
||||
want string
|
||||
}{
|
||||
"v6": {v6Armored, "not a v4 key"},
|
||||
"AEAD locked": {lockedWith(t, aeadLocked), "locked with AEAD"},
|
||||
"salted S2K": {lockedWith(t, salted), "S2K mode 1"},
|
||||
} {
|
||||
t.Run("NodeKey "+name, func(t *testing.T) {
|
||||
f := x.newFileRequest("f")
|
||||
f.req.NodeKey = tc.key
|
||||
status, body := post(f)
|
||||
requireRejected(t, api.CodeInvalidValue, status, body, "NodeKey", tc.want)
|
||||
})
|
||||
}
|
||||
|
||||
legacy := newContentKey(newDriveKey(false).key, false)
|
||||
unrounded := int64(123_456)
|
||||
for name, tc := range map[string]struct {
|
||||
spoil func(req *createFileRequest)
|
||||
want string
|
||||
}{
|
||||
"v3 content key packet": {func(req *createFileRequest) { req.ContentKeyPacket = legacy.packet }, "v6 PKESK"},
|
||||
"no content key sig": {func(req *createFileRequest) { req.ContentKeyPacketSignature = nil }, "ContentKeyPacketSignature"},
|
||||
"no passphrase sig": {func(req *createFileRequest) { req.NodePassphraseSignature = "" }, "NodePassphraseSignature"},
|
||||
"unrounded size": {func(req *createFileRequest) { req.IntendedUploadSize = &unrounded }, "IntendedUploadSize"},
|
||||
"no signer": {func(req *createFileRequest) { req.SignatureAddress = nil }, "SignatureAddress"},
|
||||
"no media type": {func(req *createFileRequest) { req.MIMEType = "" }, "MIMEType"},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
f := x.newFileRequest("f")
|
||||
tc.spoil(f.req)
|
||||
status, body := post(f)
|
||||
requireRejected(t, api.CodeInvalidValue, status, body, tc.want)
|
||||
})
|
||||
}
|
||||
assert.Empty(t, x.u.Drafts())
|
||||
|
||||
// The name hash must be unique, and a conflict names the draft and
|
||||
// its creator.
|
||||
f := x.newFileRequest("f")
|
||||
rounded := int64(200_000)
|
||||
f.req.IntendedUploadSize = &rounded
|
||||
x.create(f)
|
||||
assert.Equal(t, []string{f.linkID}, x.u.Drafts())
|
||||
status, body := post(x.newFileRequest("f"))
|
||||
requireRejected(t, api.CodeAlreadyExists, status, body)
|
||||
var conflict conflictResponse
|
||||
require.NoError(t, json.Unmarshal(body, &conflict))
|
||||
assert.Equal(t, f.linkID, conflict.Details.ConflictLinkID)
|
||||
assert.Nil(t, conflict.Details.ConflictRevisionID)
|
||||
require.NotNil(t, conflict.Details.ConflictDraftRevisionID)
|
||||
assert.Equal(t, f.revID, *conflict.Details.ConflictDraftRevisionID)
|
||||
require.NotNil(t, conflict.Details.ConflictDraftClientUID)
|
||||
assert.Equal(t, testClientUID, *conflict.Details.ConflictDraftClientUID)
|
||||
assert.Empty(t, x.u.Dump(), "a draft is dumped")
|
||||
}
|
||||
|
||||
func TestCommitChecks(t *testing.T) {
|
||||
x := newUploader(t)
|
||||
content := patterned(blockSize + 1000)
|
||||
n := 0
|
||||
// prepare returns a new draft with content encrypted, its blocks
|
||||
// and their commit request.
|
||||
prepare := func() (*fileDraft, []testBlock, *commitRevisionRequest) {
|
||||
n++
|
||||
f := x.newFileRequest("f" + strconv.Itoa(n))
|
||||
x.create(f)
|
||||
blocks := f.encrypt(content)
|
||||
return f, blocks, f.commitRequest(blocks)
|
||||
}
|
||||
impostor := generateKey("impostor", "impostor@proton.test")
|
||||
empty := ""
|
||||
aead := aeadMessages(t)["v6 PKESK and SEIPDv2"]
|
||||
legacy := newContentKey(newDriveKey(false).key, false)
|
||||
otherHash := base64.StdEncoding.EncodeToString(make([]byte, sha256.Size))
|
||||
for name, tc := range map[string]struct {
|
||||
spoil func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock
|
||||
code int
|
||||
want string
|
||||
}{
|
||||
"AEAD XAttr": {func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock {
|
||||
req.XAttr = &aead
|
||||
return blocks
|
||||
}, api.CodeInvalidValue, "XAttr"},
|
||||
"empty XAttr": {func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock {
|
||||
req.XAttr = &empty
|
||||
return blocks
|
||||
}, api.CodeInvalidValue, "XAttr"},
|
||||
"no XAttr": {func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock {
|
||||
req.XAttr = nil
|
||||
return blocks
|
||||
}, api.CodeInvalidValue, "XAttr"},
|
||||
"verifier": {func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock {
|
||||
token := xorPrefix(f.code, blocks[1].data)
|
||||
token[5] ^= 1
|
||||
blocks[1].in.Verifier.Token = base64.StdEncoding.EncodeToString(token)
|
||||
return blocks
|
||||
}, api.CodeInvalidRequirements, "block 2: verifier token"},
|
||||
"block not uploaded": {func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock {
|
||||
_, _, links := x.requestURLs(f, blocks[1:])
|
||||
require.Len(t, links, 1)
|
||||
return blocks[:1]
|
||||
}, api.CodeInvalidRequirements, "block 2 was not uploaded"},
|
||||
"index gap": {func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock {
|
||||
blocks[1].in.Index = 3
|
||||
return blocks
|
||||
}, api.CodeInvalidRequirements, "block 2 was not requested"},
|
||||
"declared hash": {func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock {
|
||||
blocks[0].in.Hash = &otherHash
|
||||
return blocks
|
||||
}, api.CodeInvalidRequirements, "declared hash"},
|
||||
"manifest": {func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock {
|
||||
req.ManifestSignature = signArmored([]byte("not the manifest"), f.signer)
|
||||
return blocks
|
||||
}, api.CodeInvalidValue, "manifest"},
|
||||
"manifest signer": {func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock {
|
||||
var manifest []byte
|
||||
for _, b := range blocks {
|
||||
sum := sha256.Sum256(b.data)
|
||||
manifest = append(manifest, sum[:]...)
|
||||
}
|
||||
req.ManifestSignature = signArmored(manifest, impostor)
|
||||
return blocks
|
||||
}, api.CodeInvalidValue, "manifest"},
|
||||
"SEIPDv1 block": {func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock {
|
||||
data, _ := legacy.encryptBlock(content[blockSize:], f.node.key, f.signer)
|
||||
blocks[1].data = data
|
||||
blocks[1].in.Verifier.Token = base64.StdEncoding.EncodeToString(xorPrefix(f.code, data))
|
||||
*req = *f.commitRequest(blocks)
|
||||
return blocks
|
||||
}, api.CodeInvalidValue, "block 2: packet with tag 18 version 1, want SEIPDv2"},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
f, blocks, req := prepare()
|
||||
blocks = tc.spoil(f, blocks, req)
|
||||
x.uploadAll(f, blocks)
|
||||
status, body := x.commit(f, req)
|
||||
requireRejected(t, tc.code, status, body, tc.want)
|
||||
assert.Contains(t, x.u.Drafts(), f.linkID)
|
||||
})
|
||||
}
|
||||
assert.Empty(t, x.u.Dump(), "a draft was committed")
|
||||
|
||||
f, blocks, req := prepare()
|
||||
x.uploadAll(f, blocks)
|
||||
status, body := x.commit(f, req)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
dump := x.u.Dump()
|
||||
require.Len(t, dump, 1)
|
||||
assert.NoError(t, dump[0].Err)
|
||||
assert.Equal(t, f.linkID, dump[0].ID)
|
||||
assert.True(t, bytes.Equal(content, dump[0].Content))
|
||||
assert.NotContains(t, x.u.Drafts(), f.linkID)
|
||||
|
||||
// A committed revision can't be committed again or deleted as a
|
||||
// draft.
|
||||
status, body = x.commit(f, req)
|
||||
requireRejected(t, api.CodeNotExists, status, body)
|
||||
status, body = x.send("POST", "/drive/v2/volumes/"+x.volume+"/delete_multiple", &linksRequest{LinkIDs: []string{f.linkID}})
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
var multi multiResponse
|
||||
require.NoError(t, json.Unmarshal(body, &multi))
|
||||
require.Len(t, multi.Responses, 1)
|
||||
assert.Equal(t, api.CodeInvalidRequirements, multi.Responses[0].Response.Code)
|
||||
status, body = x.send("DELETE", "/drive/v2/volumes/"+x.volume+"/files/"+f.linkID+"/revisions/"+f.revID, nil)
|
||||
requireRejected(t, api.CodeNotExists, status, body)
|
||||
require.Len(t, x.u.Dump(), 1)
|
||||
}
|
||||
|
||||
func TestStorageUploadRules(t *testing.T) {
|
||||
x := newUploader(t)
|
||||
f := x.newFileRequest("f")
|
||||
x.create(f)
|
||||
blocks := f.encrypt([]byte("content"))
|
||||
status, body, links := x.requestURLs(f, blocks)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
require.Len(t, links, 1)
|
||||
link := links[0]
|
||||
|
||||
assert.Equal(t, http.StatusBadRequest, x.putBlock(link, blocks[0].data, sessionHeader(x.sess)), "session credentials accepted")
|
||||
wrong := link
|
||||
wrong.Token = "wrong"
|
||||
assert.Equal(t, http.StatusForbidden, x.putBlock(wrong, blocks[0].data, nil))
|
||||
x.s.ExpireUploadTokens()
|
||||
assert.Equal(t, http.StatusNotFound, x.putBlock(link, blocks[0].data, nil))
|
||||
|
||||
// A block requested again gets a URL which works.
|
||||
_, _, links = x.requestURLs(f, blocks)
|
||||
require.Len(t, links, 1)
|
||||
require.Equal(t, http.StatusOK, x.putBlock(links[0], blocks[0].data, nil))
|
||||
status, body = x.commit(f, f.commitRequest(blocks))
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
dump := x.u.Dump()
|
||||
require.Len(t, dump, 1)
|
||||
require.NoError(t, dump[0].Err)
|
||||
|
||||
// Uploads to a committed revision are refused.
|
||||
assert.Equal(t, http.StatusNotFound, x.putBlock(links[0], blocks[0].data, nil))
|
||||
|
||||
// Another user's AddressID is refused.
|
||||
other := x.s.AddUser("other", "pass")
|
||||
g := x.newFileRequest("g")
|
||||
x.create(g)
|
||||
addressID := other.addresses[0].id
|
||||
status, body = x.send("POST", "/drive/blocks", &blockUploadRequest{LinkID: g.linkID, RevisionID: g.revID, AddressID: &addressID, VolumeID: &x.volume, BlockList: []blockUploadInput{g.encrypt([]byte("x"))[0].in}})
|
||||
requireRejected(t, api.CodeInvalidValue, status, body, "AddressID")
|
||||
}
|
||||
|
||||
func TestRevisionRules(t *testing.T) {
|
||||
x := newUploader(t)
|
||||
id := x.u.SeedFile(x.u.RootID(), "f", []byte("old"), time.Now())
|
||||
current := x.u.view().d.links[id].activeRevision().id
|
||||
path := "/drive/v2/volumes/" + x.volume + "/files/" + id + "/revisions"
|
||||
stale := "stale"
|
||||
status, body := x.send("POST", path, &createRevisionRequest{CurrentRevisionID: &stale})
|
||||
requireRejected(t, api.CodeInvalidRequirements, status, body, "CurrentRevisionID")
|
||||
status, body = x.send("POST", path, &createRevisionRequest{})
|
||||
requireRejected(t, api.CodeInvalidRequirements, status, body, "CurrentRevisionID")
|
||||
|
||||
uid := testClientUID
|
||||
status, body = x.send("POST", path, &createRevisionRequest{CurrentRevisionID: ¤t, ClientUID: &uid})
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
var resp createRevisionResponse
|
||||
require.NoError(t, json.Unmarshal(body, &resp))
|
||||
assert.Equal(t, []string{resp.Revision.ID}, x.u.Drafts())
|
||||
|
||||
// The name conflict of a file with a draft revision names both.
|
||||
status, body = x.send("POST", "/drive/v2/volumes/"+x.volume+"/files", x.newFileRequest("f").req)
|
||||
requireRejected(t, api.CodeAlreadyExists, status, body)
|
||||
var conflict conflictResponse
|
||||
require.NoError(t, json.Unmarshal(body, &conflict))
|
||||
require.NotNil(t, conflict.Details.ConflictRevisionID)
|
||||
assert.Equal(t, current, *conflict.Details.ConflictRevisionID)
|
||||
require.NotNil(t, conflict.Details.ConflictDraftRevisionID)
|
||||
assert.Equal(t, resp.Revision.ID, *conflict.Details.ConflictDraftRevisionID)
|
||||
|
||||
status, body = x.send("DELETE", path+"/"+resp.Revision.ID, nil)
|
||||
require.Equal(t, http.StatusOK, status, "body: %s", body)
|
||||
assert.Empty(t, x.u.Drafts())
|
||||
status, body = x.send("DELETE", path+"/"+current, nil)
|
||||
requireRejected(t, api.CodeNotExists, status, body)
|
||||
dump := x.u.Dump()
|
||||
require.Len(t, dump, 1)
|
||||
assert.Equal(t, []byte("old"), dump[0].Content)
|
||||
}
|
||||
|
||||
// TestUploadWireNames checks the backend's upload request types decode
|
||||
// into the fake's without unknown fields.
|
||||
func TestUploadWireNames(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
client any
|
||||
fake any
|
||||
}{
|
||||
{&api.CreateFileRequest{}, &createFileRequest{}},
|
||||
{&api.CreateRevisionRequest{}, &createRevisionRequest{}},
|
||||
{&api.BlockUploadRequest{BlockList: []api.BlockUploadInfo{{}}, ThumbnailList: []struct{}{}}, &blockUploadRequest{}},
|
||||
{&api.CommitRevisionRequest{}, &commitRevisionRequest{}},
|
||||
} {
|
||||
data, err := json.Marshal(tc.client)
|
||||
require.NoError(t, err)
|
||||
dec := json.NewDecoder(bytes.NewReader(data))
|
||||
dec.DisallowUnknownFields()
|
||||
assert.NoError(t, dec.Decode(tc.fake), "%T", tc.client)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,631 @@
|
||||
package protondrive_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha1"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
_ "github.com/rclone/rclone/backend/local"
|
||||
"github.com/rclone/rclone/backend/protondrive"
|
||||
"github.com/rclone/rclone/backend/protondrive/protontest"
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/accounting"
|
||||
"github.com/rclone/rclone/fs/config/configmap"
|
||||
"github.com/rclone/rclone/fs/config/obscure"
|
||||
"github.com/rclone/rclone/fs/fserrors"
|
||||
"github.com/rclone/rclone/fs/object"
|
||||
"github.com/rclone/rclone/fs/operations"
|
||||
fssync "github.com/rclone/rclone/fs/sync"
|
||||
"github.com/rclone/rclone/lib/random"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
childrenRoute = "GET /drive/v2/volumes/{volumeID}/folders/{linkID}/children"
|
||||
refreshRoute = "POST /auth/v4/refresh"
|
||||
draftRoute = "POST /drive/v2/volumes/{volumeID}/files"
|
||||
)
|
||||
|
||||
// credentialKeys are the config keys holding a saved session.
|
||||
var credentialKeys = []string{"client_uid", "client_access_token", "client_refresh_token", "client_salted_key_pass"}
|
||||
|
||||
// newFakeFs returns an Fs for remote at root, shut down, if it can
|
||||
// be, when the test ends.
|
||||
func newFakeFs(t *testing.T, remote, root string) fs.Fs {
|
||||
t.Helper()
|
||||
f, err := fs.NewFs(context.Background(), remote+root)
|
||||
require.NoError(t, err)
|
||||
if s, ok := f.(fs.Shutdowner); ok {
|
||||
t.Cleanup(func() { _ = s.Shutdown(context.Background()) })
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
// sessionMap returns the config of a remote on srv with a new saved
|
||||
// session of u.
|
||||
func sessionMap(srv *protontest.Server, u *protontest.User) configmap.Simple {
|
||||
sess := srv.NewSession(u)
|
||||
return configmap.Simple{
|
||||
"endpoint": srv.URL(),
|
||||
"client_uid": sess.UID,
|
||||
"client_access_token": sess.AccessToken,
|
||||
"client_refresh_token": sess.RefreshToken,
|
||||
"client_salted_key_pass": base64.StdEncoding.EncodeToString([]byte(u.KeyPassword())),
|
||||
"draft_client_uid": random.String(32),
|
||||
}
|
||||
}
|
||||
|
||||
// lockedMap is a configmap.Mapper safe for concurrent use, as rclone's
|
||||
// config file is. It records every value set.
|
||||
type lockedMap struct {
|
||||
mu sync.Mutex
|
||||
m configmap.Simple
|
||||
set map[string][]string // every value set per key, in order
|
||||
}
|
||||
|
||||
// newLockedMap returns a lockedMap holding a copy of m.
|
||||
func newLockedMap(m configmap.Simple) *lockedMap {
|
||||
l := &lockedMap{m: configmap.Simple{}, set: map[string][]string{}}
|
||||
for k, v := range m {
|
||||
l.m[k] = v
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
// Get returns the value of key.
|
||||
func (l *lockedMap) Get(key string) (string, bool) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
v, ok := l.m[key]
|
||||
return v, ok
|
||||
}
|
||||
|
||||
// Set sets key to value.
|
||||
func (l *lockedMap) Set(key, value string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.m[key] = value
|
||||
l.set[key] = append(l.set[key], value)
|
||||
}
|
||||
|
||||
// values returns every value set for key.
|
||||
func (l *lockedMap) values(key string) []string {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return append([]string(nil), l.set[key]...)
|
||||
}
|
||||
|
||||
// processMap is one process's view of a config file shared through
|
||||
// backing: it reads its own writes at once, but they reach backing,
|
||||
// and so other processes, only after delay.
|
||||
type processMap struct {
|
||||
backing *lockedMap
|
||||
delay time.Duration
|
||||
flushes *sync.WaitGroup
|
||||
|
||||
mu sync.Mutex
|
||||
pending map[string]string // values set and not yet in backing
|
||||
}
|
||||
|
||||
// Get returns the value of key.
|
||||
func (p *processMap) Get(key string) (string, bool) {
|
||||
p.mu.Lock()
|
||||
v, ok := p.pending[key]
|
||||
p.mu.Unlock()
|
||||
if ok {
|
||||
return v, true
|
||||
}
|
||||
return p.backing.Get(key)
|
||||
}
|
||||
|
||||
// Set sets key to value, writing it to backing after p.delay.
|
||||
func (p *processMap) Set(key, value string) {
|
||||
p.mu.Lock()
|
||||
p.pending[key] = value
|
||||
p.mu.Unlock()
|
||||
p.flushes.Add(1)
|
||||
time.AfterFunc(p.delay, func() {
|
||||
defer p.flushes.Done()
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.backing.Set(key, value)
|
||||
if p.pending[key] == value {
|
||||
delete(p.pending, key)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// requireValidSession checks the session saved in m is accepted by srv.
|
||||
func requireValidSession(t *testing.T, srv *protontest.Server, m configmap.Getter) {
|
||||
t.Helper()
|
||||
uid, _ := m.Get("client_uid")
|
||||
token, _ := m.Get("client_access_token")
|
||||
req, err := http.NewRequest("GET", srv.URL()+"/core/v4/users", nil)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("x-pm-appversion", "external-drive-rclone@1.0.0-stable")
|
||||
req.Header.Set("x-pm-uid", uid)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
resp, err := srv.Client().Do(req)
|
||||
require.NoError(t, err)
|
||||
_ = resp.Body.Close()
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode, "the saved session is rejected")
|
||||
}
|
||||
|
||||
// listConcurrently lists the root of every Fs at once and checks each
|
||||
// listing succeeds.
|
||||
func listConcurrently(ctx context.Context, t *testing.T, fsys ...fs.Fs) {
|
||||
t.Helper()
|
||||
var wg sync.WaitGroup
|
||||
for _, f := range fsys {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, err := f.List(ctx, "")
|
||||
assert.NoError(t, err)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// TestRegressionTwoFsRefreshRace is a regression test for rclone issues
|
||||
// #9880 and #8135: two remotes on one config refreshing at once lost
|
||||
// the session.
|
||||
func TestRegressionTwoFsRefreshRace(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
m := newLockedMap(sessionMap(srv, u))
|
||||
uid, _ := m.Get("client_uid")
|
||||
f1, err := protondrive.NewFs(ctx, "remote", "", m)
|
||||
require.NoError(t, err)
|
||||
f2, err := protondrive.NewFs(ctx, "remote", "", m)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Both refreshes reach the server with the same refresh token.
|
||||
srv.Inject(protontest.Fault{Method: "POST", Pattern: "/auth/v4/refresh", Times: 2, Gather: true})
|
||||
srv.ExpireAccessToken(uid)
|
||||
srv.ResetRequests()
|
||||
listConcurrently(ctx, t, f1, f2)
|
||||
assert.Equal(t, 2, srv.Requests()[refreshRoute])
|
||||
|
||||
requireValidSession(t, srv, m)
|
||||
for _, k := range credentialKeys {
|
||||
for _, v := range m.values(k) {
|
||||
assert.NotEmpty(t, v, "%s was blanked", k)
|
||||
}
|
||||
}
|
||||
// Both use the surviving session without refreshing again.
|
||||
f1.(fs.DirCacheFlusher).DirCacheFlush()
|
||||
f2.(fs.DirCacheFlusher).DirCacheFlush()
|
||||
listConcurrently(ctx, t, f1, f2)
|
||||
assert.Equal(t, 2, srv.Requests()[refreshRoute])
|
||||
}
|
||||
|
||||
// TestRegressionTwoProcessRefreshRace checks two processes sharing a
|
||||
// config file, which sees each one's saves only after a delay, both
|
||||
// keep working when they refresh at once.
|
||||
func TestRegressionTwoProcessRefreshRace(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
backing := newLockedMap(sessionMap(srv, u))
|
||||
uid, _ := backing.Get("client_uid")
|
||||
var flushes sync.WaitGroup
|
||||
newProcess := func() fs.Fs {
|
||||
p := &processMap{backing: backing, delay: 500 * time.Millisecond, flushes: &flushes, pending: map[string]string{}}
|
||||
f, err := protondrive.NewFs(ctx, "remote", "", p)
|
||||
require.NoError(t, err)
|
||||
return f
|
||||
}
|
||||
f1, f2 := newProcess(), newProcess()
|
||||
|
||||
srv.Inject(protontest.Fault{Method: "POST", Pattern: "/auth/v4/refresh", Times: 2, Gather: true})
|
||||
srv.ExpireAccessToken(uid)
|
||||
srv.ResetRequests()
|
||||
listConcurrently(ctx, t, f1, f2)
|
||||
flushes.Wait()
|
||||
assert.Equal(t, 2, srv.Requests()[refreshRoute], "one refresh wins, the other is rejected")
|
||||
|
||||
requireValidSession(t, srv, backing)
|
||||
for _, k := range credentialKeys {
|
||||
for _, v := range backing.values(k) {
|
||||
assert.NotEmpty(t, v, "%s was blanked", k)
|
||||
}
|
||||
}
|
||||
// The loser adopted the winner's tokens.
|
||||
f1.(fs.DirCacheFlusher).DirCacheFlush()
|
||||
f2.(fs.DirCacheFlusher).DirCacheFlush()
|
||||
listConcurrently(ctx, t, f1, f2)
|
||||
assert.Equal(t, 2, srv.Requests()[refreshRoute])
|
||||
}
|
||||
|
||||
// TestRegressionManyNewFs is a regression test for rclone issue #9816:
|
||||
// many remotes created at once were OOM-killed unlocking keys.
|
||||
//
|
||||
// All the NewFs calls are held until each has fetched its keys, so
|
||||
// their unlocks contend. That unlocks then run one at a time can't be
|
||||
// seen from the server; TestLoadAccountSerialised checks it.
|
||||
func TestRegressionManyNewFs(t *testing.T) {
|
||||
const n = 16
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
maps := make([]configmap.Simple, n)
|
||||
for i := range maps {
|
||||
maps[i] = sessionMap(srv, u)
|
||||
}
|
||||
srv.Inject(protontest.Fault{Method: "GET", Pattern: "/core/v4/addresses", Times: n, Gather: true})
|
||||
|
||||
fsys := make([]fs.Fs, n)
|
||||
var wg sync.WaitGroup
|
||||
for i := range fsys {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
f, err := protondrive.NewFs(ctx, "remote", "", maps[i])
|
||||
if assert.NoError(t, err) {
|
||||
fsys[i] = f
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if t.Failed() {
|
||||
return
|
||||
}
|
||||
listConcurrently(ctx, t, fsys...)
|
||||
// Keys are fetched, and so unlocked, once per Fs.
|
||||
assert.Equal(t, n, srv.Requests()["GET /core/v4/users"])
|
||||
assert.Equal(t, n, srv.Requests()["GET /core/v4/addresses"])
|
||||
}
|
||||
|
||||
// TestRegressionFileOverDirectory is a regression test for rclone issue
|
||||
// #9438: copying a file over a directory destroyed data.
|
||||
func TestRegressionFileOverDirectory(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
remote, _, _ := setupFakeRemote(t)
|
||||
f := newFakeFs(t, remote, "")
|
||||
inside := object.NewMemoryObject("x/inside.txt", time.Now(), []byte("inside"))
|
||||
_, err := operations.Copy(ctx, f, nil, inside.Remote(), inside)
|
||||
require.NoError(t, err)
|
||||
|
||||
src := object.NewMemoryObject("x", time.Now(), []byte("a file"))
|
||||
_, err = operations.Copy(ctx, f, nil, "x", src)
|
||||
require.ErrorIs(t, err, fs.ErrorIsDir)
|
||||
|
||||
f = newFakeFs(t, remote, "")
|
||||
entries, err := f.List(ctx, "x")
|
||||
require.NoError(t, err, "the directory survives")
|
||||
require.Len(t, entries, 1)
|
||||
assert.Equal(t, "x/inside.txt", entries[0].Remote())
|
||||
}
|
||||
|
||||
// TestRegressionDirectoryOverFile is a regression test for rclone issue
|
||||
// #9438: copying into a directory where a file of its name is
|
||||
// destroyed data.
|
||||
func TestRegressionDirectoryOverFile(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
remote, _, _ := setupFakeRemote(t)
|
||||
f := newFakeFs(t, remote, "")
|
||||
file := object.NewMemoryObject("x", time.Now(), []byte("a file"))
|
||||
_, err := operations.Copy(ctx, f, nil, "x", file)
|
||||
require.NoError(t, err)
|
||||
|
||||
src := object.NewMemoryObject("x/y", time.Now(), []byte("inside"))
|
||||
_, err = operations.Copy(ctx, f, nil, "x/y", src)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), `create folder "x": already exists`)
|
||||
|
||||
f = newFakeFs(t, remote, "")
|
||||
o, err := f.NewObject(ctx, "x")
|
||||
require.NoError(t, err, "the file survives")
|
||||
assert.Equal(t, "a file", readObject(t, o))
|
||||
}
|
||||
|
||||
// readObject returns the content of o.
|
||||
func readObject(t *testing.T, o fs.Object) string {
|
||||
t.Helper()
|
||||
rc, err := o.Open(context.Background())
|
||||
require.NoError(t, err)
|
||||
data, err := io.ReadAll(rc)
|
||||
require.NoError(t, rc.Close())
|
||||
require.NoError(t, err)
|
||||
return string(data)
|
||||
}
|
||||
|
||||
// TestRegressionDocsNodeSkipped is a regression test for rclone issue
|
||||
// #7959: a Proton Docs document made every sync fail.
|
||||
func TestRegressionDocsNodeSkipped(t *testing.T) {
|
||||
ctx := accounting.WithStatsGroup(context.Background(), "docs")
|
||||
remote, _, u := setupFakeRemote(t)
|
||||
dir := u.SeedFolder(u.RootID(), "dir")
|
||||
u.SeedDoc(dir, "notes")
|
||||
u.SeedFile(dir, "file.txt", []byte("content"), time.Now())
|
||||
|
||||
src := newFakeFs(t, remote, "dir")
|
||||
dst := newFakeFs(t, "", t.TempDir())
|
||||
require.NoError(t, fssync.Sync(ctx, dst, src, false))
|
||||
assert.Zero(t, accounting.Stats(ctx).GetErrors())
|
||||
entries, err := os.ReadDir(dst.Root())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, entries, 1)
|
||||
assert.Equal(t, "file.txt", entries[0].Name())
|
||||
}
|
||||
|
||||
// TestRegressionBadSignatureFile is a regression test for rclone issue
|
||||
// #8003: files whose signatures didn't verify couldn't be read at all.
|
||||
func TestRegressionBadSignatureFile(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
remote, _, u := setupFakeRemote(t)
|
||||
const second = "second@proton.test"
|
||||
u.AddAddress(second)
|
||||
content := []byte("signed by another address")
|
||||
u.SeedFileContentKeySignedBy(second, time.Now(), u.RootID(), "bad.txt", content)
|
||||
|
||||
f := newFakeFs(t, remote, "")
|
||||
entries, err := f.List(ctx, "")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, entries, 1)
|
||||
o, err := f.NewObject(ctx, "bad.txt")
|
||||
require.NoError(t, err)
|
||||
_, err = o.Open(ctx)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "bad.txt")
|
||||
assert.Contains(t, err.Error(), "signature")
|
||||
assert.Contains(t, err.Error(), "ignore_signature_errors")
|
||||
|
||||
f = newFakeFs(t, strings.TrimSuffix(remote, ":")+",ignore_signature_errors=true:", "")
|
||||
o, err = f.NewObject(ctx, "bad.txt")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, string(content), readObject(t, o))
|
||||
}
|
||||
|
||||
// TestRegressionSDKCreatedFolderResolvable is a regression test for
|
||||
// rclone issue #9622: files in folders made by Proton's own clients
|
||||
// couldn't be found by path.
|
||||
func TestRegressionSDKCreatedFolderResolvable(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
remote, _, u := setupFakeRemote(t)
|
||||
for _, names := range [][3]string{
|
||||
{"dir", "sub", "file"},
|
||||
{"Café", "é combining", "Ünïcødé file.txt"},
|
||||
} {
|
||||
dir := u.SeedFolder(u.RootID(), names[0])
|
||||
sub := u.SeedFolder(dir, names[1])
|
||||
u.SeedFile(sub, names[2], []byte(names[2]), time.Now())
|
||||
|
||||
f := newFakeFs(t, remote, "")
|
||||
o, err := f.NewObject(ctx, strings.Join(names[:], "/"))
|
||||
require.NoError(t, err, "%q", names)
|
||||
assert.Equal(t, names[2], readObject(t, o))
|
||||
}
|
||||
}
|
||||
|
||||
// blockTransfers returns the number of block uploads and downloads in
|
||||
// requests.
|
||||
func blockTransfers(requests map[string]int) int {
|
||||
n := 0
|
||||
for route, count := range requests {
|
||||
if strings.Contains(route, "/storage/") || route == "POST /drive/blocks" {
|
||||
n += count
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// TestRegressionMoveIsServerSide checks a move transfers no content.
|
||||
func TestRegressionMoveIsServerSide(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
remote, srv, _ := setupFakeRemote(t)
|
||||
f := newFakeFs(t, remote, "")
|
||||
src, err := operations.Copy(ctx, f, nil, "a.txt", object.NewMemoryObject("a.txt", time.Now(), []byte("move me")))
|
||||
require.NoError(t, err)
|
||||
|
||||
srv.ResetRequests()
|
||||
moved, err := operations.Move(ctx, f, nil, "dir/b.txt", src)
|
||||
require.NoError(t, err)
|
||||
assert.Zero(t, blockTransfers(srv.Requests()), "%v", srv.Requests())
|
||||
assert.Equal(t, "move me", readObject(t, moved))
|
||||
_, err = f.NewObject(ctx, "a.txt")
|
||||
assert.ErrorIs(t, err, fs.ErrorObjectNotFound)
|
||||
}
|
||||
|
||||
// TestRegressionCopyIsServerSide checks a copy transfers no content.
|
||||
func TestRegressionCopyIsServerSide(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
remote, srv, _ := setupFakeRemote(t)
|
||||
f := newFakeFs(t, remote, "")
|
||||
src, err := operations.Copy(ctx, f, nil, "a.txt", object.NewMemoryObject("a.txt", time.Now(), []byte("copy me")))
|
||||
require.NoError(t, err)
|
||||
|
||||
srv.ResetRequests()
|
||||
copied, err := operations.Copy(ctx, f, nil, "dir/b.txt", src)
|
||||
require.NoError(t, err)
|
||||
assert.Zero(t, blockTransfers(srv.Requests()), "%v", srv.Requests())
|
||||
assert.Equal(t, "copy me", readObject(t, copied))
|
||||
assert.Equal(t, "copy me", readObject(t, src))
|
||||
}
|
||||
|
||||
// TestRegressionMultiThreadDownload checks a multi-thread download
|
||||
// assembles the file correctly.
|
||||
func TestRegressionMultiThreadDownload(t *testing.T) {
|
||||
ctx, ci := fs.AddConfig(context.Background())
|
||||
ci.MultiThreadStreams = 4
|
||||
ci.MultiThreadSet = true
|
||||
ci.MultiThreadCutoff = 1 << 20
|
||||
// Chunks which don't line up with the 4 MiB blocks.
|
||||
ci.MultiThreadChunkSize = 5 << 20
|
||||
remote, srv, u := setupFakeRemote(t)
|
||||
content := []byte(random.String(20 << 20))
|
||||
u.SeedFile(u.RootID(), "big.bin", content, time.Now())
|
||||
|
||||
src := newFakeFs(t, remote, "")
|
||||
o, err := src.NewObject(ctx, "big.bin")
|
||||
require.NoError(t, err)
|
||||
dst := newFakeFs(t, "", t.TempDir())
|
||||
srv.ResetRequests()
|
||||
_, err = operations.Copy(ctx, dst, nil, "big.bin", o)
|
||||
require.NoError(t, err)
|
||||
// A single stream fetches each of the 5 blocks once.
|
||||
assert.Greater(t, srv.Requests()["GET /storage/blocks/{id}"], 5, "not downloaded in parallel ranges")
|
||||
|
||||
got, err := os.ReadFile(filepath.Join(dst.Root(), "big.bin"))
|
||||
require.NoError(t, err)
|
||||
want := sha1.Sum(content)
|
||||
gotSum := sha1.Sum(got)
|
||||
assert.Equal(t, hex.EncodeToString(want[:]), hex.EncodeToString(gotSum[:]))
|
||||
}
|
||||
|
||||
// TestRegressionPutStreamUnknownSize checks an upload of unknown size.
|
||||
func TestRegressionPutStreamUnknownSize(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
remote, _, _ := setupFakeRemote(t)
|
||||
f := newFakeFs(t, remote, "")
|
||||
require.NotNil(t, f.Features().PutStream)
|
||||
content := []byte(random.String(9 << 20))
|
||||
modTime := time.Now().Truncate(time.Second)
|
||||
info := object.NewStaticObjectInfo("stream.bin", modTime, -1, true, nil, nil)
|
||||
_, err := f.Features().PutStream(ctx, bytes.NewReader(content), info)
|
||||
require.NoError(t, err)
|
||||
|
||||
o, err := newFakeFs(t, remote, "").NewObject(ctx, "stream.bin")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(len(content)), o.Size())
|
||||
assert.True(t, modTime.Equal(o.ModTime(ctx)))
|
||||
assert.True(t, readObject(t, o) == string(content), "content differs")
|
||||
}
|
||||
|
||||
// TestRegressionCaptcha checks a CAPTCHA on password sign-in tells the
|
||||
// user how to sign in with a browser.
|
||||
func TestRegressionCaptcha(t *testing.T) {
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
srv.RequireCaptcha(u)
|
||||
m := configmap.Simple{
|
||||
"endpoint": srv.URL(),
|
||||
"username": "user",
|
||||
"password": obscure.MustObscure("pass"),
|
||||
}
|
||||
_, err := protondrive.NewFs(context.Background(), "myremote", "", m)
|
||||
require.Error(t, err)
|
||||
assert.True(t, fserrors.IsFatalError(err), "not fatal: %v", err)
|
||||
assert.Contains(t, err.Error(), `rclone config reconnect myremote:`)
|
||||
assert.Contains(t, err.Error(), "browser sign-in")
|
||||
}
|
||||
|
||||
// TestRegressionAppVersionRejected checks Proton refusing rclone's
|
||||
// version is a fatal error which says to upgrade.
|
||||
func TestRegressionAppVersionRejected(t *testing.T) {
|
||||
remote, srv, _ := setupFakeRemote(t)
|
||||
f := newFakeFs(t, remote, "")
|
||||
srv.Inject(protontest.Fault{Method: "GET", Pattern: "/drive/v2/volumes/{volumeID}/folders/{linkID}/children", Status: http.StatusBadRequest, Code: 5003})
|
||||
_, err := f.List(context.Background(), "")
|
||||
require.Error(t, err)
|
||||
assert.True(t, fserrors.IsFatalError(err), "not fatal: %v", err)
|
||||
assert.Contains(t, err.Error(), "upgrade rclone")
|
||||
}
|
||||
|
||||
// TestRegressionFeatureBlockedRetried checks Proton's code for a
|
||||
// feature disabled, rate-limited or blocked is retried, not fatal.
|
||||
func TestRegressionFeatureBlockedRetried(t *testing.T) {
|
||||
remote, srv, u := setupFakeRemote(t)
|
||||
u.SeedFile(u.RootID(), "a.txt", []byte("a"), time.Now())
|
||||
f := newFakeFs(t, remote, "")
|
||||
srv.Inject(protontest.Fault{Method: "GET", Pattern: "/drive/v2/volumes/{volumeID}/folders/{linkID}/children", Times: 2, Status: http.StatusUnprocessableEntity, Code: 2028})
|
||||
entries, err := f.List(context.Background(), "")
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, entries, 1)
|
||||
}
|
||||
|
||||
// TestRegressionRenameResendNotFatal checks a rename whose response was
|
||||
// lost, so that its resend fails Proton's stale-state check, doesn't
|
||||
// abort the whole run as an "upgrade rclone" error.
|
||||
func TestRegressionRenameResendNotFatal(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
remote, srv, u := setupFakeRemote(t)
|
||||
u.SeedFile(u.RootID(), "old.txt", []byte("x"), time.Now())
|
||||
f := newFakeFs(t, remote, "")
|
||||
o, err := f.NewObject(ctx, "old.txt")
|
||||
require.NoError(t, err)
|
||||
srv.Inject(protontest.Fault{Method: "PUT", Pattern: "/drive/v2/volumes/{volumeID}/links/{linkID}/rename", Status: http.StatusBadGateway, AfterHandler: true, Times: 1})
|
||||
_, err = f.Features().Move(ctx, o, "new.txt")
|
||||
require.Error(t, err, "the resend saw the rename already made")
|
||||
assert.False(t, fserrors.IsFatalError(err), "fatal: %v", err)
|
||||
assert.NotContains(t, err.Error(), "upgrade rclone")
|
||||
}
|
||||
|
||||
// TestRegressionQuotaExceeded checks running out of space is reported
|
||||
// with Proton's message and not retried.
|
||||
func TestRegressionQuotaExceeded(t *testing.T) {
|
||||
remote, srv, _ := setupFakeRemote(t)
|
||||
f := newFakeFs(t, remote, "")
|
||||
srv.Inject(protontest.Fault{Method: "POST", Pattern: "/drive/v2/volumes/{volumeID}/files", Status: http.StatusUnprocessableEntity, Code: 200001})
|
||||
srv.ResetRequests()
|
||||
src := object.NewMemoryObject("a.txt", time.Now(), []byte("no room"))
|
||||
_, err := operations.Copy(context.Background(), f, nil, "a.txt", src)
|
||||
require.Error(t, err)
|
||||
assert.True(t, fserrors.IsNoRetryError(err), "retryable: %v", err)
|
||||
assert.Contains(t, err.Error(), "protontest: injected fault")
|
||||
assert.Equal(t, 1, srv.Requests()[draftRoute])
|
||||
}
|
||||
|
||||
// TestRegressionRateLimited checks listing waits out every Retry-After
|
||||
// and then succeeds.
|
||||
func TestRegressionRateLimited(t *testing.T) {
|
||||
const times, retryAfter = 5, 1
|
||||
remote, srv, u := setupFakeRemote(t)
|
||||
u.SeedFile(u.RootID(), "a.txt", []byte("a"), time.Now())
|
||||
f := newFakeFs(t, remote, "")
|
||||
srv.Inject(protontest.Fault{Method: "GET", Pattern: "/drive/v2/volumes/{volumeID}/folders/{linkID}/children", Times: times, Status: http.StatusTooManyRequests, RetryAfter: retryAfter})
|
||||
srv.ResetRequests()
|
||||
start := time.Now()
|
||||
entries, err := f.List(context.Background(), "")
|
||||
require.NoError(t, err)
|
||||
assert.GreaterOrEqual(t, time.Since(start), times*retryAfter*time.Second)
|
||||
assert.Len(t, entries, 1)
|
||||
assert.Equal(t, times+1, srv.Requests()[childrenRoute])
|
||||
}
|
||||
|
||||
// TestRenamedFolderByOtherClient checks a folder renamed by another
|
||||
// client is seen under its new name after a poll, and that nothing is
|
||||
// left at its old path, as a mount needs.
|
||||
func TestRenamedFolderByOtherClient(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
remote, srv, u := setupFakeRemote(t)
|
||||
f := newFakeFs(t, remote, "")
|
||||
other, err := protondrive.NewFs(ctx, "other", "", sessionMap(srv, u))
|
||||
require.NoError(t, err)
|
||||
_, err = operations.Copy(ctx, f, nil, "a/b/f", object.NewMemoryObject("a/b/f", time.Now(), []byte("file")))
|
||||
require.NoError(t, err)
|
||||
|
||||
entries, err := f.List(ctx, "a/b")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, entries, 1)
|
||||
require.NoError(t, other.Features().DirMove(ctx, other, "a", "c"))
|
||||
|
||||
// One interval of 1s, with up to 1s of jitter, and some slack.
|
||||
assert.Eventually(t, func() bool {
|
||||
_, oldErr := f.NewObject(ctx, "a/b/f")
|
||||
_, newErr := f.NewObject(ctx, "c/b/f")
|
||||
return errors.Is(oldErr, fs.ErrorObjectNotFound) && newErr == nil
|
||||
}, 4*time.Second, 50*time.Millisecond, "the old path lingers or the new one isn't found")
|
||||
_, err = f.List(ctx, "a/b")
|
||||
assert.ErrorIs(t, err, fs.ErrorDirNotFound)
|
||||
entries, err = f.List(ctx, "c/b")
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, entries, 1)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,679 @@
|
||||
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@<semver>-<channel>.
|
||||
//
|
||||
// Releases map to stable, betas to beta with their build number as
|
||||
// build metadata, and anything else to alpha. An unparsable version
|
||||
// maps to 1.0.0-stable.
|
||||
func appVersionFromRcloneVersion(v string) string {
|
||||
const prefix = "external-drive-rclone@"
|
||||
m := rcloneVersionRe.FindStringSubmatch(strings.TrimSpace(v))
|
||||
if m == nil {
|
||||
return prefix + "1.0.0-stable"
|
||||
}
|
||||
number, suffix := m[1], m[2]
|
||||
switch {
|
||||
case suffix == "":
|
||||
return prefix + number + "-stable"
|
||||
case suffix == "beta":
|
||||
return prefix + number + "-beta"
|
||||
case strings.HasPrefix(suffix, "beta."):
|
||||
var build []string
|
||||
for _, id := range strings.Split(strings.TrimPrefix(suffix, "beta."), ".") {
|
||||
id = strings.Trim(invalidBuildCharsRe.ReplaceAllString(id, "-"), "-")
|
||||
if id != "" {
|
||||
build = append(build, id)
|
||||
}
|
||||
}
|
||||
if len(build) == 0 {
|
||||
return prefix + number + "-beta"
|
||||
}
|
||||
return prefix + number + "-beta+" + strings.Join(build, ".")
|
||||
default:
|
||||
return prefix + number + "-alpha"
|
||||
}
|
||||
}
|
||||
|
||||
// credentials are the saved tokens of a session.
|
||||
type credentials struct {
|
||||
UID string
|
||||
AccessToken string
|
||||
RefreshToken string
|
||||
KeyPassword string // salted password which unlocks the user keys
|
||||
}
|
||||
|
||||
// credentialStore persists credentials, possibly shared with other
|
||||
// sessions and processes.
|
||||
type credentialStore interface {
|
||||
Load() credentials
|
||||
Save(credentials)
|
||||
}
|
||||
|
||||
// memoryStore is a credentialStore held in memory.
|
||||
type memoryStore struct {
|
||||
mu sync.Mutex
|
||||
creds credentials
|
||||
}
|
||||
|
||||
// Load returns the stored credentials.
|
||||
func (m *memoryStore) Load() credentials {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.creds
|
||||
}
|
||||
|
||||
// Save replaces the stored credentials.
|
||||
func (m *memoryStore) Save(c credentials) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.creds = c
|
||||
}
|
||||
|
||||
// session makes API calls with a Proton session, refreshing its tokens
|
||||
// when they expire.
|
||||
type session struct {
|
||||
srv *rest.Client
|
||||
store credentialStore
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,596 @@
|
||||
package protondrive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/pquerna/otp/totp"
|
||||
"github.com/rclone/rclone/backend/protondrive/api"
|
||||
"github.com/rclone/rclone/backend/protondrive/protontest"
|
||||
"github.com/rclone/rclone/fs/fserrors"
|
||||
"github.com/rclone/rclone/lib/rest"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
testAppVersion = "external-drive-rclone@1.77.0-stable"
|
||||
refreshRoute = "POST /auth/v4/refresh"
|
||||
)
|
||||
|
||||
// appVersionGrammar is Proton's x-pm-appversion grammar with the name
|
||||
// fixed to rclone and the channel required.
|
||||
var appVersionGrammar = regexp.MustCompile(`^external-drive-rclone@[0-9]+\.[0-9]+\.[0-9]+-(stable|beta|alpha)(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$`)
|
||||
|
||||
func TestAppVersionFromRcloneVersion(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{"v1.77.0", "external-drive-rclone@1.77.0-stable"},
|
||||
{"1.77.0", "external-drive-rclone@1.77.0-stable"},
|
||||
{"v1.77.0-DEV", "external-drive-rclone@1.77.0-alpha"},
|
||||
{"v1.77.0-beta.10754.448d7361c", "external-drive-rclone@1.77.0-beta+10754.448d7361c"},
|
||||
{"v1.77.0-beta.10754.448d7361c.fix/proton_drive", "external-drive-rclone@1.77.0-beta+10754.448d7361c.fix-proton-drive"},
|
||||
{"v1.77.0-beta", "external-drive-rclone@1.77.0-beta"},
|
||||
{"v1.77.0-rc1", "external-drive-rclone@1.77.0-alpha"},
|
||||
{"garbage", "external-drive-rclone@1.0.0-stable"},
|
||||
{"", "external-drive-rclone@1.0.0-stable"},
|
||||
{"v1.77", "external-drive-rclone@1.0.0-stable"},
|
||||
} {
|
||||
got := appVersionFromRcloneVersion(test.in)
|
||||
assert.Equal(t, test.want, got, "input %q", test.in)
|
||||
assert.Regexp(t, appVersionGrammar, got, "input %q", test.in)
|
||||
}
|
||||
}
|
||||
|
||||
// headerRecorder records the headers of every request it sends.
|
||||
type headerRecorder struct {
|
||||
mu sync.Mutex
|
||||
headers []http.Header
|
||||
next http.RoundTripper
|
||||
}
|
||||
|
||||
func (h *headerRecorder) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
h.mu.Lock()
|
||||
h.headers = append(h.headers, req.Header.Clone())
|
||||
h.mu.Unlock()
|
||||
return h.next.RoundTrip(req)
|
||||
}
|
||||
|
||||
// newTestSession signs a new user in to srv and returns a session using
|
||||
// a store holding its credentials.
|
||||
func newTestSession(t *testing.T, srv *protontest.Server) (*session, *memoryStore, protontest.Session) {
|
||||
t.Helper()
|
||||
tokens := srv.NewSession(srv.AddUser("user", "pass"))
|
||||
store := &memoryStore{creds: credentials{
|
||||
UID: tokens.UID,
|
||||
AccessToken: tokens.AccessToken,
|
||||
RefreshToken: tokens.RefreshToken,
|
||||
KeyPassword: "key-pass",
|
||||
}}
|
||||
return newSession(srv.Client(), srv.URL(), testAppVersion, store), store, tokens
|
||||
}
|
||||
|
||||
// authCall makes an authenticated test call.
|
||||
func authCall(ctx context.Context, s *session) error {
|
||||
var out struct {
|
||||
UserID string `json:"UserID"`
|
||||
}
|
||||
_, err := s.call(ctx, &rest.Opts{Method: "GET", Path: "/tests/auth"}, nil, &out)
|
||||
if err == nil && out.UserID == "" {
|
||||
return errors.New("no UserID in response")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func TestSessionHeaders(t *testing.T) {
|
||||
srv := protontest.New(t)
|
||||
tokens := srv.NewSession(srv.AddUser("user", "pass"))
|
||||
rec := &headerRecorder{next: srv.Client().Transport}
|
||||
client := &http.Client{Transport: rec}
|
||||
store := &memoryStore{creds: credentials{UID: tokens.UID, AccessToken: tokens.AccessToken, RefreshToken: tokens.RefreshToken}}
|
||||
s := newSession(client, srv.URL(), testAppVersion, store)
|
||||
|
||||
require.NoError(t, authCall(context.Background(), s))
|
||||
_, err := s.callUnauthenticated(context.Background(), &rest.Opts{Method: "GET", Path: "/tests/ping"}, nil, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Len(t, rec.headers, 2)
|
||||
auth, unauth := rec.headers[0], rec.headers[1]
|
||||
assert.Equal(t, tokens.UID, auth.Get("x-pm-uid"))
|
||||
assert.Equal(t, "Bearer "+tokens.AccessToken, auth.Get("Authorization"))
|
||||
for _, h := range []http.Header{auth, unauth} {
|
||||
assert.Equal(t, testAppVersion, h.Get("x-pm-appversion"))
|
||||
assert.Equal(t, "application/vnd.protonmail.v1+json", h.Get("Accept"))
|
||||
assert.Empty(t, h.Get("x-pm-drive-sdk-version"))
|
||||
}
|
||||
assert.Empty(t, unauth.Get("x-pm-uid"))
|
||||
assert.Empty(t, unauth.Get("Authorization"))
|
||||
}
|
||||
|
||||
func TestSessionUnauthenticatedNoRefresh(t *testing.T) {
|
||||
srv := protontest.New(t)
|
||||
s, _, _ := newTestSession(t, srv)
|
||||
_, err := s.callUnauthenticated(context.Background(), &rest.Opts{Method: "GET", Path: "/tests/auth"}, nil, nil)
|
||||
var apiErr *api.Error
|
||||
require.ErrorAs(t, err, &apiErr)
|
||||
assert.Equal(t, http.StatusUnauthorized, apiErr.Status)
|
||||
assert.Zero(t, srv.Requests()[refreshRoute])
|
||||
}
|
||||
|
||||
func TestSessionRefreshOn401(t *testing.T) {
|
||||
srv := protontest.New(t)
|
||||
s, store, tokens := newTestSession(t, srv)
|
||||
srv.ExpireAccessToken(tokens.UID)
|
||||
|
||||
require.NoError(t, authCall(context.Background(), s))
|
||||
assert.Equal(t, 1, srv.Requests()[refreshRoute])
|
||||
assert.Equal(t, 2, srv.Requests()["GET /tests/auth"])
|
||||
|
||||
saved := store.Load()
|
||||
assert.Equal(t, tokens.UID, saved.UID)
|
||||
assert.NotEqual(t, tokens.AccessToken, saved.AccessToken)
|
||||
assert.NotEqual(t, tokens.RefreshToken, saved.RefreshToken)
|
||||
assert.Equal(t, "key-pass", saved.KeyPassword)
|
||||
|
||||
// The new tokens are used without another refresh.
|
||||
require.NoError(t, authCall(context.Background(), s))
|
||||
assert.Equal(t, 1, srv.Requests()[refreshRoute])
|
||||
}
|
||||
|
||||
func TestSessionRefreshResendsBody(t *testing.T) {
|
||||
srv := protontest.New(t)
|
||||
s, _, tokens := newTestSession(t, srv)
|
||||
type echo struct {
|
||||
Echo string `json:"Echo"`
|
||||
}
|
||||
opts := &rest.Opts{Method: "POST", Path: "/tests/echo"}
|
||||
|
||||
srv.ExpireAccessToken(tokens.UID)
|
||||
var out echo
|
||||
_, err := s.call(context.Background(), opts, &echo{Echo: "request"}, &out)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "request", out.Echo)
|
||||
|
||||
srv.ExpireAccessToken(tokens.UID)
|
||||
out = echo{}
|
||||
bodyOpts := *opts
|
||||
bodyOpts.Body = bytes.NewReader([]byte(`{"Echo":"body"}`))
|
||||
_, err = s.call(context.Background(), &bodyOpts, nil, &out)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "body", out.Echo)
|
||||
assert.Equal(t, 2, srv.Requests()[refreshRoute])
|
||||
}
|
||||
|
||||
func TestSessionRefreshSingleFlight(t *testing.T) {
|
||||
srv := protontest.New(t)
|
||||
s, _, tokens := newTestSession(t, srv)
|
||||
srv.ExpireAccessToken(tokens.UID)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
errs := make([]error, 20)
|
||||
for i := range errs {
|
||||
wg.Go(func() {
|
||||
errs[i] = authCall(context.Background(), s)
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
for i, err := range errs {
|
||||
assert.NoError(t, err, "call %d", i)
|
||||
}
|
||||
assert.Equal(t, 1, srv.Requests()[refreshRoute])
|
||||
}
|
||||
|
||||
func TestSessionRefreshRereadsStore(t *testing.T) {
|
||||
srv := protontest.New(t)
|
||||
a, store, tokens := newTestSession(t, srv)
|
||||
b := newSession(srv.Client(), srv.URL(), testAppVersion, store)
|
||||
srv.ExpireAccessToken(tokens.UID)
|
||||
|
||||
require.NoError(t, authCall(context.Background(), a))
|
||||
assert.Equal(t, 1, srv.Requests()[refreshRoute])
|
||||
|
||||
// b still holds the rotated tokens, so its first call gets 401 and
|
||||
// adopts a's tokens from the store instead of reusing its refresh
|
||||
// token.
|
||||
require.NoError(t, authCall(context.Background(), b))
|
||||
assert.Equal(t, 1, srv.Requests()[refreshRoute])
|
||||
assert.Equal(t, 4, srv.Requests()["GET /tests/auth"])
|
||||
}
|
||||
|
||||
func TestSessionRefreshTwoSessionsConcurrent(t *testing.T) {
|
||||
srv := protontest.New(t)
|
||||
a, store, tokens := newTestSession(t, srv)
|
||||
b := newSession(srv.Client(), srv.URL(), testAppVersion, store)
|
||||
// Holding each refresh makes both sessions post the same refresh
|
||||
// token before either saves the new one.
|
||||
srv.Inject(protontest.Fault{Method: "POST", Pattern: "/auth/v4/refresh", Delay: 200 * time.Millisecond})
|
||||
srv.ExpireAccessToken(tokens.UID)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
errs := make([]error, 2)
|
||||
for i, s := range []*session{a, b} {
|
||||
wg.Go(func() {
|
||||
errs[i] = authCall(context.Background(), s)
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
for i, err := range errs {
|
||||
assert.NoError(t, err, "session %d", i)
|
||||
}
|
||||
assert.Equal(t, 2, srv.Requests()[refreshRoute], "both sessions posted the refresh token")
|
||||
|
||||
// The stored credentials work in a fresh session.
|
||||
c := newSession(srv.Client(), srv.URL(), testAppVersion, store)
|
||||
require.NoError(t, authCall(context.Background(), c))
|
||||
assert.Equal(t, 2, srv.Requests()[refreshRoute])
|
||||
}
|
||||
|
||||
func TestSessionRevoked(t *testing.T) {
|
||||
srv := protontest.New(t)
|
||||
s, store, tokens := newTestSession(t, srv)
|
||||
s.adoptWait = 50 * time.Millisecond
|
||||
s.reconnect = `run "rclone config reconnect myremote:"`
|
||||
before := store.Load()
|
||||
srv.RevokeSession(tokens.UID)
|
||||
|
||||
err := authCall(context.Background(), s)
|
||||
require.Error(t, err)
|
||||
assert.ErrorIs(t, err, errSessionExpired)
|
||||
assert.True(t, fserrors.IsFatalError(err), "error is fatal: %v", err)
|
||||
assert.Contains(t, err.Error(), `rclone config reconnect myremote:`)
|
||||
assert.Equal(t, before, store.Load(), "credentials kept")
|
||||
assert.Equal(t, 1, srv.Requests()[refreshRoute])
|
||||
|
||||
// Further calls fail the same way without retrying the refresh.
|
||||
err = authCall(context.Background(), s)
|
||||
assert.ErrorIs(t, err, errSessionExpired)
|
||||
assert.Equal(t, 1, srv.Requests()[refreshRoute])
|
||||
assert.Equal(t, before, store.Load(), "credentials kept")
|
||||
}
|
||||
|
||||
func TestSessionServerTime(t *testing.T) {
|
||||
srv := protontest.New(t)
|
||||
srv.SetClockSkew(3 * time.Hour)
|
||||
s, _, _ := newTestSession(t, srv)
|
||||
assert.True(t, s.serverTime().IsZero())
|
||||
|
||||
require.NoError(t, authCall(context.Background(), s))
|
||||
assert.WithinDuration(t, time.Now().Add(3*time.Hour), s.serverTime(), 5*time.Second)
|
||||
}
|
||||
|
||||
func TestSessionAPIError(t *testing.T) {
|
||||
for _, status := range []int{http.StatusUnprocessableEntity, http.StatusOK} {
|
||||
srv := protontest.New(t)
|
||||
s, _, _ := newTestSession(t, srv)
|
||||
srv.Inject(protontest.Fault{Pattern: "/tests/auth", Times: 1, Status: status, Code: api.CodeAlreadyExists})
|
||||
|
||||
err := authCall(context.Background(), s)
|
||||
var apiErr *api.Error
|
||||
require.ErrorAs(t, err, &apiErr, "status %d", status)
|
||||
assert.Equal(t, status, apiErr.Status)
|
||||
assert.Equal(t, api.CodeAlreadyExists, apiErr.Code)
|
||||
assert.Zero(t, srv.Requests()[refreshRoute])
|
||||
}
|
||||
}
|
||||
|
||||
// newLoginSession returns a session for srv with an empty store.
|
||||
func newLoginSession(srv *protontest.Server) (*session, *memoryStore) {
|
||||
store := &memoryStore{}
|
||||
return newSession(srv.Client(), srv.URL(), testAppVersion, store), store
|
||||
}
|
||||
|
||||
// noTwoFA is a twoFA callback for accounts without 2FA.
|
||||
func noTwoFA() (string, error) {
|
||||
return "", errors.New("unexpected 2FA prompt")
|
||||
}
|
||||
|
||||
// requireSignedIn checks store holds complete credentials for a working
|
||||
// session whose key password derives from keyPassword and u's key salt.
|
||||
func requireSignedIn(t *testing.T, s *session, store *memoryStore, u *protontest.User, keyPassword string) {
|
||||
t.Helper()
|
||||
saved := store.Load()
|
||||
require.NotEmpty(t, saved.UID)
|
||||
require.NotEmpty(t, saved.AccessToken)
|
||||
require.NotEmpty(t, saved.RefreshToken)
|
||||
want, err := computeKeyPassword([]byte(keyPassword), u.KeySalt)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, string(want), saved.KeyPassword)
|
||||
assert.Equal(t, saved, s.current())
|
||||
require.NoError(t, authCall(context.Background(), s))
|
||||
}
|
||||
|
||||
func TestLoginSRP(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "correct password")
|
||||
|
||||
s, store := newLoginSession(srv)
|
||||
err := s.loginSRP(context.Background(), "user", "wrong password", "", noTwoFA)
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, credentials{}, store.Load(), "nothing stored")
|
||||
assert.Equal(t, credentials{}, s.current())
|
||||
|
||||
require.NoError(t, s.loginSRP(context.Background(), "user", "correct password", "", noTwoFA))
|
||||
requireSignedIn(t, s, store, u, "correct password")
|
||||
}
|
||||
|
||||
func TestLoginSRPSaltOfPrimaryKey(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
oldSalt := u.KeySalt
|
||||
u.AddUserKey()
|
||||
require.NotEqual(t, oldSalt, u.KeySalt)
|
||||
|
||||
// The salts list the old key first; the primary key's salt is second.
|
||||
s, store := newLoginSession(srv)
|
||||
require.NoError(t, s.loginSRP(context.Background(), "user", "pass", "", noTwoFA))
|
||||
requireSignedIn(t, s, store, u, "pass")
|
||||
assert.Equal(t, u.KeyPassword(), store.Load().KeyPassword)
|
||||
a, err := loadAccount(context.Background(), s, []byte(store.Load().KeyPassword))
|
||||
require.NoError(t, err)
|
||||
a.close()
|
||||
}
|
||||
|
||||
func TestPrimaryKeySalt(t *testing.T) {
|
||||
keys := []api.UserKey{{ID: "old", Primary: 0}, {ID: "new", Primary: 1}}
|
||||
salts := []api.KeySalt{{ID: "old", KeySalt: "old-salt"}, {ID: "new", KeySalt: "new-salt"}}
|
||||
|
||||
salt, ok := primaryKeySalt(keys, salts)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, "new-salt", salt)
|
||||
|
||||
salt, ok = primaryKeySalt(keys, []api.KeySalt{{ID: "other", KeySalt: "first"}, {ID: "x", KeySalt: "second"}})
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, "first", salt, "falls back to the first salt")
|
||||
|
||||
salt, ok = primaryKeySalt(nil, salts)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, "old-salt", salt)
|
||||
|
||||
_, ok = primaryKeySalt(keys, nil)
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
func TestLoginSRPBadServerProof(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
srv.CorruptServerProof(u)
|
||||
|
||||
s, store := newLoginSession(srv)
|
||||
err := s.loginSRP(context.Background(), "user", "pass", "", noTwoFA)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "server proof verification")
|
||||
assert.Equal(t, credentials{}, store.Load(), "nothing stored")
|
||||
assert.Equal(t, credentials{}, s.current())
|
||||
}
|
||||
|
||||
func TestLoginSRPPasswords(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, password := range []string{
|
||||
"with space ",
|
||||
`quo"te'`,
|
||||
"пароль-密码",
|
||||
strings.Repeat("abcdefghij", 10),
|
||||
} {
|
||||
t.Run(password, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", password)
|
||||
s, store := newLoginSession(srv)
|
||||
require.NoError(t, s.loginSRP(context.Background(), "user", password, "", noTwoFA))
|
||||
requireSignedIn(t, s, store, u, password)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginSRPMailboxPassword(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddTwoPasswordUser("user", "login password", "mailbox password")
|
||||
|
||||
s, store := newLoginSession(srv)
|
||||
require.NoError(t, s.loginSRP(context.Background(), "user", "login password", "mailbox password", noTwoFA))
|
||||
requireSignedIn(t, s, store, u, "mailbox password")
|
||||
|
||||
// Without the mailbox password the key password can't be derived.
|
||||
s, store = newLoginSession(srv)
|
||||
err := s.loginSRP(context.Background(), "user", "login password", "", noTwoFA)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "mailbox_password")
|
||||
assert.Equal(t, credentials{}, store.Load())
|
||||
}
|
||||
|
||||
func TestLoginSRPTOTP(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
secret := u.EnableTOTP()
|
||||
|
||||
calls := 0
|
||||
s, store := newLoginSession(srv)
|
||||
require.NoError(t, s.loginSRP(context.Background(), "user", "pass", "", func() (string, error) {
|
||||
calls++
|
||||
return totp.GenerateCode(secret, time.Now())
|
||||
}))
|
||||
assert.Equal(t, 1, calls)
|
||||
requireSignedIn(t, s, store, u, "pass")
|
||||
|
||||
calls = 0
|
||||
s, store = newLoginSession(srv)
|
||||
err := s.loginSRP(context.Background(), "user", "pass", "", func() (string, error) {
|
||||
calls++
|
||||
return "000000x", nil
|
||||
})
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, 1, calls)
|
||||
assert.Equal(t, credentials{}, store.Load())
|
||||
}
|
||||
|
||||
func TestLoginSRPCaptcha(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
srv.RequireCaptcha(u)
|
||||
|
||||
s, store := newLoginSession(srv)
|
||||
err := s.loginSRP(context.Background(), "user", "pass", "", noTwoFA)
|
||||
require.ErrorIs(t, err, errCaptcha)
|
||||
assert.Equal(t, credentials{}, store.Load())
|
||||
}
|
||||
|
||||
func TestForkLogin(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
u := srv.AddUser("user", "pass")
|
||||
s, store := newLoginSession(srv)
|
||||
|
||||
f, err := s.forkStart(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.NotEmpty(t, f.Selector)
|
||||
assert.Len(t, f.key, 32)
|
||||
prefix := "https://account.proton.me/desktop/login?app=drive&pv=3#payload="
|
||||
require.True(t, strings.HasPrefix(f.URL, prefix), f.URL)
|
||||
payload, err := url.QueryUnescape(strings.TrimPrefix(f.URL, prefix))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "0:"+f.UserCode+":"+base64.StdEncoding.EncodeToString(f.key)+":external-drive", payload)
|
||||
|
||||
go func() {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
assert.NoError(t, srv.ApproveFork(f.URL, u))
|
||||
}()
|
||||
require.NoError(t, s.forkPoll(context.Background(), f, 10*time.Millisecond, 10*time.Second))
|
||||
requireSignedIn(t, s, store, u, "pass")
|
||||
}
|
||||
|
||||
func TestForkLoginTimeout(t *testing.T) {
|
||||
srv := protontest.New(t)
|
||||
s, store := newLoginSession(srv)
|
||||
f, err := s.forkStart(context.Background())
|
||||
require.NoError(t, err)
|
||||
|
||||
start := time.Now()
|
||||
err = s.forkPoll(context.Background(), f, 10*time.Millisecond, 100*time.Millisecond)
|
||||
require.Error(t, err)
|
||||
assert.GreaterOrEqual(t, time.Since(start), 100*time.Millisecond)
|
||||
assert.Less(t, time.Since(start), 5*time.Second)
|
||||
assert.Greater(t, srv.Requests()["GET /auth/v4/sessions/forks/{selector}"], 1)
|
||||
assert.Equal(t, credentials{}, store.Load())
|
||||
}
|
||||
|
||||
func TestForkLoginCancel(t *testing.T) {
|
||||
srv := protontest.New(t)
|
||||
s, store := newLoginSession(srv)
|
||||
f, err := s.forkStart(context.Background())
|
||||
require.NoError(t, err)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
time.AfterFunc(50*time.Millisecond, cancel)
|
||||
start := time.Now()
|
||||
err = s.forkPoll(ctx, f, 10*time.Millisecond, 10*time.Minute)
|
||||
assert.ErrorIs(t, err, context.Canceled)
|
||||
assert.Less(t, time.Since(start), 5*time.Second)
|
||||
assert.Equal(t, credentials{}, store.Load())
|
||||
}
|
||||
|
||||
func TestLogout(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := protontest.New(t)
|
||||
srv.AddUser("user", "pass")
|
||||
s, store := newLoginSession(srv)
|
||||
require.NoError(t, s.loginSRP(context.Background(), "user", "pass", "", noTwoFA))
|
||||
before := store.Load()
|
||||
|
||||
require.NoError(t, s.logout(context.Background()))
|
||||
assert.Equal(t, credentials{}, store.Load())
|
||||
srv.ResetRequests()
|
||||
err := authCall(context.Background(), s)
|
||||
assert.ErrorIs(t, err, errNotSignedIn)
|
||||
assert.True(t, fserrors.IsFatalError(err))
|
||||
assert.Empty(t, srv.Requests(), "no request is sent without a session")
|
||||
|
||||
// The server ended the session too.
|
||||
old := newSession(srv.Client(), srv.URL(), testAppVersion, &memoryStore{creds: before})
|
||||
old.adoptWait = 0
|
||||
assert.ErrorIs(t, authCall(context.Background(), old), errSessionExpired)
|
||||
}
|
||||
|
||||
func TestCallDuringLogout(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
srv := protontest.New(t)
|
||||
s, _, _ := newTestSession(t, srv)
|
||||
// The call is rejected only after the session has signed out.
|
||||
srv.Inject(protontest.Fault{Method: "GET", Pattern: "/tests/auth", Times: 1, Status: http.StatusUnauthorized, Delay: 500 * time.Millisecond})
|
||||
errc := make(chan error, 1)
|
||||
go func() { errc <- authCall(ctx, s) }()
|
||||
require.Eventually(t, func() bool { return srv.Requests()["GET /tests/auth"] == 1 }, 5*time.Second, 5*time.Millisecond)
|
||||
require.NoError(t, s.logout(ctx))
|
||||
|
||||
err := <-errc
|
||||
assert.ErrorIs(t, err, errNotSignedIn)
|
||||
assert.Equal(t, 1, srv.Requests()["GET /tests/auth"], "retried without credentials")
|
||||
assert.Zero(t, srv.Requests()[refreshRoute])
|
||||
}
|
||||
|
||||
func TestRefreshDuringLogout(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
srv := protontest.New(t)
|
||||
tokens := srv.NewSession(srv.AddUser("user", "pass"))
|
||||
refreshing, release := make(chan struct{}), make(chan struct{})
|
||||
// The refresh succeeds, but its answer arrives only after the
|
||||
// session has signed out.
|
||||
client := &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path != "/auth/v4/refresh" {
|
||||
return srv.Client().Transport.RoundTrip(r)
|
||||
}
|
||||
close(refreshing)
|
||||
<-release
|
||||
body := `{"Code":1000,"UID":"` + tokens.UID + `","AccessToken":"new-access","RefreshToken":"new-refresh"}`
|
||||
return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"application/json"}}, Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
|
||||
})}
|
||||
store := &memoryStore{creds: credentials{UID: tokens.UID, AccessToken: tokens.AccessToken, RefreshToken: tokens.RefreshToken, KeyPassword: "key-pass"}}
|
||||
s := newSession(client, srv.URL(), testAppVersion, store)
|
||||
srv.Inject(protontest.Fault{Method: "GET", Pattern: "/tests/auth", Times: 1, Status: http.StatusUnauthorized})
|
||||
|
||||
errc := make(chan error, 1)
|
||||
go func() { errc <- authCall(ctx, s) }()
|
||||
<-refreshing
|
||||
logoutErr := make(chan error, 1)
|
||||
go func() { logoutErr <- s.logout(ctx) }()
|
||||
require.Eventually(t, func() bool { return srv.Requests()["DELETE /core/v4/auth"] == 1 }, 5*time.Second, 5*time.Millisecond)
|
||||
close(release)
|
||||
require.NoError(t, <-logoutErr)
|
||||
assert.Error(t, <-errc, "the call succeeded with tokens refreshed after signing out")
|
||||
|
||||
assert.Equal(t, credentials{}, store.Load(), "tokens saved after signing out")
|
||||
assert.Equal(t, credentials{}, s.current())
|
||||
}
|
||||
|
||||
func TestRefreshTransientErrorRetried(t *testing.T) {
|
||||
for _, status := range []int{http.StatusServiceUnavailable, http.StatusRequestTimeout} {
|
||||
t.Run(http.StatusText(status), func(t *testing.T) {
|
||||
c, srv, _ := newTestClient(t)
|
||||
ctx := context.Background()
|
||||
srv.ExpireAccessToken(c.s.current().UID)
|
||||
srv.Inject(protontest.Fault{Method: "POST", Pattern: "/auth/v4/refresh", Status: status, Times: 1})
|
||||
_, _, err := c.about(ctx)
|
||||
require.NoError(t, err, "a %d on the refresh wasn't retried", status)
|
||||
assert.Equal(t, 2, srv.Requests()["POST /auth/v4/refresh"])
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"Comment": "Keys made by TestGoldenCapture for the tests alone.",
|
||||
"Email": "golden@example.invalid",
|
||||
"Keys": {
|
||||
"AddressKey": "-----BEGIN PGP PRIVATE KEY BLOCK-----\n\nxYYEavQ+PBYJKwYBBAHaRw8BAQdAtg+4mrPbyi6Tjo0WFynmLyYdmwCE243WA+Ak\nQ7yhPRL+BwMIOyH0WSccjL3gS/40gwjnjBy7+HjOp7WJxPc2Eh8FDjOHUkrWi0Qi\nj6R4hVeNOStSLVvewHyPphKoSdQxVM4Q5/mvrkQowER6fdEGmpYAjc0fZ29sZGVu\nIDxnb2xkZW5AZXhhbXBsZS5pbnZhbGlkPsK/BBMWCABxBYJq9D48AwsJBwkQdw3k\nqPWekNs1FAAAAAAAHAAQc2FsdEBub3RhdGlvbnMub3BlbnBncGpzLm9yZ2VOFH8X\nh5yxg5eroXQ18qcCFQgDFgACAhkBApsDAh4BFiEEK2cnqpmZRXt67JN/dw3kqPWe\nkNsAAG6fAQDV8ehsHsFOKQzpeYLsixmXs/h0/DAH2sHWoj49Z9CqeQD+Oa+nLFB7\nqUQUr66n59p4R6RQ8yv5H3HSiP222s9fmAXHiwRq9D48EgorBgEEAZdVAQUBAQdA\n6FutOZ0NLbRiCAqLSd2txpkq/hfv0HgedU5u29B4mkYDAQoJ/gcDCDsh9FknHIy9\n4NWExuQW8SLjmpFYDBp0NvnfM8CdqvOnOmpuE3Fefei8GtlgkYmQferCHqw38bBv\nrKXVMg3lxzsl4PhnykpmmcYP7niNnCzCrgQYFggAYAWCavQ+PAkQdw3kqPWekNs1\nFAAAAAAAHAAQc2FsdEBub3RhdGlvbnMub3BlbnBncGpzLm9yZ34i6EDHnkQF/krz\nlrpZWpICmwwWIQQrZyeqmZlFe3rsk393DeSo9Z6Q2wAA4ocA/Rr/qWSSPj+q+uSN\n5imo6ET2IhnLJvcfhXQaMjN9aZvRAP9RWbdgdexbkbyoPI1I6zT1Yfb3Lg/9Vk/h\n0WiqPzmhAQ==\n=13w4\n-----END PGP PRIVATE KEY BLOCK-----",
|
||||
"AddressKeyPassphrase": "qoww/oDsj2wClAHEcf1w6KRmiiIegYZN8gnIEYiR+yo=",
|
||||
"RootKey": "-----BEGIN PGP PRIVATE KEY BLOCK-----\n\nxYYEavRU8BYJKwYBBAHaRw8BAQdAyYx5cRV31ovNSetf7tN542QIjXofDRwb5REq\nbgAUfTL+BwMIMMJR+/aYJWvg8RWLH459XM6tdGMymPBJf6uYIfNkCZPJuH/xgQlP\nUgnfauP/HE3mB4raN0Ewfdd5t3YHFH3LkKi9PTeyBIOxoSq+03v9ec0fZ29sZGVu\nIDxnb2xkZW5AZXhhbXBsZS5pbnZhbGlkPsK/BBMWCABxBYJq9FTwAwsJBwkQcokY\nuWqSnJY1FAAAAAAAHAAQc2FsdEBub3RhdGlvbnMub3BlbnBncGpzLm9yZwCnRKL/\nEVKgVnzorTxO7x0CFQgDFgACAhkBApsDAh4BFiEElLi748AC52UTTWtJcokYuWqS\nnJYAACRRAPwN9DnHokHSakHFOxhk4uQ7Vr782ISOzHngJ/NgOYtmygD/R/1ctxo5\nY32q3O+N1memq7Dij6DfU4GN6WbTA6ypaArHiwRq9FTwEgorBgEEAZdVAQUBAQdA\ncVbkQob/gu0TMrl+8sxRZKfmMKrnRC8QtN63i88MFE8DAQoJ/gcDCDDCUfv2mCVr\n4OixHp4Iy/zOVSPhV3eQSvPgFIb7lBp0m3nSGBgs6BGHRWLOys+Od7+AlLA0HjGa\nQf4cLnRKfvmiHV69WS0flFzsqxwfkdrCrgQYFggAYAWCavRU8AkQcokYuWqSnJY1\nFAAAAAAAHAAQc2FsdEBub3RhdGlvbnMub3BlbnBncGpzLm9yZ4m//YFqqVLRVFiw\njVvAD08CmwwWIQSUuLvjwALnZRNNa0lyiRi5apKclgAAAbYA/jDBwlC+AccJp5hS\n1nHztq3bhQqs88y8eS7fCucXwDA7AQDkXzeePakq4JUtoPCiTe/Zf5wzME0BJ6Hk\nEu0vBJkWCg==\n=oZX1\n-----END PGP PRIVATE KEY BLOCK-----",
|
||||
"RootKeyPassphrase": "a2W6imzT596kxrkFLloSQicvaE0k4CcUFRAmBkdDp3s=",
|
||||
"RootHashKey": "-----BEGIN PGP MESSAGE-----\n\nwV4DC8CXHujYN4ASAQdAAGQNjBfh2oFIyAgUxqF6Nk9KA70Yg/S4IuThF/nFnAMw\nTjLXIcTbQmZsjmIwJi2xSDFAKvaGADIE7f2J9s65RPHkzcea2btnJOeifP0cJJSy\n0sBZAT+gElIVu/UWLXbOl4r84L9SyJCrb5dAOxrAOmTjdpEif28K3oOo3AanKCc8\nkBVYnFz5tUWq4wjYLYKOG/UZJFY+X6ue6gBBxR7tbXWQ4BGcrF7EeeaSE2XyfX+A\naSsZ7EuLKD6Ow3c0lxFx77/9hZFDlYGRyfZIDFERZw/ibOfMITxIj9DsXI31Xl8u\nf40ZrdRragq2Wzk8t8sd0h5pvFzw0y99PjWlzeo4pTKHT5lfz+xPpj4Nn09KMqhR\nMW1VWtfTES3rwNEYw3NmLRSrEP480kr1tp10uLt4hNfDs9ymCCW/N5ZdNc0ycKJ6\nt7fH9QPa4fbPAUdgNRBjniYeco6hyUzEH7s4kSayX+IqB2zicdpEQhqdM/Q=\n=DyXT\n-----END PGP MESSAGE-----"
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Loaded 100 of 316 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user