session.go 21.2 KB
Newer Older
1
package irmaclient
2
3

import (
Koen van Ingen's avatar
Koen van Ingen committed
4
	"encoding/json"
Sietse Ringers's avatar
Sietse Ringers committed
5
6
	"fmt"
	"sort"
7
8
	"strings"

9
10
	"math/big"

11
	"github.com/go-errors/errors"
12
	"github.com/mhe/gabi"
13
	"github.com/privacybydesign/irmago"
14
15
)

Sietse Ringers's avatar
Sietse Ringers committed
16
17
18
// This file contains the logic and state of performing IRMA sessions, communicates
// with IRMA API servers, and uses the calling Client to construct messages and replies
// in the IRMA protocol.
Sietse Ringers's avatar
Sietse Ringers committed
19

Sietse Ringers's avatar
Sietse Ringers committed
20
21
// PermissionHandler is a callback for providing permission for an IRMA session
// and specifying the attributes to be disclosed.
22
type PermissionHandler func(proceed bool, choice *irma.DisclosureChoice)
23

Sietse Ringers's avatar
Sietse Ringers committed
24
// PinHandler is used to provide the user's PIN code.
25
26
type PinHandler func(proceed bool, pin string)

27
28
// A Handler contains callbacks for communication to the user.
type Handler interface {
29
	StatusUpdate(action irma.Action, status irma.Status)
30
	Success(action irma.Action, result string)
31
32
	Cancelled(action irma.Action)
	Failure(action irma.Action, err *irma.SessionError)
33
	UnsatisfiableRequest(action irma.Action, ServerName string, missing irma.AttributeDisjunctionList)
34
35

	KeyshareBlocked(manager irma.SchemeManagerIdentifier, duration int)
36
	KeyshareEnrollmentIncomplete(manager irma.SchemeManagerIdentifier)
37
	KeyshareEnrollmentMissing(manager irma.SchemeManagerIdentifier)
38
	KeyshareEnrollmentDeleted(manager irma.SchemeManagerIdentifier)
39
40
41
42
43

	RequestIssuancePermission(request irma.IssuanceRequest, ServerName string, callback PermissionHandler)
	RequestVerificationPermission(request irma.DisclosureRequest, ServerName string, callback PermissionHandler)
	RequestSignaturePermission(request irma.SignatureRequest, ServerName string, callback PermissionHandler)
	RequestSchemeManagerPermission(manager *irma.SchemeManager, callback func(proceed bool))
Sietse Ringers's avatar
Sietse Ringers committed
44

45
	RequestPin(remainingAttempts int, callback PinHandler)
46
47
}

Sietse Ringers's avatar
Sietse Ringers committed
48
// SessionDismisser can dismiss the current IRMA session.
49
50
51
52
type SessionDismisser interface {
	Dismiss()
}

Sietse Ringers's avatar
Sietse Ringers committed
53
type session struct {
Koen van Ingen's avatar
Koen van Ingen committed
54
55
	Action  irma.Action
	Handler Handler
56
	Version *irma.ProtocolVersion
57

58
59
60
61
	choice  *irma.DisclosureChoice
	client  *Client
	request irma.SessionRequest
	done    bool
62

63
64
65
66
	// State for issuance protocol
	issuerProofNonce *big.Int
	builders         gabi.ProofBuilderList

67
	// These are empty on manual sessions
68
	ServerURL string
Koen van Ingen's avatar
Koen van Ingen committed
69
70
71
	info      *irma.SessionInfo
	jwt       irma.RequestorJwt
	transport *irma.HTTPTransport
72
73
}

74
// We implement the handler for the keyshare protocol
75
var _ keyshareSessionHandler = (*session)(nil)
76

77
78
// Supported protocol versions. Minor version numbers should be reverse sorted.
var supportedVersions = map[int][]int{
79
	2: {3, 2, 1},
80
81
}

82
// Session constructors
83

