irmago_test.go 50.2 KB
Newer Older
1
package irma
2
3

import (
4
	"crypto/rand"
5
	"encoding/json"
Sietse Ringers's avatar
Sietse Ringers committed
6
	"encoding/xml"
Sietse Ringers's avatar
Sietse Ringers committed
7
	"io/ioutil"
8
	"os"
9
	"path/filepath"
10
	"reflect"
Sietse Ringers's avatar
Sietse Ringers committed
11
	"testing"
12
	"time"
13

14
	"github.com/privacybydesign/gabi"
15
	"github.com/privacybydesign/gabi/big"
16
	"github.com/privacybydesign/gabi/revocation"
17
	"github.com/privacybydesign/irmago/internal/common"
18
	"github.com/privacybydesign/irmago/internal/test"
Sietse Ringers's avatar
Sietse Ringers committed
19
	"github.com/sirupsen/logrus"
Sietse Ringers's avatar
Sietse Ringers committed
20
	"github.com/stretchr/testify/require"
21
22
)

23
24
func init() {
	common.ForceHTTPS = false // globally disable https enforcement
Sietse Ringers's avatar
Sietse Ringers committed
25
	Logger.SetLevel(logrus.FatalLevel)
26
27
}

28
func parseConfiguration(t *testing.T) *Configuration {
29
	conf, err := NewConfiguration("testdata/irma_configuration", ConfigurationOptions{})
30
	require.NoError(t, err)
31
	require.NoError(t, conf.ParseFolder())
32
33
34
35
36
37
38
39
40
41
	return conf
}

// A convenience function for initializing big integers from known correct (10
// base) strings. Use with care, errors are ignored.
func s2big(s string) (r *big.Int) {
	r, _ = new(big.Int).SetString(s, 10)
	return
}

42
func TestConfigurationAutocopy(t *testing.T) {
43
44
	storage := test.CreateTestStorage(t)
	defer test.ClearTestStorage(t, storage)
45

46
47
48
	require.NoError(t, os.Remove(filepath.Join(storage, "client")))
	require.NoError(t, common.CopyDirectory(filepath.Join("testdata", "irma_configuration"), storage))
	conf, err := NewConfiguration(storage, ConfigurationOptions{Assets: filepath.Join("testdata", "irma_configuration_updated")})
49
	require.NoError(t, err)
50
	require.NoError(t, conf.ParseFolder())
51

52
53
54
	credid := NewCredentialTypeIdentifier("irma-demo.RU.studentCard")
	attrid := NewAttributeTypeIdentifier("irma-demo.RU.studentCard.newAttribute")
	require.True(t, conf.CredentialTypes[credid].ContainsAttribute(attrid))
55
56
	require.Contains(t, conf.RequestorSchemes, NewRequestorSchemeIdentifier("test-requestors"))
	require.Contains(t, conf.Requestors, "localhost")
57
58
}

59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
func TestUpdateConfiguration(t *testing.T) {
	storage := test.SetupTestStorage(t)
	defer test.ClearTestStorage(t, storage)
	test.StartSchemeManagerHttpServer()
	defer test.StopSchemeManagerHttpServer()

	conf, err := NewConfiguration(filepath.Join(storage, "client"), ConfigurationOptions{Assets: filepath.Join("testdata", "irma_configuration")})
	require.NoError(t, err)
	require.NoError(t, conf.ParseFolder())

	// first update just a public key. We don't have such an updated scheme in the testdata
	// so we hackily manipulate scheme state to mark it out of date.
	issuerid := NewIssuerIdentifier("irma-demo.MijnOverheid")
	schemeid := NewSchemeManagerIdentifier("irma-demo")
	scheme := conf.SchemeManagers[schemeid]
	scheme.Timestamp = Timestamp(time.Time(scheme.Timestamp).Add(-1000 * time.Hour))
	// modify hash of a public key in the index so it will update the file
	path := "irma-demo/MijnOverheid/PublicKeys/2.xml"
	scheme.index[path][0] = ^scheme.index[path][0]

	updated := newIrmaIdentifierSet()
80
	require.NoError(t, conf.UpdateScheme(scheme, updated))
81
82
83
84
85
86
	require.Contains(t, updated.PublicKeys, issuerid)
	require.Contains(t, updated.PublicKeys[issuerid], uint(2))

	// next, update to a copy of the scheme in which a credential type was modified
	scheme.URL = "http://localhost:48681/irma_configuration_updated/irma-demo"
	updated = newIrmaIdentifierSet()
87
	require.NoError(t, conf.UpdateScheme(scheme, updated))
88
	require.Contains(t, updated.CredentialTypes, NewCredentialTypeIdentifier("irma-demo.RU.studentCard"))
89
90
91
92
93
94
95

	updated = newIrmaIdentifierSet()
	requestorschemeid := NewRequestorSchemeIdentifier("test-requestors")
	requestorscheme := conf.RequestorSchemes[requestorschemeid]
	requestorscheme.URL = "http://localhost:48681/irma_configuration_updated/test-requestors"
	require.NoError(t, conf.UpdateScheme(requestorscheme, updated))
	require.Contains(t, updated.RequestorSchemes, requestorschemeid)
96
97
}

98
99
100
func TestParseInvalidIrmaConfiguration(t *testing.T) {
	// The description.xml of the scheme manager under this folder has been edited
	// to invalidate the scheme manager signature
101
	conf, err := NewConfiguration(filepath.Join("testdata", "irma_configuration_invalid"), ConfigurationOptions{ReadOnly: true})
102
103
104
105
106
107
108
109
110
111
	require.NoError(t, err)

	// Parsing it should return a SchemeManagerError
	err = conf.ParseFolder()
	require.Error(t, err)
	smerr, ok := err.(*SchemeManagerError)
	require.True(t, ok)
	require.Equal(t, SchemeManagerStatusInvalidSignature, smerr.Status)

	// The manager should still be in conf.SchemeManagers, but also in DisabledSchemeManagers
112
113
114
115
	id := NewSchemeManagerIdentifier(smerr.Scheme)
	require.Contains(t, conf.SchemeManagers, id)
	require.Contains(t, conf.DisabledSchemeManagers, id)
	require.Equal(t, SchemeManagerStatusInvalidSignature, conf.SchemeManagers[id].Status)
116
117
}

118
func TestRetryHTTPRequest(t *testing.T) {
119
	test.StartBadHttpServer(2, 1*time.Second, "42")
120
	defer test.StopBadHttpServer()
121

122
	transport := NewHTTPTransport("http://localhost:48682", false)
123
124
125
126
127
128
	transport.client.HTTPClient.Timeout = 500 * time.Millisecond
	bts, err := transport.GetBytes("")
	require.NoError(t, err)
	require.Equal(t, "42\n", string(bts))
}

