irmaclient_test.go 14.7 KB
Newer Older
Sietse Ringers's avatar
Sietse Ringers committed
1
2
3
package irmaclient

import (
4
	"encoding/json"
Sietse Ringers's avatar
Sietse Ringers committed
5
6
7
8
	"math/big"
	"os"
	"testing"

9
	"github.com/mhe/gabi"
10
11
	"github.com/privacybydesign/irmago"
	"github.com/privacybydesign/irmago/internal/fs"
12
	"github.com/privacybydesign/irmago/internal/test"
Sietse Ringers's avatar
Sietse Ringers committed
13
14
15
16
	"github.com/stretchr/testify/require"
)

func TestMain(m *testing.M) {
17
	// Create HTTP server for scheme managers
18
	test.StartSchemeManagerHttpServer()
19

20
21
	test.ClearTestStorage(nil)
	test.CreateTestStorage(nil)
22
	retCode := m.Run()
23
	test.ClearTestStorage(nil)
24

25
	test.StopSchemeManagerHttpServer()
Sietse Ringers's avatar
Sietse Ringers committed
26
27
28
29
	os.Exit(retCode)
}

func parseStorage(t *testing.T) *Client {
30
	require.NoError(t, fs.CopyDirectory("../testdata/teststorage", "../testdata/storage/test"))
31
	manager, err := New(
32
33
		"../testdata/storage/test",
		"../testdata/irma_configuration",
34
		"",
35
		&TestClientHandler{t: t},
Sietse Ringers's avatar
Sietse Ringers committed
36
37
38
39
40
	)
	require.NoError(t, err)
	return manager
}

Sietse Ringers's avatar
Sietse Ringers committed
41
func verifyClientIsUnmarshaled(t *testing.T, client *Client) {
42
	cred, err := client.credential(irma.NewCredentialTypeIdentifier("irma-demo.RU.studentCard"), 0)
Sietse Ringers's avatar
Sietse Ringers committed
43
44
45
46
	require.NoError(t, err, "could not fetch credential")
	require.NotNil(t, cred, "Credential should exist")
	require.NotNil(t, cred.Attributes[0], "Metadata attribute of irma-demo.RU.studentCard should not be nil")

47
	cred, err = client.credential(irma.NewCredentialTypeIdentifier("test.test.mijnirma"), 0)
Sietse Ringers's avatar
Sietse Ringers committed
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
	require.NoError(t, err, "could not fetch credential")
	require.NotNil(t, cred, "Credential should exist")
	require.NotNil(t, cred.Signature.KeyshareP)

	require.NotEmpty(t, client.CredentialInfoList())

	pk, err := cred.PublicKey()
	require.NoError(t, err)
	require.True(t,
		cred.Signature.Verify(pk, cred.Attributes),
		"Credential should be valid",
	)
}

func verifyCredentials(t *testing.T, client *Client) {
	var pk *gabi.PublicKey
64
65
66
67
	for credtype, credsmap := range client.attributes {
		for index, attrs := range credsmap {
			cred, err := client.credential(attrs.CredentialType().Identifier(), index)
			require.NoError(t, err)
Sietse Ringers's avatar
Sietse Ringers committed
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
			pk, err = cred.PublicKey()
			require.NoError(t, err)
			require.True(t,
				cred.Credential.Signature.Verify(pk, cred.Attributes),
				"Credential %s-%d was invalid", credtype.String(), index,
			)
			require.Equal(t, cred.Attributes[0], client.secretkey.Key,
				"Secret key of credential %s-%d unequal to main secret key",
				cred.CredentialType().Identifier().String(), index,
			)
		}
	}
}

func verifyPaillierKey(t *testing.T, PrivateKey *paillierPrivateKey) {
	require.NotNil(t, PrivateKey)
	require.NotNil(t, PrivateKey.L)
	require.NotNil(t, PrivateKey.U)
	require.NotNil(t, PrivateKey.PublicKey.N)

	require.Equal(t, big.NewInt(1), new(big.Int).Exp(big.NewInt(2), PrivateKey.L, PrivateKey.N))
	require.Equal(t, PrivateKey.NSquared, new(big.Int).Exp(PrivateKey.N, big.NewInt(2), nil))

	plaintext := "Hello Paillier!"
	ciphertext, err := PrivateKey.Encrypt([]byte(plaintext))
	require.NoError(t, err)
	decrypted, err := PrivateKey.Decrypt(ciphertext)
	require.NoError(t, err)
	require.Equal(t, plaintext, string(decrypted))
}

