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