129
func TestInvalidIrmaConfigurationRestoreFromRemote(t *testing.T) {
130
	test.StartSchemeManagerHttpServer()
131
132
	defer test.StopSchemeManagerHttpServer()

133
134
	storage := test.CreateTestStorage(t)
	defer test.ClearTestStorage(t, storage)
135
	require.NoError(t, os.Remove(filepath.Join(storage, "client")))
136

137
	conf, err := NewConfiguration(storage, ConfigurationOptions{
138
139
		Assets: filepath.Join("testdata", "irma_configuration_invalid"),
	})
140
141
	require.NoError(t, err)

142
	// check that restoring works
143
144
145
	err = conf.ParseOrRestoreFolder()
	require.NoError(t, err)
	require.Empty(t, conf.DisabledSchemeManagers)
146
147
148
149
150
151
152
153

	// switch to correct assets, and parse again to check that ParseOrRestoreFolder
	// left the folder in a consistent state
	conf.assets = filepath.Join("testdata", "irma_configuration")
	err = conf.ParseFolder()
	require.NoError(t, err)
	require.Empty(t, conf.DisabledSchemeManagers)

154
	require.Contains(t, conf.SchemeManagers, NewSchemeManagerIdentifier("irma-demo"))
155
	require.Contains(t, conf.CredentialTypes, NewCredentialTypeIdentifier("irma-demo.RU.studentCard"))
156
157
}

158
func TestInvalidIrmaConfigurationRestoreFromAssets(t *testing.T) {
159
160
	storage := test.CreateTestStorage(t)
	defer test.ClearTestStorage(t, storage)
161

162
	conf, err := NewConfiguration(filepath.Join(storage, "client", "irma_configuration"), ConfigurationOptions{
163
164
		Assets: filepath.Join("testdata", "irma_configuration_invalid"),
	})
165
166
167
168
169
170
171
172
	require.NoError(t, err)

	// Fails: no remote and the version in the assets is broken
	err = conf.ParseOrRestoreFolder()
	require.Error(t, err)
	require.NotEmpty(t, conf.DisabledSchemeManagers)

	// Try again from correct assets
173
	conf.assets = filepath.Join("testdata", "irma_configuration")
174
175
176
	err = conf.ParseOrRestoreFolder()
	require.NoError(t, err)
	require.Empty(t, conf.DisabledSchemeManagers)
177
178
179
180
181
182

	// parse again to check that ParseOrRestoreFolder left the folder in a consistent state
	err = conf.ParseFolder()
	require.NoError(t, err)
	require.Empty(t, conf.DisabledSchemeManagers)

183
184
	require.Contains(t, conf.SchemeManagers, NewSchemeManagerIdentifier("irma-demo"))
	require.Contains(t, conf.CredentialTypes, NewCredentialTypeIdentifier("irma-demo.RU.studentCard"))
185
186
	require.Contains(t, conf.RequestorSchemes, NewRequestorSchemeIdentifier("test-requestors"))
	require.Contains(t, conf.Requestors, "localhost")
187
188
}

189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
func TestParseIrmaConfiguration(t *testing.T) {
	conf := parseConfiguration(t)

	require.Contains(t, conf.SchemeManagers, NewSchemeManagerIdentifier("irma-demo"))
	require.Contains(t, conf.SchemeManagers, NewSchemeManagerIdentifier("test"))

	pk, err := conf.PublicKey(NewIssuerIdentifier("irma-demo.RU"), 0)
	require.NoError(t, err)
	require.NotNil(t, pk)
	require.NotNil(t, pk.N, "irma-demo.RU public key has no modulus")
	require.Equal(t,
		"Irma Demo",
		conf.SchemeManagers[NewSchemeManagerIdentifier("irma-demo")].Name["en"],
		"irma-demo scheme manager has unexpected name")
	require.Equal(t,
204
		"Demo Radboud University Nijmegen",
205
206
207
		conf.Issuers[NewIssuerIdentifier("irma-demo.RU")].Name["en"],
		"irma-demo.RU issuer has unexpected name")
	require.Equal(t,
208
209
		"Demo Student Card",
		conf.CredentialTypes[NewCredentialTypeIdentifier("irma-demo.RU.studentCard")].Name["en"],
210
211
212
213
		"irma-demo.RU.studentCard has unexpected name")

	require.Equal(t,
		"studentID",
214
		conf.CredentialTypes[NewCredentialTypeIdentifier("irma-demo.RU.studentCard")].AttributeTypes[2].ID,
215
216
217
218
		"irma-demo.RU.studentCard.studentID has unexpected name")

	// Hash algorithm pseudocode:
	// Base64(SHA256("irma-demo.RU.studentCard")[0:16])
219
220
221
222
223
224
225
226
	require.Contains(t, conf.reverseHashes, "1stqlPad5edpfS1Na1U+DA==",
		"irma-demo.RU.studentCard had improper hash")
	require.Contains(t, conf.reverseHashes, "CLjnADMBYlFcuGOT7Z0xRg==",
		"irma-demo.MijnOverheid.root had improper hash")

	id := NewRequestorSchemeIdentifier("test-requestors")
	require.Contains(t, conf.RequestorSchemes, id)
	require.Equal(t, conf.Requestors["localhost"], conf.RequestorSchemes[id].requestors[0])
227
228
}

Sietse Ringers's avatar
Sietse Ringers committed
229
230
231
232
233
234
235
236
237
238
239
240
func TestInstallScheme(t *testing.T) {
	test.StartSchemeManagerHttpServer()
	defer test.StopSchemeManagerHttpServer()

	// setup a new empty Configuration
	storage, err := ioutil.TempDir("", "scheme")
	require.NoError(t, err)
	defer test.ClearTestStorage(t, storage)
	conf, err := NewConfiguration(storage, ConfigurationOptions{})
	require.NoError(t, err)
	require.NoError(t, conf.ParseFolder())

241
	// install test schemes from remote
242
243
	require.NoError(t, conf.DangerousTOFUInstallScheme(
		"http://localhost:48681/irma_configuration/test",
244
	))
245
246
247
248
249
250
251
252
	require.NoError(t, conf.DangerousTOFUInstallScheme(
		"http://localhost:48681/irma_configuration/test-requestors",
	))

	require.Contains(t, conf.SchemeManagers, NewSchemeManagerIdentifier("test"))
	require.Contains(t, conf.CredentialTypes, NewCredentialTypeIdentifier("test.test.email"))
	require.Contains(t, conf.RequestorSchemes, NewRequestorSchemeIdentifier("test-requestors"))
	require.Contains(t, conf.Requestors, "localhost")
253
254
255
256
257
258
259
260
261

	require.NoError(t, conf.DangerousTOFUInstallScheme(
		"http://localhost:48681/irma_configuration/irma-demo",
	))
	require.Contains(t, conf.SchemeManagers, NewSchemeManagerIdentifier("irma-demo"))
	require.Contains(t, conf.Issuers, NewIssuerIdentifier("irma-demo.MijnOverheid"))
	sk, err := conf.PrivateKeys.Get(NewIssuerIdentifier("irma-demo.MijnOverheid"), 2)
	require.NoError(t, err)
	require.NotNil(t, sk)
Sietse Ringers's avatar
Sietse Ringers committed
262
263
}