func verifyKeyshareIsUnmarshaled(t *testing.T, client *Client) {
	require.NotNil(t, client.paillierKeyCache)
	require.NotNil(t, client.keyshareServers)
102
103
104
	testManager := irma.NewSchemeManagerIdentifier("test")
	require.Contains(t, client.keyshareServers, testManager)
	kss := client.keyshareServers[testManager]
Sietse Ringers's avatar
Sietse Ringers committed
105
106
107
108
109
110
	require.NotEmpty(t, kss.Nonce)

	verifyPaillierKey(t, kss.PrivateKey)
	verifyPaillierKey(t, client.paillierKeyCache)
}

111
func TestStorageDeserialization(t *testing.T) {
Sietse Ringers's avatar
Sietse Ringers committed
112
	client := parseStorage(t)
Sietse Ringers's avatar
Sietse Ringers committed
113
	verifyClientIsUnmarshaled(t, client)
Sietse Ringers's avatar
Sietse Ringers committed
114
115
116
	verifyCredentials(t, client)
	verifyKeyshareIsUnmarshaled(t, client)

117
	test.ClearTestStorage(t)
Sietse Ringers's avatar
Sietse Ringers committed
118
119
}

120
func TestLogging(t *testing.T) {
Sietse Ringers's avatar
Sietse Ringers committed
121
122
123
	client := parseStorage(t)

	logs, err := client.Logs()
124
	oldLogLength := len(logs)
Sietse Ringers's avatar
Sietse Ringers committed
125
	require.NoError(t, err)
126
	attrid := irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.studentID")
127

128
129
	// Do issuance session
	jwt := getCombinedJwt("testip", attrid)
Sietse Ringers's avatar
Sietse Ringers committed
130
131
	sessionHelper(t, jwt, "issue", client)

132
	logs, err = client.Logs()
Sietse Ringers's avatar
Sietse Ringers committed
133
	require.NoError(t, err)
134
	require.True(t, len(logs) == oldLogLength+1)
Sietse Ringers's avatar
Sietse Ringers committed
135

136
	entry := logs[len(logs)-1]
Sietse Ringers's avatar
Sietse Ringers committed
137
	require.NotNil(t, entry)
138
	require.Equal(t, "testip", entry.Request.GetRequestorName())
Sietse Ringers's avatar
Sietse Ringers committed
139
	require.NoError(t, err)
140
141
142
	issued, err := entry.GetIssuedCredentials(client.Configuration)
	require.NoError(t, err)
	require.NotNil(t, issued)
Tomas's avatar
Tomas committed
143
	disclosed, err := entry.GetDisclosedCredentials(client.Configuration)
Sietse Ringers's avatar
Sietse Ringers committed
144
	require.NoError(t, err)
Tomas's avatar
Tomas committed
145
146
	require.NotEmpty(t, disclosed)

147
148
	// Do disclosure session
	jwt = getDisclosureJwt("testsp", attrid)
Tomas's avatar
Tomas committed
149
150
151
152
153
154
155
	sessionHelper(t, jwt, "verification", client)
	logs, err = client.Logs()
	require.NoError(t, err)
	require.True(t, len(logs) == oldLogLength+2)

	entry = logs[len(logs)-1]
	require.NotNil(t, entry)
156
	require.Equal(t, "testsp", entry.Request.GetRequestorName())
Tomas's avatar
Tomas committed
157
158
159
160
	require.NoError(t, err)
	disclosed, err = entry.GetDisclosedCredentials(client.Configuration)
	require.NoError(t, err)
	require.NotEmpty(t, disclosed)
Sietse Ringers's avatar
Sietse Ringers committed
161

162
163
164
165
166
167
168
169
	// Do signature session
	jwt = getSigningJwt("testsigclient", attrid)
	sessionHelper(t, jwt, "signature", client)
	logs, err = client.Logs()
	require.NoError(t, err)
	require.True(t, len(logs) == oldLogLength+3)
	entry = logs[len(logs)-1]
	require.NotNil(t, entry)
170
	require.Equal(t, "testsigclient", entry.Request.GetRequestorName())
171
172
173
174
	require.NoError(t, err)
	sig, err := entry.GetSignedMessage()
	require.NoError(t, err)
	require.NotNil(t, sig)
175
	status, list := sig.VerifyWithoutRequest(client.Configuration)
176
	require.Equal(t, irma.ProofStatusValid, status)
177
178
179
180
	require.NotEmpty(t, list)
	require.Contains(t, list[0].Attributes, attrid)
	require.Equal(t, "s1234567", list[0].Attributes[attrid]["en"])

181
	test.ClearTestStorage(t)
Sietse Ringers's avatar
Sietse Ringers committed
182
183
}

