aboutsummaryrefslogtreecommitdiffstats
path: root/entities/identity/key.go
blob: 82b9b95ca2689502ac42dea65bcdca268c6e7457 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package identity

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"strings"
	"time"

	"github.com/ProtonMail/go-crypto/openpgp"
	"github.com/ProtonMail/go-crypto/openpgp/armor"
	"github.com/ProtonMail/go-crypto/openpgp/packet"
	"github.com/pkg/errors"

	"github.com/MichaelMure/git-bug/repository"
)

var errNoPrivateKey = fmt.Errorf("no private key")

type Key struct {
	public  *packet.PublicKey
	private *packet.PrivateKey
}

// GenerateKey generate a keypair (public+private)
// The type and configuration of the key is determined by the default value in go's OpenPGP.
func GenerateKey() *Key {
	entity, err := openpgp.NewEntity("", "", "", &packet.Config{
		// The armored format doesn't include the creation time, which makes the round-trip data not being fully equal.
		// We don't care about the creation time so we can set it to the zero value.
		Time: func() time.Time {
			return time.Time{}
		},
	})
	if err != nil {
		panic(err)
	}
	return &Key{
		public:  entity.PrimaryKey,
		private: entity.PrivateKey,
	}
}

// generatePublicKey generate only a public key (only useful for testing)
// See GenerateKey for the details.
func generatePublicKey() *Key {
	k := GenerateKey()
	k.private = nil
	return k
}

func (k *Key) Public() *packet.PublicKey {
	return k.public
}

func (k *Key) Private() *packet.PrivateKey {
	return k.private
}

func (k *Key) Validate() error {
	if k.public == nil {
		return fmt.Errorf("nil public key")
	}
	if !k.public.CanSign() {
		return fmt.Errorf("public key can't sign")
	}

	if k.private != nil {
		if !k.private.CanSign() {
			return fmt.Errorf("private key can't sign")
		}
	}

	return nil
}

func (k *Key) Clone() *Key {
	clone := &Key{}

	pub := *k.public
	clone.public = &pub

	if k.private != nil {
		priv := *k.private
		clone.private = &priv
	}

	return clone
}

func (k *Key) MarshalJSON() ([]byte, error) {
	// Serialize only the public key, in the armored format.
	var buf bytes.Buffer
	w, err := armor.Encode(&buf, openpgp.PublicKeyType, nil)
	if err != nil {
		return nil, err
	}

	err = k.public.Serialize(w)
	if err != nil {
		return nil, err
	}
	err = w.Close()
	if err != nil {
		return nil, err
	}
	return json.Marshal(buf.String())
}

func (k *Key) UnmarshalJSON(data []byte) error {
	// De-serialize only the public key, in the armored format.
	var armored string
	err := json.Unmarshal(data, &armored)
	if err != nil {
		return err
	}

	block, err := armor.Decode(strings.NewReader(armored))
	if err == io.EOF {
		return fmt.Errorf("no armored data found")
	}
	if err != nil {
		return err
	}

	if block.Type != openpgp.PublicKeyType {
		return fmt.Errorf("invalid key type")
	}

	p, err := packet.Read(block.Body)
	if err != nil {
		return errors.Wrap(err, "failed to read public key packet")
	}

	public, ok := p.(*packet.PublicKey)
	if !ok {
		return errors.New("got no packet.publicKey")
	}

	// The armored format doesn't include the creation time, which makes the round-trip data not being fully equal.
	// We don't care about the creation time so we can set it to the zero value.
	public.CreationTime = time.Time{}

	k.public = public
	return nil
}

func (k *Key) loadPrivate(repo repository.RepoKeyring) error {
	item, err := repo.Keyring().Get(k.public.KeyIdString())
	if err == repository.ErrKeyringKeyNotFound {
		return errNoPrivateKey
	}
	if err != nil {
		return err
	}

	block, err := armor.Decode(bytes.NewReader(item.Data))
	if err == io.EOF {
		return fmt.Errorf("no armored data found")
	}
	if err != nil {
		return err
	}

	if block.Type != openpgp.PrivateKeyType {
		return fmt.Errorf("invalid key type")
	}

	p, err := packet.Read(block.Body)
	if err != nil {
		return errors.Wrap(err, "failed to read private key packet")
	}

	private, ok := p.(*packet.PrivateKey)
	if !ok {
		return errors.New("got no packet.privateKey")
	}

	// The armored format doesn't include the creation time, which makes the round-trip data not being fully equal.
	// We don't care about the creation time so we can set it to the zero value.
	private.CreationTime = time.Time{}

	k.private = private
	return nil
}

// ensurePrivateKey attempt to load the corresponding private key if it is not loaded already.
// If no private key is found, returns errNoPrivateKey
func (k *Key) ensurePrivateKey(repo repository.RepoKeyring) error {
	if k.private != nil {
		return nil
	}

	return k.loadPrivate(repo)
}

func (k *Key) storePrivate(repo repository.RepoKeyring) error {
	var buf bytes.Buffer
	w, err := armor.Encode(&buf, openpgp.PrivateKeyType, nil)
	if err != nil {
		return err
	}
	err = k.private.Serialize(w)
	if err != nil {
		return err
	}
	err = w.Close()
	if err != nil {
		return err
	}

	return repo.Keyring().Set(repository.Item{
		Key:  k.public.KeyIdString(),
		Data: buf.Bytes(),
	})
}

func (k *Key) PGPEntity() *openpgp.Entity {
	uid := packet.NewUserId("", "", "")
	return &openpgp.Entity{
		PrimaryKey: k.public,
		PrivateKey: k.private,
		Identities: map[string]*openpgp.Identity{
			uid.Id: {
				Name:   uid.Id,
				UserId: uid,
				SelfSignature: &packet.Signature{
					IsPrimaryId: func() *bool { b := true; return &b }(),
				},
			},
		},
	}
}