84
// NewSession starts a new IRMA session, given (along with a handler to pass feedback to)
85
// either an irma.QR or *irma.QR; a string that contains a JSON-serialized irma.QR;
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
// or a string that contains a serialized *irma.SignatureRequest.
// In any other case it calls the Failure method of the specified Handler.
func (client *Client) NewSession(info interface{}, handler Handler) SessionDismisser {
	parsed := map[string]interface{}{}

	switch x := info.(type) {
	case *irma.Qr: // Just start the session directly
		return client.newQrSession(x, handler)
	case irma.Qr:
		return client.newQrSession(&x, handler)

	// We assume the string contains a JSON object
	// Deserialize it into a temp to see which fields it contains, and infer from that what kind of object it is
	case string:
		bts := []byte(x)
		if err := json.Unmarshal(bts, &parsed); err != nil {
			handler.Failure(irma.ActionUnknown, &irma.SessionError{Err: err})
			return nil
		}

		if _, isqr := parsed["irmaqr"]; isqr {
			qr := &irma.Qr{}
			if err := json.Unmarshal(bts, qr); err != nil {
				handler.Failure(irma.ActionUnknown, &irma.SessionError{Err: err})
				return nil
			}
			return client.newQrSession(qr, handler)
		}

		if _, isSigRequest := parsed["message"]; isSigRequest {
			sigrequest := &irma.SignatureRequest{}
			if err := json.Unmarshal([]byte(x), sigrequest); err != nil {
				handler.Failure(irma.ActionUnknown, &irma.SessionError{Err: err})
				return nil
			}
			return client.newManualSession(sigrequest, handler)
		}
Koen van Ingen's avatar
Koen van Ingen committed
123
124
	}

125
126
127
128
129
130
	handler.Failure(irma.ActionUnknown, &irma.SessionError{Err: errors.New("Info specified of unsupported type")})
	return nil
}

// newManualSession starts a manual session, given a signature request in JSON and a handler to pass messages to
func (client *Client) newManualSession(sigrequest *irma.SignatureRequest, handler Handler) SessionDismisser {
131
	session := &session{
132
133
134
135
136
		Action:  irma.ActionSigning, // TODO hardcoded for now
		Handler: handler,
		client:  client,
		Version: irma.NewVersion(2, 0), // TODO hardcoded for now
		request: sigrequest,
Koen van Ingen's avatar
Koen van Ingen committed
137
138
139
140
	}

	session.Handler.StatusUpdate(session.Action, irma.StatusManualStarted)

141
	session.processSessionInfo("Email request")
142
	return session
143
144
}

145
146
// newQrSession creates and starts a new interactive IRMA session
func (client *Client) newQrSession(qr *irma.Qr, handler Handler) SessionDismisser {
147
	session := &session{
148
		ServerURL: qr.URL,
149
		transport: irma.NewHTTPTransport(qr.URL),
150
151
152
		Action:    irma.Action(qr.Type),
		Handler:   handler,
		client:    client,
153
	}
154
155
156
157
158
159

	if session.Action == irma.ActionSchemeManager {
		go session.managerSession()
		return session
	}

160
161
	version, err := calcVersion(qr)
	if err != nil {
162
		session.fail(&irma.SessionError{ErrorType: irma.ErrorProtocolVersionNotSupported, Err: err})
163
		return nil
164
	}
165
166
	session.Version = version
	session.transport.SetHeader("X-IRMA-ProtocolVersion", version.String())
167
168
169
	if !strings.HasSuffix(session.ServerURL, "/") {
		session.ServerURL += "/"
	}
170
171
172

	// Check if the action is one of the supported types
	switch session.Action {
173
174
175
176
	case irma.ActionDisclosing: // nop
	case irma.ActionSigning: // nop
	case irma.ActionIssuing: // nop
	case irma.ActionUnknown:
177
178
		fallthrough
	default:
179
		session.fail(&irma.SessionError{ErrorType: irma.ErrorUnknownAction, Info: string(session.Action)})
180
		return nil
181
182
	}

Sietse Ringers's avatar
Sietse Ringers committed
183
	go session.getSessionInfo()
184
	return session
185
186
}

