1package identity
2
3import (
4 "crypto/rand"
5 "encoding/json"
6 "fmt"
7 "strings"
8 "time"
9
10 "github.com/pkg/errors"
11
12 "github.com/MichaelMure/git-bug/entity"
13 "github.com/MichaelMure/git-bug/repository"
14 "github.com/MichaelMure/git-bug/util/lamport"
15 "github.com/MichaelMure/git-bug/util/text"
16)
17
18// 1: original format
19// 2: Identity Ids are generated from the first version serialized data instead of from the first git commit
20// + Identity hold multiple lamport clocks from other entities, instead of just bug edit
21const formatVersion = 2
22
23// version is a complete set of information about an Identity at a point in time.
24type version struct {
25 name string
26 email string // as defined in git or from a bridge when importing the identity
27 login string // from a bridge when importing the identity
28 avatarURL string
29
30 // The lamport times of the other entities at which this version become effective
31 times map[string]lamport.Time
32 unixTime int64
33
34 // The set of keys valid at that time, from this version onward, until they get removed
35 // in a new version. This allow to have multiple key for the same identity (e.g. one per
36 // device) as well as revoke key.
37 keys []*Key
38
39 // mandatory random bytes to ensure a better randomness of the data of the first
40 // version of an identity, used to later generate the ID
41 // len(Nonce) should be > 20 and < 64 bytes
42 // It has no functional purpose and should be ignored.
43 // TODO: optional after first version?
44 nonce []byte
45
46 // A set of arbitrary key/value to store metadata about a version or about an Identity in general.
47 metadata map[string]string
48
49 // Not serialized. Store the version's id in memory.
50 id entity.Id
51 // Not serialized
52 commitHash repository.Hash
53}
54
55func newVersion(repo repository.RepoClock, name string, email string, login string, avatarURL string, keys []*Key) (*version, error) {
56 clocks, err := repo.AllClocks()
57 if err != nil {
58 return nil, err
59 }
60
61 times := make(map[string]lamport.Time)
62 for name, clock := range clocks {
63 times[name] = clock.Time()
64 }
65
66 return &version{
67 id: entity.UnsetId,
68 name: name,
69 email: email,
70 login: login,
71 avatarURL: avatarURL,
72 times: times,
73 unixTime: time.Now().Unix(),
74 keys: keys,
75 nonce: makeNonce(20),
76 }, nil
77}
78
79type versionJSON struct {
80 // Additional field to version the data
81 FormatVersion uint `json:"version"`
82
83 Times map[string]lamport.Time `json:"times"`
84 UnixTime int64 `json:"unix_time"`
85 Name string `json:"name,omitempty"`
86 Email string `json:"email,omitempty"`
87 Login string `json:"login,omitempty"`
88 AvatarUrl string `json:"avatar_url,omitempty"`
89 Keys []*Key `json:"pub_keys,omitempty"`
90 Nonce []byte `json:"nonce"`
91 Metadata map[string]string `json:"metadata,omitempty"`
92}
93
94// Id return the identifier of the version
95func (v *version) Id() entity.Id {
96 if v.id == "" {
97 // something went really wrong
98 panic("version's id not set")
99 }
100 if v.id == entity.UnsetId {
101 // This means we are trying to get the version's Id *before* it has been stored.
102 // As the Id is computed based on the actual bytes written on the disk, we are going to predict
103 // those and then get the Id. This is safe as it will be the exact same code writing on disk later.
104 data, err := json.Marshal(v)
105 if err != nil {
106 panic(err)
107 }
108 v.id = entity.DeriveId(data)
109 }
110 return v.id
111}
112
113// Make a deep copy
114func (v *version) Clone() *version {
115 // copy direct fields
116 clone := *v
117
118 // reset some fields
119 clone.commitHash = ""
120 clone.id = entity.UnsetId
121
122 clone.times = make(map[string]lamport.Time)
123 for name, t := range v.times {
124 clone.times[name] = t
125 }
126
127 clone.keys = make([]*Key, len(v.keys))
128 for i, key := range v.keys {
129 clone.keys[i] = key.Clone()
130 }
131
132 clone.nonce = make([]byte, len(v.nonce))
133 copy(clone.nonce, v.nonce)
134
135 // not copying metadata
136
137 return &clone
138}
139
140func (v *version) MarshalJSON() ([]byte, error) {
141 return json.Marshal(versionJSON{
142 FormatVersion: formatVersion,
143 Times: v.times,
144 UnixTime: v.unixTime,
145 Name: v.name,
146 Email: v.email,
147 Login: v.login,
148 AvatarUrl: v.avatarURL,
149 Keys: v.keys,
150 Nonce: v.nonce,
151 Metadata: v.metadata,
152 })
153}
154
155func (v *version) UnmarshalJSON(data []byte) error {
156 var aux versionJSON
157
158 if err := json.Unmarshal(data, &aux); err != nil {
159 return err
160 }
161
162 if aux.FormatVersion != formatVersion {
163 return entity.NewErrInvalidFormat(aux.FormatVersion, formatVersion)
164 }
165
166 v.id = entity.DeriveId(data)
167 v.times = aux.Times
168 v.unixTime = aux.UnixTime
169 v.name = aux.Name
170 v.email = aux.Email
171 v.login = aux.Login
172 v.avatarURL = aux.AvatarUrl
173 v.keys = aux.Keys
174 v.nonce = aux.Nonce
175 v.metadata = aux.Metadata
176
177 return nil
178}
179
180func (v *version) Validate() error {
181 // time must be set after a commit
182 if v.commitHash != "" && v.unixTime == 0 {
183 return fmt.Errorf("unix time not set")
184 }
185
186 if text.Empty(v.name) && text.Empty(v.login) {
187 return fmt.Errorf("either name or login should be set")
188 }
189 if strings.Contains(v.name, "\n") {
190 return fmt.Errorf("name should be a single line")
191 }
192 if !text.Safe(v.name) {
193 return fmt.Errorf("name is not fully printable")
194 }
195
196 if strings.Contains(v.login, "\n") {
197 return fmt.Errorf("login should be a single line")
198 }
199 if !text.Safe(v.login) {
200 return fmt.Errorf("login is not fully printable")
201 }
202
203 if strings.Contains(v.email, "\n") {
204 return fmt.Errorf("email should be a single line")
205 }
206 if !text.Safe(v.email) {
207 return fmt.Errorf("email is not fully printable")
208 }
209
210 if v.avatarURL != "" && !text.ValidUrl(v.avatarURL) {
211 return fmt.Errorf("avatarUrl is not a valid URL")
212 }
213
214 if len(v.nonce) > 64 {
215 return fmt.Errorf("nonce is too big")
216 }
217 if len(v.nonce) < 20 {
218 return fmt.Errorf("nonce is too small")
219 }
220
221 for _, k := range v.keys {
222 if err := k.Validate(); err != nil {
223 return errors.Wrap(err, "invalid key")
224 }
225 }
226
227 return nil
228}
229
230// Write will serialize and store the version as a git blob and return
231// its hash
232func (v *version) Write(repo repository.Repo) (repository.Hash, error) {
233 // make sure we don't write invalid data
234 err := v.Validate()
235 if err != nil {
236 return "", errors.Wrap(err, "validation error")
237 }
238
239 data, err := json.Marshal(v)
240 if err != nil {
241 return "", err
242 }
243
244 hash, err := repo.StoreData(data)
245 if err != nil {
246 return "", err
247 }
248
249 // make sure we set the Id when writing in the repo
250 v.id = entity.DeriveId(data)
251
252 return hash, nil
253}
254
255func makeNonce(len int) []byte {
256 result := make([]byte, len)
257 _, err := rand.Read(result)
258 if err != nil {
259 panic(err)
260 }
261 return result
262}
263
264// SetMetadata store arbitrary metadata about a version or an Identity in general
265// If the version has been commit to git already, it won't be overwritten.
266// Beware: changing the metadata on a version will change it's ID
267func (v *version) SetMetadata(key string, value string) {
268 if v.metadata == nil {
269 v.metadata = make(map[string]string)
270 }
271 v.metadata[key] = value
272}
273
274// GetMetadata retrieve arbitrary metadata about the version
275func (v *version) GetMetadata(key string) (string, bool) {
276 val, ok := v.metadata[key]
277 return val, ok
278}
279
280// AllMetadata return all metadata for this version
281func (v *version) AllMetadata() map[string]string {
282 return v.metadata
283}