Files
rclone/backend/protondrive/golden_internal_test.go
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

1641 lines
56 KiB
Go

package protondrive
import (
"bytes"
"context"
stdcrypto "crypto"
"crypto/sha1"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"path"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"testing"
"time"
"github.com/ProtonMail/go-crypto/openpgp/packet"
openpgp "github.com/ProtonMail/go-crypto/openpgp/v2"
"github.com/ProtonMail/gopenpgp/v3/armor"
"github.com/ProtonMail/gopenpgp/v3/constants"
"github.com/ProtonMail/gopenpgp/v3/crypto"
"github.com/ProtonMail/gopenpgp/v3/profile"
"github.com/rclone/rclone/backend/protondrive/protontest"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/fstest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var (
goldenCaptureDir = flag.String("capture", "", "Capture golden fixtures of the folder -capture-remote names into this directory")
goldenCaptureRemote = flag.String("capture-remote", "", "Folder to capture golden fixtures of, as NAME:PATH")
goldenCaptureLabel = flag.String("capture-label", "", "Client which wrote the folder -capture captures, such as web or cli")
)
// goldenDir holds folder trees written by Proton's own clients, one
// directory per client, captured by TestGoldenCapture and re-keyed onto
// keys made for the tests: no secret of the account they came from is
// in them.
//
// A directory holds keys.json (goldenKeys), nodes.json (goldenFixture)
// and the encrypted blocks of each file, as Proton stores them.
const goldenDir = "testdata/golden"
// goldenEmail replaces every email of the captured account.
const goldenEmail = "golden@example.invalid"
const (
// goldenMaxFiles is the most files TestGoldenCapture captures.
goldenMaxFiles = 3
// goldenMaxFileSize is the largest encrypted size of a file
// TestGoldenCapture captures.
goldenMaxFileSize = 16 << 20
)
// goldenKeys is the key material a fixture is encrypted to, made for
// the tests alone.
type goldenKeys struct {
Comment string
Email string // address which signs, the owner's primary address
Keys protontest.FixedKeys
}
// goldenFixture is a folder tree another client wrote, re-keyed.
type goldenFixture struct {
Comment string
Label string // the client which wrote the nodes
Nodes []goldenNode // parents before children; the first is the captured folder
}
// goldenNode is a node of a fixture as the server stores it, with what
// the backend must read from it.
type goldenNode struct {
ID string // placeholder
ParentID string // placeholder; empty for the captured folder, stored in the root
Folder *protontest.StoredFolder `json:",omitempty"`
File *protontest.StoredFile `json:",omitempty"` // block data in ID-block-N.bin
Want goldenWant
Rekeyed []string // what the capture replaced, one line per field
}
// goldenWant is what reading a node must give.
type goldenWant struct {
Name string
ModTime time.Time
MIMEType string `json:",omitempty"`
Size int64 `json:",omitempty"`
SHA1 string `json:",omitempty"` // hex of the content, not as claimed
// BlockSizes are the plaintext sizes of the blocks, and
// BlockSizesRecorded whether the extended attributes record them.
BlockSizes []int64 `json:",omitempty"`
BlockSizesRecorded bool `json:",omitempty"`
}
// goldenBlockFile returns the file name of block i, from 0, of node id.
func goldenBlockFile(id string, i int) string {
return id + "-block-" + strconv.Itoa(i+1) + ".bin"
}
// checkCaptureFlags returns whether a capture was asked for, or an
// error if its flags are incomplete or -remote is set too: with -remote
// set, a mistyped -run would run the integration tests, which write,
// against the captured account.
func checkCaptureFlags(dir, label, captureRemote, remote string) (bool, error) {
switch {
case dir == "" && captureRemote == "":
return false, nil
case remote != "":
return false, errors.New("-capture must not be used with -remote: name the folder with -capture-remote")
case dir == "":
return false, errors.New("-capture-remote needs -capture naming the directory to capture into")
case captureRemote == "":
return false, errors.New("-capture needs -capture-remote NAME:PATH naming the folder to capture")
case label == "":
return false, errors.New("-capture needs -capture-label naming the client which wrote the folder")
case label != filepath.Base(label) || label == "." || label == "..":
return false, fmt.Errorf("-capture-label %q must be a plain name", label)
}
return true, nil
}
// TestGoldenCapture captures the folder -capture-remote names, written
// by another client, into the directory -capture/-capture-label, then
// reads the fixture back as TestGoldenFixtures does. It contacts the
// remote's real server, so it runs only when asked:
//
// go test ./backend/protondrive/ -v -run '^TestGoldenCapture$' -capture DIR -capture-label web -capture-remote NAME:PATH
func TestGoldenCapture(t *testing.T) {
run, err := checkCaptureFlags(*goldenCaptureDir, *goldenCaptureLabel, *goldenCaptureRemote, *fstest.RemoteName)
require.NoError(t, err)
if !run {
t.Skip("set -capture, -capture-label and -capture-remote to capture golden fixtures")
}
fstest.Initialise()
ctx := context.Background()
fsys, err := fs.NewFs(ctx, *goldenCaptureRemote)
require.NoError(t, err)
f, ok := fsys.(*Fs)
require.True(t, ok, "%s is not a protondrive remote", *goldenCaptureRemote)
defer func() { _ = f.Shutdown(ctx) }()
out := filepath.Join(*goldenCaptureDir, *goldenCaptureLabel)
require.NoError(t, captureGolden(ctx, f, *goldenCaptureLabel, out, goldenMaxFiles, t.Logf))
keys, fx := loadGolden(t, out)
checkGolden(t, keys, fx)
}
// TestGoldenFixtures reads every fixture in goldenDir through the
// backend from a fake server storing it.
func TestGoldenFixtures(t *testing.T) {
fixtures, err := filepath.Glob(filepath.Join(goldenDir, "*", "nodes.json"))
require.NoError(t, err)
if len(fixtures) == 0 {
t.Skip("no fixtures in " + goldenDir)
}
for _, p := range fixtures {
dir := filepath.Dir(p)
t.Run(filepath.Base(dir), func(t *testing.T) {
keys, fx := loadGolden(t, dir)
checkGoldenPackets(t, keys, fx)
checkGolden(t, keys, fx)
})
}
}
// TestGoldenCaptureFlags checks a capture runs only with all its flags.
func TestGoldenCaptureFlags(t *testing.T) {
run, err := checkCaptureFlags("", "", "", "")
assert.False(t, run)
assert.NoError(t, err)
run, err = checkCaptureFlags("", "", "", "TestProtonDrive:")
assert.False(t, run, "-remote alone is for the integration tests")
assert.NoError(t, err)
_, err = checkCaptureFlags("dir", "web", "", "")
assert.ErrorContains(t, err, "-capture-remote")
_, err = checkCaptureFlags("", "web", "remote:path", "")
assert.ErrorContains(t, err, "needs -capture")
_, err = checkCaptureFlags("dir", "web", "remote:path", "remote:path")
assert.ErrorContains(t, err, "must not be used with -remote")
_, err = checkCaptureFlags("dir", "web", "", "remote:path")
assert.ErrorContains(t, err, "must not be used with -remote")
_, err = checkCaptureFlags("dir", "", "remote:path", "")
assert.ErrorContains(t, err, "-capture-label")
_, err = checkCaptureFlags("dir", "../web", "remote:path", "")
assert.ErrorContains(t, err, "plain name")
run, err = checkCaptureFlags("dir", "web", "remote:path", "")
assert.True(t, run)
assert.NoError(t, err)
}
// TestGoldenRoundTrip captures files of several shapes from a fake
// server, then reads them back from the fixture and checks it holds
// no secret of the account captured.
func TestGoldenRoundTrip(t *testing.T) {
ctx := context.Background()
// The keys of a frozen fixture are known, so the test can look for
// them in the capture.
source := loadFrozenFile(t, filepath.Join(frozenFileDir, "legacy"))
srv := protontest.New(t)
u := srv.AddUserWithKeys(source.Email, "pass", source.Keys)
modTime := time.Date(2025, 3, 4, 5, 6, 7, 0, time.UTC)
top := u.SeedFolder(u.RootID(), "captured folder")
sub := u.SeedFolder(top, "sub")
contents := map[string][]byte{
"a big.bin": testContent(5<<20 + 7),
"b blocks.txt": testContent(2<<20 + 500),
"c legacy": testContent(1500),
"sub/d anonymous.bin": testContent(2500),
"sub/e over the cap.bin": testContent(10),
}
ids := []string{
u.SeedFile(top, "a big.bin", contents["a big.bin"], modTime),
u.SeedFileInBlocks(top, "b blocks.txt", contents["b blocks.txt"], 1<<20),
u.SeedLegacyFile(top, "c legacy", contents["c legacy"]),
u.SeedAnonymousFile(sub, "d anonymous.bin", contents["sub/d anonymous.bin"], modTime),
u.SeedFile(sub, "e over the cap.bin", contents["sub/e over the cap.bin"], modTime),
}
m := sessionConfig(srv, u)
f, err := NewFs(ctx, "source", "captured folder", m)
require.NoError(t, err)
out := filepath.Join(t.TempDir(), "fake")
require.NoError(t, captureGolden(ctx, f.(*Fs), "fake", out, 4, t.Logf))
keys, fx := loadGolden(t, out)
require.Len(t, fx.Nodes, 6, "the folders and the first four files")
read := checkGolden(t, keys, fx)
delete(contents, "sub/e over the cap.bin")
require.Len(t, read, len(contents))
for name, want := range contents {
assert.True(t, bytes.Equal(want, read["captured folder/"+name]), "%s reads back different", name)
}
// The blocks are kept byte for byte.
var blocks [][]byte
for _, id := range ids[:4] {
for _, b := range u.StoredFile(id).Revision.Blocks {
blocks = append(blocks, b.Data)
}
}
var captured [][]byte
for _, n := range fx.Nodes {
if n.File != nil {
for _, b := range n.File.Revision.Blocks {
captured = append(captured, b.Data)
}
}
}
assert.Equal(t, blocks, captured)
// Shapes the backend must tell apart survive the capture.
byName := map[string]goldenNode{}
for _, n := range fx.Nodes {
byName[n.Want.Name] = n
}
assert.True(t, byName["a big.bin"].Want.BlockSizesRecorded)
assert.Equal(t, []int64{4 << 20, 1<<20 + 7}, byName["a big.bin"].Want.BlockSizes)
assert.False(t, byName["b blocks.txt"].Want.BlockSizesRecorded)
assert.Equal(t, []int64{1 << 20, 1 << 20, 500}, byName["b blocks.txt"].Want.BlockSizes)
assert.Empty(t, byName["d anonymous.bin"].File.Link.SignatureEmail)
assert.Equal(t, goldenEmail, byName["a big.bin"].File.Link.SignatureEmail)
for _, n := range fx.Nodes {
assert.NotEmpty(t, n.Rekeyed, "%s records what was re-keyed", n.Want.Name)
}
// An anonymous file is signed by its parent's node key.
assert.Equal(t, "link-5", byName["d anonymous.bin"].ParentID)
assert.Contains(t, byName["d anonymous.bin"].Rekeyed, "Name: v4 signature (type 0, SHA-256) by the node key of link-5 made again")
t.Run("tampered", func(t *testing.T) {
testGoldenTampered(t, out)
})
// Nothing of the source account is in the capture: no key, key
// packet or signature names a key but the test keys...
checkGoldenPackets(t, keys, fx)
// ...and no secret, ID or email of the account is in it as text.
var all []byte
entries, err := os.ReadDir(out)
require.NoError(t, err)
for _, e := range entries {
data, err := os.ReadFile(filepath.Join(out, e.Name()))
require.NoError(t, err)
all = append(all, data...)
}
secrets := []string{
source.Email, source.Keys.AddressKey, source.Keys.AddressKeyPassphrase,
source.Keys.RootKey, source.Keys.RootKeyPassphrase, source.Keys.RootHashKey,
u.VolumeID(), u.ShareID(), u.RootID(), top, sub,
}
secrets = append(secrets, ids...)
secrets = append(secrets, goldenSecretForms([]byte(u.KeyPassword()))...)
secrets = append(secrets, srv.IssuedSecrets(protontest.SessionToken, protontest.StorageToken)...)
sourceKeys := []string{source.Keys.AddressKey, source.Keys.RootKey}
for _, id := range ids {
stored := u.StoredFile(id)
sourceKeys = append(sourceKeys, stored.Link.NodeKey)
secrets = append(secrets, stored.Link.NodeKey, stored.Link.NodePassphrase, stored.Link.NodePassphraseSignature)
passphrase, sessionKey := u.NodeSecrets(id)
secrets = append(secrets, goldenSecretForms(passphrase)...)
secrets = append(secrets, goldenSecretForms(sessionKey)...)
}
for _, armored := range sourceKeys {
key, err := crypto.NewKeyFromArmored(armored)
require.NoError(t, err)
e := key.GetEntity()
pks := []*packet.PublicKey{e.PrimaryKey}
for _, sub := range e.Subkeys {
pks = append(pks, sub.PublicKey)
}
for _, pk := range pks {
id := fmt.Sprintf("%016x", pk.KeyId)
fp := hex.EncodeToString(pk.Fingerprint)
secrets = append(secrets, id, strings.ToUpper(id), fp, strings.ToUpper(fp), base64.StdEncoding.EncodeToString(pk.Fingerprint))
}
}
for _, secret := range secrets {
require.NotEmpty(t, secret)
assert.False(t, bytes.Contains(all, []byte(secret)), "the capture holds %.40q", secret)
// JSON escapes the newlines of armored text.
escaped, err := json.Marshal(secret)
require.NoError(t, err)
assert.False(t, bytes.Contains(all, escaped[1:len(escaped)-1]), "the capture holds %.40q", secret)
}
}
// goldenSecretForms returns the forms secret could be written in.
func goldenSecretForms(secret []byte) []string {
return []string{string(secret), base64.StdEncoding.EncodeToString(secret), hex.EncodeToString(secret)}
}
// loadGolden returns the keys and nodes of the fixture in dir, with
// their blocks.
func loadGolden(t testing.TB, dir string) (goldenKeys, goldenFixture) {
t.Helper()
var keys goldenKeys
var fx goldenFixture
for name, v := range map[string]any{"keys.json": &keys, "nodes.json": &fx} {
data, err := os.ReadFile(filepath.Join(dir, name))
require.NoError(t, err)
require.NoError(t, json.Unmarshal(data, v), name)
}
require.NotEmpty(t, fx.Nodes, "nodes")
for _, n := range fx.Nodes {
if n.File == nil {
continue
}
for i := range n.File.Revision.Blocks {
data, err := os.ReadFile(filepath.Join(dir, goldenBlockFile(n.ID, i)))
require.NoError(t, err)
n.File.Revision.Blocks[i].Data = data
}
}
return keys, fx
}
// serveGolden stores the fixture on a fake server for a user holding
// its keys and returns an Fs of that user with ignore_signature_errors
// off and the path of each node by placeholder.
func serveGolden(t *testing.T, keys goldenKeys, fx goldenFixture) (*Fs, map[string]string) {
t.Helper()
srv := protontest.New(t)
u := srv.AddUserWithKeys(keys.Email, "pass", keys.Keys)
ids := map[string]string{"": u.RootID()}
for _, n := range fx.Nodes {
parentID, ok := ids[n.ParentID]
require.True(t, ok, "parent of %s is stored before it", n.ID)
switch {
case n.Folder != nil:
ids[n.ID] = u.SeedStoredFolder(parentID, *n.Folder)
case n.File != nil:
ids[n.ID] = u.SeedStoredFile(parentID, *n.File)
default:
t.Fatalf("node %s is neither a folder nor a file", n.ID)
}
}
m := sessionConfig(srv, u)
m["ignore_signature_errors"] = "false"
f := newTestFs(t, m)
paths := map[string]string{"": ""}
for _, n := range fx.Nodes {
paths[n.ID] = path.Join(paths[n.ParentID], f.opt.Enc.ToStandardName(n.Want.Name))
}
return f, paths
}
// checkGolden stores the fixture on a fake server for a user holding
// its keys and reads every node through the backend, failing on any
// signature which doesn't verify. It returns the content of each file
// by path.
func checkGolden(t *testing.T, keys goldenKeys, fx goldenFixture) map[string][]byte {
t.Helper()
ctx := context.Background()
f, paths := serveGolden(t, keys, fx)
children := map[string][]string{}
for _, n := range fx.Nodes {
children[paths[n.ParentID]] = append(children[paths[n.ParentID]], paths[n.ID])
if n.Folder != nil {
// An empty folder is listed too.
if _, ok := children[paths[n.ID]]; !ok {
children[paths[n.ID]] = nil
}
}
}
// Every folder holding nodes of the fixture is listed, the root
// included.
listed := map[string]fs.DirEntry{}
for dir, want := range children {
entries, err := f.List(ctx, dir)
require.NoError(t, err, "list %q", dir)
var got []string
for _, e := range entries {
got = append(got, e.Remote())
listed[e.Remote()] = e
}
assert.ElementsMatch(t, want, got, "listing of %q", dir)
}
read := map[string][]byte{}
for _, n := range fx.Nodes {
p := paths[n.ID]
if n.Folder != nil {
if e := listed[p]; assert.NotNil(t, e, "%s listed", p) {
assert.True(t, n.Want.ModTime.Equal(e.ModTime(ctx)), "modification time of %s: %v, want %v", p, e.ModTime(ctx), n.Want.ModTime)
}
continue
}
read[p] = checkGoldenFile(ctx, t, f, p, n.Want)
}
f.c.mu.Lock()
defer f.c.mu.Unlock()
assert.Empty(t, f.c.reported, "problems reported")
assert.Zero(t, f.c.skipped, "nodes left out of listings")
return read
}
// checkGoldenFile reads file p of f whole and from its second block,
// checks it against want and returns its content.
func checkGoldenFile(ctx context.Context, t *testing.T, f *Fs, p string, want goldenWant) []byte {
t.Helper()
o, err := f.NewObject(ctx, p)
require.NoError(t, err, p)
assert.Equal(t, want.Size, o.Size(), "size of %s", p)
assert.True(t, want.ModTime.Equal(o.ModTime(ctx)), "modification time of %s: %v, want %v", p, o.ModTime(ctx), want.ModTime)
assert.Equal(t, want.MIMEType, o.(*Object).MimeType(ctx), "media type of %s", p)
sum, err := o.Hash(ctx, hash.SHA1)
require.NoError(t, err)
if want.SHA1 == sha1Of(nil) {
// A file without blocks may claim no digest.
assert.Contains(t, []string{"", want.SHA1}, sum, "SHA-1 of %s", p)
} else {
assert.Equal(t, want.SHA1, sum, "SHA-1 of %s", p)
}
rc, err := o.Open(ctx)
require.NoError(t, err, p)
data, err := io.ReadAll(rc)
require.NoError(t, err, "read %s", p)
require.NoError(t, rc.Close())
assert.Equal(t, want.SHA1, sha1Of(data), "SHA-1 of the content of %s", p)
if len(data) == 0 {
return data
}
// A ranged read starts in a later block when there is one.
offset := int64(len(data)) / 2
if len(want.BlockSizes) > 1 {
offset = want.BlockSizes[0] + want.BlockSizes[1]/2
}
rc, err = o.Open(ctx, &fs.RangeOption{Start: offset, End: -1})
require.NoError(t, err, p)
part, err := io.ReadAll(rc)
require.NoError(t, err, "read %s from %d", p, offset)
require.NoError(t, rc.Close())
assert.True(t, bytes.Equal(data[offset:], part), "%s read from %d differs", p, offset)
return data
}
// captureGolden captures the folder at the root of f, its subfolders
// and up to maxFiles files of them, into dir, re-keyed onto keys made
// for the tests, and logs a summary with logf. dir must not exist.
func captureGolden(ctx context.Context, f *Fs, label, dir string, maxFiles int, logf func(format string, args ...any)) error {
if _, err := os.Stat(dir); !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("capture: %s must not exist", dir)
}
c := f.c
if c.opt.IgnoreSignatureErrors {
return errors.New("capture: turn ignore_signature_errors off, so only nodes which verify are captured")
}
topID, err := f.dirCache.RootID(ctx, false)
if err != nil {
return fmt.Errorf("capture: %w", err)
}
top, err := c.getNode(ctx, topID)
if err != nil {
return fmt.Errorf("capture: %w", err)
}
if top.ParentID == "" {
return errors.New("capture: name a folder below the root")
}
parent, err := c.getNode(ctx, top.ParentID)
if err != nil {
return fmt.Errorf("capture: %w", err)
}
gc := &goldenCapture{
c: c,
maxFiles: maxFiles,
logf: logf,
blocks: map[string][][]byte{},
rk: &rekeyer{
signers: map[uint64]rekeyedKey{},
fingerprints: map[string][]byte{},
owns: c.acct.owns,
},
fixture: goldenFixture{
Comment: "A folder tree " + label + " wrote, captured by TestGoldenCapture: the encrypted data is the client's, its key packets re-wrapped and its signatures re-made with the keys in keys.json.",
Label: label,
},
}
keys, rootKR, rootHashKey, err := gc.testKeys(parent.keys.keyRing.GetKeys()[0])
if err != nil {
return fmt.Errorf("capture: %w", err)
}
if err := gc.node(ctx, top, parent.keys.keyRing, rootKR, rootHashKey, ""); err != nil {
return fmt.Errorf("capture: %w", err)
}
if err := gc.write(dir, keys); err != nil {
return fmt.Errorf("capture: %w", err)
}
for _, n := range gc.fixture.Nodes {
kind := "folder"
if n.File != nil {
kind = fmt.Sprintf("file, %d bytes in %d blocks, block sizes recorded: %v", n.Want.Size, len(n.Want.BlockSizes), n.Want.BlockSizesRecorded)
}
logf("%s %q (written by %s; %s)", n.ID, n.Want.Name, label, kind)
for _, line := range n.Rekeyed {
logf(" %s", line)
}
}
return nil
}
// goldenCapture is a capture in progress.
type goldenCapture struct {
c *client
rk *rekeyer
maxFiles int
logf func(format string, args ...any)
fixture goldenFixture
blocks map[string][][]byte // by node placeholder
files int
}
// testKeys returns new keys replacing the account's address keys and
// origRoot, the key of the captured folder's parent, with the root
// key's ring and its hash key.
func (gc *goldenCapture) testKeys(origRoot *crypto.Key) (keys goldenKeys, rootKR *crypto.KeyRing, rootHashKey []byte, err error) {
addrKey, err := generateKeyLike(gc.c.addr.keyRing.GetKeys()[0])
if err != nil {
return keys, nil, nil, err
}
for _, addr := range gc.c.acct.addresses {
for _, k := range addr.keyRing.GetKeys() {
gc.rk.replace(k, addrKey, "address key")
}
}
if err := gc.rk.checkUserIDs(origRoot); err != nil {
return keys, nil, nil, err
}
rootKey, err := generateKeyLike(origRoot)
if err != nil {
return keys, nil, nil, err
}
gc.rk.replace(origRoot, rootKey, "node key of the captured folder's parent")
if rootKR, err = crypto.NewKeyRing(rootKey); err != nil {
return keys, nil, nil, err
}
keys = goldenKeys{Comment: "Keys made by TestGoldenCapture for the tests alone.", Email: goldenEmail}
if keys.Keys.RootHashKey, rootHashKey, err = generateHashKey(rootKR, time.Time{}); err != nil {
return keys, nil, nil, err
}
if keys.Keys.AddressKey, keys.Keys.AddressKeyPassphrase, err = lockNewKey(addrKey); err != nil {
return keys, nil, nil, err
}
if keys.Keys.RootKey, keys.Keys.RootKeyPassphrase, err = lockNewKey(rootKey); err != nil {
return keys, nil, nil, err
}
return keys, rootKR, rootHashKey, nil
}
// lockNewKey returns key armored and locked with a new passphrase.
func lockNewKey(key *crypto.Key) (armored, passphrase string, err error) {
pass, err := generatePassphrase()
if err != nil {
return "", "", err
}
locked, err := crypto.PGP().LockKey(key, pass)
if err != nil {
return "", "", err
}
armored, err = locked.Armor()
return armored, string(pass), err
}
// goldenUserName is the user ID name of every key a capture writes,
// with goldenEmail.
const goldenUserName = "golden"
// generateKeyLike returns a new key with the algorithm, version,
// creation time and AEAD support of orig, and the user ID goldenUserName
// <goldenEmail>.
func generateKeyLike(orig *crypto.Key) (*crypto.Key, error) {
pk := orig.GetEntity().PrimaryKey
algo := pk.PubKeyAlgo
bits, err := pk.BitLength()
if err != nil {
return nil, err
}
switch algo {
case packet.PubKeyAlgoEdDSA, packet.PubKeyAlgoEd25519, packet.PubKeyAlgoEd448, packet.PubKeyAlgoRSA:
default:
return nil, fmt.Errorf("key %s: algorithm %d is not supported", orig.GetHexKeyID(), algo)
}
p := profile.Default()
p.V6 = pk.Version == 6
p.SetKeyAlgorithm = func(cfg *packet.Config, _ int8) {
cfg.Algorithm, cfg.Curve, cfg.RSABits = algo, packet.Curve25519, int(bits)
}
if sig, _ := orig.GetEntity().PrimarySelfSignature(time.Now(), nil); sig != nil && sig.SEIPDv2 {
p.AeadEncryption = &packet.AEADConfig{DefaultMode: packet.AEADModeGCM}
}
key, err := crypto.PGPWithProfile(p).KeyGeneration().AddUserId(goldenUserName, goldenEmail).GenerationTime(pk.CreationTime.Unix()).New().GenerateKey()
if err != nil {
return nil, fmt.Errorf("key like %s: %w", orig.GetHexKeyID(), err)
}
return key, nil
}
// node captures n, encrypted to origParentKR, as a child of the node
// parentID whose new key is parentKR, then its children. The captured
// folder, alone, gets a new name hash with parentHashKey.
func (gc *goldenCapture) node(ctx context.Context, n *node, origParentKR, parentKR *crypto.KeyRing, parentHashKey []byte, parentID string) error {
if !n.IsFolder {
switch {
case gc.files >= gc.maxFiles:
gc.logf("skipped %q: more than %d files", n.Name, gc.maxFiles)
return nil
case n.EncryptedSize > goldenMaxFileSize:
gc.logf("skipped %q: %d bytes encrypted, more than %d", n.Name, n.EncryptedSize, goldenMaxFileSize)
return nil
}
}
if err := gc.verified(n); err != nil {
return err
}
rk := gc.rk
rk.notes = nil
id := "link-" + strconv.Itoa(len(gc.fixture.Nodes)+1)
l := &n.link.Link
origKey := n.keys.keyRing.GetKeys()[0]
if err := rk.checkUserIDs(origKey); err != nil {
return fmt.Errorf("%q: %w", n.Name, err)
}
newKey, err := generateKeyLike(origKey)
if err != nil {
return err
}
rk.replace(origKey, newKey, "node key of "+id)
newKR, err := crypto.NewKeyRing(newKey)
if err != nil {
return err
}
armoredKey, passphrase, err := lockNewKey(newKey)
if err != nil {
return err
}
rk.note("NodeKey: new key of the same algorithm, version and creation time, user ID %s <%s>", goldenUserName, goldenEmail)
stored := protontest.StoredLink{
NodeKey: armoredKey,
NameHash: l.NameHash,
CreateTime: l.CreateTime,
ModifyTime: l.ModifyTime,
}
if parentHashKey != nil {
stored.NameHash = nameHash(n.Name, parentHashKey)
rk.note("NameHash: made again with the new parent's hash key")
}
errs := []error{
rk.field("NodePassphrase", &stored.NodePassphrase, func() (string, error) {
return rk.reseal(l.NodePassphrase, origParentKR, parentKR, []byte(passphrase))
}),
rk.field("NodePassphraseSignature", &stored.NodePassphraseSignature, func() (string, error) {
return rk.resignDetached(l.NodePassphraseSignature, []byte(passphrase))
}),
rk.field("Name", &stored.Name, func() (string, error) {
return rk.reseal(l.Name, origParentKR, parentKR, nil)
}),
rk.field("SignatureEmail", &stored.SignatureEmail, func() (string, error) { return rk.email(l.SignatureEmail) }),
rk.field("NameSignatureEmail", &stored.NameSignatureEmail, func() (string, error) { return rk.email(l.NameSignatureEmail) }),
}
if err := errors.Join(errs...); err != nil {
return fmt.Errorf("%q: %w", n.Name, err)
}
gn := goldenNode{ID: id, ParentID: parentID, Want: goldenWant{Name: n.Name, ModTime: n.modTime()}}
if n.IsFolder {
return gc.folder(ctx, n, gn, stored, newKR)
}
gc.files++
return gc.file(ctx, n, gn, stored, newKR)
}
// folder captures folder n, whose node is gn and link stored, and its
// children.
func (gc *goldenCapture) folder(ctx context.Context, n *node, gn goldenNode, stored protontest.StoredLink, newKR *crypto.KeyRing) error {
rk := gc.rk
origKR := n.keys.keyRing
gn.Folder = &protontest.StoredFolder{Link: stored}
err := errors.Join(
rk.field("NodeHashKey", &gn.Folder.HashKey, func() (string, error) {
return rk.reseal(n.link.Folder.NodeHashKey, origKR, newKR, nil)
}),
rk.field("XAttr", &gn.Folder.XAttr, func() (string, error) {
return rk.reseal(n.link.Folder.XAttr, origKR, newKR, nil)
}),
)
if err != nil {
return fmt.Errorf("%q: %w", n.Name, err)
}
gn.Rekeyed = rk.notes
gc.fixture.Nodes = append(gc.fixture.Nodes, gn)
var children []*node
err = gc.c.listChildren(ctx, n.ID, func(batch []*node) error {
children = append(children, batch...)
return nil
})
if err != nil {
return err
}
slices.SortFunc(children, func(a, b *node) int { return strings.Compare(a.Name, b.Name) })
for _, child := range children {
if err := gc.node(ctx, child, origKR, newKR, nil, gn.ID); err != nil {
return err
}
}
return nil
}
// file captures file n, whose node is gn and link stored, with its
// active revision and blocks.
func (gc *goldenCapture) file(ctx context.Context, n *node, gn goldenNode, stored protontest.StoredLink, newKR *crypto.KeyRing) error {
rk := gc.rk
c := gc.c
f := n.link.File
rev := f.ActiveRevision
if rev == nil {
return fmt.Errorf("%q: no active revision", n.Name)
}
// Reading the file whole checks every signature the backend
// checks, the manifest's included, with the account's keys.
rc, err := c.open(ctx, n, 0, -1)
if err != nil {
return fmt.Errorf("%q: %w", n.Name, err)
}
content, err := io.ReadAll(rc)
_ = rc.Close()
if err != nil {
return fmt.Errorf("%q: %w", n.Name, err)
}
sum := sha1.Sum(content)
gn.Want.SHA1 = hex.EncodeToString(sum[:])
gn.Want.Size = int64(len(content))
gn.Want.MIMEType = f.MediaType
gn.Want.BlockSizesRecorded = n.X != nil && n.X.BlockSizes != nil
if n.X != nil && n.X.SHA1 != "" && !strings.EqualFold(n.X.SHA1, gn.Want.SHA1) {
rk.note("XAttr: claims SHA-1 %s, the content has %s", n.X.SHA1, gn.Want.SHA1)
}
sk, err := c.contentKey(n, "reading")
if err != nil {
return fmt.Errorf("%q: %w", n.Name, err)
}
stored.MediaType = f.MediaType
gn.File = &protontest.StoredFile{Link: stored}
gn.File.Revision.CreateTime = rev.CreateTime
var hashes [][]byte
for from := 1; ; {
page, err := c.revisionBlocks(ctx, n, from, blocksPerPage)
if err != nil {
return fmt.Errorf("%q: %w", n.Name, err)
}
if len(page.Thumbnails) > 0 {
return fmt.Errorf("%q has thumbnails, which the fake server can't serve: capture a file which has none", n.Name)
}
if len(page.Blocks) == 0 {
break
}
for _, b := range page.Blocks {
data, hash, err := gc.downloadBlock(ctx, b.BareURL, b.Token)
if err != nil {
return fmt.Errorf("%q: block %d: %w", n.Name, b.Index, err)
}
if b.Index != from || base64.StdEncoding.EncodeToString(hash) != b.Hash {
return fmt.Errorf("%q: block %d doesn't match its listing", n.Name, b.Index)
}
plain, err := decryptBlock(data, sk)
if err != nil {
return fmt.Errorf("%q: block %d: %w", n.Name, b.Index, err)
}
gn.Want.BlockSizes = append(gn.Want.BlockSizes, int64(len(plain)))
gc.blocks[gn.ID] = append(gc.blocks[gn.ID], data)
gn.File.Revision.Blocks = append(gn.File.Revision.Blocks, protontest.StoredBlock{Hash: hash})
hashes = append(hashes, hash)
from++
}
}
if len(hashes) > 0 {
rk.note("blocks: %d kept byte for byte; their signatures, which the backend doesn't read, left out", len(hashes))
}
origKR := n.keys.keyRing
err = errors.Join(
rk.field("ContentKeyPacket", &gn.File.Link.ContentKeyPacket, func() (string, error) {
return rk.rewrapContentKey(f.ContentKeyPacket, origKR, newKR)
}),
rk.field("ContentKeyPacketSignature", &gn.File.Link.ContentKeyPacketSignature, func() (string, error) {
return rk.resignDetached(f.ContentKeyPacketSignature, sk.Key)
}),
rk.field("XAttr", &gn.File.Revision.XAttr, func() (string, error) {
return rk.reseal(rev.XAttr, origKR, newKR, nil)
}),
rk.field("ManifestSignature", &gn.File.Revision.ManifestSignature, func() (string, error) {
return rk.resignDetached(rev.ManifestSignature, bytes.Join(hashes, nil))
}),
rk.field("Revision SignatureEmail", &gn.File.Revision.SignatureEmail, func() (string, error) { return rk.email(rev.SignatureEmail) }),
)
if err != nil {
return fmt.Errorf("%q: %w", n.Name, err)
}
gn.Rekeyed = rk.notes
gc.fixture.Nodes = append(gc.fixture.Nodes, gn)
return nil
}
// downloadBlock returns the encrypted block at bareURL and its SHA-256.
func (gc *goldenCapture) downloadBlock(ctx context.Context, bareURL, token string) (data, hash []byte, err error) {
enc, hash, err := gc.c.downloadBlock(ctx, bareURL, token)
if err != nil {
return nil, nil, err
}
defer func() { _ = enc.Close() }()
data, err = io.ReadAll(enc)
return data, hash, err
}
// verified returns an error if the account's keys don't verify every
// signature of n which the backend checks on listing it.
func (gc *goldenCapture) verified(n *node) error {
if n.keys.unverified != nil {
return fmt.Errorf("%q: %w", n.Name, n.keys.unverified)
}
gc.c.mu.Lock()
defer gc.c.mu.Unlock()
for key := range gc.c.reported {
if strings.HasSuffix(key, ":"+n.ID) {
return fmt.Errorf("%q: the backend reported a problem (%s): see the log", n.Name, key)
}
}
return nil
}
// write writes the capture into dir.
func (gc *goldenCapture) write(dir string, keys goldenKeys) error {
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
for name, v := range map[string]any{"keys.json": keys, "nodes.json": gc.fixture} {
data, err := json.MarshalIndent(v, "", "\t")
if err != nil {
return err
}
if err := os.WriteFile(filepath.Join(dir, name), append(data, '\n'), 0o644); err != nil {
return err
}
}
for id, blocks := range gc.blocks {
for i, data := range blocks {
if err := os.WriteFile(filepath.Join(dir, goldenBlockFile(id, i)), data, 0o644); err != nil {
return err
}
}
}
return nil
}
// rekeyer moves OpenPGP data from the keys of an account to test keys,
// keeping its format.
type rekeyer struct {
signers map[uint64]rekeyedKey // by key ID of each original key and subkey
fingerprints map[string][]byte // fingerprint of the replacement of each original key and subkey, by the original's
owns func(email string) bool
notes []string // what was done to the current node
}
// rekeyedKey is the key replacing an original key, with what the
// original was.
type rekeyedKey struct {
key *crypto.Key
role string
}
// replace makes repl, in role, the replacement of orig.
func (rk *rekeyer) replace(orig, repl *crypto.Key, role string) {
oe, re := orig.GetEntity(), repl.GetEntity()
rk.signers[oe.PrimaryKey.KeyId] = rekeyedKey{repl, role}
rk.fingerprints[string(oe.PrimaryKey.Fingerprint)] = re.PrimaryKey.Fingerprint
for _, sub := range oe.Subkeys {
rk.signers[sub.PublicKey.KeyId] = rekeyedKey{repl, role}
if len(re.Subkeys) > 0 {
rk.fingerprints[string(sub.PublicKey.Fingerprint)] = re.Subkeys[0].PublicKey.Fingerprint
}
}
}
// note records what was done to the current node.
func (rk *rekeyer) note(format string, args ...any) {
rk.notes = append(rk.notes, fmt.Sprintf(format, args...))
}
// field sets *dst to what fn returns and names the field in the notes
// fn writes and in its error.
func (rk *rekeyer) field(name string, dst *string, fn func() (string, error)) error {
start := len(rk.notes)
v, err := fn()
if err != nil {
return fmt.Errorf("%s: %w", name, err)
}
for i := start; i < len(rk.notes); i++ {
rk.notes[i] = name + ": " + rk.notes[i]
}
*dst = v
return nil
}
// email returns the email replacing email, an address of the account
// or empty.
func (rk *rekeyer) email(email string) (string, error) {
switch {
case email == "":
return "", nil
case rk.owns(email):
rk.note("replaced by %s", goldenEmail)
return goldenEmail, nil
}
return "", fmt.Errorf("signed as %q, which is not the account's: its keys can't be replaced", email)
}
// emailPattern matches what looks like an email in a user ID.
var emailPattern = regexp.MustCompile(`[^\s<>()"]+@[^\s<>()"]+`)
// genericKeyEmails are the emails Proton's clients give every node key
// in its user ID: the C# SDK (and so the official CLI) and the old Go
// library.
var genericKeyEmails = []string{"no-reply@proton.me", "noreply@protonmail.com"}
// checkUserIDs returns an error if a user ID of orig holds an email
// other than one of the account's or a generic one: a key of someone
// else can't be replaced. Every key written has goldenUserName
// <goldenEmail> instead.
func (rk *rekeyer) checkUserIDs(orig *crypto.Key) error {
for _, id := range orig.GetEntity().Identities {
for _, email := range emailPattern.FindAllString(id.Name, -1) {
if !rk.owns(email) && !slices.Contains(genericKeyEmails, strings.ToLower(email)) {
return errors.New("a node key's user ID holds an email which is not the account's")
}
}
}
return nil
}
// rewrapContentKey returns the base64 content key packet with its
// session key, which fromKR decrypts, encrypted to toKR instead.
func (rk *rekeyer) rewrapContentKey(packetB64 string, fromKR, toKR *crypto.KeyRing) (string, error) {
sk, _, err := decryptContentKey(packetB64, "", fromKR, nil, time.Time{})
if err != nil {
return "", err
}
keyPacket, err := rk.wrap(sk, toKR)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(keyPacket), nil
}
// wrap returns sk encrypted to toKR, in a PKESK of the version sk was
// read from.
func (rk *rekeyer) wrap(sk *crypto.SessionKey, toKR *crypto.KeyRing) ([]byte, error) {
eh, err := pgpFor(sk).Encryption().Recipients(toKR).New()
if err != nil {
return nil, err
}
keyPacket, err := eh.EncryptSessionKey(sk)
if err != nil {
return nil, err
}
version := 3
if sk.IsV6() {
version = 6
}
rk.note("session key re-wrapped in a v%d PKESK", version)
return keyPacket, nil
}
// reseal returns the armored message, whose session key fromKR
// decrypts, with its session key encrypted to toKR instead, and every
// signature inside it made again. The data packet is kept byte for
// byte if it holds no signature and plain is nil; otherwise it is
// encrypted again with the same session key, cipher and AEAD mode,
// over the same packets but for the signatures. If plain is not nil it
// replaces the literal data, encrypted with a new session key of the
// same kind. An empty message stays empty.
func (rk *rekeyer) reseal(armored string, fromKR, toKR *crypto.KeyRing, plain []byte) (string, error) {
if armored == "" {
return "", nil
}
m, err := openMessage(armored, fromKR)
if err != nil {
return "", err
}
if n, err := countPackets(m.keyPackets); err != nil || n != 1 {
rk.note("%d key packets (%v), one kept", n, err)
}
sk, se, data, cipherFunc := m.sk, m.se, m.data, m.cipherFunc
inner, signatures, err := rk.resignPackets(m.inner, plain)
if err != nil {
return "", err
}
if signatures == 0 && plain == nil {
keyPacket, err := rk.wrap(sk, toKR)
if err != nil {
return "", err
}
rk.note("SEIPDv%d data packet kept byte for byte", se.Version)
return armorMessage(append(keyPacket, data...), sk)
}
if plain != nil {
token, err := crypto.RandomToken(len(sk.Key))
if err != nil {
return "", err
}
sk = crypto.NewSessionKeyFromTokenWithAead(token, sk.Algo, sk.IsV6())
rk.note("new content, encrypted with a new session key of the same kind")
}
keyPacket, err := rk.wrap(sk, toKR)
if err != nil {
return "", err
}
out := bytes.NewBuffer(keyPacket)
cfg := &packet.Config{AEADConfig: &packet.AEADConfig{DefaultMode: se.Mode, ChunkSize: 1 << (se.ChunkSizeByte + 6)}}
w, err := packet.SerializeSymmetricallyEncrypted(out, cipherFunc, se.Version == 2, packet.CipherSuite{Cipher: se.Cipher, Mode: se.Mode}, sk.Key, cfg)
if err != nil {
return "", err
}
if _, err := w.Write(inner); err != nil {
return "", err
}
if err := w.Close(); err != nil {
return "", err
}
rk.note("SEIPDv%d data packet encrypted again with the same parameters", se.Version)
return armorMessage(out.Bytes(), sk)
}
// openedMessage is an armored message decrypted down to its inner
// packets.
type openedMessage struct {
keyPackets []byte // the packets before the data packet
data []byte // the data packet
sk *crypto.SessionKey
se *packet.SymmetricallyEncrypted
cipherFunc packet.CipherFunction
inner []byte // the decrypted packets of the data packet
}
// openMessage decrypts the armored message, which must be SEIPD, with
// kr.
func openMessage(armored string, kr *crypto.KeyRing) (*openedMessage, error) {
msg, err := crypto.NewPGPMessageFromArmored(armored)
if err != nil {
return nil, err
}
m := &openedMessage{keyPackets: msg.BinaryKeyPacket(), data: msg.BinaryDataPacket()}
dh, err := crypto.PGP().Decryption().DecryptionKeys(kr).New()
if err != nil {
return nil, err
}
if m.sk, err = dh.DecryptSessionKey(m.keyPackets); err != nil {
return nil, err
}
p, err := packet.Read(bytes.NewReader(m.data))
if err != nil {
return nil, err
}
se, ok := p.(*packet.SymmetricallyEncrypted)
if !ok || !se.IntegrityProtected {
return nil, fmt.Errorf("data packet %T is not SEIPD", p)
}
m.se, m.cipherFunc = se, se.Cipher
if se.Version == 1 {
if m.cipherFunc, err = m.sk.GetCipherFunc(); err != nil {
return nil, err
}
}
rc, err := se.Decrypt(m.cipherFunc, m.sk.Key)
if err != nil {
return nil, err
}
m.inner, err = io.ReadAll(rc)
if closeErr := rc.Close(); err == nil {
err = closeErr
}
return m, err
}
// countPackets returns the number of packets in data.
func countPackets(data []byte) (int, error) {
r := packet.NewOpaqueReader(bytes.NewReader(data))
n := 0
for {
if _, err := r.Next(); err == io.EOF {
return n, nil
} else if err != nil {
return n, err
}
n++
}
}
// OpenPGP packet tags of the packets inside an encrypted message.
const (
tagSignature = 2
tagOnePassSignature = 4
tagCompressed = 8
tagLiteralData = 11
)
// resignPackets returns the decrypted packets inner with each
// signature, and its one-pass signature, made again over the literal
// data, which plain replaces if not nil, and the number of signatures.
// A compressed packet is compressed again with the same algorithm.
func (rk *rekeyer) resignPackets(inner, plain []byte) ([]byte, int, error) {
r := packet.NewOpaqueReader(bytes.NewReader(inner))
var (
items []*packet.OpaquePacket
compressed = map[*packet.OpaquePacket][]byte{} // serialized again
literal []byte
ops []*packet.OnePassSignature
sigs []*packet.Signature
total int
)
for {
op, err := r.Next()
if err == io.EOF {
break
}
if err != nil {
return nil, 0, err
}
switch op.Tag {
case tagCompressed:
if len(op.Contents) == 0 {
return nil, 0, errors.New("empty compressed packet")
}
p, err := op.Parse()
if err != nil {
return nil, 0, err
}
body, err := io.ReadAll(p.(*packet.Compressed).Body)
if err != nil {
return nil, 0, err
}
body, n, err := rk.resignPackets(body, plain)
if err != nil {
return nil, 0, err
}
total += n
var buf bytes.Buffer
w, err := packet.SerializeCompressed(nopWriteCloser{&buf}, packet.CompressionAlgo(op.Contents[0]), nil)
if err == nil {
_, err = w.Write(body)
}
if err == nil {
err = w.Close()
}
if err != nil {
return nil, 0, err
}
compressed[op] = buf.Bytes()
case tagLiteralData:
if len(op.Contents) < 2 || len(op.Contents) < 6+int(op.Contents[1]) {
return nil, 0, errors.New("short literal data packet")
}
header := op.Contents[:6+int(op.Contents[1])]
literal = op.Contents[len(header):]
if plain != nil {
literal = plain
op.Contents = append(slices.Clone(header), plain...)
}
case tagOnePassSignature, tagSignature:
p, err := op.Parse()
if err != nil {
return nil, 0, err
}
switch p := p.(type) {
case *packet.OnePassSignature:
ops = append(ops, p)
case *packet.Signature:
sigs = append(sigs, p)
}
default:
return nil, 0, fmt.Errorf("unexpected packet with tag %d in the message", op.Tag)
}
items = append(items, op)
}
if len(sigs) > 0 && literal == nil {
return nil, 0, errors.New("signature without literal data")
}
if len(ops) != 0 && len(ops) != len(sigs) {
return nil, 0, errors.New("one-pass signatures mixed with signatures without one: not supported")
}
newSigs := make([]*packet.Signature, len(sigs))
for i, sig := range sigs {
var err error
if newSigs[i], err = rk.resignSignature(sig, literal); err != nil {
return nil, 0, err
}
}
var out bytes.Buffer
var opsDone, sigsDone int
for _, op := range items {
var err error
switch {
case compressed[op] != nil:
_, err = out.Write(compressed[op])
case op.Tag == tagOnePassSignature:
// One-pass signatures nest: the first goes with the last
// signature.
orig, sig := ops[opsDone], newSigs[len(sigs)-1-opsDone]
opsDone++
newOps := &packet.OnePassSignature{
Version: orig.Version,
SigType: sig.SigType,
Hash: sig.Hash,
PubKeyAlgo: sig.PubKeyAlgo,
KeyId: *sig.IssuerKeyId,
IsLast: orig.IsLast,
Salt: sig.Salt(),
}
if orig.Version == 6 {
newOps.KeyFingerprint = sig.IssuerFingerprint
}
err = newOps.Serialize(&out)
case op.Tag == tagSignature:
err = newSigs[sigsDone].Serialize(&out)
sigsDone++
default:
err = op.Serialize(&out)
}
if err != nil {
return nil, 0, err
}
}
return out.Bytes(), total + len(sigs), nil
}
// nopWriteCloser is a Writer with a Close which does nothing.
type nopWriteCloser struct{ io.Writer }
func (nopWriteCloser) Close() error { return nil }
// resignDetached returns the armored detached signature of data made
// again for every signature in armoredSig, which may be empty.
func (rk *rekeyer) resignDetached(armoredSig string, data []byte) (string, error) {
if armoredSig == "" {
return "", nil
}
raw, err := armor.Unarmor(armoredSig)
if err != nil {
return "", err
}
r := packet.NewReader(bytes.NewReader(raw))
var out bytes.Buffer
v6 := false
for {
p, err := r.Next()
if err == io.EOF {
break
}
if err != nil {
return "", err
}
sig, ok := p.(*packet.Signature)
if !ok {
return "", fmt.Errorf("%T in a detached signature", p)
}
sig, err = rk.resignSignature(sig, data)
if err != nil {
return "", err
}
v6 = v6 || sig.Version == 6
if err := sig.Serialize(&out); err != nil {
return "", err
}
}
return armor.ArmorWithTypeChecksum(out.Bytes(), constants.PGPSignatureHeader, !v6)
}
// resignSignature returns orig made again over data by the key
// replacing its signer, with orig's type, hash, creation time, lifetime
// and notations (a salt notation with a new salt), and its intended
// recipients replaced. An intended recipient which is not a key being
// replaced is an error, so no other key is named in a fixture.
func (rk *rekeyer) resignSignature(orig *packet.Signature, data []byte) (*packet.Signature, error) {
if orig.IssuerKeyId == nil {
return nil, errors.New("signature without issuer")
}
signer, ok := rk.signers[*orig.IssuerKeyId]
if !ok {
return nil, errors.New("signature by a key which is not one being replaced")
}
priv := signer.key.GetEntity().PrivateKey
sig := &packet.Signature{
Version: priv.PublicKey.Version,
SigType: orig.SigType,
PubKeyAlgo: priv.PubKeyAlgo,
Hash: orig.Hash,
CreationTime: orig.CreationTime,
SigLifetimeSecs: orig.SigLifetimeSecs,
IssuerKeyId: &priv.KeyId,
}
// Signing adds a salt notation unless told not to, so it is there
// only if it was.
salted := false
for _, n := range orig.Notations {
if n.Name == packet.SaltNotationName {
salted = true
} else {
sig.Notations = append(sig.Notations, n)
}
}
if orig.SignerUserId != nil {
email := goldenEmail
sig.SignerUserId = &email
}
for _, r := range orig.IntendedRecipients {
fp, ok := rk.fingerprints[string(r.Fingerprint)]
if !ok {
return nil, errors.New("signature intended for a key which is not one being replaced")
}
sig.IntendedRecipients = append(sig.IntendedRecipients, &packet.Recipient{KeyVersion: r.KeyVersion, Fingerprint: fp})
}
h, err := sig.PrepareSign(nil)
if err != nil {
return nil, err
}
if sig.SigType == packet.SigTypeText {
_, err = openpgp.NewCanonicalTextHash(h).Write(data)
} else {
_, err = h.Write(data)
}
if err != nil {
return nil, err
}
if err := sig.Sign(h, priv, &packet.Config{NonDeterministicSignaturesViaNotation: &salted}); err != nil {
return nil, err
}
rk.note("v%d signature (type %d, %s) by the %s made again", orig.Version, orig.SigType, orig.Hash, signer.role)
if sig.Version != orig.Version || sig.PubKeyAlgo != orig.PubKeyAlgo {
rk.note("signature was v%d algorithm %d, made again as v%d algorithm %d", orig.Version, orig.PubKeyAlgo, sig.Version, sig.PubKeyAlgo)
}
return sig, nil
}
// checkGoldenPackets checks at packet level that every key, key packet
// and signature of the fixture, those inside encrypted messages too,
// names only its test keys and every user ID is the placeholder.
func checkGoldenPackets(t *testing.T, keys goldenKeys, fx goldenFixture) {
t.Helper()
known := map[uint64]bool{}
fingerprints := map[string]bool{}
addKey := func(armored string, passphrase []byte) *crypto.KeyRing {
t.Helper()
key, err := crypto.NewKeyFromArmored(armored)
require.NoError(t, err)
e := key.GetEntity()
known[e.PrimaryKey.KeyId], fingerprints[string(e.PrimaryKey.Fingerprint)] = true, true
for _, sub := range e.Subkeys {
known[sub.PublicKey.KeyId], fingerprints[string(sub.PublicKey.Fingerprint)] = true, true
}
for _, id := range e.Identities {
assert.Equal(t, goldenUserName+" <"+goldenEmail+">", id.Name, "user ID")
}
if passphrase == nil {
return nil
}
unlocked, err := key.Unlock(passphrase)
require.NoError(t, err)
kr, err := crypto.NewKeyRing(unlocked)
require.NoError(t, err)
return kr
}
checkSig := func(sig *packet.Signature, what string) {
t.Helper()
require.NotNil(t, sig.IssuerKeyId, "%s: issuer", what)
assert.True(t, known[*sig.IssuerKeyId], "%s: issuer %016X is not a test key", what, *sig.IssuerKeyId)
if sig.IssuerFingerprint != nil {
assert.True(t, fingerprints[string(sig.IssuerFingerprint)], "%s: issuer fingerprint is not a test key's", what)
}
for _, r := range sig.IntendedRecipients {
assert.True(t, fingerprints[string(r.Fingerprint)], "%s: intended recipient is not a test key", what)
}
if sig.SignerUserId != nil {
assert.Equal(t, goldenEmail, *sig.SignerUserId, "%s: signer user ID", what)
}
}
var checkPackets func(data []byte, what string)
checkPackets = func(data []byte, what string) {
t.Helper()
r := packet.NewReader(bytes.NewReader(data))
for {
p, err := r.Next()
if err == io.EOF {
return
}
require.NoError(t, err, what)
switch p := p.(type) {
case *packet.EncryptedKey:
if p.Version == 6 {
assert.True(t, fingerprints[string(p.KeyFingerprint)], "%s: key packet for a key which is not a test key", what)
} else {
assert.True(t, known[p.KeyId], "%s: key packet for %016X, not a test key", what, p.KeyId)
}
case *packet.Signature:
checkSig(p, what)
case *packet.OnePassSignature:
assert.True(t, known[p.KeyId], "%s: one-pass signature by %016X, not a test key", what, p.KeyId)
case *packet.Compressed:
body, err := io.ReadAll(p.Body)
require.NoError(t, err, what)
checkPackets(body, what)
case *packet.LiteralData:
_, err := io.Copy(io.Discard, p.Body)
require.NoError(t, err, what)
case *packet.SymmetricallyEncrypted:
// The data packet of a message, checked decrypted.
default:
t.Errorf("%s: unexpected %T", what, p)
}
}
}
checkMessage := func(armored string, kr *crypto.KeyRing, what string) {
t.Helper()
if armored == "" {
return
}
m, err := openMessage(armored, kr)
require.NoError(t, err, what)
checkPackets(m.keyPackets, what)
checkPackets(m.inner, what)
}
checkDetached := func(armored, what string) {
t.Helper()
if armored == "" {
return
}
raw, err := armor.Unarmor(armored)
require.NoError(t, err, what)
checkPackets(raw, what)
}
assert.Equal(t, goldenEmail, keys.Email)
addKey(keys.Keys.AddressKey, []byte(keys.Keys.AddressKeyPassphrase))
rootKR := addKey(keys.Keys.RootKey, []byte(keys.Keys.RootKeyPassphrase))
checkMessage(keys.Keys.RootHashKey, rootKR, "root hash key")
// Every node key is known before any signature is checked, as an
// anonymous node is signed by its parent's.
for _, n := range fx.Nodes {
link := goldenLink(n)
addKey(link.NodeKey, nil)
}
krs := map[string]*crypto.KeyRing{"": rootKR}
for _, n := range fx.Nodes {
link := goldenLink(n)
parentKR := krs[n.ParentID]
require.NotNil(t, parentKR, "parent of %s", n.ID)
what := n.ID + " "
dh, err := crypto.PGP().Decryption().DecryptionKeys(parentKR).New()
require.NoError(t, err)
dec, err := dh.Decrypt([]byte(link.NodePassphrase), crypto.Armor)
require.NoError(t, err, what+"passphrase")
kr := addKey(link.NodeKey, dec.Bytes())
krs[n.ID] = kr
for _, s := range []struct{ armored, what string }{{link.NodePassphrase, "passphrase"}, {link.Name, "name"}} {
checkMessage(s.armored, parentKR, what+s.what)
}
checkDetached(link.NodePassphraseSignature, what+"passphrase signature")
for _, email := range []string{link.SignatureEmail, link.NameSignatureEmail} {
assert.Contains(t, []string{"", goldenEmail}, email, what+"signature email")
}
if n.Folder != nil {
checkMessage(n.Folder.HashKey, kr, what+"hash key")
checkMessage(n.Folder.XAttr, kr, what+"extended attributes")
continue
}
keyPacket, err := base64.StdEncoding.DecodeString(n.File.Link.ContentKeyPacket)
require.NoError(t, err)
checkPackets(keyPacket, what+"content key packet")
checkDetached(n.File.Link.ContentKeyPacketSignature, what+"content key signature")
checkMessage(n.File.Revision.XAttr, kr, what+"extended attributes")
checkDetached(n.File.Revision.ManifestSignature, what+"manifest signature")
assert.Contains(t, []string{"", goldenEmail}, n.File.Revision.SignatureEmail, what+"revision signature email")
for i, b := range n.File.Revision.Blocks {
assert.Empty(t, b.EncSignature, "%sblock %d signature", what, i+1)
assert.Empty(t, b.SignatureEmail, "%sblock %d signature email", what, i+1)
}
}
}
// goldenLink returns the link of n.
func goldenLink(n goldenNode) protontest.StoredLink {
if n.Folder != nil {
return n.Folder.Link
}
return n.File.Link
}
// testGoldenTampered checks that reading the fixture in dir fails once
// a byte of a block, a name or a signature is changed.
func testGoldenTampered(t *testing.T, dir string) {
ctx := context.Background()
// flip returns the armored text with a byte near the end of its
// last packet changed.
flip := func(t *testing.T, armored, header string) string {
raw, err := armor.Unarmor(armored)
require.NoError(t, err)
raw[len(raw)-3] ^= 0x40
out, err := armor.ArmorWithType(raw, header)
require.NoError(t, err)
return out
}
firstFile := func(fx goldenFixture) *goldenNode {
for i := range fx.Nodes {
if fx.Nodes[i].File != nil {
return &fx.Nodes[i]
}
}
t.Fatal("no file in the fixture")
return nil
}
read := func(t *testing.T, keys goldenKeys, fx goldenFixture, n *goldenNode) error {
f, paths := serveGolden(t, keys, fx)
o, err := f.NewObject(ctx, paths[n.ID])
if err != nil {
return err
}
rc, err := o.Open(ctx)
if err != nil {
return err
}
defer func() { _ = rc.Close() }()
_, err = io.ReadAll(rc)
return err
}
t.Run("block", func(t *testing.T) {
keys, fx := loadGolden(t, dir)
n := firstFile(fx)
n.File.Revision.Blocks[0].Data[100] ^= 1
assert.Error(t, read(t, keys, fx, n))
})
t.Run("manifest signature", func(t *testing.T) {
keys, fx := loadGolden(t, dir)
n := firstFile(fx)
n.File.Revision.ManifestSignature = flip(t, n.File.Revision.ManifestSignature, constants.PGPSignatureHeader)
assert.ErrorContains(t, read(t, keys, fx, n), "manifest")
})
t.Run("name", func(t *testing.T) {
keys, fx := loadGolden(t, dir)
n := firstFile(fx)
n.File.Link.Name = flip(t, n.File.Link.Name, constants.PGPMessageHeader)
assert.Error(t, read(t, keys, fx, n))
})
}
// TestGoldenRefusesForeignKeys checks a capture fails, naming no key,
// on a node key holding someone else's email or a signature intended
// for a key not being replaced.
func TestGoldenRefusesForeignKeys(t *testing.T) {
rk := &rekeyer{signers: map[uint64]rekeyedKey{}, fingerprints: map[string][]byte{}, owns: func(email string) bool { return email == "me@proton.test" }}
keyFor := func(name, email string) *crypto.Key {
key, err := crypto.PGP().KeyGeneration().AddUserId(name, email).New().GenerateKey()
require.NoError(t, err)
return key
}
assert.NoError(t, rk.checkUserIDs(keyFor("Drive key", "no-reply@proton.me")))
assert.NoError(t, rk.checkUserIDs(keyFor("me@proton.test", "me@proton.test")))
assert.ErrorContains(t, rk.checkUserIDs(keyFor("Drive key", "other@proton.test")), "not the account's")
err := rk.checkUserIDs(keyFor("other@proton.test", "me@proton.test"))
require.Error(t, err)
assert.NotContains(t, err.Error(), "other@")
orig, repl, stranger := keyFor("a", ""), keyFor("b", ""), keyFor("c", "")
rk.replace(orig, repl, "node key")
priv := orig.GetEntity().PrivateKey
sign := func(recipient *crypto.Key) *packet.Signature {
sig := &packet.Signature{
Version: 4, SigType: packet.SigTypeBinary, PubKeyAlgo: priv.PubKeyAlgo, Hash: stdcrypto.SHA256,
CreationTime: time.Now(), IssuerKeyId: &priv.KeyId,
IntendedRecipients: []*packet.Recipient{{KeyVersion: 4, Fingerprint: recipient.GetEntity().PrimaryKey.Fingerprint}},
}
h, err := sig.PrepareSign(nil)
require.NoError(t, err)
h.Write([]byte("data"))
require.NoError(t, sig.Sign(h, priv, nil))
return sig
}
resigned, err := rk.resignSignature(sign(orig), []byte("data"))
require.NoError(t, err)
assert.Equal(t, repl.GetEntity().PrimaryKey.Fingerprint, resigned.IntendedRecipients[0].Fingerprint)
_, err = rk.resignSignature(sign(stranger), []byte("data"))
require.ErrorContains(t, err, "not one being replaced")
fp := stranger.GetEntity().PrimaryKey.Fingerprint
assert.NotContains(t, strings.ToLower(err.Error()), hex.EncodeToString(fp))
assert.NotContains(t, strings.ToLower(strings.Join(rk.notes, "\n")), hex.EncodeToString(fp), "the foreign key is not recorded")
}