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
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>
768 lines
23 KiB
Go
768 lines
23 KiB
Go
package protontest
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"slices"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/ProtonMail/go-crypto/openpgp/armor"
|
|
"github.com/ProtonMail/go-crypto/openpgp/packet"
|
|
"github.com/ProtonMail/go-crypto/openpgp/s2k"
|
|
"github.com/rclone/rclone/backend/protondrive/api"
|
|
)
|
|
|
|
// OpenPGP packet tags checked in client-written values.
|
|
const (
|
|
tagPKESK = 1
|
|
tagSignature = 2
|
|
tagSecretKey = 5
|
|
tagSecretSubkey = 7
|
|
tagSEIPD = 18
|
|
)
|
|
|
|
// s2kUsageSHA1 is the S2K usage octet of a secret key locked with CFB
|
|
// and a SHA-1 check, as ordinary (not AEAD) key locking writes.
|
|
const s2kUsageSHA1 = 254
|
|
|
|
// Wire types of the mutating routes, named after and shaped like the
|
|
// schemas in the SDK's driveTypes.ts.
|
|
|
|
type createFolderRequest struct {
|
|
ParentLinkID string
|
|
NodeKey string
|
|
NodeHashKey string
|
|
NodePassphrase string
|
|
NodePassphraseSignature string
|
|
SignatureEmail *string
|
|
Name string
|
|
Hash string
|
|
XAttr *string
|
|
}
|
|
|
|
type folderIDJSON struct {
|
|
ID string
|
|
}
|
|
|
|
type createFolderResponse struct {
|
|
Folder folderIDJSON
|
|
Code int
|
|
}
|
|
|
|
type renameRequest struct {
|
|
Name string
|
|
Hash *string
|
|
NameSignatureEmail *string
|
|
OriginalHash *string
|
|
}
|
|
|
|
type moveRequest struct {
|
|
Name string
|
|
NodePassphrase string
|
|
Hash string
|
|
ParentLinkID string
|
|
OriginalHash string
|
|
NameSignatureEmail *string
|
|
ContentHash *string
|
|
NodePassphraseSignature *string
|
|
SignatureEmail *string
|
|
}
|
|
|
|
type copyRequest struct {
|
|
Name string
|
|
NodePassphrase string
|
|
Hash string
|
|
TargetVolumeID string
|
|
TargetParentLinkID string
|
|
NameSignatureEmail *string
|
|
NodePassphraseSignature *string
|
|
SignatureEmail *string
|
|
}
|
|
|
|
type copyResponse struct {
|
|
LinkID string
|
|
Code int
|
|
}
|
|
|
|
type codeJSON struct {
|
|
Code int
|
|
Error string `json:",omitempty"`
|
|
}
|
|
|
|
type linkResultJSON struct {
|
|
LinkID string
|
|
Response codeJSON
|
|
}
|
|
|
|
type multiResponse struct {
|
|
Code int
|
|
Responses []linkResultJSON
|
|
}
|
|
|
|
type checkHashesRequest struct {
|
|
Hashes []string
|
|
ClientUID []string
|
|
}
|
|
|
|
type pendingHashJSON struct {
|
|
Hash string
|
|
RevisionID string
|
|
LinkID string
|
|
ClientUID *string
|
|
}
|
|
|
|
type availableHashesResponse struct {
|
|
AvailableHashes []string
|
|
PendingHashes []pendingHashJSON
|
|
Code int
|
|
}
|
|
|
|
type conflictDetailsJSON struct {
|
|
ConflictLinkID string
|
|
ConflictRevisionID *string
|
|
ConflictDraftRevisionID *string
|
|
ConflictDraftClientUID *string
|
|
}
|
|
|
|
type conflictResponse struct {
|
|
Code int
|
|
Error string
|
|
Details conflictDetailsJSON
|
|
}
|
|
|
|
// registerMutations registers the routes which change a drive.
|
|
func (s *Server) registerMutations() {
|
|
s.handleDrive("POST", "/drive/v2/volumes/{volumeID}/folders", s.handleCreateFolder)
|
|
s.handleDrive("PUT", "/drive/v2/volumes/{volumeID}/links/{linkID}/rename", s.handleRename)
|
|
s.handleDrive("PUT", "/drive/v2/volumes/{volumeID}/links/{linkID}/move", s.handleMove)
|
|
s.handleDrive("POST", "/drive/volumes/{volumeID}/links/{linkID}/copy", s.handleCopy)
|
|
s.handleDrive("POST", "/drive/v2/volumes/{volumeID}/trash_multiple", s.handleTrash)
|
|
s.handleDrive("DELETE", "/drive/volumes/{volumeID}/trash", s.handleEmptyTrash)
|
|
s.handleDrive("POST", "/drive/v2/volumes/{volumeID}/links/{linkID}/checkAvailableHashes", s.handleCheckAvailableHashes)
|
|
}
|
|
|
|
// decodeRequest decodes the JSON body of r into v, or answers HTTP 400
|
|
// and returns false.
|
|
func decodeRequest(w http.ResponseWriter, r *http.Request, v any) bool {
|
|
if err := json.NewDecoder(r.Body).Decode(v); err != nil {
|
|
writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: bad request body: "+err.Error())
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
// writeInvalid answers HTTP 422 code 2001 for a request failing check.
|
|
func writeInvalid(w http.ResponseWriter, err error) {
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidValue, "protontest: "+err.Error())
|
|
}
|
|
|
|
// writeConflict answers HTTP 422 code 2500 for a request whose name
|
|
// hash is taken by l.
|
|
func writeConflict(w http.ResponseWriter, l *link) {
|
|
details := conflictDetailsJSON{ConflictLinkID: l.id}
|
|
for _, r := range l.revisions {
|
|
switch r.state {
|
|
case revisionStateActive:
|
|
details.ConflictRevisionID = nullable(r.id)
|
|
case revisionStateDraft:
|
|
details.ConflictDraftRevisionID = nullable(r.id)
|
|
details.ConflictDraftClientUID = nullable(r.clientUID)
|
|
}
|
|
}
|
|
writeJSON(w, http.StatusUnprocessableEntity, &conflictResponse{
|
|
Code: api.CodeAlreadyExists,
|
|
Error: "A file or folder with that name already exists",
|
|
Details: details,
|
|
})
|
|
}
|
|
|
|
// activeLink returns the active link id, or nil.
|
|
func (d *drive) activeLink(id string) *link {
|
|
if l := d.links[id]; l != nil && l.state == linkStateActive {
|
|
return l
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// activeFolder returns the active folder id, or nil.
|
|
func (d *drive) activeFolder(id string) *link {
|
|
if l := d.activeLink(id); l != nil && l.typ == linkTypeFolder {
|
|
return l
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// conflict returns the link other than except in folder parentID
|
|
// which is not trashed and has the name hash hash, or nil.
|
|
func (d *drive) conflict(parentID, hash, except string) *link {
|
|
for _, l := range d.links {
|
|
if l.parentID == parentID && l.nameHash == hash && l.state != linkStateTrashed && l.id != except {
|
|
return l
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// within reports whether link id is ancestorID or below it.
|
|
func (d *drive) within(id, ancestorID string) bool {
|
|
for l := d.links[id]; l != nil; l = d.links[l.parentID] {
|
|
if l.id == ancestorID {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// inTrash reports whether l or one of its ancestors is trashed.
|
|
func (d *drive) inTrash(l *link) bool {
|
|
for ; l != nil; l = d.links[l.parentID] {
|
|
if l.state == linkStateTrashed {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// ownsEmailLocked reports whether email is one of u's addresses.
|
|
// srv.mu must be held.
|
|
func (u *User) ownsEmailLocked(email string) bool {
|
|
return u.addressByEmailLocked(email) != nil
|
|
}
|
|
|
|
// checkHash returns an error unless hash is a lower-case hex SHA-256.
|
|
func checkHash(hash string) error {
|
|
if len(hash) != 64 || strings.ToLower(hash) != hash {
|
|
return fmt.Errorf("hash %q is not lower-case hex SHA-256", hash)
|
|
}
|
|
if _, err := hex.DecodeString(hash); err != nil {
|
|
return fmt.Errorf("hash %q is not lower-case hex SHA-256", hash)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// checkSigner returns an error unless email is one of u's addresses.
|
|
func checkSigner(u *User, field string, email *string) error {
|
|
if email == nil || !u.ownsEmailLocked(*email) {
|
|
return fmt.Errorf("%s must be an address of the user", field)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// checkMessages checks every named armored message with checkMessage.
|
|
func checkMessages(messages map[string]string) error {
|
|
for field, armored := range messages {
|
|
if err := checkMessage(armored); err != nil {
|
|
return fmt.Errorf("%s: %w", field, err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// checkMessage returns an error unless armored is an OpenPGP message of
|
|
// v3 PKESKs followed by one SEIPDv1 packet.
|
|
//
|
|
// Official clients write names, passphrases, hash keys and extended
|
|
// attributes in that format and not all of them read SEIPDv2 or v6
|
|
// PKESKs there, whatever the recipient key accepts.
|
|
func checkMessage(armored string) error {
|
|
if armored == "" {
|
|
return errors.New("missing")
|
|
}
|
|
block, err := armor.Decode(strings.NewReader(armored))
|
|
if err != nil {
|
|
return fmt.Errorf("not armored: %w", err)
|
|
}
|
|
if block.Type != "PGP MESSAGE" {
|
|
return fmt.Errorf("armor type %q, want PGP MESSAGE", block.Type)
|
|
}
|
|
packets := packet.NewOpaqueReader(block.Body)
|
|
keyPackets, dataPackets := 0, 0
|
|
for {
|
|
op, err := packets.Next()
|
|
if err == io.EOF {
|
|
break
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("malformed packet: %w", err)
|
|
}
|
|
if dataPackets > 0 {
|
|
return errors.New("packet after the encrypted data")
|
|
}
|
|
version := -1
|
|
if len(op.Contents) > 0 {
|
|
version = int(op.Contents[0])
|
|
}
|
|
switch op.Tag {
|
|
case tagPKESK:
|
|
if version != 3 {
|
|
return fmt.Errorf("v%d PKESK, want v3", version)
|
|
}
|
|
keyPackets++
|
|
case tagSEIPD:
|
|
if version != 1 {
|
|
return fmt.Errorf("SEIPDv%d, want SEIPDv1", version)
|
|
}
|
|
dataPackets++
|
|
default:
|
|
return fmt.Errorf("unexpected packet with tag %d", op.Tag)
|
|
}
|
|
}
|
|
if keyPackets == 0 || dataPackets == 0 {
|
|
return errors.New("want PKESKs and an encrypted data packet")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// checkFolderKey returns an error unless armored is a v4 secret key
|
|
// whose signatures don't advertise AEAD, with every secret key packet
|
|
// locked with CFB and an iterated and salted S2K, as official clients
|
|
// generate folder keys. The official web app can't use a node key
|
|
// locked with Argon2 or AEAD.
|
|
func checkFolderKey(armored string) error {
|
|
return checkNodeKey(armored, false)
|
|
}
|
|
|
|
// checkFileKey returns an error unless armored is a v4 secret key
|
|
// locked as checkFolderKey requires. Unlike a folder key, a file key
|
|
// advertises AEAD, for its content.
|
|
func checkFileKey(armored string) error {
|
|
return checkNodeKey(armored, true)
|
|
}
|
|
|
|
// checkNodeKey does the work of checkFolderKey and checkFileKey; aead
|
|
// allows the key to advertise AEAD.
|
|
func checkNodeKey(armored string, aead bool) error {
|
|
block, err := armor.Decode(strings.NewReader(armored))
|
|
if err != nil {
|
|
return fmt.Errorf("not armored: %w", err)
|
|
}
|
|
if block.Type != "PGP PRIVATE KEY BLOCK" {
|
|
return fmt.Errorf("armor type %q, want PGP PRIVATE KEY BLOCK", block.Type)
|
|
}
|
|
packets := packet.NewOpaqueReader(block.Body)
|
|
secretKeys := 0
|
|
for {
|
|
op, err := packets.Next()
|
|
if err == io.EOF {
|
|
break
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("malformed packet: %w", err)
|
|
}
|
|
switch op.Tag {
|
|
case tagSecretKey, tagSecretSubkey:
|
|
if err := checkSecretKeyPacket(op); err != nil {
|
|
return err
|
|
}
|
|
secretKeys++
|
|
case tagSignature:
|
|
p, err := op.Parse()
|
|
sig, ok := p.(*packet.Signature)
|
|
if err != nil || !ok {
|
|
return fmt.Errorf("malformed signature: %v", err)
|
|
}
|
|
if !aead && (sig.SEIPDv2 || len(sig.PreferredCipherSuites) > 0) {
|
|
return errors.New("key advertises AEAD (SEIPDv2)")
|
|
}
|
|
}
|
|
}
|
|
if secretKeys == 0 {
|
|
return errors.New("no secret key")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// checkSecretKeyPacket checks one secret key or subkey packet for
|
|
// checkNodeKey.
|
|
func checkSecretKeyPacket(op *packet.OpaquePacket) error {
|
|
if len(op.Contents) == 0 || op.Contents[0] != 4 {
|
|
return errors.New("not a v4 key")
|
|
}
|
|
p, err := op.Parse()
|
|
pk, ok := p.(*packet.PrivateKey)
|
|
if err != nil || !ok {
|
|
return fmt.Errorf("malformed secret key: %v", err)
|
|
}
|
|
// The packet starts with the public key body, which a v4 key hashes
|
|
// after 0x99 and a two-octet length.
|
|
var pub bytes.Buffer
|
|
if err := pk.PublicKey.SerializeForHash(&pub); err != nil {
|
|
return fmt.Errorf("malformed secret key: %w", err)
|
|
}
|
|
rest := op.Contents[pub.Len()-3:]
|
|
if len(rest) < 3 {
|
|
return errors.New("malformed secret key: truncated")
|
|
}
|
|
switch usage := rest[0]; usage {
|
|
case s2kUsageSHA1:
|
|
case 0:
|
|
return errors.New("secret key is not locked")
|
|
case 253:
|
|
return errors.New("secret key is locked with AEAD")
|
|
default:
|
|
return fmt.Errorf("secret key S2K usage %d, want %d", usage, s2kUsageSHA1)
|
|
}
|
|
if mode := s2k.Mode(rest[2]); mode != s2k.IteratedSaltedS2K {
|
|
return fmt.Errorf("secret key S2K mode %d, want iterated and salted", mode)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// keySignature returns the node passphrase signature and its signer
|
|
// that l has once moved or copied, given the request's sig and email.
|
|
//
|
|
// As the SDK's moveNode and copyNode, a request gives them if and only
|
|
// if l's key is anonymous: an anonymous key is then signed by the
|
|
// user, and a signed one keeps its signature, as the passphrase is
|
|
// unchanged.
|
|
func keySignature(u *User, l *link, sig, email *string) (string, string, error) {
|
|
if l.signatureEmail != "" {
|
|
if (sig != nil && *sig != "") || (email != nil && *email != "") {
|
|
return "", "", errors.New("NodePassphraseSignature and SignatureEmail must not be given for a signed node")
|
|
}
|
|
return l.nodePass.signature, l.signatureEmail, nil
|
|
}
|
|
if sig == nil || *sig == "" {
|
|
return "", "", errors.New("NodePassphraseSignature is required for an anonymous node")
|
|
}
|
|
if err := checkSigner(u, "SignatureEmail", email); err != nil {
|
|
return "", "", err
|
|
}
|
|
return *sig, *email, nil
|
|
}
|
|
|
|
// handleCreateFolder creates a folder from key material the client
|
|
// generated.
|
|
func (s *Server) handleCreateFolder(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
|
var req createFolderRequest
|
|
if !decodeRequest(w, r, &req) {
|
|
return
|
|
}
|
|
parent := d.activeFolder(req.ParentLinkID)
|
|
if parent == nil {
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Parent folder not found")
|
|
return
|
|
}
|
|
messages := map[string]string{
|
|
"Name": req.Name,
|
|
"NodePassphrase": req.NodePassphrase,
|
|
"NodeHashKey": req.NodeHashKey,
|
|
}
|
|
if req.XAttr != nil {
|
|
messages["XAttr"] = *req.XAttr
|
|
}
|
|
err := errors.Join(
|
|
checkHash(req.Hash),
|
|
checkSigner(u, "SignatureEmail", req.SignatureEmail),
|
|
checkMessages(messages),
|
|
)
|
|
if err == nil && req.NodePassphraseSignature == "" {
|
|
err = errors.New("NodePassphraseSignature is required")
|
|
}
|
|
if err == nil {
|
|
err = annotateField("NodeKey", checkFolderKey(req.NodeKey))
|
|
}
|
|
if err != nil {
|
|
writeInvalid(w, err)
|
|
return
|
|
}
|
|
if other := d.conflict(parent.id, req.Hash, ""); other != nil {
|
|
writeConflict(w, other)
|
|
return
|
|
}
|
|
now := time.Now().Unix()
|
|
l := &link{
|
|
id: randomID(),
|
|
parentID: parent.id,
|
|
typ: linkTypeFolder,
|
|
state: linkStateActive,
|
|
createTime: now,
|
|
modifyTime: now,
|
|
name: req.Name,
|
|
nameHash: req.Hash,
|
|
nodeKey: req.NodeKey,
|
|
nodePass: sealedPassphrase{armored: req.NodePassphrase, signature: req.NodePassphraseSignature},
|
|
signatureEmail: *req.SignatureEmail,
|
|
nameSignatureEmail: *req.SignatureEmail,
|
|
hashKey: req.NodeHashKey,
|
|
}
|
|
if req.XAttr != nil {
|
|
l.xattr = *req.XAttr
|
|
}
|
|
d.addLink(l)
|
|
d.logLink(EventCreate, l)
|
|
s.lagLocked(l.id, nil)
|
|
writeJSON(w, http.StatusOK, &createFolderResponse{Folder: folderIDJSON{ID: l.id}, Code: api.CodeOK})
|
|
}
|
|
|
|
// annotateField returns err prefixed with field, or nil.
|
|
func annotateField(field string, err error) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("%s: %w", field, err)
|
|
}
|
|
|
|
// handleRename renames a link within its folder.
|
|
func (s *Server) handleRename(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
|
var req renameRequest
|
|
if !decodeRequest(w, r, &req) {
|
|
return
|
|
}
|
|
l := d.activeLink(r.PathValue("linkID"))
|
|
switch {
|
|
case l == nil:
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "File or folder not found")
|
|
return
|
|
case l.parentID == "":
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidRequirements, "protontest: the root can't be renamed")
|
|
return
|
|
case req.OriginalHash == nil || *req.OriginalHash != l.nameHash:
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidRequirements, "protontest: OriginalHash doesn't match: the node changed")
|
|
return
|
|
}
|
|
hash := ""
|
|
if req.Hash != nil {
|
|
hash = *req.Hash
|
|
}
|
|
err := errors.Join(
|
|
checkHash(hash),
|
|
checkSigner(u, "NameSignatureEmail", req.NameSignatureEmail),
|
|
checkMessages(map[string]string{"Name": req.Name}),
|
|
)
|
|
if err != nil {
|
|
writeInvalid(w, err)
|
|
return
|
|
}
|
|
if other := d.conflict(l.parentID, hash, l.id); other != nil {
|
|
writeConflict(w, other)
|
|
return
|
|
}
|
|
l.name, l.nameHash, l.nameSignatureEmail = req.Name, hash, *req.NameSignatureEmail
|
|
l.modifyTime = time.Now().Unix()
|
|
d.logLink(EventUpdateMetadata, l)
|
|
writeJSON(w, http.StatusOK, &codeJSON{Code: api.CodeOK})
|
|
}
|
|
|
|
// handleMove moves a link to another folder, possibly renaming it.
|
|
func (s *Server) handleMove(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
|
var req moveRequest
|
|
if !decodeRequest(w, r, &req) {
|
|
return
|
|
}
|
|
l := d.activeLink(r.PathValue("linkID"))
|
|
parent := d.activeFolder(req.ParentLinkID)
|
|
switch {
|
|
case l == nil:
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "File or folder not found")
|
|
return
|
|
case l.parentID == "":
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidRequirements, "protontest: the root can't be moved")
|
|
return
|
|
case parent == nil:
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Parent folder not found")
|
|
return
|
|
case d.within(parent.id, l.id):
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidRequirements, "protontest: a folder can't be moved into itself")
|
|
return
|
|
case req.OriginalHash != l.nameHash:
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidRequirements, "protontest: OriginalHash doesn't match: the node changed")
|
|
return
|
|
}
|
|
err := errors.Join(
|
|
checkHash(req.Hash),
|
|
checkSigner(u, "NameSignatureEmail", req.NameSignatureEmail),
|
|
checkMessages(map[string]string{"Name": req.Name, "NodePassphrase": req.NodePassphrase}),
|
|
)
|
|
if err != nil {
|
|
writeInvalid(w, err)
|
|
return
|
|
}
|
|
sig, signer, err := keySignature(u, l, req.NodePassphraseSignature, req.SignatureEmail)
|
|
if err != nil {
|
|
writeInvalid(w, err)
|
|
return
|
|
}
|
|
if other := d.conflict(parent.id, req.Hash, l.id); other != nil {
|
|
writeConflict(w, other)
|
|
return
|
|
}
|
|
l.parentID, l.name, l.nameHash, l.nameSignatureEmail = parent.id, req.Name, req.Hash, *req.NameSignatureEmail
|
|
l.nodePass = sealedPassphrase{armored: req.NodePassphrase, signature: sig}
|
|
l.signatureEmail = signer
|
|
l.modifyTime = time.Now().Unix()
|
|
d.logLink(EventUpdateMetadata, l)
|
|
writeJSON(w, http.StatusOK, &codeJSON{Code: api.CodeOK})
|
|
}
|
|
|
|
// handleCopy copies a link, and a folder's active descendants, into a
|
|
// folder. Only the name and passphrase of the copy come from the
|
|
// client; its key, content and descendants are the server's copies.
|
|
func (s *Server) handleCopy(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
|
var req copyRequest
|
|
if !decodeRequest(w, r, &req) {
|
|
return
|
|
}
|
|
l := d.activeLink(r.PathValue("linkID"))
|
|
parent := d.activeFolder(req.TargetParentLinkID)
|
|
switch {
|
|
case l == nil:
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "File or folder not found")
|
|
return
|
|
case l.parentID == "":
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidRequirements, "protontest: the root can't be copied")
|
|
return
|
|
case req.TargetVolumeID != d.volumeID:
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Volume not found")
|
|
return
|
|
case parent == nil:
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Parent folder not found")
|
|
return
|
|
case d.within(parent.id, l.id):
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidRequirements, "protontest: a folder can't be copied into itself")
|
|
return
|
|
}
|
|
err := errors.Join(
|
|
checkHash(req.Hash),
|
|
checkSigner(u, "NameSignatureEmail", req.NameSignatureEmail),
|
|
checkMessages(map[string]string{"Name": req.Name, "NodePassphrase": req.NodePassphrase}),
|
|
)
|
|
if err != nil {
|
|
writeInvalid(w, err)
|
|
return
|
|
}
|
|
sig, signer, err := keySignature(u, l, req.NodePassphraseSignature, req.SignatureEmail)
|
|
if err != nil {
|
|
writeInvalid(w, err)
|
|
return
|
|
}
|
|
if other := d.conflict(parent.id, req.Hash, ""); other != nil {
|
|
writeConflict(w, other)
|
|
return
|
|
}
|
|
c := d.copyLink(l, parent.id, time.Now().Unix())
|
|
c.name, c.nameHash, c.nameSignatureEmail = req.Name, req.Hash, *req.NameSignatureEmail
|
|
c.nodePass = sealedPassphrase{armored: req.NodePassphrase, signature: sig}
|
|
c.signatureEmail = signer
|
|
s.lagLocked(c.id, nil)
|
|
writeJSON(w, http.StatusOK, ©Response{LinkID: c.id, Code: api.CodeOK})
|
|
}
|
|
|
|
// copyLink stores and returns a copy of l in folder parentID with its
|
|
// active revision and, for a folder, copies of its active descendants.
|
|
// Blocks are shared, as they are immutable.
|
|
func (d *drive) copyLink(l *link, parentID string, now int64) *link {
|
|
c := *l
|
|
c.id, c.parentID = randomID(), parentID
|
|
c.state, c.createTime, c.modifyTime, c.trashTime = linkStateActive, now, now, 0
|
|
c.revisions = nil
|
|
if r := l.activeRevision(); r != nil {
|
|
rc := *r
|
|
rc.id = randomID()
|
|
rc.blocks = slices.Clone(r.blocks)
|
|
c.revisions = []*revision{&rc}
|
|
}
|
|
var children []*link
|
|
for _, child := range d.links {
|
|
if child.parentID == l.id && child.state == linkStateActive {
|
|
children = append(children, child)
|
|
}
|
|
}
|
|
sort.Slice(children, func(i, j int) bool { return children[i].seq < children[j].seq })
|
|
d.addLink(&c)
|
|
d.logLink(EventCreate, &c)
|
|
for _, child := range children {
|
|
d.copyLink(child, c.id, now)
|
|
}
|
|
return &c
|
|
}
|
|
|
|
// handleTrash trashes up to 100 links, answering for each.
|
|
func (s *Server) handleTrash(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
|
var req linksRequest
|
|
if !decodeRequest(w, r, &req) {
|
|
return
|
|
}
|
|
if len(req.LinkIDs) > maxLinksPerRequest {
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidValue, fmt.Sprintf("protontest: %d link IDs, at most %d allowed", len(req.LinkIDs), maxLinksPerRequest))
|
|
return
|
|
}
|
|
now := time.Now().Unix()
|
|
resp := &multiResponse{Code: api.CodeOKMany, Responses: []linkResultJSON{}}
|
|
for _, id := range req.LinkIDs {
|
|
result := linkResultJSON{LinkID: id, Response: codeJSON{Code: api.CodeOK}}
|
|
l := d.activeLink(id)
|
|
switch {
|
|
case l == nil:
|
|
result.Response = codeJSON{Code: api.CodeNotExists, Error: "File or folder not found"}
|
|
case l.parentID == "":
|
|
result.Response = codeJSON{Code: api.CodeInvalidRequirements, Error: "protontest: the root can't be trashed"}
|
|
default:
|
|
l.state, l.trashTime, l.modifyTime = linkStateTrashed, now, now
|
|
d.logLink(EventUpdateMetadata, l)
|
|
}
|
|
resp.Responses = append(resp.Responses, result)
|
|
}
|
|
writeJSON(w, http.StatusOK, resp)
|
|
}
|
|
|
|
// handleEmptyTrash deletes every trashed link with its descendants.
|
|
func (s *Server) handleEmptyTrash(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
|
var doomed []*link
|
|
for _, l := range d.links {
|
|
if d.inTrash(l) {
|
|
doomed = append(doomed, l)
|
|
}
|
|
}
|
|
sort.Slice(doomed, func(i, j int) bool { return doomed[i].seq < doomed[j].seq })
|
|
for _, l := range doomed {
|
|
d.logLink(EventDelete, l)
|
|
delete(d.links, l.id)
|
|
}
|
|
writeJSON(w, http.StatusOK, &codeJSON{Code: api.CodeOK})
|
|
}
|
|
|
|
// handleCheckAvailableHashes reports which name hashes are free in a
|
|
// folder, and the drafts holding the others unless they belong to one
|
|
// of the given ClientUIDs.
|
|
func (s *Server) handleCheckAvailableHashes(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
|
var req checkHashesRequest
|
|
if !decodeRequest(w, r, &req) {
|
|
return
|
|
}
|
|
parent := d.activeFolder(r.PathValue("linkID"))
|
|
if parent == nil {
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Folder not found")
|
|
return
|
|
}
|
|
resp := &availableHashesResponse{AvailableHashes: []string{}, PendingHashes: []pendingHashJSON{}, Code: api.CodeOK}
|
|
for _, hash := range req.Hashes {
|
|
other := d.conflict(parent.id, hash, "")
|
|
if other == nil {
|
|
resp.AvailableHashes = append(resp.AvailableHashes, hash)
|
|
continue
|
|
}
|
|
if other.state != linkStateDraft {
|
|
continue
|
|
}
|
|
for _, rev := range other.revisions {
|
|
if rev.state == revisionStateDraft && !slices.Contains(req.ClientUID, rev.clientUID) {
|
|
resp.PendingHashes = append(resp.PendingHashes, pendingHashJSON{
|
|
Hash: hash,
|
|
RevisionID: rev.id,
|
|
LinkID: other.id,
|
|
ClientUID: nullable(rev.clientUID),
|
|
})
|
|
}
|
|
}
|
|
}
|
|
writeJSON(w, http.StatusOK, resp)
|
|
}
|