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/irmago"
Sietse Ringers's avatar
Sietse Ringers committed
18
	"github.com/privacybydesign/irmago/server"
19
	"github.com/sirupsen/logrus"
20
21
)

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

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

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

47
48
49
50
51
52
53
54
55
	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
			}
56
			if err := s.conf.IrmaConfiguration.RevocationStorage.RevocationUpdateDB(credid); err != nil {
57
58
59
60
61
				s.conf.Logger.Error("failed to update revocation database for %s:", credid.String())
				_ = server.LogError(err)
			}
		}
	})
62

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

65
	return s, nil
66
}
67

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

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

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

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

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

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

102
103
104
105
	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))
106
	} else {
107
		s.conf.Logger.WithFields(logrus.Fields{"session": session.token}).Info("Session request (purged of attribute values): ", server.ToJson(purgeRequest(rrequest)))
108
	}
109
110
	return &irma.Qr{
		Type: action,
111
		URL:  s.conf.URL + "session/" + session.clientToken,
112
113
114
	}, session.token, nil
}

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

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

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

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

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

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

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

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

168
169
170
171
172
173
	var session *session
	if requestor {
		session = s.sessions.get(token)
	} else {
		session = s.sessions.clientGet(token)
	}
174
175
176
177
178
179
180
181
182
	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()
183
184
185
186
187
188
189
190
191
192
193
194
195

	// 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)
196
197
198
	return nil
}

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

	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
225
) (status int, output []byte, result *server.SessionResult) {
226
227
228
229
230
231
232
233
234
	// 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]
		}
	}
235

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

241
242
243
244
245
246
247
248
249
250
251
	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
252
	// Fetch the session
253
	session := s.sessions.clientGet(token)
254
	if session == nil {
255
		s.conf.Logger.WithField("clientToken", token).Warn("Session not found")
Sietse Ringers's avatar
Sietse Ringers committed
256
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorSessionUnknown, ""))
257
		return
258
	}
259
260
	session.Lock()
	defer session.Unlock()
261

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

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

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

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

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

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

335
		if noun == "proofs" && session.action == irma.ActionDisclosing {
336
337
338
339
340
341
342
			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()))
343
				return
344
			}
Sietse Ringers's avatar
Sietse Ringers committed
345
			status, output = server.JsonResponse(session.handlePostDisclosure(disclosure))
346
			session.responseCache = responseCache{message: message, response: output, status: status, sessionStatus: server.StatusDone}
Sietse Ringers's avatar
Sietse Ringers committed
347
348
			return
		}
349

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

Sietse Ringers's avatar
Sietse Ringers committed
365
		status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
366
		return
367
368
	}
}
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388

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])
389
		var records []*irma.Record
390
391
392
393
394
		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))
	}
395
396
397
398
399
400
401
402
403
404
405
	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))
	}
406
407
408

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