187
188
// Core session methods

189
// getSessionInfo retrieves the first message in the IRMA protocol (only in interactive sessions)
Sietse Ringers's avatar
Sietse Ringers committed
190
191
func (session *session) getSessionInfo() {
	defer session.recoverFromPanic()
192

193
	session.Handler.StatusUpdate(session.Action, irma.StatusCommunicating)
194

Sietse Ringers's avatar
Sietse Ringers committed
195
	// Get the first IRMA protocol message and parse it
196
	session.info = &irma.SessionInfo{}
Sietse Ringers's avatar
Sietse Ringers committed
197
	Err := session.transport.Get("jwt", session.info)
Sietse Ringers's avatar
Sietse Ringers committed
198
	if Err != nil {
199
		session.fail(Err.(*irma.SessionError))
200
201
202
		return
	}

Sietse Ringers's avatar
Sietse Ringers committed
203
	var err error
204
	session.jwt, err = irma.ParseRequestorJwt(session.Action, session.info.Jwt)
Sietse Ringers's avatar
Sietse Ringers committed
205
	if err != nil {
206
		session.fail(&irma.SessionError{ErrorType: irma.ErrorInvalidJWT, Err: err})
Sietse Ringers's avatar
Sietse Ringers committed
207
208
		return
	}
209
210
211
212
	session.request = session.jwt.SessionRequest()
	session.request.SetContext(session.info.Context)
	session.request.SetNonce(session.info.Nonce)
	session.request.SetVersion(session.Version)
213
	if session.Action == irma.ActionIssuing {
214
		ir := session.request.(*irma.IssuanceRequest)
215
		// Store which public keys the server will use
216
		for _, credreq := range ir.Credentials {
217
			credreq.KeyCounter = session.info.Keys[credreq.CredentialTypeID.IssuerIdentifier()]
218
219
220
		}
	}

221
222
223
224
225
226
227
228
	session.processSessionInfo(session.jwt.Requestor())
}

// processSessionInfo continues the session after all session state has been received:
// it checks if the session can be performed and asks the user for consent.
func (session *session) processSessionInfo(requestorname string) {
	defer session.recoverFromPanic()

229
	if !session.checkAndUpateConfiguration() {
230
231
232
		return
	}

233
	if session.Action == irma.ActionIssuing {
234
		ir := session.request.(*irma.IssuanceRequest)
Tomas's avatar
Tomas committed
235
236
237
238
239
240
241
		_, err := ir.GetCredentialInfoList(session.client.Configuration, session.Version)
		if err != nil {
			session.fail(&irma.SessionError{ErrorType: irma.ErrorUnknownCredentialType, Err: err})
			return
		}

		// Calculate singleton credentials to be removed
Sietse Ringers's avatar
Sietse Ringers committed
242
		for _, credreq := range ir.Credentials {
243
244
245
246
			preexistingCredentials := session.client.attrs(*credreq.CredentialTypeID)
			if len(preexistingCredentials) != 0 && preexistingCredentials[0].IsValid() && preexistingCredentials[0].CredentialType().IsSingleton {
				ir.RemovalCredentialInfoList = append(ir.RemovalCredentialInfoList, preexistingCredentials[0].Info())
			}
247
248
249
		}
	}

250
	candidates, missing := session.client.CheckSatisfiability(session.request.ToDisclose())
251
	if len(missing) > 0 {
252
		session.Handler.UnsatisfiableRequest(session.Action, requestorname, missing)
253
254
		return
	}
255
	session.request.SetCandidates(candidates)
256

Sietse Ringers's avatar
Sietse Ringers committed
257
	// Ask for permission to execute the session
258
	callback := PermissionHandler(func(proceed bool, choice *irma.DisclosureChoice) {
Sietse Ringers's avatar
Sietse Ringers committed
259
		session.choice = choice
260
		session.request.SetDisclosureChoice(choice)
Sietse Ringers's avatar
Sietse Ringers committed
261
		go session.doSession(proceed)
262
	})
263
	session.Handler.StatusUpdate(session.Action, irma.StatusConnected)
264
	switch session.Action {
265
	case irma.ActionDisclosing:
266
		session.Handler.RequestVerificationPermission(
267
			*session.request.(*irma.DisclosureRequest), requestorname, callback)
268
	case irma.ActionSigning:
269
		session.Handler.RequestSignaturePermission(
270
			*session.request.(*irma.SignatureRequest), requestorname, callback)
271
	case irma.ActionIssuing:
272
		session.Handler.RequestIssuancePermission(
273
			*session.request.(*irma.IssuanceRequest), requestorname, callback)
274
275
276
277
278
	default:
		panic("Invalid session type") // does not happen, session.Action has been checked earlier
	}
}