264
func TestMetadataAttribute(t *testing.T) {
265
	metadata := NewMetadataAttribute(0x02)
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
	if metadata.Version() != 0x02 {
		t.Errorf("Unexpected metadata version: %d", metadata.Version())
	}

	expiry := metadata.SigningDate().Unix() + int64(metadata.ValidityDuration()*ExpiryFactor)
	if !time.Unix(expiry, 0).Equal(metadata.Expiry()) {
		t.Errorf("Invalid signing date")
	}

	if metadata.KeyCounter() != 0 {
		t.Errorf("Unexpected key counter")
	}
}

func TestMetadataCompatibility(t *testing.T) {
281
	conf, err := NewConfiguration(filepath.Join("testdata", "irma_configuration"), ConfigurationOptions{ReadOnly: true})
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
	require.NoError(t, err)
	require.NoError(t, conf.ParseFolder())

	// An actual metadata attribute of an IRMA credential extracted from the IRMA app
	attr := MetadataFromInt(s2big("49043481832371145193140299771658227036446546573739245068"), conf)
	require.NotNil(t, attr.CredentialType(), "attr.CredentialType() should not be nil")

	require.Equal(t,
		NewCredentialTypeIdentifier("irma-demo.RU.studentCard"),
		attr.CredentialType().Identifier(),
		"Metadata credential type was not irma-demo.RU.studentCard",
	)
	require.Equal(t, byte(0x02), attr.Version(), "Unexpected metadata version")
	require.Equal(t, time.Unix(1499904000, 0), attr.SigningDate(), "Unexpected signing date")
	require.Equal(t, time.Unix(1516233600, 0), attr.Expiry(), "Unexpected expiry date")
297
	require.Equal(t, uint(2), attr.KeyCounter(), "Unexpected key counter")
298
299
300
301
302
303
304
305
306
307
308
309
310
}

func TestTimestamp(t *testing.T) {
	mytime := Timestamp(time.Unix(1500000000, 0))
	timestruct := struct{ Time *Timestamp }{Time: &mytime}
	bytes, err := json.Marshal(timestruct)
	require.NoError(t, err)

	timestruct = struct{ Time *Timestamp }{}
	require.NoError(t, json.Unmarshal(bytes, &timestruct))
	require.Equal(t, time.Time(*timestruct.Time).Unix(), int64(1500000000))
}

311
312
313
func TestVerifyValidSig(t *testing.T) {
	conf := parseConfiguration(t)

314
	irmaSignedMessageJson := "{\"signature\":[{\"c\":\"pliyrSE7wXcDcKXuBtZW5bnucvBSXpILIRvnNBgx7hQ=\",\"A\":\"D/8wLPq9860bpXZ5c+VYyoPJ+Z8CWDZNQ0jXvst8qnPRdivy/GQIfJHjVnpOPlHbguphb/7JVbfcV3bZeybA3bCF/4UesjRUZlMf/iJ/QgKHbt41ogN1PPT5z7qBJpkxuNTIkHxaUPoDvhouHmuC9pNj4afRUyLJerxKPkpdBw0=\",\"e_response\":\"YOrKTrMSs4/QOUtPkT0YaYNEmW7Cs+cu624zr2xrHodyL88ub6yaXB7MGHAcQ1+iXsGN8jkfxB/0\",\"v_response\":\"AYSa1p8ISs//MsocJjODwWuPB/z6+iKHHi+sTToRs0eJ2X1gwmWoA5QB0aHjRkWye3/+2rtosfUzI77FlPQVnrbMERwcuYM/fx3fpNCpjm2qcs3AOJRcSRxcNFMe1+4ECsmJhByMDutS1KXAAKiNvnhEXx9f0JrQGwQFtpSFPh8dOuvEKUZHAUALr4FcHCa2HL9nDRiqy2KAOxE0nAANAcMaBo/ed+WZeHtv4CTB7egyYs27cklVbwlBzmRrbjNZk57ICd0jVd6SZ2Ir93r/aPejkyhQ03xh9RVVyhOn4bkbjKIBzEybXTJAXgNmvd6F8Ds00srBZVWlo7Z23JZ7\",\"a_responses\":{\"0\":\"QHTznWWrECRNNmUNcy0yGu2L6qsZU6qkvaII8QB8QjbUxpwHzSeJWkzrn/Kk1KIowfoqB1DKGaFLATvuBl+bCoJjea+2VfK9Ns8=\",\"2\":\"H57Y9CTXJ5MAVo+aFfNSbmRMFQpraBIZVOXiRxCD/P7Aw4fW8r9P5l9pO9DTUeExaqFzsLyF5i5EridVWxlP2Wv0zbH8ku9Sg9w=\",\"3\":\"joggAmOhqM4QsKdoLHAfaslzXqJswS7MwZ/5+AKYdkMaHQ45biMdZU/6R+B7bjvsumg2f6KyTyg0G+BI+wVdJOjh3kGezdANB7Y=\",\"5\":\"5YP4A82WWeqc33e5Zg/Q8lqQQ1amLE8mOxMwCXb3N4J0UJRfV9lUFvbH1Q3Yb3YHAZpzGvhN/pBacwqktMkP4L71PnMldqA+nqA=\"},\"a_disclosed\":{\"1\":\"AgAJuwB+AALWy2qU9p3l52l9LU1rVT4M\",\"4\":\"NDU2\"}}],\"nonce\":\"Kg==\",\"context\":\"BTk=\",\"message\":\"I owe you everything\",\"timestamp\":{\"Time\":1527196489,\"ServerUrl\":\"https://metrics.privacybydesign.foundation/atum\",\"Sig\":{\"Alg\":\"ed25519\",\"Data\":\"ZV1qkvDrFK14QrUSC66xTNr9HitCOV4vwfGX0bh3iwY7qyHCi9rIOE97KY8CZifU5oLgVhFWy5E+ALR+gEpACw==\",\"PublicKey\":\"e/nMAJF7nwrvNZRpuJljNpRx+CsT7caaXyn9OX683R8=\"}}}"
315
	irmaSignedMessage := &SignedMessage{}
316
	err := json.Unmarshal([]byte(irmaSignedMessageJson), irmaSignedMessage)
317
	require.NoError(t, err)
318

319
	attrs, status, err := irmaSignedMessage.Verify(conf, nil)
320
	require.NoError(t, err)
321
	require.Equal(t, ProofStatusValid, status)
322
	require.Len(t, attrs, 1)
323
	require.Equal(t, "456", attrs[0][0].Value["en"])
324
325
326
327
328
}

