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