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