identity.go

  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	"github.com/MichaelMure/git-bug/entity"
 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 _ entity.Interface = &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 entity.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 := entity.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, entity.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) ([]entity.Id, error) {
159	refs, err := repo.ListRefs(identityRefPattern)
160	if err != nil {
161		return nil, err
162	}
163
164	return entity.RefsToIds(refs), nil
165}
166
167// RemoveIdentity will remove a local identity from its entity.Id
168func RemoveIdentity(repo repository.ClockedRepo, id entity.Id) error {
169	var fullMatches []string
170
171	refs, err := repo.ListRefs(identityRefPattern + id.String())
172	if err != nil {
173		return err
174	}
175	if len(refs) > 1 {
176		return entity.NewErrMultipleMatch(Typename, entity.RefsToIds(refs))
177	}
178	if len(refs) == 1 {
179		// we have the identity locally
180		fullMatches = append(fullMatches, refs[0])
181	}
182
183	remotes, err := repo.GetRemotes()
184	if err != nil {
185		return err
186	}
187
188	for remote := range remotes {
189		remotePrefix := fmt.Sprintf(identityRemoteRefPattern+id.String(), remote)
190		remoteRefs, err := repo.ListRefs(remotePrefix)
191		if err != nil {
192			return err
193		}
194		if len(remoteRefs) > 1 {
195			return entity.NewErrMultipleMatch(Typename, entity.RefsToIds(refs))
196		}
197		if len(remoteRefs) == 1 {
198			// found the identity in a remote
199			fullMatches = append(fullMatches, remoteRefs[0])
200		}
201	}
202
203	if len(fullMatches) == 0 {
204		return entity.NewErrNotFound(Typename)
205	}
206
207	for _, ref := range fullMatches {
208		err = repo.RemoveRef(ref)
209		if err != nil {
210			return err
211		}
212	}
213
214	return nil
215}
216
217// ReadAllLocal read and parse all local Identity
218func ReadAllLocal(repo repository.ClockedRepo) <-chan entity.StreamedEntity[*Identity] {
219	return readAll(repo, identityRefPattern)
220}
221
222// ReadAllRemote read and parse all remote Identity for a given remote
223func ReadAllRemote(repo repository.ClockedRepo, remote string) <-chan entity.StreamedEntity[*Identity] {
224	refPrefix := fmt.Sprintf(identityRemoteRefPattern, remote)
225	return readAll(repo, refPrefix)
226}
227
228// readAll read and parse all available bug with a given ref prefix
229func readAll(repo repository.ClockedRepo, refPrefix string) <-chan entity.StreamedEntity[*Identity] {
230	out := make(chan entity.StreamedEntity[*Identity])
231
232	go func() {
233		defer close(out)
234
235		refs, err := repo.ListRefs(refPrefix)
236		if err != nil {
237			out <- entity.StreamedEntity[*Identity]{Err: err}
238			return
239		}
240
241		total := int64(len(refs))
242		current := int64(1)
243
244		for _, ref := range refs {
245			i, err := read(repo, ref)
246
247			if err != nil {
248				out <- entity.StreamedEntity[*Identity]{Err: err}
249				return
250			}
251
252			out <- entity.StreamedEntity[*Identity]{
253				Entity:        i,
254				CurrentEntity: current,
255				TotalEntities: total,
256			}
257			current++
258		}
259	}()
260
261	return out
262}
263
264type Mutator struct {
265	Name      string
266	Login     string
267	Email     string
268	AvatarUrl string
269	Keys      []*Key
270}
271
272// Mutate allow to create a new version of the Identity in one go
273func (i *Identity) Mutate(repo repository.RepoClock, f func(orig *Mutator)) error {
274	copyKeys := func(keys []*Key) []*Key {
275		result := make([]*Key, len(keys))
276		for i, key := range keys {
277			result[i] = key.Clone()
278		}
279		return result
280	}
281
282	orig := Mutator{
283		Name:      i.Name(),
284		Email:     i.Email(),
285		Login:     i.Login(),
286		AvatarUrl: i.AvatarUrl(),
287		Keys:      copyKeys(i.Keys()),
288	}
289	mutated := orig
290	mutated.Keys = copyKeys(orig.Keys)
291
292	f(&mutated)
293
294	if reflect.DeepEqual(orig, mutated) {
295		return nil
296	}
297
298	v, err := newVersion(repo,
299		mutated.Name,
300		mutated.Email,
301		mutated.Login,
302		mutated.AvatarUrl,
303		mutated.Keys,
304	)
305	if err != nil {
306		return err
307	}
308
309	i.versions = append(i.versions, v)
310	return nil
311}
312
313// Commit write the identity into the Repository. In particular, this ensures that
314// the Id is properly set.
315func (i *Identity) Commit(repo repository.ClockedRepo) error {
316	if !i.NeedCommit() {
317		return fmt.Errorf("can't commit an identity with no pending version")
318	}
319
320	if err := i.Validate(); err != nil {
321		return errors.Wrap(err, "can't commit an identity with invalid data")
322	}
323
324	var lastCommit repository.Hash
325	for _, v := range i.versions {
326		if v.commitHash != "" {
327			lastCommit = v.commitHash
328			// ignore already commit versions
329			continue
330		}
331
332		blobHash, err := v.Write(repo)
333		if err != nil {
334			return err
335		}
336
337		// Make a git tree referencing the blob
338		tree := []repository.TreeEntry{
339			{ObjectType: repository.Blob, Hash: blobHash, Name: versionEntryName},
340		}
341
342		treeHash, err := repo.StoreTree(tree)
343		if err != nil {
344			return err
345		}
346
347		var commitHash repository.Hash
348		if lastCommit != "" {
349			commitHash, err = repo.StoreCommit(treeHash, lastCommit)
350		} else {
351			commitHash, err = repo.StoreCommit(treeHash)
352		}
353		if err != nil {
354			return err
355		}
356
357		lastCommit = commitHash
358		v.commitHash = commitHash
359	}
360
361	ref := fmt.Sprintf("%s%s", identityRefPattern, i.Id().String())
362	return repo.UpdateRef(ref, lastCommit)
363}
364
365func (i *Identity) CommitAsNeeded(repo repository.ClockedRepo) error {
366	if !i.NeedCommit() {
367		return nil
368	}
369	return i.Commit(repo)
370}
371
372func (i *Identity) NeedCommit() bool {
373	for _, v := range i.versions {
374		if v.commitHash == "" {
375			return true
376		}
377	}
378
379	return false
380}
381
382// Merge will merge a different version of the same Identity
383//
384// To make sure that an Identity history can't be altered, a strict fast-forward
385// only policy is applied here. As an Identity should be tied to a single user, this
386// should work in practice, but it does leave a possibility that a user would edit his
387// Identity from two different repo concurrently and push the changes in a non-centralized
388// network of repositories. In this case, it would result in some repo accepting one
389// version and some other accepting another, preventing the network in general to converge
390// to the same result. This would create a sort of partition of the network, and manual
391// cleaning would be required.
392//
393// An alternative approach would be to have a determinist rebase:
394//   - any commits present in both local and remote version would be kept, never changed.
395//   - newer commits would be merged in a linear chain of commits, ordered based on the
396//     Lamport time
397//
398// However, this approach leave the possibility, in the case of a compromised crypto keys,
399// of forging a new version with a bogus Lamport time to be inserted before a legit version,
400// invalidating the correct version and hijacking the Identity. There would only be a short
401// period of time when this would be possible (before the network converge) but I'm not
402// confident enough to implement that. I choose the strict fast-forward only approach,
403// despite its potential problem with two different version as mentioned above.
404func (i *Identity) Merge(repo repository.Repo, other *Identity) (bool, error) {
405	if i.Id() != other.Id() {
406		return false, errors.New("merging unrelated identities is not supported")
407	}
408
409	modified := false
410	var lastCommit repository.Hash
411	for j, otherVersion := range other.versions {
412		// if there is more version in other, take them
413		if len(i.versions) == j {
414			i.versions = append(i.versions, otherVersion)
415			lastCommit = otherVersion.commitHash
416			modified = true
417		}
418
419		// we have a non fast-forward merge.
420		// as explained in the doc above, refusing to merge
421		if i.versions[j].commitHash != otherVersion.commitHash {
422			return false, ErrNonFastForwardMerge
423		}
424	}
425
426	if modified {
427		err := repo.UpdateRef(identityRefPattern+i.Id().String(), lastCommit)
428		if err != nil {
429			return false, err
430		}
431	}
432
433	return false, nil
434}
435
436// Validate check if the Identity data is valid
437func (i *Identity) Validate() error {
438	lastTimes := make(map[string]lamport.Time)
439
440	if len(i.versions) == 0 {
441		return fmt.Errorf("no version")
442	}
443
444	for _, v := range i.versions {
445		if err := v.Validate(); err != nil {
446			return err
447		}
448
449		// check for always increasing lamport time
450		// check that a new version didn't drop a clock
451		for name, previous := range lastTimes {
452			if now, ok := v.times[name]; ok {
453				if now < previous {
454					return fmt.Errorf("non-chronological lamport clock %s (%d --> %d)", name, previous, now)
455				}
456			} else {
457				return fmt.Errorf("version has less lamport clocks than before (missing %s)", name)
458			}
459		}
460
461		for name, now := range v.times {
462			lastTimes[name] = now
463		}
464	}
465
466	return nil
467}
468
469func (i *Identity) lastVersion() *version {
470	if len(i.versions) <= 0 {
471		panic("no version at all")
472	}
473
474	return i.versions[len(i.versions)-1]
475}
476
477// Id return the Identity identifier
478func (i *Identity) Id() entity.Id {
479	// id is the id of the first version
480	return i.versions[0].Id()
481}
482
483// Name return the last version of the name
484func (i *Identity) Name() string {
485	return i.lastVersion().name
486}
487
488// DisplayName return a non-empty string to display, representing the
489// identity, based on the non-empty values.
490func (i *Identity) DisplayName() string {
491	switch {
492	case i.Name() == "" && i.Login() != "":
493		return i.Login()
494	case i.Name() != "" && i.Login() == "":
495		return i.Name()
496	case i.Name() != "" && i.Login() != "":
497		return fmt.Sprintf("%s (%s)", i.Name(), i.Login())
498	}
499
500	panic("invalid person data")
501}
502
503// Email return the last version of the email
504func (i *Identity) Email() string {
505	return i.lastVersion().email
506}
507
508// Login return the last version of the login
509func (i *Identity) Login() string {
510	return i.lastVersion().login
511}
512
513// AvatarUrl return the last version of the Avatar URL
514func (i *Identity) AvatarUrl() string {
515	return i.lastVersion().avatarURL
516}
517
518// Keys return the last version of the valid keys
519func (i *Identity) Keys() []*Key {
520	return i.lastVersion().keys
521}
522
523// SigningKey return the key that should be used to sign new messages. If no key is available, return nil.
524func (i *Identity) SigningKey(repo repository.RepoKeyring) (*Key, error) {
525	keys := i.Keys()
526	for _, key := range keys {
527		err := key.ensurePrivateKey(repo)
528		if err == errNoPrivateKey {
529			continue
530		}
531		if err != nil {
532			return nil, err
533		}
534		return key, nil
535	}
536	return nil, nil
537}
538
539// ValidKeysAtTime return the set of keys valid at a given lamport time
540func (i *Identity) ValidKeysAtTime(clockName string, time lamport.Time) []*Key {
541	var result []*Key
542
543	var lastTime lamport.Time
544	for _, v := range i.versions {
545		refTime, ok := v.times[clockName]
546		if !ok {
547			refTime = lastTime
548		}
549		lastTime = refTime
550
551		if refTime > time {
552			return result
553		}
554
555		result = v.keys
556	}
557
558	return result
559}
560
561// LastModification return the timestamp at which the last version of the identity became valid.
562func (i *Identity) LastModification() timestamp.Timestamp {
563	return timestamp.Timestamp(i.lastVersion().unixTime)
564}
565
566// LastModificationLamports return the lamport times at which the last version of the identity became valid.
567func (i *Identity) LastModificationLamports() map[string]lamport.Time {
568	return i.lastVersion().times
569}
570
571// IsProtected return true if the chain of git commits started to be signed.
572// If that's the case, only signed commit with a valid key for this identity can be added.
573func (i *Identity) IsProtected() bool {
574	// Todo
575	return false
576}
577
578// SetMetadata store arbitrary metadata along the last not-commit version.
579// If the version has been commit to git already, a new identical version is added and will need to be
580// commit.
581func (i *Identity) SetMetadata(key string, value string) {
582	// once commit, data is immutable so we create a new version
583	if i.lastVersion().commitHash != "" {
584		i.versions = append(i.versions, i.lastVersion().Clone())
585	}
586	// if Id() has been called, we can't change the first version anymore, so we create a new version
587	if len(i.versions) == 1 && i.versions[0].id != entity.UnsetId && i.versions[0].id != "" {
588		i.versions = append(i.versions, i.lastVersion().Clone())
589	}
590
591	i.lastVersion().SetMetadata(key, value)
592}
593
594// ImmutableMetadata return all metadata for this Identity, accumulated from each version.
595// If multiple value are found, the first defined takes precedence.
596func (i *Identity) ImmutableMetadata() map[string]string {
597	metadata := make(map[string]string)
598
599	for _, version := range i.versions {
600		for key, value := range version.metadata {
601			if _, has := metadata[key]; !has {
602				metadata[key] = value
603			}
604		}
605	}
606
607	return metadata
608}
609
610// MutableMetadata return all metadata for this Identity, accumulated from each version.
611// If multiple value are found, the last defined takes precedence.
612func (i *Identity) MutableMetadata() map[string]string {
613	metadata := make(map[string]string)
614
615	for _, version := range i.versions {
616		for key, value := range version.metadata {
617			metadata[key] = value
618		}
619	}
620
621	return metadata
622}