279
280
281
// doSession performs the session: it computes all proofs of knowledge, constructs credentials in case of issuance,
// asks for the pin and performs the keyshare session, and finishes the session by either POSTing the result to the
// API server or returning it to the caller (in case of interactive and noninteractive sessions, respectively).
Sietse Ringers's avatar
Sietse Ringers committed
282
283
func (session *session) doSession(proceed bool) {
	defer session.recoverFromPanic()
284

285
	if !proceed {
286
		session.cancel()
287
288
		return
	}
289
	session.Handler.StatusUpdate(session.Action, irma.StatusCommunicating)
290

291
	if !session.Distributed() {
Koen van Ingen's avatar
Koen van Ingen committed
292
		message, err := session.getProof()
Sietse Ringers's avatar
Sietse Ringers committed
293
		if err != nil {
294
			session.fail(&irma.SessionError{ErrorType: irma.ErrorCrypto, Err: err})
Sietse Ringers's avatar
Sietse Ringers committed
295
296
297
298
			return
		}
		session.sendResponse(message)
	} else {
299
300
		var err error
		session.builders, session.issuerProofNonce, err = session.getBuilders()
Sietse Ringers's avatar
Sietse Ringers committed
301
		if err != nil {
302
			session.fail(&irma.SessionError{ErrorType: irma.ErrorCrypto, Err: err})
Sietse Ringers's avatar
Sietse Ringers committed
303
		}
304
305
306
		startKeyshareSession(
			session,
			session.Handler,
307
			session.builders,
308
			session.request,
309
			session.client.Configuration,
310
			session.client.keyshareServers,
311
			session.issuerProofNonce,
312
		)
313
	}
Sietse Ringers's avatar
Sietse Ringers committed
314
}
315

Sietse Ringers's avatar
Sietse Ringers committed
316
317
type disclosureResponse string

