Compare commits

..
Author SHA1 Message Date
Lucas WintherandClaude Opus 5.5 5a6ceb59ff docs: record the Proton Drive handover with Gitea as the only copy
ci / protondrive (push) In progress
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 23:30:47 +01:00
Lucas WintherandClaude Opus 5.5 98552c81dc docs: record the public GitHub branch and the upstream post
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 23:23:55 +01:00
Lucas WintherandClaude Opus 5.5 a1e80580e2 docs: hand over the Proton Drive work after the plan 002 review
ci / protondrive (push) Failing after 27m24s
Correct the polling interval wording, record the comparison with
clayliddell/proton-drive-go-sdk, log the review findings left open, and
add a draft post for the upstream discussion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 23:13:48 +01:00
Lucas WintherandClaude Opus 5.5 623c3fee2d protondrive: stop a misbehaving server from making one events poll run forever
Read at most 100 pages of events per poll; the rest are read by the next
poll.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 23:13:48 +01:00
Lucas WintherandClaude Opus 5.5 b4fa0fc8cc docs: bring the Proton Drive handoffs and architecture up to date
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 23:16:52 +01:00
Lucas WintherandClaude Opus 5.5 fa43dad943 docs: hand off Proton Drive M5 at the end of the day
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 23:15:13 +01:00
Lucas WintherandClaude Opus 5.5 d912e6ba24 protondrive: record what Task 7 of the events work left open
Record the refresh race investigation and the remaining race detector
reports in the security tests, give the reasons the TestMain and two
crypto items are left, and tick Task 7 in the plan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 23:09:55 +01:00
Lucas WintherandClaude Opus 5.5 8382fba094 protondrive: make three tests hold up on a loaded machine
Seen failing with three race-enabled suites run at once:

- TestDownloadRefetchOtherHash had 300 ms to corrupt a block in; 2 s
- TestPollerShutdownAndReuse could apply the replayed events after its
  last use, emptying the cache, so polling stopped; it now keeps using
  the Fs while it waits
- polls of the fake remote ending after captureLog put the log config
  back raced with it; the fake remote no longer polls after captureLog

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:01:26 +01:00
Lucas WintherandClaude Opus 5.5 021591a0ca protondrive: document that environment-set remotes can't share a refresh
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:50:46 +01:00
Lucas WintherandClaude Opus 5.5 1517d8e3d8 protondrive: say how to reconnect when the saved key password is wrong
A saved session whose key password unlocks no key failed with "is the
password right?" alone; it now also says to run rclone config
reconnect, as other unusable saved sessions do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:50:07 +01:00
Lucas WintherandClaude Opus 5.5 01882f7910 protondrive: warn in the docs not to share rclone config output
rclone config create, show and dump print the saved session, whose
salted key password outlives a sign out. Also say that a cache unused
for 10 minutes is forgotten, and make the fake server's init.d stop
kill protonfake if it hasn't stopped within 10s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:48:40 +01:00
Lucas WintherandClaude Opus 5.5 c1aa97fe34 protondrive: refuse oversized encrypted names before decrypting them
An uncompressed encrypted name, passphrase, hash key or extended
attributes far larger than the limit for its kind was decrypted into
memory in full before being refused; one of 10 MiB took about 230 MiB
to list. It is now refused by its size first. Also wrap the error for
folders nested too deep once rather than at every level, where a
hostile server could make it about 88 KB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:47:39 +01:00
Lucas WintherandClaude Opus 5.5 a066fa3e39 protondrive: stop security tests changing the log level under a poller
captureLog writes rclone's global log config, which an Fs polling for
changes reads; three hostile server cases called it with an Fs still
polling, a data race seen under load. They now shut the Fs down or
make it after capturing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:44:27 +01:00
Lucas WintherandClaude Opus 5.5 abd6701b2b protondrive: finish a poll for changes in flight before Shutdown returns
Shutdown cancelled a poll in flight without waiting for it, so a poll
whose response had already arrived could still log after Shutdown
returned; the race detector caught one racing with a test's change to
the log level. Shutdown and Disconnect now wait for the poll, though
not for any notification it makes.

Also make TestPollerShutdownAndReuse wait for its polls rather than
count them after a fixed sleep, which failed under load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:42:00 +01:00
Lucas WintherandClaude Opus 5.5 ebdb2307c9 protondrive: make three tests end cleanly when they fail
TestListingRacingChange now releases its held request however it ends,
rather than hanging until the package timeout, protonfake's TestRun
stops and waits for its server on a failed assertion, and
TestClientBootstrapCreateVolumeRace starts both clients at once rather
than always waiting 2 s for one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:38:31 +01:00
Lucas WintherandClaude Opus 5.5 669d7c08d1 protondrive: don't send a block's storage token on to a redirected host
Go's HTTP client drops only standard credential headers on a redirect
to another host, so pm-storage-token and x-pm-uid went with it; they
are now dropped too. Also let a later pass of a sync retry an upload
whose source changed while it was read, rather than failing it for
the whole run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:35:43 +01:00
Lucas WintherandClaude Opus 5.5 272fbe5ccb protondrive: don't fail a key lookup because another caller gave up
A caller waiting for another's fetch of the same public keys got that
caller's context error if it was cancelled; it now fetches them
itself. Also:

- build each own address's public key ring once at sign-in rather
  than on every lookup, 2-3 times per decrypted node
- a listing caching a node under a new parent forgets the old
  parent's listing, as caching a single node already did

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:33:45 +01:00
Lucas WintherandClaude Opus 5.5 d934016ba2 protondrive: fail a listing whose pages repeat instead of hanging
A server answering More with an anchor already followed made a listing
page until its context ended; it now fails at once. Also read an
extended attribute Size of null as missing, so the block sizes give
the size, rather than as 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:31:38 +01:00
Lucas WintherandClaude Opus 5.5 a60b5fc04a protondrive: stop polling for changes once the cache goes unused
With nothing subscribed to changes, a node cache neither read nor
filled for 10 minutes is now cleared, which stops polling until the
Fs is used again; before, an Fs never shut down polled for ever.

Also keep to one events request per interval:

- a Retry-After on an events request no longer holds up the listing
  that filled the cache; it delays the next poll instead
- after Shutdown, polling resumes from the cursor it had, an interval
  after reuse, instead of fetching a new cursor at once
- once the start cursor fetch has failed, the next is fetched after
  the backoff rather than inline

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:28:33 +01:00
Lucas WintherandClaude Opus 5.5 7b7cec65b8 protondrive: keep the cache when an event names a parent for the root
The root can't move, so an event reporting a parent for it now drops
only the root's listing rather than everything cached. Also:

- staleNode.parentID is the cached parent, empty for uncached nodes;
  the reported parent is always newParentID
- log at debug level when an events page with More set doesn't advance
- drop invalidateTree's walk of listings, which found nothing the
  walk of nodes doesn't, and a dead case in changedPaths
- test that refresh and a gone volume forget pending nodes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:17:50 +01:00
Lucas WintherandClaude Opus 5.5 9019302d2e protondrive: make the test server's events page size reset to default on 0
SetEventsPageSize of 0 or less served empty pages with More set for
ever; it now restores the default. Also check that deleting a draft
revision emits no event.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:15:21 +01:00
Lucas WintherandClaude Opus 5.5 1f1db51f6c test_all: skip FsChangeNotify against the real Proton Drive
fstests waits 27 s for changes and Proton allows one events request per
30 s. The live events check otherwise passed; record its findings and
tick plan 002 Task 6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:06:56 +01:00
Lucas WintherandClaude Opus 5.5 209c4c1b2e protondrive: log each page of events read at debug level
One line per page with the event count, the cursor and whether more
follow, so -vv shows what each poll read. Only IDs are logged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:06:56 +01:00
Lucas WintherandClaude Opus 5.5 4f09343620 protondrive: make the test server's events match Proton's
Checked live: rename, move and trash emit UpdateMetadata, a new
revision Update, and the Link fields of an event are the link's state
when the events are read, so a link deleted for good has no parent and
isn't trashed. The test server now does the same; injected events keep
their own fields. The backend already treats UpdateMetadata like
Update; a test pins a rename as UpdateMetadata and a folder made and
removed between polls.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:05:48 +01:00
Lucas WintherandClaude Opus 5.5 cb94ae034c protondrive: say in the enable_caching help that the cache follows other clients
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 18:53:57 +01:00
Lucas WintherandClaude Opus 5.5 8fecab6450 protondrive: keep the root folder when the directory cache is flushed
DirCacheFlush reset the directory cache to the volume root until the
root was found again, so a change notified in between would be named
relative to the volume root. It now keeps the root folder's ID, as
flushes made for change events do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 18:53:57 +01:00
Lucas WintherandClaude Opus 5.5 4fa81cbe49 protondrive: test change tracking of a remote rooted at a file
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 18:53:40 +01:00
Lucas WintherandClaude Opus 5.5 16acb17940 protondrive: notify the old path of a folder moved while not cached
A folder the node cache no longer held but the directory cache did, as
after the cache is cleared, was notified only by its new parent when
another client moved it, so a mount kept showing it at its old path.
Its old path is now notified as well, and flushed as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 18:53:25 +01:00
Lucas WintherandClaude Opus 5.5 0ea3605988 protondrive: name new items exactly in change notifications
An item's event can be applied before rclone caches the item, as for
its own uploads and new folders. Its folder is still notified at once,
and the item itself is now notified at its path if it is cached within
the next two polls, with no extra requests. This makes mounts and the
FsChangeNotify integration test see exact paths for such items.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 18:53:04 +01:00
Lucas WintherandClaude Opus 5.5 2fa149c373 protondrive: document change notification
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 18:41:15 +01:00
Lucas WintherandClaude Opus 5.5 2ccddb5585 protondrive: notify mounts of changes made by other clients
Add ChangeNotify, fed by the volume events: an item is reported at its
old path, and its new folder if it moved, when it was cached; otherwise
its folder is reported. An expired cursor reports the root. Every event
batch also flushes the folders it names from the dircache, so a folder
renamed or moved by another client is found under its new path and
nothing is left at its old one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 18:37:11 +01:00
Lucas WintherandClaude Opus 5.5 27e1a9c541 fstests: fix data race in FsChangeNotify
The notify function runs on the backend's goroutine while the test
reads the changes it records, so guard them with a mutex. This showed
up as a race detector failure for backends whose ChangeNotify is
tested with -race.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 18:09:38 +01:00
Lucas WintherandClaude Opus 5.5 c7af34305f protondrive: never notify event subscribers from inside a user operation
The first poll after a fill of the cache runs on the goroutine which
filled it, which may hold the dircache's lock or VFS's. It no longer
waits for the poller's lock there, and hands any notification (a gone
volume) to a goroutine of its own, so a subscriber taking those locks
can't deadlock.

Also clamp events_min_interval for Proton's endpoint written with a
trailing dot, document that onFill must be set before the cache is
shared, test a failing start cursor on the first fill, and make the
backoff test serial and less tight, as it counts shared goroutines and
pool buffers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 16:57:59 +01:00
Lucas WintherandClaude Opus 5.5 355fb0699d protondrive: poll volume events while the cache is in use
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 16:29:55 +01:00
Lucas WintherandClaude Opus 5.5 877bb5d10c protondrive: read volume events and invalidate the cache from them
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 16:05:46 +01:00
Lucas WintherandClaude Opus 5.5 d607fc6581 protondrive: emulate volume events in the fake server
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 15:53:25 +01:00
Lucas WintherandClaude Opus 5.5 6b02131ba3 docs: plan Proton Drive events and change notification (M5)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 15:42:33 +01:00
Lucas WintherandClaude Opus 5.5 fbf2d565e8 docs: bring the Proton Drive handoff up to date after the final review
ci / protondrive (push) Successful in 23m29s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 15:12:51 +01:00
Lucas WintherandClaude Opus 5.5 944b360054 protondrive: follow the renamed Proton code constant in the fake's tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:55:58 +01:00
Lucas WintherandClaude Opus 5.5 ad3552e2e5 docs: note the Proton Drive block size cache in the architecture
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:48:33 +01:00
Lucas WintherandClaude Opus 5.5 bfa9b7122b protondrive: tighten tests and docs from the final review, log the rest
Timing bounds in parallel tests leave room for a slow race runner, the
block 502 test checks its fault fired, refusedCommit's 408 exclusion is
pinned, the user docs explain the "server doesn't show it yet" error and
the conformance checklist matches the current draft and trust rules.
Every other minor from the review is listed in docs/TODO.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:48:17 +01:00
Lucas WintherandClaude Opus 5.5 d3aee2af19 protondrive: tidy small review findings
Log lines no longer cut a name inside a UTF-8 sequence, the "superseded
upload" error says the file's state rather than claiming a revision is
active, a test-only block decrypter moves to the tests, a one-line alias
of encryptPassphrase goes, the upload godoc is rewrapped and the fake's
server struct is gofmt clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:46:52 +01:00
Lucas WintherandClaude Opus 5.5 30cfcac416 protondrive: retry a token refresh that failed with a server error or timeout
When the access token expired and the refresh request got a 5xx, 429 or
408, the operation failed instead of being retried, and a 408 even ended
the session as if the refresh token had been rejected. Such failures are
now retried like any other call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:45:39 +01:00
Lucas WintherandClaude Opus 5.5 634a2423eb protondrive: make the tests honour RCLONE_CONFIG whichever tests run
Only fstest.Initialise, run by the integration test, applied
RCLONE_CONFIG, so a filtered test run read the default rclone config,
which may hold a real Proton remote. TestMain now applies it first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:44:18 +01:00
Lucas WintherandClaude Opus 5.5 b5da26169a ci: give the Proton Drive race suite room on a slow runner and pin its tools
The race suite ran under Go's default 10 minute limit, which a slow
runner would hit; it now has 40 minutes in a 60 minute job. Go is the
1.27 line the code was verified with, not go.mod's minimum, so
govulncheck checks a patched standard library, and govulncheck is
pinned to v1.9.0 so a new release can't break the build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:41:48 +01:00
Lucas WintherandClaude Opus 5.5 b4a23a31ed protondrive: log Proton's announced drive requirements at debug level
Proton announces requirements it will enforce, such as a minimum client
version, in x-pm-drive-requirements response headers. They are now
logged at debug level whenever they change, so they show in -vv bug
reports.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:41:19 +01:00
Lucas WintherandClaude Opus 5.5 5dbf5b04c6 protondrive: stop telling users to upgrade rclone on unrelated Proton errors
Proton's generic "requirements not met" code 2000, which it returns for
a node changed since it was read (as when a lost rename response is
resent), aborted the whole run with "upgrade rclone". It is now an
ordinary error that isn't retried. Code 2028 (a feature disabled,
rate-limited or blocked) is retried, and the codes Proton actually uses
for a rejected or missing app version, 5003 and 5001, now give the
upgrade message.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:40:13 +01:00
Lucas WintherandClaude Opus 5.5 788a711dc9 protondrive: make multi-thread downloads of files without block sizes linear
A file whose extended attributes don't record its block sizes, as some
other clients write, was read from the first block for every ranged
read, so a multi-thread copy, which opens each chunk as a range,
downloaded data quadratically: about 8.5 GiB for a 1 GiB file. The sizes
of blocks already read are now remembered per Fs (bounded to 16
revisions and 65536 blocks), so later chunks start at the right block.
A block list that disagrees with what was learnt is an integrity error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:37:40 +01:00
Lucas WintherandClaude Opus 5.5 674b538ca5 protondrive: keep the draft client ID stable for remotes configured from the environment
A remote set up with environment variables or a connection string can't
save its draft client ID, so it got a new random one on every run, and a
draft left by an earlier run then blocked uploading that name as if
another client were uploading it. When the ID can't be saved it is now
derived from the remote name and the account's volume, so it is the same
on every run. A remote in the config file still gets a random ID, saved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:32:14 +01:00
Lucas WintherandClaude Opus 5.5 94eedc942f protondrive: ignore modification times and hashes the owner didn't sign
Extended attributes whose signature failed or was missing were used, so
a server could set a file's modification time, size and SHA-1 at will:
for example make `rclone sync --update` skip every changed file. Without
ignore_signature_errors they are now not used and an ERROR is logged:
the modification time is the server's, there is no SHA-1, and the size
comes from the recorded block sizes, which reads check. The file stays
readable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:29:40 +01:00
Lucas WintherandClaude Opus 5.5 67e4cfeb7a protondrive: never reuse the session key of an unverified name on rename or move
Renaming or moving a node whose name signature failed reused the old
name's session key, which a server that made that name knows, so it could
read the new name. The new name now gets a new session key unless the
old name's signature verified.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:26:02 +01:00
Lucas WintherandClaude Opus 5.5 b3f5685e62 protondrive: refuse writing into a folder whose name hash key is unsigned
A folder's hash key whose signature failed or was missing was only
logged, and the names of everything written into the folder were then
hashed with it, so a server which made the key could test guesses at
those names. Creating, uploading, renaming, moving or copying into such
a folder is now refused unless ignore_signature_errors is set, when an
ERROR is logged once per folder. Reading is unaffected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:24:56 +01:00
Lucas WintherandClaude Opus 5.5 db7afafc08 protondrive: refuse node keys whose Argon2 parameters would exhaust memory
A node or share key from the server was unlocked with whatever Argon2
parameters it carried, so a crafted key could make every listing
including it allocate up to 2 TiB and crash rclone. Node and share keys
locked with Argon2 beyond 4 passes, parallelism 8 or 128 MiB are now
refused before the key derivation runs, as an integrity error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:23:50 +01:00
Lucas WintherandClaude Opus 5.5 e95317b52a protondrive: refuse files whose content key signature is missing
A server could replace a file's content key with one it made, without a
signature: updates were then encrypted with a key the server knows, and
ranged reads returned whatever it encrypted under that key. A missing or
invalid content key signature now makes the file unverified, like an
unverified node key: reads and updates are refused unless
ignore_signature_errors is set, when an ERROR is logged once per file and
operation. The fake gains corruptions for this and for the hash key,
name and extended attribute checks that follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:21:14 +01:00
Lucas WintherandClaude Opus 5.5 ea8d09ce43 docs: say which Proton Drive test files can't go upstream without the fake
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:10:53 +01:00
Lucas WintherandClaude Opus 5.5 29ad269444 docs: record the Proton Drive live verification results
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 13:53:13 +01:00
Lucas WintherandClaude Opus 5.5 b440df2e1f docs: note the conflict-cleanup delete after an unknown upload outcome
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 12:33:37 +01:00
Lucas WintherandClaude Opus 5.5 61733fce6e protondrive: add re-keyed fixtures of files written by Proton's web app and CLI
Captured from a throwaway test account on 2026-11-12 and re-keyed onto
test-only keys; no key, passphrase, ID or email of the account is in them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 12:32:19 +01:00
Lucas WintherandClaude Opus 5.5 f8e398fce1 protondrive: skip the live integration test during a golden capture
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 12:31:02 +01:00
Lucas WintherandClaude Opus 5.5 be00536078 protondrive: never delete an upload's draft unless Proton refused the commit
After a failed commit the client read the file back and deleted the
draft if the read showed it uncommitted. Proton's server can take a
moment to show a commit, so a stale read could send a delete against a
file or revision which had in fact been committed.

The draft is now deleted only when the server refused the commit with a
4xx API error on a single attempt which was not resent; any other
failure leaves it and reports that the upload may have succeeded. A
cancelled upload whose commit succeeded stops waiting for the server to
show it at once. The fake server's read lag can also serve a file
without an active revision.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 12:30:07 +01:00
Lucas WintherandClaude Opus 5.5 1b2fcbd212 protondrive: make the golden capture fail closed on foreign keys
The capture names its folder with -capture-remote and refuses -remote,
so a mistyped -run can't start the integration tests against the
account. Every key written has a placeholder user ID; a node key holding
another user's email, or a signature by or intended for a key not being
replaced, fails the capture without naming it. Salt notations are
written only where the original had one.

TestGoldenFixtures now also walks every key, key packet and signature of
a fixture, inside encrypted messages too, and checks folder modification
times; tampered fixtures are shown to fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 12:19:05 +01:00
Lucas WintherandClaude Opus 5.5 af6fdd7899 protondrive: fix uploads failing while Proton catches up after a commit
Proton's server can take a moment to show a change: a file read back
just after its commit may be missing or still a draft with no active
revision. Uploads then failed with "upload committed, but the file now
has another revision (revision  is active ...)" or "object not found".

The read back after a commit, the read of a server-side copy and, with
enable_caching off, the read of a folder to write into now retry with
backoff for about 7 s while the change doesn't show. A committed upload
the server still doesn't show after that fails with a new "committed,
but the server doesn't show it yet" error, deletes nothing and is not
retried at once. The fake server gains SetReadLag to model the lag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 11:57:02 +01:00
Lucas WintherandClaude Opus 5.5 a2dc6f71f1 protondrive: test against re-keyed files written by Proton's own clients
TestGoldenCapture (-capture DIR -capture-label NAME -remote NAME:PATH)
captures a folder another client wrote, re-keyed onto keys made for the
tests: blocks and signature-free SEIPD packets kept byte for byte, key
packets re-wrapped, signatures re-made with the same parameters (names,
hash keys and extended attributes encrypted again with their own session
keys, as their signatures are embedded), IDs and emails replaced.
TestGoldenFixtures reads every fixture in testdata/golden through the
backend from the fake server with every signature checked.

The fake server can now seed stored folders and keeps the times of
seeded nodes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 11:35:36 +01:00
Lucas WintherandClaude Opus 5.5 502a32b5f3 protondrive: name the SDK commit the client was last checked against
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:30:31 +01:00
Lucas WintherandClaude Opus 5.5 22b9c4fdc3 protondrive: fix ranged reads of files which don't record block sizes
A file written by an old client without recorded block sizes was read
in ranges by assuming 4 MiB blocks, so a range past the first block could
return the wrong bytes, or too few, without an error. Such a range is now
read from the first block, discarding the bytes before it, with every
block still checked against its hash.

Also identify the SDK the conformance checklist was checked against by
commit, and align the enable_caching help with the docs page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:19:53 +01:00
Lucas WintherandClaude Opus 5.5 7be50f9e22 protondrive: update docs for the rewritten backend
Rewrite the hand-written parts of the Proton Drive docs page for the
native client: browser and password sign-in with a transcript taken from
the current code, the third-party notice, what is verified on upload and
download, the ranged-read caveat, the trust rules and the
ignore_signature_errors option, the two protocol limits, the --dump
warning, filename rules, drafts, trash and limits. The generated options
section is left for make backenddocs.

Describe everything ignore_signature_errors allows in its help text,
update the feature list and score in protondrive.yaml, and add the SDK
conformance checklist and fork notes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:06:19 +01:00
Lucas WintherandClaude Opus 5.5 c1464a39ab docs: mark Task 19 done in the Proton Drive handoff
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 09:54:41 +01:00
Lucas WintherandClaude Opus 5.5 fd7a0dc98d chore: allow golangci-lint run in the Claude Code settings
The owner added the rule; docs/PERMISSIONS.md already listed it in the
Allow tier. Also record that the force-with-lease deny rule misses the
`--force-with-lease=` form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 09:53:08 +01:00
Lucas WintherandClaude Opus 5.5 cf7577dc1d protondrive: drop Proton-API-Bridge and go-proton-api
The old libraries were only used by the differential crypto tests. Those
go, and TestFrozenFixtures moves into crypto_internal_test.go without its
-update branch, so files the old library wrote stay checked through the
frozen fixtures in testdata/oldlib. go mod tidy removes the two libraries
and the modules only they pulled in; relvacode/iso8601 leaves go.mod.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 09:51:43 +01:00
Lucas WintherandClaude Opus 5.5 b667a1ab0f docs: record the owner's answers, the history rewrite and Task 18 in the Proton Drive handoff
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 09:29:46 +01:00
Lucas WintherandClaude Opus 5.5 5afbe9e4fa protondrive: run the wider suites against the fake server in fork CI
Add the TestProtonDriveFake init.d script, which builds and starts
protonfake on port 28642 and passes on the session it prints, and a
test_all entry for it, so fs/operations, fs/sync, vfs and cmd/bisync
run against the fake server. Five tests that need a second Fs of the
same account to see what the first wrote are ignored, as each Fs
caches separately, and cmd/gitannex is skipped as for every init.d
remote; both are in docs/TODO.md.

