version.go

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