func TestVerifyInValidSig(t *testing.T) {
	conf := parseConfiguration(t)

329
330
	// Same json as valid case, but has modified c
	irmaSignedMessageJson := "{\"signature\":[{\"c\":\"blablaE7wXcDcKXuBtZW5bnucvBSXpILIRvnNBgx7hQ=\",\"A\":\"D/8wLPq9860bpXZ5c+VYyoPJ+Z8CWDZNQ0jXvst8qnPRdivy/GQIfJHjVnpOPlHbguphb/7JVbfcV3bZeybA3bCF/4UesjRUZlMf/iJ/QgKHbt41ogN1PPT5z7qBJpkxuNTIkHxaUPoDvhouHmuC9pNj4afRUyLJerxKPkpdBw0=\",\"e_response\":\"YOrKTrMSs4/QOUtPkT0YaYNEmW7Cs+cu624zr2xrHodyL88ub6yaXB7MGHAcQ1+iXsGN8jkfxB/0\",\"v_response\":\"AYSa1p8ISs//MsocJjODwWuPB/z6+iKHHi+sTToRs0eJ2X1gwmWoA5QB0aHjRkWye3/+2rtosfUzI77FlPQVnrbMERwcuYM/fx3fpNCpjm2qcs3AOJRcSRxcNFMe1+4ECsmJhByMDutS1KXAAKiNvnhEXx9f0JrQGwQFtpSFPh8dOuvEKUZHAUALr4FcHCa2HL9nDRiqy2KAOxE0nAANAcMaBo/ed+WZeHtv4CTB7egyYs27cklVbwlBzmRrbjNZk57ICd0jVd6SZ2Ir93r/aPejkyhQ03xh9RVVyhOn4bkbjKIBzEybXTJAXgNmvd6F8Ds00srBZVWlo7Z23JZ7\",\"a_responses\":{\"0\":\"QHTznWWrECRNNmUNcy0yGu2L6qsZU6qkvaII8QB8QjbUxpwHzSeJWkzrn/Kk1KIowfoqB1DKGaFLATvuBl+bCoJjea+2VfK9Ns8=\",\"2\":\"H57Y9CTXJ5MAVo+aFfNSbmRMFQpraBIZVOXiRxCD/P7Aw4fW8r9P5l9pO9DTUeExaqFzsLyF5i5EridVWxlP2Wv0zbH8ku9Sg9w=\",\"3\":\"joggAmOhqM4QsKdoLHAfaslzXqJswS7MwZ/5+AKYdkMaHQ45biMdZU/6R+B7bjvsumg2f6KyTyg0G+BI+wVdJOjh3kGezdANB7Y=\",\"5\":\"5YP4A82WWeqc33e5Zg/Q8lqQQ1amLE8mOxMwCXb3N4J0UJRfV9lUFvbH1Q3Yb3YHAZpzGvhN/pBacwqktMkP4L71PnMldqA+nqA=\"},\"a_disclosed\":{\"1\":\"AgAJuwB+AALWy2qU9p3l52l9LU1rVT4M\",\"4\":\"NDU2\"}}],\"nonce\":\"Kg==\",\"context\":\"BTk=\",\"message\":\"I owe you everything\",\"timestamp\":{\"Time\":1527196489,\"ServerUrl\":\"https://metrics.privacybydesign.foundation/atum\",\"Sig\":{\"Alg\":\"ed25519\",\"Data\":\"ZV1qkvDrFK14QrUSC66xTNr9HitCOV4vwfGX0bh3iwY7qyHCi9rIOE97KY8CZifU5oLgVhFWy5E+ALR+gEpACw==\",\"PublicKey\":\"e/nMAJF7nwrvNZRpuJljNpRx+CsT7caaXyn9OX683R8=\"}}}"
331
	irmaSignedMessage := &SignedMessage{}
332
	err := json.Unmarshal([]byte(irmaSignedMessageJson), irmaSignedMessage)
333
	require.NoError(t, err)
334

335
	_, status, err := irmaSignedMessage.Verify(conf, nil)
336
	require.NoError(t, err)
337
	require.Equal(t, status, ProofStatusInvalid)
338
339
340
341
342
}

func TestVerifyInValidNonce(t *testing.T) {
	conf := parseConfiguration(t)

343
344
	// Same json as valid case, but with modified nonce
	irmaSignedMessageJson := "{\"signature\":[{\"c\":\"pliyrSE7wXcDcKXuBtZW5bnucvBSXpILIRvnNBgx7hQ=\",\"A\":\"D/8wLPq9860bpXZ5c+VYyoPJ+Z8CWDZNQ0jXvst8qnPRdivy/GQIfJHjVnpOPlHbguphb/7JVbfcV3bZeybA3bCF/4UesjRUZlMf/iJ/QgKHbt41ogN1PPT5z7qBJpkxuNTIkHxaUPoDvhouHmuC9pNj4afRUyLJerxKPkpdBw0=\",\"e_response\":\"YOrKTrMSs4/QOUtPkT0YaYNEmW7Cs+cu624zr2xrHodyL88ub6yaXB7MGHAcQ1+iXsGN8jkfxB/0\",\"v_response\":\"AYSa1p8ISs//MsocJjODwWuPB/z6+iKHHi+sTToRs0eJ2X1gwmWoA5QB0aHjRkWye3/+2rtosfUzI77FlPQVnrbMERwcuYM/fx3fpNCpjm2qcs3AOJRcSRxcNFMe1+4ECsmJhByMDutS1KXAAKiNvnhEXx9f0JrQGwQFtpSFPh8dOuvEKUZHAUALr4FcHCa2HL9nDRiqy2KAOxE0nAANAcMaBo/ed+WZeHtv4CTB7egyYs27cklVbwlBzmRrbjNZk57ICd0jVd6SZ2Ir93r/aPejkyhQ03xh9RVVyhOn4bkbjKIBzEybXTJAXgNmvd6F8Ds00srBZVWlo7Z23JZ7\",\"a_responses\":{\"0\":\"QHTznWWrECRNNmUNcy0yGu2L6qsZU6qkvaII8QB8QjbUxpwHzSeJWkzrn/Kk1KIowfoqB1DKGaFLATvuBl+bCoJjea+2VfK9Ns8=\",\"2\":\"H57Y9CTXJ5MAVo+aFfNSbmRMFQpraBIZVOXiRxCD/P7Aw4fW8r9P5l9pO9DTUeExaqFzsLyF5i5EridVWxlP2Wv0zbH8ku9Sg9w=\",\"3\":\"joggAmOhqM4QsKdoLHAfaslzXqJswS7MwZ/5+AKYdkMaHQ45biMdZU/6R+B7bjvsumg2f6KyTyg0G+BI+wVdJOjh3kGezdANB7Y=\",\"5\":\"5YP4A82WWeqc33e5Zg/Q8lqQQ1amLE8mOxMwCXb3N4J0UJRfV9lUFvbH1Q3Yb3YHAZpzGvhN/pBacwqktMkP4L71PnMldqA+nqA=\"},\"a_disclosed\":{\"1\":\"AgAJuwB+AALWy2qU9p3l52l9LU1rVT4M\",\"4\":\"NDU2\"}}],\"nonce\":\"aa==\",\"context\":\"BTk=\",\"message\":\"I owe you everything\",\"timestamp\":{\"Time\":1527196489,\"ServerUrl\":\"https://metrics.privacybydesign.foundation/atum\",\"Sig\":{\"Alg\":\"ed25519\",\"Data\":\"ZV1qkvDrFK14QrUSC66xTNr9HitCOV4vwfGX0bh3iwY7qyHCi9rIOE97KY8CZifU5oLgVhFWy5E+ALR+gEpACw==\",\"PublicKey\":\"e/nMAJF7nwrvNZRpuJljNpRx+CsT7caaXyn9OX683R8=\"}}}"
345
	irmaSignedMessage := &SignedMessage{}
346
	require.NoError(t, json.Unmarshal([]byte(irmaSignedMessageJson), irmaSignedMessage))
347

348
	_, status, err := irmaSignedMessage.Verify(conf, nil)
349
	require.NoError(t, err)
350
	require.Equal(t, status, ProofStatusInvalid)
351
}
352

