diff --git a/backend/protondrive/api/types.go b/backend/protondrive/api/types.go index 3732a5447..2aa44d202 100644 --- a/backend/protondrive/api/types.go +++ b/backend/protondrive/api/types.go @@ -540,3 +540,115 @@ type Thumbnail struct { Hash string `json:"Hash"` // base64 SHA-256 of the encrypted thumbnail Size int64 `json:"Size"` } + +// ConflictDetails are the Details of a CodeAlreadyExists error from +// creating a node, naming the node which has the name. +type ConflictDetails struct { + ConflictLinkID string `json:"ConflictLinkID"` + ConflictRevisionID string `json:"ConflictRevisionID"` // active revision; empty for a draft or folder + ConflictDraftRevisionID string `json:"ConflictDraftRevisionID"` // draft revision; empty if none + ConflictDraftClientUID string `json:"ConflictDraftClientUID"` // ClientUID of the draft revision's creator +} + +// CreateFileRequest is the body of POST +// /drive/v2/volumes/{volumeID}/files, as CreateFileDto: a draft file. +type CreateFileRequest struct { + ParentLinkID string `json:"ParentLinkID"` + Name string `json:"Name"` + Hash string `json:"Hash"` + MIMEType string `json:"MIMEType"` + ClientUID *string `json:"ClientUID"` // identifies the creator's drafts; null if none + IntendedUploadSize *int64 `json:"IntendedUploadSize"` // rounded size for an early quota check; null if unknown + NodeKey string `json:"NodeKey"` + NodePassphrase string `json:"NodePassphrase"` + NodePassphraseSignature string `json:"NodePassphraseSignature"` + ContentKeyPacket string `json:"ContentKeyPacket"` // base64 + ContentKeyPacketSignature string `json:"ContentKeyPacketSignature"` // armored, by the node key + SignatureAddress string `json:"SignatureAddress"` // signer of the name and passphrase +} + +// CreateFileResponse is the response to POST +// /drive/v2/volumes/{volumeID}/files, as CreateDraftFileResponseDto. +type CreateFileResponse struct { + Code int `json:"Code"` + File struct { + ID string `json:"ID"` + RevisionID string `json:"RevisionID"` // the draft revision + } `json:"File"` +} + +// CreateRevisionRequest is the body of POST +// /drive/v2/volumes/{volumeID}/files/{linkID}/revisions, as +// CreateRevisionRequestDto: a draft revision of an active file. +type CreateRevisionRequest struct { + CurrentRevisionID string `json:"CurrentRevisionID"` // the active revision, which must match + ClientUID *string `json:"ClientUID"` + IntendedUploadSize *int64 `json:"IntendedUploadSize"` +} + +// CreateRevisionResponse is the response to POST +// /drive/v2/volumes/{volumeID}/files/{linkID}/revisions. +type CreateRevisionResponse struct { + Code int `json:"Code"` + Revision struct { + ID string `json:"ID"` + } `json:"Revision"` +} + +// VerificationResponse is the response to GET +// /drive/v2/volumes/{volumeID}/links/{linkID}/revisions/{revisionID}/verification, +// as VerificationData. +type VerificationResponse struct { + Code int `json:"Code"` + VerificationCode string `json:"VerificationCode"` // base64 + ContentKeyPacket string `json:"ContentKeyPacket"` // base64 +} + +// BlockUploadRequest is the body of POST /drive/blocks, as +// RequestUploadInput without its deprecated fields. +type BlockUploadRequest struct { + AddressID string `json:"AddressID"` // address signing the blocks + VolumeID string `json:"VolumeID"` + LinkID string `json:"LinkID"` + RevisionID string `json:"RevisionID"` + BlockList []BlockUploadInfo `json:"BlockList"` + ThumbnailList []struct{} `json:"ThumbnailList"` +} + +// BlockUploadInfo is a block to upload, as RequestUploadBlockInput +// without its deprecated Size and Hash, which the SDK doesn't send. +type BlockUploadInfo struct { + Index int `json:"Index"` // from 1, consecutive + EncSignature string `json:"EncSignature"` // armored signature of the plaintext, encrypted + Verifier BlockVerifier `json:"Verifier"` +} + +// BlockVerifier proves a block was encrypted with the right key. +type BlockVerifier struct { + Token string `json:"Token"` // base64 verification code XOR the start of the encrypted block +} + +// BlockUploadResponse is the response to POST /drive/blocks, as +// RequestUploadResponse. +type BlockUploadResponse struct { + Code int `json:"Code"` + UploadLinks []UploadLink `json:"UploadLinks"` +} + +// UploadLink is the storage URL to upload a block to, as BlockURL. +type UploadLink struct { + Index int `json:"Index"` + BareURL string `json:"BareURL"` + Token string `json:"Token"` // send as pm-storage-token +} + +// CommitRevisionRequest is the body of PUT +// /drive/v2/volumes/{volumeID}/files/{linkID}/revisions/{revisionID}, +// as CommitRevisionDto without its deprecated fields. +type CommitRevisionRequest struct { + ManifestSignature string `json:"ManifestSignature"` // armored, of the block hashes in order + SignatureAddress string `json:"SignatureAddress"` // signer of the manifest, blocks and attributes + XAttr string `json:"XAttr"` // armored extended attributes + ChecksumVerified bool `json:"ChecksumVerified"` // whether the SHA1 matched the source's + Photo *struct{} `json:"Photo"` // always null outside the photo volume +} diff --git a/backend/protondrive/crypto.go b/backend/protondrive/crypto.go index 1d9a37457..af66b5ac7 100644 --- a/backend/protondrive/crypto.go +++ b/backend/protondrive/crypto.go @@ -613,27 +613,55 @@ func decryptContentKey(contentKeyPacketB64, contentKeyPacketSig string, nodeKR, // session key, SEIPDv1 otherwise. As in the SDK the signature is // encrypted with sk too, so it takes the same format. func encryptBlock(plain []byte, sk *crypto.SessionKey, nodeKR, signerKR *crypto.KeyRing, now time.Time) (enc []byte, encSignature string, hash [32]byte, err error) { + var buf bytes.Buffer + encSignature, err = encryptBlockTo(&buf, bytes.NewReader(plain), sk, nodeKR, signerKR, now) + if err != nil { + return nil, "", hash, err + } + return buf.Bytes(), encSignature, sha256.Sum256(buf.Bytes()), nil +} + +// encryptBlockTo is encryptBlock reading the block from plain and +// writing it encrypted to enc as it goes, so neither is held in memory. +func encryptBlockTo(enc io.Writer, plain io.Reader, sk *crypto.SessionKey, nodeKR, signerKR *crypto.KeyRing, now time.Time) (encSignature string, err error) { eh, err := pgpFor(sk).Encryption().SessionKey(sk).New() if err != nil { - return nil, "", hash, fmt.Errorf("encrypt block: %w", err) + return "", fmt.Errorf("encrypt block: %w", err) } - msg, err := eh.Encrypt(plain) - if err != nil { - return nil, "", hash, fmt.Errorf("encrypt block: %w", err) + sb := crypto.PGP().Sign().SigningKeys(signerKR).Detached() + if !now.IsZero() { + sb = sb.SignTime(now.Unix()) } - enc = msg.Bytes() - sig, err := signDetachedEncoded(plain, signerKR, crypto.Bytes, now) + sh, err := sb.New() if err != nil { - return nil, "", hash, fmt.Errorf("encrypt block: sign: %w", err) + return "", fmt.Errorf("encrypt block: sign: %w", err) } - encSig, err := encryptWithSessionKey(sig, sk, nodeKR, nil, false, now) + ew, err := eh.EncryptingWriter(enc, crypto.Bytes) if err != nil { - return nil, "", hash, fmt.Errorf("encrypt block: encrypt signature: %w", err) + return "", fmt.Errorf("encrypt block: %w", err) + } + var sig bytes.Buffer + sw, err := sh.SigningWriter(&sig, crypto.Bytes) + if err != nil { + return "", fmt.Errorf("encrypt block: sign: %w", err) + } + if _, err = io.Copy(io.MultiWriter(ew, sw), plain); err != nil { + return "", fmt.Errorf("encrypt block: %w", err) + } + if err = ew.Close(); err != nil { + return "", fmt.Errorf("encrypt block: %w", err) + } + if err = sw.Close(); err != nil { + return "", fmt.Errorf("encrypt block: sign: %w", err) + } + encSig, err := encryptWithSessionKey(sig.Bytes(), sk, nodeKR, nil, false, now) + if err != nil { + return "", fmt.Errorf("encrypt block: encrypt signature: %w", err) } if encSignature, err = armorMessage(encSig, sk); err != nil { - return nil, "", hash, fmt.Errorf("encrypt block: %w", err) + return "", fmt.Errorf("encrypt block: %w", err) } - return enc, encSignature, sha256.Sum256(enc), nil + return encSignature, nil } // decryptBlock returns the encrypted block enc (SEIPDv1 or v2) diff --git a/backend/protondrive/nodes.go b/backend/protondrive/nodes.go index f494be350..75ac806e9 100644 --- a/backend/protondrive/nodes.go +++ b/backend/protondrive/nodes.go @@ -87,6 +87,10 @@ type client struct { downloadTokens *pacer.TokenDispenser cache *nodeCache + // verifierHook, if set, may change each block's verifier token + // before it is sent; for tests. + verifierHook func(token []byte) + mu sync.Mutex folderKeys map[string]*nodeKeys // by folder ID; kept whatever the cache, as node keys never change reported map[string]bool // problems already logged, by kind and node ID @@ -189,7 +193,13 @@ func (c *client) apiCall(ctx context.Context, opts *rest.Opts, request, response // pacedCall calls fn with pacer p, retrying it as shouldRetry says. func (c *client) pacedCall(ctx context.Context, p *fs.Pacer, fn func() (*http.Response, error)) error { - return p.Call(func() (bool, error) { + return p.Call(c.paced(ctx, fn)) +} + +// paced returns fn as a pacer.Paced which reports whether to retry as +// shouldRetry says, having waited out any Retry-After itself. +func (c *client) paced(ctx context.Context, fn func() (*http.Response, error)) pacer.Paced { + return func() (bool, error) { resp, callErr := fn() retry, err := c.shouldRetry(ctx, resp, callErr) if wait, ok := pacer.IsRetryAfter(err); ok && retry { @@ -207,7 +217,7 @@ func (c *client) pacedCall(ctx context.Context, p *fs.Pacer, fn func() (*http.Re return true, pacer.RetryAfterError(callErr, 0) } return retry, err - }) + } } // shouldRetry returns whether the call which returned resp and err diff --git a/backend/protondrive/protontest/account.go b/backend/protondrive/protontest/account.go index a997b4a51..cf49ae40a 100644 --- a/backend/protondrive/protontest/account.go +++ b/backend/protondrive/protontest/account.go @@ -50,7 +50,7 @@ func mustCrypto(what string, err error) { // generateKey returns a new unlocked Curve25519 key for email, which // is fast to generate unlike RSA. func generateKey(name, email string) *crypto.Key { - key, err := crypto.PGP().KeyGeneration().AddUserId(name, email).New().GenerateKey() + key, err := crypto.PGP().KeyGeneration().AddUserId(name, email).GenerationTime(signTime()).New().GenerateKey() mustCrypto("generate key", err) return key } @@ -104,7 +104,7 @@ func (k *addressKey) sealPassphrase(userKey *userKey) { mustCrypto("address key token", err) token, err := msg.ArmorBytes() mustCrypto("address key token", err) - sh, err := crypto.PGP().Sign().SigningKey(userKey.key).Detached().New() + sh, err := crypto.PGP().Sign().SigningKey(userKey.key).Detached().SignTime(signTime()).New() mustCrypto("address key signature", err) sig, err := sh.Sign(k.passphrase, crypto.Armor) mustCrypto("address key signature", err) @@ -176,7 +176,7 @@ func (s *Server) CorruptAddressKeySignature(u *User, email string, empty bool) { continue } // Sign the real passphrase, so only the signer is wrong. - sh, err := crypto.PGP().Sign().SigningKey(impostor).Detached().New() + sh, err := crypto.PGP().Sign().SigningKey(impostor).Detached().SignTime(signTime()).New() mustCrypto("impostor signature", err) sig, err := sh.Sign(k.passphrase, crypto.Armor) mustCrypto("impostor signature", err) diff --git a/backend/protondrive/protontest/crypto.go b/backend/protondrive/protontest/crypto.go index d56de2665..df36e12a5 100644 --- a/backend/protondrive/protontest/crypto.go +++ b/backend/protondrive/protontest/crypto.go @@ -12,6 +12,7 @@ import ( "encoding/hex" "errors" "fmt" + "time" "github.com/ProtonMail/go-crypto/openpgp/packet" "github.com/ProtonMail/gopenpgp/v3/constants" @@ -35,6 +36,13 @@ func aeadPGP() *crypto.PGPHandle { return crypto.PGPWithProfile(p) } +// signTime returns when the fake generates keys and makes signatures: a +// day before the local clock, so that what it writes is valid at the +// server clock whatever skew within a day a test sets. +func signTime() int64 { + return time.Now().Add(-24 * time.Hour).Unix() +} + // newPassphrase returns base64 of 32 random bytes, the SDK's // generatePassphrase. func newPassphrase() []byte { @@ -57,7 +65,7 @@ func newDriveKey(aead bool) lockedKey { if aead { pgp = aeadPGP() } - key, err := pgp.KeyGeneration().AddUserId(driveKeyName, "").New().GenerateKey() + key, err := pgp.KeyGeneration().AddUserId(driveKeyName, "").GenerationTime(signTime()).New().GenerateKey() mustCrypto("generate drive key", err) passphrase := newPassphrase() return lockedKey{key: key, passphrase: passphrase, armored: lockKey(key, passphrase)} @@ -93,7 +101,7 @@ func encryptArmored(data []byte, key, signer *crypto.Key, compress bool) string mustCrypto("encrypt session key", err) b := crypto.PGP().Encryption().SessionKey(sk) if signer != nil { - b = b.SigningKey(signer) + b = b.SigningKey(signer).SignTime(signTime()) } if compress { b = b.Compress() @@ -109,7 +117,7 @@ func encryptArmored(data []byte, key, signer *crypto.Key, compress bool) string // signArmored returns an armored detached signature of data by signer. func signArmored(data []byte, signer *crypto.Key) string { - sh, err := crypto.PGP().Sign().SigningKey(signer).Detached().New() + sh, err := crypto.PGP().Sign().SigningKey(signer).Detached().SignTime(signTime()).New() mustCrypto("sign", err) sig, err := sh.Sign(data, crypto.Armor) mustCrypto("sign", err) @@ -118,7 +126,7 @@ func signArmored(data []byte, signer *crypto.Key) string { // signBinary returns a binary detached signature of data by signer. func signBinary(data []byte, signer *crypto.Key) []byte { - sh, err := crypto.PGP().Sign().SigningKey(signer).Detached().New() + sh, err := crypto.PGP().Sign().SigningKey(signer).Detached().SignTime(signTime()).New() mustCrypto("sign", err) sig, err := sh.Sign(data, crypto.Bytes) mustCrypto("sign", err) @@ -207,11 +215,15 @@ func keyRing(keys ...*crypto.Key) *crypto.KeyRing { var errSignature = errors.New("protontest: bad signature") // decryptArmored decrypts an armored message with key. If verify is not -// nil the embedded signature must be valid for one of its keys. -func decryptArmored(armored string, key *crypto.Key, verify *crypto.KeyRing) ([]byte, error) { +// nil the embedded signature must be valid for one of its keys at time +// at, or now if at is zero. +func decryptArmored(armored string, key *crypto.Key, verify *crypto.KeyRing, at time.Time) ([]byte, error) { b := crypto.PGP().Decryption().DecryptionKey(key) if verify != nil { b = b.VerificationKeys(verify) + if !at.IsZero() { + b = b.VerifyTime(at.Unix()) + } } dh, err := b.New() if err != nil { @@ -230,9 +242,13 @@ func decryptArmored(armored string, key *crypto.Key, verify *crypto.KeyRing) ([] } // verifyDetached checks a detached signature, armored or binary per -// encoding, of data against verify. -func verifyDetached(data, sig []byte, encoding int8, verify *crypto.KeyRing) error { - vh, err := crypto.PGP().Verify().VerificationKeys(verify).New() +// encoding, of data against verify at time at, or now if at is zero. +func verifyDetached(data, sig []byte, encoding int8, verify *crypto.KeyRing, at time.Time) error { + b := crypto.PGP().Verify().VerificationKeys(verify) + if !at.IsZero() { + b = b.VerifyTime(at.Unix()) + } + vh, err := b.New() if err != nil { return err } @@ -252,8 +268,9 @@ type unlockFunc func(armoredKey string, passphrase []byte) (*crypto.Key, error) // unlockDriveKey decrypts a node or share key: the passphrase with // parent, its detached signature against verify, then the key itself // with unlock. A bad signature is returned alongside the unlocked key. -func unlockDriveKey(armoredKey string, sealed sealedPassphrase, parent *crypto.Key, verify *crypto.KeyRing, unlock unlockFunc) (*crypto.Key, error) { - passphrase, err := decryptArmored(sealed.armored, parent, nil) +// Signatures are checked at time at, or now if it is zero. +func unlockDriveKey(armoredKey string, sealed sealedPassphrase, parent *crypto.Key, verify *crypto.KeyRing, unlock unlockFunc, at time.Time) (*crypto.Key, error) { + passphrase, err := decryptArmored(sealed.armored, parent, nil, at) if err != nil { return nil, fmt.Errorf("decrypt passphrase: %w", err) } @@ -261,15 +278,15 @@ func unlockDriveKey(armoredKey string, sealed sealedPassphrase, parent *crypto.K if err != nil { return nil, fmt.Errorf("unlock key: %w", err) } - if err := verifyDetached(passphrase, []byte(sealed.signature), crypto.Armor, verify); err != nil { + if err := verifyDetached(passphrase, []byte(sealed.signature), crypto.Armor, verify, at); err != nil { return key, fmt.Errorf("passphrase: %w", err) } return key, nil } // decryptContentKey decrypts a base64 content key packet with nodeKey -// and checks its signature against nodeKey and verify. -func decryptContentKey(packet64, signature string, nodeKey *crypto.Key, verify *crypto.KeyRing) (*crypto.SessionKey, error) { +// and checks its signature against nodeKey and verify at time at. +func decryptContentKey(packet64, signature string, nodeKey *crypto.Key, verify *crypto.KeyRing, at time.Time) (*crypto.SessionKey, error) { keyPacket, err := base64.StdEncoding.DecodeString(packet64) if err != nil { return nil, fmt.Errorf("content key packet: %w", err) @@ -286,15 +303,16 @@ func decryptContentKey(packet64, signature string, nodeKey *crypto.Key, verify * for _, k := range verify.GetKeys() { mustCrypto("key ring", kr.AddKey(k)) } - if err := verifyDetached(sk.Key, []byte(signature), crypto.Armor, kr); err != nil { + if err := verifyDetached(sk.Key, []byte(signature), crypto.Armor, kr, at); err != nil { return sk, fmt.Errorf("content key packet: %w", err) } return sk, nil } // decryptBlock decrypts a block's data packet with sk and checks its -// encrypted signature, decrypted with nodeKey, against verify. -func decryptBlock(data []byte, encSignature string, sk *crypto.SessionKey, nodeKey *crypto.Key, verify *crypto.KeyRing) ([]byte, error) { +// encrypted signature, decrypted with nodeKey, against verify at time +// at. +func decryptBlock(data []byte, encSignature string, sk *crypto.SessionKey, nodeKey *crypto.Key, verify *crypto.KeyRing, at time.Time) ([]byte, error) { dh, err := crypto.PGP().Decryption().SessionKey(sk).New() if err != nil { return nil, err @@ -303,11 +321,11 @@ func decryptBlock(data []byte, encSignature string, sk *crypto.SessionKey, nodeK if err != nil { return nil, fmt.Errorf("decrypt block: %w", err) } - sig, err := decryptArmored(encSignature, nodeKey, nil) + sig, err := decryptArmored(encSignature, nodeKey, nil, at) if err != nil { return nil, fmt.Errorf("decrypt block signature: %w", err) } - if err := verifyDetached(res.Bytes(), sig, crypto.Bytes, verify); err != nil { + if err := verifyDetached(res.Bytes(), sig, crypto.Bytes, verify, at); err != nil { return res.Bytes(), fmt.Errorf("block: %w", err) } return res.Bytes(), nil diff --git a/backend/protondrive/protontest/drive.go b/backend/protondrive/protontest/drive.go index 75551af4d..bf7e6f70f 100644 --- a/backend/protondrive/protontest/drive.go +++ b/backend/protondrive/protontest/drive.go @@ -31,8 +31,9 @@ const ( linkStateActive = 1 linkStateTrashed = 2 - revisionStateDraft = 0 - revisionStateActive = 1 + revisionStateDraft = 0 + revisionStateActive = 1 + revisionStateObsolete = 2 ) const ( @@ -125,6 +126,10 @@ type revision struct { signatureEmail string clientUID string blocks []*block // in index order + + // Draft revisions only. + verificationCode []byte + pending map[int]*pendingBlock // by index; requested for upload } // size returns the encrypted size of r. @@ -307,6 +312,7 @@ type driveView struct { shareKey *crypto.Key shareErr error unlocked map[string]unlockedKey + now time.Time // the server clock, which signatures are checked at } // unlockedKey is a node key with the error from unlocking it, which @@ -327,6 +333,7 @@ func (u *User) view() *driveView { d: *d, keysByEmail: make(map[string][]*crypto.Key), unlocked: make(map[string]unlockedKey), + now: s.nowLocked(), } v.d.links = make(map[string]*link, len(d.links)) for id, l := range d.links { @@ -375,7 +382,7 @@ func (v *driveView) verifier(email string, fallback ...*crypto.Key) *crypto.KeyR // unlockShare returns the share key, decrypted with the address key. func (v *driveView) unlockShare() (*crypto.Key, error) { if v.shareKey == nil && v.shareErr == nil { - v.shareKey, v.shareErr = unlockDriveKey(v.d.shareKey, v.d.sharePass, v.addrKey, v.verifier(v.d.creatorEmail), v.srv.unlockKey) + v.shareKey, v.shareErr = unlockDriveKey(v.d.shareKey, v.d.sharePass, v.addrKey, v.verifier(v.d.creatorEmail), v.srv.unlockKey, v.now) if v.shareKey == nil && v.shareErr == nil { v.shareErr = errors.New("protontest: no share key") } @@ -406,7 +413,7 @@ func (v *driveView) unlock(id string) (*crypto.Key, error) { if parent == nil { u.err = fmt.Errorf("parent of %s: %w", id, err) } else { - u.key, u.err = unlockDriveKey(l.nodeKey, l.nodePass, parent, v.verifier(l.signatureEmail, parent), v.srv.unlockKey) + u.key, u.err = unlockDriveKey(l.nodeKey, l.nodePass, parent, v.verifier(l.signatureEmail, parent), v.srv.unlockKey, v.now) } v.unlocked[id] = u return u.key, u.err @@ -423,7 +430,7 @@ func (v *driveView) folderKeys(id string) (key *crypto.Key, hashKey []byte) { if key == nil { panic(fmt.Sprintf("protontest: unlock folder %s: %v", id, err)) } - hashKey, err = decryptArmored(l.hashKey, key, nil) + hashKey, err = decryptArmored(l.hashKey, key, nil, v.now) mustCrypto("decrypt hash key", err) return key, hashKey } @@ -735,13 +742,13 @@ func (u *User) Corrupt(id string, what string) { change = func(l *link) { l.name = bad } case "name-signature": parent, _ := v.parentKey(l) - name, err := decryptArmored(l.name, parent, nil) + name, err := decryptArmored(l.name, parent, nil, v.now) mustCrypto("decrypt name", err) bad := encryptArmored(name, parent, impostor, false) change = func(l *link) { l.name = bad } case "passphrase-signature": parent, _ := v.parentKey(l) - passphrase, err := decryptArmored(l.nodePass.armored, parent, nil) + passphrase, err := decryptArmored(l.nodePass.armored, parent, nil, v.now) mustCrypto("decrypt passphrase", err) bad := signArmored(passphrase, impostor) change = func(l *link) { l.nodePass.signature = bad } @@ -815,9 +822,9 @@ type DumpedNode struct { } // Dump decrypts u's drive and returns every node except the root and -// drafts, sorted by path. It verifies every signature, block hash and -// extended attribute claim, as a strict client would, and reports -// failures in Err rather than failing. +// drafts, sorted by path. It verifies every signature (at the server +// clock), block hash and extended attribute claim, as a strict client +// would, and reports failures in Err rather than failing. func (u *User) Dump() []DumpedNode { v := u.view() paths := make(map[string]string) @@ -870,7 +877,7 @@ func (v *driveView) path(id string, cache map[string]string) (string, error) { if parent == nil { nameErr = fmt.Errorf("name: %w", err) } else { - plain, err := decryptArmored(l.name, parent, v.verifier(l.nameSignatureEmail, parent)) + plain, err := decryptArmored(l.name, parent, v.verifier(l.nameSignatureEmail, parent), v.now) switch { case plain != nil: name = string(plain) @@ -903,11 +910,11 @@ func (v *driveView) checkNameHash(l *link) error { if parent == nil { return nil } - name, err := decryptArmored(l.name, parent, nil) + name, err := decryptArmored(l.name, parent, nil, v.now) if err != nil { return nil } - hashKey, err := decryptArmored(v.d.links[l.parentID].hashKey, parent, nil) + hashKey, err := decryptArmored(v.d.links[l.parentID].hashKey, parent, nil, v.now) if err != nil { return fmt.Errorf("name hash: parent hash key: %w", err) } @@ -922,11 +929,11 @@ func (v *driveView) checkNameHash(l *link) error { func (v *driveView) dumpFolder(l *link, key *crypto.Key, n *DumpedNode) error { var errs []error verify := keyRing(append([]*crypto.Key{key}, v.keysByEmail[l.signatureEmail]...)...) - if _, err := decryptArmored(l.hashKey, key, verify); err != nil { + if _, err := decryptArmored(l.hashKey, key, verify, v.now); err != nil { errs = append(errs, fmt.Errorf("hash key: %w", err)) } if l.xattr != "" { - plain, err := decryptArmored(l.xattr, key, v.verifier(l.signatureEmail, key)) + plain, err := decryptArmored(l.xattr, key, v.verifier(l.signatureEmail, key), v.now) if err != nil { errs = append(errs, fmt.Errorf("extended attributes: %w", err)) } @@ -951,7 +958,7 @@ func (v *driveView) dumpFile(l *link, key *crypto.Key, n *DumpedNode) error { return errors.New("no active revision") } var errs []error - sk, err := decryptContentKey(l.contentKeyPacket, l.contentKeyPacketSignature, key, v.verifier(l.signatureEmail, key)) + sk, err := decryptContentKey(l.contentKeyPacket, l.contentKeyPacketSignature, key, v.verifier(l.signatureEmail, key), v.now) if err != nil { errs = append(errs, err) } @@ -973,14 +980,14 @@ func (v *driveView) dumpFile(l *link, key *crypto.Key, n *DumpedNode) error { if signer == "" { signer = rev.signatureEmail } - plain, err := decryptBlock(b.data, b.encSignature, sk, key, v.verifier(signer, key)) + plain, err := decryptBlock(b.data, b.encSignature, sk, key, v.verifier(signer, key), v.now) if err != nil { errs = append(errs, fmt.Errorf("block %d: %w", b.index, err)) } n.Content = append(n.Content, plain...) blockSizes = append(blockSizes, int64(len(plain))) } - if err := verifyDetached(manifest, []byte(rev.manifestSignature), crypto.Armor, v.verifier(rev.signatureEmail, key)); err != nil { + if err := verifyDetached(manifest, []byte(rev.manifestSignature), crypto.Armor, v.verifier(rev.signatureEmail, key), v.now); err != nil { errs = append(errs, fmt.Errorf("manifest: %w", err)) } if rev.xattr != "" { @@ -993,7 +1000,7 @@ func (v *driveView) dumpFile(l *link, key *crypto.Key, n *DumpedNode) error { // claims against the decrypted content. func (v *driveView) dumpFileXAttr(rev *revision, key *crypto.Key, blockSizes []int64, n *DumpedNode) error { var errs []error - plain, err := decryptArmored(rev.xattr, key, v.verifier(rev.signatureEmail, key)) + plain, err := decryptArmored(rev.xattr, key, v.verifier(rev.signatureEmail, key), v.now) if err != nil { errs = append(errs, fmt.Errorf("extended attributes: %w", err)) } @@ -1325,6 +1332,7 @@ func (s *Server) registerDrive() { s.handleDrive("GET", "/drive/v2/volumes/{volumeID}/files/{linkID}/revisions/{revisionID}", s.handleRevision) s.handle("GET", "/storage/blocks/{id}", s.handleBlock) s.registerMutations() + s.registerUpload() } // handleDrive registers h for an authenticated route under @@ -1620,22 +1628,22 @@ func (s *Server) handleCreateVolume(w http.ResponseWriter, r *http.Request, u *U // key). func checkVolumeRequest(req *createVolumeRequest, addrKey *crypto.Key, unlock unlockFunc) error { addrKR := keyRing(addrKey) - shareKey, err := unlockDriveKey(req.ShareKey, sealedPassphrase{armored: req.SharePassphrase, signature: req.SharePassphraseSignature}, addrKey, addrKR, unlock) + shareKey, err := unlockDriveKey(req.ShareKey, sealedPassphrase{armored: req.SharePassphrase, signature: req.SharePassphraseSignature}, addrKey, addrKR, unlock, time.Time{}) if err != nil { return fmt.Errorf("share key: %w", err) } - folderKey, err := unlockDriveKey(req.FolderKey, sealedPassphrase{armored: req.FolderPassphrase, signature: req.FolderPassphraseSignature}, shareKey, addrKR, unlock) + folderKey, err := unlockDriveKey(req.FolderKey, sealedPassphrase{armored: req.FolderPassphrase, signature: req.FolderPassphraseSignature}, shareKey, addrKR, unlock, time.Time{}) if err != nil { return fmt.Errorf("folder key: %w", err) } - name, err := decryptArmored(req.FolderName, shareKey, addrKR) + name, err := decryptArmored(req.FolderName, shareKey, addrKR, time.Time{}) if err != nil { return fmt.Errorf("folder name: %w", err) } if len(name) == 0 { return errors.New("empty folder name") } - hashKey, err := decryptArmored(req.FolderHashKey, folderKey, keyRing(folderKey, addrKey)) + hashKey, err := decryptArmored(req.FolderHashKey, folderKey, keyRing(folderKey, addrKey), time.Time{}) if err != nil { return fmt.Errorf("folder hash key: %w", err) } diff --git a/backend/protondrive/protontest/drive_test.go b/backend/protondrive/protontest/drive_test.go index 9c45e7bbb..dd1052b2c 100644 --- a/backend/protondrive/protontest/drive_test.go +++ b/backend/protondrive/protontest/drive_test.go @@ -549,7 +549,7 @@ func TestBlockBodyIsReadable(t *testing.T) { l := v.d.links[file] key, err := v.unlock(file) require.NoError(t, err) - sk, err := decryptContentKey(l.contentKeyPacket, l.contentKeyPacketSignature, key, keyRing(key)) + sk, err := decryptContentKey(l.contentKeyPacket, l.contentKeyPacketSignature, key, keyRing(key), time.Time{}) require.NoError(t, err) var rev revisionResponse @@ -558,7 +558,7 @@ func TestBlockBodyIsReadable(t *testing.T) { b := rev.Revision.Blocks[0] status, data := getBlock(t, s, *b.BareURL, *b.Token) require.Equal(t, http.StatusOK, status) - plain, err := decryptBlock(data, *b.EncSignature, sk, key, keyRing(u.addresses[0].keys[0].key)) + plain, err := decryptBlock(data, *b.EncSignature, sk, key, keyRing(u.addresses[0].keys[0].key), time.Time{}) require.NoError(t, err) assert.Equal(t, "block body", string(plain)) } diff --git a/backend/protondrive/protontest/mutate.go b/backend/protondrive/protontest/mutate.go index 779e6d8b0..467d6eae1 100644 --- a/backend/protondrive/protontest/mutate.go +++ b/backend/protondrive/protontest/mutate.go @@ -323,9 +323,22 @@ func checkMessage(armored string) error { // checkFolderKey returns an error unless armored is a v4 secret key // whose signatures don't advertise AEAD, with every secret key packet // locked with CFB and an iterated and salted S2K, as official clients -// generate folder keys. The official web app can't use a folder key +// generate folder keys. The official web app can't use a node key // locked with Argon2 or AEAD. func checkFolderKey(armored string) error { + return checkNodeKey(armored, false) +} + +// checkFileKey returns an error unless armored is a v4 secret key +// locked as checkFolderKey requires. Unlike a folder key, a file key +// advertises AEAD, for its content. +func checkFileKey(armored string) error { + return checkNodeKey(armored, true) +} + +// checkNodeKey does the work of checkFolderKey and checkFileKey; aead +// allows the key to advertise AEAD. +func checkNodeKey(armored string, aead bool) error { block, err := armor.Decode(strings.NewReader(armored)) if err != nil { return fmt.Errorf("not armored: %w", err) @@ -355,7 +368,7 @@ func checkFolderKey(armored string) error { if err != nil || !ok { return fmt.Errorf("malformed signature: %v", err) } - if sig.SEIPDv2 || len(sig.PreferredCipherSuites) > 0 { + if !aead && (sig.SEIPDv2 || len(sig.PreferredCipherSuites) > 0) { return errors.New("key advertises AEAD (SEIPDv2)") } } @@ -367,7 +380,7 @@ func checkFolderKey(armored string) error { } // checkSecretKeyPacket checks one secret key or subkey packet for -// checkFolderKey. +// checkNodeKey. func checkSecretKeyPacket(op *packet.OpaquePacket) error { if len(op.Contents) == 0 || op.Contents[0] != 4 { return errors.New("not a v4 key") diff --git a/backend/protondrive/protontest/server.go b/backend/protondrive/protontest/server.go index 8e2749e21..a4fd37fb7 100644 --- a/backend/protondrive/protontest/server.go +++ b/backend/protondrive/protontest/server.go @@ -4,8 +4,10 @@ package protontest import ( + "bytes" "encoding/json" "fmt" + "io" "net/http" "net/http/httptest" "regexp" @@ -73,6 +75,9 @@ type Server struct { childrenPageSize int downloads map[string]*download // block URLs by ID unlockedKeys map[string]*crypto.Key // by keyCacheID + uploads map[string]*uploadURL // block upload URLs by ID + storageUploads int // block uploads in progress + storagePeak int // most block uploads in progress at once } // New starts a fake server which is closed when the test ends. @@ -88,6 +93,7 @@ func New(t testing.TB) *Server { childrenPageSize: defaultChildrenPageSize, downloads: make(map[string]*download), unlockedKeys: make(map[string]*crypto.Key), + uploads: make(map[string]*uploadURL), } s.handle("GET", "/tests/ping", func(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]int{"Code": api.CodeOK}) @@ -125,11 +131,13 @@ func (s *Server) Requests() map[string]int { return out } -// ResetRequests zeroes the request counts. +// ResetRequests zeroes the request counts and the peak of +// StorageUploadPeak. func (s *Server) ResetRequests() { s.mu.Lock() defer s.mu.Unlock() clear(s.requests) + s.storagePeak = s.storageUploads } // Inject adds a fault. Faults are checked in the order they were added @@ -165,6 +173,15 @@ func (s *Server) serveHTTP(w http.ResponseWriter, r *http.Request) { s.mu.Lock() s.requests[key]++ w.Header().Set("Date", time.Now().Add(s.clockSkew).UTC().Format(http.TimeFormat)) + if pattern == storageUploadPattern { + s.storageUploads++ + s.storagePeak = max(s.storagePeak, s.storageUploads) + defer func() { + s.mu.Lock() + s.storageUploads-- + s.mu.Unlock() + }() + } s.mu.Unlock() switch { @@ -209,6 +226,11 @@ func (s *Server) activeFault(method, pattern string) *Fault { // serveFault applies f to a request for a registered route. func (s *Server) serveFault(w http.ResponseWriter, r *http.Request, f *Fault) { if f.Delay > 0 { + // The server notices a client giving up, and cancels the request + // context, only once the request body has been read. + if body, err := io.ReadAll(r.Body); err == nil { + r.Body = io.NopCloser(bytes.NewReader(body)) + } select { case <-time.After(f.Delay): case <-r.Context().Done(): diff --git a/backend/protondrive/protontest/upload.go b/backend/protondrive/protontest/upload.go new file mode 100644 index 000000000..3a7f1199c --- /dev/null +++ b/backend/protondrive/protontest/upload.go @@ -0,0 +1,693 @@ +package protontest + +import ( + "bytes" + "crypto/sha256" + "encoding/base64" + "errors" + "fmt" + "io" + "net/http" + "slices" + "sort" + "time" + + "github.com/ProtonMail/go-crypto/openpgp/packet" + "github.com/ProtonMail/gopenpgp/v3/crypto" + "github.com/rclone/rclone/backend/protondrive/api" +) + +const ( + // storageUploadPattern is the route of block uploads. + storageUploadPattern = "/storage/upload/{token}" + + // verificationCodeSize is the size of a draft's verification code, + // and so of each block's verifier token. + verificationCodeSize = 32 + + // maxUploadBlockSize is the largest encrypted block accepted. + maxUploadBlockSize = 8 << 20 + + // intendedSizePrecision is the precision of IntendedUploadSize. + intendedSizePrecision = 100_000 +) + +// pendingBlock is a block of a draft revision requested for upload. +type pendingBlock struct { + index int + encSignature string + token []byte // verifier token + hash []byte // SHA-256 the client declared; nil if none + data []byte // nil until uploaded +} + +// uploadURL is a block upload URL issued by /drive/blocks. +type uploadURL struct { + token string + user *User + linkID string + rev *revision + block *pendingBlock + expired bool +} + +// Wire types of the upload routes, named after and shaped like the +// schemas in the SDK's driveTypes.ts. + +type createFileRequest struct { + ParentLinkID string + Name string + Hash string + MIMEType string + ClientUID *string + IntendedUploadSize *int64 + NodeKey string + NodePassphrase string + NodePassphraseSignature string + ContentKeyPacket string + ContentKeyPacketSignature *string + SignatureAddress *string +} + +type fileResponseJSON struct { + ID string + RevisionID string + ClientUID *string +} + +type createFileResponse struct { + File fileResponseJSON + Code int +} + +type createRevisionRequest struct { + CurrentRevisionID *string + ClientUID *string + IntendedUploadSize *int64 +} + +type revisionIDJSON struct { + ID string +} + +type createRevisionResponse struct { + Revision revisionIDJSON + Code int +} + +type verificationResponse struct { + VerificationCode string + ContentKeyPacket string + Code int +} + +type verifierJSON struct { + Token string +} + +type blockUploadInput struct { + Index int + Verifier *verifierJSON + EncSignature *string + Size *int64 + Hash *string +} + +type blockUploadRequest struct { + LinkID string + RevisionID string + AddressID *string + VolumeID *string + BlockList []blockUploadInput + ThumbnailList []struct{ Type int } +} + +type blockURLJSON struct { + BareURL string + Token string + URL string + Index int +} + +type blockUploadResponse struct { + UploadLinks []blockURLJSON + ThumbnailLinks []struct{} + Code int +} + +type commitRevisionRequest struct { + ManifestSignature string + SignatureAddress *string + XAttr *string + ChecksumVerified bool + Photo *struct{} +} + +// registerUpload registers the routes which upload files. +func (s *Server) registerUpload() { + s.handleDrive("POST", "/drive/v2/volumes/{volumeID}/files", s.handleCreateFile) + s.handleDrive("POST", "/drive/v2/volumes/{volumeID}/files/{linkID}/revisions", s.handleCreateRevision) + s.handleDrive("GET", "/drive/v2/volumes/{volumeID}/links/{linkID}/revisions/{revisionID}/verification", s.handleVerification) + s.handleAuth("POST", "/drive/blocks", s.handleRequestUpload) + s.handle("POST", storageUploadPattern, s.handleStorageUpload) + s.handleDrive("PUT", "/drive/v2/volumes/{volumeID}/files/{linkID}/revisions/{revisionID}", s.handleCommit) + s.handleDrive("DELETE", "/drive/v2/volumes/{volumeID}/files/{linkID}/revisions/{revisionID}", s.handleDeleteRevision) + s.handleDrive("POST", "/drive/v2/volumes/{volumeID}/delete_multiple", s.handleDeleteMultiple) +} + +// ExpireUploadTokens makes every block upload URL issued so far answer +// HTTP 404, as an expired one does. +func (s *Server) ExpireUploadTokens() { + s.mu.Lock() + defer s.mu.Unlock() + for _, up := range s.uploads { + up.expired = true + } +} + +// StorageUploadPeak returns the most block uploads that were in +// progress at once since the server started or ResetRequests. +func (s *Server) StorageUploadPeak() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.storagePeak +} + +// nowLocked returns the server's clock. srv.mu must be held. +func (s *Server) nowLocked() time.Time { + return time.Now().Add(s.clockSkew) +} + +// newDraftRevision returns a draft revision created by clientUID. +func newDraftRevision(clientUID *string) *revision { + r := &revision{ + id: randomID(), + state: revisionStateDraft, + createTime: time.Now().Unix(), + verificationCode: randomBytes(verificationCodeSize), + pending: make(map[int]*pendingBlock), + } + if clientUID != nil { + r.clientUID = *clientUID + } + return r +} + +// checkIntendedSize returns an error if size, when given, is not +// rounded as the SDK rounds it: the server must not learn the size. +func checkIntendedSize(size *int64) error { + if size == nil { + return nil + } + if *size < 0 || (*size%intendedSizePrecision != 0 && *size != 4095) { + return fmt.Errorf("IntendedUploadSize %d is not rounded", *size) + } + return nil +} + +// checkContentKeyPacket returns an error unless packet64 is the base64 +// of one v6 PKESK: new content is written in the RFC 9580 format. +func checkContentKeyPacket(packet64 string) error { + raw, err := base64.StdEncoding.DecodeString(packet64) + if err != nil { + return fmt.Errorf("not base64: %w", err) + } + r := packet.NewOpaqueReader(bytes.NewReader(raw)) + op, err := r.Next() + if err != nil { + return fmt.Errorf("malformed packet: %w", err) + } + if op.Tag != tagPKESK || len(op.Contents) == 0 || op.Contents[0] != 6 { + return fmt.Errorf("packet with tag %d version %d, want a v6 PKESK", op.Tag, firstByte(op.Contents)) + } + if _, err := r.Next(); err != io.EOF { + return errors.New("more than one packet") + } + return nil +} + +// contentKeyVersion returns the version of the PKESK of a stored +// content key packet, or -1. +func contentKeyVersion(packet64 string) int { + raw, err := base64.StdEncoding.DecodeString(packet64) + if err != nil { + return -1 + } + op, err := packet.NewOpaqueReader(bytes.NewReader(raw)).Next() + if err != nil || op.Tag != tagPKESK { + return -1 + } + return int(firstByte(op.Contents)) +} + +// checkBlockFormat returns an error unless data is one SEIPD packet of +// version: SEIPDv2 for content whose key packet is a v6 PKESK, SEIPDv1 +// for a v3 one. +func checkBlockFormat(data []byte, version int) error { + r := packet.NewOpaqueReader(bytes.NewReader(data)) + op, err := r.Next() + if err != nil { + return fmt.Errorf("malformed packet: %w", err) + } + if op.Tag != tagSEIPD || int(firstByte(op.Contents)) != version { + return fmt.Errorf("packet with tag %d version %d, want SEIPDv%d", op.Tag, firstByte(op.Contents), version) + } + if _, err := r.Next(); err != io.EOF { + return errors.New("more than one packet") + } + return nil +} + +// firstByte returns b[0], or 0 if b is empty. +func firstByte(b []byte) byte { + if len(b) == 0 { + return 0 + } + return b[0] +} + +// draftRevision returns the draft revision id of file l, or nil. +func draftRevision(l *link, id string) *revision { + if l == nil || l.typ != linkTypeFile { + return nil + } + for _, r := range l.revisions { + if r.id == id && r.state == revisionStateDraft { + return r + } + } + return nil +} + +// handleCreateFile creates a draft file, with a draft revision, from +// key material the client generated. +func (s *Server) handleCreateFile(w http.ResponseWriter, r *http.Request, u *User, d *drive) { + var req createFileRequest + if !decodeRequest(w, r, &req) { + return + } + parent := d.activeFolder(req.ParentLinkID) + if parent == nil { + writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Parent folder not found") + return + } + err := errors.Join( + checkHash(req.Hash), + checkSigner(u, "SignatureAddress", req.SignatureAddress), + checkMessages(map[string]string{"Name": req.Name, "NodePassphrase": req.NodePassphrase}), + annotateField("ContentKeyPacket", checkContentKeyPacket(req.ContentKeyPacket)), + checkIntendedSize(req.IntendedUploadSize), + ) + switch { + case err != nil: + case req.NodePassphraseSignature == "": + err = errors.New("NodePassphraseSignature is required") + case req.ContentKeyPacketSignature == nil || *req.ContentKeyPacketSignature == "": + err = errors.New("ContentKeyPacketSignature is required") + case req.MIMEType == "": + err = errors.New("MIMEType is required") + default: + err = annotateField("NodeKey", checkFileKey(req.NodeKey)) + } + if err != nil { + writeInvalid(w, err) + return + } + if other := d.conflict(parent.id, req.Hash, ""); other != nil { + writeConflict(w, other) + return + } + now := time.Now().Unix() + rev := newDraftRevision(req.ClientUID) + l := &link{ + id: randomID(), + parentID: parent.id, + typ: linkTypeFile, + state: linkStateDraft, + createTime: now, + modifyTime: now, + name: req.Name, + nameHash: req.Hash, + nodeKey: req.NodeKey, + nodePass: sealedPassphrase{armored: req.NodePassphrase, signature: req.NodePassphraseSignature}, + signatureEmail: *req.SignatureAddress, + nameSignatureEmail: *req.SignatureAddress, + mediaType: req.MIMEType, + contentKeyPacket: req.ContentKeyPacket, + contentKeyPacketSignature: *req.ContentKeyPacketSignature, + revisions: []*revision{rev}, + } + d.addLink(l) + writeJSON(w, http.StatusOK, &createFileResponse{ + File: fileResponseJSON{ID: l.id, RevisionID: rev.id, ClientUID: nullable(rev.clientUID)}, + Code: api.CodeOK, + }) +} + +// handleCreateRevision creates a draft revision of an active file whose +// active revision is CurrentRevisionID. +func (s *Server) handleCreateRevision(w http.ResponseWriter, r *http.Request, u *User, d *drive) { + var req createRevisionRequest + if !decodeRequest(w, r, &req) { + return + } + l := d.activeLink(r.PathValue("linkID")) + if l == nil || l.typ != linkTypeFile { + writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "File not found") + return + } + if err := checkIntendedSize(req.IntendedUploadSize); err != nil { + writeInvalid(w, err) + return + } + active := l.activeRevision() + if active == nil || req.CurrentRevisionID == nil || *req.CurrentRevisionID != active.id { + writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidRequirements, "protontest: CurrentRevisionID is not the active revision: the file changed") + return + } + rev := newDraftRevision(req.ClientUID) + l.revisions = append(l.revisions, rev) + writeJSON(w, http.StatusOK, &createRevisionResponse{Revision: revisionIDJSON{ID: rev.id}, Code: api.CodeOK}) +} + +// handleVerification returns the verification code and content key +// packet of a draft revision. +func (s *Server) handleVerification(w http.ResponseWriter, r *http.Request, u *User, d *drive) { + l := d.links[r.PathValue("linkID")] + rev := draftRevision(l, r.PathValue("revisionID")) + if rev == nil { + writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Revision not found") + return + } + writeJSON(w, http.StatusOK, &verificationResponse{ + VerificationCode: base64.StdEncoding.EncodeToString(rev.verificationCode), + ContentKeyPacket: l.contentKeyPacket, + Code: api.CodeOK, + }) +} + +// handleRequestUpload issues upload URLs on this server for blocks of a +// draft revision. Requesting a block again replaces it, and its URL. +func (s *Server) handleRequestUpload(w http.ResponseWriter, r *http.Request, u *User) { + var req blockUploadRequest + if !decodeRequest(w, r, &req) { + return + } + s.mu.Lock() + defer s.mu.Unlock() + d := u.drive + if d == nil || req.VolumeID == nil || *req.VolumeID != d.volumeID { + writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Volume not found") + return + } + l := d.links[req.LinkID] + rev := draftRevision(l, req.RevisionID) + if rev == nil { + writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Revision not found") + return + } + if req.AddressID == nil || !slices.ContainsFunc(u.addresses, func(a *address) bool { return a.id == *req.AddressID }) { + writeInvalid(w, errors.New("AddressID must be an address of the user")) + return + } + if len(req.ThumbnailList) > 0 { + writeInvalid(w, errors.New("protontest: thumbnails are not supported")) + return + } + blocks := make([]*pendingBlock, 0, len(req.BlockList)) + for _, in := range req.BlockList { + b, err := pendingBlockOf(in) + if err != nil { + writeInvalid(w, fmt.Errorf("block %d: %w", in.Index, err)) + return + } + blocks = append(blocks, b) + } + resp := &blockUploadResponse{UploadLinks: []blockURLJSON{}, ThumbnailLinks: []struct{}{}, Code: api.CodeOK} + for _, b := range blocks { + rev.pending[b.index] = b + id, token := randomID(), randomID() + s.uploads[id] = &uploadURL{token: token, user: u, linkID: l.id, rev: rev, block: b} + bareURL := s.URL() + "/storage/upload/" + id + resp.UploadLinks = append(resp.UploadLinks, blockURLJSON{BareURL: bareURL, Token: token, URL: bareURL, Index: b.index}) + } + writeJSON(w, http.StatusOK, resp) +} + +// pendingBlockOf returns the block in an upload request, checked. +func pendingBlockOf(in blockUploadInput) (*pendingBlock, error) { + b := &pendingBlock{index: in.Index} + if in.Index < 1 { + return nil, errors.New("field Index must be at least 1") + } + if in.Verifier == nil { + return nil, errors.New("field Verifier is required") + } + token, err := base64.StdEncoding.DecodeString(in.Verifier.Token) + if err != nil || len(token) != verificationCodeSize { + return nil, fmt.Errorf("Verifier.Token is not the base64 of %d bytes", verificationCodeSize) + } + b.token = token + if in.EncSignature == nil || *in.EncSignature == "" { + return nil, errors.New("EncSignature is required") + } + b.encSignature = *in.EncSignature + if in.Hash != nil { + if b.hash, err = base64.StdEncoding.DecodeString(*in.Hash); err != nil || len(b.hash) != sha256.Size { + return nil, errors.New("field Hash is not the base64 of a SHA-256") + } + } + return b, nil +} + +// handleStorageUpload stores the block of a multipart upload to a URL +// issued by handleRequestUpload, which carries its pm-storage-token and +// none of the session's credentials. +func (s *Server) handleStorageUpload(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "" || r.Header.Get("x-pm-uid") != "" { + writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: session credentials must not be sent to the storage host") + return + } + s.mu.Lock() + up := s.uploads[r.PathValue("token")] + s.mu.Unlock() + switch { + case up == nil || up.expired: + writeError(w, http.StatusNotFound, api.CodeNotExists, "protontest: no such upload URL, or it expired") + return + case r.Header.Get("pm-storage-token") != up.token: + writeError(w, http.StatusForbidden, api.CodeNotEnoughPermissions, "protontest: missing or wrong pm-storage-token") + return + } + data, err := readBlockPart(r) + if err != nil { + writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: bad block upload: "+err.Error()) + return + } + s.mu.Lock() + defer s.mu.Unlock() + if up.rev.state != revisionStateDraft || up.rev.pending[up.block.index] != up.block { + writeError(w, http.StatusNotFound, api.CodeNotExists, "protontest: the block is no longer awaited") + return + } + up.block.data = data + writeJSON(w, http.StatusOK, &codeJSON{Code: api.CodeOK}) +} + +// readBlockPart returns the content of the one part, named Block, of +// the multipart body of r. +func readBlockPart(r *http.Request) ([]byte, error) { + mr, err := r.MultipartReader() + if err != nil { + return nil, err + } + var data []byte + for { + part, err := mr.NextPart() + if err == io.EOF { + break + } + if err != nil { + return nil, err + } + if part.FormName() != "Block" || data != nil { + return nil, fmt.Errorf("unexpected part %q", part.FormName()) + } + if data, err = io.ReadAll(io.LimitReader(part, maxUploadBlockSize+1)); err != nil { + return nil, err + } + if len(data) > maxUploadBlockSize { + return nil, fmt.Errorf("block larger than %d bytes", maxUploadBlockSize) + } + } + if len(data) == 0 { + return nil, errors.New("no Block part, or it is empty") + } + return data, nil +} + +// handleCommit makes a draft revision with every requested block +// uploaded the file's active revision, after checking each block's +// verifier token and format, the manifest signature over the uploaded +// blocks and the extended attributes' format. +func (s *Server) handleCommit(w http.ResponseWriter, r *http.Request, u *User, d *drive) { + var req commitRevisionRequest + if !decodeRequest(w, r, &req) { + return + } + l := d.links[r.PathValue("linkID")] + rev := draftRevision(l, r.PathValue("revisionID")) + if rev == nil { + writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Revision not found") + return + } + xattr := "" + if req.XAttr != nil { + xattr = *req.XAttr + } + err := errors.Join( + checkSigner(u, "SignatureAddress", req.SignatureAddress), + checkMessages(map[string]string{"XAttr": xattr}), + ) + if err == nil && req.ManifestSignature == "" { + err = errors.New("ManifestSignature is required") + } + if err != nil { + writeInvalid(w, err) + return + } + blocks, err := uploadedBlocks(rev, *req.SignatureAddress) + if err != nil { + writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidRequirements, "protontest: "+err.Error()) + return + } + var manifest []byte + var formatErrs []error + version := 1 + if contentKeyVersion(l.contentKeyPacket) == 6 { + version = 2 + } + for _, b := range blocks { + manifest = append(manifest, b.hash...) + formatErrs = append(formatErrs, annotateField(fmt.Sprintf("block %d", b.index), checkBlockFormat(b.data, version))) + } + addr := u.addressByEmailLocked(*req.SignatureAddress) + keys := make([]*crypto.Key, 0, len(addr.keys)) + for _, k := range addr.keys { + keys = append(keys, k.key) + } + sigErr := verifyDetached(manifest, []byte(req.ManifestSignature), crypto.Armor, keyRing(keys...), s.nowLocked()) + if err := errors.Join(append(formatErrs, annotateField("manifest", sigErr))...); err != nil { + writeInvalid(w, err) + return + } + for _, other := range l.revisions { + if other.state == revisionStateActive { + other.state = revisionStateObsolete + } + } + now := time.Now().Unix() + rev.state, rev.createTime = revisionStateActive, now + rev.manifestSignature, rev.xattr, rev.signatureEmail = req.ManifestSignature, xattr, *req.SignatureAddress + rev.blocks, rev.pending, rev.verificationCode = blocks, nil, nil + l.state, l.modifyTime = linkStateActive, now + s.dropUploadsLocked(rev) + writeJSON(w, http.StatusOK, &codeJSON{Code: api.CodeOK}) +} + +// uploadedBlocks returns the blocks of draft rev, signed by email, after +// checking that blocks 1 to n were requested and each uploaded, with the +// hash it was declared with, if any, and its verifier token. +func uploadedBlocks(rev *revision, email string) ([]*block, error) { + indexes := make([]int, 0, len(rev.pending)) + for i := range rev.pending { + indexes = append(indexes, i) + } + sort.Ints(indexes) + blocks := make([]*block, 0, len(indexes)) + for i, index := range indexes { + p := rev.pending[index] + switch { + case index != i+1: + return nil, fmt.Errorf("block %d was not requested", i+1) + case p.data == nil: + return nil, fmt.Errorf("block %d was not uploaded", index) + } + sum := sha256.Sum256(p.data) + if p.hash != nil && !bytes.Equal(p.hash, sum[:]) { + return nil, fmt.Errorf("block %d: declared hash doesn't match the uploaded block", index) + } + if want := xorPrefix(rev.verificationCode, p.data); !bytes.Equal(p.token, want) { + return nil, fmt.Errorf("block %d: verifier token doesn't match the uploaded block", index) + } + blocks = append(blocks, &block{index: index, hash: sum[:], data: p.data, encSignature: p.encSignature, signatureEmail: email}) + } + return blocks, nil +} + +// xorPrefix returns code XOR the start of data, padded with zeros: the +// verifier token of a block. +func xorPrefix(code, data []byte) []byte { + out := make([]byte, len(code)) + for i := range code { + out[i] = code[i] + if i < len(data) { + out[i] ^= data[i] + } + } + return out +} + +// dropUploadsLocked forgets the upload URLs of rev. srv.mu must be +// held. +func (s *Server) dropUploadsLocked(rev *revision) { + for id, up := range s.uploads { + if up.rev == rev { + delete(s.uploads, id) + } + } +} + +// handleDeleteRevision deletes a draft revision. +func (s *Server) handleDeleteRevision(w http.ResponseWriter, r *http.Request, u *User, d *drive) { + l := d.links[r.PathValue("linkID")] + rev := draftRevision(l, r.PathValue("revisionID")) + if rev == nil { + writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Draft revision not found") + return + } + l.revisions = slices.DeleteFunc(l.revisions, func(other *revision) bool { return other == rev }) + s.dropUploadsLocked(rev) + writeJSON(w, http.StatusOK, &codeJSON{Code: api.CodeOK}) +} + +// handleDeleteMultiple permanently deletes up to 100 draft links, +// answering for each. +func (s *Server) handleDeleteMultiple(w http.ResponseWriter, r *http.Request, u *User, d *drive) { + var req linksRequest + if !decodeRequest(w, r, &req) { + return + } + if len(req.LinkIDs) > maxLinksPerRequest { + writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidValue, fmt.Sprintf("protontest: %d link IDs, at most %d allowed", len(req.LinkIDs), maxLinksPerRequest)) + return + } + resp := &multiResponse{Code: api.CodeOKMany, Responses: []linkResultJSON{}} + for _, id := range req.LinkIDs { + result := linkResultJSON{LinkID: id, Response: codeJSON{Code: api.CodeOK}} + l := d.links[id] + switch { + case l == nil: + result.Response = codeJSON{Code: api.CodeNotExists, Error: "File or folder not found"} + case l.state != linkStateDraft: + result.Response = codeJSON{Code: api.CodeInvalidRequirements, Error: "protontest: only drafts can be deleted"} + default: + for _, rev := range l.revisions { + s.dropUploadsLocked(rev) + } + delete(d.links, id) + } + resp.Responses = append(resp.Responses, result) + } + writeJSON(w, http.StatusOK, resp) +} diff --git a/backend/protondrive/protontest/upload_test.go b/backend/protondrive/protontest/upload_test.go new file mode 100644 index 000000000..395952178 --- /dev/null +++ b/backend/protondrive/protontest/upload_test.go @@ -0,0 +1,502 @@ +package protontest + +import ( + "bytes" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "io" + "mime/multipart" + "net/http" + "strconv" + "testing" + "time" + + "github.com/ProtonMail/go-crypto/openpgp/packet" + "github.com/ProtonMail/go-crypto/openpgp/s2k" + "github.com/ProtonMail/gopenpgp/v3/crypto" + "github.com/ProtonMail/gopenpgp/v3/profile" + "github.com/rclone/rclone/backend/protondrive/api" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const testClientUID = "fake-test-client" + +// uploader uploads files to the root of a user's drive as the SDK +// does, step by step, for tests to spoil one step. +type uploader struct { + t *testing.T + s *Server + u *User + sess Session + volume string +} + +func newUploader(t *testing.T) *uploader { + s := New(t) + u := s.AddUser("user", "pass") + return &uploader{t: t, s: s, u: u, sess: s.NewSession(u), volume: u.VolumeID()} +} + +// fileDraft is a file being uploaded, with its keys. +type fileDraft struct { + req *createFileRequest + node lockedKey + ck contentKey + signer *crypto.Key + linkID string + revID string + code []byte + content []byte +} + +// newFileRequest returns a create file request for name in the root +// made as the SDK's createDraft does. +func (x *uploader) newFileRequest(name string) *fileDraft { + v := x.u.view() + parentKey, parentHashKey := v.folderKeys(v.d.rootID) + node := newDriveKey(true) + x.s.rememberKey(node) + pass := sealPassphrase(node.passphrase, parentKey, v.addrKey) + ck := newContentKey(node.key, true) + uid := testClientUID + return &fileDraft{ + req: &createFileRequest{ + ParentLinkID: v.d.rootID, + Name: encryptArmored([]byte(name), parentKey, v.addrKey, false), + Hash: lookupHash(parentHashKey, name), + MIMEType: "text/plain", + ClientUID: &uid, + NodeKey: node.armored, + NodePassphrase: pass.armored, + NodePassphraseSignature: pass.signature, + ContentKeyPacket: ck.packet, + ContentKeyPacketSignature: &ck.signature, + SignatureAddress: &v.email, + }, + node: node, + ck: ck, + signer: v.addrKey, + } +} + +// send sends in with method to path as the user. +func (x *uploader) send(method, path string, in any) (int, []byte) { + return sendJSON(x.t, x.s, x.sess, method, path, in) +} + +// create creates the draft of f, failing the test if it can't. +func (x *uploader) create(f *fileDraft) { + t := x.t + status, body := x.send("POST", "/drive/v2/volumes/"+x.volume+"/files", f.req) + require.Equal(t, http.StatusOK, status, "body: %s", body) + var resp createFileResponse + require.NoError(t, json.Unmarshal(body, &resp)) + f.linkID, f.revID = resp.File.ID, resp.File.RevisionID + x.loadCode(f) +} + +// loadCode fetches the verification code of f's draft revision. +func (x *uploader) loadCode(f *fileDraft) { + var ver verificationResponse + status, body := getJSON(x.t, x.s, x.sess, "/drive/v2/volumes/"+x.volume+"/links/"+f.linkID+"/revisions/"+f.revID+"/verification", &ver) + require.Equal(x.t, http.StatusOK, status, "body: %s", body) + code, err := base64.StdEncoding.DecodeString(ver.VerificationCode) + require.NoError(x.t, err) + require.Len(x.t, code, verificationCodeSize) + assert.Equal(x.t, f.ck.packet, ver.ContentKeyPacket) + f.code = code +} + +// testBlock is an encrypted block with its upload request entry. +type testBlock struct { + data []byte + in blockUploadInput +} + +// encrypt encrypts content as f's blocks of blockSize. +func (f *fileDraft) encrypt(content []byte) []testBlock { + f.content = content + var blocks []testBlock + for i := 0; i < len(content); i += blockSize { + data, encSig := f.ck.encryptBlock(content[i:min(i+blockSize, len(content))], f.node.key, f.signer) + blocks = append(blocks, testBlock{data: data, in: blockUploadInput{ + Index: len(blocks) + 1, + Verifier: &verifierJSON{Token: base64.StdEncoding.EncodeToString(xorPrefix(f.code, data))}, + EncSignature: &encSig, + }}) + } + return blocks +} + +// requestURLs requests upload URLs for blocks of f. +func (x *uploader) requestURLs(f *fileDraft, blocks []testBlock) (int, []byte, []blockURLJSON) { + addressID := x.u.addresses[0].id + req := &blockUploadRequest{LinkID: f.linkID, RevisionID: f.revID, AddressID: &addressID, VolumeID: &x.volume} + for _, b := range blocks { + req.BlockList = append(req.BlockList, b.in) + } + status, body := x.send("POST", "/drive/blocks", req) + var resp blockUploadResponse + if status == http.StatusOK { + require.NoError(x.t, json.Unmarshal(body, &resp)) + } + return status, body, resp.UploadLinks +} + +// putBlock uploads data to link as the SDK does, with extra headers, +// and returns the HTTP status. +func (x *uploader) putBlock(link blockURLJSON, data []byte, header map[string]string) int { + t := x.t + var body bytes.Buffer + mw := multipart.NewWriter(&body) + w, err := mw.CreateFormFile("Block", "blob") + require.NoError(t, err) + _, err = w.Write(data) + require.NoError(t, err) + require.NoError(t, mw.Close()) + req, err := http.NewRequest("POST", link.BareURL, &body) + require.NoError(t, err) + req.Header.Set("Content-Type", mw.FormDataContentType()) + req.Header.Set("x-pm-appversion", testAppVersion) + req.Header.Set("pm-storage-token", link.Token) + for k, v := range header { + req.Header.Set(k, v) + } + resp, err := x.s.Client().Do(req) + require.NoError(t, err) + _, _ = io.Copy(io.Discard, resp.Body) + _ = resp.Body.Close() + return resp.StatusCode +} + +// uploadAll requests URLs for blocks and uploads each. +func (x *uploader) uploadAll(f *fileDraft, blocks []testBlock) { + status, body, links := x.requestURLs(f, blocks) + require.Equal(x.t, http.StatusOK, status, "body: %s", body) + require.Len(x.t, links, len(blocks)) + for i, link := range links { + require.Equal(x.t, blocks[i].in.Index, link.Index) + require.Equal(x.t, http.StatusOK, x.putBlock(link, blocks[i].data, nil)) + } +} + +// commitRequest returns the commit request of f with blocks, as the SDK +// makes it. +func (f *fileDraft) commitRequest(blocks []testBlock) *commitRevisionRequest { + var manifest []byte + var sizes []int64 + for i, b := range blocks { + sum := sha256.Sum256(b.data) + manifest = append(manifest, sum[:]...) + sizes = append(sizes, int64(min(blockSize, len(f.content)-i*blockSize))) + } + xattr := encryptArmored(newFileXAttr(f.content, sizes, "2024-01-02T03:04:05.000Z"), f.node.key, f.signer, true) + return &commitRevisionRequest{ + ManifestSignature: signArmored(manifest, f.signer), + SignatureAddress: f.req.SignatureAddress, + XAttr: &xattr, + } +} + +// commit commits f's draft revision with req. +func (x *uploader) commit(f *fileDraft, req *commitRevisionRequest) (int, []byte) { + return x.send("PUT", "/drive/v2/volumes/"+x.volume+"/files/"+f.linkID+"/revisions/"+f.revID, req) +} + +func TestCreateFileFormats(t *testing.T) { + x := newUploader(t) + post := func(f *fileDraft) (int, []byte) { + return x.send("POST", "/drive/v2/volumes/"+x.volume+"/files", f.req) + } + for variant, bad := range aeadMessages(t) { + for field, spoil := range map[string]func(req *createFileRequest){ + "Name": func(req *createFileRequest) { req.Name = bad }, + "NodePassphrase": func(req *createFileRequest) { req.NodePassphrase = bad }, + } { + t.Run(field+" "+variant, func(t *testing.T) { + f := x.newFileRequest("f") + spoil(f.req) + status, body := post(f) + requireRejected(t, api.CodeInvalidValue, status, body, field) + }) + } + } + + aeadLocked := profile.Default() + aeadLocked.AeadKeyEncryption = &packet.AEADConfig{} + salted := profile.Default() + salted.S2kKeyEncryption = &s2k.Config{S2KMode: s2k.SaltedS2K, PassphraseIsHighEntropy: true} + v6Key, err := crypto.PGPWithProfile(profile.RFC9580()).KeyGeneration().AddUserId(driveKeyName, "").New().GenerateKey() + require.NoError(t, err) + v6Locked, err := crypto.PGPWithProfile(profile.RFC9580()).LockKey(v6Key, newPassphrase()) + require.NoError(t, err) + v6Armored, err := v6Locked.Armor() + require.NoError(t, err) + for name, tc := range map[string]struct { + key string + want string + }{ + "v6": {v6Armored, "not a v4 key"}, + "AEAD locked": {lockedWith(t, aeadLocked), "locked with AEAD"}, + "salted S2K": {lockedWith(t, salted), "S2K mode 1"}, + } { + t.Run("NodeKey "+name, func(t *testing.T) { + f := x.newFileRequest("f") + f.req.NodeKey = tc.key + status, body := post(f) + requireRejected(t, api.CodeInvalidValue, status, body, "NodeKey", tc.want) + }) + } + + legacy := newContentKey(newDriveKey(false).key, false) + unrounded := int64(123_456) + for name, tc := range map[string]struct { + spoil func(req *createFileRequest) + want string + }{ + "v3 content key packet": {func(req *createFileRequest) { req.ContentKeyPacket = legacy.packet }, "v6 PKESK"}, + "no content key sig": {func(req *createFileRequest) { req.ContentKeyPacketSignature = nil }, "ContentKeyPacketSignature"}, + "no passphrase sig": {func(req *createFileRequest) { req.NodePassphraseSignature = "" }, "NodePassphraseSignature"}, + "unrounded size": {func(req *createFileRequest) { req.IntendedUploadSize = &unrounded }, "IntendedUploadSize"}, + "no signer": {func(req *createFileRequest) { req.SignatureAddress = nil }, "SignatureAddress"}, + "no media type": {func(req *createFileRequest) { req.MIMEType = "" }, "MIMEType"}, + } { + t.Run(name, func(t *testing.T) { + f := x.newFileRequest("f") + tc.spoil(f.req) + status, body := post(f) + requireRejected(t, api.CodeInvalidValue, status, body, tc.want) + }) + } + assert.Empty(t, x.u.Drafts()) + + // The name hash must be unique, and a conflict names the draft and + // its creator. + f := x.newFileRequest("f") + rounded := int64(200_000) + f.req.IntendedUploadSize = &rounded + x.create(f) + assert.Equal(t, []string{f.linkID}, x.u.Drafts()) + status, body := post(x.newFileRequest("f")) + requireRejected(t, api.CodeAlreadyExists, status, body) + var conflict conflictResponse + require.NoError(t, json.Unmarshal(body, &conflict)) + assert.Equal(t, f.linkID, conflict.Details.ConflictLinkID) + assert.Nil(t, conflict.Details.ConflictRevisionID) + require.NotNil(t, conflict.Details.ConflictDraftRevisionID) + assert.Equal(t, f.revID, *conflict.Details.ConflictDraftRevisionID) + require.NotNil(t, conflict.Details.ConflictDraftClientUID) + assert.Equal(t, testClientUID, *conflict.Details.ConflictDraftClientUID) + assert.Empty(t, x.u.Dump(), "a draft is dumped") +} + +func TestCommitChecks(t *testing.T) { + x := newUploader(t) + content := patterned(blockSize + 1000) + n := 0 + // prepare returns a new draft with content encrypted, its blocks + // and their commit request. + prepare := func() (*fileDraft, []testBlock, *commitRevisionRequest) { + n++ + f := x.newFileRequest("f" + strconv.Itoa(n)) + x.create(f) + blocks := f.encrypt(content) + return f, blocks, f.commitRequest(blocks) + } + impostor := generateKey("impostor", "impostor@proton.test") + empty := "" + aead := aeadMessages(t)["v6 PKESK and SEIPDv2"] + legacy := newContentKey(newDriveKey(false).key, false) + otherHash := base64.StdEncoding.EncodeToString(make([]byte, sha256.Size)) + for name, tc := range map[string]struct { + spoil func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock + code int + want string + }{ + "AEAD XAttr": {func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock { + req.XAttr = &aead + return blocks + }, api.CodeInvalidValue, "XAttr"}, + "empty XAttr": {func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock { + req.XAttr = &empty + return blocks + }, api.CodeInvalidValue, "XAttr"}, + "no XAttr": {func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock { + req.XAttr = nil + return blocks + }, api.CodeInvalidValue, "XAttr"}, + "verifier": {func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock { + token := xorPrefix(f.code, blocks[1].data) + token[5] ^= 1 + blocks[1].in.Verifier.Token = base64.StdEncoding.EncodeToString(token) + return blocks + }, api.CodeInvalidRequirements, "block 2: verifier token"}, + "block not uploaded": {func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock { + _, _, links := x.requestURLs(f, blocks[1:]) + require.Len(t, links, 1) + return blocks[:1] + }, api.CodeInvalidRequirements, "block 2 was not uploaded"}, + "index gap": {func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock { + blocks[1].in.Index = 3 + return blocks + }, api.CodeInvalidRequirements, "block 2 was not requested"}, + "declared hash": {func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock { + blocks[0].in.Hash = &otherHash + return blocks + }, api.CodeInvalidRequirements, "declared hash"}, + "manifest": {func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock { + req.ManifestSignature = signArmored([]byte("not the manifest"), f.signer) + return blocks + }, api.CodeInvalidValue, "manifest"}, + "manifest signer": {func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock { + var manifest []byte + for _, b := range blocks { + sum := sha256.Sum256(b.data) + manifest = append(manifest, sum[:]...) + } + req.ManifestSignature = signArmored(manifest, impostor) + return blocks + }, api.CodeInvalidValue, "manifest"}, + "SEIPDv1 block": {func(f *fileDraft, blocks []testBlock, req *commitRevisionRequest) []testBlock { + data, _ := legacy.encryptBlock(content[blockSize:], f.node.key, f.signer) + blocks[1].data = data + blocks[1].in.Verifier.Token = base64.StdEncoding.EncodeToString(xorPrefix(f.code, data)) + *req = *f.commitRequest(blocks) + return blocks + }, api.CodeInvalidValue, "block 2: packet with tag 18 version 1, want SEIPDv2"}, + } { + t.Run(name, func(t *testing.T) { + f, blocks, req := prepare() + blocks = tc.spoil(f, blocks, req) + x.uploadAll(f, blocks) + status, body := x.commit(f, req) + requireRejected(t, tc.code, status, body, tc.want) + assert.Contains(t, x.u.Drafts(), f.linkID) + }) + } + assert.Empty(t, x.u.Dump(), "a draft was committed") + + f, blocks, req := prepare() + x.uploadAll(f, blocks) + status, body := x.commit(f, req) + require.Equal(t, http.StatusOK, status, "body: %s", body) + dump := x.u.Dump() + require.Len(t, dump, 1) + assert.NoError(t, dump[0].Err) + assert.Equal(t, f.linkID, dump[0].ID) + assert.True(t, bytes.Equal(content, dump[0].Content)) + assert.NotContains(t, x.u.Drafts(), f.linkID) + + // A committed revision can't be committed again or deleted as a + // draft. + status, body = x.commit(f, req) + requireRejected(t, api.CodeNotExists, status, body) + status, body = x.send("POST", "/drive/v2/volumes/"+x.volume+"/delete_multiple", &linksRequest{LinkIDs: []string{f.linkID}}) + require.Equal(t, http.StatusOK, status, "body: %s", body) + var multi multiResponse + require.NoError(t, json.Unmarshal(body, &multi)) + require.Len(t, multi.Responses, 1) + assert.Equal(t, api.CodeInvalidRequirements, multi.Responses[0].Response.Code) + status, body = x.send("DELETE", "/drive/v2/volumes/"+x.volume+"/files/"+f.linkID+"/revisions/"+f.revID, nil) + requireRejected(t, api.CodeNotExists, status, body) + require.Len(t, x.u.Dump(), 1) +} + +func TestStorageUploadRules(t *testing.T) { + x := newUploader(t) + f := x.newFileRequest("f") + x.create(f) + blocks := f.encrypt([]byte("content")) + status, body, links := x.requestURLs(f, blocks) + require.Equal(t, http.StatusOK, status, "body: %s", body) + require.Len(t, links, 1) + link := links[0] + + assert.Equal(t, http.StatusBadRequest, x.putBlock(link, blocks[0].data, sessionHeader(x.sess)), "session credentials accepted") + wrong := link + wrong.Token = "wrong" + assert.Equal(t, http.StatusForbidden, x.putBlock(wrong, blocks[0].data, nil)) + x.s.ExpireUploadTokens() + assert.Equal(t, http.StatusNotFound, x.putBlock(link, blocks[0].data, nil)) + + // A block requested again gets a URL which works. + _, _, links = x.requestURLs(f, blocks) + require.Len(t, links, 1) + require.Equal(t, http.StatusOK, x.putBlock(links[0], blocks[0].data, nil)) + status, body = x.commit(f, f.commitRequest(blocks)) + require.Equal(t, http.StatusOK, status, "body: %s", body) + dump := x.u.Dump() + require.Len(t, dump, 1) + require.NoError(t, dump[0].Err) + + // Uploads to a committed revision are refused. + assert.Equal(t, http.StatusNotFound, x.putBlock(links[0], blocks[0].data, nil)) + + // Another user's AddressID is refused. + other := x.s.AddUser("other", "pass") + g := x.newFileRequest("g") + x.create(g) + addressID := other.addresses[0].id + status, body = x.send("POST", "/drive/blocks", &blockUploadRequest{LinkID: g.linkID, RevisionID: g.revID, AddressID: &addressID, VolumeID: &x.volume, BlockList: []blockUploadInput{g.encrypt([]byte("x"))[0].in}}) + requireRejected(t, api.CodeInvalidValue, status, body, "AddressID") +} + +func TestRevisionRules(t *testing.T) { + x := newUploader(t) + id := x.u.SeedFile(x.u.RootID(), "f", []byte("old"), time.Now()) + current := x.u.view().d.links[id].activeRevision().id + path := "/drive/v2/volumes/" + x.volume + "/files/" + id + "/revisions" + stale := "stale" + status, body := x.send("POST", path, &createRevisionRequest{CurrentRevisionID: &stale}) + requireRejected(t, api.CodeInvalidRequirements, status, body, "CurrentRevisionID") + status, body = x.send("POST", path, &createRevisionRequest{}) + requireRejected(t, api.CodeInvalidRequirements, status, body, "CurrentRevisionID") + + uid := testClientUID + status, body = x.send("POST", path, &createRevisionRequest{CurrentRevisionID: ¤t, ClientUID: &uid}) + require.Equal(t, http.StatusOK, status, "body: %s", body) + var resp createRevisionResponse + require.NoError(t, json.Unmarshal(body, &resp)) + assert.Equal(t, []string{resp.Revision.ID}, x.u.Drafts()) + + // The name conflict of a file with a draft revision names both. + status, body = x.send("POST", "/drive/v2/volumes/"+x.volume+"/files", x.newFileRequest("f").req) + requireRejected(t, api.CodeAlreadyExists, status, body) + var conflict conflictResponse + require.NoError(t, json.Unmarshal(body, &conflict)) + require.NotNil(t, conflict.Details.ConflictRevisionID) + assert.Equal(t, current, *conflict.Details.ConflictRevisionID) + require.NotNil(t, conflict.Details.ConflictDraftRevisionID) + assert.Equal(t, resp.Revision.ID, *conflict.Details.ConflictDraftRevisionID) + + status, body = x.send("DELETE", path+"/"+resp.Revision.ID, nil) + require.Equal(t, http.StatusOK, status, "body: %s", body) + assert.Empty(t, x.u.Drafts()) + status, body = x.send("DELETE", path+"/"+current, nil) + requireRejected(t, api.CodeNotExists, status, body) + dump := x.u.Dump() + require.Len(t, dump, 1) + assert.Equal(t, []byte("old"), dump[0].Content) +} + +// TestUploadWireNames checks the backend's upload request types decode +// into the fake's without unknown fields. +func TestUploadWireNames(t *testing.T) { + for _, tc := range []struct { + client any + fake any + }{ + {&api.CreateFileRequest{}, &createFileRequest{}}, + {&api.CreateRevisionRequest{}, &createRevisionRequest{}}, + {&api.BlockUploadRequest{BlockList: []api.BlockUploadInfo{{}}, ThumbnailList: []struct{}{}}, &blockUploadRequest{}}, + {&api.CommitRevisionRequest{}, &commitRevisionRequest{}}, + } { + data, err := json.Marshal(tc.client) + require.NoError(t, err) + dec := json.NewDecoder(bytes.NewReader(data)) + dec.DisallowUnknownFields() + assert.NoError(t, dec.Decode(tc.fake), "%T", tc.client) + } +} diff --git a/backend/protondrive/upload.go b/backend/protondrive/upload.go new file mode 100644 index 000000000..b5c22c5f1 --- /dev/null +++ b/backend/protondrive/upload.go @@ -0,0 +1,879 @@ +package protondrive + +import ( + "bytes" + "context" + "crypto/sha1" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "mime/multipart" + "net/http" + "strings" + "sync" + "time" + + "github.com/ProtonMail/gopenpgp/v3/crypto" + "github.com/rclone/rclone/backend/protondrive/api" + "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/lib/pacer" + "github.com/rclone/rclone/lib/pool" + "github.com/rclone/rclone/lib/rest" + "golang.org/x/sync/errgroup" +) + +// errUploadMismatch is returned when the bytes read from the source of +// an upload don't match its declared size or SHA1. +var errUploadMismatch = errors.New("source doesn't match its declared size or hash") + +const ( + // defaultUploadConcurrency and maxUploadConcurrency bound the blocks + // of one file being uploaded at once, as in the SDK. + defaultUploadConcurrency = 4 + maxUploadConcurrency = 5 + + // blockUploadAttempts is how many times uploading a block is tried. + blockUploadAttempts = 3 + + // blockSealAttempts is how many times a block whose encryption + // fails its check is encrypted, as in the SDK. + blockSealAttempts = 2 + + // intendedSizePrecision is the precision of the size an upload + // declares in advance, which must not tell the server the size. + intendedSizePrecision = 100_000 + + // draftCleanupTimeout bounds deleting the draft of a failed upload. + draftCleanupTimeout = 30 * time.Second +) + +// uploadRequest is a file to upload. +type uploadRequest struct { + ParentID string // folder to create the file in; unused if Existing is set + Name string // name of the new file; unused if Existing is set + Existing *node // file to give a new revision; nil for a new file + In io.Reader + Size int64 // bytes In holds; < 0 if unknown + ModTime time.Time // zero if unknown + MIMEType string + SHA1 string // hex SHA-1 of the bytes In holds; "" if unknown +} + +// draft is an uncommitted revision being uploaded. +type draft struct { + nodeID string + revisionID string + parentID string + newFile bool // the node is a draft too, not just the revision + nodeKR *crypto.KeyRing + ownKeys bool // nodeKR was generated for the draft and is cleared with it + sk *crypto.SessionKey // content key +} + +// upload uploads r as a new file, or a new revision of r.Existing, as +// the SDK's upload module does, and returns the file. +// +// A new file whose name is taken by a file is uploaded as a new +// revision of it. A draft of the name left by this client (by +// DraftClientUID) is deleted and the upload tried again; one left by +// another client is errExists unless ReplaceExistingDraft is set. If +// the bytes read differ from r.Size or r.SHA1 the upload fails with +// errUploadMismatch. Whatever the failure, the draft is deleted. +func (c *client) upload(ctx context.Context, r uploadRequest) (*node, error) { + what := fmt.Sprintf("upload %q", r.Name) + if r.Existing != nil { + what = fmt.Sprintf("upload %q", r.Existing.Name) + } + signKR, err := c.addr.signingKeyRing() + if err != nil { + return nil, fmt.Errorf("%s: %w", what, err) + } + d, err := c.createDraft(ctx, r, signKR) + if err != nil { + return nil, fmt.Errorf("%s: %w", what, err) + } + if d.ownKeys { + defer d.nodeKR.ClearPrivateParams() + } + n, committed, err := c.uploadDraft(ctx, d, r, signKR) + if err != nil { + if !committed { + c.deleteDraft(ctx, d) + } + return nil, fmt.Errorf("%s: %w", what, err) + } + return n, nil +} + +// draftClientUID returns the ClientUID marking the client's drafts, or +// nil if it has none. +func (c *client) draftClientUID() *string { + if c.opt.DraftClientUID == "" { + return nil + } + uid := c.opt.DraftClientUID + return &uid +} + +// uploadConcurrency returns the most blocks of one file to upload at +// once. +func (c *client) uploadConcurrency() int { + if c.opt.UploadConcurrency <= 0 { + return defaultUploadConcurrency + } + return min(c.opt.UploadConcurrency, maxUploadConcurrency) +} + +// draftIntendedSize returns the IntendedUploadSize of a new file of +// size bytes as the SDK's createDraft sends it: rounded down to +// intendedSizePrecision, or nil if that is at most the precision or the +// size is unknown. +func draftIntendedSize(size int64) *int64 { + rounded := size / intendedSizePrecision * intendedSizePrecision + if size < 0 || rounded <= intendedSizePrecision { + return nil + } + return &rounded +} + +// revisionIntendedSize returns the IntendedUploadSize of a new revision +// of size bytes as the SDK's createDraftRevision sends it +// (reduceSizePrecision), or nil if the size is zero or unknown. +func revisionIntendedSize(size int64) *int64 { + var v int64 + switch { + case size <= 0: + return nil + case size < 4096: + v = 4095 + case size < intendedSizePrecision: + v = intendedSizePrecision + default: + v = size / intendedSizePrecision * intendedSizePrecision + } + return &v +} + +// createDraft creates the draft to upload r to: a draft file in +// r.ParentID, or a draft revision of r.Existing or of the file which +// has the name. +func (c *client) createDraft(ctx context.Context, r uploadRequest, signKR *crypto.KeyRing) (*draft, error) { + if r.Existing != nil { + return c.createRevision(ctx, r.Existing, r.Size) + } + if err := validateName(r.Name); err != nil { + return nil, err + } + parent, err := c.targetFolder(ctx, r.ParentID) + if err != nil { + return nil, err + } + now := c.s.serverTime() + nodeKey, passphrase, passphraseSig, keys, err := generateNodeKeys(parent.keys.keyRing, signKR, true, now) + if err != nil { + return nil, err + } + created := false + defer func() { + if !created { + keys.keyRing.ClearPrivateParams() + } + }() + contentKeyPacket, contentKeyPacketSig, sk, err := generateContentKey(keys.keyRing, now) + if err != nil { + return nil, err + } + encName, err := encryptName(r.Name, nil, parent.keys.keyRing, signKR, now) + if err != nil { + return nil, err + } + mimeType := r.MIMEType + if mimeType == "" { + mimeType = "application/octet-stream" + } + req := &api.CreateFileRequest{ + ParentLinkID: parent.ID, + Name: encName, + Hash: nameHash(r.Name, parent.hashKey), + MIMEType: mimeType, + ClientUID: c.draftClientUID(), + IntendedUploadSize: draftIntendedSize(r.Size), + NodeKey: nodeKey, + NodePassphrase: passphrase, + NodePassphraseSignature: passphraseSig, + ContentKeyPacket: contentKeyPacket, + ContentKeyPacketSignature: contentKeyPacketSig, + SignatureAddress: c.addr.Email, + } + opts := &rest.Opts{Method: "POST", Path: c.volumePath("/drive/v2/volumes") + "/files"} + for retried := false; ; retried = true { + var resp api.CreateFileResponse + err = c.apiCall(ctx, opts, req, &resp) + if err == nil { + created = true + return &draft{ + nodeID: resp.File.ID, + revisionID: resp.File.RevisionID, + parentID: parent.ID, + newFile: true, + nodeKR: keys.keyRing, + ownKeys: true, + sk: sk, + }, nil + } + existing, err := c.resolveConflict(ctx, err, retried) + if err != nil { + return nil, err + } + if existing != nil { + return c.createRevision(ctx, existing, r.Size) + } + } +} + +// resolveConflict decides what to do after creating a draft failed +// with err, as the SDK's handleConflictError does. It returns the file +// to upload a new revision of if the name is taken by a file, or nil +// and no error to try again once a draft in the way is deleted. +// +// A draft is deleted if it was left by this client or +// ReplaceExistingDraft is set, unless retried is set: a draft which +// comes back is another client's upload in progress. +func (c *client) resolveConflict(ctx context.Context, err error, retried bool) (*node, error) { + var apiErr *api.Error + if !errors.As(err, &apiErr) || apiErr.Code != api.CodeAlreadyExists { + return nil, fmt.Errorf("create draft: %w", err) + } + var conflict api.ConflictDetails + if json.Unmarshal(apiErr.Details, &conflict) != nil || conflict.ConflictLinkID == "" { + return nil, mutationError("create draft", err) + } + if conflict.ConflictRevisionID != "" || conflict.ConflictDraftRevisionID == "" { + // Only a file, which has an active revision, can take a new + // revision. A draft revision of it doesn't stop that. + c.cache.invalidate(conflict.ConflictLinkID) + n, getErr := c.getNode(ctx, conflict.ConflictLinkID) + if getErr != nil { + return nil, fmt.Errorf("create draft: %w", getErr) + } + if n.IsFolder || n.State != api.LinkStateActive || n.RevisionID == "" { + return nil, mutationError("create draft", err) + } + return n, nil + } + own := c.opt.DraftClientUID != "" && conflict.ConflictDraftClientUID == c.opt.DraftClientUID + switch { + case retried: + return nil, fmt.Errorf("create draft: a draft of the file came back after it was deleted: %w", mutationError("another client is uploading it", err)) + case !own && !c.opt.ReplaceExistingDraft: + return nil, fmt.Errorf("create draft: another client is uploading the file (set replace_existing_draft to replace its draft): %w", mutationError("draft exists", err)) + } + fs.Debugf(nil, "protondrive: deleting draft %s left by client %q", conflict.ConflictLinkID, conflict.ConflictDraftClientUID) + if delErr := c.deleteDraftLink(ctx, conflict.ConflictLinkID); delErr != nil { + return nil, fmt.Errorf("create draft: %w (deleting the draft in the way failed: %v)", mutationError("draft exists", err), delErr) + } + return nil, nil +} + +// createRevision creates a draft revision of file n, which must be +// unchanged since it was read. +func (c *client) createRevision(ctx context.Context, n *node, size int64) (*draft, error) { + if n.IsFolder || n.link == nil || n.link.File == nil || n.RevisionID == "" { + return nil, fmt.Errorf("%q is not a file with content", n.Name) + } + sk, err := c.contentKey(n) + if err != nil { + return nil, err + } + req := &api.CreateRevisionRequest{ + CurrentRevisionID: n.RevisionID, + ClientUID: c.draftClientUID(), + IntendedUploadSize: revisionIntendedSize(size), + } + var resp api.CreateRevisionResponse + err = c.apiCall(ctx, &rest.Opts{Method: "POST", Path: c.volumePath("/drive/v2/volumes", "files", n.ID, "revisions")}, req, &resp) + c.cache.invalidate(n.ID) + if err != nil { + return nil, mutationError("create revision", err) + } + return &draft{ + nodeID: n.ID, + revisionID: resp.Revision.ID, + parentID: n.ParentID, + nodeKR: n.keys.keyRing, + sk: sk, + }, nil +} + +// uploadResult is what was read from the source of an upload and +// uploaded. +type uploadResult struct { + size int64 + sha1 string // hex + hashes [][]byte // SHA-256 of each encrypted block, in order + blockSizes []int64 // plaintext size of each block, in order +} + +// check checks res against the size and SHA1 r declares, and its block +// count against its size. +func (res *uploadResult) check(r uploadRequest) error { + switch { + case r.Size >= 0 && res.size != r.Size: + return fmt.Errorf("%w: read %d bytes, expected %d", errUploadMismatch, res.size, r.Size) + case r.SHA1 != "" && !strings.EqualFold(r.SHA1, res.sha1): + return fmt.Errorf("%w: read bytes with SHA1 %s, expected %s", errUploadMismatch, res.sha1, r.SHA1) + case int64(len(res.hashes)) != (res.size+defaultBlockSize-1)/defaultBlockSize: + return fmt.Errorf("%d blocks uploaded for %d bytes", len(res.hashes), res.size) + } + return nil +} + +// uploadDraft uploads the content of r to draft d and commits it, +// returning the committed file. committed reports whether the revision +// is committed, even if err is set, when the draft must not be deleted. +func (c *client) uploadDraft(ctx context.Context, d *draft, r uploadRequest, signKR *crypto.KeyRing) (n *node, committed bool, err error) { + code, verifySK, err := c.verificationData(ctx, d) + if err != nil { + return nil, false, err + } + res, err := c.uploadBlocks(ctx, d, r, code, verifySK, signKR) + if err != nil { + return nil, false, err + } + if err := res.check(r); err != nil { + return nil, false, err + } + now := c.s.serverTime() + manifest, err := signManifest(res.hashes, signKR, now) + if err != nil { + return nil, false, err + } + x := &xattrs{Size: res.size, BlockSizes: res.blockSizes, SHA1: res.sha1} + if !r.ModTime.IsZero() { + x.ModTime = r.ModTime.UTC() + } + encXAttrs, err := encryptXAttrs(x, d.nodeKR, signKR, now) + if err != nil { + return nil, false, err + } + req := &api.CommitRevisionRequest{ + ManifestSignature: manifest, + SignatureAddress: c.addr.Email, + XAttr: encXAttrs, + ChecksumVerified: r.SHA1 != "", + } + commitErr := c.apiCall(ctx, &rest.Opts{Method: "PUT", Path: c.volumePath("/drive/v2/volumes", "files", d.nodeID, "revisions", d.revisionID)}, req, nil) + c.forget(d.nodeID, d.parentID) + n, err = c.getNode(ctx, d.nodeID) + active := err == nil && n.State == api.LinkStateActive && n.RevisionID == d.revisionID + switch { + case commitErr != nil && !active: + return nil, false, fmt.Errorf("commit: %w", commitErr) + case commitErr != nil: + // The response of a commit which succeeded may have been lost, + // and its retry then failed. + fs.Debugf(nil, "protondrive: %q (ID %s): commit failed but the revision is active: %v", n.Name, n.ID, commitErr) + case err != nil: + return nil, true, fmt.Errorf("read the uploaded file: %w", err) + } + return n, true, nil +} + +// verificationData returns the verification code of draft d and the +// content key the server holds for it, which blocks are checked +// against as in the SDK. +func (c *client) verificationData(ctx context.Context, d *draft) (code []byte, sk *crypto.SessionKey, err error) { + var resp api.VerificationResponse + opts := &rest.Opts{Method: "GET", Path: c.volumePath("/drive/v2/volumes", "links", d.nodeID, "revisions", d.revisionID, "verification")} + if err := c.apiCall(ctx, opts, nil, &resp); err != nil { + return nil, nil, fmt.Errorf("get verification data: %w", err) + } + code, err = base64.StdEncoding.DecodeString(resp.VerificationCode) + if err != nil { + return nil, nil, fmt.Errorf("get verification data: %w", err) + } + sk, _, err = decryptContentKey(resp.ContentKeyPacket, "", d.nodeKR, nil, c.s.serverTime()) + if err != nil { + return nil, nil, fmt.Errorf("get verification data: %w", err) + } + return code, sk, nil +} + +// encryptedBlock is a block of a draft, encrypted and checked, which +// holds its share of the upload concurrency until freed. +type encryptedBlock struct { + index int + enc *pool.RW + encSignature string + token []byte // verifier token + release func() // gives back the share of the upload concurrency +} + +// free frees the block's buffer and its share of the upload +// concurrency. +func (b *encryptedBlock) free() { + _ = b.enc.Close() + b.release() +} + +// freeBlocks frees every block of blocks. +func freeBlocks(blocks []*encryptedBlock) { + for _, b := range blocks { + b.free() + } +} + +// blockUpload is a block with the URL to upload it to. +type blockUpload struct { + block *encryptedBlock + link api.UploadLink +} + +// uploadBlocks reads, encrypts and uploads the content of r to draft +// d: one goroutine reads and encrypts blocks, one requests their upload +// URLs in batches, and uploadConcurrency workers upload them. Every +// wait is bounded by ctx. +func (c *client) uploadBlocks(ctx context.Context, d *draft, r uploadRequest, code []byte, verifySK *crypto.SessionKey, signKR *crypto.KeyRing) (*uploadResult, error) { + concurrency := c.uploadConcurrency() + g, gCtx := errgroup.WithContext(ctx) + ready := make(chan *encryptedBlock) + uploads := make(chan blockUpload) + res := &uploadResult{} + g.Go(func() error { + defer close(ready) + return c.readBlocks(gCtx, d, r, code, verifySK, signKR, concurrency, res, ready) + }) + g.Go(func() error { + defer close(uploads) + return c.requestURLs(gCtx, d, ready, uploads) + }) + for range concurrency { + g.Go(func() error { + for { + var u blockUpload + var ok bool + select { + case u, ok = <-uploads: + case <-gCtx.Done(): + return gCtx.Err() + } + if !ok { + return nil + } + err := c.uploadBlock(gCtx, d, u) + u.block.free() + if err != nil { + return fmt.Errorf("block %d: %w", u.block.index, err) + } + } + }) + } + if err := g.Wait(); err != nil { + return nil, err + } + return res, nil +} + +// readBlocks reads r.In block by block into pool buffers, encrypts and +// checks each block and sends it to ready, recording what it read in +// res. At most concurrency blocks of the upload, and blocksInFlight of +// the client, are held at once. +// +// A source longer than r.Size fails with errUploadMismatch as soon as +// that is seen. +func (c *client) readBlocks(ctx context.Context, d *draft, r uploadRequest, code []byte, verifySK *crypto.SessionKey, signKR *crypto.KeyRing, concurrency int, res *uploadResult, ready chan<- *encryptedBlock) error { + slots := make(chan struct{}, concurrency) + digest := sha1.New() + in := io.TeeReader(r.In, digest) + for index := 1; ; index++ { + release, err := c.reserveBlock(ctx, slots) + if err != nil { + return err + } + plain := pool.NewRW(pool.Global()) + n, err := plain.ReadFrom(io.LimitReader(in, defaultBlockSize)) + res.size += n + switch { + case err != nil: + err = fmt.Errorf("read source: %w", err) + case r.Size >= 0 && res.size > r.Size: + err = fmt.Errorf("%w: source is longer than %d bytes", errUploadMismatch, r.Size) + } + if err != nil || n == 0 { + _ = plain.Close() + release() + if err != nil { + return err + } + break + } + b, hash, err := c.sealBlock(d, plain, index, code, verifySK, signKR) + _ = plain.Close() + if err != nil { + release() + return fmt.Errorf("block %d: %w", index, err) + } + b.release = release + res.hashes = append(res.hashes, hash) + res.blockSizes = append(res.blockSizes, n) + select { + case ready <- b: + case <-ctx.Done(): + b.free() + return ctx.Err() + } + if n < defaultBlockSize { + break + } + } + res.sha1 = hex.EncodeToString(digest.Sum(nil)) + return nil +} + +// reserveBlock takes a share of the upload's concurrency from slots and +// of the client's from uploadTokens, returning the function which +// gives both back. +func (c *client) reserveBlock(ctx context.Context, slots chan struct{}) (release func(), err error) { + select { + case slots <- struct{}{}: + case <-ctx.Done(): + return nil, ctx.Err() + } + if err := acquireToken(ctx, c.uploadTokens); err != nil { + <-slots + return nil, err + } + return func() { + c.uploadTokens.Put() + <-slots + }, nil +} + +// acquireToken gets a token from td, or returns the error of ctx if it +// is done first. TokenDispenser.Get can't be cancelled, so an abandoned +// wait gives the token back when it gets it. +func acquireToken(ctx context.Context, td *pacer.TokenDispenser) error { + if err := ctx.Err(); err != nil { + return err + } + got := make(chan struct{}) + go func() { + td.Get() + select { + case got <- struct{}{}: + case <-ctx.Done(): + td.Put() + } + }() + select { + case <-got: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +// sealBlock encrypts and signs the block in plain as block index of d, +// checks it decrypts with the server's content key verifySK and makes +// its verifier token from code. As in the SDK, a block whose check +// fails, which may be a bit flip, is encrypted once more. +func (c *client) sealBlock(d *draft, plain *pool.RW, index int, code []byte, verifySK *crypto.SessionKey, signKR *crypto.KeyRing) (b *encryptedBlock, hash []byte, err error) { + for attempt := 1; ; attempt++ { + b, hash, err = c.sealBlockOnce(d, plain, index, code, verifySK, signKR) + if err == nil || attempt == blockSealAttempts { + return b, hash, err + } + fs.Debugf(nil, "protondrive: block %d: %v: encrypting it again", index, err) + } +} + +// sealBlockOnce makes one attempt of sealBlock. +func (c *client) sealBlockOnce(d *draft, plain *pool.RW, index int, code []byte, verifySK *crypto.SessionKey, signKR *crypto.KeyRing) (*encryptedBlock, []byte, error) { + if _, err := plain.Seek(0, io.SeekStart); err != nil { + return nil, nil, err + } + enc := pool.NewRW(pool.Global()) + h := sha256.New() + encSignature, err := encryptBlockTo(io.MultiWriter(enc, h), plain, d.sk, d.nodeKR, signKR, c.s.serverTime()) + if err == nil { + err = checkBlock(enc, verifySK) + } + var token []byte + if err == nil { + token, err = blockToken(enc, code) + } + if err != nil { + _ = enc.Close() + return nil, nil, err + } + if c.verifierHook != nil { + c.verifierHook(token) + } + return &encryptedBlock{index: index, enc: enc, encSignature: encSignature, token: token}, h.Sum(nil), nil +} + +// checkBlock checks the encrypted block enc decrypts with sk. +func checkBlock(enc *pool.RW, sk *crypto.SessionKey) error { + if _, err := enc.Seek(0, io.SeekStart); err != nil { + return err + } + dec, err := blockDecrypter(enc, sk) + if err == nil { + _, err = io.Copy(io.Discard, dec) + } + if err != nil { + return fmt.Errorf("encrypted block doesn't decrypt with the file's content key: %w", err) + } + return nil +} + +// blockToken returns the verifier token of the encrypted block enc. +func blockToken(enc *pool.RW, code []byte) ([]byte, error) { + if _, err := enc.Seek(0, io.SeekStart); err != nil { + return nil, err + } + prefix := make([]byte, len(code)) + n, err := io.ReadFull(enc, prefix) + if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF { + return nil, err + } + return verifierToken(code, prefix[:n]), nil +} + +// requestURLs takes blocks from ready as they come, requests their +// upload URLs in batches of those waiting and passes them to uploads. +func (c *client) requestURLs(ctx context.Context, d *draft, ready <-chan *encryptedBlock, uploads chan<- blockUpload) error { + for { + var batch []*encryptedBlock + select { + case b, ok := <-ready: + if !ok { + return nil + } + batch = append(batch, b) + case <-ctx.Done(): + return ctx.Err() + } + done := false + waiting: + for !done { + select { + case b, ok := <-ready: + if ok { + batch = append(batch, b) + } + done = !ok + default: + break waiting + } + } + links, err := c.blockURLs(ctx, d, batch) + if err != nil { + freeBlocks(batch) + return err + } + for i, b := range batch { + select { + case uploads <- blockUpload{block: b, link: links[i]}: + case <-ctx.Done(): + freeBlocks(batch[i:]) + return ctx.Err() + } + } + if done { + return nil + } + } +} + +// blockURLs requests the upload URLs of blocks of draft d, in the +// order of blocks. +func (c *client) blockURLs(ctx context.Context, d *draft, blocks []*encryptedBlock) ([]api.UploadLink, error) { + req := &api.BlockUploadRequest{ + AddressID: c.addr.ID, + VolumeID: c.volumeID, + LinkID: d.nodeID, + RevisionID: d.revisionID, + BlockList: make([]api.BlockUploadInfo, 0, len(blocks)), + ThumbnailList: []struct{}{}, + } + for _, b := range blocks { + req.BlockList = append(req.BlockList, api.BlockUploadInfo{ + Index: b.index, + EncSignature: b.encSignature, + Verifier: api.BlockVerifier{Token: base64.StdEncoding.EncodeToString(b.token)}, + }) + } + var resp api.BlockUploadResponse + if err := c.apiCall(ctx, &rest.Opts{Method: "POST", Path: "/drive/blocks"}, req, &resp); err != nil { + return nil, fmt.Errorf("request upload URLs: %w", err) + } + byIndex := make(map[int]api.UploadLink, len(resp.UploadLinks)) + for _, l := range resp.UploadLinks { + byIndex[l.Index] = l + } + links := make([]api.UploadLink, len(blocks)) + for i, b := range blocks { + l, ok := byIndex[b.index] + if !ok || l.BareURL == "" { + return nil, fmt.Errorf("request upload URLs: no URL for block %d", b.index) + } + links[i] = l + } + return links, nil +} + +// uploadBlock uploads block u to the storage host, trying up to +// blockUploadAttempts times. A 404 means the URL expired, so a new one +// is requested. +func (c *client) uploadBlock(ctx context.Context, d *draft, u blockUpload) error { + link := u.link + for attempt := 1; ; attempt++ { + retry, err := c.postBlock(ctx, link, u.block.enc) + var apiErr *api.Error + switch { + case err == nil: + return nil + case ctx.Err() != nil: + return ctx.Err() + case attempt >= blockUploadAttempts: + return err + case errors.As(err, &apiErr) && apiErr.Status == http.StatusNotFound: + fs.Debugf(nil, "protondrive: block %d: upload URL expired: requesting a new one", u.block.index) + links, err := c.blockURLs(ctx, d, []*encryptedBlock{u.block}) + if err != nil { + return err + } + link = links[0] + case !retry: + return err + default: + fs.Debugf(nil, "protondrive: block %d: upload failed: %v: retrying", u.block.index, err) + } + } +} + +// postBlock makes one attempt to upload the encrypted block enc to +// link, paced by the storage pacer, and reports whether a failure may +// be retried. +func (c *client) postBlock(ctx context.Context, link api.UploadLink, enc *pool.RW) (retry bool, err error) { + paced := c.paced(ctx, func() (*http.Response, error) { + if _, err := enc.Seek(0, io.SeekStart); err != nil { + return nil, err + } + body := newMultipartBlock(enc) + defer body.finish() + opts := &rest.Opts{ + Method: "POST", + RootURL: link.BareURL, + Body: body, + ContentType: body.contentType, + ContentLength: &body.size, + NoResponse: true, + // The storage host gets the block's token, never the + // session's credentials, which only session.call adds. + ExtraHeaders: map[string]string{"pm-storage-token": link.Token}, + } + return c.s.srv.Call(ctx, opts) + }) + err = c.storagePacer.CallNoRetry(func() (bool, error) { + var err error + retry, err = paced() + return retry, err + }) + return retry, err +} + +// errAttemptOver is returned by reads of a multipartBlock whose upload +// attempt is over. +var errAttemptOver = errors.New("upload attempt is over") + +// multipartBlock is the multipart/form-data body of one attempt to +// upload a block, as the SDK's uploadBlock sends it: the block in the +// field Block. +// +// The HTTP transport may still read a request body after the request +// returns, so the body stops reading the block once finished: the +// block may then be read for a retry, or freed. +type multipartBlock struct { + contentType string + size int64 + + mu sync.Mutex + r io.Reader + done bool +} + +// newMultipartBlock returns the body uploading the block in enc from +// its read position. +func newMultipartBlock(enc *pool.RW) *multipartBlock { + var buf bytes.Buffer + mw := multipart.NewWriter(&buf) + // Writes to a bytes.Buffer don't fail. + _, _ = mw.CreateFormFile("Block", "blob") + head := buf.String() + buf.Reset() + _ = mw.Close() + tail := buf.String() + pos, _ := enc.Seek(0, io.SeekCurrent) + return &multipartBlock{ + contentType: mw.FormDataContentType(), + size: int64(len(head)+len(tail)) + enc.Size() - pos, + r: io.MultiReader(strings.NewReader(head), enc, strings.NewReader(tail)), + } +} + +// Read reads the body, or fails once the body is finished. +func (b *multipartBlock) Read(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + if b.done { + return 0, errAttemptOver + } + return b.r.Read(p) +} + +// finish stops the body reading the block, waiting for a read in +// progress. +func (b *multipartBlock) finish() { + b.mu.Lock() + b.done = true + b.mu.Unlock() +} + +// deleteDraft deletes draft d of a failed upload, even if ctx is done, +// logging a failure: the draft stands in the way of the next upload of +// the name until it is replaced. +func (c *client) deleteDraft(ctx context.Context, d *draft) { + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), draftCleanupTimeout) + defer cancel() + var err error + if d.newFile { + err = c.deleteDraftLink(ctx, d.nodeID) + } else { + err = c.apiCall(ctx, &rest.Opts{Method: "DELETE", Path: c.volumePath("/drive/v2/volumes", "files", d.nodeID, "revisions", d.revisionID)}, nil, nil) + } + c.forget(d.nodeID, d.parentID) + if err != nil { + fs.Errorf(nil, "protondrive: failed to delete the draft of a failed upload (node %s, revision %s): %v", d.nodeID, d.revisionID, err) + } +} + +// deleteDraftLink permanently deletes the draft node id. +func (c *client) deleteDraftLink(ctx context.Context, id string) error { + var resp api.MultiLinkResponse + opts := &rest.Opts{Method: "POST", Path: c.volumePath("/drive/v2/volumes") + "/delete_multiple"} + if err := c.apiCall(ctx, opts, &api.LinksRequest{LinkIDs: []string{id}}, &resp); err != nil { + return fmt.Errorf("delete draft: %w", err) + } + for _, r := range resp.Responses { + if r.Response.Code/1000 != 1 || r.Response.Error != "" { + return mutationError("delete draft "+r.LinkID, &api.Error{Code: r.Response.Code, Message: r.Response.Error}) + } + } + return nil +} diff --git a/backend/protondrive/upload_internal_test.go b/backend/protondrive/upload_internal_test.go new file mode 100644 index 000000000..5a0e19d28 --- /dev/null +++ b/backend/protondrive/upload_internal_test.go @@ -0,0 +1,494 @@ +package protondrive + +import ( + "bytes" + "context" + "crypto/sha1" + "encoding/hex" + "errors" + "io" + "net/http" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/rclone/rclone/backend/protondrive/api" + "github.com/rclone/rclone/backend/protondrive/protontest" + "github.com/rclone/rclone/lib/pacer" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + filesPattern = "/drive/v2/volumes/{volumeID}/files" + commitPattern = "/drive/v2/volumes/{volumeID}/files/{linkID}/revisions/{revisionID}" + deleteDraftsPattern = "/drive/v2/volumes/{volumeID}/delete_multiple" + storageUploadPattern = "/storage/upload/{token}" + + testDraftClientUID = "rclone-test-draft-client" +) + +// newUploadClient returns a client of a new user of a new fake server +// with a draft client UID and the options opt. +func newUploadClient(t *testing.T, opt clientOptions) (*client, *protontest.Server, *protontest.User) { + t.Helper() + if opt.DraftClientUID == "" { + opt.DraftClientUID = testDraftClientUID + } + return newTestClientOpt(t, opt) +} + +// testModTime is the modification time of uploaded files. +var testModTime = time.Date(2024, 5, 6, 7, 8, 9, 0, time.UTC) + +// sha1Of returns the hex SHA-1 of b. +func sha1Of(b []byte) string { + sum := sha1.Sum(b) + return hex.EncodeToString(sum[:]) +} + +// uploadContent uploads content as name in the root with size declared +// as size. +func uploadContent(ctx context.Context, c *client, name string, in io.Reader, size int64) (*node, error) { + return c.upload(ctx, uploadRequest{ + ParentID: c.rootID(), + Name: name, + In: in, + Size: size, + ModTime: testModTime, + MIMEType: "application/octet-stream", + }) +} + +// uploadBytes uploads content as name in the root, declaring its size. +func uploadBytes(t *testing.T, c *client, name string, content []byte) *node { + t.Helper() + n, err := uploadContent(context.Background(), c, name, bytes.NewReader(content), int64(len(content))) + require.NoError(t, err) + return n +} + +// requireUploaded fails the test unless the fake decrypts and verifies +// every node of u without error, and finds the files of want, by path, +// with that content, the test modification time and its SHA1. +func requireUploaded(t *testing.T, u *protontest.User, want map[string][]byte) { + t.Helper() + dump := u.Dump() + got := make(map[string]bool) + for _, d := range dump { + require.NoError(t, d.Err, "node %q", d.Path) + content, ok := want[d.Path] + if !ok { + continue + } + got[d.Path] = true + assert.True(t, bytes.Equal(content, d.Content), "%q: content differs: %d bytes, want %d", d.Path, len(d.Content), len(content)) + assert.Equal(t, sha1Of(content), d.SHA1, "%q: SHA1", d.Path) + assert.True(t, testModTime.Equal(d.ModTime), "%q: modification time %v", d.Path, d.ModTime) + } + for path := range want { + assert.True(t, got[path], "%q not in the drive", path) + } + assert.Empty(t, u.Drafts(), "drafts left") +} + +// files returns the paths of the files in u's drive. +func files(u *protontest.User) []string { + var paths []string + for _, d := range u.Dump() { + if !d.IsFolder { + paths = append(paths, d.Path) + } + } + return paths +} + +func TestUploadSizes(t *testing.T) { + t.Parallel() + c, srv, u := newUploadClient(t, clientOptions{}) + want := make(map[string][]byte) + for _, size := range []int{0, 1, 4<<20 - 1, 4 << 20, 4<<20 + 1, bigSize} { + t.Run(strconv.Itoa(size), func(t *testing.T) { + name := "f" + strconv.Itoa(size) + content := testContent(size) + want[name] = content + srv.ResetRequests() + n := uploadBytes(t, c, name, content) + blocks := (size + 4<<20 - 1) / (4 << 20) + assert.Equal(t, blocks, srv.Requests()["POST "+storageUploadPattern], "blocks uploaded") + assert.Equal(t, name, n.Name) + assert.Equal(t, int64(size), n.size(true)) + assert.Equal(t, sha1Of(content), n.sha1()) + assert.True(t, testModTime.Equal(n.modTime())) + require.NotNil(t, n.X) + assert.Len(t, n.X.BlockSizes, blocks) + }) + } + requireUploaded(t, u, want) +} + +func TestUploadUnknownSize(t *testing.T) { + t.Parallel() + c, _, u := newUploadClient(t, clientOptions{}) + want := make(map[string][]byte) + for _, size := range []int{0, 5 << 20} { + name := "f" + strconv.Itoa(size) + want[name] = testContent(size) + n, err := uploadContent(context.Background(), c, name, bytes.NewReader(want[name]), -1) + require.NoError(t, err) + assert.Equal(t, int64(size), n.size(true)) + } + requireUploaded(t, u, want) +} + +func TestUploadNewRevision(t *testing.T) { + t.Parallel() + c, _, u := newUploadClient(t, clientOptions{}) + first := uploadBytes(t, c, "f", testContent(5<<20)) + content := []byte("new content") + n, err := c.upload(context.Background(), uploadRequest{ + Existing: first, + In: bytes.NewReader(content), + Size: int64(len(content)), + ModTime: testModTime, + SHA1: sha1Of(content), + }) + require.NoError(t, err) + assert.Equal(t, first.ID, n.ID) + assert.NotEqual(t, first.RevisionID, n.RevisionID) + requireUploaded(t, u, map[string][]byte{"f": content}) + assert.Equal(t, []string{"f"}, files(u)) + old, err := c.revisionBlocks(context.Background(), first, 1, 1) + require.NoError(t, err) + assert.Equal(t, 2, old.State, "old revision not superseded") +} + +func TestUploadOverExistingNameCreatesRevision(t *testing.T) { + t.Parallel() + c, _, u := newUploadClient(t, clientOptions{}) + first := uploadBytes(t, c, "f", []byte("first")) + n := uploadBytes(t, c, "f", []byte("second")) + assert.Equal(t, first.ID, n.ID) + assert.NotEqual(t, first.RevisionID, n.RevisionID) + requireUploaded(t, u, map[string][]byte{"f": []byte("second")}) + assert.Equal(t, []string{"f"}, files(u)) + + // A folder in the way is not replaced. + _, err := c.createFolder(context.Background(), c.rootID(), "dir", time.Time{}) + require.NoError(t, err) + _, err = uploadContent(context.Background(), c, "dir", strings.NewReader("x"), 1) + assert.ErrorIs(t, err, errExists) + assert.Empty(t, u.Drafts()) +} + +// testSourceMismatch uploads actual bytes declared as 5 MiB, which must +// fail cleanly. +func testSourceMismatch(t *testing.T, actual int) { + c, srv, u := newUploadClient(t, clientOptions{}) + goroutines, buffers := leakBaseline(srv) + _, err := uploadContent(context.Background(), c, "f", bytes.NewReader(testContent(actual)), 5<<20) + assert.ErrorIs(t, err, errUploadMismatch) + assert.Empty(t, u.Drafts()) + assert.Empty(t, files(u)) + requireNoLeaks(t, srv, goroutines, buffers) +} + +func TestUploadShortSource(t *testing.T) { + testSourceMismatch(t, 3<<20) + testSourceMismatch(t, 0) +} + +func TestUploadLongSource(t *testing.T) { + testSourceMismatch(t, 6<<20) + testSourceMismatch(t, 9<<20) +} + +func TestUploadSHA1Mismatch(t *testing.T) { + t.Parallel() + c, _, u := newUploadClient(t, clientOptions{}) + content := testContent(1000) + _, err := c.upload(context.Background(), uploadRequest{ + ParentID: c.rootID(), Name: "f", In: bytes.NewReader(content), Size: 1000, + SHA1: sha1Of([]byte("something else")), + }) + assert.ErrorIs(t, err, errUploadMismatch) + assert.Empty(t, u.Drafts()) + assert.Empty(t, files(u)) + + _, err = c.upload(context.Background(), uploadRequest{ + ParentID: c.rootID(), Name: "f", In: bytes.NewReader(content), Size: 1000, + ModTime: testModTime, SHA1: strings.ToUpper(sha1Of(content)), + }) + require.NoError(t, err) + requireUploaded(t, u, map[string][]byte{"f": content}) +} + +func TestUploadBlock502Once(t *testing.T) { + t.Parallel() + c, srv, u := newUploadClient(t, clientOptions{}) + srv.Inject(protontest.Fault{Method: "POST", Pattern: storageUploadPattern, Status: http.StatusBadGateway, Times: 1}) + content := testContent(5 << 20) + uploadBytes(t, c, "f", content) + requireUploaded(t, u, map[string][]byte{"f": content}) +} + +// TestUploadBlock502Forever is issue 10224: a block which can't be +// uploaded must fail the upload, not hang it. +func TestUploadBlock502Forever(t *testing.T) { + c, srv, u := newUploadClient(t, clientOptions{}) + goroutines, buffers := leakBaseline(srv) + srv.Inject(protontest.Fault{Method: "POST", Pattern: storageUploadPattern, Status: http.StatusBadGateway}) + start := time.Now() + _, err := uploadContent(context.Background(), c, "f", bytes.NewReader(testContent(9<<20)), 9<<20) + require.Error(t, err) + assert.Less(t, time.Since(start), 30*time.Second) + var apiErr *api.Error + require.ErrorAs(t, err, &apiErr) + assert.Equal(t, http.StatusBadGateway, apiErr.Status) + assert.Empty(t, u.Drafts()) + requireNoLeaks(t, srv, goroutines, buffers) +} + +func TestUploadStorageTokenExpired(t *testing.T) { + t.Parallel() + srv := protontest.New(t) + u := srv.AddUser("user", "pass") + var expired atomic.Bool + c := newTestClientTransport(t, srv, u, clientOptions{DraftClientUID: testDraftClientUID}, func(next http.RoundTripper) http.RoundTripper { + return roundTripFunc(func(r *http.Request) (*http.Response, error) { + if strings.HasPrefix(r.URL.Path, "/storage/upload/") && !expired.Swap(true) { + srv.ExpireUploadTokens() + } + return next.RoundTrip(r) + }) + }) + content := testContent(9 << 20) + uploadBytes(t, c, "f", content) + assert.Greater(t, srv.Requests()["POST /drive/blocks"], 1, "no new URL requested") + assert.Greater(t, srv.Requests()["POST "+storageUploadPattern], 3, "no upload refused") + requireUploaded(t, u, map[string][]byte{"f": content}) +} + +func TestUploadCommitErrorButCommitted(t *testing.T) { + t.Parallel() + c, srv, u := newUploadClient(t, clientOptions{}) + srv.Inject(protontest.Fault{Method: "PUT", Pattern: commitPattern, Status: http.StatusBadGateway, AfterHandler: true, Times: 1}) + content := testContent(1 << 20) + n := uploadBytes(t, c, "f", content) + assert.Equal(t, 2, srv.Requests()["PUT "+commitPattern], "commit not retried") + assert.Equal(t, "f", n.Name) + requireUploaded(t, u, map[string][]byte{"f": content}) + assert.Equal(t, []string{"f"}, files(u)) +} + +func TestUploadDraftResponseLost(t *testing.T) { + t.Parallel() + c, srv, u := newUploadClient(t, clientOptions{}) + srv.Inject(protontest.Fault{Method: "POST", Pattern: filesPattern, Status: http.StatusBadGateway, AfterHandler: true, Times: 1}) + content := testContent(1000) + uploadBytes(t, c, "f", content) + assert.Equal(t, 3, srv.Requests()["POST "+filesPattern], "draft creation: first, retry, after deleting the draft") + requireUploaded(t, u, map[string][]byte{"f": content}) + assert.Equal(t, []string{"f"}, files(u)) +} + +// leaveDraft makes an upload of name by c fail at commit and its +// cleanup fail too, leaving its draft behind. +func leaveDraft(t *testing.T, c *client, srv *protontest.Server, u *protontest.User, name string) { + t.Helper() + srv.Inject(protontest.Fault{Method: "PUT", Pattern: commitPattern, Status: http.StatusUnprocessableEntity, Code: api.CodeInvalidValue, Times: 1}) + srv.Inject(protontest.Fault{Method: "POST", Pattern: deleteDraftsPattern, Status: http.StatusUnprocessableEntity, Code: api.CodeInvalidValue, Times: 1}) + _, err := uploadContent(context.Background(), c, name, strings.NewReader("draft"), 5) + require.Error(t, err) + require.Len(t, u.Drafts(), 1) +} + +// TestUploadOwnDraftReplaced is issue 9622: a draft left by a failed +// upload must not block the next upload of the name. +func TestUploadOwnDraftReplaced(t *testing.T) { + t.Parallel() + c, srv, u := newUploadClient(t, clientOptions{}) + leaveDraft(t, c, srv, u, "f") + content := testContent(1000) + uploadBytes(t, c, "f", content) + requireUploaded(t, u, map[string][]byte{"f": content}) + assert.Equal(t, []string{"f"}, files(u)) +} + +func TestUploadForeignDraft(t *testing.T) { + t.Parallel() + other, srv, u := newUploadClient(t, clientOptions{DraftClientUID: "another client"}) + leaveDraft(t, other, srv, u, "f") + + c := newTestClientFor(t, srv, u, clientOptions{DraftClientUID: testDraftClientUID}) + _, err := uploadContent(context.Background(), c, "f", strings.NewReader("x"), 1) + assert.ErrorIs(t, err, errExists) + assert.Len(t, u.Drafts(), 1, "another client's draft deleted") + + // Without a draft client UID no draft is the client's own. + anon := newTestClientFor(t, srv, u, clientOptions{}) + _, err = uploadContent(context.Background(), anon, "f", strings.NewReader("x"), 1) + assert.ErrorIs(t, err, errExists) + + replacer := newTestClientFor(t, srv, u, clientOptions{DraftClientUID: testDraftClientUID, ReplaceExistingDraft: true}) + content := testContent(1000) + uploadBytes(t, replacer, "f", content) + requireUploaded(t, u, map[string][]byte{"f": content}) + assert.Equal(t, []string{"f"}, files(u)) +} + +func TestUploadCancel(t *testing.T) { + for _, tc := range []struct { + name string + fault protontest.Fault + }{ + {"draft", protontest.Fault{Method: "POST", Pattern: filesPattern}}, + {"blocks", protontest.Fault{Method: "POST", Pattern: storageUploadPattern, Skip: 1}}, + {"commit", protontest.Fault{Method: "PUT", Pattern: commitPattern}}, + } { + t.Run(tc.name, func(t *testing.T) { + c, srv, u := newUploadClient(t, clientOptions{}) + goroutines, buffers := leakBaseline(srv) + tc.fault.Delay = time.Minute + srv.Inject(tc.fault) + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + start := time.Now() + _, err := uploadContent(ctx, c, "f", bytes.NewReader(testContent(9<<20)), 9<<20) + assert.ErrorIs(t, err, context.DeadlineExceeded) + assert.Less(t, time.Since(start), 10*time.Second) + assert.Empty(t, u.Drafts()) + assert.Empty(t, files(u)) + requireNoLeaks(t, srv, goroutines, buffers) + }) + } +} + +func TestUploadConcurrencyBound(t *testing.T) { + t.Run("PerFile", func(t *testing.T) { + t.Parallel() + c, srv, u := newUploadClient(t, clientOptions{UploadConcurrency: 2}) + srv.Inject(protontest.Fault{Method: "POST", Pattern: storageUploadPattern, Delay: 200 * time.Millisecond}) + content := testContent(12<<20 + 1) + uploadBytes(t, c, "f", content) + assert.LessOrEqual(t, srv.StorageUploadPeak(), 2) + requireUploaded(t, u, map[string][]byte{"f": content}) + }) + t.Run("PerClient", func(t *testing.T) { + t.Parallel() + c, srv, u := newUploadClient(t, clientOptions{UploadConcurrency: maxUploadConcurrency}) + srv.Inject(protontest.Fault{Method: "POST", Pattern: storageUploadPattern, Delay: 300 * time.Millisecond}) + want := make(map[string][]byte) + var wg sync.WaitGroup + errs := make([]error, 16) + for i := range errs { + name := "f" + strconv.Itoa(i) + content := testContent(1000 + i) + want[name] = content + wg.Go(func() { + _, errs[i] = uploadContent(context.Background(), c, name, bytes.NewReader(content), int64(len(content))) + }) + } + wg.Wait() + for _, err := range errs { + require.NoError(t, err) + } + peak := srv.StorageUploadPeak() + assert.LessOrEqual(t, peak, blocksInFlight) + assert.Greater(t, peak, 1, "uploads not concurrent") + requireUploaded(t, u, want) + }) +} + +func TestUploadVerifierChecked(t *testing.T) { + t.Parallel() + c, _, u := newUploadClient(t, clientOptions{}) + c.verifierHook = func(token []byte) { token[0] ^= 1 } + _, err := uploadContent(context.Background(), c, "f", bytes.NewReader(testContent(1000)), 1000) + require.Error(t, err) + assert.Equal(t, api.CodeInvalidRequirements, apiErrorCode(err)) + assert.Contains(t, err.Error(), "verifier token") + assert.Empty(t, u.Drafts()) + assert.Empty(t, files(u)) +} + +func TestUploadClockSkew(t *testing.T) { + t.Parallel() + for _, skew := range []time.Duration{3 * time.Hour, -3 * time.Hour} { + t.Run(skew.String(), func(t *testing.T) { + srv := protontest.New(t) + srv.SetClockSkew(skew) + u := srv.AddUser("user", "pass") + c := newTestClientFor(t, srv, u, clientOptions{DraftClientUID: testDraftClientUID}) + first := uploadBytes(t, c, "f", []byte("first")) + content := testContent(5 << 20) + _, err := c.upload(context.Background(), uploadRequest{Existing: first, In: bytes.NewReader(content), Size: -1, ModTime: testModTime}) + require.NoError(t, err) + requireUploaded(t, u, map[string][]byte{"f": content}) + }) + } +} + +func TestUploadThenDownload(t *testing.T) { + t.Parallel() + c, _, _ := newUploadClient(t, clientOptions{}) + content := testContent(bigSize) + n := uploadBytes(t, c, "f", content) + data, err := readRange(t, c, n, 0, -1) + require.NoError(t, err) + assert.True(t, bytes.Equal(content, data), "content differs") + data, err = readRange(t, c, n, bigSize-1, -1) + require.NoError(t, err) + assert.Equal(t, content[bigSize-1:], data) +} + +func TestIntendedUploadSize(t *testing.T) { + ptr := func(v int64) *int64 { return &v } + for _, tc := range []struct { + size int64 + draft, revise *int64 + }{ + {-1, nil, nil}, + {0, nil, nil}, + {1, nil, ptr(4095)}, + {4096, nil, ptr(100_000)}, + {150_000, nil, ptr(100_000)}, + {199_999, nil, ptr(100_000)}, + {200_000, ptr(200_000), ptr(200_000)}, + {9_876_543, ptr(9_800_000), ptr(9_800_000)}, + } { + assert.Equal(t, tc.draft, draftIntendedSize(tc.size), "draft %d", tc.size) + assert.Equal(t, tc.revise, revisionIntendedSize(tc.size), "revision %d", tc.size) + } +} + +// TestAcquireTokenCancel checks a cancelled wait for a token returns at +// once and gives the token back when it gets it. +func TestAcquireTokenCancel(t *testing.T) { + td := pacer.NewTokenDispenser(1) + td.Get() + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error) + go func() { done <- acquireToken(ctx, td) }() + time.Sleep(20 * time.Millisecond) + cancel() + select { + case err := <-done: + assert.ErrorIs(t, err, context.Canceled) + case <-time.After(5 * time.Second): + t.Fatal("cancelled wait for a token didn't return") + } + td.Put() + got := make(chan error) + go func() { got <- acquireToken(context.Background(), td) }() + select { + case err := <-got: + require.NoError(t, err) + case <-time.After(5 * time.Second): + t.Fatal("token kept by the cancelled wait") + } + assert.True(t, errors.Is(acquireToken(ctx, td), context.Canceled)) +} diff --git a/docs/TODO.md b/docs/TODO.md index 06bc6c683..584360d09 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -39,6 +39,21 @@ Small, specific, independently actionable. Remove only when actually done. `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. +- [ ] 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"). + - [ ] Propose a CI check for this fork: `AGENTS.md`, `CLAUDE.md`, `GEMINI.md` and the `docs/` agent files exist, and `AGENTS.md` is at most 150 lines. - [ ] Upstream CI (`.github/workflows/build.yml`) is gated on diff --git a/docs/plans/001-protondrive-tier1.md b/docs/plans/001-protondrive-tier1.md index e3a48cd1b..2815c50a7 100644 --- a/docs/plans/001-protondrive-tier1.md +++ b/docs/plans/001-protondrive-tier1.md @@ -891,7 +891,7 @@ Reference: `client/js/src/internal/upload/` (`manager.ts`, `streamUploader.ts`, `fileUploader.ts`, `apiService.ts`, `blockVerifier.ts`, `cryptoService.ts`). -- [ ] **Step 1: Write failing tests** (assert with `user.Dump()` and +- [x] **Step 1: Write failing tests** (assert with `user.Dump()` and `user.Drafts()`): - `TestUploadSizes` (Review Focus 1): 0, 1, 4 MiB - 1, 4 MiB, 4 MiB + 1, 9 MiB + 123; content, modtime (1s precision), SHA1 and block count @@ -923,11 +923,11 @@ Reference: `client/js/src/internal/upload/` (`manager.ts`, through a test hook is rejected by the fake (proves the fake checks). - `TestUploadClockSkew`: server 3h ahead and 3h behind both succeed. - `TestUploadThenDownload`: round trip through Task 10 for 9 MiB + 123. -- [ ] **Step 2: Run** - expect FAIL. -- [ ] **Step 3: Implement.** -- [ ] **Step 4: Run** the verification commands - expect PASS. Also +- [x] **Step 2: Run** - expect FAIL. +- [x] **Step 3: Implement.** +- [x] **Step 4: Run** the verification commands - expect PASS. Also `go test -race -count=5 ./backend/protondrive/ -run TestUpload`. -- [ ] **Step 5: Commit** `protondrive: add verified block upload`. +- [x] **Step 5: Commit** `protondrive: add verified block upload`. ### Task 12: Differential interop of whole files