irmaclient_test.go 10.1 KB
Newer Older
Sietse Ringers's avatar
Sietse Ringers committed
1
2
3
4
5
6
7
8
package irmaclient

import (
	"fmt"
	"math/big"
	"os"
	"testing"

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

func TestMain(m *testing.M) {
16
17
18
19
20
21
22
	// Remove any output from previously run to ensure a clean state
	// Some of the tests don't like it when there is existing state in storage
	err := os.RemoveAll("testdata/storage/test")
	if err != nil {
		fmt.Println("Could not delete test storage", err.Error())
		os.Exit(1)
	}
Sietse Ringers's avatar
Sietse Ringers committed
23

24
25
26
27
28
29
30
31
32
33
	// EnsureDirectoryExists eventually uses mkdir from the OS which is not recursive
	// so we have to create the temporary test storage by two function calls.
	// We ignore any error possibly returned by creating the first one, because if it errors,
	// then the second one certainly will as well.
	_ = fs.EnsureDirectoryExists("testdata/storage")
	err = fs.EnsureDirectoryExists("testdata/storage/test")
	if err != nil {
		fmt.Println("Could not create test storage: ", err.Error())
		os.Exit(1)
	}
Sietse Ringers's avatar
Sietse Ringers committed
34

35
36
37
	retCode := m.Run()

	err = os.RemoveAll("testdata/storage/test")
Sietse Ringers's avatar
Sietse Ringers committed
38
	if err != nil {
39
		fmt.Println("Could not delete test storage", err.Error())
Sietse Ringers's avatar
Sietse Ringers committed
40
41
42
43
44
45
46
47
		os.Exit(1)
	}

	os.Exit(retCode)
}

type IgnoringClientHandler struct{}

48
func (i *IgnoringClientHandler) UpdateConfiguration(new *irma.IrmaIdentifierSet)                 {}
49
50
51
func (i *IgnoringClientHandler) UpdateAttributes()                                               {}
func (i *IgnoringClientHandler) EnrollmentError(manager irma.SchemeManagerIdentifier, err error) {}
func (i *IgnoringClientHandler) EnrollmentSuccess(manager irma.SchemeManagerIdentifier)          {}
Sietse Ringers's avatar
Sietse Ringers committed
52
53
54

func parseStorage(t *testing.T) *Client {
	exists, err := fs.PathExists("testdata/storage/test")
55
	require.NoError(t, err, "fs.PathExists() failed")
Sietse Ringers's avatar
Sietse Ringers committed
56
57
58
	if !exists {
		require.NoError(t, os.Mkdir("testdata/storage/test", 0755), "Could not create test storage")
	}
59
	manager, err := New(
Sietse Ringers's avatar
Sietse Ringers committed
60
61
62
63
64
65
66
67
68
69
70
71
72
		"testdata/storage/test",
		"testdata/irma_configuration",
		"testdata/oldstorage",
		&IgnoringClientHandler{},
	)
	require.NoError(t, err)
	return manager
}

func teardown(t *testing.T) {
	require.NoError(t, os.RemoveAll("testdata/storage/test"))
}

Sietse Ringers's avatar
Sietse Ringers committed
73
func verifyClientIsUnmarshaled(t *testing.T, client *Client) {
74
	cred, err := client.credential(irma.NewCredentialTypeIdentifier("irma-demo.RU.studentCard"), 0)
Sietse Ringers's avatar
Sietse Ringers committed
75
76
77
78
	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")

79
	cred, err = client.credential(irma.NewCredentialTypeIdentifier("test.test.mijnirma"), 0)
Sietse Ringers's avatar
Sietse Ringers committed
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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
	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)
133
	test := irma.NewSchemeManagerIdentifier("test")
Sietse Ringers's avatar
Sietse Ringers committed
134
135
136
137
138
139
140
141
142
143
	require.Contains(t, client.keyshareServers, test)
	kss := client.keyshareServers[test]
	require.NotEmpty(t, kss.Nonce)

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

func TestAndroidParse(t *testing.T) {
	client := parseStorage(t)
Sietse Ringers's avatar
Sietse Ringers committed
144
	verifyClientIsUnmarshaled(t, client)
Sietse Ringers's avatar
Sietse Ringers committed
145
146
147
148
149
150
151
152
153
154
155
156
	verifyCredentials(t, client)
	verifyKeyshareIsUnmarshaled(t, client)

	teardown(t)
}

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

	// Do session so we can examine its log item later
	logs, err := client.Logs()
	require.NoError(t, err)
157
	jwt := getCombinedJwt("testip", irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.studentID"))
Sietse Ringers's avatar
Sietse Ringers committed
158
159
	sessionHelper(t, jwt, "issue", client)

160
	newclient, err := New("testdata/storage/test", "testdata/irma_configuration", "testdata/oldstorage", nil)
Sietse Ringers's avatar
Sietse Ringers committed
161
	require.NoError(t, err)
Sietse Ringers's avatar
Sietse Ringers committed
162
	verifyClientIsUnmarshaled(t, newclient)
Sietse Ringers's avatar
Sietse Ringers committed
163
164
165
166
167
168
169
170
171
172
173
	verifyCredentials(t, newclient)
	verifyKeyshareIsUnmarshaled(t, newclient)

	newlogs, err := newclient.Logs()
	require.NoError(t, err)
	require.True(t, len(newlogs) == len(logs)+1)

	entry := newlogs[len(newlogs)-1]
	require.NotNil(t, entry)
	sessionjwt, err := entry.Jwt()
	require.NoError(t, err)
174
	require.Equal(t, "testip", sessionjwt.(*irma.IdentityProviderJwt).ServerName)
Sietse Ringers's avatar
Sietse Ringers committed
175
176
177
178
179
180
181
182
183
184
185
186
187
188
	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)

	teardown(t)
}

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

