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 id, err := GetUserIdentityId(repo)
232 if err != nil {
233 return nil, err
234 }
235
236 i, err := ReadLocal(repo, id)
237 if err == ErrIdentityNotExist {
238 innerErr := repo.LocalConfig().RemoveAll(identityConfigKey)
239 if innerErr != nil {
240 _, _ = fmt.Fprintln(os.Stderr, errors.Wrap(innerErr, "can't clear user identity").Error())
241 }
242 return nil, err
243 }
244
245 return i, nil
246}
247
248func GetUserIdentityId(repo repository.Repo) (entity.Id, error) {
249 configs, err := repo.LocalConfig().ReadAll(identityConfigKey)
250 if err != nil {
251 return entity.UnsetId, err
252 }
253
254 if len(configs) == 0 {
255 return entity.UnsetId, ErrNoIdentitySet
256 }
257
258 if len(configs) > 1 {
259 return entity.UnsetId, ErrMultipleIdentitiesSet
260 }
261
262 var id entity.Id
263 for _, val := range configs {
264 id = entity.Id(val)
265 }
266
267 if err := id.Validate(); err != nil {
268 return entity.UnsetId, err
269 }
270
271 return id, nil
272}
273
274// IsUserIdentitySet say if the user has set his identity
275func IsUserIdentitySet(repo repository.Repo) (bool, error) {
276 configs, err := repo.LocalConfig().ReadAll(identityConfigKey)
277 if err != nil {
278 return false, err
279 }
280
281 return len(configs) == 1, nil
282}
283
284type Mutator struct {
285 Name string
286 Login string
287 Email string
288 AvatarUrl string
289 Keys []*Key
290}
291
292// Mutate allow to create a new version of the Identity in one go
293func (i *Identity) Mutate(f func(orig Mutator) Mutator) {
294 orig := Mutator{
295 Name: i.Name(),
296 Email: i.Email(),
297 Login: i.Login(),
298 AvatarUrl: i.AvatarUrl(),
299 Keys: i.Keys(),
300 }
301 mutated := f(orig)
302 if reflect.DeepEqual(orig, mutated) {
303 return
304 }
305 i.versions = append(i.versions, &Version{
306 name: mutated.Name,
307 email: mutated.Email,
308 login: mutated.Login,
309 avatarURL: mutated.AvatarUrl,
310 keys: mutated.Keys,
311 })
312}
313
314// Write the identity into the Repository. In particular, this ensure that
315// the Id is properly set.
316func (i *Identity) Commit(repo repository.ClockedRepo) error {
317 // Todo: check for mismatch between memory and commit data
318
319 if !i.NeedCommit() {
320 return fmt.Errorf("can't commit an identity with no pending version")
321 }
322
323 if err := i.Validate(); err != nil {
324 return errors.Wrap(err, "can't commit an identity with invalid data")
325 }
326
327 for _, v := range i.versions {
328 if v.commitHash != "" {
329 i.lastCommit = v.commitHash
330 // ignore already commit versions
331 continue
332 }
333
334 // get the times where new versions starts to be valid
335 v.time = repo.EditTime()
336 v.unixTime = time.Now().Unix()
337
338 blobHash, err := v.Write(repo)
339 if err != nil {
340 return err
341 }
342
343 // Make a git tree referencing the blob
344 tree := []repository.TreeEntry{
345 {ObjectType: repository.Blob, Hash: blobHash, Name: versionEntryName},
346 }
347
348 treeHash, err := repo.StoreTree(tree)
349 if err != nil {
350 return err
351 }
352
353 var commitHash git.Hash
354 if i.lastCommit != "" {
355 commitHash, err = repo.StoreCommitWithParent(treeHash, i.lastCommit)
356 } else {
357 commitHash, err = repo.StoreCommit(treeHash)
358 }
359
360 if err != nil {
361 return err
362 }
363
364 i.lastCommit = commitHash
365 v.commitHash = commitHash
366
367 // if it was the first commit, use the commit hash as the Identity id
368 if i.id == "" || i.id == entity.UnsetId {
369 i.id = entity.Id(commitHash)
370 }
371 }
372
373 if i.id == "" {
374 panic("identity with no id")
375 }
376
377 ref := fmt.Sprintf("%s%s", identityRefPattern, i.id)
378 err := repo.UpdateRef(ref, i.lastCommit)
379
380 if err != nil {
381 return err
382 }
383
384 return nil
385}
386
387func (i *Identity) CommitAsNeeded(repo repository.ClockedRepo) error {
388 if !i.NeedCommit() {
389 return nil
390 }
391 return i.Commit(repo)
392}
393
394func (i *Identity) NeedCommit() bool {
395 for _, v := range i.versions {
396 if v.commitHash == "" {
397 return true
398 }
399 }
400
401 return false
402}
403
404// Merge will merge a different version of the same Identity
405//
406// To make sure that an Identity history can't be altered, a strict fast-forward
407// only policy is applied here. As an Identity should be tied to a single user, this
408// should work in practice but it does leave a possibility that a user would edit his
409// Identity from two different repo concurrently and push the changes in a non-centralized
410// network of repositories. In this case, it would result in some of the repo accepting one
411// version and some other accepting another, preventing the network in general to converge
412// to the same result. This would create a sort of partition of the network, and manual
413// cleaning would be required.
414//
415// An alternative approach would be to have a determinist rebase:
416// - any commits present in both local and remote version would be kept, never changed.
417// - newer commits would be merged in a linear chain of commits, ordered based on the
418// Lamport time
419//
420// However, this approach leave the possibility, in the case of a compromised crypto keys,
421// of forging a new version with a bogus Lamport time to be inserted before a legit version,
422// invalidating the correct version and hijacking the Identity. There would only be a short
423// period of time where this would be possible (before the network converge) but I'm not
424// confident enough to implement that. I choose the strict fast-forward only approach,
425// despite it's potential problem with two different version as mentioned above.
426func (i *Identity) Merge(repo repository.Repo, other *Identity) (bool, error) {
427 if i.id != other.id {
428 return false, errors.New("merging unrelated identities is not supported")
429 }
430
431 if i.lastCommit == "" || other.lastCommit == "" {
432 return false, errors.New("can't merge identities that has never been stored")
433 }
434
435 modified := false
436 for j, otherVersion := range other.versions {
437 // if there is more version in other, take them
438 if len(i.versions) == j {
439 i.versions = append(i.versions, otherVersion)
440 i.lastCommit = otherVersion.commitHash
441 modified = true
442 }
443
444 // we have a non fast-forward merge.
445 // as explained in the doc above, refusing to merge
446 if i.versions[j].commitHash != otherVersion.commitHash {
447 return false, ErrNonFastForwardMerge
448 }
449 }
450
451 if modified {
452 err := repo.UpdateRef(identityRefPattern+i.id.String(), i.lastCommit)
453 if err != nil {
454 return false, err
455 }
456 }
457
458 return false, nil
459}
460
461// Validate check if the Identity data is valid
462func (i *Identity) Validate() error {
463 lastTime := lamport.Time(0)
464
465 if len(i.versions) == 0 {
466 return fmt.Errorf("no version")
467 }
468
469 for _, v := range i.versions {
470 if err := v.Validate(); err != nil {
471 return err
472 }
473
474 if v.commitHash != "" && v.time < lastTime {
475 return fmt.Errorf("non-chronological version (%d --> %d)", lastTime, v.time)
476 }
477
478 lastTime = v.time
479 }
480
481 // The identity Id should be the hash of the first commit
482 if i.versions[0].commitHash != "" && string(i.versions[0].commitHash) != i.id.String() {
483 return fmt.Errorf("identity id should be the first commit hash")
484 }
485
486 return nil
487}
488
489func (i *Identity) lastVersion() *Version {
490 if len(i.versions) <= 0 {
491 panic("no version at all")
492 }
493
494 return i.versions[len(i.versions)-1]
495}
496
497// Id return the Identity identifier
498func (i *Identity) Id() entity.Id {
499 if i.id == "" {
500 // simply panic as it would be a coding error
501 // (using an id of an identity not stored yet)
502 panic("no id yet")
503 }
504 return i.id
505}
506
507// Name return the last version of the name
508func (i *Identity) Name() string {
509 return i.lastVersion().name
510}
511
512// Email return the last version of the email
513func (i *Identity) Email() string {
514 return i.lastVersion().email
515}
516
517// Login return the last version of the login
518func (i *Identity) Login() string {
519 return i.lastVersion().login
520}
521
522// AvatarUrl return the last version of the Avatar URL
523func (i *Identity) AvatarUrl() string {
524 return i.lastVersion().avatarURL
525}
526
527// Keys return the last version of the valid keys
528func (i *Identity) Keys() []*Key {
529 return i.lastVersion().keys
530}
531
532// ValidKeysAtTime return the set of keys valid at a given lamport time
533func (i *Identity) ValidKeysAtTime(time lamport.Time) []*Key {
534 var result []*Key
535
536 for _, v := range i.versions {
537 if v.time > time {
538 return result
539 }
540
541 result = v.keys
542 }
543
544 return result
545}
546
547// DisplayName return a non-empty string to display, representing the
548// identity, based on the non-empty values.
549func (i *Identity) DisplayName() string {
550 switch {
551 case i.Name() == "" && i.Login() != "":
552 return i.Login()
553 case i.Name() != "" && i.Login() == "":
554 return i.Name()
555 case i.Name() != "" && i.Login() != "":
556 return fmt.Sprintf("%s (%s)", i.Name(), i.Login())
557 }
558
559 panic("invalid person data")
560}
561
562// IsProtected return true if the chain of git commits started to be signed.
563// If that's the case, only signed commit with a valid key for this identity can be added.
564func (i *Identity) IsProtected() bool {
565 // Todo
566 return false
567}
568
569// LastModificationLamportTime return the Lamport time at which the last version of the identity became valid.
570func (i *Identity) LastModificationLamport() lamport.Time {
571 return i.lastVersion().time
572}
573
574// LastModification return the timestamp at which the last version of the identity became valid.
575func (i *Identity) LastModification() timestamp.Timestamp {
576 return timestamp.Timestamp(i.lastVersion().unixTime)
577}
578
579// SetMetadata store arbitrary metadata along the last not-commit Version.
580// If the Version has been commit to git already, a new identical version is added and will need to be
581// commit.
582func (i *Identity) SetMetadata(key string, value string) {
583 if i.lastVersion().commitHash != "" {
584 i.versions = append(i.versions, i.lastVersion().Clone())
585 }
586 i.lastVersion().SetMetadata(key, value)
587}
588
589// ImmutableMetadata return all metadata for this Identity, accumulated from each Version.
590// If multiple value are found, the first defined takes precedence.
591func (i *Identity) ImmutableMetadata() map[string]string {
592 metadata := make(map[string]string)
593
594 for _, version := range i.versions {
595 for key, value := range version.metadata {
596 if _, has := metadata[key]; !has {
597 metadata[key] = value
598 }
599 }
600 }
601
602 return metadata
603}
604
605// MutableMetadata return all metadata for this Identity, accumulated from each Version.
606// If multiple value are found, the last defined takes precedence.
607func (i *Identity) MutableMetadata() map[string]string {
608 metadata := make(map[string]string)
609
610 for _, version := range i.versions {
611 for key, value := range version.metadata {
612 metadata[key] = value
613 }
614 }
615
616 return metadata
617}
618
619// addVersionForTest add a new version to the identity
620// Only for testing !
621func (i *Identity) addVersionForTest(version *Version) {
622 i.versions = append(i.versions, version)
623}