irmaclient_test.go 12.2 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
	"math/big"
	"os"
	"testing"
8
	"errors"
Sietse Ringers's avatar
Sietse Ringers committed
9

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

func TestMain(m *testing.M) {
18
19
	test.ClearTestStorage(nil)
	test.CreateTestStorage(nil)
20
	retCode := m.Run()
21
	test.ClearTestStorage(nil)
Sietse Ringers's avatar
Sietse Ringers committed
22
23
24
	os.Exit(retCode)
}

25
26
27
28
type TestClientHandler struct {
	t *testing.T
	c chan error
}
Sietse Ringers's avatar
Sietse Ringers committed
29

30
31
32
33
34
35
36
37
func (i *TestClientHandler) UpdateConfiguration(new *irma.IrmaIdentifierSet) {}
func (i *TestClientHandler) UpdateAttributes()                               {}
func (i *TestClientHandler) EnrollmentSuccess(manager irma.SchemeManagerIdentifier) {
	select {
	case i.c <- nil: // nop
	default: // nop
	}
}
Tomas's avatar
Tomas committed
38
func (i *TestClientHandler) EnrollmentFailure(manager irma.SchemeManagerIdentifier, err error) {
39
40
41
42
43
44
	select {
	case i.c <- err: // nop
	default:
		i.t.Fatal(err)
	}
}
45
func (i *TestClientHandler) ChangePinSuccess(manager irma.SchemeManagerIdentifier) {
46
47
48
49
50
	select {
	case i.c <- nil: // nop
	default: // nop
	}
}
51
func (i *TestClientHandler) ChangePinFailure(manager irma.SchemeManagerIdentifier, err error) {
52
53
54
55
56
57
	select {
	case i.c <- err: //nop
	default:
		i.t.Fatal(err)
	}
}
58
func (i *TestClientHandler) ChangePinIncorrect(manager irma.SchemeManagerIdentifier, message string) {
59
60
61
62
63
64
65
	err := errors.New("incorrect pin")
	select {
	case i.c <- err: //nop
	default:
		i.t.Fatal(err)
	}
}
66
67
68
69
70
71
72
73
func (i *TestClientHandler) ChangePinBlocked(manager irma.SchemeManagerIdentifier, message string) {
	err := errors.New("blocked account")
	select {
	case i.c <- err: //nop
	default:
		i.t.Fatal(err)
	}
}
Sietse Ringers's avatar
Sietse Ringers committed
74
75

func parseStorage(t *testing.T) *Client {
76
	require.NoError(t, fs.CopyDirectory("../testdata/teststorage", "../testdata/storage/test"))
77
	manager, err := New(
78
79
		"../testdata/storage/test",
		"../testdata/irma_configuration",
80
		"",
81
		&TestClientHandler{t: t},
Sietse Ringers's avatar
Sietse Ringers committed
82
83
84
85
86
	)
	require.NoError(t, err)
	return manager
}

