irmaclient_test.go 12.7 KB
Newer Older
Sietse Ringers's avatar
Sietse Ringers committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package irmaclient

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

	"encoding/json"

	"github.com/credentials/irmago"
	"github.com/credentials/irmago/internal/fs"
	"github.com/mhe/gabi"
	"github.com/stretchr/testify/require"
)

func TestMain(m *testing.M) {
	retCode := m.Run()

	// TODO make testdata/storage

	err := os.RemoveAll("testdata/storage/test")
	if err != nil {
		fmt.Println("Could not delete test storage")
		os.Exit(1)
	}

	os.Exit(retCode)
}

type IgnoringClientHandler struct{}

34
func (i *IgnoringClientHandler) UpdateConfiguration(new *irma.IrmaIdentifierSet)                 {}
35
36
37
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
38
39
40
41
42
43
44

func parseStorage(t *testing.T) *Client {
	exists, err := fs.PathExists("testdata/storage/test")
	require.NoError(t, err, "pathexists() failed")
	if !exists {
		require.NoError(t, os.Mkdir("testdata/storage/test", 0755), "Could not create test storage")
	}
45
	manager, err := New(
Sietse Ringers's avatar
Sietse Ringers committed
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
		"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"))
}

// 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
}

Sietse Ringers's avatar
Sietse Ringers committed
66
func verifyClientIsUnmarshaled(t *testing.T, client *Client) {
67
	cred, err := client.credential(irma.NewCredentialTypeIdentifier("irma-demo.RU.studentCard"), 0)
Sietse Ringers's avatar
Sietse Ringers committed
68
69
70
71
	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")

72
	cred, err = client.credential(irma.NewCredentialTypeIdentifier("test.test.mijnirma"), 0)
Sietse Ringers's avatar
Sietse Ringers committed
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
	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)
126
	test := irma.NewSchemeManagerIdentifier("test")
Sietse Ringers's avatar
Sietse Ringers committed
127
128
129
130
131
132
133
134
135
	require.Contains(t, client.keyshareServers, test)
	kss := client.keyshareServers[test]
	require.NotEmpty(t, kss.Nonce)

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

// TODO move up to irmago?
136
137
138
func verifyConfigurationIsLoaded(t *testing.T, conf *irma.Configuration, android bool) {
	require.Contains(t, conf.SchemeManagers, irma.NewSchemeManagerIdentifier("irma-demo"))
	require.Contains(t, conf.SchemeManagers, irma.NewSchemeManagerIdentifier("test"))
Sietse Ringers's avatar
Sietse Ringers committed
139
	if android {
140
		require.Contains(t, conf.SchemeManagers, irma.NewSchemeManagerIdentifier("test2"))
Sietse Ringers's avatar
Sietse Ringers committed
141
142
	}

143
	pk, err := conf.PublicKey(irma.NewIssuerIdentifier("irma-demo.RU"), 0)
Sietse Ringers's avatar
Sietse Ringers committed
144
145
146
147
148
	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",
149
		conf.SchemeManagers[irma.NewSchemeManagerIdentifier("irma-demo")].Name["en"],
Sietse Ringers's avatar
Sietse Ringers committed
150
151
152
		"irma-demo scheme manager has unexpected name")
	require.Equal(t,
		"Radboud University Nijmegen",
153
		conf.Issuers[irma.NewIssuerIdentifier("irma-demo.RU")].Name["en"],
Sietse Ringers's avatar
Sietse Ringers committed
154
155
156
		"irma-demo.RU issuer has unexpected name")
	require.Equal(t,
		"Student Card",
157
		conf.CredentialTypes[irma.NewCredentialTypeIdentifier("irma-demo.RU.studentCard")].ShortName["en"],
Sietse Ringers's avatar
Sietse Ringers committed
158
159
160
161
		"irma-demo.RU.studentCard has unexpected name")

	require.Equal(t,
		"studentID",
162
		conf.CredentialTypes[irma.NewCredentialTypeIdentifier("irma-demo.RU.studentCard")].Attributes[2].ID,
Sietse Ringers's avatar
Sietse Ringers committed
163
164
165
166
		"irma-demo.RU.studentCard.studentID has unexpected name")

	// Hash algorithm pseudocode:
	// Base64(SHA256("irma-demo.RU.studentCard")[0:16])