353
354
355
356
357
358
func TestEmptySignature(t *testing.T) {
	msg := &SignedMessage{}
	_, status, _ := msg.Verify(&Configuration{}, nil)
	require.NotEqual(t, ProofStatusValid, status)
}

359
360
361
362
363
364
365
366
367
368
369
370
// Test attribute decoding with both old and new metadata versions
func TestAttributeDecoding(t *testing.T) {
	expected := "male"

	newAttribute, _ := new(big.Int).SetString("3670202571", 10)
	newString := decodeAttribute(newAttribute, 3)
	require.Equal(t, *newString, expected)

	oldAttribute, _ := new(big.Int).SetString("1835101285", 10)
	oldString := decodeAttribute(oldAttribute, 2)
	require.Equal(t, *oldString, expected)
}
371
372
373
374
375
376

func TestSessionRequests(t *testing.T) {
	attrval := "hello"
	sigMessage := "message to be signed"

	base := &DisclosureRequest{
377
		BaseRequest: BaseRequest{LDContext: LDContextDisclosureRequest},
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
		Disclose: AttributeConDisCon{
			AttributeDisCon{
				AttributeCon{NewAttributeRequest("irma-demo.MijnOverheid.ageLimits.over18")},
				AttributeCon{NewAttributeRequest("irma-demo.MijnOverheid.ageLimits.over21")},
			},
			AttributeDisCon{
				AttributeCon{AttributeRequest{Type: NewAttributeTypeIdentifier("irma-demo.MijnOverheid.fullName.firstname"), Value: &attrval}},
			},
		},
		Labels: map[int]TranslatedString{0: trivialTranslation("Age limit"), 1: trivialTranslation("First name")},
	}

	tests := []struct {
		oldJson, currentJson   string
		old, current, expected SessionRequest
	}{
		{
			expected: base,
			old:      &DisclosureRequest{},
			oldJson: `{
				"type": "disclosing",
				"content": [{
					"label": "Age limit",
					"attributes": [
						"irma-demo.MijnOverheid.ageLimits.over18",
						"irma-demo.MijnOverheid.ageLimits.over21"
					]
				},
				{
					"label": "First name",
					"attributes": {
						"irma-demo.MijnOverheid.fullName.firstname": "hello"
					}
				}]
			}`,
			current: &DisclosureRequest{},
			currentJson: `{
415
				"@context": "https://irma.app/ld/request/disclosure/v2",
416
417
418
419
420
421
422
423
424
425
				"disclose": [
					[
						[
							"irma-demo.MijnOverheid.ageLimits.over18"
						],
						[
							"irma-demo.MijnOverheid.ageLimits.over21"
						]
					],
					[
426
427
428
						[
							{ "type": "irma-demo.MijnOverheid.fullName.firstname", "value": "hello" }
						]
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
					]
				],
				"labels": {
					"0": {
						"en": "Age limit",
						"nl": "Age limit"
					},
					"1": {
						"en": "First name",
						"nl": "First name"
					}
				}
			}`,
		},

		{
			expected: &SignatureRequest{
446
				DisclosureRequest{BaseRequest{LDContext: LDContextSignatureRequest}, base.Disclose, base.Labels},
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
				sigMessage,
			},
			old: &SignatureRequest{},
			oldJson: `{
				"type": "signing",
				"message": "message to be signed",
				"content": [{
					"label": "Age limit",
					"attributes": [
						"irma-demo.MijnOverheid.ageLimits.over18",
						"irma-demo.MijnOverheid.ageLimits.over21"
					]
				},
				{
					"label": "First name",
					"attributes": {
						"irma-demo.MijnOverheid.fullName.firstname": "hello"
					}
				}]
			}`,
			current: &SignatureRequest{},
			currentJson: `{
469
				"@context": "https://irma.app/ld/request/signature/v2",
470
471
472
473
474
475
476
477
478
479
				"disclose": [
					[
						[
							"irma-demo.MijnOverheid.ageLimits.over18"
						],
						[
							"irma-demo.MijnOverheid.ageLimits.over21"
						]
					],
					[
480
481
482
						[
							{ "type": "irma-demo.MijnOverheid.fullName.firstname", "value": "hello" }
						]
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
					]
				],
				"labels": {
					"0": {
						"en": "Age limit",
						"nl": "Age limit"
					},
					"1": {
						"en": "First name",
						"nl": "First name"
					}
				},
				"message": "message to be signed"
			}`,
		},

		{
			expected: &IssuanceRequest{
501
				DisclosureRequest: DisclosureRequest{BaseRequest{LDContext: LDContextIssuanceRequest}, base.Disclose, base.Labels},
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
				Credentials: []*CredentialRequest{
					{
						CredentialTypeID: NewCredentialTypeIdentifier("irma-demo.MijnOverheid.root"),
						Attributes:       map[string]string{"BSN": "12345"},
					},
				},
			},
			old: &IssuanceRequest{},
			oldJson: `{
				"type": "issuing",
				"credentials": [{
					"credential": "irma-demo.MijnOverheid.root",
					"attributes": { "BSN": "12345" }
				}],
				"disclose": [{
					"label": "Age limit",
					"attributes": [
						"irma-demo.MijnOverheid.ageLimits.over18",
						"irma-demo.MijnOverheid.ageLimits.over21"
					]
				},
				{
					"label": "First name",
					"attributes": {
						"irma-demo.MijnOverheid.fullName.firstname": "hello"
					}
				}]
			}`,
			current: &IssuanceRequest{},
			currentJson: `{
532
				"@context": "https://irma.app/ld/request/issuance/v2",
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
				"credentials": [
					{
						"credential": "irma-demo.MijnOverheid.root",
						"attributes": {
							"BSN": "12345"
						}
					}
				],
				"disclose": [
					[
						[
							"irma-demo.MijnOverheid.ageLimits.over18"
						],
						[
							"irma-demo.MijnOverheid.ageLimits.over21"
						]
					],
					[
551
552
553
						[
							{ "type": "irma-demo.MijnOverheid.fullName.firstname", "value": "hello" }
						]
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
					]
				],
				"labels": {
					"0": {
						"en": "Age limit",
						"nl": "Age limit"
					},
					"1": {
						"en": "First name",
						"nl": "First name"
					}
				}
			}`,
		},
	}

	for _, tst := range tests {
		require.NoError(t, json.Unmarshal([]byte(tst.oldJson), tst.old))
		require.NoError(t, json.Unmarshal([]byte(tst.currentJson), tst.current))
573
574
		tst.old.Base().legacy = false // We don't care about this field differing, override it
		tst.old.Base().Type = ""      // same
575
576
		require.True(t, reflect.DeepEqual(tst.old, tst.expected), "Legacy %s did not unmarshal to expected value", reflect.TypeOf(tst.old).String())
		require.True(t, reflect.DeepEqual(tst.current, tst.expected), "%s did not unmarshal to expected value", reflect.TypeOf(tst.old).String())
577
578
579

		_, err := tst.expected.Legacy()
		require.NoError(t, err)
580
581
582
583
584
585
	}
}