318
319
// sendResponse sends the proofs of knowledge of the hidden attributes and/or the secret key, or the constructed
// attribute-based signature, to the API server.
320
func (session *session) sendResponse(message interface{}) {
Sietse Ringers's avatar
Sietse Ringers committed
321
	var log *LogEntry
Sietse Ringers's avatar
Sietse Ringers committed
322
	var err error
323
324
	var messageJson []byte

325
326
	switch session.Action {
	case irma.ActionSigning:
327
		request, ok := session.request.(*irma.SignatureRequest)
328
329
330
331
332
		if !ok {
			session.fail(&irma.SessionError{ErrorType: irma.ErrorSerialization, Info: "Type assertion failed"})
			return
		}

333
334
335
336
337
338
		irmaSignature, err := request.SignatureFromMessage(message)
		if err != nil {
			session.fail(&irma.SessionError{ErrorType: irma.ErrorSerialization, Info: "Type assertion failed"})
			return
		}

339
340
341
342
343
344
345
		messageJson, err = json.Marshal(irmaSignature)
		if err != nil {
			session.fail(&irma.SessionError{ErrorType: irma.ErrorSerialization, Err: err})
			return
		}

		if session.IsInteractive() {
346
			var response disclosureResponse
347
			if err = session.transport.Post("proofs", &response, irmaSignature); err != nil {
348
349
350
351
352
353
354
				session.fail(err.(*irma.SessionError))
				return
			}
			if response != "VALID" {
				session.fail(&irma.SessionError{ErrorType: irma.ErrorRejected, Info: string(response)})
				return
			}
Sietse Ringers's avatar
Sietse Ringers committed
355
		}
356
		log, _ = session.createLogEntry(message.(gabi.ProofList)) // TODO err
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
	case irma.ActionDisclosing:
		var response disclosureResponse
		if err = session.transport.Post("proofs", &response, message); err != nil {
			session.fail(err.(*irma.SessionError))
			return
		}
		if response != "VALID" {
			session.fail(&irma.SessionError{ErrorType: irma.ErrorRejected, Info: string(response)})
			return
		}
		log, _ = session.createLogEntry(message.(gabi.ProofList)) // TODO err
	case irma.ActionIssuing:
		response := []*gabi.IssueSignatureMessage{}
		if err = session.transport.Post("commitments", &response, message); err != nil {
			session.fail(err.(*irma.SessionError))
			return
		}
374
		if err = session.client.ConstructCredentials(response, session.request.(*irma.IssuanceRequest), session.builders); err != nil {
375
			session.fail(&irma.SessionError{ErrorType: irma.ErrorCrypto, Err: err})
Sietse Ringers's avatar
Sietse Ringers committed
376
377
			return
		}
378
		log, _ = session.createLogEntry(message) // TODO err
379
380
	}

381
	_ = session.client.addLogEntry(log) // TODO err
382
	if session.Action == irma.ActionIssuing {
383
		session.client.handler.UpdateAttributes()
384
	}
385
	session.done = true
386
387
388
	session.Handler.Success(session.Action, string(messageJson))
}

389
// managerSession performs a "session" in which a new scheme manager is added (asking for permission first).
390
func (session *session) managerSession() {
391
	defer session.recoverFromPanic()
392
393
394
395

	// We have to download the scheme manager description.xml here before installing it,
	// because we need to show its contents (name, description, website) to the user
	// when asking installation permission.
396
	manager, err := irma.DownloadSchemeManager(session.ServerURL)
397
	if err != nil {
398
		session.Handler.Failure(session.Action, &irma.SessionError{ErrorType: irma.ErrorConfigurationDownload, Err: err})
399
400
		return
	}
401

402
	session.Handler.RequestSchemeManagerPermission(manager, func(proceed bool) {
403
		if !proceed {
404
			session.Handler.Cancelled(session.Action) // No need to DELETE session here
405
406
			return
		}
407
		if err := session.client.Configuration.InstallSchemeManager(manager); err != nil {
408
			session.Handler.Failure(session.Action, &irma.SessionError{ErrorType: irma.ErrorConfigurationDownload, Err: err})
Sietse Ringers's avatar
Sietse Ringers committed
409
410
			return
		}
411
412

		// Update state and inform user of success
413
		session.client.handler.UpdateConfiguration(
414
415
416
417
			&irma.IrmaIdentifierSet{
				SchemeManagers:  map[irma.SchemeManagerIdentifier]struct{}{manager.Identifier(): {}},
				Issuers:         map[irma.IssuerIdentifier]struct{}{},
				CredentialTypes: map[irma.CredentialTypeIdentifier]struct{}{},
Sietse Ringers's avatar
Sietse Ringers committed
418
419
			},
		)
420
		session.Handler.Success(session.Action, "")
421
422
423
	})
	return
}
424

425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
// Response calculation methods

