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