api.go 13.3 KB
Newer Older
Sietse Ringers's avatar
Sietse Ringers committed
1
// Package servercore is the core of the IRMA server library, allowing IRMA verifiers, issuers
2
3
// or attribute-based signature applications to perform IRMA sessions with irmaclient instances
// (i.e. the IRMA app). It exposes a small interface to expose to other programming languages
Sietse Ringers's avatar
Sietse Ringers committed
4
// through cgo. It is used by the irmaserver package but otherwise not meant for use in Go.
5
package servercore
6
7
8
9
10

import (
	"encoding/json"
	"net/http"
	"regexp"
11
	"strconv"
12
	"strings"
13
	"time"
14
15

	"github.com/go-errors/errors"
16
	"github.com/jasonlvhit/gocron"
17
	"github.com/privacybydesign/gabi/revocation"
18
	"github.com/privacybydesign/irmago"
Sietse Ringers's avatar
Sietse Ringers committed
19
	"github.com/privacybydesign/irmago/server"
20
	"github.com/sirupsen/logrus"
21
22
)

23
type Server struct {
24
25
26
27
	conf          *server.Configuration
	sessions      sessionStore
	scheduler     *gocron.Scheduler
	stopScheduler chan bool
28
29
30
}

func New(conf *server.Configuration) (*Server, error) {
31
32
33
34
	if err := conf.Check(); err != nil {
		return nil, err
	}

35
36
37
38
	s := &Server{
		conf:      conf,
		scheduler: gocron.NewScheduler(),
		sessions: &memorySessionStore{
39
40
41
			requestor: make(map[string]*session),
			client:    make(map[string]*session),
			conf:      conf,
42
43
44
45
46
		},
	}
	s.scheduler.Every(10).Seconds().Do(func() {
		s.sessions.deleteExpired()
	})
47

48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
	s.scheduler.Every(5).Minutes().Do(func() {
		for credid, credtype := range s.conf.IrmaConfiguration.CredentialTypes {
			if !credtype.SupportsRevocation() {
				continue
			}
			if _, ours := conf.RevocationServers[credid]; ours {
				// TODO rethink this condition
				continue
			}
			if err := s.conf.IrmaConfiguration.RevocationUpdateDB(credid); err != nil {
				s.conf.Logger.Error("failed to update revocation database for %s:", credid.String())
				_ = server.LogError(err)
			}
		}
	})
63

64
	s.stopScheduler = s.scheduler.Start()
65

66
	return s, nil
67
}
68

69
func (s *Server) Stop() {
70
71
72
	if err := s.conf.IrmaConfiguration.Close(); err != nil {
		_ = server.LogWarning(err)
	}
73
74
75
76
	s.stopScheduler <- true
	s.sessions.stop()
}

77
func (s *Server) validateRequest(request irma.SessionRequest) error {
78
79
80
81
	if _, err := s.conf.IrmaConfiguration.Download(request); err != nil {
		return err
	}
	return request.Disclosure().Disclose.Validate(s.conf.IrmaConfiguration)
82
83
}

84
func (s *Server) StartSession(req interface{}) (*irma.Qr, string, error) {
85
86
	rrequest, err := server.ParseSessionRequest(req)
	if err != nil {
87
		return nil, "", err
88
	}
89
90
91

	request := rrequest.SessionRequest()
	action := request.Action()
92

Leon's avatar
Leon committed
93
94
95
96
	if err := s.validateRequest(request); err != nil {
		return nil, "", err
	}

97
	if action == irma.ActionIssuing {
98
		if err := s.validateIssuanceRequest(request.(*irma.IssuanceRequest)); err != nil {
99
			return nil, "", err
100
101
102
		}
	}

103
104
105
106
	session := s.newSession(action, rrequest)
	s.conf.Logger.WithFields(logrus.Fields{"action": action, "session": session.token}).Infof("Session started")
	if s.conf.Logger.IsLevelEnabled(logrus.DebugLevel) {
		s.conf.Logger.WithFields(logrus.Fields{"session": session.token}).Info("Session request: ", server.ToJson(rrequest))
107
	} else {
108
		s.conf.Logger.WithFields(logrus.Fields{"session": session.token}).Info("Session request (purged of attribute values): ", server.ToJson(purgeRequest(rrequest)))
109
	}
110
111
	return &irma.Qr{
		Type: action,
112
		URL:  s.conf.URL + "session/" + session.clientToken,
113
114
115
	}, session.token, nil
}