// getBuilders computes the builders for disclosure proofs or secretkey-knowledge proof (in case of disclosure/signing
// and issuing respectively).
func (session *session) getBuilders() (gabi.ProofBuilderList, *big.Int, error) {
	var builders gabi.ProofBuilderList
	var err error

	var issuerProofNonce *big.Int
	switch session.Action {
	case irma.ActionSigning:
		builders, err = session.client.ProofBuilders(session.choice, session.request, true)
	case irma.ActionDisclosing:
		builders, err = session.client.ProofBuilders(session.choice, session.request, false)
	case irma.ActionIssuing:
		builders, issuerProofNonce, err = session.client.IssuanceProofBuilders(session.request.(*irma.IssuanceRequest))
	}

	return builders, issuerProofNonce, err
}

// getProofs computes the disclosure proofs or secretkey-knowledge proof (in case of disclosure/signing
// and issuing respectively) to be sent to the server.
func (session *session) getProof() (interface{}, error) {
	var message interface{}
	var err error

	switch session.Action {
	case irma.ActionSigning:
		message, err = session.client.Proofs(session.choice, session.request, true)
	case irma.ActionDisclosing:
		message, err = session.client.Proofs(session.choice, session.request, false)
	case irma.ActionIssuing:
		message, session.builders, err = session.client.IssueCommitments(session.request.(*irma.IssuanceRequest))
	}

	return message, err
}

// Helper functions

func calcVersion(qr *irma.Qr) (*irma.ProtocolVersion, error) {
	// Iterate supportedVersions in reverse sorted order (i.e. biggest major number first)
	keys := make([]int, 0, len(supportedVersions))
	for k := range supportedVersions {
		keys = append(keys, k)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(keys)))
	for _, major := range keys {
		for _, minor := range supportedVersions[major] {
			aboveMinimum := major > qr.ProtocolVersion.Major || (major == qr.ProtocolVersion.Major && minor >= qr.ProtocolVersion.Minor)
			underMaximum := major < qr.ProtocolMaxVersion.Major || (major == qr.ProtocolMaxVersion.Major && minor <= qr.ProtocolMaxVersion.Minor)
			if aboveMinimum && underMaximum {
				return irma.NewVersion(major, minor), nil
			}
		}
	}
	return nil, fmt.Errorf("No supported protocol version between %s and %s", qr.ProtocolVersion.String(), qr.ProtocolMaxVersion.String())
}

// checkKeyshareEnrollment checks if we are enrolled into all involved keyshare servers,
// and aborts the session if not
func (session *session) checkKeyshareEnrollment() bool {
	for id := range session.request.Identifiers().SchemeManagers {
		manager, ok := session.client.Configuration.SchemeManagers[id]
		if !ok {
			session.Handler.Failure(session.Action, &irma.SessionError{ErrorType: irma.ErrorUnknownSchemeManager, Info: id.String()})
			return false
		}
		distributed := manager.Distributed()
		_, enrolled := session.client.keyshareServers[id]
		if distributed && !enrolled {
			session.Handler.KeyshareEnrollmentMissing(id)
			return false
		}
	}
	return true
}

func (session *session) checkAndUpateConfiguration() bool {
	for id := range session.request.Identifiers().SchemeManagers {
		manager, contains := session.client.Configuration.SchemeManagers[id]
		if !contains {
			session.fail(&irma.SessionError{
				ErrorType: irma.ErrorUnknownSchemeManager,
				Info:      id.String(),
			})
			return false
		}
		if !manager.Valid {
			session.fail(&irma.SessionError{
				ErrorType: irma.ErrorInvalidSchemeManager,
				Info:      string(manager.Status),
			})
			return false
		}
	}

	// Check if we are enrolled into all involved keyshare servers
	if !session.checkKeyshareEnrollment() {
		return false
	}

	// Download missing credential types/issuers/public keys from the scheme manager
	downloaded, err := session.client.Configuration.Download(session.request)
	if err != nil {
		session.fail(&irma.SessionError{ErrorType: irma.ErrorConfigurationDownload, Err: err})
		return false
	}
	if downloaded != nil && !downloaded.Empty() {
		session.client.handler.UpdateConfiguration(downloaded)
	}
	return true
}

