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
 64	clone := &Version{
 65		name:      v.name,
 66		email:     v.email,
 67		avatarURL: v.avatarURL,
 68		keys:      make([]Key, len(v.keys)),
 69		metadata:  make(map[string]string),
 70	}
 71
 72	for i, op := range opp.Operations {
 73		clone.Operations[i] = op
 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		AvatarUrl:     v.avatarURL,
 87		Keys:          v.keys,
 88		Nonce:         v.nonce,
 89		Metadata:      v.metadata,
 90	})
 91}
 92
 93func (v *Version) UnmarshalJSON(data []byte) error {
 94	var aux VersionJSON
 95
 96	if err := json.Unmarshal(data, &aux); err != nil {
 97		return err
 98	}
 99
100	if aux.FormatVersion != formatVersion {
101		return fmt.Errorf("unknown format version %v", aux.FormatVersion)
102	}
103
104	v.time = aux.Time
105	v.unixTime = aux.UnixTime
106	v.name = aux.Name
107	v.email = aux.Email
108	v.avatarURL = aux.AvatarUrl
109	v.keys = aux.Keys
110	v.nonce = aux.Nonce
111	v.metadata = aux.Metadata
112
113	return nil
114}
115
116func (v *Version) Validate() error {
117	// time must be set after a commit
118	if v.commitHash != "" && v.unixTime == 0 {
119		return fmt.Errorf("unix time not set")
120	}
121	if v.commitHash != "" && v.time == 0 {
122		return fmt.Errorf("lamport time not set")
123	}
124
125	if text.Empty(v.name) {
126		return fmt.Errorf("name not set")
127	}
128
129	if strings.Contains(v.name, "\n") {
130		return fmt.Errorf("name should be a single line")
131	}
132
133	if !text.Safe(v.name) {
134		return fmt.Errorf("name is not fully printable")
135	}
136
137	if strings.Contains(v.email, "\n") {
138		return fmt.Errorf("email should be a single line")
139	}
140
141	if !text.Safe(v.email) {
142		return fmt.Errorf("email is not fully printable")
143	}
144
145	if v.avatarURL != "" && !text.ValidUrl(v.avatarURL) {
146		return fmt.Errorf("avatarUrl is not a valid URL")
147	}
148
149	if len(v.nonce) > 64 {
150		return fmt.Errorf("nonce is too big")
151	}
152
153	for _, k := range v.keys {
154		if err := k.Validate(); err != nil {
155			return errors.Wrap(err, "invalid key")
156		}
157	}
158
159	return nil
160}
161
162// Write will serialize and store the Version as a git blob and return
163// its hash
164func (v *Version) Write(repo repository.Repo) (git.Hash, error) {
165	// make sure we don't write invalid data
166	err := v.Validate()
167	if err != nil {
168		return "", errors.Wrap(err, "validation error")
169	}
170
171	data, err := json.Marshal(v)
172
173	if err != nil {
174		return "", err
175	}
176
177	hash, err := repo.StoreData(data)
178
179	if err != nil {
180		return "", err
181	}
182
183	return hash, nil
184}
185
186func makeNonce(len int) []byte {
187	result := make([]byte, len)
188	_, err := rand.Read(result)
189	if err != nil {
190		panic(err)
191	}
192	return result
193}
194
195// SetMetadata store arbitrary metadata about a version or an Identity in general
196// If the Version has been commit to git already, it won't be overwritten.
197func (v *Version) SetMetadata(key string, value string) {
198	if v.metadata == nil {
199		v.metadata = make(map[string]string)
200	}
201
202	v.metadata[key] = value
203}
204
205// GetMetadata retrieve arbitrary metadata about the Version
206func (v *Version) GetMetadata(key string) (string, bool) {
207	val, ok := v.metadata[key]
208	return val, ok
209}
210
211// AllMetadata return all metadata for this Version
212func (v *Version) AllMetadata() map[string]string {
213	return v.metadata
214}