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