irmaconfig.go 10.7 KB
Newer Older
1
package irma
2
3
4
5
6
7
8
9
10

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

11
12
	"crypto/sha256"

13
14
15
16
	"fmt"

	"strings"

17
	"github.com/credentials/irmago/internal/fs"
18
	"github.com/go-errors/errors"
19
20
21
	"github.com/mhe/gabi"
)

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

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

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

42
	if err = fs.EnsureDirectoryExists(conf.path); err != nil {
43
44
		return nil, err
	}
45
	if assets != "" {
46
		if err = conf.Copy(assets, false); err != nil {
47
48
49
50
			return nil, err
		}
	}

51
52
53
	return
}

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

63
	conf.reverseHashes = make(map[string]CredentialTypeIdentifier)
64

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

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

95
func (conf *Configuration) addReverseHash(credid CredentialTypeIdentifier) {
96
	hash := sha256.Sum256([]byte(credid.String()))
97
	conf.reverseHashes[base64.StdEncoding.EncodeToString(hash[:16])] = credid
98
99
}

100
101
102
func (conf *Configuration) hashToCredentialType(hash []byte) *CredentialType {
	if str, exists := conf.reverseHashes[base64.StdEncoding.EncodeToString(hash)]; exists {
		return conf.CredentialTypes[str]
103
104
105
106
	}
	return nil
}

107
// IsInitialized indicates whether this instance has successfully been initialized.
108
109
func (conf *Configuration) IsInitialized() bool {
	return conf.initialized
110
111
}

112
func (conf *Configuration) parseIssuerFolders(path string) error {
113
114
115
116
117
118
119
	return iterateSubfolders(path, func(dir string) error {
		issuer := &Issuer{}
		exists, err := pathToDescription(dir+"/description.xml", issuer)
		if err != nil {
			return err
		}
		if exists {
120
121
			conf.Issuers[issuer.Identifier()] = issuer
			if err = conf.parseCredentialsFolder(dir + "/Issues/"); err != nil {
122
123
124
125
126
127
128
				return err
			}
		}
		return nil
	})
}

129
// parse $schememanager/$issuer/PublicKeys/$i.xml for $i = 1, ...
130
131
func (conf *Configuration) parseKeysFolder(issuerid IssuerIdentifier) error {
	path := fmt.Sprintf("%s/%s/%s/PublicKeys/*.xml", conf.path, issuerid.SchemeManagerIdentifier().Name(), issuerid.Name())
132
133
134
135
136
137
138
139
140
141
142
	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
143
144
145
146
147
		}
		pk, err := gabi.NewPublicKeyFromFile(file)
		if err != nil {
			return err
		}
148
		pk.Issuer = issuerid.String()
149
		conf.publicKeys[issuerid][i] = pk
150
	}
151

152
153
154
	return nil
}

155
// parse $schememanager/$issuer/Issues/*/description.xml
156
func (conf *Configuration) parseCredentialsFolder(path string) error {
157
158
159
160
161
162
163
164
	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()
165
166
			conf.CredentialTypes[credid] = cred
			conf.addReverseHash(credid)
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
220
		}
		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
}
221

222
223
224
225
226
// Contains checks if the configuration contains the specified credential type.
func (conf *Configuration) Contains(cred CredentialTypeIdentifier) bool {
	return conf.SchemeManagers[cred.IssuerIdentifier().SchemeManagerIdentifier()] != nil &&
		conf.Issuers[cred.IssuerIdentifier()] != nil &&
		conf.CredentialTypes[cred] != nil
227
}
228

229
230
func (conf *Configuration) Copy(source string, parse bool) error {
	if err := fs.EnsureDirectoryExists(conf.path); err != nil {
231
232
233
		return err
	}

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

	if err != nil {
		return err
	}
	if parse {
266
		return conf.ParseFolder()
267
268
	}
	return nil
269
}
270

271
func (conf *Configuration) DownloadSchemeManager(url string) (*SchemeManager, error) {
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
	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
}

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

316
func (conf *Configuration) AddSchemeManager(manager *SchemeManager) error {
317
	name := manager.ID
318
	if err := fs.EnsureDirectoryExists(fmt.Sprintf("%s/%s", conf.path, name)); err != nil {
319
320
321
322
323
324
		return err
	}
	b, err := xml.Marshal(manager)
	if err != nil {
		return err
	}
325
	if err := fs.SaveFile(fmt.Sprintf("%s/%s/description.xml", conf.path, name), b); err != nil {
326
327
		return err
	}
328
	conf.SchemeManagers[NewSchemeManagerIdentifier(name)] = manager
329
330
	return nil
}
331

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

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

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

396
	return downloaded, conf.ParseFolder()
397
}