Add a Gitea Actions workflow that builds, vets, lints, race-tests,
fuzzes and vulnerability-checks the backend, and re-verify the agent
permission table on the host toolchain.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 09:23:26 +01:00
Lucas WintherandClaude Fable 5.2 65840bdc57 docs: record open questions and credential locations in the Proton Drive handoff
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 21:24:07 +01:00
Lucas WintherandClaude Fable 5.2 4282540e02 docs: correct the Proton Drive handoff after a cold read
build / windows (push) Skipped
build / other_os (push) Skipped
build / mac_amd64 (push) Skipped
build / mac_arm64 (push) Skipped
build / linux (push) Skipped
build / go1.26 (push) Skipped
build / linux_386 (push) Skipped
build / lint (push) Skipped
build / android-all (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/386 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/amd64 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm/v6 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm/v7 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm64 (push) Skipped
Build & Push Docker Images / Merge & Push Final Docker Image (push) Waiting for needed jobs
A reader with only the repository walked the handoff and the remaining
plan tasks against the code. Mark the plan and spec lines that later
rulings superseded, add corrections for Tasks 18 to 21, fix stale TODO
and PERMISSIONS entries, ignore the skill workspace, point AGENTS.md at
the handoff and take the test account usernames out of it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 21:21:43 +01:00
Lucas WintherandClaude Fable 5.2 31f6aafd91 docs: hand off the paused Proton Drive backend rewrite
Development of plan 001 is paused after Task 17 of 21. Record the state,
the rulings made during execution, the test setup and how to resume in
docs/plans/001-protondrive-tier1-HANDOFF.md, commit the execution ledger,
task briefs, implementer reports and reviews, and mark the plan and spec
with their current status.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 21:09:43 +01:00
Lucas WintherandClaude Opus 5.5 9c90998f76 protondrive: correct the memory a full read may hold and note what remains unbounded
The comment and spec put the block metadata a full read holds at a few
hundred bytes a block; with realistic tokens and URLs the cap allows
about 250-350 MiB, and those fields and API response bodies aren't
bounded at all. TODO also asks the live check to confirm the
root-of-trust rule on a drive made by Proton's own apps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:46:18 +01:00
Lucas WintherandClaude Opus 5.5 0cd3af4295 protondrive: return only the bytes asked for when a range covers the whole file
A range covering the whole file was read as a plain full read, so a
file whose recorded size understated its content returned more bytes
than the range asked for. It is now checked as a full read but stops
at the end of the range.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:45:54 +01:00
Lucas WintherandClaude Opus 5.5 8666b66038 protondrive: stop at a folder the server reports as its own ancestor
Fetching a file or folder fetches its folders up to one already known,
and a server reporting folders as each other's parents made that
recurse until rclone crashed. A cycle, or folders nested more than 2048
deep, is now an error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:44:19 +01:00
Lucas WintherandClaude Opus 5.5 52a44e41ce protondrive: log an error for each unverified file or folder used with ignore_signature_errors
With ignore_signature_errors set, reading a file, writing into a folder,
or moving, copying or renaming either when its key isn't verified went
ahead without a word. Each now logs an error, once per file or folder
and operation, saying what was done and why the key isn't trusted - and
that what is moved or copied out is trusted from then on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:42:14 +01:00
Lucas WintherandClaude Opus 5.5 15bc60ead9 protondrive: verify your own address in any letter case with your own keys
The check that the drive is shared and signed by your own address
ignored letter case, but keys were looked up by exact address, so a
server naming your address in capitals could serve keys of its own for
it. Addresses are now matched ignoring ASCII case only, everywhere, and
your own address in any such case is always verified with your own
keys, never ones the server supplies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:40:43 +01:00
Lucas WintherandClaude Opus 5.5 c28077174e protondrive: check warm listings within the listing budget test
The warm listing budget, with caching on and off, reuses the folders
TestBudgetList seeds instead of seeding its own, which saves about 15s
under -race. The assertions are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:30:05 +01:00
Lucas WintherandClaude Opus 5.5 16480e3d80 protondrive: refuse to write names which aren't valid UTF-8
With an encoding which lets invalid UTF-8 through, rclone could create
a file or folder whose name Proton's clients, and rclone itself, then
refuse to read, so it vanished from listings. Such names are now
refused when writing.

Found by FuzzValidateName.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:28:21 +01:00
Lucas WintherandClaude Opus 5.5 18b4f7d1d1 protondrive: don't list a file as empty when its recorded size is missing or invalid
A file whose extended attributes had a SHA-1 but a missing, negative or
malformed Size was listed with size 0, so copying it failed with a size
mismatch. Its size is now the sum of its recorded block sizes, if they
are usable, and otherwise unknown, as for a file without extended
attributes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:27:33 +01:00
Lucas WintherandClaude Opus 5.5 f89be42eaf protondrive: don't cache a folder listing read while the folder changed
A listing whose pages were read before a file or folder was made in,
copied into or trashed from the folder cached what it read when it
finished, overwriting the change. As new files are added to a cached
listing rather than dropping it, the stale listing then lasted: a file
just uploaded stayed missing, and a trashed one stayed listed, until
something else dropped the listing.

The node cache now counts changes to the children of each folder being
listed, and a listing is cached only if none happened since its first
page was read. The count is kept only while a listing is in progress.

The fake server gains a Hold fault, which answers a request with the
response made on arrival only once released, to test this without
sleeps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:25:35 +01:00
Lucas WintherandClaude Opus 5.5 e7e43095d8 protondrive: restore the config storage even when rclone's config is in memory
The password test's cleanup restored the config path before the
storage, and setting the storage does nothing while the path is empty,
so with an in-memory config the storage was left behind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:10:25 +01:00
Lucas WintherandClaude Opus 5.5 2a1a8f046e protondrive: restore rclone's config storage after the password test
TestPasswordStoredObscured installed the config file storage for its
temporary config and left it in place for the tests after it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:03:39 +01:00
Lucas WintherandClaude Opus 5.5 202b64cf1e protondrive: cap the number of blocks a file may list
A full read holds the list of a file's blocks until it has checked the
signed manifest, and how long that list could grow was bounded only by
a size the server sends unsigned. A file listing more than 2^19 blocks
(2 TiB in 4 MiB blocks) is now an error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:03:18 +01:00
Lucas WintherandClaude Opus 5.5 58fde59f34 protondrive: check the signed block list when a range asks for the whole file
A request for the whole file as a range, as "bytes=0-" from serve http
or webdav clients, was read as a ranged read, which can't check the
file's signed block list. It is now read as a full read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:01:02 +01:00
Lucas WintherandClaude Opus 5.5 cb6e6759b8 protondrive: trust a drive only if it is shared and signed by your own address
The drive's share and root folder were accepted when signed by any
address whose keys the server served, so a hostile server could vouch
for a whole drive of its own making. If the share wasn't created, or
the root folder signed, by one of the account's own addresses, reading
and writing now fail with an error saying so, unless
ignore_signature_errors is set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:00:16 +01:00
Lucas WintherandClaude Opus 5.5 787bb3b3fa protondrive: refuse to move or copy a file or folder whose key isn't verified
Moving or copying a file or folder out of a folder with a forged key
had rclone sign the server's key as the user's, after which it read
without error. Moving, copying or renaming a node whose key isn't
verified now fails unless ignore_signature_errors is set, and anything
beneath such a folder, including what rclone writes there with the
option set, stays unverified.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 19:57:18 +01:00
Lucas WintherandClaude Opus 5.5 12ce57ed31 protondrive: add request budget tests and fuzz targets
Request budgets, measured against the fake server and asserted at the
measured counts, for listing (cold and warm, with and without
enable_caching), a no-op sync by modification time and by checksum,
NewObject three folders deep, uploads and making folders. A TestMain
hook fails the package if any test, through any fake server, requested
a removed share-scoped route; the fake keeps a process-wide tally of
them for it.

Fuzz targets, seeded from testdata/oldlib and from what the fake
writes, for name validation, link decoding, extended attributes, API
error bodies with Retry-After and session fork payloads. Each checks
invariants of what is accepted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 19:48:18 +01:00
Lucas WintherandClaude Opus 5.5 90b2a48e71 protondrive: skip nodes the server sends without an ID or with a negative size
A node which decrypted was handed on whatever its link ID and encrypted
size, so a faulty or hostile server could make rclone cache a node
under an empty ID or list a file with a negative size. Such nodes are
now left out of listings and logged, as nodes with invalid names are.

Found by FuzzDecodeLink.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 19:33:39 +01:00
Lucas WintherandClaude Opus 5.5 32710eefd1 protondrive: refuse metadata which decompresses to an excessive size
Names, node passphrases, hash keys and extended attributes are
encrypted to public keys, so the server, or anyone, can write them as a
small compressed message which expands to gigabytes when decrypted.
They were decompressed into memory without a limit.

Names, passphrases and hash keys are now limited to 64 KiB and extended
attributes to 16 MiB, enough for the block sizes of an 8 TiB file.

Extended attributes with a negative Size are now read as having no
size, as the reference SDK reads other invalid sizes, so a file is never
listed with a negative size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 19:22:28 +01:00
Lucas WintherandClaude Opus 5.5 3fac25de75 protondrive: don't list a folder again after each file or folder made in it
Making a file or folder, or a server-side copy, forgot the cached
listing of its folder, so the next upload into that folder - which
checks the name is free - listed the whole folder again. Copying M new
files into a folder of N cost on the order of M*N/100 extra requests.

The new node is now added to the cached listing. A failed call still
forgets it, as the call may have taken effect.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 19:19:14 +01:00
Lucas WintherandClaude Opus 5.5 751a3ea357 protondrive: test config obscuring the password and refused updates
The password test now runs rclone config with the password in plain
text and checks it is stored obscured; a test checks a file whose key
isn't its owner's can't be updated; and the log test checks every
session token the fake issued, which it now labels by kind, not only
the saved ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 18:59:21 +01:00
Lucas WintherandClaude Opus 5.5 248f467054 protondrive: don't save refreshed tokens after disconnect
A token refresh still in flight when the remote was disconnected could
write its new tokens back to the config after Disconnect removed them.
Disconnect now waits for it and removes them afterwards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 18:59:21 +01:00
Lucas WintherandClaude Opus 5.5 9598e22d90 protondrive: check a file's signed block list before handing out any of it
A full read verified the manifest signature only at the end, so blocks
a server swapped, dropped or took from an older revision reached the
reader - and rclone cat or a mount - before the error. A full read now
lists every block and verifies the manifest before releasing the first
byte, and a block listed again with a different hash is an integrity
error. Ranged reads are unchanged.

The fake's "rollback" corruption is renamed "block-rollback": serving a
whole earlier revision under the current revision ID can't be detected,
which the spec and TODO now say.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 18:51:15 +01:00
Lucas WintherandClaude Opus 5.5 88654eb04d protondrive: distrust files and folders beneath a folder with a forged key
A server could put a folder with a key of its own making into a real
folder and serve anonymous files beneath it whose every signature
checked out against that key, so they were read without an error.
A key checked against an unverified folder key is now unverified too,
all the way down: reading such a file, or creating, uploading, moving
or copying anything into such a folder, fails unless
ignore_signature_errors is set. Listing it still works.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 18:48:11 +01:00
Lucas WintherandClaude Opus 5.5 f4105adfc1 protondrive: add hostile-server and secret-hygiene tests
A hostile fake server tampers with block hashes, block order and count,
serves an older revision's or another key's blocks, signs a node
passphrase with its own key and gives nodes names such as "../x", "a/b",
NUL and 10 MiB: each read fails or the node is left out, with and
without ignore_signature_errors, and a copy or sync writes nothing
wrong or outside its destination. The log at debug level, and with
--dump headers, holds no password, key password, session or storage
token, node passphrase or session key; browser sign-in leaves no
password in the config and password sign-in keeps it obscured.

The fake gains rollback and foreign-block corruptions and exposes the
secrets it issued and a file's node secrets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 18:34:50 +01:00
Lucas WintherandClaude Opus 5.5 db97ef7c8d protondrive: stop a call rejected during disconnect retrying without credentials
A call in flight when the remote was disconnected, and then rejected
as unauthorised, was sent again with empty credentials. It now fails
with the "not signed in" error instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 18:22:53 +01:00
Lucas WintherandClaude Opus 5.5 59f0f31b34 protondrive: name the remote to reconnect when the session expires or is signed out
An expired session, or one signed out with "rclone config disconnect"
while a long running rclone was using it, told the user to reconnect a
remote literally called "remote:". The error now names the remote.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 18:22:02 +01:00
Lucas WintherandClaude Opus 5.5 6065801968 protondrive: refuse to read a file whose key isn't signed by its owner
A file whose node passphrase signature didn't verify was read with
only an error logged when it was listed, although a server could have
substituted a key of its own making and with it any content. Reading
such a file now fails unless ignore_signature_errors is set, as for a
content key or manifest signature which fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 18:21:07 +01:00
Lucas WintherandClaude Opus 5.5 8600815384 protondrive: add regression tests for known failures
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 18:05:33 +01:00
Lucas WintherandClaude Opus 5.5 14128d59c0 protondrive: say how to read a file whose signature fails to verify
The error for a content key or manifest signature which fails now
ends with a hint to set ignore_signature_errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 17:59:16 +01:00
Lucas WintherandClaude Opus 5.5 6e2410de69 protondrive: name the remote in the CAPTCHA error and offer browser sign-in in config
A CAPTCHA on password sign-in told the user to reconnect a remote
literally called "remote:". The error from NewFs now names the remote
and is fatal, and rclone config goes back to the choice of sign-in
method with a hint to use the web browser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 17:58:35 +01:00
Lucas WintherandClaude Opus 5.5 c00162ed20 protondrive: keep folders with unseen content, saved sessions on config edits and a usable Fs after shutdown
- rmdir asks the server whether a folder has any child, so it never
  trashes a folder holding Proton Docs, unreadable files or children
  added by another client since it was listed
- rclone config asks before replacing a saved session (default no), and
  signs the old session out after signing in again
- Shutdown only drops caches; after Disconnect the remote reports that
  it isn't signed in
- update, move and copy refuse a file another client has trashed
- ranged reads are computed on the decrypted size whatever
  original_file_size says

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 17:47:54 +01:00
Lucas WintherandClaude Opus 5.5 0ec7dce0e5 protondrive: rewrite the backend on a native client following Proton's SDK
The backend no longer uses Proton-API-Bridge or go-proton-api at run
time. Saved sessions from earlier versions keep working without signing
in again, and every option keeps its name and meaning. rclone config
now offers sign-in with a web browser. The full backend test suite runs
against an in-process fake Proton server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 17:28:24 +01:00
Lucas WintherandClaude Opus 5.5 414de88c99 protondrive: add hermetic contract test harness
Add protonfake, a command which serves the fake Proton server on a
given address and prints the endpoint and a saved session of a user
with a Drive volume as key=value lines, for an fstest test server
script. protontest gains NewStandalone and Close for it.

Add setupFakeRemote, which configures TestProtonDriveFake: with a
fresh session on the fake through environment variables, and
TestIntegrationFake, which runs the backend contract suite against it.
It is skipped until the backend has an endpoint option.

client_salted_key_pass is written base64 encoded, the meaning the key
has in existing configs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 17:01:53 +01:00
Lucas WintherandClaude Opus 5.5 e23de0b586 protondrive: make the volume creation race test deterministic
TestClientBootstrapCreateVolumeRace failed now and then in whole
package race runs with "expected 2 POST /drive/volumes, got 1".

loadAccount holds the process-wide unlockMu while unlocking keys, so
the second client's first GET drive/v2/shares/my-files is sent one
key unlock, or under load many queued unlocks, after the first's. The
500ms Delay fault on both GETs shifted them equally and so did not
keep them together: when the first client's create had finished
before the second client's GET was handled, the second client found
the volume and never POSTed. The client handles that ordering
correctly; only the test's assertion depended on timing.

Add a Gather option to protontest faults, which holds each faulted
request until all Times have arrived, and use it for both GETs and
both POSTs. The test now starts the second client as late as the
server lets it, which failed 10 of 10 runs with the Delay fault.

Gathering the POSTs runs both create volume checks in the fake at
once, which exposed a data race there: go-crypto records signature
checks in a key on its first use, and the new user's address key had
never been used. Check each request with its own copy of the key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 16:37:14 +01:00
Lucas WintherandClaude Opus 5.5 e65c785c15 protondrive: state the v6 file fixture's provenance in the fixture
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:07:50 +01:00
Lucas WintherandClaude Opus 5.5 e76b6783b2 protondrive: add whole-file differential tests
Files uploaded by the new client are read whole by the old library's
readers, and files written by the old library (go-proton-api v1.0.4,
Proton-API-Bridge v1.0.5), in the legacy and the v6 format, are
downloaded by the new client through the fake server. Frozen fixtures
of both formats keep the second direction tested once the old library
is gone.

protontest gains read-only access to a file as stored, seeding of a
stored file, and users built from fixed address and root keys. It now
signs no earlier than the signing key's creation time, which a key
supplied by a test may be.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:52:55 +01:00
Lucas WintherandClaude Opus 5.5 dc7d977e17 protondrive: delete an upload's draft only on proof its commit failed
After a failed commit the draft was deleted whenever the file read
back did not show the upload's revision active. A file changed by
another client since (a newer revision, or trashed) proves nothing,
and deleting then removed committed content. Now the draft is deleted
only when the read shows a new file still a draft, or the revision the
upload started from still active; otherwise nothing is deleted and
the outcome is reported as unknown. A successful commit whose file
already has another revision when read back is an error rather than
returning another client's revision as the upload's.

The fake gains SeedRevision, giving a file a new revision as another
client would.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:25:08 +01:00
Lucas WintherandClaude Opus 5.5 1f1b2bb325 protondrive: never delete an upload whose commit may have succeeded
After a failed commit the upload read the file back with the caller's
context. When that context was cancelled, or the read failed, the
commit was taken as not done and its draft deleted, which deletes the
file or revision if the commit had in fact taken effect. The read now
runs past cancellation, the draft is deleted only when the read shows
the revision is not active, and an outcome that can't be read is
reported as possibly successful without deleting anything.

Also fix a data race in the fake's storage upload handler and add
tests for a failing source and for a failing block with the producer
blocked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:18:00 +01:00
Lucas WintherandClaude Opus 5.5 9a4ed61a88 protondrive: add verified block upload
Upload follows the SDK's upload module (js/v0.23.0) step for step:
draft file or draft revision, name-conflict handling (own draft
deleted and retried once, another client's draft refused unless
replace_existing_draft, an existing file given a new revision),
verification code, blocks encrypted and checked against the server's
content key, upload URLs requested in batches, uploads bounded per file
(upload_concurrency, default 4, max 5) and per client (10 blocks),
size and SHA1 checks, signed manifest and extended attributes, commit
with a check that a failed commit is not in fact active, and draft
cleanup on any failure or cancellation. Blocks are streamed through
lib/pool buffers; a block is tried 3 times and a storage 404 requests a
new URL. Cancellation is bounded everywhere, including waits for the
client's upload tokens.

The fake server gains the upload routes with strict checks: names,
passphrases and extended attributes must be non-AEAD, the file key a
v4 key with an ordinary S2K, the content key packet a v6 PKESK and
blocks SEIPDv2; verifier tokens, block indexes, declared hashes and the
manifest signature are checked at commit. It now signs a day in the
past and checks signatures in Dump at its own clock, so clock-skew
tests can run in both directions.

Where the plan and the SDK differ on the wire, the SDK wins:
- IntendedUploadSize follows the SDK: for a new file it is sent only
  when the rounded size is over 100,000 bytes; for a new revision it is
  reduceSizePrecision (4095 under 4 KiB, 100,000 under 100 kB).
- BlockList entries carry no Hash or Size (deprecated, unused); the
  fake checks a Hash only if one is sent.
- An empty stream of unknown size is uploaded as zero blocks, which
  the SDK refuses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:07:27 +01:00
Lucas WintherandClaude Opus 5.5 e8b1359760 protondrive: reject absurd recorded block sizes when downloading
A recorded block size above 8 MiB is now an integrity error, so the
sizes can't overflow, and a full read always lists the blocks so it
reaches the manifest check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:26:35 +01:00
Lucas WintherandClaude Opus 5.5 4bcafe5cd4 protondrive: add verified ranged download
Download a range of a file's content block by block: block URLs come
from the revision's paged block list (20 per page), blocks are fetched
through the storage pacer holding a download token without the
session's credentials, checked against their SHA-256 before decrypting
and decrypted into pool buffers. A full read checks the manifest
signature, by the content author's address or the node key for an
anonymous upload, and the content key packet signature is checked on
open with the SDK's fallback to every address key for files created
before 2023.

The retry and capped Retry-After logic of apiCall is shared with block
downloads through the new pacedCall.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:20:18 +01:00
Lucas WintherandClaude Opus 5.5 ee81e742f2 protondrive: add folder, move, copy and trash operations
Add createFolder, rename, move, copyNode, trash and emptyTrash to the
new client, following the SDK's nodesManagement.ts: names and
passphrases are re-encrypted to the new parent with their session keys
and signed by the share's address; the node passphrase signature is
sent on move and copy only for an anonymous node; API code 2500 maps to
errExists and 2501 to errNotFound. Every mutation updates the node
cache, and nodeCache.put forgets both parents' listings when a node's
parent changes.

The fake gains the matching routes plus checkAvailableHashes. It
rejects SEIPDv2 or v6 PKESK names, passphrases, hash keys and extended
attributes, and folder keys which are not v4, advertise AEAD or are not
locked with an iterated and salted S2K. It enforces name hash
uniqueness, OriginalHash, no move into a descendant and the anonymous
signature rule. Dump now also checks every name hash, and
SeedAnonymousFile seeds a public-link upload.

Wire format: the create folder request sends SignatureEmail as the SDK
does, although CreateFolderDto lists SignatureAddress.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 12:59:34 +01:00
Lucas WintherandClaude Opus 5.5 a8856ff7cd protondrive: cap Retry-After and retry public key lookups
A 429's Retry-After is now honoured for at most 60 seconds and is
waited out by the call alone, so a hostile value can neither stall the
client nor hold every other call behind the shared pacer. Public key
lookups during listing are paced and retried like every other call
instead of failing the listing on one 429 or 5xx.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 12:42:20 +01:00
Lucas WintherandClaude Opus 5.5 2065b7b09a protondrive: add node listing with cache and pacing
Add the client the new backend will use above the wire: it loads the
account, finds or creates the main volume, share and root, and lists
folders by paging child IDs and fetching their metadata 100 at a time
with at most 15 requests in flight, decrypting with the verification
keys the SDK's nodes module chooses.

A brand-new account has no volume: my-files answers code 2501 and the
client creates the volume as the SDK's shares module does, accepting
code 2500 from a concurrent creator.

Nodes whose name or key can't be decrypted, or whose name is not valid,
are left out with one error each; Proton Docs and Sheets are left out
with one notice; failed signature checks are logged once and the node
is still listed.

API calls are paced and retried: 429 waits for Retry-After before
retrying, 408 and 5xx are retried, other client errors are not.

errExists moves to Task 9, which first uses it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 12:32:38 +01:00
Lucas WintherandClaude Opus 5.5 27d06dca19 protondrive: add drive state to the fake server
Every fake user now has a real, correctly encrypted drive: a volume, a
main share and a root folder, built as the SDK's
generateVolumeBootstrap does. Seeding helpers create folders, files in
the current format (v6 PKESK content key, SEIPDv2 GCM blocks, encrypted
block signatures, signed manifest, extended attributes), legacy files
(v3 PKESK, SEIPDv1) and Proton Docs nodes; Corrupt damages them as a
hostile server would and Dump decrypts and verifies the whole tree.

The read routes (my-files, volume, share, link metadata, children,
revision) answer with the field names of the SDK's driveTypes.ts, and
block bytes are served from the same server behind pm-storage-token.

AddUserWithoutDrive models a brand-new account, whose my-files answers
HTTP 422 code 2501, and POST /drive/volumes creates its volume after
checking the key material decrypts with the address key.

protontest/crypto.go is written from the SDK independently of the
backend's crypto.go. Interface additions are recorded in the plan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 12:14:13 +01:00
Lucas WintherandClaude Opus 5.5 3b63f3c7d5 protondrive: add differential crypto tests against the old library
Cross-test crypto.go against go-proton-api v1.0.4 and Proton-API-Bridge
v1.0.5 in both directions, compare account key unlocking with
proton.Unlock, and freeze old-library output under testdata/oldlib so
it stays tested once the old libraries are gone. github.com/relvacode/iso8601
becomes a direct requirement because the test parses modification
times as the bridge does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:52:16 +01:00
Lucas WintherandClaude Opus 5.5 fdcb6ab322 protondrive: verify hash keys signed by older rclone versions
Folder hash keys written by go-proton-api (and any message gopenpgp
encrypts and signs in one go) carry intended recipient fingerprints in
their signature. Decrypting with the session key alone made gopenpgp
reject those as "intended recipients in non-encrypted message", so
every folder created by released rclone reported a hash key signature
error. The intended recipients are now checked against the decryption
keys by hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:52:16 +01:00
Lucas WintherandClaude Opus 5.5 a1e1333c7d protondrive: check node signatures against the verification keys only
gopenpgp looks the signer of an inline signature up in the decryption
keys as well as the verification keys, so a name or extended attributes
signed by the parent or node key reported as verified whatever keys the
caller asked for. Decrypt the session key first and the data with the
session key alone, so only the verification keys count, as in the SDK.

Also clear the decrypted passphrase when the node key fails to unlock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:33:33 +01:00
Lucas WintherandClaude Opus 5.5 0bb2dbdf34 protondrive: add node cryptography
Add the OpenPGP operations of the Drive data model as pure functions:
node keys and passphrases, names, hash keys and lookup hashes, content
keys, blocks, verifier tokens, manifests and extended attributes.

The formats follow the reference SDK (driveCrypto.ts, openPGPCrypto.ts),
which differs from the plan's Task 5 interfaces in these ways, now
updated in the plan:

- node keys are v4 EdDSA/ECDH with user ID "Drive key" and ordinary S2K
  locking; file keys (aead=true) advertise SEIPDv2 with AES-256-GCM and
  folder keys don't, as the SDK's enableAead
- the content key is v6 only when the node key advertises SEIPDv2, as
  the SDK's preference-following session key generation
- the content key signature is checked on read against the node key and
  extra (address) keys
- block signatures are encrypted with the content session key, as the
  SDK's encryptSignature
- hash keys are signed by the node key; reading also accepts address keys
- reencryptPassphrase signs anew, and encryptName takes the current name
  session key for rename and move
- name length is counted in UTF-16 code units, as the SDK

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:27:57 +01:00
Lucas WintherandClaude Fable 5.2 666df153e2 docs: run plan tests with RCLONE_CONFIG=/notfound
Fork-only. Not for upstream.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 11:14:27 +01:00
Lucas WintherandClaude Opus 5.5 483c3a1518 protondrive: test that address keys with a bad signature are refused
Add a fake server switch that signs an address key's passphrase with an
unrelated key or removes the signature, and test that loading fails on
the primary address and leaves out a secondary one. Also clear an
unlocked key that can't be added to its key ring.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:13:50 +01:00
Lucas WintherandClaude Opus 5.5 6ec49842c4 protondrive: load and unlock account keys
Load the user and addresses and unlock their keys, one unlock at a time
across all sessions so concurrent sign-ins don't multiply peak memory.
Address key passphrases are taken from their Token only when the user
key's signature on it verifies, as the SDK requires. Other users' public
keys are fetched once per account and cached, an email without a Proton
address having no keys.

Password sign-in now derives the key password from the salt of the
primary user key rather than the first salt, which is wrong for accounts
whose user keys have different salts. The SDK uses the first salt; it
remains the fallback when no salt matches.

The fake server gives each user real Curve25519 user and address keys,
and serves GET /core/v4/users, /core/v4/addresses and /core/v4/keys/all.

gopenpgp v3 moves to a direct dependency.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:08:40 +01:00
Lucas WintherandClaude Opus 5.5 5a8bb0247f protondrive: test that password sign-in rejects a bad server proof
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 10:59:52 +01:00
Lucas WintherandClaude Opus 5.5 2ba0848dcc protondrive: add password and browser sign-in
Add SRP password sign-in (with TOTP, two-password accounts and a clear
error when Proton asks for a CAPTCHA), browser sign-in through a session
fork, and sign-out to the new session, with the matching routes in the
fake server. The fake does real server-side SRP with go-srp and issues
a per-user key salt.

Where the plan and the SDK differ, the SDK wins:
- the fork sign-in URL escapes its payload like encodeURIComponent
  (authWeb.ts generateSignInUrl), so the plan's literal URL is the
  unescaped form;
- POST /core/v4/auth sends PersistentCookies 1 and an empty Payload
  (auth.ts authViaPassword);
- the key password uses the first KeySalts entry (auth.ts
  getUserKeyPassword).

protontest.ApproveFork takes the sign-in URL instead of the user code,
since the payload key exists only in the URL; the plan is updated.

go-srp moves to a direct dependency.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 10:56:04 +01:00
Lucas WintherandClaude Opus 5.5 9d894ab1b7 protondrive: keep two sessions on one config working when both refresh
When two sessions that share stored credentials refresh at the same
time, both post the same single-use refresh token and the server
rejects one. The session that loses now waits briefly for the winner's
tokens to appear in the store and uses them, instead of failing with
"session expired".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 10:37:19 +01:00
Lucas WintherandClaude Opus 5.5 ea41704ade protondrive: add session with safe token refresh
Add the session used for authenticated API calls: it sends x-pm-uid,
the bearer token, x-pm-appversion and the Proton Accept header, decodes
failures into api.Error, and on HTTP 401 refreshes the tokens and
retries once. Refresh is single-flight, first adopts tokens another
session saved to the shared store, and on a rejected refresh token
returns a fatal "session expired" error without clearing the stored
credentials or retrying the refresh. The session also tracks the
server's clock from the Date header.

The app version maps development builds to the "alpha" channel, as
Proton's x-pm-appversion grammar has no "dev" channel.

The fake server gains users, sessions, single-use refresh tokens and
401 for invalid access tokens on authenticated routes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 10:33:43 +01:00
Lucas WintherandClaude Opus 5.5 2e3dbac3a4 protondrive: add fake Proton server skeleton for tests
Add the api.Error type with Proton response codes and the protontest
package: an httptest-based fake that rejects legacy share-scoped routes
with 410, enforces the published x-pm-appversion grammar, refuses
x-pm-drive-sdk-version, counts requests per route, skews the Date header
and injects scripted faults.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 10:27:41 +01:00
Lucas WintherandClaude Fable 5.2 06700aaf22 docs: add implementation plan for the Proton Drive rewrite (M0-M4)
Fork-only. Not for upstream.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 10:23:09 +01:00
Lucas WintherandClaude Fable 5.2 83ae5d1876 docs: approve Proton Drive spec with the fork owner's decisions
Fork-only. Not for upstream.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 10:17:10 +01:00
Lucas WintherandClaude Fable 5.2 6f92948dac docs: add draft spec for an SDK-conformant Proton Drive backend
Fork-only. Not for upstream.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 10:12:23 +01:00
Lucas WintherandClaude Fable 5.2 a28ee25855 build: add agent docs, permissions and spec/plan layout for the fork
Fork-only. Appends a Fork Workflow section to AGENTS.md and adds
GEMINI.md, per-tool permission files and docs/ pages for agent driven
development. Not for upstream.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 10:01:49 +01:00
261 changed files with 16326 additions and 3117 deletions

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
{
"permissions": {
"allow": [
"Bash(git status:*)", "Bash(git diff:*)", "Bash(git log:*)", "Bash(git show:*)",
"Bash(git rev-parse:*)", "Bash(git add:*)", "Bash(git commit:*)",
"Bash(go mod download:*)", "Bash(go build:*)", "Bash(go test:*)", "Bash(go vet:*)",
"Bash(gofmt -l:*)",
"Bash(golangci-lint run:*)"
],
"ask": [
"Bash(git push:*)", "Bash(git merge:*)", "Bash(git rebase:*)", "Bash(git switch:*)",
"Bash(git restore:*)", "Bash(git commit --amend:*)", "Bash(rm:*)",
"Bash(go get:*)", "Bash(go mod tidy:*)", "Bash(go install:*)",
"Bash(make:*)", "Bash(docker:*)"
],
"deny": [
"Bash(git push --force:*)", "Bash(git push -f:*)", "Bash(git push --force-with-lease:*)",
"Bash(git reset --hard:*)", "Bash(git clean:*)", "Bash(git add -f:*)", "Bash(git add --force:*)",
"Bash(git commit --no-verify:*)", "Bash(git commit -n:*)",
"Bash(rm -r:*)", "Bash(rm -R:*)", "Bash(rm -rf:*)", "Bash(rm -fr:*)", "Bash(rm -Rf:*)",
"Bash(rm -fR:*)", "Bash(rm --recursive:*)", "Bash(sudo:*)",
"Read(./.env)", "Read(./.env.*)", "Read(./secrets/**)"
]
}
}
+2
View File
@@ -0,0 +1,2 @@
sandbox_mode = "workspace-write"
approval_policy = "on-request"
+20
View File
@@ -0,0 +1,20 @@
# Rendered from docs/PERMISSIONS.md - change both in the same commit.
# Deny
prefix_rule(pattern = ["git", "push", ["--force", "-f", "--force-with-lease"]], decision = "forbidden",
justification = "Force-push rewrites shared history.")
prefix_rule(pattern = ["git", "reset", "--hard"], decision = "forbidden", justification = "Discards work.")
prefix_rule(pattern = ["git", "clean"], decision = "forbidden", justification = "Deletes untracked files.")
prefix_rule(pattern = ["git", "add", ["-f", "--force"]], decision = "forbidden",
justification = "Stages ignored files, e.g. secrets.")
prefix_rule(pattern = ["git", "commit", ["--no-verify", "-n"]], decision = "forbidden", justification = "Skips hooks.")
prefix_rule(pattern = ["rm", ["-r", "-R", "-rf", "-fr", "-Rf", "-fR", "--recursive"]], decision = "forbidden",
justification = "Recursive delete.")
prefix_rule(pattern = ["sudo"], decision = "forbidden", justification = "No privilege escalation.")
# Ask
prefix_rule(pattern = ["git", ["push", "merge", "rebase", "switch", "restore"]], decision = "prompt")
prefix_rule(pattern = ["git", "commit", "--amend"], decision = "prompt")
prefix_rule(pattern = ["rm"], decision = "prompt")
prefix_rule(pattern = ["go", ["get", "install"]], decision = "prompt")
prefix_rule(pattern = ["go", "mod", "tidy"], decision = "prompt")
prefix_rule(pattern = ["make"], decision = "prompt")
prefix_rule(pattern = ["docker"], decision = "prompt")
+20
View File
@@ -0,0 +1,20 @@
{
"tools": {
"allowed": [
"run_shell_command(git status)", "run_shell_command(git diff)", "run_shell_command(git log)",
"run_shell_command(git show)", "run_shell_command(git branch --list)",
"run_shell_command(git add)", "run_shell_command(git commit)",
"run_shell_command(go mod download)", "run_shell_command(go build)",
"run_shell_command(go test)", "run_shell_command(go vet)", "run_shell_command(gofmt -l)",
"run_shell_command(golangci-lint run)"
],
"exclude": [
"run_shell_command(git push --force)", "run_shell_command(git push -f)",
"run_shell_command(git push --force-with-lease)", "run_shell_command(git reset --hard)",
"run_shell_command(git clean)", "run_shell_command(git add -f)", "run_shell_command(git add --force)",
"run_shell_command(git commit --no-verify)", "run_shell_command(git commit -n)",
"run_shell_command(rm -r)", "run_shell_command(rm -R)", "run_shell_command(rm -rf)",
"run_shell_command(rm -fr)", "run_shell_command(rm -Rf)", "run_shell_command(sudo)"
]
}
}
+56
View File
@@ -0,0 +1,56 @@
# Fork CI for the Proton Drive backend. Every step is hermetic: the
# tests run against the fake server in backend/protondrive/protontest.
name: ci
on:
push:
pull_request:
env:
# Never pick up a config holding a real Proton remote.
RCLONE_CONFIG: /notfound
jobs:
protondrive:
runs-on: ubuntu-latest
# The race suite takes about 6 minutes on a fast machine and 7 on
# two cores; the slow runner may take several times that.
timeout-minutes: 60
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install Go
uses: actions/setup-go@v5
with:
# The line the code was verified with, not go.mod's minimum,
# so govulncheck sees a patched standard library.
go-version: '1.27.x'
# Caches the module and build caches, keyed on go.sum.
cache: true
- name: Build
run: go build ./...
- name: Vet
run: go vet ./backend/protondrive/...
- name: Lint
uses: golangci/golangci-lint-action@v8
with:
version: v2.15.0
args: ./backend/protondrive/...
- name: Test
# Go's default 10 minute limit per test binary is too short
# for the race suite on a slow runner.
run: go test -race -timeout 40m ./backend/protondrive/...
- name: Fuzz
run: |
for target in $(go test -list '^Fuzz' ./backend/protondrive/ | grep '^Fuzz'); do
go test -run '^$' -fuzz "^${target}\$" -fuzztime 20s ./backend/protondrive/
done
- name: Vulnerability check
run: go run golang.org/x/vuln/cmd/govulncheck@v1.9.0 ./backend/protondrive/...
+9 -9
View File
@@ -37,7 +37,7 @@ jobs:
include:
- job_name: linux
os: ubuntu-latest
go: '~1.27.4'
go: '~1.27.3'
gotags: cmount
build_flags: '-include "^linux/"'
check: true
@@ -48,14 +48,14 @@ jobs:
- job_name: linux_386
os: ubuntu-latest
go: '~1.27.4'
go: '~1.27.3'
goarch: 386
gotags: cmount
quicktest: true
- job_name: mac_amd64
os: macos-latest
go: '~1.27.4'
go: '~1.27.3'
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.4'
go: '~1.27.3'
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.4'
go: '~1.27.3'
gotags: cmount
cgo: '0'
build_flags: '-include "^windows/"'
@@ -81,14 +81,14 @@ jobs:
- job_name: other_os
os: ubuntu-latest
go: '~1.27.4'
go: '~1.27.3'
build_flags: '-exclude "^(windows/|darwin/|linux/)"'
compile_all: true
deploy: true
- job_name: go1.26
os: ubuntu-latest
go: '~1.26.11'
go: '~1.26.10'
quicktest: true
racequicktest: true
@@ -287,7 +287,7 @@ jobs:
id: setup-go
uses: actions/setup-go@v7
with:
go-version: '~1.27.4'
go-version: '~1.27.3'
check-latest: true
cache: false
@@ -402,7 +402,7 @@ jobs:
id: setup-go
uses: actions/setup-go@v7
with:
go-version: '~1.27.4'
go-version: '~1.27.3'
# Caching is handled explicitly below to share the module cache
# with the other jobs - see the build job for the rationale.
cache: false
+6
View File
@@ -22,3 +22,9 @@ resource_windows_*.syso
/librclone.h
.devcontainer
/cmd/bisync/testdata/bisync_vscode_debuggers_launch.json
.env
.env.*
CLAUDE.local.md
.claude/settings.local.json
.worktrees/
.superpowers/
+13
View File
@@ -134,3 +134,16 @@ Uses golangci-lint v2 with config in `.golangci.yml`. Enabled linters: errcheck,
- Command docs are in the command source code (e.g., `cmd/ls/ls.go`).
- Don't commit autogenerated doc changes from `make backenddocs` or `make commanddocs`.
- Website docs are in `docs/content/` as markdown, built with Hugo (`make serve` to preview).
## Fork Workflow
This fork carries agent tooling that upstream does not. Never include `docs/specs/`, `docs/plans/`, `docs/{ARCHITECTURE,DECISIONS,TODO,PERMISSIONS}.md`, `GEMINI.md`, `.claude/`, `.codex/`, `.gemini/` or this section in a PR to rclone/rclone.
- Required skill: `superpowers` - check at session start, install if missing. There is no product UI here, so `impeccable` is not needed.
- Specs go in `docs/specs/NNN-slug.md` (permanent). Plans go in `docs/plans/NNN-slug.md` and are removed with `git rm` before merge. This overrides the superpowers default paths.
- Paused or in-flight work is listed under "Now" in `docs/TODO.md` with the handoff to read first.
- Non-trivial work: brainstorm → spec → plan → TDD → review. For trivial fixes say "trivial, skipping spec" and proceed.
- Log things noticed but deliberately not fixed in `docs/TODO.md`, record decisions in `docs/DECISIONS.md`, and keep `docs/ARCHITECTURE.md` in step with structural changes - in the same commit as the code.
- `docs/PERMISSIONS.md` is the source for the `.claude/`, `.codex/` and `.gemini/` permission files - change them together.
- Never push, force-push or commit directly to `master`. Ask before adding or upgrading a dependency (`go get`, `go mod tidy`).
- Done means run in this session and seen passing: `go build`, `go test` on the touched packages, and `golangci-lint run` on them.
+8
View File
@@ -0,0 +1,8 @@
# GEMINI.md
**`AGENTS.md` is the single source of truth for this repository.** Read
`./AGENTS.md` before doing anything else and follow it exactly.
This file exists only so Gemini CLI finds the rules. It contains no project
rules of its own - add those to `AGENTS.md`. If anything here ever conflicts
with `AGENTS.md`, `AGENTS.md` wins.
-1
View File
@@ -63,7 +63,6 @@ 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)
-144
View File
@@ -1,144 +0,0 @@
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)
}
-3
View File
@@ -91,9 +91,6 @@ 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 {
+3 -16
View File
@@ -44,8 +44,6 @@ const (
heuristicBytes = 1048576
minCompressionRatio = 1.1
defaultCompressionLevel = sgzip.DefaultCompression
gzFileExt = ".gz"
zstdFileExt = ".zst"
metaFileExt = ".json"
@@ -109,11 +107,8 @@ 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).
- 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,
- Negative gzip levels: -2 = Huffman-only, -1 = default (≈ level 5).`,
Required: true,
}, {
Name: "ram_cache_limit",
Help: `Some remotes don't allow the upload of files with unknown size.
@@ -230,17 +225,9 @@ 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:
level, err := resolveZstdLevel(opt.CompressionLevel)
if err != nil {
return nil, err
}
opt.CompressionLevel = level
modeHandler = &zstdModeHandler{level: level}
modeHandler = &zstdModeHandler{}
case Uncompressed:
modeHandler = &uncompressedModeHandler{}
default:
+2 -115
View File
@@ -2,27 +2,16 @@
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"
)
@@ -149,6 +138,7 @@ 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)
@@ -167,111 +157,8 @@ 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())
}
+1 -15
View File
@@ -6,7 +6,6 @@ import (
"crypto/md5"
"encoding/hex"
"errors"
"fmt"
"io"
"github.com/buengese/sgzip"
@@ -17,15 +16,6 @@ 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{}
@@ -117,11 +107,10 @@ func (g *gzipModeHandler) putCompress(
// Compress the file
pipeReader, pipeWriter := io.Pipe()
resultsGzip := make(chan compressionResult[sgzip.GzipMetadata], 1)
resultsGzip := make(chan compressionResult[sgzip.GzipMetadata])
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
@@ -161,9 +150,6 @@ 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)
+1 -1
View File
@@ -123,7 +123,7 @@ func TestIsCompressible(t *testing.T) {
require.NoError(t, err)
for name, handler := range map[string]compressionModeHandler{
"gzip": &gzipModeHandler{},
"zstd": &zstdModeHandler{level: defaultZstdLevel},
"zstd": &zstdModeHandler{},
} {
t.Run(name, func(t *testing.T) {
ok, err := handler.isCompressible(bytes.NewReader(compressible), 0)
+3 -38
View File
@@ -6,7 +6,6 @@ import (
"crypto/md5"
"encoding/hex"
"errors"
"fmt"
"io"
"github.com/klauspost/compress/zstd"
@@ -17,39 +16,12 @@ 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 {
level int
}
type zstdModeHandler struct{}
// 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))
@@ -135,11 +107,10 @@ func (z *zstdModeHandler) putCompress(
// Compress the file
pipeReader, pipeWriter := io.Pipe()
resultsZstd := make(chan compressionResult[SzstdMetadata], 1)
resultsZstd := make(chan compressionResult[SzstdMetadata])
go func() {
writer, err := NewWriterSzstd(pipeWriter, zstd.WithEncoderLevel(zstd.EncoderLevel(z.level)))
writer, err := NewWriterSzstd(pipeWriter, zstd.WithEncoderLevel(zstd.EncoderLevel(f.opt.CompressionLevel)))
if err != nil {
_ = pipeWriter.CloseWithError(err)
resultsZstd <- compressionResult[SzstdMetadata]{err: err}
close(resultsZstd)
return
@@ -173,12 +144,6 @@ 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
}
-8
View File
@@ -3908,10 +3908,6 @@ 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.
@@ -3936,10 +3932,6 @@ 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.
+64 -9
View File
@@ -67,21 +67,76 @@ 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)
opts := rest.Opts{
Method: "GET",
RootURL: directLink,
Options: options,
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)
}
}
}
var resp *http.Response
// Wrap the response body to handle offset and count
var reader io.ReadCloser
err = o.fs.pacer.Call(func() (bool, error) {
resp, err = o.fs.srv.Call(ctx, &opts)
return shouldRetry(err), err
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
})
if err != nil {
return nil, fmt.Errorf("failed to download file: %w", err)
return nil, err
}
return resp.Body, nil
return reader, nil
}
// Update updates the object with new data
+9 -95
View File
@@ -34,7 +34,6 @@ func init() {
Name: "filen",
Description: "Filen",
NewFs: NewFs,
Config: Config,
Options: []fs.Option{
{
Name: "email",
@@ -52,14 +51,11 @@ func init() {
Name: "api_key",
Help: `API Key for your Filen account
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
Get this 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",
@@ -109,75 +105,6 @@ 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)
@@ -191,16 +118,13 @@ 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 := opt.APIKey
if apiKey != "" {
apiKey, err = obscure.Reveal(apiKey)
if err != nil {
return nil, fmt.Errorf("failed to reveal api key: %w", err)
}
apiKey, err := obscure.Reveal(opt.APIKey)
if err != nil {
return nil, fmt.Errorf("failed to reveal api key: %w", err)
}
var filen *sdk.Filen
if password == internalPassword {
if password == "INTERNAL" {
tsconfig := sdk.TSConfig{
Email: opt.Email,
MasterKeys: strings.Split(opt.MasterKeys, "|"),
@@ -214,13 +138,6 @@ 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 {
@@ -254,7 +171,6 @@ 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{
@@ -929,7 +845,7 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
return nil, err
}
defer f.filen.Unlock()
if sdk.NamesEqual(oldParentPath, newParentPath) {
if oldParentPath == newParentPath {
err = f.rename(ctx, obj.file, newPath, newName)
} else if newName == oldName {
err = f.move(ctx, obj.file, newPath, newParentPath)
@@ -1104,9 +1020,7 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
return fs.ErrorDirNotFound
}
// 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() {
if dstDir != nil {
return fs.ErrorDirExists
}
@@ -1126,7 +1040,7 @@ func (f *Fs) dirMoveEntireDir(ctx context.Context, srcDir *types.Directory, oldP
var err error
if oldPath == newPath {
return fs.ErrorDirExists
} else if sdk.NamesEqual(oldParentPath, newParentPath) {
} else if oldParentPath == newParentPath {
err = f.rename(ctx, srcDir, newPath, newName)
} else if newName == oldName {
err = f.move(ctx, srcDir, newPath, newParentPath)
-80
View File
@@ -1,80 +0,0 @@
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"`)
})
}
-23
View File
@@ -133,25 +133,6 @@ 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),
@@ -287,7 +268,6 @@ 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"`
@@ -542,9 +522,6 @@ 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))
}
+1 -1
View File
@@ -145,7 +145,7 @@ func (f *Fs) dbImport(ctx context.Context, hashName, sumRemote string, sticky bo
if err != nil {
return fmt.Errorf("cannot open sum file: %w", err)
}
hashes, err := operations.ParseSumFile(ctx, sumObj, hashType)
hashes, err := operations.ParseSumFile(ctx, sumObj)
if err != nil {
return fmt.Errorf("failed to parse sum file: %w", err)
}
+20 -34
View File
@@ -25,15 +25,6 @@ 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"
@@ -135,16 +126,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 len(c.Session.Cookies) > 0 && len(c.Session.AccountInfo.Webservices) > 0 {
if c.Session.Cookies != nil && 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 len(c.Session.Cookies) > 0 && c.loadCachedWebservices() {
if c.Session.Cookies != nil && c.loadCachedWebservices() {
fs.Debugf(nil, "iclouddrive: reusing session with cached endpoints")
return nil
}
if len(c.Session.Cookies) > 0 {
if c.Session.Cookies != nil {
if err := c.Session.ValidateSession(ctx); err == nil {
fs.Debugf(nil, "iclouddrive: valid session, no need to reauth")
c.saveCachedWebservices()
@@ -154,29 +145,24 @@ func (c *Client) authenticateSession(ctx context.Context) error {
}
fs.Debugf(nil, "iclouddrive: authenticating")
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{}
err := c.Session.SignIn(ctx, c.appleID, c.password)
if err != nil {
return err
}
return errors.New("iCloud account domain changed repeatedly")
// 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)
}
}
return err
}
// loadCachedWebservices loads service endpoints from disk cache
+34 -66
View File
@@ -6,7 +6,6 @@ import (
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"maps"
@@ -31,7 +30,6 @@ 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"`
@@ -44,18 +42,6 @@ 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"`
@@ -234,7 +220,6 @@ 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)
@@ -300,7 +285,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", s.endpoints().base)
params.Set("redirect_uri", "https://www.icloud.com")
params.Set("response_type", "code")
params.Set("response_mode", "web_message")
params.Set("state", frameTag)
@@ -314,7 +299,7 @@ func (s *Session) authStart(ctx context.Context) error {
"Accept": "*/*",
"User-Agent": iCloudUserAgent,
},
RootURL: s.endpoints().auth,
RootURL: authEndpoint,
NoResponse: true,
}
@@ -348,7 +333,7 @@ func (s *Session) authFederate(ctx context.Context, accountName string) error {
Path: "/federate",
Parameters: url.Values{"isRememberMeEnabled": {"true"}},
ExtraHeaders: s.getSRPAuthHeaders(),
RootURL: s.endpoints().auth,
RootURL: authEndpoint,
Body: body,
NoResponse: true,
}
@@ -383,7 +368,7 @@ func (s *Session) authSRPInit(ctx context.Context, aBase64, accountName string)
Method: "POST",
Path: "/signin/init",
ExtraHeaders: s.getSRPAuthHeaders(),
RootURL: s.endpoints().auth,
RootURL: authEndpoint,
Body: body,
}
@@ -423,7 +408,7 @@ func (s *Session) authSRPComplete(ctx context.Context, accountName, m1Base64, m2
Path: "/signin/complete",
Parameters: url.Values{"isRememberMeEnabled": {"true"}},
ExtraHeaders: s.getSRPAuthHeaders(),
RootURL: s.endpoints().auth,
RootURL: authEndpoint,
IgnoreStatus: true,
Body: body,
}
@@ -432,7 +417,7 @@ func (s *Session) authSRPComplete(ctx context.Context, accountName, m1Base64, m2
if err != nil {
return err
}
_, _ = io.Copy(io.Discard, resp.Body)
respBody, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
s.extractHeaders(resp)
@@ -443,7 +428,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")
fs.Debugf(nil, "iclouddrive: SRP sign in requires 2FA, response: %s", respBody)
s.needs2FA = true
return nil
case http.StatusPreconditionFailed:
@@ -453,7 +438,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", resp.Status)
return fmt.Errorf("sign in failed: %s: %s", resp.Status, respBody)
}
}
@@ -467,7 +452,7 @@ func (s *Session) authRepairComplete(ctx context.Context) error {
Method: "POST",
Path: "/repair/complete",
ExtraHeaders: s.getSRPAuthHeaders(),
RootURL: s.endpoints().auth,
RootURL: authEndpoint,
IgnoreStatus: true,
NoResponse: true,
Body: body,
@@ -486,14 +471,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 (s *Session) getAuthOrigin() string {
return strings.TrimSuffix(s.endpoints().auth, "/appleauth/auth")
func getAuthOrigin() string {
return strings.TrimSuffix(authEndpoint, "/appleauth/auth")
}
// getSRPAuthHeaders returns headers needed for SRP auth requests
func (s *Session) getSRPAuthHeaders() map[string]string {
frameTag := "auth-" + s.FrameID
authOrigin := s.getAuthOrigin()
authOrigin := getAuthOrigin()
headers := map[string]string{
"Accept": "application/json",
"Content-Type": "application/json",
@@ -503,7 +488,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": s.endpoints().base,
"X-Apple-OAuth-Redirect-URI": "https://www.icloud.com",
"X-Apple-OAuth-Require-Grant-Code": "true",
"X-Apple-OAuth-Response-Mode": "web_message",
"X-Apple-OAuth-Response-Type": "code",
@@ -541,37 +526,20 @@ func (s *Session) AuthWithToken(ctx context.Context) error {
opts := rest.Opts{
Method: "POST",
Path: "/accountLogin",
ExtraHeaders: s.getCommonHeaders(nil),
RootURL: s.endpoints().setup,
IgnoreStatus: true,
ExtraHeaders: GetCommonHeaders(map[string]string{}),
RootURL: setupEndpoint,
Body: body,
}
var login struct {
AccountInfo
DomainToUse string `json:"domainToUse"`
}
resp, err := s.Request(ctx, opts, nil, &login)
resp, err := s.Request(ctx, opts, nil, &s.AccountInfo)
if err != nil {
return err
}
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)
}
}
fs.Debugf(nil, "iclouddrive: accountLogin response cookies: %v", cookieDebugSummaries(resp.Cookies()))
fs.Debugf(nil, "iclouddrive: session cookie jar after accountLogin: %v", cookieJarDebugSummaries(s.Cookies))
// ErrDomainChanged indicates that Apple requires authentication on another iCloud domain.
var ErrDomainChanged = errors.New("iCloud account domain changed")
return nil
}
type pcsService struct {
wsKey string
@@ -640,7 +608,7 @@ func (s *Session) acquirePCSCookiesFor(ctx context.Context, appName string, cook
Method: "POST",
Path: "/requestPCS",
ExtraHeaders: s.GetHeaders(map[string]string{}),
RootURL: s.endpoints().setup,
RootURL: setupEndpoint,
Body: body,
}
var pcsResp struct {
@@ -683,7 +651,7 @@ func (s *Session) RequestPushNotification(ctx context.Context) error {
Method: "PUT",
Path: "/verify/trusteddevice/securitycode",
ExtraHeaders: s.GetAuthHeaders(map[string]string{}),
RootURL: s.endpoints().auth,
RootURL: authEndpoint,
NoResponse: true,
}
@@ -703,7 +671,7 @@ func (s *Session) Validate2FACode(ctx context.Context, code string) error {
Method: "POST",
Path: "/verify/trusteddevice/securitycode",
ExtraHeaders: s.GetAuthHeaders(map[string]string{}),
RootURL: s.endpoints().auth,
RootURL: authEndpoint,
Body: body,
NoResponse: true,
}
@@ -749,7 +717,7 @@ func (s *Session) GetAuthState(ctx context.Context) (*AuthStateResponse, error)
Method: "GET",
Path: "",
ExtraHeaders: s.GetAuthHeaders(map[string]string{}),
RootURL: s.endpoints().auth,
RootURL: authEndpoint,
ContentLength: new(int64(0)),
}
// Use srv.Call directly to capture the raw response body for debugging
@@ -809,7 +777,7 @@ func (s *Session) RequestSMSCode(ctx context.Context, phoneID int, mode string)
Method: "PUT",
Path: "/verify/phone",
ExtraHeaders: s.GetAuthHeaders(map[string]string{}),
RootURL: s.endpoints().auth,
RootURL: authEndpoint,
Body: body,
NoResponse: true,
}
@@ -835,7 +803,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: s.endpoints().auth,
RootURL: authEndpoint,
Body: body,
NoResponse: true,
}
@@ -858,7 +826,7 @@ func (s *Session) TrustSession(ctx context.Context) error {
Method: "GET",
Path: "/2sv/trust",
ExtraHeaders: s.GetAuthHeaders(map[string]string{}),
RootURL: s.endpoints().auth,
RootURL: authEndpoint,
NoResponse: true,
ContentLength: new(int64(0)),
}
@@ -877,7 +845,7 @@ func (s *Session) ValidateSession(ctx context.Context) error {
Method: "POST",
Path: "/validate",
ExtraHeaders: s.GetHeaders(map[string]string{}),
RootURL: s.endpoints().setup,
RootURL: setupEndpoint,
ContentLength: new(int64(0)),
}
_, err := s.Request(ctx, opts, nil, &s.AccountInfo)
@@ -899,7 +867,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 := s.getCommonHeaders(map[string]string{})
headers := GetCommonHeaders(map[string]string{})
headers["Cookie"] = s.GetCookieString()
maps.Copy(headers, overwrite)
return headers
@@ -924,12 +892,12 @@ func (s *Session) GetCookieString() string {
return b.String()
}
// getCommonHeaders generates common HTTP headers with optional overwrite
func (s *Session) getCommonHeaders(overwrite map[string]string) map[string]string {
// GetCommonHeaders generates common HTTP headers with optional overwrite
func GetCommonHeaders(overwrite map[string]string) map[string]string {
headers := map[string]string{
"Content-Type": "application/json",
"Origin": s.endpoints().base,
"Referer": fmt.Sprintf("%s/", s.endpoints().base),
"Origin": baseEndpoint,
"Referer": fmt.Sprintf("%s/", baseEndpoint),
"User-Agent": iCloudUserAgent,
}
maps.Copy(headers, overwrite)
-112
View File
@@ -1,125 +1,13 @@
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"}}
+27 -103
View File
@@ -35,7 +35,6 @@ 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"`
}
@@ -54,7 +53,6 @@ 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)
@@ -81,7 +79,7 @@ func loadAuthSession(m configmap.Mapper) (*configAuthState, error) {
return &st, nil
}
func restoreAuthSession(icloud *api.Client, st *configAuthState) error {
func restoreAuthSession(icloud *api.Client, st *configAuthState) {
icloud.Session.Scnt = st.Scnt
icloud.Session.SessionID = st.SessionID
icloud.Session.AuthAttributes = st.AuthAttributes
@@ -89,10 +87,6 @@ func restoreAuthSession(icloud *api.Client, st *configAuthState) error {
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
@@ -106,9 +100,7 @@ func resumeConfigClient(m configmap.Mapper, appleid, password, trustToken, clien
if err != nil {
return nil, nil, err
}
if err := restoreAuthSession(icloud, st); err != nil {
return nil, nil, err
}
restoreAuthSession(icloud, st)
return icloud, st, nil
}
@@ -116,29 +108,11 @@ 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
@@ -174,49 +148,6 @@ 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"
@@ -298,18 +229,6 @@ 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.",
@@ -317,11 +236,6 @@ 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.",
@@ -359,7 +273,6 @@ 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 {
@@ -371,13 +284,34 @@ 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
}
return finishConfigAuthentication(ctx, name, m, icloud)
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
case config.State == "2fa_do":
code := config.Result
@@ -404,9 +338,6 @@ 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)
@@ -466,9 +397,6 @@ 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
}
@@ -505,7 +433,6 @@ 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(
@@ -521,9 +448,6 @@ 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
-57
View File
@@ -1,57 +0,0 @@
//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)
}
-4
View File
@@ -41,9 +41,6 @@ const (
configClientID = "client_id"
configCookies = "cookies"
configTrustToken = "trust_token"
configRegion = "region"
regionGlobal = "global"
regionChina = "china"
minSleep = 10 * time.Millisecond
maxSleep = 2 * time.Second
@@ -55,7 +52,6 @@ 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"`
+3 -12
View File
@@ -18,7 +18,6 @@ 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"
@@ -189,7 +188,6 @@ 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
@@ -226,7 +224,6 @@ 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))),
}
@@ -633,10 +630,8 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
return nil, err
}
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, err
}
client := &http.Client{}
req, _ := http.NewRequest("GET", url, nil)
if partialContent {
if count > 0 {
req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+count-1))
@@ -644,15 +639,11 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
req.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset))
}
}
resp, err := o.fs.srv.Do(req)
resp, err := client.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
@@ -1,86 +0,0 @@
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))
})
}
}
-15
View File
@@ -101,11 +101,6 @@ 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,
@@ -136,16 +131,6 @@ 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,
}},
})
}
+17 -55
View File
@@ -50,8 +50,7 @@ const (
defaultMountpoint = "Archive"
jfsURL = "https://jfs.jottacloud.com/jfs/"
apiURL = "https://api.jottacloud.com/"
contentURL = "https://content.jottacloud.com/"
webAppURL = "https://app.jottacloud.com/"
wwwURL = "https://www.jottacloud.com/"
cachePrefix = "rclone-jcmd5-"
configDevice = "device"
configMountpoint = "mountpoint"
@@ -59,9 +58,6 @@ 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"
@@ -174,39 +170,6 @@ 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,
}}...),
})
}
@@ -244,7 +207,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(configVersionKey, fmt.Sprint(configVersion))
m.Set("configVersion", 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.`)
@@ -293,7 +256,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(configVersionKey, fmt.Sprint(configVersion))
m.Set("configVersion", fmt.Sprint(configVersion))
m.Set(configClientID, service.clientID)
m.Set(configClientSecret, "")
m.Set(configTokenURL, wellKnown.TokenEndpoint)
@@ -307,9 +270,9 @@ service, for the official service on https://www.jottacloud.com/web/secure.`)
},
})
case "legacy": // configure a jottacloud backend using legacy authentication
m.Set(configVersionKey, fmt.Sprint(legacyConfigVersion))
m.Set("configVersion", fmt.Sprint(legacyConfigVersion))
return fs.ConfigConfirm("legacy_api", false, "config_machine_specific", `Do you want to create a machine specific API key?
Rclone has its own Jottacloud API KEY which works fine as long as one
Rclone has it's 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
@@ -323,25 +286,25 @@ machines.`)
}
m.Set(configClientID, deviceRegistration.ClientID)
m.Set(configClientSecret, obscure.MustObscure(deviceRegistration.ClientSecret))
fs.Debugf(nil, "Got clientID %q and clientSecret %s", deviceRegistration.ClientID, fs.RedactValue(fs.GetConfig(ctx), deviceRegistration.ClientSecret))
fs.Debugf(nil, "Got clientID %q and clientSecret %q", deviceRegistration.ClientID, 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(configPassword, conf.Result)
m.Set(configAuthCode, "")
m.Set("password", conf.Result)
m.Set("auth_code", "")
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(configAuthCode, authCode)
m.Set("auth_code", authCode)
return fs.ConfigGoto("legacy_do_auth")
case "legacy_do_auth":
username, _ := m.Get(configUsername)
password, _ := m.Get(configPassword)
password, _ := m.Get("password")
password = obscure.MustReveal(password)
authCode, _ := m.Get(configAuthCode)
authCode, _ := m.Get("auth_code")
srv := rest.NewClient(fshttp.NewClient(ctx))
clientID, _ := m.Get(configClientID)
@@ -364,8 +327,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(configPassword, "")
m.Set(configAuthCode, "")
m.Set("password", "")
m.Set("auth_code", "")
if err != nil {
return nil, fmt.Errorf("failed to get oauth token: %w", err)
}
@@ -953,8 +916,7 @@ 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, _ := m.Get(configVersionKey)
ok := version != ""
version, ok := m.Get("configVersion")
if ok {
ver, err = strconv.Atoi(version)
if err != nil {
@@ -974,7 +936,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, _ := m.Get(configTokenURL); tokenURL != "" {
if tokenURL, ok := m.Get(configTokenURL); ok {
oauthConfig.TokenURL = tokenURL
// jottacloud is weird. we need to use the tokenURL as authURL
oauthConfig.AuthURL = tokenURL
@@ -1708,12 +1670,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(webAppURL, result.PublicSharePath)
webLink := joinPath(wwwURL, result.PublicSharePath)
fs.Debugf(nil, "Web link: %s", webLink)
} else {
fs.Debugf(nil, "No web link received")
}
directLink := joinPath(contentURL, fmt.Sprintf("opin/io/downloadPublic/%s/%s", f.user, result.PublicURI))
directLink := joinPath(wwwURL, fmt.Sprintf("opin/io/downloadPublic/%s/%s", f.user, result.PublicURI))
fs.Debugf(nil, "Direct link: %s", directLink)
return directLink, nil
}
+3 -4
View File
@@ -73,10 +73,9 @@ func init() {
IsPassword: true,
Required: true,
}, {
Name: "web_token",
Help: "Web API login token - set automatically.",
Hide: fs.OptionHideBoth,
Sensitive: true,
Name: "web_token",
Help: "Web API login token - set automatically.",
Hide: fs.OptionHideBoth,
}},
}
fs.Register(fsi)
+1 -1
View File
@@ -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 an object.
Long: `This command can be used to rename a object.
Usage example:
-3
View File
@@ -314,7 +314,6 @@ 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
@@ -325,7 +324,6 @@ 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
@@ -337,7 +335,6 @@ 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.
+9 -14
View File
@@ -21,6 +21,7 @@ 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"
)
@@ -540,6 +541,7 @@ type CaptchaTokenSource struct {
m configmap.Mapper
opt *Options
token *api.CaptchaToken
ctx context.Context
rst *pikpakClient
}
@@ -558,6 +560,7 @@ func newCaptchaTokenSource(ctx context.Context, opt *Options, m configmap.Mapper
m: m,
opt: opt,
token: token,
ctx: ctx,
rst: newPikpakClient(getClient(ctx, opt), opt),
}
}
@@ -578,7 +581,7 @@ func (cts *CaptchaTokenSource) requestToken(ctx context.Context, req *api.Captch
return
}
func (cts *CaptchaTokenSource) refreshToken(ctx context.Context, opts *rest.Opts) (string, error) {
func (cts *CaptchaTokenSource) refreshToken(opts *rest.Opts) (string, error) {
oldToken := ""
if cts.token != nil {
oldToken = cts.token.CaptchaToken
@@ -590,7 +593,7 @@ func (cts *CaptchaTokenSource) refreshToken(ctx context.Context, opts *rest.Opts
action = fmt.Sprintf("%s:%s", opts.Method, u.Path)
}
req := newCaptchaTokenRequest(action, oldToken, cts.opt)
if err := cts.requestToken(ctx, req); err != nil {
if err := cts.requestToken(cts.ctx, req); err != nil {
return "", fmt.Errorf("failed to retrieve captcha token from api: %w", err)
}
@@ -611,18 +614,13 @@ func (cts *CaptchaTokenSource) Invalidate() {
}
// Token returns a valid captcha token
//
// 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) {
func (cts *CaptchaTokenSource) Token(opts *rest.Opts) (string, error) {
cts.mu.Lock()
defer cts.mu.Unlock()
if cts.token.Valid() {
return cts.token.CaptchaToken, nil
}
return cts.refreshToken(ctx, opts)
return cts.refreshToken(opts)
}
// pikpakClient wraps rest.Client with a handle of captcha token
@@ -669,12 +667,9 @@ 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(ctx, opts)
token, err := c.captcha.Token(opts)
if err != nil || token == "" {
// 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)
return nil, fserrors.FatalError(fmt.Errorf("couldn't get captcha token: %v", err))
}
if opts.ExtraHeaders == nil {
opts.ExtraHeaders = make(map[string]string)
-10
View File
@@ -193,16 +193,6 @@ 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,
-49
View File
@@ -6,15 +6,11 @@ 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"
)
@@ -187,48 +183,3 @@ 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")
}
+1 -1
View File
@@ -317,7 +317,7 @@ func TestBudgetMkdir(t *testing.T) {
// 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.
// and then at most one poll per events_min_interval, 1s here (spec 9).
func TestBudgetEvents(t *testing.T) {
ctx := context.Background()
remote, srv, u := setupFakeRemote(t)
-8
View File
@@ -1,8 +0,0 @@
name: Hippius
description: Hippius S3
region:
decentralized: Hippius decentralized storage network
endpoint:
s3.hippius.com: Hippius S3 endpoint
quirks:
force_path_style: true
File renamed without changes.
+19 -5
View File
@@ -498,7 +498,7 @@ It reads the following items from the response for a single part PUT:
For multipart uploads these items aren't read.
If a source object of unknown length is uploaded then rclone **will** do a
If an source object of unknown length is uploaded then rclone **will** do a
HEAD request.
Setting this flag increases the chance for undetected upload failures,
@@ -841,9 +841,8 @@ use |-vv| to see the debug level logs.
Default: sdkLogMode(0),
Advanced: true,
}, {
Name: "ibm_api_key",
Help: "IBM API Key to be used to obtain IAM token",
Sensitive: true,
Name: "ibm_api_key",
Help: "IBM API Key to be used to obtain IAM token",
}, {
Name: "ibm_resource_instance_id",
Help: "IBM service instance id",
@@ -4722,8 +4721,23 @@ func (w *s3ChunkWriter) WriteChunk(ctx context.Context, chunkNumber int, reader
// create checksum of buffer for integrity checking
// currently there is no way to calculate the md5 without reading the chunk a 2nd time (1st read is in uploadMultipart)
// possible in AWS SDK v2 with trailers?
//
// io.Copy reads with a 32 KiB buffer from a reader that implements
// neither WriterTo nor a memory backed Read - which is what a local
// file opened by a multi-thread copy is - so give it a bigger one to
// keep the source reads a useful size. It isn't taken from the pool,
// where it could wait for ever on --max-buffer-memory. A reader with
// WriterTo, such as a pool.RW, doesn't need one.
m := md5.New()
currentChunkSize, err := io.Copy(m, reader)
var (
currentChunkSize int64
err error
)
if _, ok := reader.(io.WriterTo); ok {
currentChunkSize, err = io.Copy(m, reader)
} else {
currentChunkSize, err = io.CopyBuffer(m, reader, make([]byte, multipart.BufferSize))
}
if err != nil {
return -1, err
}
-6
View File
@@ -983,9 +983,3 @@ func TestSetQuirksNoCheckBucket(t *testing.T) {
setQuirks(opt, loadProvider("AWS"))
assert.False(t, opt.NoCheckBucket)
}
func TestLoadProviderByListedName(t *testing.T) {
for name := range loadProviders() {
assert.NotNil(t, loadProvider(name), name)
}
}
+1 -5
View File
@@ -96,16 +96,12 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
// The upload can't be retried here as the input stream can't be re-read and
// the upload link is single use, so upload returns a retry
// error for the caller to retry with a fresh stream.
uploaded, err := o.fs.upload(ctx, in, uploadLink, o.pathInLibrary, src.ModTime(ctx))
uploaded, err := o.fs.upload(ctx, in, uploadLink, o.pathInLibrary)
if err != nil {
return err
}
// Set the properties from the upload back to the object
o.size = uploaded.Size
if o.fs.uploadModTime {
// The server keeps whole seconds only
o.modTime = src.ModTime(ctx).Truncate(time.Second)
}
return nil
}
+1 -1
View File
@@ -12,7 +12,7 @@ import (
)
const (
minSleep = 10 * time.Millisecond
minSleep = 100 * time.Millisecond
maxSleep = 10 * time.Second
decayConstant = 2 // bigger for slower decay, exponential
)
-27
View File
@@ -1,27 +0,0 @@
package seafile
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// The pacer is shared by every request to a server, so its minimum sleep
// caps the request rate. Uploading a small file takes two requests, so a
// large minSleep makes many small files slow whatever --transfers is.
func TestPacerDoesNotThrottleSmallFiles(t *testing.T) {
ctx := context.Background()
p := getPacer(ctx, "https://pacer-test.invalid")
const calls = 50
start := time.Now()
for i := 0; i < calls; i++ {
err := p.Call(func() (bool, error) { return false, nil })
require.NoError(t, err)
}
// 50 calls at minSleep=100ms take about 5s, at 10ms about 0.5s
assert.Less(t, time.Since(start), 2*time.Second)
}
+1 -17
View File
@@ -150,18 +150,9 @@ type Fs struct {
createDirMutex sync.Mutex // Protect creation of directories
useOldDirectoryAPI bool // Use the old API v2 if seafile < 7
moveDirNotAvailable bool // Version < 7.0 don't have an API to move a directory
uploadModTime bool // Version >= 12.0.4 accepts last_modify when uploading a file
renew *Renew // Renew an encrypted library token
}
// minUploadModTimeVersion is the first server version which reads the
// last_modify field of the upload form
var minUploadModTimeVersion = *semver.New("12.0.4")
func canUploadModTime(serverVersion *semver.Version) bool {
return !serverVersion.LessThan(minUploadModTimeVersion)
}
// ------------------------------------------------------------
// NewFs constructs an Fs from the path, container:path
@@ -241,7 +232,6 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
// It also does no support moving directories
f.moveDirNotAvailable = true
}
f.uploadModTime = canUploadModTime(serverVersion)
// Take the authentication token from the configuration first
token := f.opt.AuthToken
@@ -286,9 +276,6 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
}
// And remove the public link feature
f.features.PublicLink = nil
// Encrypted libraries ignore Range so every chunk
// would download the file from the start
f.features.NoMultiThreading = true
// renew the library password every 45 minutes
f.renew = NewRenew(45*time.Minute, func() error {
@@ -519,10 +506,7 @@ func (f *Fs) String() string {
// Precision of the ModTimes in this Fs
func (f *Fs) Precision() time.Duration {
// The modification time can only be set when uploading, and only from v12.0.4
if f.uploadModTime {
return time.Second
}
// The API doesn't support setting the modified time
return fs.ModTimeNotSupported
}
+1 -1
View File
@@ -277,7 +277,7 @@ func TestUploadErrorReleasesSource(t *testing.T) {
in, err := asyncreader.New(ctx, io.NopCloser(readers.NewPatternReader(64<<20)), 4)
require.NoError(t, err)
_, err = f.upload(ctx, in, server.URL+"/upload", "/file.bin", time.Time{})
_, err = f.upload(ctx, in, server.URL+"/upload", "/file.bin")
require.Error(t, err)
closed := make(chan struct{})
+1 -5
View File
@@ -10,7 +10,6 @@ import (
"net/url"
"path"
"strings"
"time"
"github.com/rclone/rclone/backend/seafile/api"
"github.com/rclone/rclone/fs"
@@ -680,7 +679,7 @@ func (f *Fs) getUploadLink(ctx context.Context, libraryID string) (string, error
return result, nil
}
func (f *Fs) upload(ctx context.Context, in io.Reader, uploadLink, filePath string, modTime time.Time) (*api.FileDetail, error) {
func (f *Fs) upload(ctx context.Context, in io.Reader, uploadLink, filePath string) (*api.FileDetail, error) {
// API Documentation
// https://download.seafile.com/published/web-api/v2.1/file-upload.md
fileDir, filename := path.Split(filePath)
@@ -690,9 +689,6 @@ func (f *Fs) upload(ctx context.Context, in io.Reader, uploadLink, filePath stri
"need_idx_progress": {"true"},
"replace": {"1"},
}
if f.uploadModTime && !modTime.IsZero() {
parameters.Set("last_modify", modTime.UTC().Format(time.RFC3339))
}
formReader, contentType, _, err := rest.MultipartUpload(ctx, in, parameters, "file", f.opt.Enc.FromStandardName(filename), "application/octet-stream")
if err != nil {
return nil, fmt.Errorf("failed to make multipart upload: %w", err)
-89
View File
@@ -1,89 +0,0 @@
package seafile
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/coreos/go-semver/semver"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/lib/encoder"
"github.com/rclone/rclone/lib/rest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestCanUploadModTime(t *testing.T) {
for version, want := range map[string]bool{
"7.1.5": false,
"11.0.13": false,
"12.0.3": false,
"12.0.4": true,
"12.0.14": true,
"13.0.28": true,
} {
assert.Equal(t, want, canUploadModTime(semver.New(version)), version)
}
}
func TestPrecision(t *testing.T) {
assert.Equal(t, time.Second, (&Fs{uploadModTime: true}).Precision())
assert.Equal(t, fs.ModTimeNotSupported, (&Fs{uploadModTime: false}).Precision())
}
func TestUploadSendsModTime(t *testing.T) {
modTime := time.Date(2020, 1, 2, 3, 4, 5, 600, time.FixedZone("CET", 3600))
for _, test := range []struct {
name string
uploadModTime bool
modTime time.Time
want string
}{
{name: "supported", uploadModTime: true, modTime: modTime, want: "2020-01-02T02:04:05Z"},
{name: "unsupported", uploadModTime: false, modTime: modTime},
{name: "zero time", uploadModTime: true},
} {
t.Run(test.name, func(t *testing.T) {
var (
got []string
content string
)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "1", r.URL.Query().Get("ret-json"))
if !assert.NoError(t, r.ParseMultipartForm(1<<20)) {
return
}
got = r.MultipartForm.Value["last_modify"]
file, _, err := r.FormFile("file")
if assert.NoError(t, err) {
data, err := io.ReadAll(file)
assert.NoError(t, err)
content = string(data)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`[{"name":"file.txt","size":5}]`))
}))
defer ts.Close()
ctx := context.Background()
f := &Fs{
opt: Options{Enc: encoder.EncodeSlash},
srv: rest.NewClient(ts.Client()),
pacer: getPacer(ctx, ts.URL),
uploadModTime: test.uploadModTime,
}
_, err := f.upload(ctx, strings.NewReader("hello"), ts.URL+"/upload-api/token", "dir/file.txt", test.modTime)
require.NoError(t, err)
assert.Equal(t, "hello", content)
if test.want == "" {
assert.Empty(t, got)
} else {
assert.Equal(t, []string{test.want}, got)
}
})
}
}
+5 -6
View File
@@ -98,11 +98,10 @@ func init() {
Default: maxUploadParts,
Advanced: true,
}, {
Name: "token",
Help: "JWT Token for performing Shade FS operations. Don't set this value - rclone will set it automatically",
Default: "",
Advanced: true,
Sensitive: true,
Name: "token",
Help: "JWT Token for performing Shade FS operations. Don't set this value - rclone will set it automatically",
Default: "",
Advanced: true,
}, {
Name: "token_expiry",
Help: "JWT Token Expiration time. Don't set this value - rclone will set it automatically",
@@ -353,7 +352,7 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
resp, err := f.srv.Call(ctx, &opts)
if err != nil && resp != nil && resp.StatusCode == http.StatusBadRequest {
fs.Debugf(f, "Bad token from server: %s", fs.RedactValue(fs.GetConfig(ctx), token))
fs.Debugf(f, "Bad token from server: %v", token)
}
return shouldRetry(ctx, resp, err)
-5
View File
@@ -177,11 +177,6 @@ func init() {
Help: "Sugarsync deleted folder id.\n\nLeave blank normally, will be auto configured by rclone.",
Advanced: true,
Sensitive: true,
}, {
Name: "username",
Help: "Username (email address) used during setup - set automatically.",
Sensitive: true,
Hide: fs.OptionHideBoth,
}, {
Name: config.ConfigEncoding,
Help: config.ConfigEncodingHelp,
+5 -35
View File
@@ -1302,7 +1302,7 @@ func (su *segmentedUpload) onFail() {
return
}
ctx := context.Background()
fs.Debugf(f, "Segment operation failed: deleting failed segments")
fs.Debugf(f, "Segment operation failed: bulk deleting failed segments")
if len(su.container) == 0 {
fs.Debugf(f, "Invalid segments container")
return
@@ -1311,9 +1311,9 @@ func (su *segmentedUpload) onFail() {
fs.Debugf(f, "No segments to delete")
return
}
err := f.deleteSegments(ctx, su.container, su.segments)
_, err := f.c.BulkDelete(ctx, su.container, su.segments)
if err != nil {
fs.Errorf(f, "Failed to delete failed segments: %v", err)
fs.Errorf(f, "Failed to bulk delete failed segments: %v", err)
}
}
@@ -1601,43 +1601,13 @@ func (o *Object) removeSegmentsLargeObject(ctx context.Context, container string
if len(segments) == 0 {
return nil
}
err := o.fs.deleteSegments(ctx, container, segments)
_, err := o.fs.c.BulkDelete(ctx, container, segments)
if err != nil {
return fmt.Errorf("failed to delete segments: %w", err)
return fmt.Errorf("failed to delete bulk segments: %w", err)
}
return nil
}
// deleteSegments deletes segments from container with a bulk delete,
// deleting them one by one if the server doesn't support that.
//
// It returns the first error encountered.
func (f *Fs) deleteSegments(ctx context.Context, container string, segments []string) error {
_, err := f.c.BulkDelete(ctx, container, segments)
if err != swift.Forbidden {
return err
}
fs.Debugf(f, "Bulk delete not supported, deleting %d segments one by one", len(segments))
var firstErr error
for _, segment := range segments {
err = f.pacer.Call(func() (bool, error) {
err = f.c.ObjectDelete(ctx, container, segment)
// A bulk delete doesn't fail on missing segments either
if err == swift.ObjectNotFound {
err = nil
}
return shouldRetry(ctx, err)
})
if err != nil {
fs.Debugf(f, "Failed to delete segment %q: %v", segment, err)
if firstErr == nil {
firstErr = err
}
}
}
return firstErr
}
// urlEncode encodes a string so that it is a valid URL
//
// We don't use any of Go's standard methods as we need `/` not
-73
View File
@@ -6,7 +6,6 @@ import (
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
@@ -16,7 +15,6 @@ import (
"github.com/rclone/rclone/fs/config/configmap"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/fs/fshttp"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/rest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -276,74 +274,3 @@ func TestAuthRedirectRefusesToResendPassword(t *testing.T) {
})
}
}
func TestInternalDeleteSegmentsWithoutBulkDelete(t *testing.T) {
ctx := context.Background()
var (
mu sync.Mutex
bulkDeletes int
deleted []string
)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/v1.0":
w.Header().Set("X-Storage-Url", "http://"+r.Host+"/v1/AUTH_test")
w.Header().Set("X-Auth-Token", "token")
case r.URL.Query().Get("bulk-delete") == "1":
mu.Lock()
bulkDeletes++
mu.Unlock()
// Swift returns this when the bulk middleware isn't in the pipeline
w.WriteHeader(http.StatusForbidden)
case r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/missing"):
w.WriteHeader(http.StatusNotFound)
case r.Method == http.MethodDelete:
mu.Lock()
deleted = append(deleted, r.URL.Path)
mu.Unlock()
w.WriteHeader(http.StatusNoContent)
default:
w.WriteHeader(http.StatusNotFound)
}
}))
defer ts.Close()
f := &Fs{
c: &swift.Connection{
UserName: "test",
ApiKey: "test",
AuthUrl: ts.URL + "/v1.0",
},
pacer: fs.NewPacer(ctx, pacer.NewS3(pacer.MinSleep(minSleep))),
}
segments := []string{"file/00000000", "file/00000001"}
want := []string{
"/v1/AUTH_test/segments/file/00000000",
"/v1/AUTH_test/segments/file/00000001",
}
check := func(t *testing.T) {
mu.Lock()
defer mu.Unlock()
assert.Equal(t, 1, bulkDeletes)
assert.Equal(t, want, deleted)
bulkDeletes, deleted = 0, nil
}
t.Run("RemoveLargeObject", func(t *testing.T) {
o := &Object{fs: f}
require.NoError(t, o.removeSegmentsLargeObject(ctx, "segments", segments))
check(t)
})
t.Run("FailedUpload", func(t *testing.T) {
su := &segmentedUpload{f: f, container: "segments", segments: segments}
su.onFail()
check(t)
})
t.Run("MissingSegment", func(t *testing.T) {
o := &Object{fs: f}
require.NoError(t, o.removeSegmentsLargeObject(ctx, "segments", append(segments, "file/missing")))
check(t)
})
}
+1 -1
View File
@@ -76,7 +76,7 @@ var (
// go run ./fstest/test_all -remotes local,TestCrypt:,TestDrive:,TestOneDrive:,TestOneDriveBusiness:,TestDropbox:,TestCryptDrive:,TestOpenDrive:,TestChunker:,:memory:,TestCryptNoEncryption:,TestCombine:DirA,TestFTPRclone:,TestWebdavRclone:,TestS3Rclone:,TestSFTPRclone:,TestSFTPRcloneSSH:,TestNextcloud:,TestChunkerNometaLocal:,TestChunkerChunk3bLocal:,TestChunkerLocal:,TestChunkerChunk3bNometaLocal:,TestStorj: -run '^TestBisync.*$' -timeout 3h -verbose -maxtries 5
// go test -timeout 3h -run '^TestBisync.*$' github.com/rclone/rclone/cmd/bisync -remote TestDrive:Bisync -v
// go test -timeout 3h -run '^TestBisyncRemoteRemote/basic$' github.com/rclone/rclone/cmd/bisync -remote TestDropbox:Bisync -v
// TestFTPProftpd:,TestFTPPureftpd:,TestFTPRclone:,TestFTPVsftpd:,TestHdfs:,TestS3Minio:,TestS3Rclone:,TestSeafile:,TestSeafileEncrypted:,TestSFTPOpenssh:,TestSFTPRclone:,TestSFTPRcloneSSH:,TestSia:,TestSwiftAIO:,TestWebdavNextcloud:,TestWebdavOwncloud:,TestWebdavRclone:
// TestFTPProftpd:,TestFTPPureftpd:,TestFTPRclone:,TestFTPVsftpd:,TestHdfs:,TestS3Minio:,TestS3Rclone:,TestSeafile:,TestSeafileEncrypted:,TestSeafileV6:,TestSFTPOpenssh:,TestSFTPRclone:,TestSFTPRcloneSSH:,TestSia:,TestSwiftAIO:,TestWebdavNextcloud:,TestWebdavOwncloud:,TestWebdavRclone:
// logReplacements make modern test logs comparable with golden dir.
// It is a string slice of even length with this structure:
-4
View File
@@ -2,7 +2,6 @@ package bisync
import (
"encoding/json"
"errors"
"fmt"
"io"
"os"
@@ -109,9 +108,6 @@ func (b *bisyncRun) lockFileIsExpired() bool {
}
}
b.handleErr(b.lockFile, "error closing file", rdf.Close(), true, true)
if decodeErr == nil && b.lockFileOpt.data.TimeExpires.IsZero() {
decodeErr = errors.New("lock file is empty or has no expiry time")
}
if decodeErr != nil {
if b.opt.MaxLock < basicallyforever {
fs.Infof(b.lockFile, Color(terminal.YellowFg, "Lock file is unreadable (decode error: %v) and --max-lock is set. Treating as expired."), decodeErr)
-10
View File
@@ -41,16 +41,6 @@ func TestLockfileIsExpired_UnreadableWithoutMaxLock(t *testing.T) {
assert.False(t, b.lockFileIsExpired(), "unreadable lockfile without --max-lock should not be treated as expired")
}
func TestLockfileIsExpired_EmptyWithMaxLock(t *testing.T) {
b := newTestLockfileBisyncRun(t, "", fs.Duration(5*time.Minute))
assert.True(t, b.lockFileIsExpired(), "empty lockfile with --max-lock set should be treated as expired")
}
func TestLockfileIsExpired_EmptyWithoutMaxLock(t *testing.T) {
b := newTestLockfileBisyncRun(t, "", basicallyforever)
assert.False(t, b.lockFileIsExpired(), "empty lockfile without --max-lock should not be treated as expired")
}
func TestLockfileIsExpired_ValidExpired(t *testing.T) {
data := struct {
Session string
+1 -1
View File
@@ -105,7 +105,7 @@ sizes and hashes (MD5 or SHA1) and logs a report of files that don't
match. It doesn't alter the source or destination.
For the [crypt](/crypt/) remote there is a dedicated command,
[cryptcheck](/commands/rclone_cryptcheck/), that is able to check
[cryptcheck](/commands/rclone_cryptcheck/), that are able to check
the checksums of the encrypted files.
If you supply the |--size-only| flag, it will only compare the sizes not
-4
View File
@@ -37,10 +37,6 @@ If you supply the |--download| flag, it will download the data from the remote
and calculate the content hash on the fly. This can be useful for remotes
that don't support hashes or if you really want to check all the data.
The SUM file can be in the format of the standard md5sum/sha1sum tools.
Lines starting with |#| or |;| are ignored. The file may be UTF-8, or
UTF-16 with a byte order mark.
Note that hash values in the SUM file are treated as case insensitive.
`, "|", "`") + check.FlagsHelp,
Annotations: map[string]string{
-3
View File
@@ -361,9 +361,6 @@ require this add an extra parameter thus:
rclone config update myremote env_auth=true config_refresh_token=false
|||
This is done for you when you pass a |token|, so the token you pass is
the one that gets stored.
`, "|", "`") + configPasswordHelp,
Annotations: map[string]string{
"versionIntroduced": "v1.39",
+3 -18
View File
@@ -18,7 +18,6 @@ import (
"github.com/go-chi/chi/v5/middleware"
"github.com/rclone/rclone/cmd"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config/flags"
"github.com/rclone/rclone/fs/rc"
"github.com/rclone/rclone/fs/rc/rcserver"
libhttp "github.com/rclone/rclone/lib/http"
@@ -42,7 +41,6 @@ var (
noAuth bool
noOpenBrowser bool
enableMetrics bool
noCheckUsage bool
)
func init() {
@@ -55,7 +53,6 @@ func init() {
f.BoolVar(&noAuth, "no-auth", false, "Don't require auth for the RC API")
f.BoolVar(&noOpenBrowser, "no-open-browser", false, "Skip opening the browser automatically")
f.BoolVar(&enableMetrics, "enable-metrics", false, "Enable OpenMetrics/Prometheus compatible endpoint at /metrics")
flags.BoolVarP(f, &noCheckUsage, "no-check-usage", "", false, "Turn off the GUI's automatic remote usage checks", "")
}
var commandDefinition = &cobra.Command{
@@ -98,12 +95,6 @@ Use --no-auth to disable authentication entirely:
rclone gui --no-auth
Use --no-check-usage to turn off the GUI's automatic remote usage
checks, which connect to every remote that supports them. This needs
GUI version 1.2.1 or later and has no effect with --no-auth:
rclone gui --no-check-usage
For more help see [the GUI docs](/gui/).
`,
Annotations: map[string]string{
@@ -183,9 +174,6 @@ For more help see [the GUI docs](/gui/).
fs.Infof(nil, "No password specified. Using random password: %s", randomPass)
}
}
if noCheckUsage && opt.NoAuth {
fs.Logf(nil, "--no-check-usage has no effect without auth")
}
addr, _ := guiServer.Addr().(*net.TCPAddr)
opt.HTTP.AllowOrigin = resolveAllowOrigin(command.Flags().Changed("rc-allow-origin"), opt.HTTP.AllowOrigin, guiOrigin, addr, opt.NoAuth)
@@ -218,7 +206,7 @@ For more help see [the GUI docs](/gui/).
fs.Logf(nil, "Serving GUI %s on %s", guiSource, guiURL)
// Open browser
loginURL := buildLoginURL(guiURL, rcURL, opt.Auth.BasicUser, opt.Auth.BasicPass, opt.NoAuth, noCheckUsage)
loginURL := buildLoginURL(guiURL, rcURL, opt.Auth.BasicUser, opt.Auth.BasicPass, opt.NoAuth)
fs.Logf(nil, "GUI available at %s", loginURL)
if !noOpenBrowser {
@@ -335,8 +323,8 @@ func guiHandler(srcFS iofs.FS) (http.Handler, error) {
// guiBaseURL is the GUI server's URL. rcURL is the RC API server's URL.
// When auth is enabled it appends url, user, and pass as query
// parameters so the React app can discover the API endpoint and
// log in automatically, plus checkUsage=false if noCheckUsage is set.
func buildLoginURL(guiBaseURL, rcURL, user, pass string, noAuth, noCheckUsage bool) string {
// log in automatically.
func buildLoginURL(guiBaseURL, rcURL, user, pass string, noAuth bool) string {
u, err := url.Parse(guiBaseURL)
if err != nil {
return guiBaseURL
@@ -349,9 +337,6 @@ func buildLoginURL(guiBaseURL, rcURL, user, pass string, noAuth, noCheckUsage bo
q.Set("url", rcURL)
q.Set("user", user)
q.Set("pass", pass)
if noCheckUsage {
q.Set("checkUsage", "false")
}
u.RawQuery = q.Encode()
return u.String()
}
+8 -28
View File
@@ -26,14 +26,13 @@ const (
func TestBuildLoginURL(t *testing.T) {
tests := []struct {
name string
guiURL string
rcURL string
user string
pass string
noAuth bool
noCheckUsage bool
want string
name string
guiURL string
rcURL string
user string
pass string
noAuth bool
want string
}{
{
name: "with credentials",
@@ -62,29 +61,10 @@ func TestBuildLoginURL(t *testing.T) {
noAuth: true,
want: "http://localhost:5580/",
},
{
name: "no check usage",
guiURL: "http://localhost:5580/",
rcURL: "http://localhost:5572/",
user: "gui",
pass: "secret",
noCheckUsage: true,
want: "http://localhost:5580/login?checkUsage=false&pass=secret&url=http%3A%2F%2Flocalhost%3A5572%2F&user=gui",
},
{
name: "no check usage with no auth",
guiURL: "http://localhost:5580/",
rcURL: "http://localhost:5572/",
user: "gui",
pass: "secret",
noAuth: true,
noCheckUsage: true,
want: "http://localhost:5580/",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := buildLoginURL(tt.guiURL, tt.rcURL, tt.user, tt.pass, tt.noAuth, tt.noCheckUsage)
got := buildLoginURL(tt.guiURL, tt.rcURL, tt.user, tt.pass, tt.noAuth)
assert.Equal(t, tt.want, got)
})
}
+1 -1
View File
@@ -52,7 +52,7 @@ var commandDefinition = &cobra.Command{
Use: "rc commands parameter",
Short: `Run a command against a running rclone.`,
Long: strings.ReplaceAll(`This runs a command against a running rclone. Use the |--url| flag to
specify a non-default URL to connect on. This can be either a
specify an non default URL to connect on. This can be either a
":port" which is taken to mean <http://localhost:port> or a
"host:port" which is taken to mean <http://host:port>.
+3 -4
View File
@@ -55,10 +55,9 @@ var OptionsInfo = fs.Options{{
Default: "anonymous",
Help: "User name for authentication",
}, {
Name: "pass",
Default: "",
Help: "Password for authentication (empty value allow every password)",
Sensitive: true,
Name: "pass",
Default: "",
Help: "Password for authentication (empty value allow every password)",
}, {
Name: "cert",
Default: "",
+12 -33
View File
@@ -227,10 +227,7 @@ func (b *s3Backend) SetObjectTagging(ctx context.Context, bucketName, objectName
return err
}
node, err := _vfs.Stat(fp)
if err != nil {
return notFound(err, gofakes3.KeyNotFound(objectName))
}
if !node.IsFile() {
if err != nil || !node.IsFile() {
return gofakes3.KeyNotFound(objectName)
}
t := b.tenant(ctx)
@@ -316,7 +313,7 @@ func (b *s3Backend) ListBucket(ctx context.Context, bucket string, prefix *gofak
}
_, err = _vfs.Stat(bucket)
if err != nil {
return nil, notFound(err, gofakes3.BucketNotFound(bucket))
return nil, gofakes3.BucketNotFound(bucket)
}
if prefix == nil {
prefix = emptyPrefix
@@ -346,16 +343,6 @@ func formatHeaderTime(t time.Time) string {
return t.UTC().Format("Mon, 02 Jan 2006 15:04:05") + " GMT"
}
// notFound returns notFoundErr if err means the path doesn't exist and
// err otherwise, so that a failure reading the remote is reported to
// the client as an error and not as a missing bucket or key.
func notFound(err error, notFoundErr error) error {
if errors.Is(err, vfs.ENOENT) {
return notFoundErr
}
return err
}
// HeadObject returns the fileinfo for the given object name.
//
// Note that the metadata is not supported yet.
@@ -366,7 +353,7 @@ func (b *s3Backend) HeadObject(ctx context.Context, bucketName, objectName strin
}
_, err = _vfs.Stat(bucketName)
if err != nil {
return nil, notFound(err, gofakes3.BucketNotFound(bucketName))
return nil, gofakes3.BucketNotFound(bucketName)
}
if fp, isMarker, err := bucketDirMarkerPath(bucketName, objectName); isMarker {
@@ -381,7 +368,7 @@ func (b *s3Backend) HeadObject(ctx context.Context, bucketName, objectName strin
}
node, err := _vfs.Stat(fp)
if err != nil {
return nil, notFound(err, gofakes3.KeyNotFound(objectName))
return nil, gofakes3.KeyNotFound(objectName)
}
if !node.IsFile() {
@@ -435,7 +422,7 @@ func (b *s3Backend) GetObject(ctx context.Context, bucketName, objectName string
}
_, err = _vfs.Stat(bucketName)
if err != nil {
return nil, notFound(err, gofakes3.BucketNotFound(bucketName))
return nil, gofakes3.BucketNotFound(bucketName)
}
if fp, isMarker, err := bucketDirMarkerPath(bucketName, objectName); isMarker {
@@ -453,7 +440,7 @@ func (b *s3Backend) GetObject(ctx context.Context, bucketName, objectName string
}
node, err := _vfs.Stat(fp)
if err != nil {
return nil, notFound(err, gofakes3.KeyNotFound(objectName))
return nil, gofakes3.KeyNotFound(objectName)
}
if !node.IsFile() {
@@ -527,10 +514,7 @@ func (b *s3Backend) GetObject(ctx context.Context, bucketName, objectName string
// objectName stands for if its directory fp exists.
func (b *s3Backend) dirMarkerObject(_vfs *vfs.VFS, fp, objectName string) (*gofakes3.Object, error) {
node, err := _vfs.Stat(fp)
if err != nil {
return nil, notFound(err, gofakes3.KeyNotFound(objectName))
}
if !node.IsDir() {
if err != nil || !node.IsDir() {
return nil, gofakes3.KeyNotFound(objectName)
}
return &gofakes3.Object{
@@ -606,7 +590,7 @@ func (b *s3Backend) PutObject(
}
_, err = _vfs.Stat(bucketName)
if err != nil {
return result, notFound(err, gofakes3.BucketNotFound(bucketName))
return result, gofakes3.BucketNotFound(bucketName)
}
if fp, isMarker, err := bucketDirMarkerPath(bucketName, objectName); isMarker {
@@ -803,7 +787,7 @@ func (b *s3Backend) deleteObject(ctx context.Context, bucketName, objectName str
}
_, err = _vfs.Stat(bucketName)
if err != nil {
return notFound(err, gofakes3.BucketNotFound(bucketName))
return gofakes3.BucketNotFound(bucketName)
}
t := b.tenant(ctx)
@@ -870,7 +854,7 @@ func (b *s3Backend) DeleteBucket(ctx context.Context, name string) error {
}
_, err = _vfs.Stat(name)
if err != nil {
return notFound(err, gofakes3.BucketNotFound(name))
return gofakes3.BucketNotFound(name)
}
// The bucket may hold empty directories, which S3 clients can't
@@ -893,10 +877,8 @@ func (b *s3Backend) BucketExists(ctx context.Context, name string) (exists bool,
return false, err
}
_, err = _vfs.Stat(name)
if errors.Is(err, vfs.ENOENT) {
if err != nil {
return false, nil
} else if err != nil {
return false, err
}
return true, nil
@@ -916,10 +898,7 @@ func (b *s3Backend) CopyObject(ctx context.Context, srcBucket, srcKey, dstBucket
return result, err
}
cStat, err := _vfs.Stat(fp)
if err != nil {
return result, notFound(err, gofakes3.KeyNotFound(srcKey))
}
if cStat.IsDir() != isMarker {
if err != nil || cStat.IsDir() != isMarker {
return result, gofakes3.KeyNotFound(srcKey)
}
if srcBucket == dstBucket && srcKey == dstKey {
-86
View File
@@ -4,7 +4,6 @@ import (
"context"
"crypto/md5"
"encoding/hex"
"errors"
"io"
"os"
"path/filepath"
@@ -479,88 +478,3 @@ func TestFileDirConflicts(t *testing.T) {
assert.True(t, gofakes3.HasErrorCode(err, gofakes3.ErrInvalidRequest), "%s: %v", test.key, err)
}
}
// listErrorFs fails listings of failDir once err is set.
type listErrorFs struct {
fs.Fs
failDir string
err error
}
// List the objects and directories in dir
func (f *listErrorFs) List(ctx context.Context, dir string) (fs.DirEntries, error) {
if f.err != nil && dir == f.failDir {
return nil, f.err
}
return f.Fs.List(ctx, dir)
}
// newListErrorBackend is newTestBackend with listings of failDir failing.
func newListErrorBackend(t *testing.T, failDir string) *s3Backend {
ctx := context.Background()
// don't use newTestBackend, as the VFS for the same root would be reused
root := t.TempDir()
require.NoError(t, os.MkdirAll(filepath.Join(root, "bucket"), 0777))
require.NoError(t, os.WriteFile(filepath.Join(root, "bucket", "object.txt"), []byte("normal object"), 0666))
f, err := fs.NewFs(ctx, root)
require.NoError(t, err)
opt := Opt
opt.HTTP.ListenAddr = []string{endpoint}
w, err := newServer(ctx, &listErrorFs{Fs: f, failDir: failDir, err: errors.New("listing failed")}, &opt, &vfscommon.Opt, &proxy.Opt)
require.NoError(t, err)
return newBackend(w)
}
func isNotFound(err error) bool {
return gofakes3.HasErrorCode(err, gofakes3.ErrNoSuchKey) || gofakes3.HasErrorCode(err, gofakes3.ErrNoSuchBucket)
}
// TestStatErrors checks that a failure to read the remote is returned
// as an error and not reported as a missing bucket or key, which
// clients treat as final and don't retry.
func TestStatErrors(t *testing.T) {
ctx := context.Background()
t.Run("NotFound", func(t *testing.T) {
b, _ := newTestBackend(t)
_, err := b.HeadObject(ctx, "bucket", "missing.txt")
assert.True(t, isNotFound(err), "missing key: %v", err)
_, err = b.HeadObject(ctx, "missing", "object.txt")
assert.True(t, isNotFound(err), "missing bucket: %v", err)
exists, err := b.BucketExists(ctx, "missing")
require.NoError(t, err)
assert.False(t, exists)
})
t.Run("Object", func(t *testing.T) {
b := newListErrorBackend(t, "bucket")
_, err := b.HeadObject(ctx, "bucket", "object.txt")
assert.ErrorContains(t, err, "listing failed", "HeadObject")
_, err = b.GetObject(ctx, "bucket", "object.txt", nil)
assert.ErrorContains(t, err, "listing failed", "GetObject")
_, err = b.CopyObject(ctx, "bucket", "object.txt", "bucket", "copy.txt", map[string]string{})
assert.ErrorContains(t, err, "listing failed", "CopyObject")
err = b.SetObjectTagging(ctx, "bucket", "object.txt", "a=1")
assert.ErrorContains(t, err, "listing failed", "SetObjectTagging")
_, err = b.HeadObject(ctx, "bucket", "dir/")
assert.ErrorContains(t, err, "listing failed", "HeadObject dir marker")
_, err = b.GetObject(ctx, "bucket", "dir/", nil)
assert.ErrorContains(t, err, "listing failed", "GetObject dir marker")
})
t.Run("Bucket", func(t *testing.T) {
b := newListErrorBackend(t, "")
_, err := b.BucketExists(ctx, "bucket")
assert.ErrorContains(t, err, "listing failed", "BucketExists")
_, err = b.ListBucket(ctx, "bucket", nil, gofakes3.ListBucketPage{})
assert.ErrorContains(t, err, "listing failed", "ListBucket")
_, err = b.HeadObject(ctx, "bucket", "object.txt")
assert.ErrorContains(t, err, "listing failed", "HeadObject")
_, err = b.PutObject(ctx, "bucket", "new.txt", map[string]string{}, strings.NewReader("x"), 1)
assert.ErrorContains(t, err, "listing failed", "PutObject")
_, err = b.CreateMultipartUpload(ctx, "bucket", "new.txt", map[string]string{})
assert.ErrorContains(t, err, "listing failed", "CreateMultipartUpload")
err = b.DeleteBucket(ctx, "bucket")
assert.ErrorContains(t, err, "listing failed", "DeleteBucket")
})
}
+1 -1
View File
@@ -274,7 +274,7 @@ func (b *s3Backend) CreateMultipartUpload(ctx context.Context, bucketName, objec
return "", err
}
if _, err := _vfs.Stat(bucketName); err != nil {
return "", notFound(err, gofakes3.BucketNotFound(bucketName))
return "", gofakes3.BucketNotFound(bucketName)
}
if b.s.opt.DisableMultipartStreaming && _vfs.Opt.CacheMode < vfscommon.CacheModeMinimal {
+3 -4
View File
@@ -30,10 +30,9 @@ var OptionsInfo = fs.Options{{
Default: "MD5",
Help: "Which hash to use for the ETag, or auto or blank for off",
}, {
Name: "auth_key",
Default: []string{},
Help: "Set key pair for v4 authorization: access_key_id,secret_access_key",
Sensitive: true,
Name: "auth_key",
Default: []string{},
Help: "Set key pair for v4 authorization: access_key_id,secret_access_key",
}, {
Name: "no_cleanup",
Default: false,
+3 -4
View File
@@ -41,10 +41,9 @@ var OptionsInfo = fs.Options{{
Default: "",
Help: "User name for authentication",
}, {
Name: "pass",
Default: "",
Help: "Password for authentication",
Sensitive: true,
Name: "pass",
Default: "",
Help: "Password for authentication",
}, {
Name: "no_auth",
Default: false,
+93
View File
@@ -0,0 +1,93 @@
# Architecture
Fork-only orientation for agents. The summary in `AGENTS.md` ("Architecture")
is upstream's and is not repeated here; this page adds what that summary
leaves out. Update in the same commit as any structural change.
## Map
| Path | Responsibility |
|---|---|
| `rclone.go` | Entry point; blank-imports `backend/all` and `cmd/all` |
| `backend/<name>/` | One storage backend per package, registered in `init()` |
| `cmd/<name>/` | One cobra command per package |
| `fs/` | Core interfaces, config, operations, sync, accounting |
| `vfs/` | Virtual filesystem used by mount and serve |
| `lib/` | Shared helpers: `rest`, `pacer`, `dircache`, `oauthutil`, `encoder` |
| `fstest/` | Test framework: `fstests` (backend contract), `test_all` (runner) |
| `docs/content/` | Hugo website source; partly autogenerated |
| `docs/specs/`, `docs/plans/` | Fork-only agent workflow artefacts |
| `bin/` | Build and docs scripts |
## Test layers
- Unit tests: `RCLONE_CONFIG=/notfound go test ./...` - no credentials.
- Backend contract: each `backend/<name>/<name>_test.go` calls
`fstests.Run()` against a remote named `Test<Name>:` in the user's rclone
config. Without that remote the test skips, so a green `go test` on a
backend package says nothing about the backend against the real service.
- Integration: `fstest/test_all` runs the backend contract plus the
`fs/operations`, `fs/sync`, `vfs` etc. suites against the backends listed in
`fstest/test_all/config.yaml`.
## Invariants
- Backwards compatibility of commands, flags, config keys and the rc API.
- `fs` and `vfs` contain no backend-specific code.
- cgo use differs per release target (the `cgo` and `build_flags` columns of
the matrix in `.github/workflows/build.yml`), so a backend cannot assume cgo.
## `backend/protondrive`
A native client of the Proton Drive API, following Proton's Drive SDK
(spec: `docs/specs/001-protondrive-tier1.md`).
| File | Responsibility |
|---|---|
| `protondrive.go` | `Fs`, `Object`, options, `Config` sign-in, dircache glue, `translateError` |
| `session.go` | SRP and browser (session fork) sign-in, token refresh, app version |
| `account.go` | User and address keys, public-key lookups |
| `crypto.go` | Every OpenPGP operation |
| `nodes.go` | The `client`: volume bootstrap, pacing, listing, folder/rename/move/copy/trash |
| `cache.go` | In-memory node and listing cache |
| `events.go` | Volume events: the poller (a `time.AfterFunc` timer, running only while the cache holds anything or `ChangeNotify` subscribes), cache invalidation from events |
| `upload.go`, `download.go` | Block pipelines; `download.go` also keeps the per-client cache of block sizes learnt for files that don't record them |
| `api/` | Wire types |
| `protontest/` | Fake Proton server, imported by tests only; never imports the backend |
- **The seam:** `protondrive.go` holds no cryptography and no API routes;
the other files never take or return `fs.Fs`/`fs.Object`.
- No package-level mutable state except `unlockMu` (key unlocking is
serialised across `Fs` instances). Each `Fs` has its own client, session
and cache; credentials go through a per-`Fs` `configStore` over the
remote's config.
- `fake_test.go` runs the full `fstests` contract suite against
`protontest` through the hidden `endpoint` option, on every
`go test`; `protondrive_test.go` is the live suite (`TestProtonDrive:`).
- `fstest/testserver/init.d/TestProtonDriveFake` builds and starts
`protontest/cmd/protonfake` for `test_all`, which runs the wider suites
against the `TestProtonDriveFake:` remote. Fork CI is
`.gitea/workflows/ci.yml`.
- User docs: `docs/content/protondrive.md` (hand-written parts; the
options section is generated from the `Help:` fields).
`docs/specs/001-conformance-checklist.md` maps each SDK module to its Go
file and the tag it was last checked against.
- Events: each `Fs` polls its volume's events on its own (no shared
state). `events.go` invalidates the node cache; `protondrive.go`
observes every applied batch to flush changed folders from the
dircache (`forgetChanged`) and turns it into `ChangeNotify` paths
(`changedPaths`). Subscribers and the observer run only on the
poller's goroutine, never inside a user operation.
With no subscriber, a cache unused for 10 minutes is cleared, which
stops polling. `Shutdown` stops the poller (waiting for a poll in
flight) and keeps the cursor; later use restarts it. `Disconnect`
stops it for good.
- Not implemented yet: the persistent metadata cache, rclone Metadata
and the small-file upload path (M6).
Ranged reads check block hashes but not the signed manifest. Open items
and unrun live checks are in `docs/TODO.md`.
## Known rough edges
- See `docs/TODO.md` for host tooling gaps.
+622
View File
@@ -0,0 +1,622 @@
# Decisions
Fork-only. Append-only, newest first. Never edit or delete an entry - supersede
it with a new one that links back. One entry per decision a future maintainer
would otherwise have to reverse-engineer.
No index: `grep -n '^## ' docs/DECISIONS.md` lists every entry.
## 2026-11-23 - Proton Drive stays on its own code, not clayliddell's Go SDK
**Status:** accepted
**Context:** github.com/clayliddell/proton-drive-go-sdk (MIT, about 2.3k
lines, written 2026-03-23..27, inactive since) is a pure-Go Proton Drive
client offered on rclone issue #9252. It builds on go-proton-api and
gopenpgp v2, uses the share-scoped routes Proton will remove, has no events,
no new revisions, no AEAD and no retries; its `go.mod` path doesn't match
its repository, and large uploads drop the extended attributes.
**Decision:** Don't depend on it or copy from it; mention it as prior art.
Two details are noted for later: its small-file upload (`POST
/drive/v2/volumes/{vol}/files/small`, verification token = last 32 bytes of
the content key packet XOR the encrypted block, matching the official JS
SDK) is a reference for M6, with the JS SDK's 128 KiB limit rather than its
4 MiB; and block upload requests omit `Hash` and `Size` as the official JS
SDK does (the C# SDK still sends them) - revisit if Proton starts requiring
them.
**Alternatives:** Using it as the API layer (narrower, deprecated routes,
the old stack rclone is leaving).
**Consequences:** None for the code now.
## 2026-11-12 - Proton Drive's test server reports events as the real one does
**Status:** accepted (supersedes ruling 8 of "Proton Drive follows volume
events for change notification", below; plan 002 Task 6)
**Context:** Ruling 8 described the fake server's events, to be checked
live. The check (free account, `rclone test changenotify` at the 30 s
floor, changes made with rclone and the official CLI 0.9.0) found:
| Action | Events |
|---|---|
| upload (at commit), mkdir, server-side copy | Create (1); a copied folder: one per link |
| new revision | Update (2) |
| rename, move, trash (file or folder) | UpdateMetadata (3) |
| permanent delete, empty trash | Delete (0), one per link removed |
Link fields (`ParentLinkID`, `IsTrashed`) are the link's state when the
events are read: a folder made and removed between polls comes back as
a Create with `IsTrashed` set; a link deleted for good has no parent and
isn't trashed. Pages hold 299 events; a 2783-event poll read 10 pages.
**Decision:** The fake emits these types and reports Link fields at read
time; events added with `InjectEvent` keep their own fields. The backend
needed no change: only Delete is treated specially, so UpdateMetadata is
handled like Update. `pollEvents` logs one DEBUG line per page (IDs and
counts only). Live `FsChangeNotify` is ignored for `TestProtonDrive:`:
fstests waits 27 s, below the 30 s floor.
**Alternatives:** Keeping the fake's per-change snapshots (tests would
pass on states the real server never reports).
**Consequences:** A file trashed and emptied between polls is named at
its cached path only; its Delete names no parent.
## 2026-11-12 - Proton Drive follows volume events for change notification
**Status:** accepted (plan 002 rulings 1-9, as built in M5 Tasks 2-4; ruling 2
amended in the Task 4 review; ruling 9 and the idle cache added in Task 7)
**Context:** The node cache never saw changes made by other clients, so a
long `rclone mount` or `rclone serve` showed stale listings. Proton's
volume events (`GET /drive/volumes/{volumeID}/events/latest` for the
start cursor, `GET /drive/v2/volumes/{volumeID}/events/{eventID}` for
pages) report changed nodes by ID only: no names, no paths, no client.
**Decision:**
1. Own writes come back as events and are applied like any other
(invalidate, re-fetch on next use); there is no attempt to recognise
them.
2. `ChangeNotify` names a cached node at its old path (from the
dircache), and at its new folder if it moved to a known one. A node
that wasn't cached is reported at once as its parent folder, if that
is in the dircache, else not at all, and at its old path if it is a
folder the dircache holds. Its ID is then kept (at most 1000, oldest
dropped) for the next two polls, which look it up in the node cache
even when they bring no events; if it has been cached by then (an own
upload or `Mkdir` caches its node a round trip after the server
commits it, so its event can be applied first) it is reported at its
exact path. No extra requests are made to name nodes; pending IDs are
dropped on refresh, volume gone, `Shutdown` and when the last
subscriber leaves. A folder renamed in place is reported as its old
path plus its parent, since events carry no names. Nothing outside
the `Fs` root is reported.
3. `Refresh` (cursor unknown or expired) clears the node cache, takes the
returned `EventID` as the cursor and notifies `""` as a directory. The
dircache is flushed but keeps the root folder's ID, not `ResetRoot`:
after `ResetRoot` an `Fs` below the volume root would name later
events relative to the volume root until something found its root
again. `DirCacheFlush` keeps the root's ID for the same reason.
4. A Delete, or an Update that moves or trashes a folder, drops the node
and everything cached below it (`invalidateTree`). Every applied batch
flushes each changed folder's old path, and everything below it, from
the dircache, with or without `ChangeNotify`.
5. Proton code 2501 on an events route (volume gone) stops polling for
the life of the `Fs`, clears the cache, logs one ERROR and notifies
subscribers as for a refresh.
6. The hidden option `events_min_interval` (default 30s) sets the floor;
below 30s it is raised to 30s, with a NOTICE, when the endpoint host is
`proton.me` or ends in `.proton.me` (trailing dot ignored) or can't be
parsed. The interval rclone passes to `ChangeNotify` is used when
longer. Each wait adds up to 1s of jitter; failures back off by
Fibonacci multiples of the interval, capped at 10 minutes.
7. Each `Fs` polls on its own and keeps its own cache; the five cross-`Fs`
cache tests stay ignored.
8. The fake server emits Create at upload commit, Update at a revision
commit, rename, move and trash, Create on copy, and nothing for a
draft's deletion; to be checked against the real server (plan 002
Task 6).
9. `Shutdown` stops the poller; using the `Fs` again restarts it from
the cursor it had, an interval later, so a `Shutdown` and reuse never
make two events requests within an interval. `Shutdown` returns once
a poll in flight has ended (not its notifications), so nothing of it
runs, or logs, afterwards. `Disconnect` stops it for good.
10. With nothing subscribed, a node cache unused (neither read nor
filled; applying events doesn't count) for 10 minutes is cleared,
which stops polling as an empty cache does; the next use refills it
and polls from the kept cursor.
The poller is a `time.AfterFunc` timer, polling only while the node cache
holds anything or a `ChangeNotify` subscribes. Subscribers (and the
dircache observer) are called only from the poller's goroutine, never
from inside a user operation, which may hold dircache or VFS locks the
subscriber takes. The first fill of an empty cache fetches the start
cursor in the caller's path, so no change after the fill is missed;
once that fetch has failed, later ones wait for the backoff instead.
Events requests are paced but not retried by the pacer, so the poller's
own backoff governs failures; a Retry-After isn't waited out in the
request (nor given to the pacer, which would hold every call of the
client) but delays the next poll.
The data race fixed in `fstests` `FsChangeNotify` (commit `27e1a9c54`:
its maps were written from the backend's goroutine and read from the
test's without a lock) is a generic test fix, not Proton-specific.
**Alternatives:** Recognising own writes (v2 events name no client);
a fetch per unknown node to name it (extra requests per poll; under
review); a cache shared across the `Fs` of one account (package state,
which the spec rules out); `ResetRoot` on refresh (wrong paths below the
volume root).
**Consequences:** A mount sees other clients' changes within about one
poll interval. A moved node is reported under its old name in its new
folder, and an own upload's event applied before the node is cached is
reported only as its folder. An `Fs` that is never shut down and holds
anything in its cache polls until the cache has gone unused for 10
minutes. If the root folder
is deleted and recreated by another client while the cursor is expired,
the `Fs` keeps the old root ID.
## 2026-11-12 - Proton Drive maps only the app-version codes to "upgrade rclone"
**Status:** accepted (handoff ruling 30). Supersedes spec 6.6's
"2000/2028 ... to a fatal error telling the user to upgrade rclone".
**Context:** 2000 is Proton's generic "requirements not met" code, which
the server returns for a stale `OriginalHash` or `CurrentRevisionID`, as
after a rename whose response was lost and which was resent. Mapping it to
a fatal "upgrade rclone" error aborted whole runs over a rename that had
succeeded. 2028 means a feature is disabled, rate-limited or blocked for
abuse (`driveTypes.ts`). The code Proton returns for a rejected app
version is 5003 ("You need to update this app", `coreTypes.ts`), and 5001
for a missing one (go-proton-api), neither of which was mapped.
**Decision:** 5001 and 5003 are a fatal error telling the user to upgrade
rclone. 2000 is a no-retry error keeping Proton's message. 2028 is retried
through the pacer (honouring `Retry-After` when sent), then returned as
it is. 2064 (malformed header) is left unmapped.
**Alternatives:** Keeping the spec's mapping (false fatal errors);
treating 2028 as a no-retry error (fails at once on rate limiting).
**Consequences:** A feature Proton disables outright costs the low-level
retries before its error is returned.
## 2026-11-12 - Proton Drive caps the Argon2 cost of node and share keys
**Status:** accepted
**Context:** go-crypto unlocks an Argon2-locked key with whatever
parameters it carries, up to 2 TiB of memory and 255 passes, and runs the
KDF before it can tell the passphrase is wrong. Node and share keys come
from the server, or from other users' clients in shared folders, so one
crafted key could crash every listing that includes it.
**Decision:** Before unlocking a node or share key, every secret key
packet's S2K is checked: Argon2 may use at most 4 passes, parallelism 8
and 2^17 KiB (128 MiB). gopenpgp and OpenPGP.js write 3, 4 and 64 MiB by
default, and Proton's node keys use an iterated and salted S2K, whose
one-byte count encoding already bounds it to 4 times the default. A key
beyond the limits is an integrity error, making the node unreadable, and
`ignore_signature_errors` doesn't change that.
**Alternatives:** Refusing Argon2 on node keys outright (no genuine node
key is known to use it, but a future client might); capping the iterated
count below the encoding's maximum (could refuse genuine old keys for a
bounded cost).
**Consequences:** At most 128 MiB per unlock while a listing decrypts
nodes. The account's own user keys aren't checked yet (`docs/TODO.md`).
## 2026-11-12 - Proton Drive refuses a file whose content key is unsigned
**Status:** accepted (handoff ruling 29)
**Context:** Anyone holding a file's public node key, which the server
stores, can make a content key packet for it. Proton's SDK checks the
content key packet's signature only when one is present. A server could
then send its own content key without a signature: rclone would encrypt
every update of the file with a key the server knows, and a ranged read
(which can't check the manifest) would return whatever the server
encrypted under it.
**Decision:** A content key whose signature is missing or invalid makes
the file unverified, as an unverified node key does (rulings 18 and 22):
reads, full and ranged, and updates are refused unless
`ignore_signature_errors` is set, when rclone logs an `ERROR` once per file
and operation and goes ahead. The pre-2023 fallback to the account's other
address keys still applies to a signature which is present but fails, as
in the SDK. Integrity checks are never turned off. This is stricter than
the SDK.
**Alternatives:** Following the SDK (leaves the hole); a creation-date
exemption for unsigned keys (the date is server-supplied, so it would
exempt anything the server back-dates).
**Consequences:** A genuine file whose content key was never signed, if
any client ever wrote one, needs `ignore_signature_errors`. Every file in
the golden fixtures, written by Proton's web app, CLI and the old
library, has a signed content key.
## 2026-11-12 - Proton Drive deletes an upload's draft only on an explicit refusal
**Status:** accepted. Supersedes the read-back half of handoff ruling 11
("a draft is deleted only on positive proof it never committed", where a
read showing the draft or the old revision counted as proof).
**Context:** Proton's server can take a moment to show a commit (entry
below). After a failed commit, one stale read showing the draft or the
base revision made the client delete the draft, but the commit may
have landed: `delete_multiple` against what is now an active file, or
`DELETE .../revisions/{id}` against what is now the active revision. What
the real server does with those is unconfirmed, so this could lose data.
**Decision:** The draft is deleted only when the server explicitly
refused the commit, meaning a 4xx `api.Error` (not 408) with a Proton code,
on a single attempt that the pacer did not resend. A resend after
5xx/408/network/timeout makes the outcome unknown even if the final
answer is a refusal, because an earlier attempt may have landed. No
read-back decides deletion, and a refusal is not read back at all. Every
other failure (5xx, network, timeout, cancelled ctx, resent attempts)
returns `errUploadOutcomeUnknown` and deletes nothing. The read after
such a failure can still turn it into a success when it shows the
upload's revision. It retries through lag while the caller's ctx lives,
and reads once, detached, if ctx is done.
**Alternatives:** Requiring every read across the whole lag window to
show the pre-commit state (a heuristic, as the lag length is unmeasured);
the old single-read proof.
**Consequences:** More drafts are left behind after ambiguous failures.
The next upload of the name replaces them, otherwise they stay (see
`docs/TODO.md`). A refused commit fails at once, with no reads.
## 2026-11-12 - Proton Drive uploads tolerate read-after-write lag, but never invent the result
**Status:** accepted
**Context:** Against the real service an upload whose commit succeeded
failed because the node read back just after was missing or still a
draft with an empty active revision (`errUploadSuperseded` with revision
"", and "object not found"). The client read the node once and trusted it.
**Decision:** After a commit the node is read again with backoff (100 ms
doubling to 2 s, 8 reads, about 7 s) while it is missing, active with no
revision, or - when the commit returned success - still as it was before
the commit. `errUploadSuperseded` is kept for a non-empty revision which
is neither ours nor the one we started from. If the lag outlasts the
reads, the upload returns `errUploadUnconfirmed` (no low-level retry, as
for `errUploadOutcomeUnknown`), deletes nothing, and a later sync pass
finds the file. The same not-found retry covers a copy's read back and,
with `enable_caching` off, a folder to write into (with it on, a folder
the client made is cached, so a miss means it is gone).
**Alternatives:** Returning success with a node built from what was
committed (the caller then reads, moves or updates through it, and that
needs the decrypted keys and server metadata the client would be
inventing; a wrong node would be cached and acted on); retrying every
read after any write (slows every genuine not-found).
**Consequences:** With `enable_caching` off, a put into a folder deleted
elsewhere takes about 7 s longer to fail. A lag longer than 7 s still fails the upload,
now with an error saying it was committed. See `docs/TODO.md` for the
read-after-write spots not yet tolerant.
## 2026-11-12 - Proton Drive golden captures fail closed
**Status:** accepted; amends "Proton Drive golden fixtures are re-keyed
captures" below
**Context:** Review found the capture could copy account data into a
fixture: an intended-recipient fingerprint of a key not being replaced (in
the notes), and the user ID of a node key. It also reused `-remote`, so a
mistyped `-run` would start the writing integration suite against the
account.
**Decision:** The capture names its folder with `-capture-remote` and
refuses to run with `-remote` set. Every key written has the user ID
`golden <golden@example.invalid>`; a node key whose user ID holds an email
other than the account's or the generic ones Proton's clients use
(`no-reply@proton.me`, `noreply@protonmail.com`) fails the capture. A
signature by, or intended for, a key not being replaced fails the capture,
and the error names no key. A salt notation is written only where the
original had one (with a new salt). `TestGoldenFixtures` also walks every
key, key packet and signature, inside encrypted messages too, and fails
on any key ID, fingerprint or user ID not of the test keys.
**Consequences:** What the committed fixtures expose, by design: with the
test keys in `keys.json`, anyone can decrypt the captured names, extended
attributes (as the client wrote them: check them for camera or location
fields before committing), literal-packet file names and dates, folder
hash keys (so whether a guessed name exists in those real folders can be
tested) and file contents; and the address key's creation time is kept.
Node passphrases and the account's keys are not exposed.
## 2026-11-12 - Proton Drive golden fixtures are re-keyed captures
**Status:** accepted
**Context:** Plan Task 21 asks for fixtures of nodes written by Proton's
web app and official CLI. Captured as they are, they would carry the test
account's keys, IDs and emails. The owner chose to re-encrypt them under
keys made for the tests.
**Decision:** `TestGoldenCapture` (`-capture DIR -capture-label NAME
-remote NAME:PATH`) writes `backend/protondrive/testdata/golden/<label>/`,
read by `TestGoldenFixtures` from the fake server with every signature
checked. Preserved: every block byte for byte; every SEIPD packet which
holds no signature (re-wrapped session key only); the session key, cipher,
SEIPD version, AEAD mode and chunk size, compression algorithm and literal
data packet (format, file name, date, content) of names, hash keys and
extended attributes; signature version, type, hash, creation time,
lifetime and notations; key algorithm, version, creation time and AEAD
support; timestamps, sizes, flags, media types, block sizes and whether
they are recorded. Replaced: all keys (address, node, the captured
folder's parent) by new ones; every PKESK, re-wrapped in the same version;
every signature, re-made by the key replacing its signer (an embedded one
forces its SEIPD packet to be encrypted again with the same session key
and parameters, as a signature can't change in place); node passphrases,
new ones in a message of the same format; the captured folder's name hash;
intended recipients and signer user IDs; emails by
`golden@example.invalid`; IDs by placeholders. Dropped: block signatures
(the backend doesn't read them), block URLs and tokens. Each node lists
what was done to it in `Rekeyed`. Files with thumbnails are refused (the
fake can't serve them); the address key passphrase is sealed to a user key
the fake generates, so no user key is written.
**Alternatives:** Raw captures (account secrets in the repository);
fixtures re-made with gopenpgp from the decrypted content (loses the
other clients' packet formats, the point of the exercise).
**Consequences:** The fixtures test the formats of names, hash keys and
extended attributes as other clients lay them out, but their signature
bytes are ours. Packet headers are re-serialised with fixed lengths.
## 2026-11-12 - Proton Drive is a native port of Proton's Drive SDK
**Status:** accepted
**Context:** With the bridge libraries gone (plan Task 19), the backend
is a Go client written for rclone. Its behaviour has to be checked against
something as Proton changes the service, and the user docs still
described the old libraries.
**Decision:** The backend is maintained as a port of Proton's Drive SDK,
module by module, tracked in `docs/specs/001-conformance-checklist.md`
against SDK commit `05c9115955589d9f6ab7392a36f8f0cb39327133` (whose
`client/js/CHANGELOG.md` ends at `js/v0.23.0`; that tag is not on the
commit), with its deliberate differences (stricter trust
rules, no small-file path, no events, no thumbnails) listed per module.
The user docs describe only what the code does and the protocol limits
the SDK shares, with no fork-only content, so they could go upstream.
**Alternatives:** Binding to the SDK itself (it is TypeScript and C#;
rclone refuses cgo and helper binaries); writing from observed traffic
alone, as the old libraries did (no reference to re-check against).
**Consequences:** Each SDK update needs a walk of the checklist: a diff
of the listed files between the checked commit and the new one. The
docs page must change with any behaviour change, and its generated
options section is left to `make backenddocs` at release.
## 2026-11-12 - Proton Drive keeps frozen old-library fixtures, not the old library
**Status:** accepted
**Context:** `go-proton-api` v1.0.4 and `Proton-API-Bridge` v1.0.5 stayed
in `go.mod` only for differential tests checking that the new client and
the old library read each other's output (plan Task 19).
**Decision:** The differential tests and both libraries were removed. What
the old library wrote stays checked through the frozen fixtures in
`backend/protondrive/testdata/oldlib/` (`TestFrozenFixtures`,
`TestFrozenFileFixture`), which can no longer be regenerated.
**Alternatives:** Keeping the libraries as test-only requirements (they
would stay in `go.mod` and its vulnerability surface, and upstream would
carry them).
**Consequences:** Multi-block and empty old-library files, and old-reader
compatibility of new writes, are no longer tested (`docs/TODO.md`).
## 2026-11-12 - Test-account usernames removed from git history by force-push
**Status:** accepted
**Context:** The first Proton Drive handoff commit contained the two
test-account usernames (no passwords or tokens); a later commit removed
them from the file but they stayed in history on the Gitea remote.
**Decision:** On the owner's explicit instruction, that commit was
rebuilt without the usernames, the following commits were replayed with
identical trees and metadata, and `master` was force-pushed once with
`--force-with-lease`. The rule against force-pushing still stands.
**Consequences:** Commit hashes from `901d7fd5b` onward changed (mapping
in the handoff's "Open questions" section). The old objects may stay
reachable on the server until Gitea garbage-collects the repository.
## 2026-11-12 - test_all shares one protonfake session across test processes
**Status:** accepted
**Context:** `fstest/testserver/init.d/TestProtonDriveFake` starts one
`protonfake` per `test_all` run (reference counted by `run.bash`), and
every test process gets the same session through
`RCLONE_CONFIG_TESTPROTONDRIVEFAKE_*` variables. Refresh tokens are
single use and a process can't see another's refresh, so one process
refreshing would leave the rest with dead tokens.
**Decision:** Share the session; change nothing in `protontest`,
`protonfake` or the client. The client refreshes only after an HTTP 401
(`session.call`); the fake answers 401 only for a session expired by
`Server.ExpireAccessToken` or ended by logout or `RevokeSession`, and
`protonfake` calls none of them. The only logouts are `Fs.Disconnect`
and re-running `rclone config`, which no test in `fs/operations`,
`fs/sync`, `vfs`, `cmd/bisync`, `cmd/gitannex` or `fstests` calls.
**Alternatives:** A session per test process (`protonfake` would need a
sign-in route for `test_all` to call, and the init.d protocol has one
output per server); non-expiring or logout-tolerant tokens in
standalone mode (behaviour no test needs, and a fake that differs from
Proton).
**Consequences:** A future test that calls `Disconnect`, or a fake that
expires tokens on a timer, breaks every process sharing the run: the
symptom is "not signed in" or refresh failures across all suites at
once. Revisit then.
## 2026-11-11 - Proton Drive rewrite paused mid-plan and merged to master
- **Decision:** at the owner's request, work on plan 001 stopped after Task
17 of 21 and the branch was fast-forwarded into `master` and pushed, with
the plan, a handoff document and the execution workspace committed under
`docs/plans/`.
- **Why:** the owner wanted development wound down with nothing left only
in an agent's conversation.
- **Consequences:** `master` carries an unfinished plan, against the usual
rule that plans are removed before merging; the user docs still describe
the old backend; the old libraries are still in `go.mod`. The push to
`master` was a one-off instruction - the rule against pushing to
`master` stands. Resume from `docs/plans/001-protondrive-tier1-HANDOFF.md`.
## 2026-11-11 - Proton Drive logs what ignore_signature_errors lets through
**Status:** accepted
**Context:** With `ignore_signature_errors` set, reads, writes, moves,
copies and renames of nodes whose keys are unverified went ahead
silently, although spec 6.4 promises a logged ERROR (Task 16 re-review
2).
**Decision:** Each such operation logs one ERROR per node and kind of
operation for the life of the `Fs`, naming the node, its ID, the
operation and why its key is unverified. Completes "Proton Drive won't
vouch for a node it couldn't verify".
**Alternatives:** Logging every call (floods a sync); a NOTICE (too
easily missed for something permanent).
**Consequences:** With the option set, moving or copying a node out of
an unverified folder re-signs or re-homes it as the user's, so it is
trusted from then on; the ERROR says so.
## 2026-11-11 - Proton Drive matches email addresses by ASCII case only
**Status:** accepted
**Context:** The own-address check of "Proton Drive roots trust in the
user's own addresses" ignored case, but the key lookup didn't, so a
server could name the user's address in capitals and serve its own keys
for it, at the root and below (Task 16 re-review 2).
**Decision:** One rule everywhere: emails are compared after lowercasing
ASCII letters only. An email matching one of the account's addresses
under it is verified with the account's own keys and never looked up on
the server, and other users' keys are cached under the same key. Unicode
case folding is not used, as it maps the Kelvin sign to k and the long s
to s, letting a non-ASCII address pass for an ASCII one.
**Alternatives:** Exact matching (an address the server stores in other
case would be looked up remotely); `strings.EqualFold` (Unicode folding).
**Consequences:** Two addresses differing only in non-ASCII case are
different addresses to rclone.
## 2026-11-11 - Proton Drive roots trust in the user's own addresses
**Status:** accepted
**Context:** "Proton Drive distrusts what a forged folder key vouches
for" and "Proton Drive refuses a file whose node key signature fails"
read as if every key were checked against keys rclone can trust. But
the keys of another user's email come from the server, so a server can
forge a share, root or node "signed" by a foreign address it vouches
for (Task 16 re-review).
**Decision:** Corrects those entries. The My Files share's creator and
the root folder's signer must be addresses whose keys the account
holds (compared ignoring case); otherwise the share or root key is
unverified, which makes the whole drive unreadable and unwritable
without `ignore_signature_errors`, and the error says why. Below the
root, nodes signed under another user's email are still verified
against server-supplied keys: a protocol limit Proton's SDK shares,
documented in spec section 7 and TODO.
**Alternatives:** Pinning other users' keys on first use (state rclone
doesn't keep); trusting server keys at the root too.
**Consequences:** A folder genuinely signed by an address since deleted
from the account, or whose keys no longer unlock, is unverified: writes
into it, and reads beneath it, need `ignore_signature_errors`.
## 2026-11-11 - Proton Drive won't vouch for a node it couldn't verify
**Status:** accepted
**Context:** Refusing writes into a folder with an unverified key left
the other direction open: moving or copying an anonymous node out of it
has rclone sign its server-made passphrase as the user's, after which it
and everything beneath it verified (Task 16 re-review). And a node made
under such a folder with `ignore_signature_errors` set was signed by the
user, so verified later, although whoever made the folder's key can
decrypt its passphrase.
**Decision:** Supersedes the inheritance rule of "Proton Drive distrusts
what a forged folder key vouches for": every node beneath a folder with
an unverified key is unverified, however it is signed, and so is a
folder rclone makes there. Moving, copying, directory-moving or
renaming a node whose key is unverified fails unless
`ignore_signature_errors` is set.
**Alternatives:** Inheriting only into anonymous nodes (leaves the
user-signed children of a forged folder trusted).
**Consequences:** A genuine folder whose key fails to verify, as one
signed by a since-deleted address, makes its whole subtree unreadable
and unwritable without `ignore_signature_errors`.
## 2026-11-11 - Proton Drive verifies the manifest before releasing a full read
**Status:** accepted
**Context:** A full read checked the manifest signature at EOF, as the
SDK does, so blocks swapped, truncated or from an older revision, each
matching its listed hash and recorded size, reached the reader before
the error: `rclone cat` and streaming mounts showed wrong bytes (spec
9.6 asks for "an integrity error, not data").
**Decision:** A full read lists every block page first, verifies the
manifest over the listed hashes, then fetches; each block is checked
against its listed hash, and a block listed again with another hash
is an integrity error. Pages are fetched one after another. Ranged
reads keep checking blocks against their listed hashes only.
**Alternatives:** Keeping the SDK's EOF check; verifying ranged reads
too by listing the whole file on each ranged open (costly for mounts
and multi-thread copies without a hash cache).
**Consequences:** No extra requests, but a file of more than 20 blocks
waits for its whole list before the first byte. Block metadata, not
data, is held meanwhile. A whole earlier revision served under the
current ID stays undetectable (protocol limit).
## 2026-11-11 - Proton Drive distrusts what a forged folder key vouches for
**Status:** accepted
**Context:** An anonymous node's passphrase, name and content signatures
are checked against its parent folder's key. A server can make a folder
key of its own, seal it to the real parent and sign everything beneath
it, so a refusal based only on each node's own signature check is
bypassed (Task 16 review).
**Decision:** A node key is unverified if its own passphrase signature
fails, or if it was checked against an unverified parent key; this
passes down the tree. Reading a file with an unverified key, and
creating, uploading, renaming, moving or copying into a folder with
one, fail unless `ignore_signature_errors` is set. Listing such a folder
still works, with one ERROR for the folder itself.
**Alternatives:** Leaving the folder's children to their own checks
(bypassable); refusing to list the folder (a sync would delete its
destination copy).
**Consequences:** Builds on the 2026-11-11 entry "Proton Drive refuses a
file whose node key signature fails". Files in a public-link upload
folder whose key fails to verify need `ignore_signature_errors`.
## 2026-11-11 - Proton Drive refuses a file whose node key signature fails
**Status:** accepted
**Context:** The node passphrase signature was only logged when it
failed, as the SDK does, so a server could seal a key of its own to
the parent folder's public key and serve any content under it (spec 7
puts the server in the threat model; 9.6 asks for an error).
**Decision:** Opening such a file fails with an integrity error naming
`ignore_signature_errors`, like a content key or manifest signature
failure; with the option set it is read, the failure logged once. The
node is still listed. Sign-in errors that need a reconnect name the
remote through a hint the seam gives the session, so read errors, which
don't pass through `translateError`, name it too.
**Alternatives:** Skipping the node from listings (a sync would then
delete its copy at the destination); leaving it to the SDK's behaviour.
**Consequences:** Legacy files whose keys were signed by a since-removed
address need `ignore_signature_errors`, which the error says.
## 2026-11-11 - Proton Drive backend runs on its own client
**Status:** accepted
**Context:** The backend sat on `rclone/Proton-API-Bridge` and
`rclone/go-proton-api`, which share credentials through package globals,
write files the official clients can't always read, and can't be tested
without a live account (spec 001).
**Decision:** `protondrive.go` was rewritten on the native client built in
plan Tasks 2-12, keeping every option name and meaning and reading v1.76
saved sessions without signing in again. `Config` offers browser sign-in
(default unless a username and password are already set, so existing
scripted setups keep using them) and password sign-in. An upload whose
commit outcome can't be known is a no-low-level-retry error: an immediate
retry could add a revision that already landed, while a later sync pass
reads the destination first.
**Alternatives:** Patching the bridge (globals and crypto stay outside the
tree); keeping browser sign-in the default even with a password set
(non-interactive `config create` would wait on a browser).
**Consequences:** The full contract suite runs hermetically against
`protontest`. Several `Fs` of one account in one process each cache
separately until events land (spec 6.2).
## 2026-11-11 - Fork agent tooling is appended, not merged, into upstream files
**Status:** accepted
**Context:** Upstream rclone already ships a maintainer-written `AGENTS.md`
and a `CLAUDE.md` that imports it. This fork tracks upstream and intends to
send work back, so every edit to an upstream file is a future merge conflict
and a risk of leaking fork-only material into an upstream PR.
**Decision:** Upstream's `AGENTS.md` text is kept verbatim. Fork rules are one
"Fork Workflow" section appended at the end. `CLAUDE.md` and `README.md` are
untouched. Fork-only docs live at the top of `docs/` (Hugo only builds
`docs/content/`, so they do not reach the website).
**Alternatives:** Restructuring `AGENTS.md` with the fork rules first (better
agent attention, permanent conflicts with upstream); a separate fork rules
file (two sources of truth).
**Consequences:** `AGENTS.md` sits at 148 of a 150 line budget - a new fork
rule must replace an old one. Upstream PR branches must be cut so they exclude
the paths listed in the Fork Workflow section.
## 2026-11-11 - Adopt AGENTS.md as single source of truth
**Status:** accepted
**Context:** Agents had no fork-specific workflow or permission config between
sessions.
**Decision:** `AGENTS.md` is canonical; `CLAUDE.md`/`GEMINI.md` are pointers.
Specs are permanent in `docs/specs/`. Plans live in `docs/plans/` only while
work is in progress and are removed before merge. Both override the
superpowers default paths.
**Alternatives:** Per-tool rule files (drift); no rules file (agents
re-explore the repo every session).
**Consequences:** Rule changes happen in one file; pointer files stay thin.
The spec, not the plan, is the record.
+65
View File
@@ -0,0 +1,65 @@
# Agent permissions
Fork-only. Source of truth for what AI coding agents may run here. Tool files
are renderings of this page: `.claude/settings.json`, `.codex/config.toml`,
`.codex/rules/project.rules`, `.gemini/settings.json`. Change this page and
every tool file in the same commit. Review changes to these files and to
`AGENTS.md` like CI config: one line redirects agent behaviour repo-wide.
## Verified commands
Run on the host on 2026-11-12 with Go 1.27.4 (`~/.local/opt/go`) and
golangci-lint 2.15.0 (`~/.local/bin`), from the repository root, with
`RCLONE_CONFIG=/notfound` set so no test can reach a real remote. The rows
marked (container) are from 2026-11-11, before Go was on the host, run in
the `golang:1.26` container and not repeated.
Only `worked` rows may appear in a tier, a tool file, or `AGENTS.md`.
| Command | Result |
|---|---|
| `go mod download` | worked |
| `go build` | worked - binary reports `rclone v1.77.0-DEV` |
| `go test ./backend/memory/` | worked |
| `go test -run 'TestIntegration/FsMkdir/FsPutFiles/FsCopy' ./backend/memory/` | worked |
| `go test ./backend/protondrive/...` | worked - the contract suite runs against the fake server; the live `TestProtonDrive:` suite skips without a config |
| `go vet ./backend/protondrive/...` | worked |
| `gofmt -l backend/protondrive` | worked - no output |
| `golangci-lint run ./backend/protondrive/...` | worked - 0 issues |
| `golangci-lint run ./...` | worked - 0 issues |
| `go run ./fstest/test_all -backends protondrive -remotes TestProtonDriveFake: -maxtries 1 -n 4` | worked - starts the fake server through `fstest/testserver/init.d/TestProtonDriveFake` |
| `RCLONE_CONFIG=/notfound go test ./...` | failed - only `cmd/serve/s3`, undiagnosed (2026-11-11, `docs/TODO.md` "Known issues"); in the container 7 packages failed: `backend/smb`, `cmd/gitannex`, `cmd/mount`, `cmd/mount2`, `cmd/serve/docker`, `cmd/serve/nfs`, `fs/logger` (container) |
| `make`, `make quicktest`, `make racequicktest` | not run - `make` is in Ask |
## Tiers
| Tier | Commands | Why |
|---|---|---|
| Allow | `git status`, `git diff`, `git log`, `git show`, `git branch --list`, `git rev-parse`, `git add`, `git commit`, `go mod download`, `go build`, `go test`, `go vet`, `gofmt -l`, `golangci-lint run` | Inspection and the verified dev loop; no prompt needed. |
| Ask | `git push`, `git merge`, `git rebase`, `git switch`, `git restore`, `git commit --amend`, `rm` (any), `go get`, `go mod tidy`, `go install`, `make` (any target), `docker` (any) | Leaves the machine, rewrites work, changes dependencies, or is unverified. |
| Deny | `git push --force` / `-f` / `--force-with-lease`, `git reset --hard`, `git clean` (any), `git add -f` / `--force`, `git commit --no-verify` / `-n`, `rm -r` / `-R` / `-rf` / `-fr` / `-Rf` / `-fR` / `--recursive`, `sudo`; reading `.env`, `.env.*`, `secrets/**` | Destroys work, skips checks, or exposes secrets. |
## Known gaps
- The Claude Code deny rule `git push --force-with-lease:*` does not match
`git push --force-with-lease=<ref>:<sha> ...` (no word boundary before
`=`); a force-push the owner approved on 2026-11-12 went through it.
- Allowlists save prompts; they are not a security boundary. Use the tool's
sandbox for isolation.
- Prefix rules are bypassable: `git -C dir push`, flags placed later
(`git push origin main --force`), `+refspec` pushes. Claude Code's `:*`
matches at a word boundary, so each flag cluster must be listed - which is
why `git clean` is denied whole and `rm` always asks.
- Allowed test and build commands run code from the repo; an agent that can
edit Go files or tests can run anything through `go test`.
- Denying reads of `.env` does not stop a program that opens it itself, and
git can print staged or committed secrets. Rclone test credentials live in
the user's rclone config, outside this repository - keep them there.
- Codex: loaded only once the project is trusted; `approval_policy` here can
loosen a stricter user setting. No `allow` rules are written because in
Codex `allow` means "run outside the sandbox". Codex cannot deny file reads.
`--force-with-lease=<ref>`, `+refspec` and late flags only match Ask.
- Gemini CLI: ignored until the folder is trusted; no Ask tier (anything not
allowed already asks); cannot deny file reads.
- Cursor and Copilot files are not written: nothing in the repository shows
the fork uses them (`.vscode` is gitignored).
+454
View File
@@ -0,0 +1,454 @@
# TODO
Fork-only durable backlog for things noticed and deliberately not fixed.
Small, specific, independently actionable. Remove only when actually done.
(In Go source, upstream's `FIXME`/`TODO` comment convention still applies.)
## Now
- [ ] protondrive: project handed over 2026-11-23 with M1-M5 done (M5 on
branch `protondrive-m5`). The plan 002 whole-branch review ran; its one
fix (a cap on event pages per poll) is in, the rest is listed under
"plan 002 whole-branch review" below. Next: M6 as plan 003 (see Next).
Public code-only branch: `protondrive` on
github.com/StereotypicalCat/rclone-protondrive (squashed, `c0bdbcde6`).
The owner posted the announcement upstream on 2026-11-23 (text in
`docs/plans/upstream-post-draft.md`); watch rclone #9252 and forum
thread 53609 for replies before starting new work.
Context: `docs/plans/002-protondrive-m5-HANDOFF.md`.
- [ ] protondrive: plan 001 (the backend rewrite) is complete and on
`master`; its handoff `docs/plans/001-protondrive-tier1-HANDOFF.md`
still holds the standing instructions, rulings 1-33 and live results.
- [ ] protondrive: the free test account's derived key passphrase (the
`client_salted_key_pass` of a browser sign-in on 2026-11-12) was shown
in an agent's tool output when `rclone config create` printed the new
remote; that session was logged out at once, but the passphrase only
changes with the account password. Owner: change the free account's
password if that matters, then update `~/proton_rclone_test_acc_password`
and the remote's saved password.
## Next
- [ ] protondrive M6: opt-in persistent metadata cache of encrypted node
records and the event cursor through `lib/kv` (`metadata_cache`), rclone
Metadata (`mtime`, `btime`, `content-type`), and the SDK's single-request
upload for files under 128 KiB (`files/small`). Needs its own plan; the
docs page and `protondrive.yaml` features change with it.
- [ ] protondrive M7: the upstream path (spec 13), deferred by the owner;
also the new crypto model once Proton publishes it in the SDK.
- [ ] protondrive live checks not yet run (plan Task 21), each of which
the user docs avoid claiming: 2FA, by code and by `otp_secret_key`;
CAPTCHA handling; Proton's desktop and mobile clients reading files
rclone wrote (the web app and the official CLI 0.9.0 have been
checked); whether the real server lists drafts or trashed items as
children (affects `Rmdir`); whether any real address differs from
another of the account only by non-ASCII case (counted as foreign);
how long the server's read-after-write lag after a commit really is
(the client retries for about 7 s).
- [ ] protondrive: `test_all` against the real service (2026-11-12,
free account) fails only the five cross-`Fs` cache tests listed
below; `fstest/test_all/config.yaml`'s `TestProtonDrive:` entry has no
`ignore` for them, so plan Task 21's "clean with no ignore entries" is
not met until that is decided.
- [ ] protondrive: `TestIntegration/FsMkdir/FsChangeNotify` is ignored
for `TestProtonDrive:` in `fstest/test_all/config.yaml`: fstests waits
9 x 3 s = 27 s for changes, and Proton allows one events request per
30 s, so it saw none live (2026-11-12). The live events check
otherwise passed (`rclone test changenotify`, rclone and the official
CLI). Fixing it needs a longer wait in fstests or a per-backend one.
- [ ] protondrive: `docs/content/protondrive.md`'s generated options
section still shows the old options and help texts (its
`enable_caching` text says events are not implemented, contradicting
the hand-written "Changes made elsewhere" section); regenerate it with
`make backenddocs` when the work goes upstream (generated doc changes
are not committed in the fork, per `AGENTS.md`).
- [ ] protondrive: API responses have no body-size limit, and a block
list's `Token` and `BareURL` and the first page's `Thumbnails` are
unbounded, so the 2^19-block cap bounds how many blocks a full read
holds but not the bytes (about 250-350 MiB at the cap with realistic
values, unbounded against a hostile server). Consider a limit on API
response bodies and on those fields.
- [ ] protondrive: confirm on an account whose drive was made by
Proton's own apps (both test accounts' drives were most likely created
by rclone itself) that the
root-of-trust rule passes (the My Files share created, and its root
signed, by one of the account's addresses), and count how many folders
fail key verification.
- [ ] protondrive: a range from offset 0 of a file whose size isn't
recorded (`bytes=0-N`, N at or past the end) is read as a ranged read,
so its manifest isn't checked; only a known size identifies a range
covering the whole file.
- [ ] protondrive: `TestGoldenCapture` refuses files with thumbnails (the
fake server serves none, and the manifest covers them) and keys other
than RSA, EdDSA, Ed25519 and Ed448; images and photos from Proton's apps
can't become golden fixtures until the fake serves thumbnails.
- [ ] protondrive: below the root, a node signed under another user's
email (a shared folder's members) is verified against public keys the
server supplies (`account.publicKeys`), so a hostile server can forge
it; the SDK does the same. Revisit when Proton offers key transparency
or address-key pinning.
- [ ] protondrive: a full read lists every block page before releasing
the first byte, one request per 20 blocks in sequence, so a very large
file waits (about 12 requests for 1 GiB, about 1280 for 100 GiB) before
data flows. Fetching pages in parallel under the 15-request metadata
limit would cut that.
- [ ] protondrive: a ranged read (offset > 0 or a limit, as multi-thread
copies and mounts make) checks each block against the hash the server
lists for it, its decryption and its recorded size, but not the
manifest, so a server can serve validly encrypted blocks of the same
file swapped or from an older revision of the same size. The planned
fix is a bounded per-revision cache of manifest-verified block hashes.
- [ ] protondrive: a server can serve an earlier revision whole (blocks,
manifest and extended attributes, all validly signed) under the current
revision ID undetected, as nothing signed binds them to the revision;
the SDK can't detect it either. Raise with Proton.
- [ ] protondrive: `--dump headers` logs Proton's `pm-storage-token` and
`x-pm-uid` (fshttp redacts only `Authorization`), and `--dump bodies`
logs the access, refresh and upload tokens in JSON bodies (seen in
`TestNoSecretsInLogs`). The docs page warns about it; a header
redaction list in `fshttp` would be an upstream change.
- [ ] protondrive: a name whose signature fails is listed and the file
read with only an `ERROR` logged (spec 6.2, the SDK's behaviour), and
names aren't bound to their node, so a server can swap the encrypted
names of two files in one folder undetected. Raise with Proton.
- [ ] lib/pacer: `TokenDispenser.Get` takes no context, so a cancelled
protondrive block download still waits for a download token (held by
other in-flight blocks, which finish or fail soon) before it notices.
Consider a context-aware `Get`.
- [ ] protondrive: confirm that Proton's desktop and mobile clients read
a file written by Task 5's `crypto.go` (the web app and the official CLI
0.9.0 do, with signatures verified, as of 2026-11-12) (v4 node key
advertising SEIPDv2, v6 PKESK content key, SEIPDv2 GCM blocks, block
signatures encrypted with the content session key). This is what the SDK
(js/v0.23.0) writes, but go-proton-api v1.0.4 `link_file_types.go`
(`SetContentKeyPacketAndSignature`) and Proton-API-Bridge v1.0.5
`crypto.go` (`generateLockedKey`) say the official clients do not reliably
read crypto-refresh files and that the server rejects a v6 content key
packet for a v4 node key; the bridge never sent one with a key advertising
SEIPDv2, so its claim may not apply. Released rclone itself is not the
problem: Task 6's `TestNewWriterOldReader` (removed with the old
libraries in Task 19) showed go-proton-api v1.0.4 and the bridge's block
reader read this format (v6 PKESK, SEIPDv2 blocks and block signatures)
and the new `toISOString` modification time.
- [ ] protondrive: files the old library (go-proton-api v1.0.4 and
Proton-API-Bridge v1.0.5) wrote are covered only by the single-block
frozen fixtures in `backend/protondrive/testdata/oldlib/`
(`TestFrozenFixtures`, `TestFrozenFileFixture`); the multi-block and
empty-file cases left with the differential tests in Task 19. A
multi-block fixture would need the old library back to write it. Nothing
checks any more that released rclone (v1.76 and older) can read what the
new backend writes; that matters to users who downgrade.
Commit `b667a1ab0` still has the differential tests and both libraries,
so such fixtures can be generated from a worktree of it.
- [ ] protondrive: a ranged read of a file which doesn't record its
block sizes (written by some other clients) starts at the furthest
block whose size an earlier read in the same `Fs` learnt
(download.go `blockSizeCache`, 16 revisions, 65536 blocks), else at
the first block. The first chunks of a multi-thread copy, which start
together, still each read from the first block, and a random-offset
read beyond what was read before through a mount is slow. A ranged
read with sizes unknown also fetches up to `downloadAhead` blocks past
its end. Neither cache nor listing tells where a block starts without
reading the ones before it, as the packet framing varies by writer.
- [ ] protondrive: `client.apiCall` retries POST and PUT mutations
(create folder, move, rename, copy) after 5xx and network errors, as the
SDK does. If a lost response hid a success, the retry fails with
`errExists` (2500) or a stale `OriginalHash` (2000) although the change
was made. Consider re-reading the node after such a retry failure.
- [ ] protondrive: `createRevision` (POST `.../files/{id}/revisions`) is
retried by `apiCall` after a lost response like any POST; a retry that
succeeds leaves the first draft revision orphaned on the server (the
fake allows several draft revisions). Find out whether Proton refuses a
second draft revision, and delete or reuse our own if so.
- [ ] protondrive: confirm on a real account what `delete_multiple` does to
an active (non-draft) link. The upload cleanup only sends it for drafts,
and the fake refuses non-drafts, but the SDK's conflict handler sends it
for any `ConflictDraftRevisionID`, which an active file with a draft
revision also reports; Task 11 uploads a new revision in that case
instead.
A `--retries` pass after an upload whose outcome was unknown can reach
the own-draft `delete_multiple` in `resolveConflict` (`upload.go`); it
is decided by Proton's conflict details, which could in theory lag.
- [ ] protondrive: confirm the HTTP status and code Proton returns for a
bad verifier token, a missing block and a stale `CurrentRevisionID`
(the fake uses 422 / 2000, which the spec maps to "upgrade rclone").
- [ ] protondrive: Proton's server can take a moment to show a change
(seen live: a node read just after its commit was missing, or still a
draft with no active revision). The fake models this only through
`Server.SetReadLag`, on the links route after a create, copy or
commit; how long the real lag lasts and whether listings
(`folders/{id}/children`) lag too is unmeasured. Only the reads back
after a commit, a copy and, with `enable_caching` off, of a folder to
write into (`targetFolder`) retry, for about 7 s. Not tolerant yet, and the next
symptoms to expect: `activeNode` (Update, Move, Copy, DirMove of an
object just written) fails "object not found" while the node is
missing or still a draft; Move's read of the moved node may be stale.
- [ ] protondrive: drafts left after an ambiguous commit failure (5xx,
network error, timeout, cancel, or a refusal after the commit was
resent) are never deleted by the client, by design (see DECISIONS,
"a draft is deleted only on an explicit refusal"). The next upload of
the same name by this remote replaces its own draft, but a name never
uploaded again keeps an orphan draft (a new file's draft node, or a
draft revision) taking quota. `CleanUp` only empties the trash. Find
out whether Proton expires drafts by itself, and consider having
`CleanUp` delete this remote's own drafts (by `DraftClientUID`).
- [ ] protondrive: `errUploadUnconfirmed` is not retried at once, but a
whole-sync `--retries` pass lists again; if the listing still lags it
uploads the file again, adding a revision with identical content
(wasted work and version history, no data loss).
- [ ] protondrive: several `Fs` of one account in one process each have
their own node cache; only Move/DirMove sources are invalidated across
them. A name missing from one `Fs`'s cached listing stays missing after
another `Fs` creates it, so `--compare-dest`, `--copy-dest` (with
`--immutable`) and `checksum --download` decide on stale listings when
the other `Fs` writes during the run, and an `Fs` made on a path that
doesn't exist yet never finds it once it is made elsewhere. Five
`test_all` tests fail for this and are in the `ignore` list of
`TestProtonDriveFake:` (`fstest/test_all/config.yaml`):
`TestCheckSumDownload`, `TestCopyFileCompareDest`,
`TestCopyFileCopyDestImmutable`, `TestSyncCompareDest`,
`TestSyncCopyDestImmutable`; all pass with `enable_caching = false`.
Events polled every 30 s (spec 6.2) will not close a window of
seconds. Re-listing on every cache miss fixes them but breaks
`TestBudgetUpload` and `TestBudgetMkdir` (a folder re-listed per new
file). A cache shared by the `Fs` of one account would fix them, but
is package state, which the spec rules out: owner decision.
M5 kept per-`Fs` caches and left these five ignored (plan 002
ruling 7); events bound how long a mount shows other clients' changes
as stale, to about one poll interval, but not this window.
- [ ] protondrive: `cmd/gitannex` is in `ignoretests` for
`TestProtonDriveFake:` because its remote name check
(`cmd/gitannex/configparse.go`, `config.GetRemoteNames`) sees remotes
set by environment variables lower cased, as for every other init.d
remote; it says nothing about the backend. Run it against a remote in
a config file to cover it.
- [ ] `.gitea/workflows/ci.yml` could not be run locally. The Gitea has
an Actions runner (slow, so the workflow is kept light: 20 s per fuzz
target, a 45 minute job timeout, no `test_all`); the first push must
confirm the runner picks the workflow up.
- [ ] protondrive: browser sign-in in `rclone config` waits up to 10 minutes
polling; a non-interactive `config create` without username and password
waits the same.
- [ ] Propose a CI check for this fork: `AGENTS.md`, `CLAUDE.md`, `GEMINI.md`
and the `docs/` agent files exist, and `AGENTS.md` is at most 150 lines.
### final review minors (2026-11-12)
- [ ] protondrive (final re-review): ranged reads place their start from
block sizes in extended attributes even when those are unsigned, so a
forging server can shift the bytes a ranged read returns (full reads
are unaffected).
- [ ] protondrive (final re-review): `TestMain` applies `RCLONE_CONFIG`
only when it is set; with it unset, tests may still find the user's
config. Left for the owner (M5 Task 7): rclone's convention is that a
plain `go test` in a backend directory runs against the configured
`TestRemote:`, so defaulting to no config would change how live runs
are made.
- [ ] protondrive (final re-review): the draft client ID stays random per
run when the remote has a config section that can't be saved.
Minors from the whole-branch review (`final-review-*.md` in the plan
workspace) not fixed in its fix wave. Paths are under `backend/protondrive/`.
- [ ] A node fetched while it is being changed can overwrite the newer
cached node and stay cached: `put` after `fetchLinks` has no per-node
generation (`nodes.go` `fetchNode`, `cache.go` `put`).
- [ ] Unbounded per-client maps: `client.folderKeys` (kept whatever the
cache), the node cache, `client.reported`, `account.foreign`; `close()`
doesn't clear the private keys of cached file nodes.
- [ ] The name and hash key signature date exemptions
(`nameSignedSince`, `hashKeySignedSince`) and the content key fallback
read the server-supplied `CreateTime`, so a server can back-date a node
to exempt it (commented in `nodes.go`, as in the SDK).
- [ ] Earlier deferred crypto minors still present: the node passphrase
isn't checked as UTF-8 (`crypto.go` `decryptNodeKeys`); Move
detects an anonymous node by `SignatureEmail == ""` (`nodes.go`
`encryptForNewParent`). Left: either change needs checking against
what the SDK and Proton's apps accept.
- [ ] Two processes sharing one config (a mount and a cron job) can
delete each other's in-progress draft of the same new name, since the
draft client ID is per remote (`upload.go` `resolveConflict`).
- [ ] An own leftover draft revision on an active file is never deleted
and keeps taking quota (`upload.go` conflict path).
- [ ] A `createDraft` resend can report the client's own new draft as
one that "came back after it was deleted" (`upload.go` `createDraft`).
- [ ] `rclone config` on a remote with a saved session asks "Already
signed in - sign in again?" with default no, even when the session is
dead and the user followed the reconnect hint (`protondrive.go`
`Config`, ruling 17).
- [ ] After a CAPTCHA in `rclone config`, the method question defaults
back to password sign-in (`protondrive.go` `Config`).
- [ ] Token refresh hasn't been seen working against the real server,
and its request lacks the `UID` and `RedirectURI` go-proton-api sends
(`api/types.go` `AuthRefreshRequest`); add it to the live checks.
- [ ] Session minors deferred since Tasks 2-4: an adopted stored token
whose access token is stale fails one call with a 401; the refresh uses
the first waiter's ctx; `serverTime` can step back; the half-signed-in
cleanup `DELETE` uses a possibly cancelled ctx; an empty SRP salt isn't
refused up front; `GET /core/v4/users` is fetched twice at sign-in
(`session.go`, `account.go`).
- [ ] Server-side Copy onto an existing name falls back to download and
re-upload (`protondrive.go` `Copy`).
- [ ] `Precision()` is 1 s while `ModTime` has milliseconds;
cross-account Move/Copy/DirMove aren't refused; the on-the-fly remote
hint names the bare backend; logging passes `nil`, not the `Fs`,
throughout (sweep before upstream).
- [ ] Goroutine-count leak checks remain (`download_internal_test.go`
`requireNoLeaks`, `nodes_internal_test.go`); don't add more.
- [ ] `TestAcquireTokenCancel` sleeps 20 ms to let the wait start
(`upload_internal_test.go`). A miss only tests a cancel before the
wait, and still passes; removing it needs a hook in `acquireToken`.
- [ ] CI runs on both `push` and `pull_request` with no `concurrency`
group, so twice per PR push (`.gitea/workflows/ci.yml`); check Gitea
supports `concurrency` first.
- [ ] The fake's read lag (`protontest` `SetReadLag`) never runs with the
contract suite; consider a second `fstests.Run` or a `protonfake
-read-lag` flag.
- [ ] The docs page describes CAPTCHA handling, 2FA prompting and
account-wide `about` that are proven only against the fake, while this
file says the docs avoid claiming them; soften one or the other.
- [ ] `docs/PERMISSIONS.md` and `.claude/`/`.gemini/` allow
`golangci-lint run` but `.codex/rules/project.rules` doesn't; bring it
in step (owner, as it is a permission change).
### plan 002 whole-branch review (2026-11-23), not fixed at handover
- [ ] protondrive events: after another client renames a folder, a mount
re-listing the parent before `forgetChanged` runs makes `GetInv` return
the new path, so the old path's dircache entries stay
(`protondrive.go` `forgetChanged`). Fix: also flush the old path from
`GetInv(parentID)` + name, or compute flush paths before notifying.
- [ ] protondrive events: the start cursor is fetched after the first
listing is read and decrypted, so changes in between are never
reported; same for a `fetchNodeIn` -> `put` in flight across a poll
(`nodes.go` `onFill`, `cache.go`). Fix: fetch the cursor before the
first server read; guard `put` with a cache generation token.
- [ ] protondrive events: `invalidateTree` walks the whole cache for each
Delete or folder move, under `p.mu` and `cache.mu`; emptying a big trash
(one Delete per link) on a large cache can stall a mount. Fix: one
parent->children index per `applyEvents` batch, skip unknown IDs.
- [ ] protondrive events (minor): `stop()` can miss a timer poll queued on
`runMu` (re-check `gen` after `pollMu.Lock()`); `setInterval` is never
reset when the last subscriber leaves; an event for an uncached node
invalidates all in-flight listings; a non-advancing page is re-applied
every interval.
- [ ] protondrive tests: test `Fs` made with `NewFs` and never shut down
(`regression_test.go` 192, 194, 230, 280, 610; `security_test.go` 571,
1032; `golden_internal_test.go` 227) keep polling closed or reused-port
servers for the whole run. This is the likely cause of both the
`ci.LogLevel` `-race` report in TestHostileServer and the
TestRegressionTwoFsRefreshRace flake (a foreign refresh takes a Gather
slot). Fix: a `mustNewFs` helper that registers `Shutdown` in
`t.Cleanup` after `protontest.New(t)`; in `fake_test.go` wrap
`ri.NewFs` to shut down every `Fs` made during `TestIntegrationFake`,
replacing the 2501 fault and 3 s sleep. Also widen the timing bounds in
`events_internal_test.go` (TestPollerPollsWhileCached, Eventually
waits at 603/646, TestPollerBackoff upper bound).
- [ ] protondrive docs (minor): environment-variable limitation paragraph
belongs under Limitations and likely applies to connection-string
remotes too; mention that a 2501 stops change tracking until restart;
conformance checklist "30 s between polls" holds only for Proton hosts;
`original_file_size` Help still has the old wording.
## Someday
## Recurring
- [ ] Maintain `AGENTS.md`:
- **Add a rule only in response to a real failure.** Do not pre-empt
hypothetical mistakes.
- **Update in the same commit as the convention change.**
- **Prune quarterly**, and re-check the Fork Workflow section against
upstream's `AGENTS.md` after each upstream merge.
## Known issues
- [ ] On the development host (Go 1.27.4) `RCLONE_CONFIG=/notfound go test ./...`
fails only `cmd/serve/s3`, unrelated to this work and undiagnosed (seen
2026-11-11 before the Proton Drive rewrite began). That is the baseline
for plan Task 19's "no new failures"; the container list below is not.
- [ ] On the development host on 2026-11-12, `cmd/bisync` `TestRcBackupDir`
(`backupDir1`, `backupDir2`) fails every run with "unable to find file
.../backup/file0.txt", also at `06700aaf2` (before the Proton Drive
rewrite), so it is not caused by that work; undiagnosed. `cmd/serve/s3`
passed in the same full run.
- [ ] `RCLONE_CONFIG=/notfound go test ./...` in the bare `golang:1.26`
container fails 7 packages (list in `docs/PERMISSIONS.md`). `fs/logger`
needs `rsync`; the mount, serve and smb failures are undiagnosed and are
probably missing container tooling (FUSE, git-annex), not code. Confirm on a
host with Go installed before treating a full-suite failure as a regression.
- [ ] protondrive: `TestRegressionManyNewFs` can't see from the fake
server that key unlocks run one at a time; only
`TestLoadAccountSerialised` (internal, `unlockHook`) checks it.
- [ ] protondrive: an address key's `Token` (account.go
`unlockAddressKey`) is decrypted without a decompression limit, unlike
node metadata (`decryptMessage`); a hostile server could send a
compression bomb there too. Seen in Task 17.
- [ ] protondrive: API error bodies are read whole and their `Error`
message is logged as the server sent it, of any length and with any
control characters (session.go `errorHandler`). Bound and sanitise it
if a hostile server is in scope for logs. Seen in Task 17.
- [ ] protondrive: a new revision (`createRevision`), a move, rename or
trash still forget the parent folder's cached listing, so `Put` over
existing files in one folder lists it again each time (`sync` is not
affected: it calls `Update`). New files and folders are added to the
listing instead since Task 17.
- [ ] protondrive: the account's own user keys (account.go `loadAccount`)
are unlocked without the Argon2 limits node and share keys get
(crypto.go `checkKeyS2K`): the server stores them too, so a hostile
server could make sign-in run a KDF of up to 2 TiB. Left out because a
genuine user key's S2K parameters aren't known to be within the
limits; check what Proton's apps write before applying them. Address
keys are safe: their token's signature is checked first.
- [ ] protondrive: `TestRegressionTwoFsRefreshRace` failed once in a
full `-race` run of the package on 2026-11-12 (a listing got 401 and
the server saw 3 refreshes, not 2); it passed 30 runs alone with
`-race`. Undiagnosed; seen in M5 Task 4. Not reproduced in M5 Task 7:
1200 runs alone with `-race` at `-cpu 1,2,4,16`, and nine full
`-race` runs of the package, three at a time (which did turn up
other load-only failures, since fixed). Lead: any third refresh
request in the test's window gives the count of 3 (shown by sending
one from a client of another session: 3 refreshes, no 401), and the
package leaks `Fs` whose pollers keep polling closed test servers,
so one that hits a later server on a reused port would send one. The
401 is not explained: neither our two sessions nor a foreign one
rotate the session's tokens after a retry. The failure's full output
was not kept; keep it if it recurs.
- [ ] protondrive `ChangeNotify`: a folder renamed in place by another
client is reported at its old path and as a change to its parent, not
at its new path, which the event doesn't carry; a moved node is
reported under its old name in the new folder. VFS only needs the
parent, so mounts are right; other consumers get no new name.
- [ ] protondrive: a listing fetched before an event is applied can
still `Put` its folders into the dircache after the event flushed
them (`ListP`); the node cache's fetch guard doesn't cover the
dircache. The next event or `DirCacheFlush` corrects it.
- [ ] protondrive tests: with three `-race` package runs at once, the
race detector still reports `captureLog` (`security_test.go`) writing
`ci.LogLevel` against a poll's debug line (`events.go` `pollEvents`)
in `TestHostileServer` cases and `TestNoSecretsInLogs`, about once
per run, even where the polling `Fs` was shut down first and
`Shutdown` now waits for a poll in flight (M5 Task 7). Also seen once
in a single full run, in a case that doesn't call `captureLog`,
against the previous case's cleanup: the polling `Fs` was made after
that cleanup, so the two are ordered by `t.Run`, which suggests the
detector sees no happens-before edge into `time.AfterFunc` callbacks
(worth checking against Go's runtime). Instrumenting the pollers
didn't catch one polling after its `Shutdown`. Left at wind-down;
next step is that check, or a fake remote for the security tests
that doesn't poll at all.
- [ ] protondrive events: an `Fs` never shut down with nothing
subscribed polls until its node cache has gone unused for 10 minutes
(`cacheIdleTime`), which is longer than the rest of the package's
test run, so `TestIntegrationFake` still makes the volume gone at
cleanup to stop the `Fs` fstests leaks (`fake_test.go`).
-1
View File
@@ -153,7 +153,6 @@ WebDAV or S3, that work out of the box.)
{{< provider name="Hetzner Object Storage" home="https://www.hetzner.com/storage/object-storage/" config="/s3/#hetzner" >}}
{{< provider name="Hetzner Storage Box" home="https://www.hetzner.com/storage/storage-box" config="/sftp/#hetzner-storage-box" >}}
{{< provider name="HiDrive" home="https://www.strato.de/cloud-speicher/" config="/hidrive/" >}}
{{< provider name="Hippius" home="https://hippius.com/s3-compatible" config="/s3/#hippius" >}}
{{< provider name="Hitachi Content Platform (HCP)" home="https://www.hitachivantara.com/en-us/products/storage/content-platform.html" config="/s3/#hcp" >}}
{{< provider name="HTTP" home="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol" config="/http/" >}}
{{< provider name="Huawei Drive" home="https://cloud.huawei.com/" config="/huaweidrive/" >}}
+1 -1
View File
@@ -146,7 +146,7 @@ Blob tags (`x-ms-tags` metadata) aren't supported on these accounts.
When uploading large files, increasing the value of
`--azureblob-upload-concurrency` will increase performance at the cost
of using more memory. The default of 16 is set quite conservatively to
use less memory. It may be necessary to raise it to 64 or higher to
use less memory. It maybe be necessary raise it to 64 or higher to
fully utilize a 1 GBit/s link with a single file transfer.
### Restricted filename characters
+1 -1
View File
@@ -123,7 +123,7 @@ files. It has a precision of 100 ns.
When uploading large files, increasing the value of
`--azurefiles-upload-concurrency` will increase performance at the cost
of using more memory. The default of 16 is set quite conservatively to
use less memory. It may be necessary to raise it to 64 or higher to
use less memory. It maybe be necessary raise it to 64 or higher to
fully utilize a 1 GBit/s link with a single file transfer.
### Restricted filename characters
+2 -2
View File
@@ -675,7 +675,7 @@ separators.) To address this particular issue, an additional `{MacFriendlyTime}`
(or just `{mac}`) option is supported, which results in `2006-01-02 0304PM`.
Note that `--conflict-suffix` is entirely separate from rclone's main
[`--suffix`](/docs/#suffix-string) flag. This is intentional, as users may wish
[`--sufix`](/docs/#suffix-string) flag. This is intentional, as users may wish
to use both flags simultaneously, if also using
[`--backup-dir`](#backup-dir1-and-backup-dir2).
@@ -1608,7 +1608,7 @@ personal files between one's home network, one's personal notebook when on the
road, and with one's work computer. The routine data is not sensitive.
For the sensitive data, configure an rclone [crypt remote](/crypt/) to point to
a subdirectory within the local disk tree that is bisync'd to Dropbox,
and then set up a bisync for this local crypt directory to a directory
and then set up an bisync for this local crypt directory to a directory
outside of the main sync tree.
### Linux server setup
+2 -2
View File
@@ -107,7 +107,7 @@ List all the files in your Box
rclone ls remote:
```
To copy a local directory to a Box directory called backup
To copy a local directory to an Box directory called backup
```console
rclone copy /home/source remote:backup
@@ -121,7 +121,7 @@ be done at your Enterprise Box account by going to Settings, "Account"
Tab, and then set the password in the "Authentication" field.
Once you have done this, you can setup your Enterprise Box account
using the same procedure detailed above, using the password you
using the same procedure detailed above in the, using the password you
have just set.
### Invalid refresh token
+22 -4
View File
@@ -63,6 +63,26 @@ Press Enter for the default (gzip).
\ (zstd)
mode> gzip
Option level.
GZIP (levels -2 to 9):
- -2 — Huffman encoding only. Only use if you know what you're doing.
- -1 (default) — recommended; equivalent to level 5.
- 0 — turns off compression.
- 1–9 — increase compression at the cost of speed. Going past 6 generally offers very little return.
ZSTD (levels 0 to 4):
- 0 — turns off compression entirely.
- 1 — fastest compression with the lowest ratio.
- 2 (default) — good balance of speed and compression.
- 3 — better compression, but uses about 2–3x more CPU than the default.
- 4 — best possible compression ratio (highest CPU cost).
Notes:
- Choose GZIP for wide compatibility; ZSTD for better speed/ratio tradeoffs.
- Negative gzip levels: -2 = Huffman-only, -1 = default (≈ level 5).
Enter a value.
level> -1
Edit advanced config?
y) Yes
n) No (default)
@@ -73,6 +93,7 @@ Options:
- type: compress
- remote: remote_to_press:subdir
- mode: gzip
- level: -1
Keep this "compress" remote?
y) Yes this is OK (default)
e) Edit this remote
@@ -84,10 +105,7 @@ y/e/d> y
- **GZIP** – a well-established and widely adopted algorithm that strikes a solid balance between compression speed and ratio. It supports compression levels from -2 to 9, with the default -1 (roughly equivalent to level 5) offering an effective middle ground for most scenarios.
- **Zstandard (zstd)** – a modern, high-performance algorithm that offers precise control over the trade-off between speed and compression efficiency. Compression levels range from 0 (no compression) to 4 (maximum compression), with level 2 as the default.
The compression level of both algorithms can be set with the advanced `level`
option.
- **Zstandard (zstd)** – a modern, high-performance algorithm that offers precise control over the trade-off between speed and compression efficiency. Compression levels range from 0 (no compression) to 4 (maximum compression).
### File types
+3 -3
View File
@@ -118,7 +118,7 @@ will look like this:
[gdrive]
type = drive
scope = drive
team_drive = 1234567...
drive_id = 1234567...
root_folder_id = 0Abcd...
token = {"access_token":...}
```
@@ -249,7 +249,7 @@ This option defaults to the first found method, which is usually `mount`
so you generally won't need it.
`persist` is a reserved boolean (true/false) option.
In future it will allow you to persist on-the-fly remotes in the plugin
In future it will allow to persist on-the-fly remotes in the plugin
`rclone.conf` file.
## Connection Strings
@@ -274,7 +274,7 @@ with equivalent connection string:
This difference exists because flag options `-o key=val` include not only
backend parameters but also mount/VFS flags and possibly other settings.
Also it allows you to discriminate the `remote` option from the `crypt-remote`
Also it allows to discriminate the `remote` option from the `crypt-remote`
(or similarly named backend parameters) and arguably simplifies scripting
due to clearer value substitution.
+9 -9
View File
@@ -152,7 +152,7 @@ The main rclone commands with most used first
<!-- markdownlint-capture -->
<!-- markdownlint-disable line-length -->
- [rclone config](/commands/rclone_config/) - Enter an interactive configuration session.
- [rclone config](/commands/rclone_config/) - Enter an interactive configurationsession.
- [rclone copy](/commands/rclone_copy/) - Copy files from source to dest, skipping already copied.
- [rclone sync](/commands/rclone_sync/) - Make source and dest identical, modifying destination only.
- [rclone bisync](/commands/rclone_bisync/) - [Bidirectional synchronization](/bisync/) between two paths.
@@ -242,7 +242,7 @@ the config file (configured with `rclone config`).
### remote:/path/to/dir
On most backends this refers to the same directory as
On most backends this is refers to the same directory as
`remote:path/to/dir` and that format should be preferred. On a very
small number of remotes (FTP, SFTP, Dropbox for business) this will
refer to a different directory. On these, paths without a leading `/`
@@ -1156,7 +1156,7 @@ to use half of it - 5 Mbit/s. This is 5/8 = 0.625 MiB/s so you would
use a `--bwlimit 0.625M` parameter for rclone.
On Unix systems (Linux, macOS, …) the bandwidth limiter can be toggled by
sending a `SIGUSR2` signal to rclone. This allows you to remove the limitations
sending a `SIGUSR2` signal to rclone. This allows to remove the limitations
of a long running rclone transfer and to restore it back to the value specified
with `--bwlimit` quickly when needed. Assuming there is only one rclone instance
running, you can toggle the limiter like this:
@@ -2122,7 +2122,7 @@ If set, don't allocate more than given amount of memory as buffers. If
not set or set to `0` or `off` this will not limit the amount of memory
in use.
This includes memory used by buffers created by the `--buffer-size` flag
This includes memory used by buffers created by the `--buffer` flag
and buffers used by multi-thread transfers.
Most multi-thread transfers do not take additional memory, but some do
@@ -2142,7 +2142,7 @@ in use and the use of HTTP1 vs HTTP2.
When downloading files, backends only limit the initial opening of the
stream. The bulk data download is not counted as a connection. This
means that the `--max-connections` flag won't limit the total number
means that the `--max--connections` flag won't limit the total number
of downloads.
Note that it is possible to cause deadlocks with this setting so it
@@ -2424,7 +2424,7 @@ Most multi-thread transfers do not take additional memory, but some do
(for example uploading to s3). In the worst case memory usage can be
at maximum `--transfers` \* `--multi-thread-chunk-size` \*
`--multi-thread-streams` or specifically for the s3 backend
`--transfers` \* `--s3-chunk-size` \* `--s3-upload-concurrency`. However you
`--transfers` \* `--s3-chunk-size` \* `--s3-concurrency`. However you
can use the [--max-buffer-memory](/docs/#max-buffer-memory) flag
to control the maximum memory used here.
@@ -2922,7 +2922,7 @@ See also `--tpslimit-burst`.
Max burst of transactions for `--tpslimit` (default `1`).
Normally `--tpslimit` will do exactly the number of transaction per
second specified. However if you supply `--tpslimit-burst` then rclone can
second specified. However if you supply `--tps-burst` then rclone can
save up some transactions from when it was idle giving a burst of up
to the parameter supplied.
@@ -3395,13 +3395,13 @@ at rest or transfer. Detailed instructions for popular OSes:
- Generate and store a password
```powershell
Add-Type -AssemblyName System.Web; New-Object -TypeName PSCredential -ArgumentList "rclone", (ConvertTo-SecureString -String ([System.Web.Security.Membership]::GeneratePassword(40, 10)) -AsPlainText -Force) | Export-Clixml -Path "$env:USERPROFILE\rclone-credential.xml"
New-Object -TypeName PSCredential -ArgumentList "rclone", (ConvertTo-SecureString -String ([System.Web.Security.Membership]::GeneratePassword(40, 10)) -AsPlainText -Force) | Export-Clixml -Path "rclone-credential.xml"
```
- Add the password retrieval instruction
```powershell
[Environment]::SetEnvironmentVariable("RCLONE_PASSWORD_COMMAND", "powershell [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR((Import-Clixml -Path '$env:USERPROFILE\rclone-credential.xml').Password))")
[Environment]::SetEnvironmentVariable("RCLONE_PASSWORD_COMMAND", "[System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR((Import-Clixml -Path "rclone-credential.xml").Password))")
```
#### Encrypt the config file (all systems)
+24 -78
View File
@@ -27,70 +27,48 @@ This will guide you through an interactive setup process:
```text
No remotes found, make a new one?
n) New remote
r) Rename remote
c) Copy remote
s) Set configuration password
q) Quit config
n/s/q> n
Enter name for new remote.
n/r/c/s/q> n
name> remote
Option Storage.
Type of storage to configure.
Choose a number from below, or type in your own value.
Choose a number from below, or type in your own value
[snip]
XX / Google Drive
\ (drive)
\ "drive"
[snip]
Storage> drive
Option client_id.
Google Application Client Id
Leave blank to use rclone's shared client_id, or if you are using a service account.
The shared client_id is being retired and will stop working during 2026, so creating your own is now strongly recommended.
See https://rclone.org/drive/#making-your-own-client-id for how to create your own.
Enter a value. Press Enter to leave empty.
client_id>
Option client_secret.
Google Application Client Secret
Leave blank to use rclone's shared client_id, or if you are using a service account.
If you created your own client_id then enter its client secret here.
Enter a value. Press Enter to leave empty.
client_secret>
Option scope.
Comma separated list of scopes that rclone should use when requesting access from drive.
Choose a number from below, or type in your own value.
Press Enter to leave empty.
Scope that rclone should use when requesting access from drive.
Choose a number from below, or type in your own value
1 / Full access all files, excluding Application Data Folder.
\ (drive)
\ "drive"
2 / Read-only access to file metadata and file contents.
\ (drive.readonly)
\ "drive.readonly"
/ Access to files created by rclone only.
3 | These are visible in the drive website.
| File authorization is revoked when the user deauthorizes the app.
\ (drive.file)
\ "drive.file"
/ Allows read and write access to the Application Data folder.
4 | This is not visible in the drive website.
\ (drive.appfolder)
\ "drive.appfolder"
/ Allows read-only access to file metadata but
5 | does not allow any access to read or download file content.
\ (drive.metadata.readonly)
\ "drive.metadata.readonly"
scope> 1
Option service_account_file.
Service Account Credentials JSON file path.
Leave blank normally.
Needed only if you want use SA instead of interactive login.
Leading `~` will be expanded in the file name as will environment variables such as `${RCLONE_CONFIG_DIR}`.
Enter a value. Press Enter to leave empty.
Service Account Credentials JSON file path - needed only if you want use SA instead of interactive login.
service_account_file>
Edit advanced config?
y) Yes
n) No (default)
y/n> n
Remote config
rclone's shared Google Drive client_id is being retired and will stop working during 2026.
Create your own to avoid interruption: https://rclone.org/drive/#making-your-own-client-id
@@ -98,47 +76,36 @@ Continue using the shared client_id anyway?
y) Yes
n) No (default)
y/n> n
Option client_id.
Google Application Client Id
Enter a value.
client_id> 1234567890-abcdefghijklmnop.apps.googleusercontent.com
Option client_secret.
Google Application Client Secret
Enter a value.
client_secret> GOCSPX-your-client-secret
Use web browser to automatically authenticate rclone with remote?
* Say Y if the machine running rclone has a web browser you can use
* Say N if running rclone on a (remote) machine without web browser access
If not sure try Y. If Y failed, try N.
y) Yes (default)
y) Yes
n) No
y/n> y
If your browser doesn't open automatically go to the following link: http://127.0.0.1:53682/auth
Log in and authorize rclone for access
Waiting for code...
Got code
Configure this as a Shared Drive (Team Drive)?
y) Yes
n) No (default)
n) No
y/n> n
Configuration complete.
Options:
- type: drive
- scope: drive
type: drive
- client_id: 1234567890-abcdefghijklmnop.apps.googleusercontent.com
- client_secret: GOCSPX-your-client-secret
- scope: drive
- root_folder_id:
- service_account_file:
- token: {"access_token":"XXX","token_type":"Bearer","refresh_token":"XXX","expiry":"2014-03-16T13:57:58.955387075Z"}
- team_drive:
Keep this "remote" remote?
y) Yes this is OK (default)
y) Yes this is OK
e) Edit this remote
d) Delete this remote
y/e/d> y
@@ -206,16 +173,10 @@ folders it creates.
So if you uploaded files to drive via the web interface (or any other
means) they will not be visible to rclone.
Files created with this scope are visible in the web interface.
This can be useful if you are using rclone to backup data and you want
to be sure confidential data on your drive is not visible to rclone.
Access is tied to the client_id used to create the files, not to your
account. If you deauthorize the app or its client_id is revoked,
rclone loses access to these files. If you change client_id, for
example when [making your own client_id](#making-your-own-client-id),
rclone will not see the files created with the previous one, although
they remain visible in the web interface. A sync may then upload them
again as duplicates. If you later switch to the `drive` scope, you can
remove these with `rclone dedupe`.
Files created with this scope are visible in the web interface.
#### drive.appfolder
@@ -223,11 +184,6 @@ This gives rclone its own private area to store files. Rclone will
not be able to see any other files on your drive and you won't be able
to see rclone's files from the web interface either.
As with `drive.file`, these files are tied to the client_id. If it is
revoked, rclone can no longer access them, and as they aren't shown in
the web interface they cannot be reached any other way. If you change
it, switch back to the original client_id to regain access.
#### drive.metadata.readonly
This allows read only access to file names only. It does not allow
@@ -2007,16 +1963,6 @@ client_id, so creating one is now required rather than merely
recommended. New remotes created with `rclone config` will warn you if
you leave the client_id blank.
If your remote uses the `drive.file` [scope](#scopes), files created
with your previous client_id will not be visible after you switch. To
access them, set your new client_id with the `drive` scope and keep
using that scope (note this gives rclone access to all your files).
This also re-authorizes rclone:
```console
rclone config update remote client_id YOUR_ID client_secret YOUR_SECRET scope drive
```
Using your own client_id has other benefits too. There is a global
rate limit on the number of queries per second that each client_id can
do set by Google. If you have multiple services running, it is
+1 -1
View File
@@ -207,7 +207,7 @@ documents. These files need to be converted to another format in
order to be downloaded. Often multiple formats are available for
conversion.
When rclone downloads an exportable file, it chooses the format to
When rclone downloads a exportable file, it chooses the format to
download based on the `--dropbox-export-formats` setting. By
default, the export formats are `html,md`, which are sensible
defaults for Dropbox Paper.
+17 -18
View File
@@ -6,19 +6,11 @@ versionIntroduced: "1.73"
# Filen
## Configuration
The initial setup for Filen logs in to your account with your email, password
and, if enabled, a two-factor authentication code. Rclone saves the API key
it receives in the config file so it only needs to log in once.
The initial setup for Filen requires that you get an API key for your account,
currently this is only possible using the [Filen CLI](https://github.com/FilenCloudDienste/filen-cli).
This means you must first download the CLI, login, and then run the `export-api-key` command.
If two-factor authentication is not enabled on your account, rclone can also
log in by itself the first time a remote without an `api_key` is used. This
needs a config file to save the API key in, so if you configure the remote
only with environment variables or a connection string, set `api_key` too
(you can get it with the `export-api-key` command of the
[Filen CLI](https://github.com/FilenCloudDienste/filen-cli)), otherwise rclone
will log in on every run and may be rate limited.
**Note:** If you change your Filen account password, you will need to update your rclone configuration with the new password, then remove the saved API key with `rclone config unset remote api_key` and log in again with `rclone config reconnect remote:`.
**Note:** If you change your Filen account password, you will need to update your rclone configuration with the new password and a re-exported API key (via `export-api-key`).
Here is an example of how to make a remote called `FilenRemote`. First run:
@@ -59,17 +51,24 @@ password:
Confirm the password:
password:
Option API Key.
An API Key for your Filen account
Get this using the Filen CLI export-api-key command
You can download the Filen CLI from https://github.com/FilenCloudDienste/filen-cli
Choose an alternative below.
y) Yes, type in my own password
g) Generate random password
y/g> y
Enter the password:
password:
Confirm the password:
password:
Edit advanced config?
y) Yes
n) No (default)
y/n> n
Option config_2fa.
Two-factor authentication code
Leave blank if two-factor authentication is not enabled on your account.
Enter a value. Press Enter to leave empty.
config_2fa> 123456
Configuration complete.
Options:
- type: filen
+1 -1
View File
@@ -159,7 +159,7 @@ filter will prevent rclone from using [directory filter rules](#directory_filter
as it will instead check every path against
the supplied regular expression(s).
Here is how the `{{regexp}}` is transformed into a full regular
Here is how the `{{regexp}}` is transformed into an full regular
expression to match the entire path:
```text
+1 -1
View File
@@ -75,7 +75,7 @@ List directories and files in the top level of your Gofile
rclone lsf remote:
```
To copy a local directory to a Gofile directory called backup
To copy a local directory to an Gofile directory called backup
```console
rclone copy /home/source remote:backup
-1
View File
@@ -116,7 +116,6 @@ Tailscale (all free).
--enable-metrics Enable OpenMetrics/Prometheus compatible endpoint at /metrics
-h, --help help for gui
--no-auth Don't require auth for the RC API
--no-check-usage Turn off the GUI's automatic remote usage checks
--no-open-browser Skip opening the browser automatically
--pass string Password for RC authentication
--user string User name for RC authentication
+2 -2
View File
@@ -49,7 +49,7 @@ Enter a string value. Press Enter for the default ("").
remote> myRemote:path
Comma separated list of supported checksum types.
Enter a string value. Press Enter for the default ("md5,sha1").
hashes> md5
hashsums> md5
Maximum time to keep checksums in cache. 0 = no cache, off = cache forever.
max_age> off
Edit advanced config? (y/n)
@@ -61,7 +61,7 @@ Remote config
[Hasher1]
type = hasher
remote = myRemote:path
hashes = md5
hashsums = md5
max_age = off
--------------------
y) Yes this is OK
-4
View File
@@ -24,10 +24,6 @@ This backend serves two Apple services:
for 30 days. After which you will have to reauthenticate with `rclone reconnect`
or `rclone config`.
China Mainland (GCBD) iCloud accounts are supported. rclone normally detects
them automatically during sign-in. The advanced `region` option can be set to
`china` if automatic detection is unavailable.
## Authentication
rclone authenticates with Apple using [SRP (Secure Remote Password)](https://en.wikipedia.org/wiki/Secure_Remote_Password_protocol),
+3 -3
View File
@@ -24,7 +24,7 @@ Make a new item
rclone mkdir remote:item
```
List the contents of an item
List the contents of a item
```console
rclone ls remote:item
@@ -42,8 +42,8 @@ rclone sync --interactive /home/local/directory remote:item
Because of Internet Archive's architecture, it enqueues write operations (and
extra post-processings) in a per-item queue. You can check item's queue at
<https://catalogd.archive.org/history/item-name-here>. Because of that, all
uploads/deletes will not show up immediately and take some time to be available.
The per-item queue is enqueued to another queue, Item Deriver Queue.
uploads/deletes will not show up immediately and takes some time to be available.
The per-item queue is enqueued to an another queue, Item Deriver Queue.
[You can check the status of Item Deriver Queue here.](https://catalogd.archive.org/catalog.php?whereami=1)
This queue has a limit, and it may block you from uploading, or even deleting.
You should avoid uploading a lot of small files for better behavior.
+2 -2
View File
@@ -55,7 +55,7 @@ also refresh token, and invalidates the existing refresh token, the one that
was supplied. It keeps track of the history of refresh tokens, sometimes
referred to as a token family, descending from the original refresh token that
was issued after the initial authentication. This is used to detect any
attempts at reusing old refresh tokens, and trigger an immediate invalidation of
attempts at reusing old refresh tokens, and trigger an immedate invalidation of
the current refresh token, and effectively the entire refresh token family.
When the current refresh token has been invalidated, next time rclone tries to
@@ -294,7 +294,7 @@ List all the files in your Jottacloud
rclone ls remote:
```
To copy a local directory to a Jottacloud directory called backup
To copy a local directory to an Jottacloud directory called backup
```console
rclone copy /home/source remote:backup
+1 -1
View File
@@ -101,7 +101,7 @@ List all the files in your Koofr
rclone ls koofr:
```
To copy a local directory to a Koofr directory called backup
To copy a local directory to an Koofr directory called backup
```console
rclone copy /home/source koofr:backup
+1 -1
View File
@@ -90,7 +90,7 @@ List all the files in your Mega
rclone ls remote:
```
To copy a local directory to a Mega directory called backup
To copy a local directory to an Mega directory called backup
```console
rclone copy /home/source remote:backup
+2 -2
View File
@@ -1361,7 +1361,7 @@ Shared with me files is not supported by rclone
[currently](https://github.com/rclone/rclone/issues/4062), but there is a workaround:
1. Visit [https://onedrive.live.com](https://onedrive.live.com/)
2. Right click an item in `Shared`, then click `Add shortcut to My files` in the context
2. Right click a item in `Shared`, then click `Add shortcut to My files` in the context
![make_shortcut](https://user-images.githubusercontent.com/60313789/206118040-7e762b3b-aa61-41a1-8649-cc18889f3572.png "Screenshot (Shared with me)")
3. The shortcut will appear in `My files`, you can access it with rclone, it
behaves like a normal folder/file.
@@ -1433,7 +1433,7 @@ error something like this:
ERROR : 20230203_123826234_iOS.heic: ReadFileHandle.Read error: low level retry 1/10: unexpected EOF
```
or like this when using `--vfs-cache-mode=full`:
or like this when using `--cache-mode=full`:
```text
INFO : 20230203_123826234_iOS.heic: vfs cache: downloader: error count now 1: vfs reader: failed to write to cache file: 416 Requested Range Not Satisfiable:
@@ -62,7 +62,7 @@ instance principal provider as means of authenticating with object storage servi
- namespace-c, bucket-c
Rclone configuration file needs to have 3 remote sections, one section of each
of above 3 buckets. Create a configuration file in an accessible location that
of above 3 buckets. Create a configuration file in a accessible location that
rclone program can read.
```console
+1 -1
View File
@@ -88,7 +88,7 @@ List all the files in your premiumize.me
rclone ls remote:
```
To copy a local directory to a premiumize.me directory called backup
To copy a local directory to an premiumize.me directory called backup
```console
rclone copy /home/source remote:backup
+1 -1
View File
@@ -74,7 +74,7 @@ List all the files in your Quatrix
rclone ls remote:
```
To copy a local directory to a Quatrix directory called backup
To copy a local directory to an Quatrix directory called backup
```console
rclone copy /home/source remote:backup
+7 -12
View File
@@ -115,17 +115,12 @@ so you can browse to `http://127.0.0.1:5572/` or `http://127.0.0.1:5572/*`
to see a listing of the remotes. Objects may be requested from
remotes using this syntax `http://127.0.0.1:5572/[remote:path]/path/to/object`
Only remotes already present in the config file, and local paths (e.g.
`[/path/to/dir]`), may be served this way. Inline remotes (e.g.
`[:webdav,url=...:]`) and connection string parameters are always
rejected, since instantiating them could run commands, and a web page
can make a browser send requests like these to any rc server the
browser can reach. The exception is `[:local:/path/to/dir]` without
parameters, which is treated as a local path.
Local paths are only served if the rc server has authentication
configured (`--rc-user`/`--rc-pass` or `--rc-htpasswd`) or the
`--rc-no-auth` flag is set.
Unless the rc server has authentication configured (`--rc-user`/`--rc-pass`
or `--rc-htpasswd`) or the `--rc-no-auth` flag is set, only remotes already
present in the config file may be served this way. Inline remotes (e.g.
`[:webdav,url=...:]`), connection string parameters and bare local paths are
rejected, since instantiating them from an unauthenticated request could run
commands or read arbitrary local files.
Default Off.
@@ -717,7 +712,7 @@ The parameters can be a string as per the rest of rclone, eg
`s3:bucket/path` or `:sftp:/my/dir`. They can also be specified as
JSON blobs.
If specifying a JSON blob it should be an object mapping strings to
If specifying a JSON blob it should be a object mapping strings to
strings. These values will be used to configure the remote. There are
3 special values which may be set:
+2 -64
View File
@@ -30,7 +30,6 @@ The S3 backend can be used with a number of different providers:
{{< provider name="FileLu S5 (S3-Compatible Object Storage)" home="https://s5lu.com/" config="/s3/#filelu-s5" >}}
{{< provider name="GCS" home="https://cloud.google.com/storage/docs" config="/s3/#google-cloud-storage" >}}
{{< provider name="Hetzner" home="https://www.hetzner.com/storage/object-storage/" config="/s3/#hetzner" >}}
{{< provider name="Hippius" home="https://hippius.com/s3-compatible" config="/s3/#hippius" >}}
{{< provider name="Hitachi Content Platform (HCP)" home="https://www.hitachivantara.com/en-us/products/storage/content-platform.html" config="/s3/#hcp" >}}
{{< provider name="Huawei OBS" home="https://www.huaweicloud.com/intl/en-us/product/obs.html" config="/s3/#huawei-obs" >}}
{{< provider name="IBM COS S3" home="http://www.ibm.com/cloud/object-storage" config="/s3/#ibm-cos-s3" >}}
@@ -769,7 +768,7 @@ With `env_auth = true` rclone (which uses the SDK for Go v2) should support
[all authentication methods](https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html)
that the `aws` CLI tool does and the other AWS SDKs.
If none of these options actually end up providing `rclone` with AWS
If none of these option actually end up providing `rclone` with AWS
credentials then S3 interaction will be non-authenticated (see the
[anonymous access](#anonymous-access) section for more info).
@@ -6578,67 +6577,6 @@ endpoint = hel1.your-objectstorage.com
acl = private
```
### Hippius {#hippius}
[Hippius](https://hippius.com/s3-compatible) is an S3-compatible
object storage service which stores data across a decentralized
network of providers.
An `rclone config` walkthrough might look like this.
```text
No remotes found, make a new one?
n) New remote
s) Set configuration password
q) Quit config
n/s/q> n
Enter name for new remote.
name> hippius
Option Storage.
Type of storage to configure.
Storage> s3
Option provider.
Choose your S3 provider.
provider> Hippius
Option env_auth.
env_auth> 1
Option access_key_id.
access_key_id> ACCESS_KEY
Option secret_access_key.
secret_access_key> SECRET_KEY
Option region.
region> decentralized
Option endpoint.
endpoint> s3.hippius.com
Edit advanced config?
y) Yes
n) No (default)
y/n> n
```
And the config generated will end up looking like this:
```ini
[hippius]
type = s3
provider = Hippius
access_key_id = ACCESS_KEY
secret_access_key = SECRET_KEY
region = decentralized
endpoint = s3.hippius.com
```
Note that Hippius buckets do not allow ACLs, so `acl` is left unset.
### Hitachi Content Platform (HCP) {#hcp}
Here is an example of making a [Hitachi Content Platform (HCP)](https://www.hitachivantara.com/en-us/products/storage/content-platform.html)
@@ -10674,7 +10612,7 @@ grant](https://docs.storj.io/dcs/api-reference/s3-compatible-gateway#usage).
#### Backend quirks
- `--s3-chunk-size` is forced to be 64 MiB or greater. This will use more
- `--chunk-size` is forced to be 64 MiB or greater. This will use more
memory than the default of 5 MiB.
- Server side copy is disabled as it isn't currently supported in the
gateway.
Loaded 100 of 261 files, more files were not shown because too many files have changed in this diff. Show more