184
185
186
// TestCandidates tests the correctness of the function of the client that, given a disjunction of attributes
// requested by the verifier, calculates a list of candidate attributes contained by the client that would
// satisfy the attribute disjunction.
Sietse Ringers's avatar
Sietse Ringers committed
187
188
189
func TestCandidates(t *testing.T) {
	client := parseStorage(t)

190
	// client contains one instance of the studentCard credential, whose studentID attribute is 456.
191
	attrtype := irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.studentID")
192
193

	// If the disjunction contains no required values at all, then our attribute is a candidate
194
195
	disjunction := &irma.AttributeDisjunction{
		Attributes: []irma.AttributeTypeIdentifier{attrtype},
Sietse Ringers's avatar
Sietse Ringers committed
196
197
198
199
	}
	attrs := client.Candidates(disjunction)
	require.NotNil(t, attrs)
	require.Len(t, attrs, 1)
200
201
	require.NotNil(t, attrs[0])
	require.Equal(t, attrs[0].Type, attrtype)
Sietse Ringers's avatar
Sietse Ringers committed
202

203
204
205
	// If the disjunction requires our attribute to have 456 as value, which it does,
	// then our attribute is a candidate
	reqval := "456"
206
207
	disjunction = &irma.AttributeDisjunction{
		Attributes: []irma.AttributeTypeIdentifier{attrtype},
208
		Values:     map[irma.AttributeTypeIdentifier]*string{attrtype: &reqval},
Sietse Ringers's avatar
Sietse Ringers committed
209
210
211
212
	}
	attrs = client.Candidates(disjunction)
	require.NotNil(t, attrs)
	require.Len(t, attrs, 1)
213
214
	require.NotNil(t, attrs[0])
	require.Equal(t, attrs[0].Type, attrtype)
Sietse Ringers's avatar
Sietse Ringers committed
215

216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
	// If the disjunction requires our attribute to have a different value than it does,
	// then it is NOT a match.
	reqval = "foobarbaz"
	disjunction.Values[attrtype] = &reqval
	attrs = client.Candidates(disjunction)
	require.NotNil(t, attrs)
	require.Empty(t, attrs)

	// A required value of nil counts as no requirement on the value, so our attribute is a candidate
	disjunction.Values[attrtype] = nil
	attrs = client.Candidates(disjunction)
	require.NotNil(t, attrs)
	require.Len(t, attrs, 1)
	require.NotNil(t, attrs[0])
	require.Equal(t, attrs[0].Type, attrtype)

	// This test should be equivalent to the one above
	disjunction = &irma.AttributeDisjunction{}
	json.Unmarshal([]byte(`{"attributes":{"irma-demo.RU.studentCard.studentID":null}}`), &disjunction)
Sietse Ringers's avatar
Sietse Ringers committed
235
236
	attrs = client.Candidates(disjunction)
	require.NotNil(t, attrs)
237
238
239
240
241
242
243
244
245
	require.Len(t, attrs, 1)
	require.NotNil(t, attrs[0])
	require.Equal(t, attrs[0].Type, attrtype)

	// A required value of null counts as no requirement on the value, but we must still satisfy the disjunction
	// We do not have an instance of this attribute so we have no candidate
	disjunction = &irma.AttributeDisjunction{}
	json.Unmarshal([]byte(`{"attributes":{"irma-demo.MijnOverheid.ageLower.over12":null}}`), &disjunction)
	attrs = client.Candidates(disjunction)
Sietse Ringers's avatar
Sietse Ringers committed
246
247
	require.Empty(t, attrs)

248
	test.ClearTestStorage(t)
Sietse Ringers's avatar
Sietse Ringers committed
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
}