func trivialTranslation(str string) TranslatedString {
	return TranslatedString{"en": str, "nl": str}
}
586
587
588
589
590
591
592
593
594
595

func TestConDisconSingletons(t *testing.T) {
	tests := []struct {
		attrs   AttributeConDisCon
		allowed bool
	}{
		{
			AttributeConDisCon{
				AttributeDisCon{
					AttributeCon{
596
597
						NewAttributeRequest("irma-demo.RU.studentCard.studentID"), // non singleton
						NewAttributeRequest("test.test.email.email"),              // non singleton
598
599
600
					},
				},
			},
601
			false, // multiple non-singletons in one inner conjunction is not allowed
602
603
604
605
606
607
		},
		{
			AttributeConDisCon{
				AttributeDisCon{
					AttributeCon{
						NewAttributeRequest("irma-demo.RU.studentCard.studentID"), // non singleton
608
						NewAttributeRequest("test.test.mijnirma.email"),           // singleton
609
610
611
612
613
614
615
616
617
618
					},
				},
			},
			true,
		},
		{
			AttributeConDisCon{
				AttributeDisCon{
					AttributeCon{
						NewAttributeRequest("irma-demo.MijnOverheid.root.BSN"), // singleton
619
						NewAttributeRequest("test.test.mijnirma.email"),        // singleton
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
					},
				},
			},
			true,
		},
	}

	conf := parseConfiguration(t)
	for _, args := range tests {
		if args.allowed {
			require.NoError(t, args.attrs.Validate(conf))
		} else {
			require.Error(t, args.attrs.Validate(conf))
		}
	}
}
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682

func parseDisclosure(t *testing.T) (*Configuration, *DisclosureRequest, *Disclosure) {
	conf := parseConfiguration(t)

	requestJson := `{"@context":"https://irma.app/ld/request/disclosure/v2","context":"AQ==","nonce":"zVQJMG6TKZwfcv5TExFVSQ==","protocolVersion":"2.5","disclose":[[["irma-demo.RU.studentCard.studentID"]]],"labels":{"0":null}}`
	dislosureJson := `{"proofs":[{"c":"o21UPItMKWXmXNhBKsCBHDWjfRoy+uDdbDB1yhhpg3k=","A":"Bl68Ut2nu2nwhIweU9QGoNd6TkjUIRbQ6SDg22m8PzMEgca0KA4/Oy1gaJCUHM3FFJ0Gdj0+6/VpcF85JyuQZou93UXXwzN/Y7ohUw+YxVTQ7WcJmZ/VGDh3SME5KJ9aWjGmq61J2LQiiDSq+XrcWFfKPwad6BkDhV2reo4yo68=","e_response":"VD0pWdeDkd3V+R3734xyRcGeWMMTzpB0ZiJhKMzv37DmHN6RpRzTF/0HroAsMIMz8mBWxYPVRBiw","v_response":"3OWsmIDM7v0ByEXax2YZGp3BnJ5nkCLMcT6/ENU0EcpjrOz+rT+NayQSLgMshxAATpgkgAluFQ3owOoQEL8ZAkZTWUDW5j+qy7GDFd22ZOKEZLWf8Q1XRK3x6exV9CIMkcBQrv5W6EI9XB5OKKNB3Z/VTALY3UW8cQQ0DPHj83YBEL3LJQDxwaxvQeHx4nysJjsEoLJE1KPBynXlfxpk17O3HTg+NuX5gj7+ckiHrmXgthJHvqCTnNpEORtXDJTmKJUccUiyWuftA36cIXIxW4N6I88T4BYctwN+T9NY+hcjYESITtxB+r2elB98bzlWgHF8ohpOkkJGuNjTFjw=","a_responses":{"0":"eDQA3Lrh2WC3o/VP6KD/uaMSRy/em3gEfuqXD9tVT+yJFYb7GT91lle5dB6lg235pUSHzYIOET7FYOHwb4/YSAGQiix0IzqFkLo=","2":"kT3kfcIaPy3UBYPX78X10w/R1Cb5rHqoW5OUd06xqC1V9MqVw3zhtc/nBgWmvVwTgJrl2CyuBjjoF10RJz/FEjYZ0JAF57uUXW8=","3":"4oSBcyUT6mOBhk/Szk/5G5QrgaAADW6wSl91hGwTTNDTIUiK01GE11JozbwDeZsLPoFikzikwkPu9ZsOAtOtb/+IcadB6NP0KXA=","5":"OwUSSCBb9NOMOYYSGSYCrdFUNLKJ/b2YP5LlElFG5r4GPR71zTQsZ4QuJiMIt9iFPRP6PQUvMvjWA59UTQ9AlwKc9JcQzbScYBM="},"a_disclosed":{"1":"AwAKOQIBAALWy2qU9p3l52l9LU1rVT4M","4":"aGpt"}}],"indices":[[{"cred":0,"attr":4}]]}`
	request := &DisclosureRequest{}
	require.NoError(t, json.Unmarshal([]byte(requestJson), request))
	disclosure := &Disclosure{}
	require.NoError(t, json.Unmarshal([]byte(dislosureJson), disclosure))

	return conf, request, disclosure
}

func TestVerify(t *testing.T) {
	t.Run("valid", func(t *testing.T) {
		conf, request, disclosure := parseDisclosure(t)
		attr, status, err := disclosure.Verify(conf, request)
		require.NoError(t, err)
		require.Equal(t, ProofStatusValid, status)
		require.Equal(t, "456", *attr[0][0].RawValue)
	})

	t.Run("invalid", func(t *testing.T) {
		conf, request, disclosure := parseDisclosure(t)
		disclosure.Proofs[0].(*gabi.ProofD).AResponses[0] = big.NewInt(100)
		_, status, err := disclosure.Verify(conf, request)
		require.NoError(t, err)
		require.Equal(t, ProofStatusInvalid, status)
	})

	t.Run("wrong attribute", func(t *testing.T) {
		conf, request, disclosure := parseDisclosure(t)
		request.Disclose[0][0][0].Type = NewAttributeTypeIdentifier("irma-demo.MijnOverheid.root.BSN")
		_, status, err := disclosure.Verify(conf, request)
		require.NoError(t, err)
		require.Equal(t, ProofStatusMissingAttributes, status)
	})

	t.Run("wrong nonce", func(t *testing.T) {
		conf, request, disclosure := parseDisclosure(t)
		request.Nonce = big.NewInt(100)
		_, status, err := disclosure.Verify(conf, request)
		require.NoError(t, err)
		require.Equal(t, ProofStatusInvalid, status)
	})
}
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747

