irmago_test.go 8.32 KB
Newer Older
Sietse Ringers's avatar
Sietse Ringers committed
1
package irmago
2
3

import (
4
5
	"fmt"
	"math/big"
Sietse Ringers's avatar
Sietse Ringers committed
6
	"os"
7
8
	"testing"
	"time"
Sietse Ringers's avatar
Sietse Ringers committed
9

10
11
	"encoding/json"

12
	"github.com/stretchr/testify/assert"
Sietse Ringers's avatar
Sietse Ringers committed
13
	"github.com/stretchr/testify/require"
14
15
)

Sietse Ringers's avatar
Sietse Ringers committed
16
func TestMain(m *testing.M) {
Sietse Ringers's avatar
Sietse Ringers committed
17
18
	retCode := m.Run()

Sietse Ringers's avatar
Sietse Ringers committed
19
20
	err := os.RemoveAll("testdata/storage/test")
	if err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
21
		fmt.Println("Could not delete test storage")
Sietse Ringers's avatar
Sietse Ringers committed
22
23
24
		os.Exit(1)
	}

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

Sietse Ringers's avatar
Sietse Ringers committed
28
29
30
31
type IgnoringKeyshareHandler struct{}

func (i *IgnoringKeyshareHandler) StartKeyshareRegistration(m *SchemeManager) {}

Sietse Ringers's avatar
Sietse Ringers committed
32
33
34
35
36
func parseMetaStore(t *testing.T) {
	require.NoError(t, MetaStore.ParseFolder("testdata/irma_configuration"), "MetaStore.ParseFolder() failed")
}

func parseStorage(t *testing.T) {
37
	exists, err := PathExists("testdata/storage/test")
Sietse Ringers's avatar
Sietse Ringers committed
38
39
40
	require.NoError(t, err, "pathexists() failed")
	if !exists {
		require.NoError(t, os.Mkdir("testdata/storage/test", 0755), "Could not create test storage")
Sietse Ringers's avatar
Sietse Ringers committed
41
	}
Sietse Ringers's avatar
Sietse Ringers committed
42
	require.NoError(t, Manager.Init("testdata/storage/test", &IgnoringKeyshareHandler{}), "Manager.Init() failed")
Sietse Ringers's avatar
Sietse Ringers committed
43
44
45
46
47
}

func teardown(t *testing.T) {
	MetaStore = newConfigurationStore()
	Manager = newCredentialManager()
48
	assert.NoError(t, os.RemoveAll("testdata/storage/test"))
Sietse Ringers's avatar
Sietse Ringers committed
49
50
}

51
52
53
54
55
56
57
// 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
58
func parseAndroidStorage(t *testing.T) {
59
	assert.NoError(t, Manager.ParseAndroidStorage(), "ParseAndroidStorage() failed")
Sietse Ringers's avatar
Sietse Ringers committed
60
61
62
}