func TestPaillier(t *testing.T) {
	client := parseStorage(t)

	challenge, _ := gabi.RandomBigInt(256)
	comm, _ := gabi.RandomBigInt(1000)
	resp, _ := gabi.RandomBigInt(1000)

	sk := client.paillierKey(true)
	bytes, err := sk.Encrypt(challenge.Bytes())
	require.NoError(t, err)
	cipher := new(big.Int).SetBytes(bytes)

	bytes, err = sk.Encrypt(comm.Bytes())
	require.NoError(t, err)
	commcipher := new(big.Int).SetBytes(bytes)

	// [[ c ]]^resp * [[ comm ]]
	cipher.Exp(cipher, resp, sk.NSquared).Mul(cipher, commcipher).Mod(cipher, sk.NSquared)

	bytes, err = sk.Decrypt(cipher.Bytes())
	require.NoError(t, err)
	plaintext := new(big.Int).SetBytes(bytes)
	expected := new(big.Int).Set(challenge)
	expected.Mul(expected, resp).Add(expected, comm)

	require.Equal(t, plaintext, expected)

278
	test.ClearTestStorage(t)
Sietse Ringers's avatar
Sietse Ringers committed
279
280
281
282
}

func TestCredentialRemoval(t *testing.T) {
	client := parseStorage(t)
283

284
285
	id := irma.NewCredentialTypeIdentifier("irma-demo.RU.studentCard")
	id2 := irma.NewCredentialTypeIdentifier("test.test.mijnirma")
Sietse Ringers's avatar
Sietse Ringers committed
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304

	cred, err := client.credential(id, 0)
	require.NoError(t, err)
	require.NotNil(t, cred)
	err = client.RemoveCredentialByHash(cred.AttributeList().Hash())
	require.NoError(t, err)
	cred, err = client.credential(id, 0)
	require.NoError(t, err)
	require.Nil(t, cred)

	cred, err = client.credential(id2, 0)
	require.NoError(t, err)
	require.NotNil(t, cred)
	err = client.RemoveCredential(id2, 0)
	require.NoError(t, err)
	cred, err = client.credential(id2, 0)
	require.NoError(t, err)
	require.Nil(t, cred)

305
	test.ClearTestStorage(t)
Sietse Ringers's avatar
Sietse Ringers committed
306
307
}

308
309
310
311
312
func TestWrongSchemeManager(t *testing.T) {
	client := parseStorage(t)

	irmademo := irma.NewSchemeManagerIdentifier("irma-demo")
	require.Contains(t, client.Configuration.SchemeManagers, irmademo)
313
	require.NoError(t, os.Remove("../testdata/storage/test/irma_configuration/irma-demo/index"))
314
315
316
317
318

	err := client.Configuration.ParseFolder()
	_, ok := err.(*irma.SchemeManagerError)
	require.True(t, ok)
	require.Contains(t, client.Configuration.DisabledSchemeManagers, irmademo)
319
320
321
322
323
	require.Contains(t, client.Configuration.SchemeManagers, irmademo)
	require.NotEqual(t,
		client.Configuration.SchemeManagers[irmademo].Status,
		irma.SchemeManagerStatusValid,
	)
324

325
	test.ClearTestStorage(t)
326
327
}

328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
func TestDisclosureNewAttributeUpdateSchemeManager(t *testing.T) {
	client := parseStorage(t)

	schemeid := irma.NewSchemeManagerIdentifier("irma-demo")
	credid := irma.NewCredentialTypeIdentifier("irma-demo.RU.studentCard")
	attrid := irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.newAttribute")
	require.False(t, client.Configuration.CredentialTypes[credid].ContainsAttribute(attrid))

	client.Configuration.SchemeManagers[schemeid].URL = "http://localhost:48681/irma_configuration_updated/irma-demo"
	disclosureRequest := irma.DisclosureRequest{
		Content: irma.AttributeDisjunctionList{
			&irma.AttributeDisjunction{
				Label: "foo",
				Attributes: []irma.AttributeTypeIdentifier{
					attrid,
				},
			},
		},
	}

	client.Configuration.Download(&disclosureRequest)
	require.True(t, client.Configuration.CredentialTypes[credid].ContainsAttribute(attrid))
350
351

	test.ClearTestStorage(t)
352
353
354
355
356
357
358
359
360
361
362
363
364
365
}

