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>
702 lines
22 KiB
Go
702 lines
22 KiB
Go
package protontest
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"slices"
|
|
"sort"
|
|
"time"
|
|
|
|
"github.com/ProtonMail/go-crypto/openpgp/packet"
|
|
"github.com/ProtonMail/gopenpgp/v3/crypto"
|
|
"github.com/rclone/rclone/backend/protondrive/api"
|
|
)
|
|
|
|
const (
|
|
// storageUploadPattern is the route of block uploads.
|
|
storageUploadPattern = "/storage/upload/{token}"
|
|
|
|
// verificationCodeSize is the size of a draft's verification code,
|
|
// and so of each block's verifier token.
|
|
verificationCodeSize = 32
|
|
|
|
// maxUploadBlockSize is the largest encrypted block accepted.
|
|
maxUploadBlockSize = 8 << 20
|
|
|
|
// intendedSizePrecision is the precision of IntendedUploadSize.
|
|
intendedSizePrecision = 100_000
|
|
)
|
|
|
|
// pendingBlock is a block of a draft revision requested for upload.
|
|
type pendingBlock struct {
|
|
index int
|
|
encSignature string
|
|
token []byte // verifier token
|
|
hash []byte // SHA-256 the client declared; nil if none
|
|
data []byte // nil until uploaded
|
|
}
|
|
|
|
// uploadURL is a block upload URL issued by /drive/blocks.
|
|
type uploadURL struct {
|
|
token string
|
|
user *User
|
|
linkID string
|
|
rev *revision
|
|
block *pendingBlock
|
|
expired bool
|
|
}
|
|
|
|
// Wire types of the upload routes, named after and shaped like the
|
|
// schemas in the SDK's driveTypes.ts.
|
|
|
|
type createFileRequest struct {
|
|
ParentLinkID string
|
|
Name string
|
|
Hash string
|
|
MIMEType string
|
|
ClientUID *string
|
|
IntendedUploadSize *int64
|
|
NodeKey string
|
|
NodePassphrase string
|
|
NodePassphraseSignature string
|
|
ContentKeyPacket string
|
|
ContentKeyPacketSignature *string
|
|
SignatureAddress *string
|
|
}
|
|
|
|
type fileResponseJSON struct {
|
|
ID string
|
|
RevisionID string
|
|
ClientUID *string
|
|
}
|
|
|
|
type createFileResponse struct {
|
|
File fileResponseJSON
|
|
Code int
|
|
}
|
|
|
|
type createRevisionRequest struct {
|
|
CurrentRevisionID *string
|
|
ClientUID *string
|
|
IntendedUploadSize *int64
|
|
}
|
|
|
|
type revisionIDJSON struct {
|
|
ID string
|
|
}
|
|
|
|
type createRevisionResponse struct {
|
|
Revision revisionIDJSON
|
|
Code int
|
|
}
|
|
|
|
type verificationResponse struct {
|
|
VerificationCode string
|
|
ContentKeyPacket string
|
|
Code int
|
|
}
|
|
|
|
type verifierJSON struct {
|
|
Token string
|
|
}
|
|
|
|
type blockUploadInput struct {
|
|
Index int
|
|
Verifier *verifierJSON
|
|
EncSignature *string
|
|
Size *int64
|
|
Hash *string
|
|
}
|
|
|
|
type blockUploadRequest struct {
|
|
LinkID string
|
|
RevisionID string
|
|
AddressID *string
|
|
VolumeID *string
|
|
BlockList []blockUploadInput
|
|
ThumbnailList []struct{ Type int }
|
|
}
|
|
|
|
type blockURLJSON struct {
|
|
BareURL string
|
|
Token string
|
|
URL string
|
|
Index int
|
|
}
|
|
|
|
type blockUploadResponse struct {
|
|
UploadLinks []blockURLJSON
|
|
ThumbnailLinks []struct{}
|
|
Code int
|
|
}
|
|
|
|
type commitRevisionRequest struct {
|
|
ManifestSignature string
|
|
SignatureAddress *string
|
|
XAttr *string
|
|
ChecksumVerified bool
|
|
Photo *struct{}
|
|
}
|
|
|
|
// registerUpload registers the routes which upload files.
|
|
func (s *Server) registerUpload() {
|
|
s.handleDrive("POST", "/drive/v2/volumes/{volumeID}/files", s.handleCreateFile)
|
|
s.handleDrive("POST", "/drive/v2/volumes/{volumeID}/files/{linkID}/revisions", s.handleCreateRevision)
|
|
s.handleDrive("GET", "/drive/v2/volumes/{volumeID}/links/{linkID}/revisions/{revisionID}/verification", s.handleVerification)
|
|
s.handleAuth("POST", "/drive/blocks", s.handleRequestUpload)
|
|
s.handle("POST", storageUploadPattern, s.handleStorageUpload)
|
|
s.handleDrive("PUT", "/drive/v2/volumes/{volumeID}/files/{linkID}/revisions/{revisionID}", s.handleCommit)
|
|
s.handleDrive("DELETE", "/drive/v2/volumes/{volumeID}/files/{linkID}/revisions/{revisionID}", s.handleDeleteRevision)
|
|
s.handleDrive("POST", "/drive/v2/volumes/{volumeID}/delete_multiple", s.handleDeleteMultiple)
|
|
}
|
|
|
|
// ExpireUploadTokens makes every block upload URL issued so far answer
|
|
// HTTP 404, as an expired one does.
|
|
func (s *Server) ExpireUploadTokens() {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
for _, up := range s.uploads {
|
|
up.expired = true
|
|
}
|
|
}
|
|
|
|
// StorageUploadPeak returns the most block uploads that were in
|
|
// progress at once since the server started or ResetRequests.
|
|
func (s *Server) StorageUploadPeak() int {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
return s.storagePeak
|
|
}
|
|
|
|
// nowLocked returns the server's clock. srv.mu must be held.
|
|
func (s *Server) nowLocked() time.Time {
|
|
return time.Now().Add(s.clockSkew)
|
|
}
|
|
|
|
// newDraftRevision returns a draft revision created by clientUID.
|
|
func newDraftRevision(clientUID *string) *revision {
|
|
r := &revision{
|
|
id: randomID(),
|
|
state: revisionStateDraft,
|
|
createTime: time.Now().Unix(),
|
|
verificationCode: randomBytes(verificationCodeSize),
|
|
pending: make(map[int]*pendingBlock),
|
|
}
|
|
if clientUID != nil {
|
|
r.clientUID = *clientUID
|
|
}
|
|
return r
|
|
}
|
|
|
|
// checkIntendedSize returns an error if size, when given, is not
|
|
// rounded as the SDK rounds it: the server must not learn the size.
|
|
func checkIntendedSize(size *int64) error {
|
|
if size == nil {
|
|
return nil
|
|
}
|
|
if *size < 0 || (*size%intendedSizePrecision != 0 && *size != 4095) {
|
|
return fmt.Errorf("IntendedUploadSize %d is not rounded", *size)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// checkContentKeyPacket returns an error unless packet64 is the base64
|
|
// of one v6 PKESK: new content is written in the RFC 9580 format.
|
|
func checkContentKeyPacket(packet64 string) error {
|
|
raw, err := base64.StdEncoding.DecodeString(packet64)
|
|
if err != nil {
|
|
return fmt.Errorf("not base64: %w", err)
|
|
}
|
|
r := packet.NewOpaqueReader(bytes.NewReader(raw))
|
|
op, err := r.Next()
|
|
if err != nil {
|
|
return fmt.Errorf("malformed packet: %w", err)
|
|
}
|
|
if op.Tag != tagPKESK || len(op.Contents) == 0 || op.Contents[0] != 6 {
|
|
return fmt.Errorf("packet with tag %d version %d, want a v6 PKESK", op.Tag, firstByte(op.Contents))
|
|
}
|
|
if _, err := r.Next(); err != io.EOF {
|
|
return errors.New("more than one packet")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// contentKeyVersion returns the version of the PKESK of a stored
|
|
// content key packet, or -1.
|
|
func contentKeyVersion(packet64 string) int {
|
|
raw, err := base64.StdEncoding.DecodeString(packet64)
|
|
if err != nil {
|
|
return -1
|
|
}
|
|
op, err := packet.NewOpaqueReader(bytes.NewReader(raw)).Next()
|
|
if err != nil || op.Tag != tagPKESK {
|
|
return -1
|
|
}
|
|
return int(firstByte(op.Contents))
|
|
}
|
|
|
|
// checkBlockFormat returns an error unless data is one SEIPD packet of
|
|
// version: SEIPDv2 for content whose key packet is a v6 PKESK, SEIPDv1
|
|
// for a v3 one.
|
|
func checkBlockFormat(data []byte, version int) error {
|
|
r := packet.NewOpaqueReader(bytes.NewReader(data))
|
|
op, err := r.Next()
|
|
if err != nil {
|
|
return fmt.Errorf("malformed packet: %w", err)
|
|
}
|
|
if op.Tag != tagSEIPD || int(firstByte(op.Contents)) != version {
|
|
return fmt.Errorf("packet with tag %d version %d, want SEIPDv%d", op.Tag, firstByte(op.Contents), version)
|
|
}
|
|
if _, err := r.Next(); err != io.EOF {
|
|
return errors.New("more than one packet")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// firstByte returns b[0], or 0 if b is empty.
|
|
func firstByte(b []byte) byte {
|
|
if len(b) == 0 {
|
|
return 0
|
|
}
|
|
return b[0]
|
|
}
|
|
|
|
// draftRevision returns the draft revision id of file l, or nil.
|
|
func draftRevision(l *link, id string) *revision {
|
|
if l == nil || l.typ != linkTypeFile {
|
|
return nil
|
|
}
|
|
for _, r := range l.revisions {
|
|
if r.id == id && r.state == revisionStateDraft {
|
|
return r
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// handleCreateFile creates a draft file, with a draft revision, from
|
|
// key material the client generated.
|
|
func (s *Server) handleCreateFile(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
|
var req createFileRequest
|
|
if !decodeRequest(w, r, &req) {
|
|
return
|
|
}
|
|
parent := d.activeFolder(req.ParentLinkID)
|
|
if parent == nil {
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Parent folder not found")
|
|
return
|
|
}
|
|
err := errors.Join(
|
|
checkHash(req.Hash),
|
|
checkSigner(u, "SignatureAddress", req.SignatureAddress),
|
|
checkMessages(map[string]string{"Name": req.Name, "NodePassphrase": req.NodePassphrase}),
|
|
annotateField("ContentKeyPacket", checkContentKeyPacket(req.ContentKeyPacket)),
|
|
checkIntendedSize(req.IntendedUploadSize),
|
|
)
|
|
switch {
|
|
case err != nil:
|
|
case req.NodePassphraseSignature == "":
|
|
err = errors.New("NodePassphraseSignature is required")
|
|
case req.ContentKeyPacketSignature == nil || *req.ContentKeyPacketSignature == "":
|
|
err = errors.New("ContentKeyPacketSignature is required")
|
|
case req.MIMEType == "":
|
|
err = errors.New("MIMEType is required")
|
|
default:
|
|
err = annotateField("NodeKey", checkFileKey(req.NodeKey))
|
|
}
|
|
if err != nil {
|
|
writeInvalid(w, err)
|
|
return
|
|
}
|
|
if other := d.conflict(parent.id, req.Hash, ""); other != nil {
|
|
writeConflict(w, other)
|
|
return
|
|
}
|
|
now := time.Now().Unix()
|
|
rev := newDraftRevision(req.ClientUID)
|
|
l := &link{
|
|
id: randomID(),
|
|
parentID: parent.id,
|
|
typ: linkTypeFile,
|
|
state: linkStateDraft,
|
|
createTime: now,
|
|
modifyTime: now,
|
|
name: req.Name,
|
|
nameHash: req.Hash,
|
|
nodeKey: req.NodeKey,
|
|
nodePass: sealedPassphrase{armored: req.NodePassphrase, signature: req.NodePassphraseSignature},
|
|
signatureEmail: *req.SignatureAddress,
|
|
nameSignatureEmail: *req.SignatureAddress,
|
|
mediaType: req.MIMEType,
|
|
contentKeyPacket: req.ContentKeyPacket,
|
|
contentKeyPacketSignature: *req.ContentKeyPacketSignature,
|
|
revisions: []*revision{rev},
|
|
}
|
|
d.addLink(l)
|
|
writeJSON(w, http.StatusOK, &createFileResponse{
|
|
File: fileResponseJSON{ID: l.id, RevisionID: rev.id, ClientUID: nullable(rev.clientUID)},
|
|
Code: api.CodeOK,
|
|
})
|
|
}
|
|
|
|
// handleCreateRevision creates a draft revision of an active file whose
|
|
// active revision is CurrentRevisionID.
|
|
func (s *Server) handleCreateRevision(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
|
var req createRevisionRequest
|
|
if !decodeRequest(w, r, &req) {
|
|
return
|
|
}
|
|
l := d.activeLink(r.PathValue("linkID"))
|
|
if l == nil || l.typ != linkTypeFile {
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "File not found")
|
|
return
|
|
}
|
|
if err := checkIntendedSize(req.IntendedUploadSize); err != nil {
|
|
writeInvalid(w, err)
|
|
return
|
|
}
|
|
active := l.activeRevision()
|
|
if active == nil || req.CurrentRevisionID == nil || *req.CurrentRevisionID != active.id {
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidRequirements, "protontest: CurrentRevisionID is not the active revision: the file changed")
|
|
return
|
|
}
|
|
rev := newDraftRevision(req.ClientUID)
|
|
l.revisions = append(l.revisions, rev)
|
|
writeJSON(w, http.StatusOK, &createRevisionResponse{Revision: revisionIDJSON{ID: rev.id}, Code: api.CodeOK})
|
|
}
|
|
|
|
// handleVerification returns the verification code and content key
|
|
// packet of a draft revision.
|
|
func (s *Server) handleVerification(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
|
l := d.links[r.PathValue("linkID")]
|
|
rev := draftRevision(l, r.PathValue("revisionID"))
|
|
if rev == nil {
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Revision not found")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, &verificationResponse{
|
|
VerificationCode: base64.StdEncoding.EncodeToString(rev.verificationCode),
|
|
ContentKeyPacket: l.contentKeyPacket,
|
|
Code: api.CodeOK,
|
|
})
|
|
}
|
|
|
|
// handleRequestUpload issues upload URLs on this server for blocks of a
|
|
// draft revision. Requesting a block again replaces it, and its URL.
|
|
func (s *Server) handleRequestUpload(w http.ResponseWriter, r *http.Request, u *User) {
|
|
var req blockUploadRequest
|
|
if !decodeRequest(w, r, &req) {
|
|
return
|
|
}
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
d := u.drive
|
|
if d == nil || req.VolumeID == nil || *req.VolumeID != d.volumeID {
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Volume not found")
|
|
return
|
|
}
|
|
l := d.links[req.LinkID]
|
|
rev := draftRevision(l, req.RevisionID)
|
|
if rev == nil {
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Revision not found")
|
|
return
|
|
}
|
|
if req.AddressID == nil || !slices.ContainsFunc(u.addresses, func(a *address) bool { return a.id == *req.AddressID }) {
|
|
writeInvalid(w, errors.New("AddressID must be an address of the user"))
|
|
return
|
|
}
|
|
if len(req.ThumbnailList) > 0 {
|
|
writeInvalid(w, errors.New("protontest: thumbnails are not supported"))
|
|
return
|
|
}
|
|
blocks := make([]*pendingBlock, 0, len(req.BlockList))
|
|
for _, in := range req.BlockList {
|
|
b, err := pendingBlockOf(in)
|
|
if err != nil {
|
|
writeInvalid(w, fmt.Errorf("block %d: %w", in.Index, err))
|
|
return
|
|
}
|
|
blocks = append(blocks, b)
|
|
}
|
|
resp := &blockUploadResponse{UploadLinks: []blockURLJSON{}, ThumbnailLinks: []struct{}{}, Code: api.CodeOK}
|
|
for _, b := range blocks {
|
|
rev.pending[b.index] = b
|
|
id, token := randomID(), s.newSecretLocked(StorageToken)
|
|
s.uploads[id] = &uploadURL{token: token, user: u, linkID: l.id, rev: rev, block: b}
|
|
bareURL := s.URL() + "/storage/upload/" + id
|
|
resp.UploadLinks = append(resp.UploadLinks, blockURLJSON{BareURL: bareURL, Token: token, URL: bareURL, Index: b.index})
|
|
}
|
|
writeJSON(w, http.StatusOK, resp)
|
|
}
|
|
|
|
// pendingBlockOf returns the block in an upload request, checked.
|
|
func pendingBlockOf(in blockUploadInput) (*pendingBlock, error) {
|
|
b := &pendingBlock{index: in.Index}
|
|
if in.Index < 1 {
|
|
return nil, errors.New("field Index must be at least 1")
|
|
}
|
|
if in.Verifier == nil {
|
|
return nil, errors.New("field Verifier is required")
|
|
}
|
|
token, err := base64.StdEncoding.DecodeString(in.Verifier.Token)
|
|
if err != nil || len(token) != verificationCodeSize {
|
|
return nil, fmt.Errorf("Verifier.Token is not the base64 of %d bytes", verificationCodeSize)
|
|
}
|
|
b.token = token
|
|
if in.EncSignature == nil || *in.EncSignature == "" {
|
|
return nil, errors.New("EncSignature is required")
|
|
}
|
|
b.encSignature = *in.EncSignature
|
|
if in.Hash != nil {
|
|
if b.hash, err = base64.StdEncoding.DecodeString(*in.Hash); err != nil || len(b.hash) != sha256.Size {
|
|
return nil, errors.New("field Hash is not the base64 of a SHA-256")
|
|
}
|
|
}
|
|
return b, nil
|
|
}
|
|
|
|
// handleStorageUpload stores the block of a multipart upload to a URL
|
|
// issued by handleRequestUpload, which carries its pm-storage-token and
|
|
// none of the session's credentials.
|
|
func (s *Server) handleStorageUpload(w http.ResponseWriter, r *http.Request) {
|
|
if r.Header.Get("Authorization") != "" || r.Header.Get("x-pm-uid") != "" {
|
|
writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: session credentials must not be sent to the storage host")
|
|
return
|
|
}
|
|
s.mu.Lock()
|
|
up := s.uploads[r.PathValue("token")]
|
|
usable := up != nil && !up.expired
|
|
s.mu.Unlock()
|
|
switch {
|
|
case !usable:
|
|
writeError(w, http.StatusNotFound, api.CodeNotExists, "protontest: no such upload URL, or it expired")
|
|
return
|
|
case r.Header.Get("pm-storage-token") != up.token:
|
|
writeError(w, http.StatusForbidden, api.CodeNotEnoughPermissions, "protontest: missing or wrong pm-storage-token")
|
|
return
|
|
}
|
|
data, err := readBlockPart(r)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, api.CodeInvalidValue, "protontest: bad block upload: "+err.Error())
|
|
return
|
|
}
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if up.rev.state != revisionStateDraft || up.rev.pending[up.block.index] != up.block {
|
|
writeError(w, http.StatusNotFound, api.CodeNotExists, "protontest: the block is no longer awaited")
|
|
return
|
|
}
|
|
up.block.data = data
|
|
writeJSON(w, http.StatusOK, &codeJSON{Code: api.CodeOK})
|
|
}
|
|
|
|
// readBlockPart returns the content of the one part, named Block, of
|
|
// the multipart body of r.
|
|
func readBlockPart(r *http.Request) ([]byte, error) {
|
|
mr, err := r.MultipartReader()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var data []byte
|
|
for {
|
|
part, err := mr.NextPart()
|
|
if err == io.EOF {
|
|
break
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if part.FormName() != "Block" || data != nil {
|
|
return nil, fmt.Errorf("unexpected part %q", part.FormName())
|
|
}
|
|
if data, err = io.ReadAll(io.LimitReader(part, maxUploadBlockSize+1)); err != nil {
|
|
return nil, err
|
|
}
|
|
if len(data) > maxUploadBlockSize {
|
|
return nil, fmt.Errorf("block larger than %d bytes", maxUploadBlockSize)
|
|
}
|
|
}
|
|
if len(data) == 0 {
|
|
return nil, errors.New("no Block part, or it is empty")
|
|
}
|
|
return data, nil
|
|
}
|
|
|
|
// handleCommit makes a draft revision with every requested block
|
|
// uploaded the file's active revision, after checking each block's
|
|
// verifier token and format, the manifest signature over the uploaded
|
|
// blocks and the extended attributes' format.
|
|
func (s *Server) handleCommit(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
|
var req commitRevisionRequest
|
|
if !decodeRequest(w, r, &req) {
|
|
return
|
|
}
|
|
l := d.links[r.PathValue("linkID")]
|
|
rev := draftRevision(l, r.PathValue("revisionID"))
|
|
if rev == nil {
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Revision not found")
|
|
return
|
|
}
|
|
xattr := ""
|
|
if req.XAttr != nil {
|
|
xattr = *req.XAttr
|
|
}
|
|
err := errors.Join(
|
|
checkSigner(u, "SignatureAddress", req.SignatureAddress),
|
|
checkMessages(map[string]string{"XAttr": xattr}),
|
|
)
|
|
if err == nil && req.ManifestSignature == "" {
|
|
err = errors.New("ManifestSignature is required")
|
|
}
|
|
if err != nil {
|
|
writeInvalid(w, err)
|
|
return
|
|
}
|
|
blocks, err := uploadedBlocks(rev, *req.SignatureAddress)
|
|
if err != nil {
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidRequirements, "protontest: "+err.Error())
|
|
return
|
|
}
|
|
var manifest []byte
|
|
var formatErrs []error
|
|
version := 1
|
|
if contentKeyVersion(l.contentKeyPacket) == 6 {
|
|
version = 2
|
|
}
|
|
for _, b := range blocks {
|
|
manifest = append(manifest, b.hash...)
|
|
formatErrs = append(formatErrs, annotateField(fmt.Sprintf("block %d", b.index), checkBlockFormat(b.data, version)))
|
|
}
|
|
addr := u.addressByEmailLocked(*req.SignatureAddress)
|
|
keys := make([]*crypto.Key, 0, len(addr.keys))
|
|
for _, k := range addr.keys {
|
|
keys = append(keys, k.key)
|
|
}
|
|
sigErr := verifyDetached(manifest, []byte(req.ManifestSignature), crypto.Armor, keyRing(keys...), s.nowLocked())
|
|
if err := errors.Join(append(formatErrs, annotateField("manifest", sigErr))...); err != nil {
|
|
writeInvalid(w, err)
|
|
return
|
|
}
|
|
before := d.linkDetails(l)
|
|
event := EventUpdate
|
|
if l.state == linkStateDraft {
|
|
event = EventCreate
|
|
}
|
|
for _, other := range l.revisions {
|
|
if other.state == revisionStateActive {
|
|
other.state = revisionStateObsolete
|
|
}
|
|
}
|
|
now := time.Now().Unix()
|
|
rev.state, rev.createTime = revisionStateActive, now
|
|
rev.manifestSignature, rev.xattr, rev.signatureEmail = req.ManifestSignature, xattr, *req.SignatureAddress
|
|
rev.blocks, rev.pending, rev.verificationCode = blocks, nil, nil
|
|
l.state, l.modifyTime = linkStateActive, now
|
|
d.logLink(event, l)
|
|
s.dropUploadsLocked(rev)
|
|
s.lagLocked(l.id, &before)
|
|
writeJSON(w, http.StatusOK, &codeJSON{Code: api.CodeOK})
|
|
}
|
|
|
|
// uploadedBlocks returns the blocks of draft rev, signed by email, after
|
|
// checking that blocks 1 to n were requested and each uploaded, with the
|
|
// hash it was declared with, if any, and its verifier token.
|
|
func uploadedBlocks(rev *revision, email string) ([]*block, error) {
|
|
indexes := make([]int, 0, len(rev.pending))
|
|
for i := range rev.pending {
|
|
indexes = append(indexes, i)
|
|
}
|
|
sort.Ints(indexes)
|
|
blocks := make([]*block, 0, len(indexes))
|
|
for i, index := range indexes {
|
|
p := rev.pending[index]
|
|
switch {
|
|
case index != i+1:
|
|
return nil, fmt.Errorf("block %d was not requested", i+1)
|
|
case p.data == nil:
|
|
return nil, fmt.Errorf("block %d was not uploaded", index)
|
|
}
|
|
sum := sha256.Sum256(p.data)
|
|
if p.hash != nil && !bytes.Equal(p.hash, sum[:]) {
|
|
return nil, fmt.Errorf("block %d: declared hash doesn't match the uploaded block", index)
|
|
}
|
|
if want := xorPrefix(rev.verificationCode, p.data); !bytes.Equal(p.token, want) {
|
|
return nil, fmt.Errorf("block %d: verifier token doesn't match the uploaded block", index)
|
|
}
|
|
blocks = append(blocks, &block{index: index, hash: sum[:], data: p.data, encSignature: p.encSignature, signatureEmail: email})
|
|
}
|
|
return blocks, nil
|
|
}
|
|
|
|
// xorPrefix returns code XOR the start of data, padded with zeros: the
|
|
// verifier token of a block.
|
|
func xorPrefix(code, data []byte) []byte {
|
|
out := make([]byte, len(code))
|
|
for i := range code {
|
|
out[i] = code[i]
|
|
if i < len(data) {
|
|
out[i] ^= data[i]
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// dropUploadsLocked forgets the upload URLs of rev. srv.mu must be
|
|
// held.
|
|
func (s *Server) dropUploadsLocked(rev *revision) {
|
|
for id, up := range s.uploads {
|
|
if up.rev == rev {
|
|
delete(s.uploads, id)
|
|
}
|
|
}
|
|
}
|
|
|
|
// handleDeleteRevision deletes a draft revision.
|
|
func (s *Server) handleDeleteRevision(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
|
l := d.links[r.PathValue("linkID")]
|
|
rev := draftRevision(l, r.PathValue("revisionID"))
|
|
if rev == nil {
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeNotExists, "Draft revision not found")
|
|
return
|
|
}
|
|
l.revisions = slices.DeleteFunc(l.revisions, func(other *revision) bool { return other == rev })
|
|
s.dropUploadsLocked(rev)
|
|
writeJSON(w, http.StatusOK, &codeJSON{Code: api.CodeOK})
|
|
}
|
|
|
|
// handleDeleteMultiple permanently deletes up to 100 draft links,
|
|
// answering for each.
|
|
func (s *Server) handleDeleteMultiple(w http.ResponseWriter, r *http.Request, u *User, d *drive) {
|
|
var req linksRequest
|
|
if !decodeRequest(w, r, &req) {
|
|
return
|
|
}
|
|
if len(req.LinkIDs) > maxLinksPerRequest {
|
|
writeError(w, http.StatusUnprocessableEntity, api.CodeInvalidValue, fmt.Sprintf("protontest: %d link IDs, at most %d allowed", len(req.LinkIDs), maxLinksPerRequest))
|
|
return
|
|
}
|
|
resp := &multiResponse{Code: api.CodeOKMany, Responses: []linkResultJSON{}}
|
|
for _, id := range req.LinkIDs {
|
|
result := linkResultJSON{LinkID: id, Response: codeJSON{Code: api.CodeOK}}
|
|
l := d.links[id]
|
|
switch {
|
|
case l == nil:
|
|
result.Response = codeJSON{Code: api.CodeNotExists, Error: "File or folder not found"}
|
|
case l.state != linkStateDraft:
|
|
result.Response = codeJSON{Code: api.CodeInvalidRequirements, Error: "protontest: only drafts can be deleted"}
|
|
default:
|
|
for _, rev := range l.revisions {
|
|
s.dropUploadsLocked(rev)
|
|
}
|
|
delete(d.links, id)
|
|
}
|
|
resp.Responses = append(resp.Responses, result)
|
|
}
|
|
writeJSON(w, http.StatusOK, resp)
|
|
}
|