var (
	revocationTestCred  = NewCredentialTypeIdentifier("irma-demo.MijnOverheid.root")
	revocationPkCounter = uint(2)
)

func TestRevocationMemoryStore(t *testing.T) {
	conf := parseConfiguration(t)
	db := conf.Revocation.memdb
	require.NotNil(t, db)

	// prepare key material
	sk, err := conf.Revocation.Keys.PrivateKey(revocationTestCred.IssuerIdentifier(), revocationPkCounter)
	require.NoError(t, err)
	pk, err := conf.Revocation.Keys.PublicKey(revocationTestCred.IssuerIdentifier(), revocationPkCounter)
	require.NoError(t, err)

	// construct initial update
	update, err := revocation.NewAccumulator(sk)
	require.NoError(t, err)

	// insert and retrieve it and check its validity
	db.Insert(revocationTestCred, update)
	retrieve(t, pk, db, 0, 0)

	// construct new update message with a few revocation events
	update = revokeMultiple(t, sk, update)
	oldupdate := *update // save a copy for below

	// insert it, retrieve it with a varying amount of events, verify
	db.Insert(revocationTestCred, update)
	retrieve(t, pk, db, 4, 3)

	// construct and test against a new update whose events have no overlap with that of our db
	update = revokeMultiple(t, sk, update)
	update.Events = update.Events[4:]
	require.Equal(t, uint64(4), update.Events[0].Index)
	db.Insert(revocationTestCred, update)
	retrieve(t, pk, db, 4, 6)

	// attempt to insert an update that is too new
	update = revokeMultiple(t, sk, update)
	update.Events = update.Events[5:]
	require.Equal(t, uint64(9), update.Events[0].Index)
	db.Insert(revocationTestCred, update)
	retrieve(t, pk, db, 4, 6)

	// attempt to insert an update that is too old
	db.Insert(revocationTestCred, &oldupdate)
	retrieve(t, pk, db, 4, 6)
}

func revokeMultiple(t *testing.T, sk *revocation.PrivateKey, update *revocation.Update) *revocation.Update {
	acc := update.SignedAccumulator.Accumulator
	event := update.Events[len(update.Events)-1]
	events := update.Events
	for i := 0; i < 3; i++ {
		acc, event = revoke(t, acc, event, sk)
		events = append(events, event)
	}
	update, err := revocation.NewUpdate(sk, acc, events)
	require.NoError(t, err)
	return update
}

748
func retrieve(t *testing.T, pk *revocation.PublicKey, db *memRevStorage, count uint64, expectedIndex uint64) {
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
	var updates map[uint]*revocation.Update
	var err error
	for i := uint64(0); i <= count; i++ {
		updates = db.Latest(revocationTestCred, i)
		require.Len(t, updates, 1)
		require.NotNil(t, updates[revocationPkCounter])
		require.Len(t, updates[revocationPkCounter].Events, int(i))
		_, err = updates[revocationPkCounter].Verify(pk)
		require.NoError(t, err)
	}
	sacc := db.SignedAccumulator(revocationTestCred, revocationPkCounter)
	acc, err := sacc.UnmarshalVerify(pk)
	require.NoError(t, err)
	require.Equal(t, expectedIndex, acc.Index)
}

func revoke(t *testing.T, acc *revocation.Accumulator, parent *revocation.Event, sk *revocation.PrivateKey) (*revocation.Accumulator, *revocation.Event) {
	e, err := rand.Prime(rand.Reader, 100)
	require.NoError(t, err)
	acc, event, err := acc.Remove(sk, big.Convert(e), parent)
	require.NoError(t, err)
	return acc, event
}
Sietse Ringers's avatar
Sietse Ringers committed
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816

func TestPrivateKeyRings(t *testing.T) {
	conf := parseConfiguration(t)
	mo := NewIssuerIdentifier("irma-demo.MijnOverheid")
	ru := NewIssuerIdentifier("irma-demo.RU")
	tst := NewIssuerIdentifier("test.test")

	schemering, err := newPrivateKeyRingScheme(conf)
	require.NoError(t, err)
	_, err = schemering.Get(mo, 2)
	require.NoError(t, err)
	_, err = schemering.Latest(mo)
	require.NoError(t, err)
	_, err = schemering.Get(ru, 2)
	require.Error(t, err) // not present in scheme
	_, err = schemering.Latest(ru)
	require.Error(t, err) // not present in scheme

	folderring, err := NewPrivateKeyRingFolder(filepath.Join(test.FindTestdataFolder(t), "privatekeys"), conf)
	require.NoError(t, err)
	_, err = folderring.Get(mo, 2)
	require.Error(t, err) // not present in folder
	_, err = folderring.Get(mo, 1)
	require.NoError(t, err) // present in both
	_, err = folderring.Get(ru, 2)
	require.NoError(t, err)
	_, err = folderring.Latest(ru)
	require.NoError(t, err)
	_, err = folderring.Get(tst, 3)
	require.NoError(t, err)
	_, err = folderring.Latest(tst)
	require.NoError(t, err)

	mergedring := privateKeyRingMerge{rings: []PrivateKeyRing{schemering, folderring}}
	_, err = mergedring.Get(mo, 1)
	require.NoError(t, err) // present in both
	_, err = mergedring.Get(mo, 2)
	require.NoError(t, err)
	_, err = mergedring.Latest(mo)
	require.NoError(t, err)
	_, err = mergedring.Get(ru, 2)
	require.NoError(t, err)
	_, err = mergedring.Latest(ru)
	require.NoError(t, err)
}
Sietse Ringers's avatar
Sietse Ringers committed
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922

// Helper functions for wizard tests below
func credid(s string) CredentialTypeIdentifier {
	return NewCredentialTypeIdentifier(s)
}
func credidptr(s string) *CredentialTypeIdentifier {
	id := credid(s)
	return &id
}
func credinfo(id string) *CredentialInfo {
	i := credid(id)
	return &CredentialInfo{
		SchemeManagerID: i.Root(),
		IssuerID:        i.IssuerIdentifier().Name(),
		ID:              i.Name(),
	}
}
func credtype(id string, deps ...string) *CredentialType {
	i := credid(id)
	d := CredentialDependencies{{{}}}
	for _, dep := range deps {
		d[0][0] = append(d[0][0], credid(dep))
	}
	return &CredentialType{
		SchemeManagerID: i.Root(),
		IssuerID:        i.IssuerIdentifier().Name(),
		ID:              i.Name(),
		Dependencies:    d,
	}
}
func credwizarditem(id string) IssueWizardItem {
	return IssueWizardItem{Type: IssueWizardItemTypeCredential, Credential: credidptr(id)}
}

