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