func TestIssueNewAttributeUpdateSchemeManager(t *testing.T) {
	client := parseStorage(t)
	schemeid := irma.NewSchemeManagerIdentifier("irma-demo")
	credid := irma.NewCredentialTypeIdentifier("irma-demo.RU.studentCard")
	attrid := irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.newAttribute")
	require.False(t, client.Configuration.CredentialTypes[credid].ContainsAttribute(attrid))

	client.Configuration.SchemeManagers[schemeid].URL = "http://localhost:48681/irma_configuration_updated/irma-demo"
	issuanceRequest := getIssuanceRequest(true)
	issuanceRequest.Credentials[0].Attributes["newAttribute"] = "foobar"
	client.Configuration.Download(issuanceRequest)
	require.True(t, client.Configuration.CredentialTypes[credid].ContainsAttribute(attrid))
366
367

	test.ClearTestStorage(t)
368
369
370
371
372
373
374
}

func TestIssueOptionalAttributeUpdateSchemeManager(t *testing.T) {
	client := parseStorage(t)
	schemeid := irma.NewSchemeManagerIdentifier("irma-demo")
	credid := irma.NewCredentialTypeIdentifier("irma-demo.RU.studentCard")
	attrid := irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.level")
375
	require.False(t, client.Configuration.CredentialTypes[credid].AttributeType(attrid).IsOptional())
376
377
378
379
380

	client.Configuration.SchemeManagers[schemeid].URL = "http://localhost:48681/irma_configuration_updated/irma-demo"
	issuanceRequest := getIssuanceRequest(true)
	delete(issuanceRequest.Credentials[0].Attributes, "level")
	client.Configuration.Download(issuanceRequest)
381
	require.True(t, client.Configuration.CredentialTypes[credid].AttributeType(attrid).IsOptional())
382
383

	test.ClearTestStorage(t)
384
385
}

386
387
388
// Test installing a new scheme manager from a qr, and do a(n issuance) session
// within this manager to test the autmatic downloading of credential definitions,
// issuers, and public keys.
Sietse Ringers's avatar
Sietse Ringers committed
389
390
391
func TestDownloadSchemeManager(t *testing.T) {
	client := parseStorage(t)

392
393
394
	// Remove irma-demo scheme manager as we need to test adding it
	irmademo := irma.NewSchemeManagerIdentifier("irma-demo")
	require.Contains(t, client.Configuration.SchemeManagers, irmademo)
395
	require.NoError(t, client.Configuration.RemoveSchemeManager(irmademo, true))
396
397
398
	require.NotContains(t, client.Configuration.SchemeManagers, irmademo)

	// Do an add-scheme-manager-session
399
400
	c := make(chan *irma.SessionError)
	qr, err := json.Marshal(&irma.SchemeManagerRequest{
401
		Type: irma.ActionSchemeManager,
402
		URL:  "http://localhost:48681/irma_configuration/irma-demo",
403
404
405
	})
	require.NoError(t, err)
	client.NewSession(string(qr), TestHandler{t, c, client})
406
407
408
409
	if err := <-c; err != nil {
		t.Fatal(*err)
	}
	require.Contains(t, client.Configuration.SchemeManagers, irmademo)
Sietse Ringers's avatar
Sietse Ringers committed
410

411
	// Do a session to test downloading of cred types, issuers and keys
412
	jwt := getCombinedJwt("testip", irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.studentID"))
Sietse Ringers's avatar
Sietse Ringers committed
413
414
	sessionHelper(t, jwt, "issue", client)

415
416
417
418
	require.Contains(t, client.Configuration.SchemeManagers, irmademo)
	require.Contains(t, client.Configuration.Issuers, irma.NewIssuerIdentifier("irma-demo.RU"))
	require.Contains(t, client.Configuration.CredentialTypes, irma.NewCredentialTypeIdentifier("irma-demo.RU.studentCard"))

419
	basepath := "../testdata/storage/test/irma_configuration/irma-demo"
420
421
422
423
424
425
426
427
428
429
	exists, err := fs.PathExists(basepath + "/description.xml")
	require.NoError(t, err)
	require.True(t, exists)
	exists, err = fs.PathExists(basepath + "/RU/description.xml")
	require.NoError(t, err)
	require.True(t, exists)
	exists, err = fs.PathExists(basepath + "/RU/Issues/studentCard/description.xml")
	require.NoError(t, err)
	require.True(t, exists)

430
	test.ClearTestStorage(t)
Sietse Ringers's avatar
Sietse Ringers committed
431
}