func TestWizardDependencies(t *testing.T) {
	dependencies := CredentialDependencies{
		{
			{credid("a.a.a"), credid("a.a.b")},
			{credid("a.b.a")},
		},
		{
			{credid("b.a.a")},
			{credid("b.b.a"), credid("b.b.b")},
		},
	}

	wizardcontents := dependencies.WizardContents()
	require.Equal(t,
		IssueWizardContents{
			{
				{credwizarditem("a.a.a"), credwizarditem("a.a.b")},
				{credwizarditem("a.b.a")},
			},
			{
				{credwizarditem("b.a.a")},
				{credwizarditem("b.b.a"), credwizarditem("b.b.b")},
			},
		},
		wizardcontents,
	)

	conf := &Configuration{CredentialTypes: map[CredentialTypeIdentifier]*CredentialType{}}
	for _, discon := range dependencies {
		for _, con := range discon {
			for _, cred := range con {
				conf.CredentialTypes[cred] = credtype(cred.String())
			}
		}
	}
	tests := []struct {
		creds  map[CredentialTypeIdentifier]struct{}
		wizard []IssueWizardItem
	}{
		{
			creds: nil,
			wizard: []IssueWizardItem{
				credwizarditem("a.a.a"), credwizarditem("a.a.b"), credwizarditem("b.a.a"),
			},
		},
		{
			creds: map[CredentialTypeIdentifier]struct{}{credid("a.a.a"): {}},
			wizard: []IssueWizardItem{
				credwizarditem("a.a.a"), credwizarditem("a.a.b"), credwizarditem("b.a.a"),
			},
		},
		{
			creds: map[CredentialTypeIdentifier]struct{}{credid("a.b.a"): {}},
			wizard: []IssueWizardItem{
				credwizarditem("a.b.a"), credwizarditem("b.a.a"),
			},
		},
		{
			creds: map[CredentialTypeIdentifier]struct{}{credid("b.b.a"): {}},
			wizard: []IssueWizardItem{
				credwizarditem("a.a.a"), credwizarditem("a.a.b"), credwizarditem("b.a.a"),
			},
		},
		{
			creds: map[CredentialTypeIdentifier]struct{}{credid("b.b.a"): {}, credid("b.b.b"): {}},
			wizard: []IssueWizardItem{
				credwizarditem("a.a.a"), credwizarditem("a.a.b"), credwizarditem("b.b.a"), credwizarditem("b.b.b"),
			},
		},
	}

	for _, tst := range tests {
923
		require.Equal(t, tst.wizard, wizardcontents.ChoosePath(conf, tst.creds))
Sietse Ringers's avatar
Sietse Ringers committed
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
	}
}

func TestWizardConstructed(t *testing.T) {
	conf := &Configuration{
		CredentialTypes: map[CredentialTypeIdentifier]*CredentialType{
			credid("scheme.issuer.a"): credtype("scheme.issuer.a"),
			credid("scheme.issuer.b"): credtype("scheme.issuer.b",
				"scheme.issuer.a",
			),
			credid("scheme.issuer.c"): credtype("scheme.issuer.c",
				"scheme.issuer.a", "scheme.issuer.b",
			),
			credid("scheme.issuer.d"): credtype("scheme.issuer.d",
				"scheme.issuer.a",
			),
			credid("scheme.issuer.e"): credtype("scheme.issuer.e",
				"scheme.issuer.d",
			),
		},
	}

	wizard := IssueWizard{
947
		ID: NewIssueWizardIdentifier("test-requestors.test-requestor.testwizard"),
Sietse Ringers's avatar
Sietse Ringers committed
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
		Contents: IssueWizardContents{
			{{
				credwizarditem("scheme.issuer.c"),
			}},
			{{{
				Type:       IssueWizardItemTypeCredential,
				Credential: credidptr("scheme.issuer.e"),
				Text:       &TranslatedString{"en": "custom description of credential e"},
			}}},
			{{{
				Type: IssueWizardItemTypeWebsite,
				URL:  &TranslatedString{"en": "https://example.com"},
			}}},
		},
	}

964
	contents, err := wizard.Path(conf, nil)
Sietse Ringers's avatar
Sietse Ringers committed
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
	require.NoError(t, err)
	require.Equal(t,
		[]IssueWizardItem{
			credwizarditem("scheme.issuer.a"),
			credwizarditem("scheme.issuer.b"),
			credwizarditem("scheme.issuer.d"),
			credwizarditem("scheme.issuer.c"),
			wizard.Contents[1][0][0],
			wizard.Contents[2][0][0],
		},
		contents,
	)
}

func TestWizardFromScheme(t *testing.T) {
	conf := parseConfiguration(t)
981
982
	id := NewIssueWizardIdentifier("test-requestors.test-requestor.testwizard")
	wizard := conf.Requestors["localhost"].Wizards[id]
Sietse Ringers's avatar
Sietse Ringers committed
983
984
985

	var expected []IssueWizardItem
	require.NoError(t, json.Unmarshal(
986
		[]byte(`[{"type":"credential","credential":"irma-demo.MijnOverheid.fullName","header":{"en":"Full name","nl":"Volledige naam"},"text":{"en":"Lorem ipsum dolor sit amet, consectetur adipiscing elit.","nl":"Lorem ipsum dolor sit amet, consectetur adipiscing elit."},"label":{"en":"Get name data","nl":"Haal naamgegevens op"}},{"type":"credential","credential":"irma-demo.MijnOverheid.singleton","text":{"en":"Lorem ipsum dolor sit amet, consectetur adipiscing elit.","nl":"Lorem ipsum dolor sit amet, consectetur adipiscing elit."}},{"type":"session","credential":"irma-demo.RU.studentCard","header":{"en":"Student Card","nl":"Studentpas"},"text":{"en":"Lorem ipsum dolor sit amet, consectetur adipiscing elit.","nl":"Lorem ipsum dolor sit amet, consectetur adipiscing elit."},"label":{"en":"Get Student Card","nl":"Haal studentpas op"},"sessionUrl":"https://example.com/getsession"},{"type":"website","credential":"irma-demo.stemmen.stempas","header":{"en":"Voting Card","nl":"Stempas"},"text":{"en":"Lorem ipsum dolor sit amet, consectetur adipiscing elit.","nl":"Lorem ipsum dolor sit amet, consectetur adipiscing elit."},"label":{"en":"Get Voting Card","nl":"Haal stempas op"},"url":{"en":"https://example.com/en","nl":"https://example.com/nl"},"inapp":true}]`),
Sietse Ringers's avatar
Sietse Ringers committed
987
988
989
		&expected,
	))

990
	contents, err := wizard.Path(conf, nil)
Sietse Ringers's avatar
Sietse Ringers committed
991
992
993
994
995
	require.NoError(t, err)
	require.Equal(t, expected, contents)

	True := true
	wizard.ExpandDependencies = &True
996
	contents, err = wizard.Path(conf, nil)
Sietse Ringers's avatar
Sietse Ringers committed
997
998
999
1000
	require.NoError(t, err)
	require.Equal(t,
		append([]IssueWizardItem{credwizarditem("irma-demo.MijnOverheid.root")}, expected...),
		contents,
For faster browsing, not all history is shown. View entire blame