1package identity
  2
  3import (
  4	"crypto/rand"
  5	"encoding/json"
  6	"fmt"
  7	"strings"
  8
  9	"github.com/MichaelMure/git-bug/repository"
 10	"github.com/MichaelMure/git-bug/util/git"
 11	"github.com/MichaelMure/git-bug/util/lamport"
 12	"github.com/MichaelMure/git-bug/util/text"
 13	"github.com/pkg/errors"
 14)
 15
 16const formatVersion = 1
 17
 18// Version is a complete set of information about an Identity at a point in time.
 19type Version struct {
 20	// The lamport time at which this version become effective
 21	// The reference time is the bug edition lamport clock
 22	// It must be the first field in this struct due to https://github.com/golang/go/issues/599
 23	time     lamport.Time
 24	unixTime int64
 25
 26	name      string
 27	email     string // as defined in git or from a bridge when importing the identity
 28	login     string // from a bridge when importing the identity
 29	avatarURL string
 30
 31	// The set of keys valid at that time, from this version onward, until they get removed
 32	// in a new version. This allow to have multiple key for the same identity (e.g. one per
 33	// device) as well as revoke key.
 34	keys []*Key
 35
 36	// This optional array is here to ensure a better randomness of the identity id to avoid collisions.
 37	// It has no functional purpose and should be ignored.
 38	// It is advised to fill this array if there is not enough entropy, e.g. if there is no keys.
 39	nonce []byte
 40
 41	// A set of arbitrary key/value to store metadata about a version or about an Identity in general.
 42	metadata map[string]string
 43
 44	// Not serialized
 45	commitHash git.Hash
 46}
 47
 48type VersionJSON struct {
 49	// Additional field to version the data
 50	FormatVersion uint `json:"version"`
 51
 52	Time      lamport.Time      `json:"time"`
 53	UnixTime  int64             `json:"unix_time"`
 54	Name      string            `json:"name,omitempty"`
 55	Email     string            `json:"email,omitempty"`
 56	Login     string            `json:"login,omitempty"`
 57	AvatarUrl string            `json:"avatar_url,omitempty"`
 58	Keys      []*Key            `json:"pub_keys,omitempty"`
 59	Nonce     []byte            `json:"nonce,omitempty"`
 60	Metadata  map[string]string `json:"metadata,omitempty"`
 61}
 62
 63// Make a deep copy
 64func (v *Version) Clone() *Version {
 65	clone := &Version{
 66		name:      v.name,
 67		email:     v.email,
 68		avatarURL: v.avatarURL,
 69		keys:      make([]*Key, len(v.keys)),
 70	}
 71
 72	for i, key := range v.keys {
 73		clone.keys[i] = key.Clone()
 74	}
 75
 76	return clone
 77}
 78
 79func (v *Version) MarshalJSON() ([]byte, error) {
 80	return json.Marshal(VersionJSON{
 81		FormatVersion: formatVersion,
 82		Time:          v.time,
 83		UnixTime:      v.unixTime,
 84		Name:          v.name,
 85		Email:         v.email,
 86		Login:         v.login,
 87		AvatarUrl:     v.avatarURL,
 88		Keys:          v.keys,
 89		Nonce:         v.nonce,
 90		Metadata:      v.metadata,
 91	})
 92}
 93
 94func (v *Version) UnmarshalJSON(data []byte) error {
 95	var aux VersionJSON
 96
 97	if err := json.Unmarshal(data, &aux); err != nil {
 98		return err
 99	}
100
101	if aux.FormatVersion != formatVersion {
102		return fmt.Errorf("unknown format version %v", aux.FormatVersion)
103	}
104
105	v.time = aux.Time
106	v.unixTime = aux.UnixTime
107	v.name = aux.Name
108	v.email = aux.Email
109	v.login = aux.Login
110	v.avatarURL = aux.AvatarUrl
111	v.keys = aux.Keys
112	v.nonce = aux.Nonce
113	v.metadata = aux.Metadata
114
115	return nil
116}
117
118func (v *Version) Validate() error {
119	// time must be set after a commit
120	if v.commitHash != "" && v.unixTime == 0 {
121		return fmt.Errorf("unix time not set")
122	}
123	if v.commitHash != "" && v.time == 0 {
124		return fmt.Errorf("lamport time not set")
125	}
126
127	if text.Empty(v.name) && text.Empty(v.login) {
128		return fmt.Errorf("either name or login should be set")
129	}
130
131	if strings.Contains(v.name, "\n") {
132		return fmt.Errorf("name should be a single line")
133	}
134
135	if !text.Safe(v.name) {
136		return fmt.Errorf("name is not fully printable")
137	}
138
139	if strings.Contains(v.login, "\n") {
140		return fmt.Errorf("login should be a single line")
141	}
142
143	if !text.Safe(v.login) {
144		return fmt.Errorf("login is not fully printable")
145	}
146
147	if strings.Contains(v.email, "\n") {
148		return fmt.Errorf("email should be a single line")
149	}
150
151	if !text.Safe(v.email) {
152		return fmt.Errorf("email is not fully printable")
153	}
154
155	if v.avatarURL != "" && !text.ValidUrl(v.avatarURL) {
156		return fmt.Errorf("avatarUrl is not a valid URL")
157	}
158
159	if len(v.nonce) > 64 {
160		return fmt.Errorf("nonce is too big")
161	}
162
163	for _, k := range v.keys {
164		if err := k.Validate(); err != nil {
165			return errors.Wrap(err, "invalid key")
166		}
167	}
168
169	return nil
170}
171
172// Write will serialize and store the Version as a git blob and return
173// its hash
174func (v *Version) Write(repo repository.Repo) (git.Hash, error) {
175	// make sure we don't write invalid data
176	err := v.Validate()
177	if err != nil {
178		return "", errors.Wrap(err, "validation error")
179	}
180
181	data, err := json.Marshal(v)
182
183	if err != nil {
184		return "", err
185	}
186
187	hash, err := repo.StoreData(data)
188
189	if err != nil {
190		return "", err
191	}
192
193	return hash, nil
194}
195
196func makeNonce(len int) []byte {
197	result := make([]byte, len)
198	_, err := rand.Read(result)
199	if err != nil {
200		panic(err)
201	}
202	return result
203}
204
205// SetMetadata store arbitrary metadata about a version or an Identity in general
206// If the Version has been commit to git already, it won't be overwritten.
207func (v *Version) SetMetadata(key string, value string) {
208	if v.metadata == nil {
209		v.metadata = make(map[string]string)
210	}
211
212	v.metadata[key] = value
213}
214
215// GetMetadata retrieve arbitrary metadata about the Version
216func (v *Version) GetMetadata(key string) (string, bool) {
217	val, ok := v.metadata[key]
218	return val, ok
219}
220
221// AllMetadata return all metadata for this Version
222func (v *Version) AllMetadata() map[string]string {
223	return v.metadata
224}