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 // TODO: instead of this hardcoded clock for bugs only, this need to be
336 // a vector of edit clock, one for each entity (bug, PR, config ..)
337 bugEditClock, err := repo.GetOrCreateClock("bug-edit")
338 if err != nil {
339 return err
340 }
341
342 v.time = bugEditClock.Time()
343 v.unixTime = time.Now().Unix()
344
345 blobHash, err := v.Write(repo)
346 if err != nil {
347 return err
348 }
349
350 // Make a git tree referencing the blob
351 tree := []repository.TreeEntry{
352 {ObjectType: repository.Blob, Hash: blobHash, Name: versionEntryName},
353 }
354
355 treeHash, err := repo.StoreTree(tree)
356 if err != nil {
357 return err
358 }
359
360 var commitHash git.Hash
361 if i.lastCommit != "" {
362 commitHash, err = repo.StoreCommitWithParent(treeHash, i.lastCommit)
363 } else {
364 commitHash, err = repo.StoreCommit(treeHash)
365 }
366
367 if err != nil {
368 return err
369 }
370
371 i.lastCommit = commitHash
372 v.commitHash = commitHash
373
374 // if it was the first commit, use the commit hash as the Identity id
375 if i.id == "" || i.id == entity.UnsetId {
376 i.id = entity.Id(commitHash)
377 }
378 }
379
380 if i.id == "" {
381 panic("identity with no id")
382 }
383
384 ref := fmt.Sprintf("%s%s", identityRefPattern, i.id)
385 err := repo.UpdateRef(ref, i.lastCommit)
386
387 if err != nil {
388 return err
389 }
390
391 return nil
392}
393
394func (i *Identity) CommitAsNeeded(repo repository.ClockedRepo) error {
395 if !i.NeedCommit() {
396 return nil
397 }
398 return i.Commit(repo)
399}
400
401func (i *Identity) NeedCommit() bool {
402 for _, v := range i.versions {
403 if v.commitHash == "" {
404 return true
405 }
406 }
407
408 return false
409}
410
411// Merge will merge a different version of the same Identity
412//
413// To make sure that an Identity history can't be altered, a strict fast-forward
414// only policy is applied here. As an Identity should be tied to a single user, this
415// should work in practice but it does leave a possibility that a user would edit his
416// Identity from two different repo concurrently and push the changes in a non-centralized
417// network of repositories. In this case, it would result in some of the repo accepting one
418// version and some other accepting another, preventing the network in general to converge
419// to the same result. This would create a sort of partition of the network, and manual
420// cleaning would be required.
421//
422// An alternative approach would be to have a determinist rebase:
423// - any commits present in both local and remote version would be kept, never changed.
424// - newer commits would be merged in a linear chain of commits, ordered based on the
425// Lamport time
426//
427// However, this approach leave the possibility, in the case of a compromised crypto keys,
428// of forging a new version with a bogus Lamport time to be inserted before a legit version,
429// invalidating the correct version and hijacking the Identity. There would only be a short
430// period of time where this would be possible (before the network converge) but I'm not
431// confident enough to implement that. I choose the strict fast-forward only approach,
432// despite it's potential problem with two different version as mentioned above.
433func (i *Identity) Merge(repo repository.Repo, other *Identity) (bool, error) {
434 if i.id != other.id {
435 return false, errors.New("merging unrelated identities is not supported")
436 }
437
438 if i.lastCommit == "" || other.lastCommit == "" {
439 return false, errors.New("can't merge identities that has never been stored")
440 }
441
442 modified := false
443 for j, otherVersion := range other.versions {
444 // if there is more version in other, take them
445 if len(i.versions) == j {
446 i.versions = append(i.versions, otherVersion)
447 i.lastCommit = otherVersion.commitHash
448 modified = true
449 }
450
451 // we have a non fast-forward merge.
452 // as explained in the doc above, refusing to merge
453 if i.versions[j].commitHash != otherVersion.commitHash {
454 return false, ErrNonFastForwardMerge
455 }
456 }
457
458 if modified {
459 err := repo.UpdateRef(identityRefPattern+i.id.String(), i.lastCommit)
460 if err != nil {
461 return false, err
462 }
463 }
464
465 return false, nil
466}
467
468// Validate check if the Identity data is valid
469func (i *Identity) Validate() error {
470 lastTime := lamport.Time(0)
471
472 if len(i.versions) == 0 {
473 return fmt.Errorf("no version")
474 }
475
476 for _, v := range i.versions {
477 if err := v.Validate(); err != nil {
478 return err
479 }
480
481 if v.commitHash != "" && v.time < lastTime {
482 return fmt.Errorf("non-chronological version (%d --> %d)", lastTime, v.time)
483 }
484
485 lastTime = v.time
486 }
487
488 // The identity Id should be the hash of the first commit
489 if i.versions[0].commitHash != "" && string(i.versions[0].commitHash) != i.id.String() {
490 return fmt.Errorf("identity id should be the first commit hash")
491 }
492
493 return nil
494}
495
496func (i *Identity) lastVersion() *Version {
497 if len(i.versions) <= 0 {
498 panic("no version at all")
499 }
500
501 return i.versions[len(i.versions)-1]
502}
503
504// Id return the Identity identifier
505func (i *Identity) Id() entity.Id {
506 if i.id == "" {
507 // simply panic as it would be a coding error
508 // (using an id of an identity not stored yet)
509 panic("no id yet")
510 }
511 return i.id
512}
513
514// Name return the last version of the name
515func (i *Identity) Name() string {
516 return i.lastVersion().name
517}
518
519// Email return the last version of the email
520func (i *Identity) Email() string {
521 return i.lastVersion().email
522}
523
524// Login return the last version of the login
525func (i *Identity) Login() string {
526 return i.lastVersion().login
527}
528
529// AvatarUrl return the last version of the Avatar URL
530func (i *Identity) AvatarUrl() string {
531 return i.lastVersion().avatarURL
532}
533
534// Keys return the last version of the valid keys
535func (i *Identity) Keys() []*Key {
536 return i.lastVersion().keys
537}
538
539// ValidKeysAtTime return the set of keys valid at a given lamport time
540func (i *Identity) ValidKeysAtTime(time lamport.Time) []*Key {
541 var result []*Key
542
543 for _, v := range i.versions {
544 if v.time > time {
545 return result
546 }
547
548 result = v.keys
549 }
550
551 return result
552}
553
554// DisplayName return a non-empty string to display, representing the
555// identity, based on the non-empty values.
556func (i *Identity) DisplayName() string {
557 switch {
558 case i.Name() == "" && i.Login() != "":
559 return i.Login()
560 case i.Name() != "" && i.Login() == "":
561 return i.Name()
562 case i.Name() != "" && i.Login() != "":
563 return fmt.Sprintf("%s (%s)", i.Name(), i.Login())
564 }
565
566 panic("invalid person data")
567}
568
569// IsProtected return true if the chain of git commits started to be signed.
570// If that's the case, only signed commit with a valid key for this identity can be added.
571func (i *Identity) IsProtected() bool {
572 // Todo
573 return false
574}
575
576// LastModificationLamportTime return the Lamport time at which the last version of the identity became valid.
577func (i *Identity) LastModificationLamport() lamport.Time {
578 return i.lastVersion().time
579}
580
581// LastModification return the timestamp at which the last version of the identity became valid.
582func (i *Identity) LastModification() timestamp.Timestamp {
583 return timestamp.Timestamp(i.lastVersion().unixTime)
584}
585
586// SetMetadata store arbitrary metadata along the last not-commit Version.
587// If the Version has been commit to git already, a new identical version is added and will need to be
588// commit.
589func (i *Identity) SetMetadata(key string, value string) {
590 if i.lastVersion().commitHash != "" {
591 i.versions = append(i.versions, i.lastVersion().Clone())
592 }
593 i.lastVersion().SetMetadata(key, value)
594}
595
596// ImmutableMetadata return all metadata for this Identity, accumulated from each Version.
597// If multiple value are found, the first defined takes precedence.
598func (i *Identity) ImmutableMetadata() map[string]string {
599 metadata := make(map[string]string)
600
601 for _, version := range i.versions {
602 for key, value := range version.metadata {
603 if _, has := metadata[key]; !has {
604 metadata[key] = value
605 }
606 }
607 }
608
609 return metadata
610}
611
612// MutableMetadata return all metadata for this Identity, accumulated from each Version.
613// If multiple value are found, the last defined takes precedence.
614func (i *Identity) MutableMetadata() map[string]string {
615 metadata := make(map[string]string)
616
617 for _, version := range i.versions {
618 for key, value := range version.metadata {
619 metadata[key] = value
620 }
621 }
622
623 return metadata
624}
625
626// addVersionForTest add a new version to the identity
627// Only for testing !
628func (i *Identity) addVersionForTest(version *Version) {
629 i.versions = append(i.versions, version)
630}