116
117
func (s *Server) GetSessionResult(token string) *server.SessionResult {
	session := s.sessions.get(token)
118
	if session == nil {
119
		s.conf.Logger.Warn("Session result requested of unknown session ", token)
Sietse Ringers's avatar
Sietse Ringers committed
120
121
122
123
124
		return nil
	}
	return session.result
}

125
126
func (s *Server) GetRequest(token string) irma.RequestorRequest {
	session := s.sessions.get(token)
127
	if session == nil {
128
		s.conf.Logger.Warn("Session request requested of unknown session ", token)
129
130
131
132
133
		return nil
	}
	return session.rrequest
}

134
135
func (s *Server) CancelSession(token string) error {
	session := s.sessions.get(token)
136
	if session == nil {
137
		return server.LogError(errors.Errorf("can't cancel unknown session %s", token))
138
139
140
141
142
	}
	session.handleDelete()
	return nil
}

143
144
145
146
func (s *Server) Revoke(credid irma.CredentialTypeIdentifier, key string) error {
	return s.conf.IrmaConfiguration.Revoke(credid, key)
}

147
func ParsePath(path string) (token, noun string, arg []string, err error) {
148
	rev := regexp.MustCompile("-/revocation/(records|issuancerecord)/?(.*)$")
149
	matches := rev.FindStringSubmatch(path)
150
151
152
153
154
	if len(matches) == 3 {
		args := strings.Split(matches[2], "/")
		return "", matches[1], args, nil
	}

155
156
157
158
159
160
	client := regexp.MustCompile("session/(\\w+)/?(|commitments|proofs|status|statusevents)$")
	matches = client.FindStringSubmatch(path)
	if len(matches) == 3 {
		return matches[1], matches[2], nil, nil
	}

161
	return "", "", nil, server.LogWarning(errors.Errorf("Invalid URL: %s", path))
162
163
}

164
func (s *Server) SubscribeServerSentEvents(w http.ResponseWriter, r *http.Request, token string, requestor bool) error {
165
166
167
168
	if !s.conf.EnableSSE {
		return errors.New("Server sent events disabled")
	}

169
170
171
172
173
174
	var session *session
	if requestor {
		session = s.sessions.get(token)
	} else {
		session = s.sessions.clientGet(token)
	}
175
176
177
178
179
180
181
182
183
	if session == nil {
		return server.LogError(errors.Errorf("can't subscribe to server sent events of unknown session %s", token))
	}
	if session.status.Finished() {
		return server.LogError(errors.Errorf("can't subscribe to server sent events of finished session %s", token))
	}

	session.Lock()
	defer session.Unlock()
184
185
186
187
188
189
190
191
192
193
194
195
196

	// The EventSource.onopen Javascript callback is not consistently called across browsers (Chrome yes, Firefox+Safari no).
	// However, when the SSE connection has been opened the webclient needs some signal so that it can early detect SSE failures.
	// So we manually send an "open" event. Unfortunately:
	// - we need to give the webclient that connected just now some time, otherwise it will miss the "open" event
	// - the "open" event also goes to all other webclients currently listening, as we have no way to send this
	//   event to just the webclient currently listening. (Thus the handler of this "open" event must be idempotent.)
	evtSource := session.eventSource()
	go func() {
		time.Sleep(200 * time.Millisecond)
		evtSource.SendEventMessage("", "open", "")
	}()
	evtSource.ServeHTTP(w, r)
197
198
199
	return nil
}

200
func (s *Server) HandleProtocolMessage(
201
202
203
204
	path string,
	method string,
	headers map[string][]string,
	message []byte,
205
206
207
208
) (int, []byte, *server.SessionResult) {
	var start time.Time
	if s.conf.Verbose >= 2 {
		start = time.Now()
209
		server.LogRequest("client", method, path, "", http.Header(headers), message)
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
	}

	status, output, result := s.handleProtocolMessage(path, method, headers, message)

	if s.conf.Verbose >= 2 {
		server.LogResponse(status, time.Now().Sub(start), output)
	}

	return status, output, result
}

