Files
rclone/backend/protondrive/crypto_diff_internal_test.go
T
Lucas WintherandClaude Opus 5.5 3b63f3c7d5 protondrive: add differential crypto tests against the old library
Cross-test crypto.go against go-proton-api v1.0.4 and Proton-API-Bridge
v1.0.5 in both directions, compare account key unlocking with
proton.Unlock, and freeze old-library output under testdata/oldlib so
it stays tested once the old libraries are gone. github.com/relvacode/iso8601
becomes a direct requirement because the test parses modification
times as the bridge does.

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

599 lines
24 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package protondrive
// Differential tests of crypto.go against the library rclone used before
// it: go-proton-api v1.0.4 (proton) and Proton-API-Bridge v1.0.5 (the
// bridge). Where the old writer or reader is unexported it is mirrored
// with gopenpgp, citing the old file and lines.
//
// testdata/oldlib holds values written by the old library, so that they
// stay readable once it is gone; TestFrozenFixtures, less its -update
// branch, is all that need outlive it. Regenerate them with
//
// go test ./backend/protondrive/ -run TestFrozenFixtures -update
import (
"context"
"crypto/rand"
"crypto/sha1"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/ProtonMail/go-crypto/openpgp/packet"
"github.com/ProtonMail/gopenpgp/v3/crypto"
"github.com/ProtonMail/gopenpgp/v3/profile"
"github.com/rclone/go-proton-api"
"github.com/rclone/rclone/backend/protondrive/protontest"
"github.com/rclone/rclone/lib/rest"
"github.com/relvacode/iso8601"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var updateOldLib = flag.Bool("update", false, "regenerate testdata/oldlib with the old library")
// oldLibDir holds the frozen old library fixtures.
const oldLibDir = "testdata/oldlib"
// oldLibFixture is a node written by the old library with the test-only
// keys it was written with and the plaintexts it encrypted.
type oldLibFixture struct {
Comment string
Type string // "folder" or "file"
ParentKey string // armored parent node key, locked with ParentKeyPassphrase
ParentKeyPassphrase string
AddressKey string // armored address key which signs, locked with AddressKeyPassphrase
AddressKeyPassphrase string
NodeKey string
NodePassphrase string // encrypted to the parent key
NodePassphraseSignature string // by the address key
NodePassphrasePlain string
Name string // encrypted to the parent key, signed by the address key
NamePlain string
// A folder's hash key, encrypted to and signed by its node key, and
// the hash of ChildName with it.
NodeHashKey string `json:",omitempty"`
HashKeyPlain string `json:",omitempty"` // base64 of the raw bytes
ChildName string `json:",omitempty"`
ChildNameHash string `json:",omitempty"`
// A file's content key, signed by its node key, and one block of
// content with its signature by the address key, encrypted to the
// node key, and the manifest signature by the address key.
ContentKeyPacket string `json:",omitempty"` // base64, encrypted to the node key
ContentKeyPacketSignature string `json:",omitempty"`
ContentSessionKey string `json:",omitempty"` // hex
Block string `json:",omitempty"` // base64
BlockPlain string `json:",omitempty"` // base64
BlockEncSignature string `json:",omitempty"`
BlockHash string `json:",omitempty"` // base64 SHA-256 of Block
ManifestSignature string `json:",omitempty"`
XAttr string `json:",omitempty"` // encrypted to the node key, signed by the address key
XAttrModificationTime string `json:",omitempty"` // as the old library wrote it
XAttrSize int64 `json:",omitempty"`
XAttrBlockSizes []int64 `json:",omitempty"`
XAttrSHA1 string `json:",omitempty"`
}
// loadOldLibFixture returns the fixture testdata/oldlib/name.json.
func loadOldLibFixture(t *testing.T, name string) oldLibFixture {
t.Helper()
data, err := os.ReadFile(filepath.Join(oldLibDir, name+".json"))
require.NoError(t, err)
var f oldLibFixture
require.NoError(t, json.Unmarshal(data, &f))
return f
}
// unlockedKeyRing returns a key ring of the armored key unlocked with
// passphrase.
func unlockedKeyRing(t *testing.T, armored, passphrase string) *crypto.KeyRing {
t.Helper()
key, err := unlockKey(armored, []byte(passphrase))
require.NoError(t, err)
kr, err := crypto.NewKeyRing(key)
require.NoError(t, err)
return kr
}
// checkOldLibFixture reads f with crypto.go and checks every value
// against its plaintext and every signature against its signer.
func checkOldLibFixture(t *testing.T, f oldLibFixture, now time.Time) {
t.Helper()
parentKR := unlockedKeyRing(t, f.ParentKey, f.ParentKeyPassphrase)
addrPub := publicOf(t, unlockedKeyRing(t, f.AddressKey, f.AddressKeyPassphrase))
keys, verifyErr, err := decryptNodeKeys(parentKR, addrPub, f.NodeKey, f.NodePassphrase, f.NodePassphraseSignature, now)
require.NoError(t, err)
assert.NoError(t, verifyErr, "node passphrase signature")
assert.Equal(t, f.NodePassphrasePlain, string(keys.passphrase))
nodeKR := keys.keyRing
name, verifyErr, err := decryptName(f.Name, parentKR, addrPub, now)
require.NoError(t, err)
assert.NoError(t, verifyErr, "name signature")
assert.Equal(t, f.NamePlain, name)
switch f.Type {
case "folder":
hashKey, verifyErr, err := decryptHashKey(f.NodeHashKey, nodeKR, nil, now)
require.NoError(t, err)
assert.NoError(t, verifyErr, "hash key signature")
assert.Equal(t, f.HashKeyPlain, base64.StdEncoding.EncodeToString(hashKey))
assert.Equal(t, f.ChildNameHash, nameHash(f.ChildName, hashKey))
case "file":
sk, verifyErr, err := decryptContentKey(f.ContentKeyPacket, f.ContentKeyPacketSignature, nodeKR, nil, now)
require.NoError(t, err)
assert.NoError(t, verifyErr, "content key signature")
assert.Equal(t, f.ContentSessionKey, hex.EncodeToString(sk.Key))
block, err := base64.StdEncoding.DecodeString(f.Block)
require.NoError(t, err)
plain, err := decryptBlock(block, sk)
require.NoError(t, err)
assert.Equal(t, f.BlockPlain, base64.StdEncoding.EncodeToString(plain))
hash := sha256.Sum256(block)
assert.Equal(t, f.BlockHash, base64.StdEncoding.EncodeToString(hash[:]))
assert.NoError(t, decryptBlockSignature(t, f.BlockEncSignature, plain, nodeKR, addrPub), "block signature")
assert.NoError(t, verifyManifest([][]byte{hash[:]}, f.ManifestSignature, addrPub, now))
x, verifyErr, err := decryptXAttrs(f.XAttr, nodeKR, addrPub, now)
require.NoError(t, err)
assert.NoError(t, verifyErr, "extended attributes signature")
modTime, err := time.Parse("2006-01-02T15:04:05-0700", f.XAttrModificationTime)
require.NoError(t, err)
assert.True(t, modTime.Equal(x.ModTime), "%v != %v", modTime, x.ModTime)
assert.Equal(t, f.XAttrSize, x.Size)
assert.Equal(t, f.XAttrBlockSizes, x.BlockSizes)
assert.Equal(t, f.XAttrSHA1, x.SHA1)
default:
t.Fatalf("unknown fixture type %q", f.Type)
}
}
// Old library writers.
// oldGeneratePassphrase mirrors generatePassphrase, bridge crypto.go:33-41.
func oldGeneratePassphrase(t *testing.T) string {
t.Helper()
token, err := crypto.RandomToken(32)
require.NoError(t, err)
return base64.StdEncoding.EncodeToString(token)
}
// oldGenerateLockedKey mirrors generateLockedKey, bridge crypto.go:53-69.
func oldGenerateLockedKey(t *testing.T, name, email string, passphrase []byte, aead bool) string {
t.Helper()
pgp := crypto.PGP()
if aead {
// protonDrivePGP, bridge crypto.go:27-31.
p := profile.RFC9580()
p.AeadEncryption = &packet.AEADConfig{DefaultMode: packet.AEADModeGCM}
pgp = crypto.PGPWithProfile(p)
}
key, err := pgp.KeyGeneration().AddUserId(name, email).New().GenerateKey()
require.NoError(t, err)
defer key.ClearPrivateParams()
locked, err := pgp.LockKey(key, passphrase)
require.NoError(t, err)
armored, err := locked.Armor()
require.NoError(t, err)
return armored
}
// oldGenerateCryptoKey mirrors generateCryptoKey, bridge crypto.go:71-86.
func oldGenerateCryptoKey(t *testing.T, aead bool) (passphrase, armoredKey string) {
t.Helper()
passphrase = oldGeneratePassphrase(t)
return passphrase, oldGenerateLockedKey(t, "Drive key", "noreply@protonmail.com", []byte(passphrase), aead)
}
// oldGenerateNodeKeys mirrors generateNodeKeys and encryptWithSignature,
// bridge crypto.go:93-135, also returning the passphrase, which the
// bridge drops.
func oldGenerateNodeKeys(t *testing.T, kr, addrKR *crypto.KeyRing, aead bool) (passphrase, nodeKey, encPassphrase, passphraseSig string) {
t.Helper()
passphrase, nodeKey = oldGenerateCryptoKey(t, aead)
enc, err := proton.EncryptMessageNonAead(kr, []byte(passphrase), nil)
require.NoError(t, err)
encPassphrase, err = enc.Armor()
require.NoError(t, err)
sh, err := crypto.PGP().Sign().SigningKeys(addrKR).Detached().New()
require.NoError(t, err)
sig, err := sh.Sign([]byte(passphrase), crypto.Armor)
require.NoError(t, err)
return passphrase, nodeKey, encPassphrase, string(sig)
}
// oldEncryptBlock mirrors the block encryption of
// uploadAndCollectBlockData, bridge file_upload.go:360-406, returning
// the encrypted block, its encrypted signature and its SHA-256.
func oldEncryptBlock(t *testing.T, data []byte, sk *crypto.SessionKey, nodeKR, addrKR *crypto.KeyRing) (encData []byte, encSignature string, hash []byte) {
t.Helper()
p := profile.RFC9580()
p.AeadEncryption = &packet.AEADConfig{DefaultMode: packet.AEADModeGCM}
eh, err := crypto.PGPWithProfile(p).Encryption().SessionKey(sk).New()
require.NoError(t, err)
msg, err := eh.Encrypt(data)
require.NoError(t, err)
encData = msg.Bytes()
sh, err := crypto.PGP().Sign().SigningKeys(addrKR).Detached().New()
require.NoError(t, err)
rawSig, err := sh.Sign(data, crypto.Bytes)
require.NoError(t, err)
encSig, err := proton.EncryptMessageNonAead(nodeKR, rawSig, nil)
require.NoError(t, err)
encSignature, err = encSig.Armor()
require.NoError(t, err)
sum := sha256.Sum256(encData)
return encData, encSignature, sum[:]
}
// oldSignManifest mirrors commitNewRevision, bridge file_upload.go:429-437.
func oldSignManifest(t *testing.T, manifest []byte, addrKR *crypto.KeyRing) string {
t.Helper()
sh, err := crypto.PGP().Sign().SigningKeys(addrKR).Detached().New()
require.NoError(t, err)
sig, err := sh.Sign(manifest, crypto.Armor)
require.NoError(t, err)
return string(sig)
}
// oldLibKeys returns a new parent node key and address key as the old
// library would hold them, armored and locked, and unlocked.
func oldLibKeys(t *testing.T) (f oldLibFixture, parentKR, addrKR *crypto.KeyRing) {
t.Helper()
f.ParentKeyPassphrase, f.ParentKey = oldGenerateCryptoKey(t, false)
f.AddressKeyPassphrase = oldGeneratePassphrase(t)
f.AddressKey = oldGenerateLockedKey(t, "test", "test@proton.test", []byte(f.AddressKeyPassphrase), false)
return f, unlockedKeyRing(t, f.ParentKey, f.ParentKeyPassphrase), unlockedKeyRing(t, f.AddressKey, f.AddressKeyPassphrase)
}
// writeOldLibFolder returns a folder written by the old library, as
// CreateNewFolder does in bridge folder.go:83-136.
func writeOldLibFolder(t *testing.T) oldLibFixture {
t.Helper()
f, parentKR, addrKR := oldLibKeys(t)
f.Comment = "Folder written by go-proton-api v1.0.4 and Proton-API-Bridge v1.0.5 with test-only keys."
f.Type = "folder"
f.NodePassphrasePlain, f.NodeKey, f.NodePassphrase, f.NodePassphraseSignature = oldGenerateNodeKeys(t, parentKR, addrKR, false)
req := proton.CreateFolderReq{}
f.NamePlain = "Fichiers d'été 📁"
require.NoError(t, req.SetName(f.NamePlain, addrKR, parentKR))
f.Name = req.Name
nodeKR := unlockedKeyRing(t, f.NodeKey, f.NodePassphrasePlain)
require.NoError(t, req.SetNodeHashKey(nodeKR))
f.NodeHashKey = req.NodeHashKey
// The old library never returns the plaintext hash key, so read it
// back with its own reader, as its callers do (bridge folder.go:116-120).
verifyKR, err := joinKeyRings(addrKR, nodeKR)
require.NoError(t, err)
hashKey, err := proton.Link{Type: proton.LinkTypeFolder, FolderProperties: &proton.FolderProperties{NodeHashKey: f.NodeHashKey}}.GetHashKey(nodeKR, verifyKR)
require.NoError(t, err)
f.HashKeyPlain = base64.StdEncoding.EncodeToString(hashKey)
f.ChildName = "Document.txt"
f.ChildNameHash, err = proton.GetNameHash(f.ChildName, hashKey)
require.NoError(t, err)
return f
}
// writeOldLibFile returns a file of one 1 KiB block written by the old
// library, as uploadFile does in bridge file_upload.go:97-169 and
// 355-505.
func writeOldLibFile(t *testing.T) oldLibFixture {
t.Helper()
f, parentKR, addrKR := oldLibKeys(t)
f.Comment = "File written by go-proton-api v1.0.4 and Proton-API-Bridge v1.0.5 with test-only keys."
f.Type = "file"
f.NodePassphrasePlain, f.NodeKey, f.NodePassphrase, f.NodePassphraseSignature = oldGenerateNodeKeys(t, parentKR, addrKR, false)
req := proton.CreateFileReq{}
f.NamePlain = "Résumé – final.pdf"
require.NoError(t, req.SetName(f.NamePlain, addrKR, parentKR))
f.Name = req.Name
nodeKR := unlockedKeyRing(t, f.NodeKey, f.NodePassphrasePlain)
sk, err := req.SetContentKeyPacketAndSignature(nodeKR)
require.NoError(t, err)
f.ContentKeyPacket, f.ContentKeyPacketSignature = req.ContentKeyPacket, req.ContentKeyPacketSignature
f.ContentSessionKey = hex.EncodeToString(sk.Key)
plain := make([]byte, 1024)
_, err = rand.Read(plain)
require.NoError(t, err)
block, encSig, hash := oldEncryptBlock(t, plain, sk, nodeKR, addrKR)
f.Block, f.BlockPlain, f.BlockEncSignature = base64.StdEncoding.EncodeToString(block), base64.StdEncoding.EncodeToString(plain), encSig
f.BlockHash = base64.StdEncoding.EncodeToString(hash)
f.ManifestSignature = oldSignManifest(t, hash, addrKR)
digest := sha1.Sum(plain)
common := &proton.RevisionXAttrCommon{
ModificationTime: time.Date(2023, 11, 20, 9, 30, 15, 0, time.FixedZone("", 5*3600+30*60)).Format("2006-01-02T15:04:05-0700"),
Size: int64(len(plain)),
BlockSizes: []int64{int64(len(plain))},
Digests: map[string]string{"SHA1": hex.EncodeToString(digest[:])},
}
commit := proton.CommitRevisionReq{}
require.NoError(t, commit.SetEncXAttrString(addrKR, nodeKR, common))
f.XAttr = commit.XAttr
f.XAttrModificationTime, f.XAttrSize, f.XAttrBlockSizes, f.XAttrSHA1 = common.ModificationTime, common.Size, common.BlockSizes, common.Digests["SHA1"]
return f
}
// Old library readers.
// oldDecryptBlock mirrors decryptBlockIntoBuffer, bridge crypto.go:218-280.
func oldDecryptBlock(sk *crypto.SessionKey, addrKR, nodeKR *crypto.KeyRing, originalHash, encSignature string, data []byte) ([]byte, error) {
skDec, err := crypto.PGP().Decryption().SessionKey(sk).New()
if err != nil {
return nil, err
}
skResult, err := skDec.Decrypt(data, crypto.Bytes)
if err != nil {
return nil, err
}
plain := skResult.Bytes()
encSignatureMsg, err := crypto.NewPGPMessageFromArmored(encSignature)
if err != nil {
return nil, err
}
sigDec, err := crypto.PGP().Decryption().DecryptionKeys(nodeKR).New()
if err != nil {
return nil, err
}
sigResult, err := sigDec.Decrypt(encSignatureMsg.Bytes(), crypto.Bytes)
if err != nil {
return nil, err
}
vh, err := crypto.PGP().Verify().VerificationKeys(addrKR).New()
if err != nil {
return nil, err
}
verifyResult, err := vh.VerifyDetached(plain, sigResult.Bytes(), crypto.Bytes)
if err != nil {
return nil, err
}
if err := verifyResult.SignatureError(); err != nil {
return nil, err
}
hash := sha256.Sum256(data)
if base64.StdEncoding.EncodeToString(hash[:]) != originalHash {
return nil, errors.New("block hash mismatch")
}
return plain, nil
}
// requireFingerprints checks that got holds the keys of want, in order.
func requireFingerprints(t *testing.T, want, got *crypto.KeyRing) {
t.Helper()
var wantFPs, gotFPs []string
for _, k := range want.GetKeys() {
wantFPs = append(wantFPs, k.GetFingerprint())
}
for _, k := range got.GetKeys() {
gotFPs = append(gotFPs, k.GetFingerprint())
}
require.NotEmpty(t, wantFPs)
require.Equal(t, wantFPs, gotFPs)
}
func TestNewWriterOldReader(t *testing.T) {
now := time.Now()
parentKR, addrKR, otherParentKR := newTestKeyRing(t, now), newTestKeyRing(t, now), newTestKeyRing(t, now)
addrPub := publicOf(t, addrKR)
t.Run("Folder", func(t *testing.T) {
armoredKey, encPassphrase, passphraseSig, keys := testNodeKeys(t, parentKR, addrKR, false, now)
const name = "Fichiers d'été 📁"
encName, err := encryptName(name, nil, parentKR, addrKR, now)
require.NoError(t, err)
encHashKey, hashKey, err := generateHashKey(keys.keyRing, now)
require.NoError(t, err)
link := proton.Link{
Type: proton.LinkTypeFolder,
Name: encName,
NodeKey: armoredKey,
NodePassphrase: encPassphrase,
NodePassphraseSignature: passphraseSig,
FolderProperties: &proton.FolderProperties{NodeHashKey: encHashKey},
}
nodeKR, err := link.GetKeyRing(parentKR, addrPub)
require.NoError(t, err)
requireFingerprints(t, keys.keyRing, nodeKR)
gotName, err := link.GetName(parentKR, addrPub)
require.NoError(t, err)
assert.Equal(t, name, gotName)
// The bridge verifies hash keys against the signer's address keys
// and the folder's node key (folder.go:116-120).
verifyKR, err := joinKeyRings(addrPub, nodeKR)
require.NoError(t, err)
gotHashKey, err := link.GetHashKey(nodeKR, verifyKR)
require.NoError(t, err)
assert.Equal(t, hashKey, gotHashKey)
oldHash, err := proton.GetNameHash("Document.txt", gotHashKey)
require.NoError(t, err)
assert.Equal(t, nameHash("Document.txt", hashKey), oldHash)
// A move re-encrypts the passphrase and the name to the new
// parent with their session keys.
link.NodePassphrase, link.NodePassphraseSignature, err = reencryptPassphrase(keys, otherParentKR, addrKR, now)
require.NoError(t, err)
sk, err := nameSessionKey(encName, parentKR)
require.NoError(t, err)
link.Name, err = encryptName("Moved", sk, otherParentKR, addrKR, now)
require.NoError(t, err)
nodeKR, err = link.GetKeyRing(otherParentKR, addrPub)
require.NoError(t, err)
requireFingerprints(t, keys.keyRing, nodeKR)
gotName, err = link.GetName(otherParentKR, addrPub)
require.NoError(t, err)
assert.Equal(t, "Moved", gotName)
})
t.Run("File", func(t *testing.T) {
armoredKey, encPassphrase, passphraseSig, keys := testNodeKeys(t, parentKR, addrKR, true, now)
const name = "Résumé – final.pdf"
encName, err := encryptName(name, nil, parentKR, addrKR, now)
require.NoError(t, err)
contentKeyPacket, contentKeyPacketSig, sk, err := generateContentKey(keys.keyRing, now)
require.NoError(t, err)
link := proton.Link{
Type: proton.LinkTypeFile,
Name: encName,
NodeKey: armoredKey,
NodePassphrase: encPassphrase,
NodePassphraseSignature: passphraseSig,
FileProperties: &proton.FileProperties{
ContentKeyPacket: contentKeyPacket,
ContentKeyPacketSignature: contentKeyPacketSig,
},
}
nodeKR, err := link.GetKeyRing(parentKR, addrPub)
require.NoError(t, err)
requireFingerprints(t, keys.keyRing, nodeKR)
gotName, err := link.GetName(parentKR, addrPub)
require.NoError(t, err)
assert.Equal(t, name, gotName)
gotSK, err := link.GetSessionKey(nodeKR)
require.NoError(t, err)
assert.Equal(t, sk.Key, gotSK.Key)
// The content written for a new file - a v6 content key packet and
// SEIPDv2 blocks and block signatures - is read by the old
// library's block reader.
plain := make([]byte, 1024)
_, err = rand.Read(plain)
require.NoError(t, err)
block, encSig, hash, err := encryptBlock(plain, sk, keys.keyRing, addrKR, now)
require.NoError(t, err)
rawKeyPacket, err := base64.StdEncoding.DecodeString(contentKeyPacket)
require.NoError(t, err)
require.Equal(t, 6, readPackets(t, rawKeyPacket, 1)[0].(*packet.EncryptedKey).Version)
require.Equal(t, 2, readPackets(t, block, 1)[0].(*packet.SymmetricallyEncrypted).Version)
require.Equal(t, 2, readPackets(t, unarmor(t, encSig), 2)[1].(*packet.SymmetricallyEncrypted).Version)
gotPlain, err := oldDecryptBlock(gotSK, addrPub, nodeKR, base64.StdEncoding.EncodeToString(hash[:]), encSig, block)
require.NoError(t, err)
assert.Equal(t, plain, gotPlain)
// Extended attributes, read as the bridge does (file.go:47-91).
digest := sha1.Sum(plain)
modTime := time.Date(2024, 3, 5, 7, 7, 8, 123456789, time.FixedZone("CET", 3600))
encXAttr, err := encryptXAttrs(&xattrs{ModTime: modTime, Size: 1024, BlockSizes: []int64{1024}, SHA1: hex.EncodeToString(digest[:])}, keys.keyRing, addrKR, now)
require.NoError(t, err)
rev := proton.RevisionMetadata{XAttr: encXAttr}
common, err := rev.GetDecXAttrString(addrPub, nodeKR)
require.NoError(t, err)
require.NotNil(t, common)
gotModTime, err := iso8601.ParseString(common.ModificationTime)
require.NoError(t, err)
assert.True(t, modTime.Truncate(time.Millisecond).Equal(gotModTime), "%v", gotModTime)
assert.Equal(t, int64(1024), common.Size)
assert.Equal(t, []int64{1024}, common.BlockSizes)
assert.Equal(t, hex.EncodeToString(digest[:]), common.Digests["SHA1"])
})
}
func TestOldWriterNewReader(t *testing.T) {
t.Run("Folder", func(t *testing.T) {
checkOldLibFixture(t, writeOldLibFolder(t), time.Time{})
})
t.Run("File", func(t *testing.T) {
checkOldLibFixture(t, writeOldLibFile(t), time.Time{})
})
t.Run("ShareKey", func(t *testing.T) {
// A share key is a node key whose passphrase is encrypted to and
// signed by the address key; proton.Share.GetKeyRing reads it.
_, _, addrKR := oldLibKeys(t)
passphrase, shareKey, encPassphrase, passphraseSig := oldGenerateNodeKeys(t, addrKR, addrKR, false)
share := proton.Share{Key: shareKey, Passphrase: encPassphrase, PassphraseSignature: passphraseSig}
oldKR, err := share.GetKeyRing(addrKR)
require.NoError(t, err)
keys, verifyErr, err := decryptNodeKeys(addrKR, publicOf(t, addrKR), shareKey, encPassphrase, passphraseSig, time.Time{})
require.NoError(t, err)
assert.NoError(t, verifyErr)
assert.Equal(t, passphrase, string(keys.passphrase))
requireFingerprints(t, oldKR, keys.keyRing)
})
t.Run("CryptoRefreshNodeKey", func(t *testing.T) {
// The bridge can also generate a v6 node key locked with the
// RFC 9580 profile (bridge crypto.go:53-69 with aead set).
_, parentKR, addrKR := oldLibKeys(t)
passphrase, nodeKey, encPassphrase, passphraseSig := oldGenerateNodeKeys(t, parentKR, addrKR, true)
keys, verifyErr, err := decryptNodeKeys(parentKR, publicOf(t, addrKR), nodeKey, encPassphrase, passphraseSig, time.Time{})
require.NoError(t, err)
assert.NoError(t, verifyErr)
assert.Equal(t, passphrase, string(keys.passphrase))
assert.Equal(t, 6, keys.keyRing.GetKeys()[0].GetVersion())
})
}
func TestKeyUnlockMatchesOldLibrary(t *testing.T) {
srv := protontest.New(t)
u := srv.AddUser("user", "pass")
u.AddAddress("alias@proton.test")
s := newAccountSession(srv, u)
ctx := context.Background()
a, err := loadAccount(ctx, s, []byte(u.KeyPassword()))
require.NoError(t, err)
defer a.close()
// The same responses, decoded as the old library's types.
var user struct{ User proton.User }
_, err = s.call(ctx, &rest.Opts{Method: "GET", Path: "/core/v4/users"}, nil, &user)
require.NoError(t, err)
var addrs struct{ Addresses []proton.Address }
_, err = s.call(ctx, &rest.Opts{Method: "GET", Path: "/core/v4/addresses"}, nil, &addrs)
require.NoError(t, err)
userKR, addrKRs, err := proton.Unlock(user.User, addrs.Addresses, []byte(u.KeyPassword()), nil)
require.NoError(t, err)
requireFingerprints(t, userKR, a.userKR)
require.Len(t, a.addresses, len(addrKRs))
for _, addr := range a.addresses {
require.Contains(t, addrKRs, addr.ID)
requireFingerprints(t, addrKRs[addr.ID], addr.keyRing)
}
}
func TestFrozenFixtures(t *testing.T) {
if *updateOldLib {
require.NoError(t, os.MkdirAll(oldLibDir, 0o755))
for name, f := range map[string]oldLibFixture{"folder": writeOldLibFolder(t), "file": writeOldLibFile(t)} {
data, err := json.MarshalIndent(f, "", "\t")
require.NoError(t, err)
require.NoError(t, os.WriteFile(filepath.Join(oldLibDir, name+".json"), append(data, '\n'), 0o644))
}
}
entries, err := os.ReadDir(oldLibDir)
require.NoError(t, err)
var n int
for _, e := range entries {
name, ok := strings.CutSuffix(e.Name(), ".json")
if !ok {
continue
}
n++
t.Run(name, func(t *testing.T) {
checkOldLibFixture(t, loadOldLibFixture(t, name), time.Time{})
})
}
assert.Equal(t, 2, n, "fixtures in %s", oldLibDir)
}