// IsInteractive returns whether this session uses an API server or not.
func (session *session) IsInteractive() bool {
	return session.ServerURL != ""
}

// Distributed returns whether or not this session involves a keyshare server.
func (session *session) Distributed() bool {
	var smi irma.SchemeManagerIdentifier
	if session.Action == irma.ActionIssuing {
		for _, credreq := range session.request.(*irma.IssuanceRequest).Credentials {
			smi = credreq.CredentialTypeID.IssuerIdentifier().SchemeManagerIdentifier()
			if session.client.Configuration.SchemeManagers[smi].Distributed() {
				return true
			}
		}
	}

	if session.choice == nil || session.choice.Attributes == nil {
		return false
	}

	for _, ai := range session.choice.Attributes {
		smi = ai.Type.CredentialTypeIdentifier().IssuerIdentifier().SchemeManagerIdentifier()
		if session.client.Configuration.SchemeManagers[smi].Distributed() {
			return true
		}
	}

	return false
}

571
572
// Session lifetime functions

573
574
575
576
577
578
579
580
func (session *session) recoverFromPanic() {
	if e := recover(); e != nil {
		if session.Handler != nil {
			session.Handler.Failure(session.Action, panicToError(e))
		}
	}
}

581
582
583
584
585
586
587
588
589
590
func panicToError(e interface{}) *irma.SessionError {
	var info string
	switch x := e.(type) {
	case string:
		info = x
	case error:
		info = x.Error()
	case fmt.Stringer:
		info = x.String()
	default: // nop
591
	}
592
	fmt.Println("Panic: " + info)
593
	return &irma.SessionError{ErrorType: irma.ErrorPanic, Info: info}
594
595
596
}

// Idempotently send DELETE to remote server, returning whether or not we did something
597
func (session *session) delete() bool {
598
	if !session.done {
599
600
601
		if session.IsInteractive() {
			session.transport.Delete()
		}
602
		session.done = true
603
604
605
606
607
		return true
	}
	return false
}

608
func (session *session) fail(err *irma.SessionError) {
609
610
611
612
613
614
	if session.delete() {
		err.Err = errors.Wrap(err.Err, 0)
		session.Handler.Failure(session.Action, err)
	}
}

615
func (session *session) cancel() {
616
617
618
619
620
	if session.delete() {
		session.Handler.Cancelled(session.Action)
	}
}

621
func (session *session) Dismiss() {
622
623
	session.cancel()
}
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664

// Keyshare session handler methods

func (session *session) KeyshareDone(message interface{}) {
	session.sendResponse(message)
}

func (session *session) KeyshareCancelled() {
	session.cancel()
}

func (session *session) KeyshareEnrollmentIncomplete(manager irma.SchemeManagerIdentifier) {
	session.Handler.KeyshareEnrollmentIncomplete(manager)
}

func (session *session) KeyshareEnrollmentDeleted(manager irma.SchemeManagerIdentifier) {
	session.Handler.KeyshareEnrollmentDeleted(manager)
}

func (session *session) KeyshareBlocked(manager irma.SchemeManagerIdentifier, duration int) {
	session.Handler.KeyshareBlocked(manager, duration)
}

func (session *session) KeyshareError(manager *irma.SchemeManagerIdentifier, err error) {
	var serr *irma.SessionError
	var ok bool
	if serr, ok = err.(*irma.SessionError); !ok {
		serr = &irma.SessionError{ErrorType: irma.ErrorKeyshare, Err: err}
	} else {
		serr.ErrorType = irma.ErrorKeyshare
	}
	session.fail(serr)
}

func (session *session) KeysharePin() {
	session.Handler.StatusUpdate(session.Action, irma.StatusConnected)
}

func (session *session) KeysharePinOK() {
	session.Handler.StatusUpdate(session.Action, irma.StatusCommunicating)
}