167
	//require.Contains(t, conf.reverseHashes, "1stqlPad5edpfS1Na1U+DA==",
Sietse Ringers's avatar
Sietse Ringers committed
168
	//	"irma-demo.RU.studentCard had improper hash")
169
	//require.Contains(t, conf.reverseHashes, "CLjnADMBYlFcuGOT7Z0xRg==",
Sietse Ringers's avatar
Sietse Ringers committed
170
171
172
173
174
	//	"irma-demo.MijnOverheid.root had improper hash")
}

func TestAndroidParse(t *testing.T) {
	client := parseStorage(t)
175
	verifyConfigurationIsLoaded(t, client.Configuration, true)
Sietse Ringers's avatar
Sietse Ringers committed
176
	verifyClientIsUnmarshaled(t, client)
Sietse Ringers's avatar
Sietse Ringers committed
177
178
179
180
181
182
183
184
185
186
187
188
	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)
189
	jwt := getIssuanceJwt("testip", irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.studentID"))
Sietse Ringers's avatar
Sietse Ringers committed
190
191
	sessionHelper(t, jwt, "issue", client)

192
	newclient, err := New("testdata/storage/test", "testdata/irma_configuration", "testdata/oldstorage", nil)
Sietse Ringers's avatar
Sietse Ringers committed
193
	require.NoError(t, err)
Sietse Ringers's avatar
Sietse Ringers committed
194
	verifyClientIsUnmarshaled(t, newclient)
Sietse Ringers's avatar
Sietse Ringers committed
195
196
197
198
199
200
201
202
203
204
205
	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)
206
	require.Equal(t, "testip", sessionjwt.(*irma.IdentityProviderJwt).ServerName)
Sietse Ringers's avatar
Sietse Ringers committed
207
208
209
210
211
212
213
214
215
216
217
218
	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 TestMetadataAttribute(t *testing.T) {
219
	metadata := irma.NewMetadataAttribute()
Sietse Ringers's avatar
Sietse Ringers committed
220
221
222
223
	if metadata.Version() != 0x02 {
		t.Errorf("Unexpected metadata version: %d", metadata.Version())
	}

224
	expiry := metadata.SigningDate().Unix() + int64(metadata.ValidityDuration()*irma.ExpiryFactor)
Sietse Ringers's avatar
Sietse Ringers committed
225
226
227
228
229
230
231
232
233
234
	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) {
235
	conf, err := irma.NewConfiguration("testdata/irma_configuration", "")
Sietse Ringers's avatar
Sietse Ringers committed
236
	require.NoError(t, err)
237
	require.NoError(t, conf.ParseFolder())
Sietse Ringers's avatar
Sietse Ringers committed
238
239

	// An actual metadata attribute of an IRMA credential extracted from the IRMA app
240
	attr := irma.MetadataFromInt(s2big("49043481832371145193140299771658227036446546573739245068"), conf)
Sietse Ringers's avatar
Sietse Ringers committed
241
242
243
	require.NotNil(t, attr.CredentialType(), "attr.CredentialType() should not be nil")

	require.Equal(t,
244
		irma.NewCredentialTypeIdentifier("irma-demo.RU.studentCard"),
Sietse Ringers's avatar
Sietse Ringers committed
245
246
247
248
249
250
251
252
253
254
255
256
257
258
		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")
	require.Equal(t, 2, attr.KeyCounter(), "Unexpected key counter")

	teardown(t)
}

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

259
260
261
	attrtype := irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.studentID")
	disjunction := &irma.AttributeDisjunction{
		Attributes: []irma.AttributeTypeIdentifier{attrtype},
Sietse Ringers's avatar
Sietse Ringers committed
262
263
264
265
266
267
268
269
270
	}
	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)

