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