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\" or \"git bug user adopt\"")
 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	modified := false
395	for j, otherVersion := range other.versions {
396		// if there is more version in other, take them
397		if len(i.versions) == j {
398			i.versions = append(i.versions, otherVersion)
399			i.lastCommit = otherVersion.commitHash
400			modified = true
401		}
402
403		// we have a non fast-forward merge.
404		// as explained in the doc above, refusing to merge
405		if i.versions[j].commitHash != otherVersion.commitHash {
406			return false, ErrNonFastForwardMerge
407		}
408	}
409
410	if modified {
411		err := repo.UpdateRef(identityRefPattern+i.id, i.lastCommit)
412		if err != nil {
413			return false, err
414		}
415	}
416
417	return false, nil
418}
419
420// Validate check if the Identity data is valid
421func (i *Identity) Validate() error {
422	lastTime := lamport.Time(0)
423
424	if len(i.versions) == 0 {
425		return fmt.Errorf("no version")
426	}
427
428	for _, v := range i.versions {
429		if err := v.Validate(); err != nil {
430			return err
431		}
432
433		if v.commitHash != "" && v.time < lastTime {
434			return fmt.Errorf("non-chronological version (%d --> %d)", lastTime, v.time)
435		}
436
437		lastTime = v.time
438	}
439
440	// The identity ID should be the hash of the first commit
441	if i.versions[0].commitHash != "" && string(i.versions[0].commitHash) != i.id {
442		return fmt.Errorf("identity id should be the first commit hash")
443	}
444
445	return nil
446}
447
448func (i *Identity) lastVersion() *Version {
449	if len(i.versions) <= 0 {
450		panic("no version at all")
451	}
452
453	return i.versions[len(i.versions)-1]
454}
455
456// Id return the Identity identifier
457func (i *Identity) Id() string {
458	if i.id == "" {
459		// simply panic as it would be a coding error
460		// (using an id of an identity not stored yet)
461		panic("no id yet")
462	}
463	return i.id
464}
465
466// HumanId return the Identity identifier truncated for human consumption
467func (i *Identity) HumanId() string {
468	return FormatHumanID(i.Id())
469}
470
471func FormatHumanID(id string) string {
472	format := fmt.Sprintf("%%.%ds", humanIdLength)
473	return fmt.Sprintf(format, id)
474}
475
476// Name return the last version of the name
477func (i *Identity) Name() string {
478	return i.lastVersion().name
479}
480
481// Email return the last version of the email
482func (i *Identity) Email() string {
483	return i.lastVersion().email
484}
485
486// Login return the last version of the login
487func (i *Identity) Login() string {
488	return i.lastVersion().login
489}
490
491// AvatarUrl return the last version of the Avatar URL
492func (i *Identity) AvatarUrl() string {
493	return i.lastVersion().avatarURL
494}
495
496// Keys return the last version of the valid keys
497func (i *Identity) Keys() []Key {
498	return i.lastVersion().keys
499}
500
501// IsProtected return true if the chain of git commits started to be signed.
502// If that's the case, only signed commit with a valid key for this identity can be added.
503func (i *Identity) IsProtected() bool {
504	// Todo
505	return false
506}
507
508// ValidKeysAtTime return the set of keys valid at a given lamport time
509func (i *Identity) ValidKeysAtTime(time lamport.Time) []Key {
510	var result []Key
511
512	for _, v := range i.versions {
513		if v.time > time {
514			return result
515		}
516
517		result = v.keys
518	}
519
520	return result
521}
522
523// DisplayName return a non-empty string to display, representing the
524// identity, based on the non-empty values.
525func (i *Identity) DisplayName() string {
526	switch {
527	case i.Name() == "" && i.Login() != "":
528		return i.Login()
529	case i.Name() != "" && i.Login() == "":
530		return i.Name()
531	case i.Name() != "" && i.Login() != "":
532		return fmt.Sprintf("%s (%s)", i.Name(), i.Login())
533	}
534
535	panic("invalid person data")
536}
537
538// SetMetadata store arbitrary metadata along the last defined Version.
539// If the Version has been commit to git already, it won't be overwritten.
540func (i *Identity) SetMetadata(key string, value string) {
541	i.lastVersion().SetMetadata(key, value)
542}
543
544// ImmutableMetadata return all metadata for this Identity, accumulated from each Version.
545// If multiple value are found, the first defined takes precedence.
546func (i *Identity) ImmutableMetadata() map[string]string {
547	metadata := make(map[string]string)
548
549	for _, version := range i.versions {
550		for key, value := range version.metadata {
551			if _, has := metadata[key]; !has {
552				metadata[key] = value
553			}
554		}
555	}
556
557	return metadata
558}
559
560// MutableMetadata return all metadata for this Identity, accumulated from each Version.
561// If multiple value are found, the last defined takes precedence.
562func (i *Identity) MutableMetadata() map[string]string {
563	metadata := make(map[string]string)
564
565	for _, version := range i.versions {
566		for key, value := range version.metadata {
567			metadata[key] = value
568		}
569	}
570
571	return metadata
572}