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