configstore.go 6.64 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
package irmago

import (
	"encoding/base64"
	"encoding/xml"
	"io/ioutil"
	"os"
	"path/filepath"
	"strconv"

11
12
	"crypto/sha256"

13
14
15
16
17
	"github.com/mhe/gabi"
)

// ConfigurationStore keeps track of scheme managers, issuers, credential types and public keys.
type ConfigurationStore struct {
18
19
	SchemeManagers map[SchemeManagerIdentifier]*SchemeManager
	Issuers        map[IssuerIdentifier]*Issuer
20
	Credentials    map[CredentialTypeIdentifier]*CredentialType
21

22
	publicKeys    map[IssuerIdentifier][]*gabi.PublicKey
23
	reverseHashes map[string]CredentialTypeIdentifier
24
	path          string
25
	initialized   bool
26
27
}

28
29
// NewConfigurationStore returns a new configuration store. After this
// ParseFolder() should be called to parse the specified path.
30
func NewConfigurationStore(path string, assets string) (store *ConfigurationStore, err error) {
31
	store = &ConfigurationStore{
32
		path: path,
33
	}
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

	var exist bool
	if exist, err = PathExists(store.path); err != nil {
		return nil, err
	}
	if !exist {
		if err = ensureDirectoryExists(store.path); err != nil {
			return nil, err
		}
		if assets != "" {
			if err = store.Copy(assets, false); err != nil {
				return nil, err
			}
		}
	}

50
51
52
	return
}

53
54
55
// ParseFolder populates the current store by parsing the storage path,
// listing the containing scheme managers, issuers and credential types.
func (store *ConfigurationStore) ParseFolder() error {
56
57
58
59
60
61
	// Init all maps
	store.SchemeManagers = make(map[SchemeManagerIdentifier]*SchemeManager)
	store.Issuers = make(map[IssuerIdentifier]*Issuer)
	store.Credentials = make(map[CredentialTypeIdentifier]*CredentialType)
	store.publicKeys = make(map[IssuerIdentifier][]*gabi.PublicKey)
	store.reverseHashes = make(map[string]CredentialTypeIdentifier)
62

63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
	err := iterateSubfolders(store.path, func(dir string) error {
		manager := &SchemeManager{}
		exists, err := pathToDescription(dir+"/description.xml", manager)
		if err != nil {
			return err
		}
		if exists {
			store.SchemeManagers[manager.Identifier()] = manager
			return store.parseIssuerFolders(dir)
		}
		return nil
	})
	if err != nil {
		return err
	}
	store.initialized = true
	return nil
}

82
// PublicKey returns the specified public key, or nil if not present in the ConfigurationStore.
83
84
85
86
87
88
func (store *ConfigurationStore) PublicKey(id IssuerIdentifier, counter int) (*gabi.PublicKey, error) {
	if _, contains := store.publicKeys[id]; !contains {
		store.publicKeys[id] = []*gabi.PublicKey{}
		err := store.parseKeysFolder(id)
		if err != nil {
			return nil, err
89
90
		}
	}
91
92
93
94
95
96
97

	list := store.publicKeys[id]
	if len(list) > counter {
		return list[counter], nil
	}

	return nil, nil
98
99
}

100
func (store *ConfigurationStore) addReverseHash(credid CredentialTypeIdentifier) {
101
	hash := sha256.Sum256([]byte(credid.String()))
102
103
104
105
106
107
108
109
110
111
	store.reverseHashes[base64.StdEncoding.EncodeToString(hash[:16])] = credid
}

func (store *ConfigurationStore) hashToCredentialType(hash []byte) *CredentialType {
	if str, exists := store.reverseHashes[base64.StdEncoding.EncodeToString(hash)]; exists {
		return store.Credentials[str]
	}
	return nil
}

112
// IsInitialized indicates whether this instance has successfully been initialized.
113
114
115
116
func (store *ConfigurationStore) IsInitialized() bool {
	return store.initialized
}

