Debian Codegraph @

openpgp/keys_prefer_identity_test.go

raw
1 package openpgp
2
3 import (
4 "testing"
5 "time"
6
7 "github.com/ProtonMail/go-crypto/openpgp/packet"
8 )
9
10 // A public key can carry a user ID whose self-signature is absent: for example
11 // a user ID that only has a revocation, or one whose self-signature failed to
12 // verify. Such an identity is stored with a nil SelfSignature.
13 // shouldPreferIdentity must not dereference a nil SelfSignature regardless of
14 // whether the empty identity is the existing primary or the candidate.
15 // Otherwise PrimaryIdentity panics for a fraction of runs, because it iterates
16 // the Identities map in a non-deterministic order.
17
18 func identityWithSelfSignature(name string, creationTime time.Time) *Identity {
19 return &Identity{
20 Name: name,
21 SelfSignature: &packet.Signature{CreationTime: creationTime},
22 }
23 }
24
25 func TestShouldPreferIdentityNilSelfSignature(t *testing.T) {
26 withSelfSig := identityWithSelfSignature("With self-sig <[email protected]>", time.Unix(1000, 0))
27 nilSelfSig := &Identity{Name: "No self-sig <[email protected]>"}
28 anotherNilSelfSig := &Identity{Name: "No self-sig either <[email protected]>"}
29
30 tests := []struct {
31 name string
32 existing *Identity
33 candidate *Identity
34 want bool
35 }{
36 {"candidate without self-signature keeps existing", withSelfSig, nilSelfSig, false},
37 {"existing without self-signature prefers candidate", nilSelfSig, withSelfSig, true},
38 {"both without self-signature prefers candidate", nilSelfSig, anotherNilSelfSig, true},
39 }
40
41 for _, test := range tests {
42 t.Run(test.name, func(t *testing.T) {
43 if got := shouldPreferIdentity(test.existing, test.candidate); got != test.want {
44 t.Errorf("shouldPreferIdentity() = %v, want %v", got, test.want)
45 }
46 })
47 }
48 }
49
50 func TestPrimaryIdentityWithNilSelfSignature(t *testing.T) {
51 withSelfSig := identityWithSelfSignature("With self-sig <[email protected]>", time.Unix(1000, 0))
52 nilSelfSig := &Identity{Name: "No self-sig <[email protected]>"}
53
54 entity := &Entity{
55 Identities: map[string]*Identity{
56 withSelfSig.Name: withSelfSig,
57 nilSelfSig.Name: nilSelfSig,
58 },
59 }
60
61 // Identities is iterated in a randomized order, so repeat to surface the
62 // order-dependent panic and to confirm the identity with a valid
63 // self-signature is always chosen as primary.
64 for range 100 {
65 if primary := entity.PrimaryIdentity(); primary != withSelfSig {
66 t.Fatalf("PrimaryIdentity() = %q, want the identity with a self-signature", primary.Name)
67 }
68 }
69 }