Files
StereotypicalCatandClaude Opus 5.5 c0bdbcde6b
build / windows (push) Skipped
build / other_os (push) Skipped
build / mac_amd64 (push) Skipped
build / mac_arm64 (push) Skipped
build / linux (push) Skipped
build / go1.26 (push) Skipped
build / linux_386 (push) Skipped
build / lint (push) Skipped
build / android-all (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/386 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/amd64 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm/v6 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm/v7 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm64 (push) Skipped
Build & Push Docker Images / Merge & Push Final Docker Image (push) Waiting for needed jobs
protondrive: rewrite the backend as a native Go client of the Proton Drive API
Replace Proton-API-Bridge and go-proton-api with a client in
backend/protondrive written against Proton's current Drive API, following
the behaviour of Proton's official Drive SDK:

- volume-based and v2 routes only
- upload block verification, signed manifests and extended attributes
- current content encryption (v4 node keys, v6 PKESK, SEIPDv2)
- browser (session fork) sign-in, with username and password still
  supported
- the volume's change events, used to keep the metadata cache current and
  for ChangeNotify, polled at most every 30 s
- an in-memory fake Proton server (protontest) so the tests run without
  an account

Uses ProtonMail/gopenpgp/v3 and ProtonMail/go-srp directly; no cgo.

Written with heavy AI assistance (Claude Code).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 23:22:46 +01:00

2102 lines
67 KiB
Go

package protontest
import (
"bytes"
"crypto/sha1"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"mime"
"net/http"
"path"
"slices"
"sort"
"strconv"
"strings"
"time"
"github.com/ProtonMail/gopenpgp/v3/crypto"
"github.com/rclone/rclone/backend/protondrive/api"
)
// Link types, link states and revision states as the API encodes them.
const (
linkTypeFolder = 1
linkTypeFile = 2
linkStateDraft = 0
linkStateActive = 1
linkStateTrashed = 2
revisionStateDraft = 0
revisionStateActive = 1
revisionStateObsolete = 2
)
const (
// blockSize is the plaintext size of every block but the last.
blockSize = 4 << 20
// defaultChildrenPageSize is the number of child IDs per page
// unless changed by SetChildrenPageSize.
defaultChildrenPageSize = 150
// maxLinksPerRequest is the most link IDs one metadata request may
// name.
maxLinksPerRequest = 100
// docMediaType is the media type of a Proton Docs document.
docMediaType = "application/vnd.proton.doc"
// legacyTimeFormat is the ISO 8601 modification time format older
// clients wrote in extended attributes.
legacyTimeFormat = "2006-01-02T15:04:05-0700"
)
// DefaultMaxSpace is the MaxSpace of every user, 5 GiB.
const DefaultMaxSpace int64 = 5 << 30
// The claims of the "xattrs-unsigned" corruption.
const (
ForgedModTime = "2099-01-01T00:00:00.000Z"
ForgedSHA1 = "0123456789abcdef0123456789abcdef01234567"
)
// drive is a user's volume with its main share and links.
//
// Stored values are never modified in place once a snapshot may have
// copied them: blocks are replaced, not changed, so views read outside
// the lock stay consistent.
type drive struct {
volumeID string
shareID string
rootID string
createTime int64
addressID string
addressKeyID string
creatorEmail string
shareKey string // armored, locked with the share passphrase
sharePass sealedPassphrase
links map[string]*link
seq int // creation order of links
events *eventLog
}
// link is a file or folder node.
type link struct {
id string
parentID string // empty for the root
seq int
typ int
state int
createTime int64
modifyTime int64
trashTime int64
name string // armored, encrypted to the parent key
nameHash string // empty for the root
nodeKey string // armored, locked with the node passphrase
nodePass sealedPassphrase
signatureEmail string
nameSignatureEmail string
// Folders only.
hashKey string // armored
xattr string // armored, optional
// Files only.
mediaType string
contentKeyPacket string // base64
contentKeyPacketSignature string // armored
revisions []*revision
}
// activeRevision returns l's active revision or nil.
func (l *link) activeRevision() *revision {
for _, r := range l.revisions {
if r.state == revisionStateActive {
return r
}
}
return nil
}
// revision is a version of a file's content.
type revision struct {
id string
state int
createTime int64
manifestSignature string // armored
xattr string // armored, optional
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.
func (r *revision) size() int64 {
var n int64
for _, b := range r.blocks {
n += int64(len(b.data))
}
return n
}
// block is an encrypted block of a revision. Blocks are immutable.
type block struct {
index int // from 1
hash []byte // SHA-256 of data
data []byte
encSignature string // armored
signatureEmail string
}
// download is a block URL issued by the revision route.
type download struct {
token string
block *block
}
// newDrive creates a volume, main share and root folder for addr as
// the SDK's generateVolumeBootstrap does.
func (s *Server) newDrive(addr *address) *drive {
root := newDriveKey(false)
_, hashKey := newHashKey(root.key)
return s.newDriveWithRoot(addr, root, hashKey)
}
// newDriveWithRoot is newDrive with the root folder's node key and
// armored hash key given.
func (s *Server) newDriveWithRoot(addr *address, root lockedKey, hashKey string) *drive {
addrKey := addr.keys[0]
share := newDriveKey(false)
sharePass := sealPassphrase(share.passphrase, addrKey.key, addrKey.key)
s.rememberKey(share)
s.rememberKey(root)
rootPass := sealPassphrase(root.passphrase, share.key, addrKey.key)
return assembleDrive(addr.id, addrKey.id, addr.email, &createVolumeRequest{
ShareKey: share.armored,
SharePassphrase: sharePass.armored,
SharePassphraseSignature: sharePass.signature,
FolderName: encryptArmored([]byte("root"), share.key, addrKey.key, false),
FolderKey: root.armored,
FolderPassphrase: rootPass.armored,
FolderPassphraseSignature: rootPass.signature,
FolderHashKey: hashKey,
})
}
// assembleDrive returns a drive holding the share and root folder of
// req, which has been validated.
func assembleDrive(addressID, addressKeyID, email string, req *createVolumeRequest) *drive {
now := time.Now().Unix()
d := &drive{
volumeID: randomID(),
shareID: randomID(),
rootID: randomID(),
createTime: now,
addressID: addressID,
addressKeyID: addressKeyID,
creatorEmail: email,
shareKey: req.ShareKey,
sharePass: sealedPassphrase{armored: req.SharePassphrase, signature: req.SharePassphraseSignature},
links: make(map[string]*link),
events: newEventLog(),
}
d.addLink(&link{
id: d.rootID,
typ: linkTypeFolder,
state: linkStateActive,
createTime: now,
modifyTime: now,
name: req.FolderName,
nodeKey: req.FolderKey,
nodePass: sealedPassphrase{armored: req.FolderPassphrase, signature: req.FolderPassphraseSignature},
signatureEmail: email,
nameSignatureEmail: email,
hashKey: req.FolderHashKey,
})
return d
}
// addLink stores l in creation order.
func (d *drive) addLink(l *link) {
d.seq++
l.seq = d.seq
d.links[l.id] = l
}
// usedSpace returns the encrypted size of every stored revision.
func (d *drive) usedSpace() int64 {
var n int64
for _, l := range d.links {
for _, r := range l.revisions {
n += r.size()
}
}
return n
}
// mustDriveLocked returns u's drive. srv.mu must be held.
func (u *User) mustDriveLocked() *drive {
if u.drive == nil {
panic("protontest: user " + u.Username + " has no drive")
}
return u.drive
}
// VolumeID returns the ID of u's volume.
func (u *User) VolumeID() string {
u.srv.mu.Lock()
defer u.srv.mu.Unlock()
return u.mustDriveLocked().volumeID
}
// ShareID returns the ID of u's main share.
func (u *User) ShareID() string {
u.srv.mu.Lock()
defer u.srv.mu.Unlock()
return u.mustDriveLocked().shareID
}
// RootID returns the link ID of u's root folder.
func (u *User) RootID() string {
u.srv.mu.Lock()
defer u.srv.mu.Unlock()
return u.mustDriveLocked().rootID
}
// SetChildrenPageSize sets the number of child IDs per page of the
// children route.
func (s *Server) SetChildrenPageSize(n int) {
s.mu.Lock()
defer s.mu.Unlock()
s.childrenPageSize = n
}
// keyCacheID identifies an armored key unlocked with passphrase.
func keyCacheID(armoredKey string, passphrase []byte) string {
h := sha256.New()
h.Write([]byte(armoredKey))
h.Write([]byte{0})
h.Write(passphrase)
return string(h.Sum(nil))
}
// unlockKey unlocks armoredKey with passphrase, remembering the result
// since the key derivation dominates the cost of seeding and dumping.
func (s *Server) unlockKey(armoredKey string, passphrase []byte) (*crypto.Key, error) {
id := keyCacheID(armoredKey, passphrase)
s.mu.Lock()
key := s.unlockedKeys[id]
s.mu.Unlock()
if key != nil {
return key, nil
}
key, err := crypto.NewPrivateKeyFromArmored(armoredKey, passphrase)
if err != nil {
return nil, err
}
s.rememberKey(lockedKey{key: key, passphrase: passphrase, armored: armoredKey})
return key, nil
}
// rememberKey adds a key the fake generated or unlocked to the cache
// of unlockKey.
func (s *Server) rememberKey(k lockedKey) {
s.mu.Lock()
defer s.mu.Unlock()
s.unlockedKeys[keyCacheID(k.armored, k.passphrase)] = k.key
}
// driveView is a copy of a user's drive taken under the lock, which
// decrypts outside it.
type driveView struct {
srv *Server
d drive
addrKey *crypto.Key // key of the share's address
email string // the share's address
keysByEmail map[string][]*crypto.Key // address keys of every user
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
// may be a signature error alongside a usable key.
type unlockedKey struct {
key *crypto.Key
err error
}
// view returns a snapshot of u's drive.
func (u *User) view() *driveView {
s := u.srv
s.mu.Lock()
defer s.mu.Unlock()
d := u.mustDriveLocked()
v := &driveView{
srv: s,
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 {
c := *l
c.revisions = make([]*revision, len(l.revisions))
for i, r := range l.revisions {
rc := *r
rc.blocks = slices.Clone(r.blocks)
c.revisions[i] = &rc
}
v.d.links[id] = &c
}
for _, user := range s.users {
for _, addr := range user.addresses {
for _, k := range addr.keys {
v.keysByEmail[addr.email] = append(v.keysByEmail[addr.email], k.key)
}
}
}
for _, addr := range u.addresses {
if addr.id != d.addressID {
continue
}
v.email, v.addrKey = addr.email, addr.keys[0].key
for _, k := range addr.keys {
if k.id == d.addressKeyID {
v.addrKey = k.key
}
}
}
if v.addrKey == nil {
panic("protontest: drive address " + d.addressID + " is gone")
}
return v
}
// verifier returns the address keys of email, or fallback keys for an
// anonymous signature when email is empty.
func (v *driveView) verifier(email string, fallback ...*crypto.Key) *crypto.KeyRing {
if email == "" {
return keyRing(fallback...)
}
return keyRing(v.keysByEmail[email]...)
}
// 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.now)
if v.shareKey == nil && v.shareErr == nil {
v.shareErr = errors.New("protontest: no share key")
}
}
return v.shareKey, v.shareErr
}
// parentKey returns the key l's name and passphrase are encrypted to.
func (v *driveView) parentKey(l *link) (*crypto.Key, error) {
if l.parentID == "" {
return v.unlockShare()
}
return v.unlock(l.parentID)
}
// unlock returns the node key of link id. The key may be returned with
// a signature error.
func (v *driveView) unlock(id string) (*crypto.Key, error) {
if u, ok := v.unlocked[id]; ok {
return u.key, u.err
}
l := v.d.links[id]
if l == nil {
return nil, fmt.Errorf("protontest: no link %s", id)
}
parent, err := v.parentKey(l)
var u unlockedKey
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, v.now)
}
v.unlocked[id] = u
return u.key, u.err
}
// folderKeys returns the node key and hash key of folder id, ignoring
// signature errors, for seeding into it.
func (v *driveView) folderKeys(id string) (key *crypto.Key, hashKey []byte) {
l := v.d.links[id]
if l == nil || l.typ != linkTypeFolder {
panic("protontest: no folder " + id)
}
key, err := v.unlock(id)
if key == nil {
panic(fmt.Sprintf("protontest: unlock folder %s: %v", id, err))
}
hashKey, err = decryptArmored(l.hashKey, key, nil, v.now)
mustCrypto("decrypt hash key", err)
return key, hashKey
}
// fileXAttr is the extended attributes a file revision carries, in the
// order the SDK's generateFileExtendedAttributes writes them.
type fileXAttr struct {
Common struct {
ModificationTime string `json:",omitempty"`
Size *int64 `json:",omitempty"`
BlockSizes []int64 `json:",omitempty"`
Digests *struct {
SHA1 string
} `json:",omitempty"`
}
}
// newFileXAttr returns the extended attributes of content as JSON.
func newFileXAttr(content []byte, blockSizes []int64, modTime string) []byte {
var x fileXAttr
size := int64(len(content))
sum := sha1.Sum(content)
x.Common.ModificationTime = modTime
x.Common.Size = &size
x.Common.BlockSizes = blockSizes
x.Common.Digests = &struct{ SHA1 string }{SHA1: hex.EncodeToString(sum[:])}
out, err := json.Marshal(&x)
mustCrypto("marshal extended attributes", err)
return out
}
// parseXAttrTime parses a modification time in the current or the
// legacy format.
func parseXAttrTime(s string) (time.Time, error) {
t, err := time.Parse(time.RFC3339Nano, s)
if err != nil {
t, err = time.Parse(legacyTimeFormat, s)
}
return t, err
}
// seedSpec describes a file node to seed.
type seedSpec struct {
name string
content []byte
modTime string // xattr modification time; no xattr if empty
mediaType string
legacy bool // v3 PKESK and SEIPDv1 instead of v6 PKESK and SEIPDv2
noBlocks bool
signer *User // signs as this user's primary address if set
signEmail string // with signer, the signature email; signer's address if empty
anonymous bool // signed as an anonymous uploader: no signature emails
// contentKeySigner, if set, replaces the content key packet
// signature: an address email of the user, or "" for none.
contentKeySigner *string
createTime int64 // Unix seconds; the current time if zero
claimedBlockSizes []int64 // BlockSizes in the extended attributes if not nil
blockSize int // plaintext size of every block but the last; blockSize if zero
}
// SeedFolder creates folder name in parentID as another client using
// the SDK would, and returns its ID.
func (u *User) SeedFolder(parentID, name string) (id string) {
v := u.view()
return u.seedFolder(v, parentID, name, v.addrKey, v.email)
}
// SeedAnonymousFolder is SeedFolder as an anonymous uploader to a
// public link would: no signature emails, and the name and node
// passphrase signed by the parent's node key.
func (u *User) SeedAnonymousFolder(parentID, name string) (id string) {
v := u.view()
parentKey, _ := v.folderKeys(parentID)
return u.seedFolder(v, parentID, name, parentKey, "")
}
// SeedForgedFolder creates folder name in parentID as a hostile server
// could: with a node key of its own making whose passphrase is
// encrypted to the parent's key, and the name and passphrase signed by
// a key of its own, with no signature emails. Anonymous children seeded
// into it verify against that key.
func (u *User) SeedForgedFolder(parentID, name string) (id string) {
return u.seedFolder(u.view(), parentID, name, generateKey("impostor", "impostor@proton.test"), "")
}
// SeedFolderSignedAs is SeedFolder signed by signer's primary address
// key under the signature email email, which needn't be signer's.
func (u *User) SeedFolderSignedAs(signer *User, email, parentID, name string) (id string) {
signKey, _ := signer.primaryAddressKey()
return u.seedFolder(u.view(), parentID, name, signKey, email)
}
// SeedFileSignedAs is SeedFileSignedBy under the signature email email,
// which needn't be signer's.
func (u *User) SeedFileSignedAs(signer *User, email, parentID, name string, content []byte) (id string) {
return u.seedFile(parentID, seedSpec{
name: name,
content: content,
modTime: time.Now().UTC().Format("2006-01-02T15:04:05.000Z"),
mediaType: mediaTypeOf(name),
signer: signer,
signEmail: email,
})
}
// seedFolder creates folder name in parentID with its name and node
// passphrase signed by signer as email, and returns its ID.
func (u *User) seedFolder(v *driveView, parentID, name string, signer *crypto.Key, email string) string {
parentKey, parentHashKey := v.folderKeys(parentID)
node := newDriveKey(false)
u.srv.rememberKey(node)
pass := sealPassphrase(node.passphrase, parentKey, signer)
_, hashKey := newHashKey(node.key)
return u.insertLink(parentID, &link{
typ: linkTypeFolder,
name: encryptArmored([]byte(name), parentKey, signer, false),
nameHash: lookupHash(parentHashKey, name),
nodeKey: node.armored,
nodePass: pass,
signatureEmail: email,
nameSignatureEmail: email,
hashKey: hashKey,
})
}
// SeedFile creates file name with content in parentID as a current
// client using the SDK would - v6 PKESK content key packet, SEIPDv2
// blocks of 4 MiB, encrypted block signatures, signed manifest and
// extended attributes - and returns its ID.
func (u *User) SeedFile(parentID, name string, content []byte, modTime time.Time) (id string) {
return u.seedFile(parentID, seedSpec{
name: name,
content: content,
modTime: modTime.UTC().Format("2006-01-02T15:04:05.000Z"),
mediaType: mediaTypeOf(name),
})
}
// SeedFileSignedBy is SeedFile with every signature, and the signature
// emails, by the primary address of signer, another user sharing the
// folder.
func (u *User) SeedFileSignedBy(signer *User, parentID, name string, content []byte, modTime time.Time) (id string) {
return u.seedFile(parentID, seedSpec{
name: name,
content: content,
modTime: modTime.UTC().Format("2006-01-02T15:04:05.000Z"),
mediaType: mediaTypeOf(name),
signer: signer,
})
}
// SeedAnonymousFile is SeedFile as an anonymous uploader to a public
// link would: no signature emails, the name and node passphrase signed
// by the parent's node key and everything else by the file's.
func (u *User) SeedAnonymousFile(parentID, name string, content []byte, modTime time.Time) (id string) {
return u.seedFile(parentID, seedSpec{
name: name,
content: content,
modTime: modTime.UTC().Format("2006-01-02T15:04:05.000Z"),
mediaType: mediaTypeOf(name),
anonymous: true,
})
}
// SeedFileContentKeySignedBy is SeedFile with the file created at
// created and its content key packet signed by the primary key of u's
// address email instead of the node key, as some old clients signed
// it, or not signed at all if email is empty. Dump, which checks the
// signature as current clients do, reports the file unless email is
// u's primary address.
func (u *User) SeedFileContentKeySignedBy(email string, created time.Time, parentID, name string, content []byte) (id string) {
return u.seedFile(parentID, seedSpec{
name: name,
content: content,
modTime: created.UTC().Format("2006-01-02T15:04:05.000Z"),
mediaType: mediaTypeOf(name),
contentKeySigner: &email,
createTime: created.Unix(),
})
}
// SeedFileClaimingBlockSizes is SeedFile with blockSizes, whatever the
// real ones, recorded in the extended attributes, as a broken or
// hostile client could write them.
func (u *User) SeedFileClaimingBlockSizes(parentID, name string, content []byte, blockSizes []int64) (id string) {
return u.seedFile(parentID, seedSpec{
name: name,
content: content,
modTime: time.Now().UTC().Format("2006-01-02T15:04:05.000Z"),
mediaType: mediaTypeOf(name),
claimedBlockSizes: blockSizes,
})
}
// SeedFileInBlocks is SeedFile with blocks of blockSize plaintext bytes
// but the last, and no block sizes in the extended attributes, as some
// old clients wrote files.
func (u *User) SeedFileInBlocks(parentID, name string, content []byte, blockSize int) (id string) {
return u.seedFile(parentID, seedSpec{
name: name,
content: content,
modTime: time.Now().UTC().Format("2006-01-02T15:04:05.000Z"),
mediaType: mediaTypeOf(name),
claimedBlockSizes: []int64{},
blockSize: blockSize,
})
}
// primaryAddressKey returns the first key and the email of u's primary
// address.
func (u *User) primaryAddressKey() (*crypto.Key, string) {
u.srv.mu.Lock()
defer u.srv.mu.Unlock()
addr := u.addresses[0]
return addr.keys[0].key, addr.email
}
// SeedLegacyFile creates file name with content in parentID in the
// format older clients wrote - a node key without AEAD, v3 PKESK
// content key packet and SEIPDv1 blocks - and returns its ID. Its
// modification time is the current time.
func (u *User) SeedLegacyFile(parentID, name string, content []byte) (id string) {
return u.seedFile(parentID, seedSpec{
name: name,
content: content,
modTime: time.Now().Format(legacyTimeFormat),
mediaType: mediaTypeOf(name),
legacy: true,
})
}
// SeedDoc creates a Proton Docs document name in parentID, a file node
// of media type application/vnd.proton.doc without blocks, and returns
// its ID.
func (u *User) SeedDoc(parentID, name string) (id string) {
return u.seedFile(parentID, seedSpec{name: name, mediaType: docMediaType, noBlocks: true})
}
// mediaTypeOf returns the media type a client would give name.
func mediaTypeOf(name string) string {
if t := mime.TypeByExtension(path.Ext(name)); t != "" {
return t
}
return "application/octet-stream"
}
// seedFile creates a file node with an active revision per spec.
func (u *User) seedFile(parentID string, spec seedSpec) string {
v := u.view()
parentKey, parentHashKey := v.folderKeys(parentID)
signKey, signEmail := v.addrKey, v.email
if spec.signer != nil {
signKey, signEmail = spec.signer.primaryAddressKey()
if spec.signEmail != "" {
signEmail = spec.signEmail
}
}
node := newDriveKey(!spec.legacy)
u.srv.rememberKey(node)
nameSignKey := signKey
if spec.anonymous {
nameSignKey, signKey, signEmail = parentKey, node.key, ""
}
ck := newContentKey(node.key, !spec.legacy)
if spec.contentKeySigner != nil {
ck.signature = ""
if email := *spec.contentKeySigner; email != "" {
u.srv.mu.Lock()
addr := u.addressByEmailLocked(email)
u.srv.mu.Unlock()
if addr == nil {
panic("protontest: no address " + email)
}
ck.signature = signArmored(ck.sk.Key, addr.keys[0].key)
}
}
rev := ck.newRevision(spec.content, spec.blockSize, node.key, signKey, signEmail, spec.modTime, spec.noBlocks, spec.claimedBlockSizes)
return u.insertLink(parentID, &link{
typ: linkTypeFile,
name: encryptArmored([]byte(spec.name), parentKey, nameSignKey, false),
nameHash: lookupHash(parentHashKey, spec.name),
nodeKey: node.armored,
nodePass: sealPassphrase(node.passphrase, parentKey, nameSignKey),
signatureEmail: signEmail,
nameSignatureEmail: signEmail,
mediaType: spec.mediaType,
contentKeyPacket: ck.packet,
contentKeyPacketSignature: ck.signature,
revisions: []*revision{rev},
createTime: spec.createTime,
})
}
// newRevision returns an active revision of content encrypted with ck
// in blocks of size bytes, or blockSize if size is zero, and signed by
// signKey as signEmail, with its
// manifest and, unless modTime is empty, extended attributes claiming
// claimedBlockSizes if not nil. With noBlocks it has no blocks.
func (ck contentKey) newRevision(content []byte, size int, nodeKey, signKey *crypto.Key, signEmail, modTime string, noBlocks bool, claimedBlockSizes []int64) *revision {
if size == 0 {
size = blockSize
}
rev := &revision{
id: randomID(),
state: revisionStateActive,
createTime: time.Now().Unix(),
signatureEmail: signEmail,
}
var manifest []byte
var blockSizes []int64
for i := 0; !noBlocks && i < len(content); i += size {
plain := content[i:min(i+size, len(content))]
data, encSig := ck.encryptBlock(plain, nodeKey, signKey)
sum := sha256.Sum256(data)
rev.blocks = append(rev.blocks, &block{
index: len(rev.blocks) + 1,
hash: sum[:],
data: data,
encSignature: encSig,
signatureEmail: signEmail,
})
manifest = append(manifest, sum[:]...)
blockSizes = append(blockSizes, int64(len(plain)))
}
rev.manifestSignature = signArmored(manifest, signKey)
if claimedBlockSizes != nil {
blockSizes = claimedBlockSizes
}
if modTime != "" {
rev.xattr = encryptArmored(newFileXAttr(content, blockSizes, modTime), nodeKey, signKey, true)
}
return rev
}
// SeedRevision gives file id a new active revision with content, as
// another client using the SDK would, and returns its ID. The active
// revision before it becomes obsolete.
func (u *User) SeedRevision(id string, content []byte, modTime time.Time) (revisionID string) {
v := u.view()
l := v.d.links[id]
if l == nil || l.typ != linkTypeFile {
panic("protontest: no file " + id)
}
key, sk := v.contentKey(l)
ck := contentKey{sk: sk, aead: sk.IsV6()}
rev := ck.newRevision(content, 0, key, v.addrKey, v.email, modTime.UTC().Format("2006-01-02T15:04:05.000Z"), false, nil)
u.srv.mu.Lock()
defer u.srv.mu.Unlock()
stored := u.mustDriveLocked().links[id]
for _, r := range stored.revisions {
if r.state == revisionStateActive {
r.state = revisionStateObsolete
}
}
stored.revisions = append(stored.revisions, rev)
u.mustDriveLocked().logLink(EventUpdate, stored)
return rev.id
}
// ForgeShareCreator makes u's main share look created by email, signed
// by signer's key, as a hostile server could serve it: the creator
// email is email and the share passphrase is signed by signer's primary
// address key. It still decrypts with u's address key.
func (u *User) ForgeShareCreator(signer *User, email string) {
v := u.view()
passphrase, err := decryptArmored(v.d.sharePass.armored, v.addrKey, nil, v.now)
mustCrypto("decrypt share passphrase", err)
signKey, _ := signer.primaryAddressKey()
sig := signArmored(passphrase, signKey)
u.srv.mu.Lock()
defer u.srv.mu.Unlock()
d := u.mustDriveLocked()
d.creatorEmail = email
d.sharePass.signature = sig
}
// ForgeRootSigner makes u's root folder look made by email, signed by
// signer's key, as a hostile server could serve it: its signature
// emails are email and its name and node passphrase are signed by
// signer's primary address key.
func (u *User) ForgeRootSigner(signer *User, email string) {
v := u.view()
root := v.d.links[v.d.rootID]
shareKey, err := v.unlockShare()
if shareKey == nil {
mustCrypto("unlock share key", err)
}
passphrase, err := decryptArmored(root.nodePass.armored, shareKey, nil, v.now)
mustCrypto("decrypt root passphrase", err)
name, err := decryptArmored(root.name, shareKey, nil, v.now)
mustCrypto("decrypt root name", err)
signKey, _ := signer.primaryAddressKey()
sig := signArmored(passphrase, signKey)
encName := encryptArmored(name, shareKey, signKey, false)
u.srv.mu.Lock()
defer u.srv.mu.Unlock()
d := u.mustDriveLocked()
l := d.links[v.d.rootID]
l.signatureEmail, l.nameSignatureEmail = email, email
l.nodePass.signature = sig
l.name = encName
d.logLink(EventUpdate, l)
}
// SetParent reports link id as a child of parentID from now on,
// without encrypting anything anew, as a hostile server could, even if
// that makes a cycle.
func (u *User) SetParent(id, parentID string) {
u.srv.mu.Lock()
defer u.srv.mu.Unlock()
d := u.mustDriveLocked()
l := d.links[id]
if l == nil {
panic("protontest: no link " + id)
}
l.parentID = parentID
d.logLink(EventUpdateMetadata, l)
}
// ClaimSize makes the extended attributes of file id's active revision
// claim size, signed by u as an uploader with a bug could write them.
func (u *User) ClaimSize(id string, size int64) {
v := u.view()
l := v.d.links[id]
if l == nil || l.typ != linkTypeFile {
panic("protontest: no file " + id)
}
key, _ := v.contentKey(l)
plain, err := decryptArmored(l.activeRevision().xattr, key, nil, v.now)
mustCrypto("decrypt extended attributes", err)
var x fileXAttr
mustCrypto("parse extended attributes", json.Unmarshal(plain, &x))
x.Common.Size = &size
out, err := json.Marshal(&x)
mustCrypto("marshal extended attributes", err)
enc := encryptArmored(out, key, v.addrKey, true)
u.srv.mu.Lock()
defer u.srv.mu.Unlock()
d := u.mustDriveLocked()
changeActiveRevision(func(r *revision) { r.xattr = enc })(d.links[id])
d.logLink(EventUpdate, d.links[id])
}
// insertLink adds an active link l under parentID and returns its new
// ID, created and modified now unless l has those times. It panics if
// parentID has an active or draft child with the same name hash, which
// a seeding test does not mean to create.
func (u *User) insertLink(parentID string, l *link) string {
u.srv.mu.Lock()
defer u.srv.mu.Unlock()
d := u.mustDriveLocked()
if p := d.links[parentID]; p == nil || p.typ != linkTypeFolder {
panic("protontest: no folder " + parentID)
}
for _, other := range d.links {
if other.parentID == parentID && other.nameHash == l.nameHash && other.state != linkStateTrashed {
panic("protontest: name already exists in folder " + parentID)
}
}
now := time.Now().Unix()
if l.createTime == 0 {
l.createTime = now
}
if l.modifyTime == 0 {
l.modifyTime = now
}
l.id, l.parentID, l.state = randomID(), parentID, linkStateActive
d.addLink(l)
d.logLink(EventCreate, l)
return l.id
}
// Corrupt damages node id as a hostile or broken server would. what is
// one of:
//
// - "name": the name no longer decrypts with the parent key
// - "name-signature": the name is signed by an unrelated key
// - "passphrase-signature": the node passphrase signature is by an
// unrelated key
// - "block-hash": the first block's bytes no longer match its hash
// - "manifest": the manifest signature covers different bytes
// - "swap-blocks": the first two blocks trade places, each still
// matching its own hash
// - "truncate-blocks": the last block is dropped from the revision
// - "block-rollback": the active revision serves the blocks of the
// revision before it, which SeedRevision makes, under its own ID,
// manifest signature and extended attributes. (A server serving the
// earlier revision whole under the active revision's ID can't be
// detected, so isn't modelled.)
// - "foreign-block": the first block is the same plaintext encrypted
// with another content key, with its hash and block signature to
// match
// - "content-key-unsigned": the file's content key is one the server
// made, without a signature, and the blocks are encrypted under it
// with the blocks and manifest validly signed
// - "content-key-signature": as "content-key-unsigned", with the
// content key signed by an unrelated key
// - "hash-key-unsigned": the folder's hash key is one the server
// made, without a signature
// - "name-unsigned": the name is encrypted anew under a session key
// the server made, without a signature
// - "xattrs-unsigned": the extended attributes are encrypted anew
// without a signature, claiming ForgedModTime, and for a file a
// size of 1 TiB and ForgedSHA1
func (u *User) Corrupt(id string, what string) {
impostor := generateKey("impostor", "impostor@proton.test")
v := u.view()
l := v.d.links[id]
if l == nil {
panic("protontest: no link " + id)
}
var change func(l *link)
switch what {
case "name":
bad := encryptArmored([]byte("undecryptable"), impostor, nil, false)
change = func(l *link) { l.name = bad }
case "name-signature":
parent, _ := v.parentKey(l)
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, v.now)
mustCrypto("decrypt passphrase", err)
bad := signArmored(passphrase, impostor)
change = func(l *link) { l.nodePass.signature = bad }
case "manifest":
bad := signArmored([]byte("not the manifest"), v.addrKey)
change = changeActiveRevision(func(r *revision) { r.manifestSignature = bad })
case "block-hash":
change = changeActiveRevision(func(r *revision) {
needBlocks(r, 1)
b := *r.blocks[0]
b.data = slices.Clone(b.data)
b.data[len(b.data)/2] ^= 0xff
r.blocks[0] = &b
})
case "swap-blocks":
change = changeActiveRevision(func(r *revision) {
needBlocks(r, 2)
a, b := *r.blocks[0], *r.blocks[1]
a.index, b.index = b.index, a.index
r.blocks[0], r.blocks[1] = &b, &a
})
case "truncate-blocks":
change = changeActiveRevision(func(r *revision) {
needBlocks(r, 1)
r.blocks = r.blocks[:len(r.blocks)-1]
})
case "block-rollback":
var previous *revision
for _, r := range l.revisions {
if r.state == revisionStateObsolete {
previous = r
}
}
if previous == nil {
panic("protontest: no earlier revision of " + id)
}
change = changeActiveRevision(func(r *revision) { r.blocks = slices.Clone(previous.blocks) })
case "foreign-block":
key, sk := v.contentKey(l)
rev := l.activeRevision()
needBlocks(rev, 1)
first := rev.blocks[0]
plain, err := decryptBlock(first.data, first.encSignature, sk, key, v.verifier(first.signatureEmail, key), v.now)
if plain == nil {
mustCrypto("decrypt block", err)
}
data, encSig := newContentKey(key, sk.IsV6()).encryptBlock(plain, key, v.addrKey)
sum := sha256.Sum256(data)
change = changeActiveRevision(func(r *revision) {
b := *r.blocks[0]
b.data, b.hash, b.encSignature = data, sum[:], encSig
r.blocks[0] = &b
})
case "content-key-unsigned", "content-key-signature":
// A content key the server made, with the blocks encrypted
// under it, and the blocks and manifest signed anew by the
// user: more than a server can do, so that only the content
// key's signature can catch it.
key, oldSK := v.contentKey(l)
ck := newContentKey(key, oldSK.IsV6())
sig := ""
if what == "content-key-signature" {
sig = signArmored(ck.sk.Key, impostor)
}
rev := l.activeRevision()
blocks := make([]*block, len(rev.blocks))
var manifest []byte
for i, old := range rev.blocks {
plain, err := decryptBlock(old.data, old.encSignature, oldSK, key, v.verifier(old.signatureEmail, key), v.now)
if plain == nil {
mustCrypto("decrypt block", err)
}
b := *old
b.data, b.encSignature = ck.encryptBlock(plain, key, v.addrKey)
sum := sha256.Sum256(b.data)
b.hash = sum[:]
blocks[i] = &b
manifest = append(manifest, b.hash...)
}
manifestSig := signArmored(manifest, v.addrKey)
reblock := changeActiveRevision(func(r *revision) { r.blocks, r.manifestSignature = blocks, manifestSig })
change = func(l *link) {
l.contentKeyPacket, l.contentKeyPacketSignature = ck.packet, sig
reblock(l)
}
case "hash-key-unsigned":
if l.typ != linkTypeFolder {
panic("protontest: hash-key-unsigned needs a folder")
}
key, _ := v.folderKeys(id)
bad := encryptArmored(newPassphrase(), key, nil, false)
change = func(l *link) { l.hashKey = bad }
case "name-unsigned":
parent, _ := v.parentKey(l)
name, err := decryptArmored(l.name, parent, nil, v.now)
mustCrypto("decrypt name", err)
bad := encryptArmored(name, parent, nil, false)
change = func(l *link) { l.name = bad }
case "xattrs-unsigned":
key, err := v.unlock(id)
if key == nil {
panic(fmt.Sprintf("protontest: unlock %s: %v", id, err))
}
armored := l.xattr
if l.typ == linkTypeFile {
armored = l.activeRevision().xattr
}
var x fileXAttr
if armored != "" {
plain, err := decryptArmored(armored, key, nil, v.now)
mustCrypto("decrypt extended attributes", err)
mustCrypto("parse extended attributes", json.Unmarshal(plain, &x))
}
x.Common.ModificationTime = ForgedModTime
if l.typ == linkTypeFile {
size := int64(1) << 40
x.Common.Size = &size
x.Common.Digests = &struct{ SHA1 string }{SHA1: ForgedSHA1}
}
plain, err := json.Marshal(&x)
mustCrypto("marshal extended attributes", err)
bad := encryptArmored(plain, key, nil, true)
if l.typ == linkTypeFile {
change = changeActiveRevision(func(r *revision) { r.xattr = bad })
} else {
change = func(l *link) { l.xattr = bad }
}
default:
panic("protontest: unknown corruption " + what)
}
u.srv.mu.Lock()
defer u.srv.mu.Unlock()
d := u.mustDriveLocked()
change(d.links[id])
d.logLink(EventUpdate, d.links[id])
}
// contentKey returns the node key and content session key of file l,
// ignoring signature errors. It panics if either can't be decrypted.
func (v *driveView) contentKey(l *link) (*crypto.Key, *crypto.SessionKey) {
key, err := v.unlock(l.id)
if key == nil {
panic(fmt.Sprintf("protontest: unlock file %s: %v", l.id, err))
}
sk, err := decryptContentKey(l.contentKeyPacket, l.contentKeyPacketSignature, key, v.verifier(l.signatureEmail, key), v.now)
if sk == nil {
panic(fmt.Sprintf("protontest: content key of %s: %v", l.id, err))
}
return key, sk
}
// NodeSecrets returns the decrypted node passphrase and content session
// key of file id, for tests to check a client never reveals them. It
// panics if id is not a file or they can't be decrypted.
func (u *User) NodeSecrets(id string) (passphrase, sessionKey []byte) {
v := u.view()
l := v.d.links[id]
if l == nil || l.typ != linkTypeFile {
panic("protontest: no file " + id)
}
_, sk := v.contentKey(l)
parent, err := v.parentKey(l)
if parent == nil {
panic(fmt.Sprintf("protontest: parent key of %s: %v", id, err))
}
passphrase, err = decryptArmored(l.nodePass.armored, parent, nil, v.now)
mustCrypto("decrypt passphrase", err)
return passphrase, sk.Key
}
// NameSessionKey returns the session key of the stored name of node
// id, for tests to check which key a rename or move used. It panics if
// it can't be decrypted.
func (u *User) NameSessionKey(id string) []byte {
v := u.view()
l := v.d.links[id]
if l == nil {
panic("protontest: no link " + id)
}
parent, err := v.parentKey(l)
if parent == nil {
panic(fmt.Sprintf("protontest: parent key of %s: %v", id, err))
}
msg, err := crypto.NewPGPMessageFromArmored(l.name)
mustCrypto("read name", err)
dh, err := crypto.PGP().Decryption().DecryptionKey(parent).New()
mustCrypto("decrypt name", err)
sk, err := dh.DecryptSessionKey(msg.BinaryKeyPacket())
mustCrypto("decrypt name session key", err)
return sk.Key
}
// needBlocks panics unless r has at least n blocks.
func needBlocks(r *revision, n int) {
if len(r.blocks) < n {
panic(fmt.Sprintf("protontest: revision %s has %d blocks, corruption needs %d", r.id, len(r.blocks), n))
}
}
// changeActiveRevision returns a change which applies fn to a copy of
// the active revision of a link, with its own block list, and stores
// the copy in its place.
func changeActiveRevision(fn func(r *revision)) func(l *link) {
return func(l *link) {
for i, r := range l.revisions {
if r.state != revisionStateActive {
continue
}
c := *r
c.blocks = slices.Clone(r.blocks)
fn(&c)
l.revisions[i] = &c
return
}
panic("protontest: no active revision in " + l.id)
}
}
// DumpedNode is a decrypted node of a user's drive.
type DumpedNode struct {
ID string
Path string // slash separated names from the root, which is not dumped
IsFolder bool
Content []byte // decrypted content of the active revision
ModTime time.Time // claimed in the extended attributes, zero if absent
SHA1 string // claimed in the extended attributes, empty if absent
State int // 1 active, 2 trashed
Err error // every decryption, verification or consistency failure
}
// Dump decrypts u's drive and returns every node except the root and
// 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)
var out []DumpedNode
for id, l := range v.d.links {
if id == v.d.rootID || l.state == linkStateDraft {
continue
}
n := DumpedNode{ID: id, IsFolder: l.typ == linkTypeFolder, State: l.state}
var errs []error
var nameErr error
n.Path, nameErr = v.path(id, paths)
errs = append(errs, nameErr, v.checkNameHash(l))
key, err := v.unlock(id)
if err != nil {
errs = append(errs, fmt.Errorf("node key: %w", err))
}
if key != nil {
if n.IsFolder {
errs = append(errs, v.dumpFolder(l, key, &n))
} else {
errs = append(errs, v.dumpFile(l, key, &n))
}
}
n.Err = errors.Join(errs...)
out = append(out, n)
}
sort.Slice(out, func(i, j int) bool {
if out[i].Path != out[j].Path {
return out[i].Path < out[j].Path
}
return out[i].ID < out[j].ID
})
return out
}
// path returns the slash separated path of link id below the root,
// using "<id>" for a name which cannot be decrypted.
func (v *driveView) path(id string, cache map[string]string) (string, error) {
if p, ok := cache[id]; ok {
return p, nil
}
l := v.d.links[id]
if l.parentID == "" {
return "", nil
}
var nameErr error
name := "<" + id + ">"
parent, err := v.unlock(l.parentID)
if parent == nil {
nameErr = fmt.Errorf("name: %w", err)
} else {
plain, err := decryptArmored(l.name, parent, v.verifier(l.nameSignatureEmail, parent), v.now)
switch {
case plain != nil:
name = string(plain)
if err != nil {
nameErr = fmt.Errorf("name: %w", err)
}
default:
nameErr = fmt.Errorf("name: %w", err)
}
}
parentPath, _ := v.path(l.parentID, cache)
p := name
if parentPath != "" {
p = parentPath + "/" + name
}
if nameErr == nil {
cache[id] = p
}
return p, nameErr
}
// checkNameHash checks the name hash of l against its name and its
// parent's hash key. A name or parent key which can't be decrypted is
// left to path to report.
func (v *driveView) checkNameHash(l *link) error {
if l.parentID == "" {
return nil
}
parent, _ := v.unlock(l.parentID)
if parent == nil {
return 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, v.now)
if err != nil {
return fmt.Errorf("name hash: parent hash key: %w", err)
}
if want := lookupHash(hashKey, string(name)); l.nameHash != want {
return fmt.Errorf("name hash is %s, want %s", l.nameHash, want)
}
return nil
}
// dumpFolder checks the hash key and reads the extended attributes of
// folder l.
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, 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), v.now)
if err != nil {
errs = append(errs, fmt.Errorf("extended attributes: %w", err))
}
var x fileXAttr
if plain != nil {
if err := json.Unmarshal(plain, &x); err != nil {
errs = append(errs, fmt.Errorf("extended attributes: %w", err))
}
if x.Common.ModificationTime != "" {
n.ModTime, err = parseXAttrTime(x.Common.ModificationTime)
errs = append(errs, err)
}
}
}
return errors.Join(errs...)
}
// dumpFile decrypts and checks the active revision of file l.
func (v *driveView) dumpFile(l *link, key *crypto.Key, n *DumpedNode) error {
rev := l.activeRevision()
if rev == nil {
return errors.New("no active revision")
}
var errs []error
sk, err := decryptContentKey(l.contentKeyPacket, l.contentKeyPacketSignature, key, v.verifier(l.signatureEmail, key), v.now)
if err != nil {
errs = append(errs, err)
}
var manifest []byte
var blockSizes []int64
for i, b := range rev.blocks {
manifest = append(manifest, b.hash...)
if b.index != i+1 {
errs = append(errs, fmt.Errorf("block %d has index %d", i+1, b.index))
}
if sum := sha256.Sum256(b.data); !bytes.Equal(sum[:], b.hash) {
errs = append(errs, fmt.Errorf("block %d: hash mismatch", b.index))
continue
}
if sk == nil {
continue
}
signer := b.signatureEmail
if signer == "" {
signer = rev.signatureEmail
}
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), v.now); err != nil {
errs = append(errs, fmt.Errorf("manifest: %w", err))
}
if rev.xattr != "" {
errs = append(errs, v.dumpFileXAttr(rev, key, blockSizes, n))
}
return errors.Join(errs...)
}
// dumpFileXAttr reads the extended attributes of rev and checks their
// 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), v.now)
if err != nil {
errs = append(errs, fmt.Errorf("extended attributes: %w", err))
}
if plain == nil {
return errors.Join(errs...)
}
var x fileXAttr
if err := json.Unmarshal(plain, &x); err != nil {
return errors.Join(append(errs, fmt.Errorf("extended attributes: %w", err))...)
}
c := x.Common
if c.ModificationTime != "" {
n.ModTime, err = parseXAttrTime(c.ModificationTime)
errs = append(errs, err)
}
if c.Size != nil && *c.Size != int64(len(n.Content)) {
errs = append(errs, fmt.Errorf("extended attributes claim size %d, content is %d", *c.Size, len(n.Content)))
}
if c.BlockSizes != nil && !slices.Equal(c.BlockSizes, blockSizes) {
errs = append(errs, fmt.Errorf("extended attributes claim block sizes %v, blocks are %v", c.BlockSizes, blockSizes))
}
if c.Digests != nil {
n.SHA1 = c.Digests.SHA1
if sum := sha1.Sum(n.Content); n.SHA1 != hex.EncodeToString(sum[:]) {
errs = append(errs, fmt.Errorf("extended attributes claim SHA1 %s, content has %x", n.SHA1, sum))
}
}
return errors.Join(errs...)
}
// Drafts returns the IDs of u's uncommitted drafts: links in the draft
// state, and draft revisions of other links.
func (u *User) Drafts() []string {
u.srv.mu.Lock()
defer u.srv.mu.Unlock()
var ids []string
for _, l := range u.mustDriveLocked().links {
if l.state == linkStateDraft {
ids = append(ids, l.id)
continue
}
for _, r := range l.revisions {
if r.state == revisionStateDraft {
ids = append(ids, r.id)
}
}
}
sort.Strings(ids)
return ids
}
// Wire types of the drive routes, named after and shaped like the
// schemas in the SDK's driveTypes.ts.
type volumeJSON struct {
VolumeID string
UsedSpace int64
}
type shareJSON struct {
ShareID string
CreatorEmail string
Key string
Passphrase string
PassphraseSignature string
AddressID string
}
type ownedByJSON struct {
Email *string
Organization *string
}
type linkJSON struct {
LinkID string
Type int
ParentLinkID *string
State int
CreateTime int64
ModifyTime int64
TrashTime *int64
Name string
NameHash *string
NodeKey string
NodePassphrase string
NodePassphraseSignature string
SignatureEmail *string
NameSignatureEmail *string
OwnedBy ownedByJSON
DirectPermissions *int
ThirdParty bool
Sdk bool
}
type folderJSON struct {
NodeHashKey *string
XAttr *string
IsImported bool
}
type thumbnailJSON struct{}
type activeRevisionJSON struct {
Photo *struct{}
RevisionID string
CreateTime int64
EncryptedSize int64
ChecksumVerified bool
ManifestSignature *string
XAttr *string
Thumbnails []thumbnailJSON
SignatureEmail *string
IsImported bool
ThirdParty bool
Sdk bool
}
type fileJSON struct {
ActiveRevision *activeRevisionJSON
TotalEncryptedSize int64
ContentKeyPacket string
MediaType *string
ContentKeyPacketSignature *string
}
type linkDetailsJSON struct {
Link linkJSON
Folder *folderJSON
File *fileJSON
Sharing *struct{}
Membership *struct{}
Album *struct{}
}
type shareReferenceJSON struct {
ShareID string
ID string
LinkID string
}
type volumeResponseJSON struct {
ID string
CreationTime int64
MaxSpace *int64
VolumeID string
CreateTime int64
ModifyTime int64
UsedSpace int64
DownloadedBytes int64
UploadedBytes int64
State int
Share shareReferenceJSON
Type int
}
type getVolumeResponse struct {
Volume volumeResponseJSON
Code int
}
type myFilesResponse struct {
Volume volumeJSON
Share shareJSON
Link linkDetailsJSON
Code int
}
type shareResponse struct {
ShareID string
VolumeID string
Type int
State int
VolumeType int
Creator string
Locked *bool
CreateTime int64
ModifyTime int64
LinkID string
CreationTime int64
PermissionsMask int
LinkType int
Flags int
BlockSize int
VolumeSoftDeleted bool
Key string
Passphrase string
PassphraseSignature string
AddressID *string
AddressKeyID *string
Memberships []struct{}
PossibleKeyPackets []struct{}
RootLinkRecoveryPassphrase *string
EditorsCanShare bool
Code int
}
type linksRequest struct {
LinkIDs []string
}
type linksResponse struct {
Links []linkDetailsJSON
Code int
}
type childrenResponse struct {
LinkIDs []string
AnchorID *string
More bool
Code int
}
type blockJSON struct {
Index int
Hash string
Token *string
BareURL *string
EncSignature *string
SignatureEmail *string
}
type revisionJSON struct {
Blocks []blockJSON
Photo *struct{}
ID string
ManifestSignature *string
Size int64
State int
XAttr *string
Thumbnail int
ThumbnailHash *string
ThumbnailSize int
Thumbnails []thumbnailJSON
ChecksumVerified bool
ClientUID *string
IsImported bool
ThirdParty bool
Sdk bool
CreateTime int64
SignatureEmail *string
SignatureAddress *string
}
type revisionResponse struct {
Revision revisionJSON
Code int
}
// createVolumeRequest is the body of POST /drive/volumes.
type createVolumeRequest struct {
AddressID string
ShareKey string
SharePassphrase string
SharePassphraseSignature string
FolderName string
FolderKey string
FolderPassphrase string
FolderPassphraseSignature string
FolderHashKey string
AddressKeyID *string
VolumeName *string
ShareName *string
}
// nullable returns nil for an empty string, which the API sends as null.
func nullable(s string) *string {
if s == "" {
return nil
}
return &s
}
// linkDetails returns the wire form of l. srv.mu must be held.
func (d *drive) linkDetails(l *link) linkDetailsJSON {
out := linkDetailsJSON{Link: linkJSON{
LinkID: l.id,
Type: l.typ,
ParentLinkID: nullable(l.parentID),
State: l.state,
CreateTime: l.createTime,
ModifyTime: l.modifyTime,
Name: l.name,
NameHash: nullable(l.nameHash),
NodeKey: l.nodeKey,
NodePassphrase: l.nodePass.armored,
NodePassphraseSignature: l.nodePass.signature,
SignatureEmail: nullable(l.signatureEmail),
NameSignatureEmail: nullable(l.nameSignatureEmail),
OwnedBy: ownedByJSON{Email: nullable(d.creatorEmail)},
}}
if l.trashTime != 0 {
out.Link.TrashTime = &l.trashTime
}
if l.typ == linkTypeFolder {
out.Folder = &folderJSON{NodeHashKey: nullable(l.hashKey), XAttr: nullable(l.xattr)}
return out
}
f := &fileJSON{
ContentKeyPacket: l.contentKeyPacket,
MediaType: nullable(l.mediaType),
ContentKeyPacketSignature: nullable(l.contentKeyPacketSignature),
}
for _, r := range l.revisions {
f.TotalEncryptedSize += r.size()
}
if r := l.activeRevision(); r != nil {
f.ActiveRevision = &activeRevisionJSON{
RevisionID: r.id,
CreateTime: r.createTime,
EncryptedSize: r.size(),
ManifestSignature: nullable(r.manifestSignature),
XAttr: nullable(r.xattr),
Thumbnails: []thumbnailJSON{},
SignatureEmail: nullable(r.signatureEmail),
}
}
out.File = f
return out
}
// registerDrive registers the drive routes.
func (s *Server) registerDrive() {
s.handleAuth("GET", "/drive/v2/shares/my-files", s.handleMyFiles)
s.handleAuth("POST", "/drive/volumes", s.handleCreateVolume)
s.handleDrive("GET", "/drive/volumes/{volumeID}", s.handleVolume)
s.handleAuth("GET", "/drive/shares/{shareID}", s.handleShare)
s.handleDrive("POST", "/drive/v2/volumes/{volumeID}/links", s.handleLinks)
s.handleDrive("GET", "/drive/v2/volumes/{volumeID}/folders/{linkID}/children", s.handleChildren)
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()
s.registerEvents()
}
// handleDrive registers h for an authenticated route under
// {volumeID}, which must be the user's volume. h is called with srv.mu
// held.
func (s *Server) handleDrive(method, pattern string, h func(w http.ResponseWriter, r *http.Request, u *User, d *drive)) {
s.handleAuth(method, pattern, func(w http.ResponseWriter, r *http.Request, u *User) {
s.mu.Lock()
defer s.mu.Unlock()
if u.drive == nil || u.drive.volumeID != r.PathValue("volumeID") {
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Volume not found")
return
}
h(w, r, u, u.drive)
})
}
// handleMyFiles returns the user's volume, main share and root folder,
// or HTTP 422 code 2501 if the user has no volume yet.
func (s *Server) handleMyFiles(w http.ResponseWriter, r *http.Request, u *User) {
s.mu.Lock()
defer s.mu.Unlock()
d := u.drive
if d == nil {
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Volume not found")
return
}
writeJSON(w, http.StatusOK, &myFilesResponse{
Volume: volumeJSON{VolumeID: d.volumeID, UsedSpace: d.usedSpace()},
Share: shareJSON{
ShareID: d.shareID,
CreatorEmail: d.creatorEmail,
Key: d.shareKey,
Passphrase: d.sharePass.armored,
PassphraseSignature: d.sharePass.signature,
AddressID: d.addressID,
},
Link: d.linkDetails(d.links[d.rootID]),
Code: api.CodeOK,
})
}
// volumeResponse returns the wire form of d's volume.
func (d *drive) volumeResponse() *getVolumeResponse {
return &getVolumeResponse{
Volume: volumeResponseJSON{
ID: d.volumeID,
CreationTime: d.createTime,
VolumeID: d.volumeID,
CreateTime: d.createTime,
ModifyTime: d.createTime,
UsedSpace: d.usedSpace(),
State: 1,
Share: shareReferenceJSON{ShareID: d.shareID, ID: d.shareID, LinkID: d.rootID},
Type: 1,
},
Code: api.CodeOK,
}
}
// handleVolume returns the user's volume.
func (s *Server) handleVolume(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
writeJSON(w, http.StatusOK, d.volumeResponse())
}
// handleShare returns the user's main share.
func (s *Server) handleShare(w http.ResponseWriter, r *http.Request, u *User) {
s.mu.Lock()
defer s.mu.Unlock()
d := u.drive
if d == nil || d.shareID != r.PathValue("shareID") {
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Share not found")
return
}
locked := false
writeJSON(w, http.StatusOK, &shareResponse{
ShareID: d.shareID,
VolumeID: d.volumeID,
Type: 1,
State: 1,
VolumeType: 1,
Creator: d.creatorEmail,
Locked: &locked,
CreateTime: d.createTime,
ModifyTime: d.createTime,
LinkID: d.rootID,
CreationTime: d.createTime,
LinkType: linkTypeFolder,
BlockSize: blockSize,
Key: d.shareKey,
Passphrase: d.sharePass.armored,
PassphraseSignature: d.sharePass.signature,
AddressID: &d.addressID,
AddressKeyID: &d.addressKeyID,
Memberships: []struct{}{},
PossibleKeyPackets: []struct{}{},
Code: api.CodeOK,
})
}
// handleLinks returns the metadata of up to 100 links. Unknown IDs are
// left out, as the API does.
func (s *Server) handleLinks(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
var req linksRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: bad links request: "+err.Error())
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 := &linksResponse{Links: []linkDetailsJSON{}, Code: api.CodeOK}
for _, id := range req.LinkIDs {
l := d.links[id]
if l == nil {
continue
}
details := d.linkDetails(l)
if v := s.lagging[id]; v != nil {
if v.reads--; v.reads <= 0 {
delete(s.lagging, id)
}
switch {
case v.view == LagNoRevision && details.File != nil:
details.File.ActiveRevision = nil
case v.view == LagMissing || v.before == nil:
continue
default:
details = *v.before
}
}
resp.Links = append(resp.Links, details)
}
writeJSON(w, http.StatusOK, resp)
}
// LagView is what a lagging read of a changed node sees.
type LagView int
const (
// LagBefore shows the node as it was before the change, or leaves
// it out if it is new.
LagBefore LagView = iota
// LagMissing leaves the node out.
LagMissing
// LagNoRevision shows a file as it is but without an active
// revision; a new node is left out.
LagNoRevision
)
// lagView is what reads of a node see until its change shows.
type lagView struct {
reads int // reads left which don't see the change
view LagView // what they see
before *linkDetailsJSON // the node before the change; nil if it is new
}
// SetReadLag makes the first reads reads of a node through the links
// route, after it is created, copied or has a revision committed, see
// it as view says instead of as it is, as Proton's servers may for a
// moment. Zero reads, the default, turns the lag off.
func (s *Server) SetReadLag(reads int, view LagView) {
s.mu.Lock()
defer s.mu.Unlock()
s.readLag, s.readLagView = reads, view
}
// lagLocked starts the read lag, if any, of node id after a change;
// before is its wire form before the change, or nil if it is new.
// srv.mu must be held.
func (s *Server) lagLocked(id string, before *linkDetailsJSON) {
if s.readLag <= 0 {
return
}
s.lagging[id] = &lagView{reads: s.readLag, view: s.readLagView, before: before}
}
// handleChildren returns a page of the IDs of the active children of a
// folder in creation order, after AnchorID if given.
func (s *Server) handleChildren(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
parent := d.links[r.PathValue("linkID")]
if parent == nil || parent.typ != linkTypeFolder {
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Folder not found")
return
}
q := r.URL.Query()
foldersOnly := q.Get("FoldersOnly") == "1"
var children []*link
for _, l := range d.links {
if l.parentID == parent.id && l.state == linkStateActive && (!foldersOnly || l.typ == linkTypeFolder) {
children = append(children, l)
}
}
sort.Slice(children, func(i, j int) bool { return children[i].seq < children[j].seq })
start := 0
if anchor := q.Get("AnchorID"); anchor != "" {
start = slices.IndexFunc(children, func(l *link) bool { return l.id == anchor }) + 1
if start == 0 {
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidValue, "protontest: unknown AnchorID")
return
}
}
end := min(start+s.childrenPageSize, len(children))
resp := &childrenResponse{LinkIDs: []string{}, Code: api.CodeOK}
for _, l := range children[start:end] {
resp.LinkIDs = append(resp.LinkIDs, l.id)
}
if end < len(children) {
resp.More = true
resp.AnchorID = &children[end-1].id
}
writeJSON(w, http.StatusOK, resp)
}
// handleRevision returns a revision with a page of its blocks, from
// index FromBlockIndex (default 1), at most PageSize (default all),
// with download URLs on this server unless NoBlockUrls is set.
func (s *Server) handleRevision(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
l := d.links[r.PathValue("linkID")]
if l == nil || l.typ != linkTypeFile {
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "File not found")
return
}
i := slices.IndexFunc(l.revisions, func(rev *revision) bool { return rev.id == r.PathValue("revisionID") })
if i < 0 {
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Revision not found")
return
}
rev := l.revisions[i]
q := r.URL.Query()
from, pageSize := 1, len(rev.blocks)
var err1, err2 error
if v := q.Get("FromBlockIndex"); v != "" {
from, err1 = strconv.Atoi(v)
}
if v := q.Get("PageSize"); v != "" {
pageSize, err2 = strconv.Atoi(v)
}
if err := errors.Join(err1, err2); err != nil || from < 1 || pageSize < 1 {
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidValue, "protontest: bad FromBlockIndex or PageSize")
return
}
noURLs := q.Get("NoBlockUrls") == "1" || strings.EqualFold(q.Get("NoBlockUrls"), "true")
out := revisionJSON{
Blocks: []blockJSON{},
ID: rev.id,
ManifestSignature: nullable(rev.manifestSignature),
Size: rev.size(),
State: rev.state,
XAttr: nullable(rev.xattr),
Thumbnails: []thumbnailJSON{},
ClientUID: nullable(rev.clientUID),
CreateTime: rev.createTime,
SignatureEmail: nullable(rev.signatureEmail),
}
for _, b := range rev.blocks {
if b.index < from || len(out.Blocks) >= pageSize {
continue
}
bj := blockJSON{
Index: b.index,
Hash: base64.StdEncoding.EncodeToString(b.hash),
EncSignature: nullable(b.encSignature),
SignatureEmail: nullable(b.signatureEmail),
}
if !noURLs {
id, token := randomID(), s.newSecretLocked(StorageToken)
s.downloads[id] = &download{token: token, block: b}
bareURL := s.URL() + "/storage/blocks/" + id
bj.Token, bj.BareURL = &token, &bareURL
}
out.Blocks = append(out.Blocks, bj)
}
writeJSON(w, http.StatusOK, &revisionResponse{Revision: out, Code: api.CodeOK})
}
// handleBlock serves the bytes of a block URL issued by handleRevision
// to a request carrying its pm-storage-token.
func (s *Server) handleBlock(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
dl := s.downloads[r.PathValue("id")]
s.mu.Unlock()
switch {
case dl == nil:
writeError(w, http.StatusNotFound, api.CodeNotExists, "protontest: no such block")
case r.Header.Get("pm-storage-token") != dl.token:
writeError(w, http.StatusForbidden, api.CodeNotEnoughPermissions, "protontest: missing or wrong pm-storage-token")
default:
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Length", strconv.Itoa(len(dl.block.data)))
_, _ = w.Write(dl.block.data)
}
}
// handleCreateVolume creates the user's volume from key material the
// client generated, after checking that it decrypts with the user's
// address key, or answers HTTP 422.
func (s *Server) handleCreateVolume(w http.ResponseWriter, r *http.Request, u *User) {
var req createVolumeRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: bad create volume request: "+err.Error())
return
}
s.mu.Lock()
var addr *address
for _, a := range u.addresses {
if a.id == req.AddressID {
addr = a
}
}
exists := u.drive != nil
s.mu.Unlock()
if exists {
writeError(w, http.StatusUnprocessableEntity, api.CodeAlreadyExists, "protontest: volume already exists")
return
}
if addr == nil {
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidValue, "protontest: unknown AddressID")
return
}
addrKey := addr.keys[0]
if req.AddressKeyID != nil {
i := slices.IndexFunc(addr.keys, func(k *addressKey) bool { return k.id == *req.AddressKeyID })
if i < 0 {
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidValue, "protontest: unknown AddressKeyID")
return
}
addrKey = addr.keys[i]
}
// go-crypto records signature checks in the key on first use, so
// concurrent checks each need their own copy of a key nothing has
// used yet.
checkKey, err := addrKey.key.Copy()
if err != nil {
writeError(w, http.StatusInternalServerError, 0, "protontest: copy address key: "+err.Error())
return
}
if err := checkVolumeRequest(&req, checkKey, s.unlockKey); err != nil {
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidValue, "protontest: invalid volume key material: "+err.Error())
return
}
s.mu.Lock()
defer s.mu.Unlock()
if u.drive != nil {
writeError(w, http.StatusUnprocessableEntity, api.CodeAlreadyExists, "protontest: volume already exists")
return
}
u.drive = assembleDrive(addr.id, addrKey.id, addr.email, &req)
writeJSON(w, http.StatusOK, u.drive.volumeResponse())
}
// checkVolumeRequest checks that the share key in req unlocks with
// addrKey and the root folder's key, name and hash key with the share
// key, every signature by addrKey (or, for the hash key, the folder
// 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, 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, time.Time{})
if err != nil {
return fmt.Errorf("folder key: %w", err)
}
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), time.Time{})
if err != nil {
return fmt.Errorf("folder hash key: %w", err)
}
if len(hashKey) == 0 {
return errors.New("empty folder hash key")
}
return nil
}