117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
func (store *ConfigurationStore) parseIssuerFolders(path string) error {
	return iterateSubfolders(path, func(dir string) error {
		issuer := &Issuer{}
		exists, err := pathToDescription(dir+"/description.xml", issuer)
		if err != nil {
			return err
		}
		if exists {
			store.Issuers[issuer.Identifier()] = issuer
			if err = store.parseCredentialsFolder(dir + "/Issues/"); err != nil {
				return err
			}
		}
		return nil
	})
}

134
135
136
137
138
139
func (store *ConfigurationStore) parseKeysFolder(issuerid IssuerIdentifier) error {
	issuer := store.Issuers[issuerid]
	path := store.path + "/" +
		issuer.Identifier().SchemeManagerIdentifier().String() +
		"/" + issuer.ID + "/PublicKeys/"

140
141
142
143
144
145
146
147
148
	for i := 0; ; i++ {
		file := path + strconv.Itoa(i) + ".xml"
		if _, err := os.Stat(file); err != nil {
			break
		}
		pk, err := gabi.NewPublicKeyFromFile(file)
		if err != nil {
			return err
		}
Sietse Ringers's avatar
Sietse Ringers committed
149
		pk.Issuer = issuer.Identifier().String()
150
		store.publicKeys[issuer.Identifier()] = append(store.publicKeys[issuer.Identifier()], pk)
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
	}
	return nil
}

func (store *ConfigurationStore) parseCredentialsFolder(path string) error {
	return iterateSubfolders(path, func(dir string) error {
		cred := &CredentialType{}
		exists, err := pathToDescription(dir+"/description.xml", cred)
		if err != nil {
			return err
		}
		if exists {
			credid := cred.Identifier()
			store.Credentials[credid] = cred
			store.addReverseHash(credid)
		}
		return nil
	})
}

// iterateSubfolders iterates over the subfolders of the specified path,
// calling the specified handler each time. If anything goes wrong, or
// if the caller returns a non-nil error, an error is immediately returned.
func iterateSubfolders(path string, handler func(string) error) error {
	dirs, err := filepath.Glob(path + "/*")
	if err != nil {
		return err
	}

	for _, dir := range dirs {
		stat, err := os.Stat(dir)
		if err != nil {
			return err
		}
		if !stat.IsDir() {
			continue
		}
		err = handler(dir)
		if err != nil {
			return err
		}
	}

	return nil
}

func pathToDescription(path string, description interface{}) (bool, error) {
	if _, err := os.Stat(path); err != nil {
		return false, nil
	}

	file, err := os.Open(path)
	if err != nil {
		return true, err
	}
	defer file.Close()

	bytes, err := ioutil.ReadAll(file)
	if err != nil {
		return true, err
	}

	err = xml.Unmarshal(bytes, description)
	if err != nil {
		return true, err
	}

	return true, nil
}
220

Sietse Ringers's avatar
Sietse Ringers committed
221
// Contains checks if the store contains the specified credential type.
222
223
224
225
226
func (store *ConfigurationStore) Contains(cred CredentialTypeIdentifier) bool {
	return store.SchemeManagers[cred.IssuerIdentifier().SchemeManagerIdentifier()] != nil &&
		store.Issuers[cred.IssuerIdentifier()] != nil &&
		store.Credentials[cred] != nil
}
227

228
func (store *ConfigurationStore) Copy(source string, parse bool) error {
229
230
231
232
	if err := ensureDirectoryExists(store.path); err != nil {
		return err
	}

233
	err := filepath.Walk(source, filepath.WalkFunc(
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
		func(path string, info os.FileInfo, err error) error {
			if path == source {
				return nil
			}
			subpath := path[len(source):]
			if info.IsDir() {
				if err := ensureDirectoryExists(store.path + subpath); err != nil {
					return err
				}
			} else {
				srcfile, err := os.Open(path)
				if err != nil {
					return err
				}
				defer srcfile.Close()
Sietse Ringers's avatar
Sietse Ringers committed
249
250
251
252
253
				bytes, err := ioutil.ReadAll(srcfile)
				if err != nil {
					return err
				}
				if err := saveFile(store.path+subpath, bytes); err != nil {
254
255
256
257
258
259
					return err
				}
			}
			return nil
		}),
	)
260
261
262
263
264
265
266
267

	if err != nil {
		return err
	}
	if parse {
		return store.ParseFolder()
	}
	return nil
268
}