func verifyStoreIsUnmarshaled(t *testing.T) {
Sietse Ringers's avatar
Sietse Ringers committed
63
	cred, err := Manager.credential(NewCredentialTypeIdentifier("irma-demo.RU.studentCard"), 0)
64
65
66
	assert.NoError(t, err, "could not fetch credential")
	assert.NotNil(t, cred, "Credential should exist")
	assert.NotNil(t, cred.Attributes[0], "Metadata attribute of irma-demo.RU.studentCard should not be nil")
67

68
	assert.True(t,
Sietse Ringers's avatar
Sietse Ringers committed
69
		cred.Signature.Verify(cred.PublicKey(), cred.Attributes),
70
71
72
		"Credential should be valid",
	)
}
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
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) {
	require.NotNil(t, Manager.paillierKeyCache)
	require.NotNil(t, Manager.keyshareServers)
	test := NewSchemeManagerIdentifier("test")
	require.Contains(t, Manager.keyshareServers, test)
	kss := Manager.keyshareServers[test]
	require.NotEmpty(t, kss.Nonce)

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

Sietse Ringers's avatar
Sietse Ringers committed
103
func TestAndroidParse(t *testing.T) {
Sietse Ringers's avatar
Sietse Ringers committed
104
105
	parseMetaStore(t)
	parseStorage(t)
Sietse Ringers's avatar
Sietse Ringers committed
106
107
	parseAndroidStorage(t)
	verifyStoreIsUnmarshaled(t)
108
	verifyKeyshareIsUnmarshaled(t)
Sietse Ringers's avatar
Sietse Ringers committed
109
110

	teardown(t)
Sietse Ringers's avatar
Sietse Ringers committed
111
112
113
}

func TestUnmarshaling(t *testing.T) {
Sietse Ringers's avatar
Sietse Ringers committed
114
115
	parseMetaStore(t)
	parseStorage(t)
Sietse Ringers's avatar
Sietse Ringers committed
116
117
118
	parseAndroidStorage(t)

	Manager = newCredentialManager()
Sietse Ringers's avatar
Sietse Ringers committed
119
	err := Manager.Init("testdata/storage/test", nil)
120
	require.NoError(t, err)
Sietse Ringers's avatar
Sietse Ringers committed
121
122

	verifyStoreIsUnmarshaled(t)
123
	verifyKeyshareIsUnmarshaled(t)
Sietse Ringers's avatar
Sietse Ringers committed
124
125

	teardown(t)
Sietse Ringers's avatar
Sietse Ringers committed
126
}
127
128

func TestParseStore(t *testing.T) {
Sietse Ringers's avatar
Sietse Ringers committed
129
	parseMetaStore(t)
130

131
132
	assert.NotNil(t, MetaStore.Issuers[NewIssuerIdentifier("irma-demo.RU")].CurrentPublicKey().N, "irma-demo.RU public key has no modulus")
	assert.Equal(t,
133
		"Irma Demo",
134
		MetaStore.SchemeManagers[NewSchemeManagerIdentifier("irma-demo")].Name.Translation("en"),
135
		"irma-demo scheme manager has unexpected name")
136
	assert.Equal(t,
137
		"Radboud Universiteit Nijmegen",
138
		MetaStore.Issuers[NewIssuerIdentifier("irma-demo.RU")].Name.Translation("en"),
139
		"irma-demo.RU issuer has unexpected name")
140
	assert.Equal(t,
141
		"Student Card",
142
		MetaStore.Credentials[NewCredentialTypeIdentifier("irma-demo.RU.studentCard")].ShortName.Translation("en"),
143
144
		"irma-demo.RU.studentCard has unexpected name")

145
	assert.Equal(t,
146
		"studentID",
147
		MetaStore.Credentials[NewCredentialTypeIdentifier("irma-demo.RU.studentCard")].Attributes[2].ID,
148
149
150
151
		"irma-demo.RU.studentCard.studentID has unexpected name")

	// Hash algorithm pseudocode:
	// Base64(SHA256("irma-demo.RU.studentCard")[0:16])
152
	assert.Contains(t, MetaStore.reverseHashes, "1stqlPad5edpfS1Na1U+DA==",
153
		"irma-demo.RU.studentCard had improper hash")
154
	assert.Contains(t, MetaStore.reverseHashes, "CLjnADMBYlFcuGOT7Z0xRg==",
155
		"irma-demo.MijnOverheid.root had improper hash")
Sietse Ringers's avatar
Sietse Ringers committed
156
157

	teardown(t)
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
}

func TestMetadataAttribute(t *testing.T) {
	metadata := NewMetadataAttribute()
	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) {
Sietse Ringers's avatar
Sietse Ringers committed
177
	parseMetaStore(t)
178
179
180

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

183
	assert.Equal(t,
184
		NewCredentialTypeIdentifier("irma-demo.RU.studentCard"),
185
186
187
		attr.CredentialType().Identifier(),
		"Metadata credential type was not irma-demo.RU.studentCard",
	)
188
189
190
191
	assert.Equal(t, byte(0x02), attr.Version(), "Unexpected metadata version")
	assert.Equal(t, time.Unix(1499904000, 0), attr.SigningDate(), "Unexpected signing date")
	assert.Equal(t, time.Unix(1516233600, 0), attr.Expiry(), "Unexpected expiry date")
	assert.Equal(t, 2, attr.KeyCounter(), "Unexpected key counter")
Sietse Ringers's avatar
Sietse Ringers committed
192
193

	teardown(t)
194
}
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
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

func TestAttributeDisjunctionMarshaling(t *testing.T) {
	disjunction := AttributeDisjunction{}

	var _ json.Unmarshaler = &disjunction
	var _ json.Marshaler = &disjunction

	id := NewAttributeTypeIdentifier("MijnOverheid.ageLower.over18")

	attrsjson := `
	{
		"label": "Over 18",
		"attributes": {
			"MijnOverheid.ageLower.over18": "yes",
			"Thalia.age.over18": "Yes"
		}
	}`
	require.NoError(t, json.Unmarshal([]byte(attrsjson), &disjunction))
	require.True(t, disjunction.HasValues())
	require.Contains(t, disjunction.Attributes, id)
	require.Contains(t, disjunction.Values, id)
	require.Equal(t, disjunction.Values[id], "yes")

	disjunction = AttributeDisjunction{}
	attrsjson = `
	{
		"label": "Over 18",
		"attributes": [
			"MijnOverheid.ageLower.over18",
			"Thalia.age.over18"
		]
	}`
	require.NoError(t, json.Unmarshal([]byte(attrsjson), &disjunction))
	require.False(t, disjunction.HasValues())
	require.Contains(t, disjunction.Attributes, id)

	require.True(t, disjunction.MatchesStore())

	require.False(t, disjunction.Satisfied())
	disjunction.selected = &disjunction.Attributes[0]
	require.True(t, disjunction.Satisfied())
}
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272

func TestCandidates(t *testing.T) {
	parseMetaStore(t)
	parseStorage(t)
	parseAndroidStorage(t)

	attrtype := NewAttributeTypeIdentifier("irma-demo.RU.studentCard.studentID")
	disjunction := &AttributeDisjunction{
		Attributes: []AttributeTypeIdentifier{attrtype},
	}
	attrs := Manager.Candidates(disjunction)
	require.NotNil(t, attrs)
	require.Len(t, attrs, 1)

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

	disjunction = &AttributeDisjunction{
		Attributes: []AttributeTypeIdentifier{attrtype},
		Values:     map[AttributeTypeIdentifier]string{attrtype: "s1234567"},
	}
	attrs = Manager.Candidates(disjunction)
	require.NotNil(t, attrs)
	require.Len(t, attrs, 1)

	disjunction = &AttributeDisjunction{
		Attributes: []AttributeTypeIdentifier{attrtype},
		Values:     map[AttributeTypeIdentifier]string{attrtype: "foobarbaz"},
	}
	attrs = Manager.Candidates(disjunction)
	require.NotNil(t, attrs)
	require.Empty(t, attrs)

	teardown(t)
}
273
274

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

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