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