Sietse Ringers's avatar
Sietse Ringers committed
87
func verifyClientIsUnmarshaled(t *testing.T, client *Client) {
88
	cred, err := client.credential(irma.NewCredentialTypeIdentifier("irma-demo.RU.studentCard"), 0)
Sietse Ringers's avatar
Sietse Ringers committed
89
90
91
92
	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")

93
	cred, err = client.credential(irma.NewCredentialTypeIdentifier("test.test.mijnirma"), 0)
Sietse Ringers's avatar
Sietse Ringers committed
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
	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
	var err error
	for credtype, credsmap := range client.credentials {
		for index, cred := range credsmap {
			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)
147
148
149
	testManager := irma.NewSchemeManagerIdentifier("test")
	require.Contains(t, client.keyshareServers, testManager)
	kss := client.keyshareServers[testManager]
Sietse Ringers's avatar
Sietse Ringers committed
150
151
152
153
154
155
	require.NotEmpty(t, kss.Nonce)

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

156
func TestStorageDeserialization(t *testing.T) {
Sietse Ringers's avatar
Sietse Ringers committed
157
	client := parseStorage(t)
Sietse Ringers's avatar
Sietse Ringers committed
158
	verifyClientIsUnmarshaled(t, client)
Sietse Ringers's avatar
Sietse Ringers committed
159
160
161
	verifyCredentials(t, client)
	verifyKeyshareIsUnmarshaled(t, client)

162
	test.ClearTestStorage(t)
Sietse Ringers's avatar
Sietse Ringers committed
163
164
}

165
func TestLogging(t *testing.T) {
Sietse Ringers's avatar
Sietse Ringers committed
166
167
168
	client := parseStorage(t)

	logs, err := client.Logs()
169
	oldLogLength := len(logs)
Sietse Ringers's avatar
Sietse Ringers committed
170
	require.NoError(t, err)
171
172

	// Do session so we can examine its log item later
173
	jwt := getCombinedJwt("testip", irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.studentID"))
Sietse Ringers's avatar
Sietse Ringers committed
174
175
	sessionHelper(t, jwt, "issue", client)

176
	logs, err = client.Logs()
Sietse Ringers's avatar
Sietse Ringers committed
177
	require.NoError(t, err)
178
	require.True(t, len(logs) == oldLogLength+1)
Sietse Ringers's avatar
Sietse Ringers committed
179

180
	entry := logs[len(logs)-1]
Sietse Ringers's avatar
Sietse Ringers committed
181
182
183
	require.NotNil(t, entry)
	sessionjwt, err := entry.Jwt()
	require.NoError(t, err)
184
	require.Equal(t, "testip", sessionjwt.(*irma.IdentityProviderJwt).ServerName)
Sietse Ringers's avatar
Sietse Ringers committed
185
186
187
188
189
190
191
192
	require.NoError(t, err)
	require.NotEmpty(t, entry.Disclosed)
	require.NotEmpty(t, entry.Received)
	response, err := entry.GetResponse()
	require.NoError(t, err)
	require.NotNil(t, response)
	require.IsType(t, &gabi.IssueCommitmentMessage{}, response)

193
	test.ClearTestStorage(t)
Sietse Ringers's avatar
Sietse Ringers committed
194
195
}

196
197
198
// 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
199
200
201
func TestCandidates(t *testing.T) {
	client := parseStorage(t)

202
	// client contains one instance of the studentCard credential, whose studentID attribute is 456.
203
	attrtype := irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.studentID")
204
205

	// If the disjunction contains no required values at all, then our attribute is a candidate
206
207
	disjunction := &irma.AttributeDisjunction{
		Attributes: []irma.AttributeTypeIdentifier{attrtype},
Sietse Ringers's avatar
Sietse Ringers committed
208
209
210
211
	}
	attrs := client.Candidates(disjunction)
	require.NotNil(t, attrs)
	require.Len(t, attrs, 1)
212
213
	require.NotNil(t, attrs[0])
	require.Equal(t, attrs[0].Type, attrtype)
Sietse Ringers's avatar
Sietse Ringers committed
214

215
216
217
	// If the disjunction requires our attribute to have 456 as value, which it does,
	// then our attribute is a candidate
	reqval := "456"
218
219
	disjunction = &irma.AttributeDisjunction{
		Attributes: []irma.AttributeTypeIdentifier{attrtype},
220
		Values:     map[irma.AttributeTypeIdentifier]*string{attrtype: &reqval},
Sietse Ringers's avatar
Sietse Ringers committed
221
222
223
224
	}
	attrs = client.Candidates(disjunction)
	require.NotNil(t, attrs)
	require.Len(t, attrs, 1)
225
226
	require.NotNil(t, attrs[0])
	require.Equal(t, attrs[0].Type, attrtype)
Sietse Ringers's avatar
Sietse Ringers committed
227

228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
	// 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
247
248
	attrs = client.Candidates(disjunction)
	require.NotNil(t, attrs)
249
250
251
252
253
254
255
256
257
	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
258
259
	require.Empty(t, attrs)

260
	test.ClearTestStorage(t)
Sietse Ringers's avatar
Sietse Ringers committed
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
}

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)

290
	test.ClearTestStorage(t)
Sietse Ringers's avatar
Sietse Ringers committed
291
292
293
294
}

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

296
297
	id := irma.NewCredentialTypeIdentifier("irma-demo.RU.studentCard")
	id2 := irma.NewCredentialTypeIdentifier("test.test.mijnirma")
Sietse Ringers's avatar
Sietse Ringers committed
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316

	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)

317
	test.ClearTestStorage(t)
Sietse Ringers's avatar
Sietse Ringers committed
318
319
}

320
321
322
323
324
func TestWrongSchemeManager(t *testing.T) {
	client := parseStorage(t)

	irmademo := irma.NewSchemeManagerIdentifier("irma-demo")
	require.Contains(t, client.Configuration.SchemeManagers, irmademo)
325
	require.NoError(t, os.Remove("../testdata/storage/test/irma_configuration/irma-demo/index"))
326
327
328
329
330

	err := client.Configuration.ParseFolder()
	_, ok := err.(*irma.SchemeManagerError)
	require.True(t, ok)
	require.Contains(t, client.Configuration.DisabledSchemeManagers, irmademo)
331
332
333
334
335
	require.Contains(t, client.Configuration.SchemeManagers, irmademo)
	require.NotEqual(t,
		client.Configuration.SchemeManagers[irmademo].Status,
		irma.SchemeManagerStatusValid,
	)
336

337
	test.ClearTestStorage(t)
338
339
}

340
341
342
// 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
343
344
345
func TestDownloadSchemeManager(t *testing.T) {
	client := parseStorage(t)

346
347
348
	// Remove irma-demo scheme manager as we need to test adding it
	irmademo := irma.NewSchemeManagerIdentifier("irma-demo")
	require.Contains(t, client.Configuration.SchemeManagers, irmademo)
349
	require.NoError(t, client.Configuration.RemoveSchemeManager(irmademo, true))
350
351
352
353
354
	require.NotContains(t, client.Configuration.SchemeManagers, irmademo)

	// Do an add-scheme-manager-session
	qr := &irma.Qr{
		Type: irma.ActionSchemeManager,
355
		URL:  "https://raw.githubusercontent.com/credentials/irma-demo-schememanager/master",
356
357
358
359
360
361
362
	}
	c := make(chan *irma.SessionError)
	client.NewSession(qr, TestHandler{t, c, client})
	if err := <-c; err != nil {
		t.Fatal(*err)
	}
	require.Contains(t, client.Configuration.SchemeManagers, irmademo)
Sietse Ringers's avatar
Sietse Ringers committed
363

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

368
369
370
371
	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"))

372
	basepath := "../testdata/storage/test/irma_configuration/irma-demo"
373
374
375
376
377
378
379
380
381
382
	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)

383
	test.ClearTestStorage(t)
Sietse Ringers's avatar
Sietse Ringers committed
384
}