configstore.go 10.8 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
	"fmt"

	"strings"

	"github.com/go-errors/errors"
18
19
20
	"github.com/mhe/gabi"
)

21
22
// ConfigurationStore keeps track of scheme managers, issuers, credential types and public keys,
// dezerializing them from an irma_configuration folder, and downloads and saves new ones on demand.
23
type ConfigurationStore struct {
24
25
26
	SchemeManagers  map[SchemeManagerIdentifier]*SchemeManager
	Issuers         map[IssuerIdentifier]*Issuer
	CredentialTypes map[CredentialTypeIdentifier]*CredentialType
27

28
	publicKeys    map[IssuerIdentifier]map[int]*gabi.PublicKey
29
	reverseHashes map[string]CredentialTypeIdentifier
30
	path          string
31
	initialized   bool
32
33
}

34
35
// NewConfigurationStore returns a new configuration store. After this
// ParseFolder() should be called to parse the specified path.
36
func NewConfigurationStore(path string, assets string) (store *ConfigurationStore, err error) {
37
	store = &ConfigurationStore{
38
		path: path,
39
	}
40

41
	if err = ensureDirectoryExists(store.path); err != nil {
42
43
		return nil, err
	}
44
45
	if assets != "" {
		if err = store.Copy(assets, false); err != nil {
46
47
48
49
			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
	// Init all maps
	store.SchemeManagers = make(map[SchemeManagerIdentifier]*SchemeManager)
	store.Issuers = make(map[IssuerIdentifier]*Issuer)
59
	store.CredentialTypes = make(map[CredentialTypeIdentifier]*CredentialType)
60
	store.publicKeys = make(map[IssuerIdentifier]map[int]*gabi.PublicKey)
61

62
	store.reverseHashes = make(map[string]CredentialTypeIdentifier)
63

64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
	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
}

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

94
func (store *ConfigurationStore) addReverseHash(credid CredentialTypeIdentifier) {
95
	hash := sha256.Sum256([]byte(credid.String()))
96
97
98
99
100
	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 {
101
		return store.CredentialTypes[str]
102
103
104
105
	}
	return nil
}

106
// IsInitialized indicates whether this instance has successfully been initialized.
107
108
109
110
func (store *ConfigurationStore) IsInitialized() bool {
	return store.initialized
}

111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
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
	})
}

128
// parse $schememanager/$issuer/PublicKeys/$i.xml for $i = 1, ...
129
func (store *ConfigurationStore) parseKeysFolder(issuerid IssuerIdentifier) error {
130
131
132
133
134
135
136
137
138
139
140
141
	path := fmt.Sprintf("%s/%s/%s/PublicKeys/*.xml", store.path, issuerid.SchemeManagerIdentifier().Name(), issuerid.Name())
	files, err := filepath.Glob(path)
	if err != nil {
		return err
	}

	for _, file := range files {
		filename := filepath.Base(file)
		count := filename[:len(filename)-4]
		i, err := strconv.Atoi(count)
		if err != nil {
			continue
142
143
144
145
146
		}
		pk, err := gabi.NewPublicKeyFromFile(file)
		if err != nil {
			return err
		}
147
148
		pk.Issuer = issuerid.String()
		store.publicKeys[issuerid][i] = pk
149
	}
150

151
152
153
	return nil
}

154
// parse $schememanager/$issuer/Issues/*/description.xml
155
156
157
158
159
160
161
162
163
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()
164
			store.CredentialTypes[credid] = cred
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
			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
func (store *ConfigurationStore) Contains(cred CredentialTypeIdentifier) bool {
	return store.SchemeManagers[cred.IssuerIdentifier().SchemeManagerIdentifier()] != nil &&
		store.Issuers[cred.IssuerIdentifier()] != nil &&
225
		store.CredentialTypes[cred] != nil
226
}
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
}
269

270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
func (store *ConfigurationStore) DownloadSchemeManager(url string) (*SchemeManager, error) {
	if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {
		url = "https://" + url
	}
	if url[len(url)-1] == '/' {
		url = url[:len(url)-1]
	}
	if strings.HasSuffix(url, "/description.xml") {
		url = url[:len(url)-len("/description.xml")]
	}
	b, err := NewHTTPTransport(url).GetBytes("/description.xml")
	if err != nil {
		return nil, err
	}
	manager := &SchemeManager{}
	if err = xml.Unmarshal(b, manager); err != nil {
		return nil, err
	}

	manager.URL = url // TODO?
	return manager, nil
}

