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