requestor_test.go 14.2 KB
Newer Older
1 2 3
package sessiontest

import (
4
	"bytes"
5
	"encoding/json"
6 7
	"io/ioutil"
	"net/http"
8 9 10 11

	"crypto/rand"
	"path/filepath"

12
	"reflect"
13

14 15
	"testing"

16 17
	"github.com/privacybydesign/gabi/big"
	"github.com/privacybydesign/gabi/revocation"
18 19
	"github.com/privacybydesign/irmago"
	"github.com/privacybydesign/irmago/internal/test"
20
	"github.com/privacybydesign/irmago/irmaclient"
Sietse Ringers's avatar
Sietse Ringers committed
21
	"github.com/privacybydesign/irmago/server"
22 23 24
	"github.com/stretchr/testify/require"
)

25
type sessionOption int
26

27
const (
28
	sessionOptionUpdatedIrmaConfiguration sessionOption = 1 << iota
29
	sessionOptionUnsatisfiableRequest
30
	sessionOptionRetryPost
31
	sessionOptionIgnoreClientError
32 33 34 35 36
)

type requestorSessionResult struct {
	*server.SessionResult
	Missing irmaclient.MissingAttributes
37
}
38

39
func requestorSessionHelper(t *testing.T, request irma.SessionRequest, client *irmaclient.Client, options ...sessionOption) *requestorSessionResult {
40
	if client == nil {
41
		client, _ = parseStorage(t)
42 43
		defer test.ClearTestStorage(t)
	}
44

45 46 47
	StartIrmaServer(t, len(options) == 1 && options[0] == sessionOptionUpdatedIrmaConfiguration)
	defer StopIrmaServer()

48
	clientChan := make(chan *SessionResult)
Sietse Ringers's avatar
Sietse Ringers committed
49
	serverChan := make(chan *server.SessionResult)
50

51
	qr, token, err := irmaServer.StartSession(request, func(result *server.SessionResult) {
52 53 54 55
		serverChan <- result
	})
	require.NoError(t, err)

56 57 58 59 60
	opts := 0
	for _, o := range options {
		opts |= int(o)
	}

61
	var h irmaclient.Handler
62 63
	if opts&int(sessionOptionUnsatisfiableRequest) > 0 {
		h = &UnsatisfiableTestHandler{TestHandler{t, clientChan, client, nil, ""}}
64
	} else {
65
		h = &TestHandler{t, clientChan, client, nil, ""}
66
	}
67

68 69 70 71
	j, err := json.Marshal(qr)
	require.NoError(t, err)
	client.NewSession(string(j), h)
	clientResult := <-clientChan
72
	if (len(options) == 0 || options[0] != sessionOptionIgnoreClientError) && clientResult != nil {
73 74 75
		require.NoError(t, clientResult.Err)
	}

76 77
	if opts&int(sessionOptionUnsatisfiableRequest) > 0 {
		require.NotNil(t, clientResult)
78 79
		return &requestorSessionResult{nil, clientResult.Missing}
	}
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98

	serverResult := <-serverChan
	require.Equal(t, token, serverResult.Token)

	if opts&int(sessionOptionRetryPost) > 0 {
		req, err := http.NewRequest(http.MethodPost,
			qr.URL+"/proofs",
			bytes.NewBuffer([]byte(h.(*TestHandler).result)),
		)
		require.NoError(t, err)
		req.Header.Add("Content-Type", "application/json")
		res, err := new(http.Client).Do(req)
		require.NoError(t, err)
		require.True(t, res.StatusCode < 300)
		_, err = ioutil.ReadAll(res.Body)
		require.NoError(t, err)
	}

	return &requestorSessionResult{serverResult, nil}
99 100
}

101 102
// Check that nonexistent IRMA identifiers in the session request fail the session
func TestRequestorInvalidRequest(t *testing.T) {
103
	StartIrmaServer(t, false)
104 105 106 107 108 109 110 111
	defer StopIrmaServer()
	_, _, err := irmaServer.StartSession(irma.NewDisclosureRequest(
		irma.NewAttributeTypeIdentifier("irma-demo.RU.foo.bar"),
		irma.NewAttributeTypeIdentifier("irma-demo.baz.qux.abc"),
	), nil)
	require.Error(t, err)
}

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
func TestRequestorDoubleGET(t *testing.T) {
	StartIrmaServer(t, false)
	defer StopIrmaServer()
	qr, _, err := irmaServer.StartSession(irma.NewDisclosureRequest(
		irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.studentID"),
	), nil)
	require.NoError(t, err)

	// Simulate the first GET by the client in the session protocol, twice
	var o interface{}
	transport := irma.NewHTTPTransport(qr.URL)
	transport.SetHeader(irma.MinVersionHeader, "2.5")
	transport.SetHeader(irma.MaxVersionHeader, "2.5")
	require.NoError(t, transport.Get("", &o))
	require.NoError(t, transport.Get("", &o))
}

