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	"strings"
  9
 10	"github.com/pkg/errors"
 11
 12	"github.com/MichaelMure/git-bug/entity"
 13	"github.com/MichaelMure/git-bug/repository"
 14	"github.com/MichaelMure/git-bug/util/lamport"
 15	"github.com/MichaelMure/git-bug/util/timestamp"
 16)
 17
 18const identityRefPattern = "refs/identities/"
 19const identityRemoteRefPattern = "refs/remotes/%s/identities/"
 20const versionEntryName = "version"
 21const identityConfigKey = "git-bug.identity"
 22
 23var ErrNonFastForwardMerge = errors.New("non fast-forward identity merge")
 24var ErrNoIdentitySet = errors.New("No identity is set.\n" +
 25	"To interact with bugs, an identity first needs to be created using " +
 26	"\"git bug user create\"")
 27var ErrMultipleIdentitiesSet = errors.New("multiple user identities set")
 28
 29func NewErrMultipleMatchIdentity(matching []entity.Id) *entity.ErrMultipleMatch {
 30	return entity.NewErrMultipleMatch("identity", matching)
 31}
 32
 33var _ Interface = &Identity{}
 34var _ entity.Interface = &Identity{}
 35
 36type Identity struct {
 37	// all the successive version of the identity
 38	versions []*version
 39}
 40
 41func NewIdentity(repo repository.RepoClock, name string, email string) (*Identity, error) {
 42	return NewIdentityFull(repo, name, email, "", "", nil)
 43}
 44
 45func NewIdentityFull(repo repository.RepoClock, name string, email string, login string, avatarUrl string, keys []*Key) (*Identity, error) {
 46	v, err := newVersion(repo, name, email, login, avatarUrl, keys)
 47	if err != nil {
 48		return nil, err
 49	}
 50	return &Identity{
 51		versions: []*version{v},
 52	}, nil
 53}
 54
 55// NewFromGitUser will query the repository for user detail and
 56// build the corresponding Identity
 57func NewFromGitUser(repo repository.ClockedRepo) (*Identity, error) {
 58	name, err := repo.GetUserName()
 59	if err != nil {
 60		return nil, err
 61	}
 62	if name == "" {
 63		return nil, errors.New("user name is not configured in git yet. Please use `git config --global user.name \"John Doe\"`")
 64	}
 65
 66	email, err := repo.GetUserEmail()
 67	if err != nil {
 68		return nil, err
 69	}
 70	if email == "" {
 71		return nil, errors.New("user name is not configured in git yet. Please use `git config --global user.email johndoe@example.com`")
 72	}
 73
 74	return NewIdentity(repo, name, email)
 75}
 76
 77// MarshalJSON will only serialize the id
 78func (i *Identity) MarshalJSON() ([]byte, error) {
 79	return json.Marshal(&IdentityStub{
 80		id: i.Id(),
 81	})
 82}
 83
 84// UnmarshalJSON will only read the id
 85// Users of this package are expected to run Load() to load
 86// the remaining data from the identities data in git.
 87func (i *Identity) UnmarshalJSON(data []byte) error {
 88	panic("identity should be loaded with identity.UnmarshalJSON")
 89}
 90
 91// ReadLocal load a local Identity from the identities data available in git
 92func ReadLocal(repo repository.Repo, id entity.Id) (*Identity, error) {
 93	ref := fmt.Sprintf("%s%s", identityRefPattern, id)
 94	return read(repo, ref)
 95}
 96
 97// ReadRemote load a remote Identity from the identities data available in git
 98func ReadRemote(repo repository.Repo, remote string, id string) (*Identity, error) {
 99	ref := fmt.Sprintf(identityRemoteRefPattern, remote) + id
100	return read(repo, ref)
101}
102
103// read will load and parse an identity from git
104func read(repo repository.Repo, ref string) (*Identity, error) {
105	refSplit := strings.Split(ref, "/")
106	id := entity.Id(refSplit[len(refSplit)-1])
107
108	if err := id.Validate(); err != nil {
109		return nil, errors.Wrap(err, "invalid ref")
110	}
111
112	hashes, err := repo.ListCommits(ref)
113	if err != nil {
114		return nil, ErrIdentityNotExist
115	}
116	if len(hashes) == 0 {
117		return nil, fmt.Errorf("empty identity")
118	}
119
120	i := &Identity{}
121
122	for _, hash := range hashes {
123		entries, err := repo.ReadTree(hash)
124		if err != nil {
125			return nil, errors.Wrap(err, "can't list git tree entries")
126		}
127		if len(entries) != 1 {
128			return nil, fmt.Errorf("invalid identity data at hash %s", hash)
129		}
130
131		entry := entries[0]
132		if entry.Name != versionEntryName {
133			return nil, fmt.Errorf("invalid identity data at hash %s", hash)
134		}
135
136		data, err := repo.ReadData(entry.Hash)
137		if err != nil {
138			return nil, errors.Wrap(err, "failed to read git blob data")
139		}
140
141		var version version
142		err = json.Unmarshal(data, &version)
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
150		i.versions = append(i.versions, &version)
151	}
152
153	if id != i.versions[0].Id() {
154		return nil, fmt.Errorf("identity ID doesn't math the first version ID")
155	}
156
157	return i, nil
158}
159
160// ListLocalIds list all the available local identity ids
161func ListLocalIds(repo repository.Repo) ([]entity.Id, error) {
162	refs, err := repo.ListRefs(identityRefPattern)
163	if err != nil {
164		return nil, err
165	}
166
167	return entity.RefsToIds(refs), nil
168}
169
170// RemoveIdentity will remove a local identity from its entity.Id
171func RemoveIdentity(repo repository.ClockedRepo, id entity.Id) error {
172	var fullMatches []string
173
174	refs, err := repo.ListRefs(identityRefPattern + id.String())
175	if err != nil {
176		return err
177	}
178	if len(refs) > 1 {
179		return NewErrMultipleMatchIdentity(entity.RefsToIds(refs))
180	}
181	if len(refs) == 1 {
182		// we have the identity locally
183		fullMatches = append(fullMatches, refs[0])
184	}
185
186	remotes, err := repo.GetRemotes()
187	if err != nil {
188		return err
189	}
190
191	for remote := range remotes {
192		remotePrefix := fmt.Sprintf(identityRemoteRefPattern+id.String(), remote)
193		remoteRefs, err := repo.ListRefs(remotePrefix)
194		if err != nil {
195			return err
196		}
197		if len(remoteRefs) > 1 {
198			return NewErrMultipleMatchIdentity(entity.RefsToIds(refs))
199		}
200		if len(remoteRefs) == 1 {
201			// found the identity in a remote
202			fullMatches = append(fullMatches, remoteRefs[0])
203		}
204	}
205
206	if len(fullMatches) == 0 {
207		return ErrIdentityNotExist
208	}
209
210	for _, ref := range fullMatches {
211		err = repo.RemoveRef(ref)
212		if err != nil {
213			return err
214		}
215	}
216
217	return nil
218}
219
220type StreamedIdentity struct {
221	Identity *Identity
222	Err      error
223}
224
225// ReadAllLocal read and parse all local Identity
226func ReadAllLocal(repo repository.ClockedRepo) <-chan StreamedIdentity {
227	return readAll(repo, identityRefPattern)
228}
229
230// ReadAllRemote read and parse all remote Identity for a given remote
231func ReadAllRemote(repo repository.ClockedRepo, remote string) <-chan StreamedIdentity {
232	refPrefix := fmt.Sprintf(identityRemoteRefPattern, remote)
233	return readAll(repo, refPrefix)
234}
235
236// readAll read and parse all available bug with a given ref prefix
237func readAll(repo repository.ClockedRepo, refPrefix string) <-chan StreamedIdentity {
238	out := make(chan StreamedIdentity)
239
240	go func() {
241		defer close(out)
242
243		refs, err := repo.ListRefs(refPrefix)
244		if err != nil {
245			out <- StreamedIdentity{Err: err}
246			return
247		}
248
249		for _, ref := range refs {
250			b, err := read(repo, ref)
251
252			if err != nil {
253				out <- StreamedIdentity{Err: err}
254				return
255			}
256
257			out <- StreamedIdentity{Identity: b}
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// Write the identity into the Repository. In particular, this ensure 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.StoreCommitWithParent(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 of the 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 where 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 it's 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// ValidKeysAtTime return the set of keys valid at a given lamport time
524func (i *Identity) ValidKeysAtTime(clockName string, time lamport.Time) []*Key {
525	var result []*Key
526
527	var lastTime lamport.Time
528	for _, v := range i.versions {
529		refTime, ok := v.times[clockName]
530		if !ok {
531			refTime = lastTime
532		}
533		lastTime = refTime
534
535		if refTime > time {
536			return result
537		}
538
539		result = v.keys
540	}
541
542	return result
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// LastModificationLamports return the lamport times at which the last version of the identity became valid.
551func (i *Identity) LastModificationLamports() map[string]lamport.Time {
552	return i.lastVersion().times
553}
554
555// IsProtected return true if the chain of git commits started to be signed.
556// If that's the case, only signed commit with a valid key for this identity can be added.
557func (i *Identity) IsProtected() bool {
558	// Todo
559	return false
560}
561
562// SetMetadata store arbitrary metadata along the last not-commit version.
563// If the version has been commit to git already, a new identical version is added and will need to be
564// commit.
565func (i *Identity) SetMetadata(key string, value string) {
566	// once commit, data is immutable so we create a new version
567	if i.lastVersion().commitHash != "" {
568		i.versions = append(i.versions, i.lastVersion().Clone())
569	}
570	// if Id() has been called, we can't change the first version anymore, so we create a new version
571	if len(i.versions) == 1 && i.versions[0].id != entity.UnsetId && i.versions[0].id != "" {
572		i.versions = append(i.versions, i.lastVersion().Clone())
573	}
574
575	i.lastVersion().SetMetadata(key, value)
576}
577
578// ImmutableMetadata return all metadata for this Identity, accumulated from each version.
579// If multiple value are found, the first defined takes precedence.
580func (i *Identity) ImmutableMetadata() map[string]string {
581	metadata := make(map[string]string)
582
583	for _, version := range i.versions {
584		for key, value := range version.metadata {
585			if _, has := metadata[key]; !has {
586				metadata[key] = value
587			}
588		}
589	}
590
591	return metadata
592}
593
594// MutableMetadata return all metadata for this Identity, accumulated from each version.
595// If multiple value are found, the last defined takes precedence.
596func (i *Identity) MutableMetadata() map[string]string {
597	metadata := make(map[string]string)
598
599	for _, version := range i.versions {
600		for key, value := range version.metadata {
601			metadata[key] = value
602		}
603	}
604
605	return metadata
606}