func (s *Server) handleProtocolMessage(
	path string,
	method string,
	headers map[string][]string,
	message []byte,
Sietse Ringers's avatar
Sietse Ringers committed
226
) (status int, output []byte, result *server.SessionResult) {
227
228
229
230
231
232
233
234
235
	// Parse path into session and action
	if len(path) > 0 { // Remove any starting and trailing slash
		if path[0] == '/' {
			path = path[1:]
		}
		if path[len(path)-1] == '/' {
			path = path[:len(path)-1]
		}
	}
236

237
	token, noun, args, err := ParsePath(path)
238
239
	if err != nil {
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorUnsupported, ""))
240
241
	}

242
243
244
245
246
247
248
249
250
251
252
	if token != "" {
		status, output, result = s.handleClientMessage(token, noun, method, headers, message)
	} else {
		status, output = s.handleRevocationMessage(noun, method, args, headers, message)
	}
	return
}

func (s *Server) handleClientMessage(
	token, noun, method string, headers map[string][]string, message []byte,
) (status int, output []byte, result *server.SessionResult) {
Sietse Ringers's avatar
Sietse Ringers committed
253
	// Fetch the session
254
	session := s.sessions.clientGet(token)
255
	if session == nil {
256
		s.conf.Logger.WithField("clientToken", token).Warn("Session not found")
Sietse Ringers's avatar
Sietse Ringers committed
257
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorSessionUnknown, ""))
258
		return
259
	}
260
261
	session.Lock()
	defer session.Unlock()
262

263
264
	// However we return, if the session status has been updated
	// then we should inform the user by returning a SessionResult
265
	defer func() {
266
267
		if session.status != session.prevStatus {
			session.prevStatus = session.status
268
269
270
271
			result = session.result
		}
	}()

272
	// Route to handler
273
	switch len(noun) {
274
	case 0:
275
		if method == http.MethodDelete {
276
277
278
			session.handleDelete()
			status = http.StatusOK
			return
279
		}
280
		if method == http.MethodGet {
281
282
283
284
			status, output = session.checkCache(message, server.StatusConnected)
			if len(output) != 0 {
				return
			}
285
286
287
288
			h := http.Header(headers)
			min := &irma.ProtocolVersion{}
			max := &irma.ProtocolVersion{}
			if err := json.Unmarshal([]byte(h.Get(irma.MinVersionHeader)), min); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
289
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
290
				return
291
292
			}
			if err := json.Unmarshal([]byte(h.Get(irma.MaxVersionHeader)), max); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
293
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
294
				return
295
			}
Sietse Ringers's avatar
Sietse Ringers committed
296
			status, output = server.JsonResponse(session.handleGetRequest(min, max))
297
			session.responseCache = responseCache{message: message, response: output, status: status, sessionStatus: server.StatusConnected}
298
			return
299
		}
Sietse Ringers's avatar
Sietse Ringers committed
300
		status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
301
		return
302

303
	default:
304
305
306
307
308
309
		if noun == "statusevents" {
			err := server.RemoteError(server.ErrorInvalidRequest, "server sent events not supported by this server")
			status, output = server.JsonResponse(nil, err)
			return
		}

310
311
		if method == http.MethodGet && noun == "status" {
			status, output = server.JsonResponse(session.handleGetStatus())
Sietse Ringers's avatar
Sietse Ringers committed
312
			return
313
314
315
		}

		// Below are only POST enpoints
316
		if method != http.MethodPost {
Sietse Ringers's avatar
Sietse Ringers committed
317
			status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
Sietse Ringers's avatar
Sietse Ringers committed
318
319
320
			return
		}