Sietse Ringers's avatar
Sietse Ringers committed
129
func TestRequestorSignatureSession(t *testing.T) {
130
	client, _ := parseStorage(t)
131 132
	id := irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.studentID")

133 134 135 136 137 138 139 140 141 142
	var serverResult *requestorSessionResult
	for _, opt := range []sessionOption{0, sessionOptionRetryPost} {
		serverResult = requestorSessionHelper(t, irma.NewSignatureRequest("message", id), client, opt)

		require.Nil(t, serverResult.Err)
		require.Equal(t, irma.ProofStatusValid, serverResult.ProofStatus)
		require.NotEmpty(t, serverResult.Disclosed)
		require.Equal(t, id, serverResult.Disclosed[0][0].Identifier)
		require.Equal(t, "456", serverResult.Disclosed[0][0].Value["en"])
	}
143 144 145 146 147 148 149 150 151 152 153 154

	// Load the updated scheme in which an attribute was added to the studentCard credential type
	schemeid := irma.NewSchemeManagerIdentifier("irma-demo")
	client.Configuration.SchemeManagers[schemeid].URL = "http://localhost:48681/irma_configuration_updated/irma-demo"
	require.NoError(t, client.Configuration.UpdateSchemeManager(schemeid, nil))
	require.NoError(t, client.Configuration.ParseFolder())
	require.Contains(t, client.Configuration.AttributeTypes, irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.newAttribute"))

	// Check that the just created credential is still valid after the new attribute has been added
	_, status, err := serverResult.Signature.Verify(client.Configuration, nil)
	require.NoError(t, err)
	require.Equal(t, irma.ProofStatusValid, status)
155 156
}

Sietse Ringers's avatar
Sietse Ringers committed
157
func TestRequestorDisclosureSession(t *testing.T) {
158
	id := irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.studentID")
159
	request := irma.NewDisclosureRequest(id)
160 161 162 163 164 165
	for _, opt := range []sessionOption{0, sessionOptionRetryPost} {
		serverResult := testRequestorDisclosure(t, request, opt)
		require.Len(t, serverResult.Disclosed, 1)
		require.Equal(t, id, serverResult.Disclosed[0][0].Identifier)
		require.Equal(t, "456", serverResult.Disclosed[0][0].Value["en"])
	}
166
}
167

168
func TestRequestorDisclosureMultipleAttrs(t *testing.T) {
169 170 171 172
	request := irma.NewDisclosureRequest(
		irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.studentID"),
		irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.level"),
	)
173 174 175 176
	serverResult := testRequestorDisclosure(t, request)
	require.Len(t, serverResult.Disclosed, 2)
}

177 178
func testRequestorDisclosure(t *testing.T, request *irma.DisclosureRequest, options ...sessionOption) *server.SessionResult {
	serverResult := requestorSessionHelper(t, request, nil, options...)
179 180
	require.Nil(t, serverResult.Err)
	require.Equal(t, irma.ProofStatusValid, serverResult.ProofStatus)
181
	return serverResult.SessionResult
182 183
}

Sietse Ringers's avatar
Sietse Ringers committed
184
func TestRequestorIssuanceSession(t *testing.T) {
185
	testRequestorIssuance(t, false, nil)
186 187
}

188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
func TestRequestorCombinedSessionMultipleAttributes(t *testing.T) {
	var ir irma.IssuanceRequest
	require.NoError(t, irma.UnmarshalValidate([]byte(`{
		"type":"issuing",
		"credentials": [
			{
				"credential":"irma-demo.MijnOverheid.root",
				"attributes" : {
					"BSN":"12345"
				}
			}
		],
		"disclose" : [
			{
				"label":"Initialen",
				"attributes":["irma-demo.RU.studentCard.studentCardNumber"]
			},
			{
				"label":"Achternaam",
				"attributes" : ["irma-demo.RU.studentCard.studentID"]
			},
			{
				"label":"Geboortedatum",
				"attributes":["irma-demo.RU.studentCard.university"]
			}
		]
	}`), &ir))

216
	require.Equal(t, server.StatusDone, requestorSessionHelper(t, &ir, nil).Status)
217 218
}

219
func testRequestorIssuance(t *testing.T, keyshare bool, client *irmaclient.Client) {
220
	attrid := irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.studentID")
221
	request := irma.NewIssuanceRequest([]*irma.CredentialRequest{{
222 223 224 225 226 227 228 229 230 231 232 233
		CredentialTypeID: irma.NewCredentialTypeIdentifier("irma-demo.RU.studentCard"),
		Attributes: map[string]string{
			"university":        "Radboud",
			"studentCardNumber": "31415927",
			"studentID":         "s1234567",
			"level":             "42",
		},
	}, {
		CredentialTypeID: irma.NewCredentialTypeIdentifier("irma-demo.MijnOverheid.root"),
		Attributes: map[string]string{
			"BSN": "299792458",
		},
234
	}}, attrid)
235 236 237 238 239 240
	if keyshare {
		request.Credentials = append(request.Credentials, &irma.CredentialRequest{
			CredentialTypeID: irma.NewCredentialTypeIdentifier("test.test.mijnirma"),
			Attributes:       map[string]string{"email": "testusername"},
		})
	}
241

242
	result := requestorSessionHelper(t, request, client)
243 244 245
	require.Nil(t, result.Err)
	require.Equal(t, irma.ProofStatusValid, result.ProofStatus)
	require.NotEmpty(t, result.Disclosed)
246 247 248 249 250
	require.Equal(t, attrid, result.Disclosed[0][0].Identifier)
	require.Equal(t, "456", result.Disclosed[0][0].Value["en"])
}

func TestConDisCon(t *testing.T) {
251
	client, _ := parseStorage(t)
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 278 279 280 281 282 283 284 285 286
	ir := getMultipleIssuanceRequest()
	ir.Credentials = append(ir.Credentials, &irma.CredentialRequest{
		Validity:         ir.Credentials[0].Validity,
		CredentialTypeID: irma.NewCredentialTypeIdentifier("irma-demo.MijnOverheid.fullName"),
		Attributes: map[string]string{
			"firstnames": "Jan Hendrik",
			"firstname":  "Jan",
			"familyname": "Klaassen",
			"prefix":     "van",
		},
	})
	requestorSessionHelper(t, ir, client)

	dr := irma.NewDisclosureRequest()
	dr.Disclose = irma.AttributeConDisCon{
		irma.AttributeDisCon{
			irma.AttributeCon{
				irma.NewAttributeRequest("irma-demo.MijnOverheid.root.BSN"),
				irma.NewAttributeRequest("irma-demo.MijnOverheid.fullName.firstname"),
				irma.NewAttributeRequest("irma-demo.MijnOverheid.fullName.familyname"),
			},
			irma.AttributeCon{
				irma.NewAttributeRequest("irma-demo.RU.studentCard.studentID"),
				irma.NewAttributeRequest("irma-demo.RU.studentCard.university"),
			},
		},
		//irma.AttributeDisCon{
		//	irma.AttributeCon{
		//		irma.NewAttributeRequest("irma-demo.MijnOverheid.fullName.firstname"),
		//		irma.NewAttributeRequest("irma-demo.MijnOverheid.fullName.familyname"),
		//	},
		//},
	}

	requestorSessionHelper(t, dr, client)
287
}
288 289

func TestOptionalDisclosure(t *testing.T) {
290
	client, _ := parseStorage(t)
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
	university := irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.university")
	studentid := irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.studentID")

	radboud := "Radboud"
	attrs1 := irma.AttributeConDisCon{
		irma.AttributeDisCon{ // Including one non-optional disjunction is required in disclosure and signature sessions
			irma.AttributeCon{irma.AttributeRequest{Type: university}},
		},
		irma.AttributeDisCon{
			irma.AttributeCon{},
			irma.AttributeCon{irma.AttributeRequest{Type: studentid}},
		},
	}
	disclosed1 := [][]*irma.DisclosedAttribute{
		{
			{
307 308 309 310 311
				RawValue:     &radboud,
				Value:        map[string]string{"": radboud, "en": radboud, "nl": radboud},
				Identifier:   irma.NewAttributeTypeIdentifier("irma-demo.RU.studentCard.university"),
				Status:       irma.AttributeProofStatusPresent,
				IssuanceTime: irma.Timestamp(client.Attributes(university.CredentialTypeIdentifier(), 0).SigningDate()),
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
			},
		},
		{},
	}
	attrs2 := irma.AttributeConDisCon{ // In issuance sessions, it is allowed that all disjunctions are optional
		irma.AttributeDisCon{
			irma.AttributeCon{},
			irma.AttributeCon{irma.AttributeRequest{Type: studentid}},
		},
	}
	disclosed2 := [][]*irma.DisclosedAttribute{{}}

	tests := []struct {
		request   irma.SessionRequest
		attrs     irma.AttributeConDisCon
		disclosed [][]*irma.DisclosedAttribute
	}{
		{irma.NewDisclosureRequest(), attrs1, disclosed1},
		{irma.NewSignatureRequest("message"), attrs1, disclosed1},
		{getIssuanceRequest(true), attrs1, disclosed1},
		{getIssuanceRequest(true), attrs2, disclosed2},
	}

	for _, args := range tests {
		args.request.Disclosure().Disclose = args.attrs

		// TestHandler always prefers the first option when given any choice, so it will not disclose the optional attribute
		result := requestorSessionHelper(t, args.request, client)
		require.True(t, reflect.DeepEqual(args.disclosed, result.Disclosed))
	}
}
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422

func editDB(t *testing.T, path string, keystore revocation.Keystore, current bool, f func(*revocation.DB)) {
	db, err := revocation.LoadDB(path, keystore)
	require.NoError(t, err)
	if current {
		require.NoError(t, db.LoadCurrent())
	}
	f(db)
	require.NoError(t, db.Close())
}

func revocationSession(t *testing.T, client *irmaclient.Client, options ...sessionOption) *requestorSessionResult {
	attr := irma.NewAttributeTypeIdentifier("irma-demo.MijnOverheid.root.BSN")
	req := irma.NewDisclosureRequest(attr)
	req.Revocation = irma.RevocationSet{attr.CredentialTypeIdentifier(): struct{}{}}
	result := requestorSessionHelper(t, req, client, options...)
	require.Nil(t, result.Err)
	return result
}

func TestRevocation(t *testing.T) {
	// setup client, constants, and revocation key material
	client, _ := parseStorage(t)
	iss := irma.NewIssuerIdentifier("irma-demo.MijnOverheid")
	cred := irma.NewCredentialTypeIdentifier("irma-demo.MijnOverheid.root")
	dbPath := filepath.Join(testdata, "storage", "revocation", cred.String())
	keystore := client.Configuration.RevocationKeystore(iss)
	sk, err := client.Configuration.PrivateKey(iss)
	require.NoError(t, err)
	revsk, err := sk.RevocationKey()
	require.NoError(t, err)

	// enable revocation for our credential type by creating and saving an initial accumulator
	editDB(t, dbPath, keystore, false, func(db *revocation.DB) {
		require.NoError(t, db.EnableRevocation(revsk))
	})

	// issue MijnOverheid.root instance with revocation enabled
	request := irma.NewIssuanceRequest([]*irma.CredentialRequest{{
		RevocationKey:    "12345", // once revocation is required for a credential type, this key is required
		CredentialTypeID: irma.NewCredentialTypeIdentifier("irma-demo.MijnOverheid.root"),
		Attributes: map[string]string{
			"BSN": "299792458",
		},
	}})
	result := requestorSessionHelper(t, request, client)
	require.Nil(t, result.Err)

	// perform disclosure session with nonrevocation proof
	result = revocationSession(t, client)
	require.Equal(t, irma.ProofStatusValid, result.ProofStatus)
	require.NotEmpty(t, result.Disclosed)

	// revoke fake other credential
	e, err := rand.Prime(rand.Reader, 207)
	require.NoError(t, err)
	editDB(t, dbPath, keystore, true, func(db *revocation.DB) {
		require.NoError(t, db.AddIssuanceRecord(&revocation.IssuanceRecord{
			Key:  "fake",
			Attr: big.Convert(e),
		}))
		require.NoError(t, db.Revoke(revsk, []byte("fake")))
	})

	// perform another disclosure session with nonrevocation proof
	// client updates its witness to the new accumulator first
	result = revocationSession(t, client)
	require.Equal(t, irma.ProofStatusValid, result.ProofStatus)
	require.NotEmpty(t, result.Disclosed)

	// revoke our credential
	editDB(t, dbPath, keystore, true, func(db *revocation.DB) {
		require.NoError(t, db.Revoke(revsk, []byte("12345")))
	})

	// try to perform session with revoked credential
	// client notices that is credential is revoked and aborts
	result = revocationSession(t, client, sessionOptionIgnoreClientError)
	require.Equal(t, result.Status, server.StatusCancelled)
}