1// Package identity contains the identity data model and low-level related functions
2package identity
3
4import (
5 "encoding/json"
6 "fmt"
7 "reflect"
8
9 "github.com/pkg/errors"
10
11 bootstrap "github.com/MichaelMure/git-bug/entity/boostrap"
12 "github.com/MichaelMure/git-bug/repository"
13 "github.com/MichaelMure/git-bug/util/lamport"
14 "github.com/MichaelMure/git-bug/util/timestamp"
15)
16
17const identityRefPattern = "refs/identities/"
18const identityRemoteRefPattern = "refs/remotes/%s/identities/"
19const versionEntryName = "version"
20const identityConfigKey = "git-bug.identity"
21
22const Typename = "identity"
23const Namespace = "identities"
24
25var ErrNonFastForwardMerge = errors.New("non fast-forward identity merge")
26var ErrNoIdentitySet = errors.New("No identity is set.\n" +
27 "To interact with bugs, an identity first needs to be created using " +
28 "\"git bug user new\" or adopted with \"git bug user adopt\"")
29var ErrMultipleIdentitiesSet = errors.New("multiple user identities set")
30
31var _ Interface = &Identity{}
32var _ bootstrap.Entity = &Identity{}
33
34type Identity struct {
35 // all the successive version of the identity
36 versions []*version
37}
38
39func NewIdentity(repo repository.RepoClock, name string, email string) (*Identity, error) {
40 return NewIdentityFull(repo, name, email, "", "", nil)
41}
42
43func NewIdentityFull(repo repository.RepoClock, name string, email string, login string, avatarUrl string, keys []*Key) (*Identity, error) {
44 v, err := newVersion(repo, name, email, login, avatarUrl, keys)
45 if err != nil {
46 return nil, err
47 }
48 return &Identity{
49 versions: []*version{v},
50 }, nil
51}
52
53// NewFromGitUser will query the repository for user detail and
54// build the corresponding Identity
55func NewFromGitUser(repo repository.ClockedRepo) (*Identity, error) {
56 name, err := repo.GetUserName()
57 if err != nil {
58 return nil, err
59 }
60 if name == "" {
61 return nil, errors.New("user name is not configured in git yet. Please use `git config --global user.name \"John Doe\"`")
62 }
63
64 email, err := repo.GetUserEmail()
65 if err != nil {
66 return nil, err
67 }
68 if email == "" {
69 return nil, errors.New("user name is not configured in git yet. Please use `git config --global user.email johndoe@example.com`")
70 }
71
72 return NewIdentity(repo, name, email)
73}
74
75// MarshalJSON will only serialize the id
76func (i *Identity) MarshalJSON() ([]byte, error) {
77 return json.Marshal(&IdentityStub{
78 id: i.Id(),
79 })
80}
81
82// UnmarshalJSON will only read the id
83// Users of this package are expected to run Load() to load
84// the remaining data from the identities data in git.
85func (i *Identity) UnmarshalJSON(data []byte) error {
86 panic("identity should be loaded with identity.UnmarshalJSON")
87}
88
89// ReadLocal load a local Identity from the identities data available in git
90func ReadLocal(repo repository.Repo, id bootstrap.Id) (*Identity, error) {
91 ref := fmt.Sprintf("%s%s", identityRefPattern, id)
92 return read(repo, ref)
93}
94
95// ReadRemote load a remote Identity from the identities data available in git
96func ReadRemote(repo repository.Repo, remote string, id string) (*Identity, error) {
97 ref := fmt.Sprintf(identityRemoteRefPattern, remote) + id
98 return read(repo, ref)
99}
100
101// read will load and parse an identity from git
102func read(repo repository.Repo, ref string) (*Identity, error) {
103 id := bootstrap.RefToId(ref)
104
105 if err := id.Validate(); err != nil {
106 return nil, errors.Wrap(err, "invalid ref")
107 }
108
109 hashes, err := repo.ListCommits(ref)
110 if err != nil {
111 return nil, bootstrap.NewErrNotFound(Typename)
112 }
113 if len(hashes) == 0 {
114 return nil, fmt.Errorf("empty identity")
115 }
116
117 i := &Identity{}
118
119 for _, hash := range hashes {
120 entries, err := repo.ReadTree(hash)
121 if err != nil {
122 return nil, errors.Wrap(err, "can't list git tree entries")
123 }
124 if len(entries) != 1 {
125 return nil, fmt.Errorf("invalid identity data at hash %s", hash)
126 }
127
128 entry := entries[0]
129 if entry.Name != versionEntryName {
130 return nil, fmt.Errorf("invalid identity data at hash %s", hash)
131 }
132
133 data, err := repo.ReadData(entry.Hash)
134 if err != nil {
135 return nil, errors.Wrap(err, "failed to read git blob data")
136 }
137
138 var version version
139 err = json.Unmarshal(data, &version)
140 if err != nil {
141 return nil, errors.Wrapf(err, "failed to decode Identity version json %s", hash)
142 }
143
144 // tag the version with the commit hash
145 version.commitHash = hash
146
147 i.versions = append(i.versions, &version)
148 }
149
150 if id != i.versions[0].Id() {
151 return nil, fmt.Errorf("identity ID doesn't math the first version ID")
152 }
153
154 return i, nil
155}
156
157// ListLocalIds list all the available local identity ids
158func ListLocalIds(repo repository.Repo) ([]bootstrap.Id, error) {
159 refs, err := repo.ListRefs(identityRefPattern)
160 if err != nil {
161 return nil, err
162 }
163
164 return bootstrap.RefsToIds(refs), nil
165}
166
167// ReadAllLocal read and parse all local Identity
168func ReadAllLocal(repo repository.ClockedRepo) <-chan bootstrap.StreamedEntity[*Identity] {
169 return readAll(repo, identityRefPattern)
170}
171
172// ReadAllRemote read and parse all remote Identity for a given remote
173func ReadAllRemote(repo repository.ClockedRepo, remote string) <-chan bootstrap.StreamedEntity[*Identity] {
174 refPrefix := fmt.Sprintf(identityRemoteRefPattern, remote)
175 return readAll(repo, refPrefix)
176}
177
178// readAll read and parse all available bug with a given ref prefix
179func readAll(repo repository.ClockedRepo, refPrefix string) <-chan bootstrap.StreamedEntity[*Identity] {
180 out := make(chan bootstrap.StreamedEntity[*Identity])
181
182 go func() {
183 defer close(out)
184
185 refs, err := repo.ListRefs(refPrefix)
186 if err != nil {
187 out <- bootstrap.StreamedEntity[*Identity]{Err: err}
188 return
189 }
190
191 total := int64(len(refs))
192 current := int64(1)
193
194 for _, ref := range refs {
195 i, err := read(repo, ref)
196
197 if err != nil {
198 out <- bootstrap.StreamedEntity[*Identity]{Err: err}
199 return
200 }
201
202 out <- bootstrap.StreamedEntity[*Identity]{
203 Entity: i,
204 CurrentEntity: current,
205 TotalEntities: total,
206 }
207 current++
208 }
209 }()
210
211 return out
212}
213
214type Mutator struct {
215 Name string
216 Login string
217 Email string
218 AvatarUrl string
219 Keys []*Key
220}
221
222// Mutate allow to create a new version of the Identity in one go
223func (i *Identity) Mutate(repo repository.RepoClock, f func(orig *Mutator)) error {
224 copyKeys := func(keys []*Key) []*Key {
225 result := make([]*Key, len(keys))
226 for i, key := range keys {
227 result[i] = key.Clone()
228 }
229 return result
230 }
231
232 orig := Mutator{
233 Name: i.Name(),
234 Email: i.Email(),
235 Login: i.Login(),
236 AvatarUrl: i.AvatarUrl(),
237 Keys: copyKeys(i.Keys()),
238 }
239 mutated := orig
240 mutated.Keys = copyKeys(orig.Keys)
241
242 f(&mutated)
243
244 if reflect.DeepEqual(orig, mutated) {
245 return nil
246 }
247
248 v, err := newVersion(repo,
249 mutated.Name,
250 mutated.Email,
251 mutated.Login,
252 mutated.AvatarUrl,
253 mutated.Keys,
254 )
255 if err != nil {
256 return err
257 }
258
259 i.versions = append(i.versions, v)
260 return nil
261}
262
263// Commit write the identity into the Repository. In particular, this ensures that
264// the Id is properly set.
265func (i *Identity) Commit(repo repository.ClockedRepo) error {
266 if !i.NeedCommit() {
267 return fmt.Errorf("can't commit an identity with no pending version")
268 }
269
270 if err := i.Validate(); err != nil {
271 return errors.Wrap(err, "can't commit an identity with invalid data")
272 }
273
274 var lastCommit repository.Hash
275 for _, v := range i.versions {
276 if v.commitHash != "" {
277 lastCommit = v.commitHash
278 // ignore already commit versions
279 continue
280 }
281
282 blobHash, err := v.Write(repo)
283 if err != nil {
284 return err
285 }
286
287 // Make a git tree referencing the blob
288 tree := []repository.TreeEntry{
289 {ObjectType: repository.Blob, Hash: blobHash, Name: versionEntryName},
290 }
291
292 treeHash, err := repo.StoreTree(tree)
293 if err != nil {
294 return err
295 }
296
297 var commitHash repository.Hash
298 if lastCommit != "" {
299 commitHash, err = repo.StoreCommit(treeHash, lastCommit)
300 } else {
301 commitHash, err = repo.StoreCommit(treeHash)
302 }
303 if err != nil {
304 return err
305 }
306
307 lastCommit = commitHash
308 v.commitHash = commitHash
309 }
310
311 ref := fmt.Sprintf("%s%s", identityRefPattern, i.Id().String())
312 return repo.UpdateRef(ref, lastCommit)
313}
314
315func (i *Identity) CommitAsNeeded(repo repository.ClockedRepo) error {
316 if !i.NeedCommit() {
317 return nil
318 }
319 return i.Commit(repo)
320}
321
322func (i *Identity) NeedCommit() bool {
323 for _, v := range i.versions {
324 if v.commitHash == "" {
325 return true
326 }
327 }
328
329 return false
330}
331
332// Merge will merge a different version of the same Identity
333//
334// To make sure that an Identity history can't be altered, a strict fast-forward
335// only policy is applied here. As an Identity should be tied to a single user, this
336// should work in practice, but it does leave a possibility that a user would edit his
337// Identity from two different repo concurrently and push the changes in a non-centralized
338// network of repositories. In this case, it would result in some repo accepting one
339// version and some other accepting another, preventing the network in general to converge
340// to the same result. This would create a sort of partition of the network, and manual
341// cleaning would be required.
342//
343// An alternative approach would be to have a determinist rebase:
344// - any commits present in both local and remote version would be kept, never changed.
345// - newer commits would be merged in a linear chain of commits, ordered based on the
346// Lamport time
347//
348// However, this approach leave the possibility, in the case of a compromised crypto keys,
349// of forging a new version with a bogus Lamport time to be inserted before a legit version,
350// invalidating the correct version and hijacking the Identity. There would only be a short
351// period of time when this would be possible (before the network converge) but I'm not
352// confident enough to implement that. I choose the strict fast-forward only approach,
353// despite its potential problem with two different version as mentioned above.
354func (i *Identity) Merge(repo repository.Repo, other *Identity) (bool, error) {
355 if i.Id() != other.Id() {
356 return false, errors.New("merging unrelated identities is not supported")
357 }
358
359 modified := false
360 var lastCommit repository.Hash
361 for j, otherVersion := range other.versions {
362 // if there is more version in other, take them
363 if len(i.versions) == j {
364 i.versions = append(i.versions, otherVersion)
365 lastCommit = otherVersion.commitHash
366 modified = true
367 }
368
369 // we have a non fast-forward merge.
370 // as explained in the doc above, refusing to merge
371 if i.versions[j].commitHash != otherVersion.commitHash {
372 return false, ErrNonFastForwardMerge
373 }
374 }
375
376 if modified {
377 err := repo.UpdateRef(identityRefPattern+i.Id().String(), lastCommit)
378 if err != nil {
379 return false, err
380 }
381 }
382
383 return false, nil
384}
385
386// Validate check if the Identity data is valid
387func (i *Identity) Validate() error {
388 lastTimes := make(map[string]lamport.Time)
389
390 if len(i.versions) == 0 {
391 return fmt.Errorf("no version")
392 }
393
394 for _, v := range i.versions {
395 if err := v.Validate(); err != nil {
396 return err
397 }
398
399 // check for always increasing lamport time
400 // check that a new version didn't drop a clock
401 for name, previous := range lastTimes {
402 if now, ok := v.times[name]; ok {
403 if now < previous {
404 return fmt.Errorf("non-chronological lamport clock %s (%d --> %d)", name, previous, now)
405 }
406 } else {
407 return fmt.Errorf("version has less lamport clocks than before (missing %s)", name)
408 }
409 }
410
411 for name, now := range v.times {
412 lastTimes[name] = now
413 }
414 }
415
416 return nil
417}
418
419func (i *Identity) lastVersion() *version {
420 if len(i.versions) <= 0 {
421 panic("no version at all")
422 }
423
424 return i.versions[len(i.versions)-1]
425}
426
427// Id return the Identity identifier
428func (i *Identity) Id() bootstrap.Id {
429 // id is the id of the first version
430 return i.versions[0].Id()
431}
432
433// Name return the last version of the name
434func (i *Identity) Name() string {
435 return i.lastVersion().name
436}
437
438// DisplayName return a non-empty string to display, representing the
439// identity, based on the non-empty values.
440func (i *Identity) DisplayName() string {
441 switch {
442 case i.Name() == "" && i.Login() != "":
443 return i.Login()
444 case i.Name() != "" && i.Login() == "":
445 return i.Name()
446 case i.Name() != "" && i.Login() != "":
447 return fmt.Sprintf("%s (%s)", i.Name(), i.Login())
448 }
449
450 panic("invalid person data")
451}
452
453// Email return the last version of the email
454func (i *Identity) Email() string {
455 return i.lastVersion().email
456}
457
458// Login return the last version of the login
459func (i *Identity) Login() string {
460 return i.lastVersion().login
461}
462
463// AvatarUrl return the last version of the Avatar URL
464func (i *Identity) AvatarUrl() string {
465 return i.lastVersion().avatarURL
466}
467
468// Keys return the last version of the valid keys
469func (i *Identity) Keys() []*Key {
470 return i.lastVersion().keys
471}
472
473// SigningKey return the key that should be used to sign new messages. If no key is available, return nil.
474func (i *Identity) SigningKey(repo repository.RepoKeyring) (*Key, error) {
475 keys := i.Keys()
476 for _, key := range keys {
477 err := key.ensurePrivateKey(repo)
478 if err == errNoPrivateKey {
479 continue
480 }
481 if err != nil {
482 return nil, err
483 }
484 return key, nil
485 }
486 return nil, nil
487}
488
489// ValidKeysAtTime return the set of keys valid at a given lamport time
490func (i *Identity) ValidKeysAtTime(clockName string, time lamport.Time) []*Key {
491 var result []*Key
492
493 var lastTime lamport.Time
494 for _, v := range i.versions {
495 refTime, ok := v.times[clockName]
496 if !ok {
497 refTime = lastTime
498 }
499 lastTime = refTime
500
501 if refTime > time {
502 return result
503 }
504
505 result = v.keys
506 }
507
508 return result
509}
510
511// LastModification return the timestamp at which the last version of the identity became valid.
512func (i *Identity) LastModification() timestamp.Timestamp {
513 return timestamp.Timestamp(i.lastVersion().unixTime)
514}
515
516// LastModificationLamports return the lamport times at which the last version of the identity became valid.
517func (i *Identity) LastModificationLamports() map[string]lamport.Time {
518 return i.lastVersion().times
519}
520
521// IsProtected return true if the chain of git commits started to be signed.
522// If that's the case, only signed commit with a valid key for this identity can be added.
523func (i *Identity) IsProtected() bool {
524 // Todo
525 return false
526}
527
528// SetMetadata store arbitrary metadata along the last not-commit version.
529// If the version has been commit to git already, a new identical version is added and will need to be
530// commit.
531func (i *Identity) SetMetadata(key string, value string) {
532 // once commit, data is immutable so we create a new version
533 if i.lastVersion().commitHash != "" {
534 i.versions = append(i.versions, i.lastVersion().Clone())
535 }
536 // if Id() has been called, we can't change the first version anymore, so we create a new version
537 if len(i.versions) == 1 && i.versions[0].id != bootstrap.UnsetId && i.versions[0].id != "" {
538 i.versions = append(i.versions, i.lastVersion().Clone())
539 }
540
541 i.lastVersion().SetMetadata(key, value)
542}
543
544// ImmutableMetadata return all metadata for this Identity, accumulated from each version.
545// If multiple value are found, the first defined takes precedence.
546func (i *Identity) ImmutableMetadata() map[string]string {
547 metadata := make(map[string]string)
548
549 for _, version := range i.versions {
550 for key, value := range version.metadata {
551 if _, has := metadata[key]; !has {
552 metadata[key] = value
553 }
554 }
555 }
556
557 return metadata
558}
559
560// MutableMetadata return all metadata for this Identity, accumulated from each version.
561// If multiple value are found, the last defined takes precedence.
562func (i *Identity) MutableMetadata() map[string]string {
563 metadata := make(map[string]string)
564
565 for _, version := range i.versions {
566 for key, value := range version.metadata {
567 metadata[key] = value
568 }
569 }
570
571 return metadata
572}