321
		if noun == "commitments" && session.action == irma.ActionIssuing {
322
323
324
325
			status, output = session.checkCache(message, server.StatusDone)
			if len(output) != 0 {
				return
			}
Sietse Ringers's avatar
Sietse Ringers committed
326
			commitments := &irma.IssueCommitmentMessage{}
327
328
			if err = irma.UnmarshalValidate(message, commitments); err != nil {
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
329
				return
330
			}
Sietse Ringers's avatar
Sietse Ringers committed
331
			status, output = server.JsonResponse(session.handlePostCommitments(commitments))
332
			session.responseCache = responseCache{message: message, response: output, status: status, sessionStatus: server.StatusDone}
Sietse Ringers's avatar
Sietse Ringers committed
333
334
			return
		}
335

336
		if noun == "proofs" && session.action == irma.ActionDisclosing {
337
338
339
340
341
342
343
			status, output = session.checkCache(message, server.StatusDone)
			if len(output) != 0 {
				return
			}
			disclosure := &irma.Disclosure{}
			if err = irma.UnmarshalValidate(message, disclosure); err != nil {
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
344
				return
345
			}
Sietse Ringers's avatar
Sietse Ringers committed
346
			status, output = server.JsonResponse(session.handlePostDisclosure(disclosure))
347
			session.responseCache = responseCache{message: message, response: output, status: status, sessionStatus: server.StatusDone}
Sietse Ringers's avatar
Sietse Ringers committed
348
349
			return
		}
350

351
		if noun == "proofs" && session.action == irma.ActionSigning {
352
353
354
355
			status, output = session.checkCache(message, server.StatusDone)
			if len(output) != 0 {
				return
			}
Sietse Ringers's avatar
Sietse Ringers committed
356
			signature := &irma.SignedMessage{}
357
358
			if err = irma.UnmarshalValidate(message, signature); err != nil {
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
359
				return
360
			}
Sietse Ringers's avatar
Sietse Ringers committed
361
			status, output = server.JsonResponse(session.handlePostSignature(signature))
362
			session.responseCache = responseCache{message: message, response: output, status: status, sessionStatus: server.StatusDone}
363
			return
364
		}
Sietse Ringers's avatar
Sietse Ringers committed
365

Sietse Ringers's avatar
Sietse Ringers committed
366
		status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
367
		return
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

func (s *Server) handleRevocationMessage(
	noun, method string, args []string, headers map[string][]string, message []byte,
) (int, []byte) {
	if noun == "records" && method == http.MethodGet {
		if len(args) != 2 {
			return server.JsonResponse(nil, server.RemoteError(server.ErrorInvalidRequest, "GET records expects 2 url arguments"))
		}
		index, err := strconv.Atoi(args[1])
		if err != nil {
			return server.JsonResponse(nil, server.RemoteError(server.ErrorMalformedInput, err.Error()))
		}
		cred := irma.NewCredentialTypeIdentifier(args[0])
		return server.JsonResponse(s.handleGetRevocationRecords(cred, index))
	}
	if noun == "records" && method == http.MethodPost {
		if len(args) != 1 {
			return server.JsonResponse(nil, server.RemoteError(server.ErrorInvalidRequest, "POST records expects 1 url arguments"))
		}
		cred := irma.NewCredentialTypeIdentifier(args[0])
		var records []*revocation.Record
		if err := json.Unmarshal(message, &records); err != nil {
			return server.JsonResponse(nil, server.RemoteError(server.ErrorMalformedInput, err.Error()))
		}
		return server.JsonResponse(s.handlePostRevocationRecords(cred, records))
	}
396
397
398
399
400
401
402
403
404
405
406
	if noun == "issuancerecord" && method == http.MethodPost {
		if len(args) != 2 {
			return server.JsonResponse(nil, server.RemoteError(server.ErrorInvalidRequest, "POST issuancercord expects 2 url arguments"))
		}
		cred := irma.NewCredentialTypeIdentifier(args[0])
		counter, err := strconv.Atoi(args[1])
		if err != nil {
			return server.JsonResponse(nil, server.RemoteError(server.ErrorMalformedInput, err.Error()))
		}
		return server.JsonResponse(s.handlePostIssuanceRecord(cred, counter, message))
	}
407
408
409

	return server.JsonResponse(nil, server.RemoteError(server.ErrorInvalidRequest, ""))
}