271
272
273
	disjunction = &irma.AttributeDisjunction{
		Attributes: []irma.AttributeTypeIdentifier{attrtype},
		Values:     map[irma.AttributeTypeIdentifier]string{attrtype: "456"},
Sietse Ringers's avatar
Sietse Ringers committed
274
275
276
277
278
	}
	attrs = client.Candidates(disjunction)
	require.NotNil(t, attrs)
	require.Len(t, attrs, 1)

279
280
281
	disjunction = &irma.AttributeDisjunction{
		Attributes: []irma.AttributeTypeIdentifier{attrtype},
		Values:     map[irma.AttributeTypeIdentifier]string{attrtype: "foobarbaz"},
Sietse Ringers's avatar
Sietse Ringers committed
282
283
284
285
286
287
288
289
290
	}
	attrs = client.Candidates(disjunction)
	require.NotNil(t, attrs)
	require.Empty(t, attrs)

	teardown(t)
}

func TestTimestamp(t *testing.T) {
291
292
	mytime := irma.Timestamp(time.Unix(1500000000, 0))
	timestruct := struct{ Time *irma.Timestamp }{Time: &mytime}
Sietse Ringers's avatar
Sietse Ringers committed
293
294
295
	bytes, err := json.Marshal(timestruct)
	require.NoError(t, err)

296
	timestruct = struct{ Time *irma.Timestamp }{}
Sietse Ringers's avatar
Sietse Ringers committed
297
298
299
300
301
	require.NoError(t, json.Unmarshal(bytes, &timestruct))
	require.Equal(t, time.Time(*timestruct.Time).Unix(), int64(1500000000))
}

func TestServiceProvider(t *testing.T) {
302
	var spjwt irma.ServiceProviderJwt
Sietse Ringers's avatar
Sietse Ringers committed
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327

	var spjson = `{
		"sprequest": {
			"validity": 60,
			"timeout": 60,
			"request": {
				"content": [
					{
						"label": "ID",
						"attributes": ["irma-demo.RU.studentCard.studentID"]
					}
				]
			}
		}
	}`

	require.NoError(t, json.Unmarshal([]byte(spjson), &spjwt))
	require.NotNil(t, spjwt.Request.Request.Content)
	require.NotEmpty(t, spjwt.Request.Request.Content)
	require.NotNil(t, spjwt.Request.Request.Content[0])
	require.NotEmpty(t, spjwt.Request.Request.Content[0])
	require.NotNil(t, spjwt.Request.Request.Content[0].Attributes)
	require.NotEmpty(t, spjwt.Request.Request.Content[0].Attributes)
	require.Equal(t, spjwt.Request.Request.Content[0].Attributes[0].Name(), "studentID")

328
	require.NotNil(t, spjwt.Request.Request.Content.Find(irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.studentID")))
Sietse Ringers's avatar
Sietse Ringers committed
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
}

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)
363
364
	id := irma.NewCredentialTypeIdentifier("irma-demo.RU.studentCard")
	id2 := irma.NewCredentialTypeIdentifier("test.test.mijnirma")
Sietse Ringers's avatar
Sietse Ringers committed
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388

	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)
}

func TestDownloadSchemeManager(t *testing.T) {
	client := parseStorage(t)
389
	require.NoError(t, client.Configuration.RemoveSchemeManager(irma.NewSchemeManagerIdentifier("irma-demo")))
Sietse Ringers's avatar
Sietse Ringers committed
390
	url := "https://raw.githubusercontent.com/credentials/irma_configuration/translate/irma-demo"
391
	sm, err := client.Configuration.DownloadSchemeManager(url)
Sietse Ringers's avatar
Sietse Ringers committed
392
393
394
	require.NoError(t, err)
	require.NotNil(t, sm)

395
	require.NoError(t, client.Configuration.AddSchemeManager(sm))
Sietse Ringers's avatar
Sietse Ringers committed
396

397
	jwt := getIssuanceJwt("testip", irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.studentID"))
Sietse Ringers's avatar
Sietse Ringers committed
398
399
400
401
	sessionHelper(t, jwt, "issue", client)

	teardown(t)
}