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