func (store *ConfigurationStore) RemoveSchemeManager(id SchemeManagerIdentifier) error {
	// Remove everything falling under the manager's responsibility
295
	for credid := range store.CredentialTypes {
296
		if credid.IssuerIdentifier().SchemeManagerIdentifier() == id {
297
			delete(store.CredentialTypes, credid)
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
		}
	}
	for issid := range store.Issuers {
		if issid.SchemeManagerIdentifier() == id {
			delete(store.Issuers, issid)
		}
	}
	for issid := range store.publicKeys {
		if issid.SchemeManagerIdentifier() == id {
			delete(store.publicKeys, issid)
		}
	}
	// Remove from storage
	return os.RemoveAll(fmt.Sprintf("%s/%s", store.path, id.String()))
	// or, remove above iterations and call .ParseFolder()?
}

func (store *ConfigurationStore) AddSchemeManager(manager *SchemeManager) error {
	name := manager.ID
	if err := ensureDirectoryExists(fmt.Sprintf("%s/%s", store.path, name)); err != nil {
		return err
	}
	b, err := xml.Marshal(manager)
	if err != nil {
		return err
	}
	if err := saveFile(fmt.Sprintf("%s/%s/description.xml", store.path, name), b); err != nil {
		return err
	}
	store.SchemeManagers[NewSchemeManagerIdentifier(name)] = manager
328
329
	return nil
}
330

331
func (store *ConfigurationStore) Download(set *IrmaIdentifierSet) (*IrmaIdentifierSet, error) {
332
	var contains bool
333
334
335
336
337
338
339
	var err error
	downloaded := &IrmaIdentifierSet{
		SchemeManagers:  map[SchemeManagerIdentifier]struct{}{},
		Issuers:         map[IssuerIdentifier]struct{}{},
		CredentialTypes: map[CredentialTypeIdentifier]struct{}{},
	}

340
341
	for manid := range set.SchemeManagers {
		if _, contains = store.SchemeManagers[manid]; !contains {
342
			return nil, errors.Errorf("Unknown scheme manager: %s", manid)
343
344
345
346
347
348
349
350
		}
	}

	transport := NewHTTPTransport("")
	for issid := range set.Issuers {
		if _, contains = store.Issuers[issid]; !contains {
			url := store.SchemeManagers[issid.SchemeManagerIdentifier()].URL + "/" + issid.Name()
			path := fmt.Sprintf("%s/%s/%s", store.path, issid.SchemeManagerIdentifier().String(), issid.Name())
351
352
353
354
355
356
357
			if err = transport.GetFile(url+"/description.xml", path+"/description.xml"); err != nil {
				return nil, err
			}
			if transport.GetFile(url+"/logo.png", path+"/logo.png"); err != nil {
				return nil, err
			}
			downloaded.Issuers[issid] = struct{}{}
358
		}
Sietse Ringers's avatar
Sietse Ringers committed
359
360
361
362
363
364
365
366
367
368
369
370
	}
	for issid, list := range set.PublicKeys {
		for _, count := range list {
			pk, err := store.PublicKey(issid, count)
			if err != nil {
				return nil, err
			}
			if pk == nil {
				manager := issid.SchemeManagerIdentifier()
				suffix := fmt.Sprintf("/%s/PublicKeys/%d.xml", issid.Name(), count)
				path := fmt.Sprintf("%s/%s/%s", store.path, manager.String(), suffix)
				if transport.GetFile(store.SchemeManagers[manager].URL+suffix, path); err != nil {
371
					return nil, err
372
				}
373
374
375
376
			}
		}
	}
	for credid := range set.CredentialTypes {
377
		if _, contains := store.CredentialTypes[credid]; !contains {
378
379
380
381
			issuer := credid.IssuerIdentifier()
			manager := issuer.SchemeManagerIdentifier()
			local := fmt.Sprintf("%s/%s/%s/Issues", store.path, manager.Name(), issuer.Name())
			if err := ensureDirectoryExists(local); err != nil {
382
				return nil, err
383
			}
384
			if transport.GetFile(
385
386
387
				fmt.Sprintf("%s/%s/Issues/%s/description.xml",
					store.SchemeManagers[manager].URL, issuer.Name(), credid.Name()),
				fmt.Sprintf("%s/%s/description.xml", local, credid.Name()),
388
389
390
391
			); err != nil {
				return nil, err
			}
			downloaded.CredentialTypes[credid] = struct{}{}
392
393
394
		}
	}

395
	return downloaded, store.ParseFolder()
396
}