189
190
191
	attrtype := irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.studentID")
	disjunction := &irma.AttributeDisjunction{
		Attributes: []irma.AttributeTypeIdentifier{attrtype},
Sietse Ringers's avatar
Sietse Ringers committed
192
193
194
195
196
197
198
199
200
	}
	attrs := client.Candidates(disjunction)
	require.NotNil(t, attrs)
	require.Len(t, attrs, 1)

	attr := attrs[0]
	require.NotNil(t, attr)
	require.Equal(t, attr.Type, attrtype)

201
202
203
	disjunction = &irma.AttributeDisjunction{
		Attributes: []irma.AttributeTypeIdentifier{attrtype},
		Values:     map[irma.AttributeTypeIdentifier]string{attrtype: "456"},
Sietse Ringers's avatar
Sietse Ringers committed
204
205
206
207
208
	}
	attrs = client.Candidates(disjunction)
	require.NotNil(t, attrs)
	require.Len(t, attrs, 1)

209
210
211
	disjunction = &irma.AttributeDisjunction{
		Attributes: []irma.AttributeTypeIdentifier{attrtype},
		Values:     map[irma.AttributeTypeIdentifier]string{attrtype: "foobarbaz"},
Sietse Ringers's avatar
Sietse Ringers committed
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
	}
	attrs = client.Candidates(disjunction)
	require.NotNil(t, attrs)
	require.Empty(t, attrs)

	teardown(t)
}

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)

	teardown(t)
}

func TestCredentialRemoval(t *testing.T) {
	client := parseStorage(t)
252
253
	id := irma.NewCredentialTypeIdentifier("irma-demo.RU.studentCard")
	id2 := irma.NewCredentialTypeIdentifier("test.test.mijnirma")
Sietse Ringers's avatar
Sietse Ringers committed
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275

	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)

	teardown(t)
}

276
277
278
279
280
281
282
283
284
285
286
func TestWrongSchemeManager(t *testing.T) {
	client := parseStorage(t)

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

	err := client.Configuration.ParseFolder()
	_, ok := err.(*irma.SchemeManagerError)
	require.True(t, ok)
	require.Contains(t, client.Configuration.DisabledSchemeManagers, irmademo)
287
288
289
290
291
	require.Contains(t, client.Configuration.SchemeManagers, irmademo)
	require.NotEqual(t,
		client.Configuration.SchemeManagers[irmademo].Status,
		irma.SchemeManagerStatusValid,
	)
292
293
294
295

	teardown(t)
}

296
297
298
// 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
299
300
301
func TestDownloadSchemeManager(t *testing.T) {
	client := parseStorage(t)

302
303
304
	// Remove irma-demo scheme manager as we need to test adding it
	irmademo := irma.NewSchemeManagerIdentifier("irma-demo")
	require.Contains(t, client.Configuration.SchemeManagers, irmademo)
305
	require.NoError(t, client.Configuration.RemoveSchemeManager(irmademo, true))
306
307
308
309
310
	require.NotContains(t, client.Configuration.SchemeManagers, irmademo)

	// Do an add-scheme-manager-session
	qr := &irma.Qr{
		Type: irma.ActionSchemeManager,
311
		URL:  "https://raw.githubusercontent.com/credentials/irma-demo-schememanager/master",
312
313
314
315
316
317
318
	}
	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
319

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

	teardown(t)
}