version.go

  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 a bug, 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.NewErrOldFormatVersion(aux.FormatVersion)
164	}
165	if aux.FormatVersion > formatVersion {
166		return entity.NewErrNewFormatVersion(aux.FormatVersion)
167	}
168
169	v.id = entity.DeriveId(data)
170	v.times = aux.Times
171	v.unixTime = aux.UnixTime
172	v.name = aux.Name
173	v.email = aux.Email
174	v.login = aux.Login
175	v.avatarURL = aux.AvatarUrl
176	v.keys = aux.Keys
177	v.nonce = aux.Nonce
178	v.metadata = aux.Metadata
179
180	return nil
181}
182
183func (v *version) Validate() error {
184	// time must be set after a commit
185	if v.commitHash != "" && v.unixTime == 0 {
186		return fmt.Errorf("unix time not set")
187	}
188
189	if text.Empty(v.name) && text.Empty(v.login) {
190		return fmt.Errorf("either name or login should be set")
191	}
192	if strings.Contains(v.name, "\n") {
193		return fmt.Errorf("name should be a single line")
194	}
195	if !text.Safe(v.name) {
196		return fmt.Errorf("name is not fully printable")
197	}
198
199	if strings.Contains(v.login, "\n") {
200		return fmt.Errorf("login should be a single line")
201	}
202	if !text.Safe(v.login) {
203		return fmt.Errorf("login is not fully printable")
204	}
205
206	if strings.Contains(v.email, "\n") {
207		return fmt.Errorf("email should be a single line")
208	}
209	if !text.Safe(v.email) {
210		return fmt.Errorf("email is not fully printable")
211	}
212
213	if v.avatarURL != "" && !text.ValidUrl(v.avatarURL) {
214		return fmt.Errorf("avatarUrl is not a valid URL")
215	}
216
217	if len(v.nonce) > 64 {
218		return fmt.Errorf("nonce is too big")
219	}
220	if len(v.nonce) < 20 {
221		return fmt.Errorf("nonce is too small")
222	}
223
224	for _, k := range v.keys {
225		if err := k.Validate(); err != nil {
226			return errors.Wrap(err, "invalid key")
227		}
228	}
229
230	return nil
231}
232
233// Write will serialize and store the version as a git blob and return
234// its hash
235func (v *version) Write(repo repository.Repo) (repository.Hash, error) {
236	// make sure we don't write invalid data
237	err := v.Validate()
238	if err != nil {
239		return "", errors.Wrap(err, "validation error")
240	}
241
242	data, err := json.Marshal(v)
243	if err != nil {
244		return "", err
245	}
246
247	hash, err := repo.StoreData(data)
248	if err != nil {
249		return "", err
250	}
251
252	// make sure we set the Id when writing in the repo
253	v.id = entity.DeriveId(data)
254
255	return hash, nil
256}
257
258func makeNonce(len int) []byte {
259	result := make([]byte, len)
260	_, err := rand.Read(result)
261	if err != nil {
262		panic(err)
263	}
264	return result
265}
266
267// SetMetadata store arbitrary metadata about a version or an Identity in general
268// If the version has been commit to git already, it won't be overwritten.
269// Beware: changing the metadata on a version will change it's ID
270func (v *version) SetMetadata(key string, value string) {
271	if v.metadata == nil {
272		v.metadata = make(map[string]string)
273	}
274	v.metadata[key] = value
275}
276
277// GetMetadata retrieve arbitrary metadata about the version
278func (v *version) GetMetadata(key string) (string, bool) {
279	val, ok := v.metadata[key]
280	return val, ok
281}
282
283// AllMetadata return all metadata for this version
284func (v *version) AllMetadata() map[string]string {
285	return v.metadata
286}