api.go 12.8 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

	// TODO: how do we not update revocation state for credential types of which we are the authoritative server?
	//s.scheduler.Every(5).Minutes().Do(func() {
	//	if err := s.conf.IrmaConfiguration.RevocationUpdateAll(); err != nil {
	//		s.conf.Logger.Error("failed to update revocation database:")
	//		_ = server.LogError(err)
	//	}
	//})

56
	s.stopScheduler = s.scheduler.Start()
57

58
	return s, nil
59
}
60

61
func (s *Server) Stop() {
62
63
64
	if err := s.conf.IrmaConfiguration.Close(); err != nil {
		_ = server.LogWarning(err)
	}
65
66
67
68
	s.stopScheduler <- true
	s.sessions.stop()
}

69
func (s *Server) validateRequest(request irma.SessionRequest) error {
70
71
72
73
	if _, err := s.conf.IrmaConfiguration.Download(request); err != nil {
		return err
	}
	return request.Disclosure().Disclose.Validate(s.conf.IrmaConfiguration)
74
75
}

76
func (s *Server) StartSession(req interface{}) (*irma.Qr, string, error) {
77
78
	rrequest, err := server.ParseSessionRequest(req)
	if err != nil {
79
		return nil, "", err
80
	}
81
82
83

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

Leon's avatar
Leon committed
85
86
87
88
	if err := s.validateRequest(request); err != nil {
		return nil, "", err
	}

89
	if action == irma.ActionIssuing {
90
		if err := s.validateIssuanceRequest(request.(*irma.IssuanceRequest)); err != nil {
91
			return nil, "", err
92
93
94
		}
	}

95
96
97
98
	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))
99
	} else {
100
		s.conf.Logger.WithFields(logrus.Fields{"session": session.token}).Info("Session request (purged of attribute values): ", server.ToJson(purgeRequest(rrequest)))
101
	}
102
103
	return &irma.Qr{
		Type: action,
104
		URL:  s.conf.URL + "session/" + session.clientToken,
105
106
107
	}, session.token, nil
}

108
109
func (s *Server) GetSessionResult(token string) *server.SessionResult {
	session := s.sessions.get(token)
110
	if session == nil {
111
		s.conf.Logger.Warn("Session result requested of unknown session ", token)
Sietse Ringers's avatar
Sietse Ringers committed
112
113
114
115
116
		return nil
	}
	return session.result
}

117
118
func (s *Server) GetRequest(token string) irma.RequestorRequest {
	session := s.sessions.get(token)
119
	if session == nil {
120
		s.conf.Logger.Warn("Session request requested of unknown session ", token)
121
122
123
124
125
		return nil
	}
	return session.rrequest
}

126
127
func (s *Server) CancelSession(token string) error {
	session := s.sessions.get(token)
128
	if session == nil {
129
		return server.LogError(errors.Errorf("can't cancel unknown session %s", token))
130
131
132
133
134
	}
	session.handleDelete()
	return nil
}

135
136
func ParsePath(path string) (token, noun string, arg []string, err error) {
	rev := regexp.MustCompile("-/revocation/(records)/?(.*)$")
137
	matches := rev.FindStringSubmatch(path)
138
139
140
141
142
	if len(matches) == 3 {
		args := strings.Split(matches[2], "/")
		return "", matches[1], args, nil
	}

143
144
145
146
147
148
	client := regexp.MustCompile("session/(\\w+)/?(|commitments|proofs|status|statusevents)$")
	matches = client.FindStringSubmatch(path)
	if len(matches) == 3 {
		return matches[1], matches[2], nil, nil
	}

149
	return "", "", nil, server.LogWarning(errors.Errorf("Invalid URL: %s", path))
150
151
}

152
func (s *Server) SubscribeServerSentEvents(w http.ResponseWriter, r *http.Request, token string, requestor bool) error {
153
154
155
156
	if !s.conf.EnableSSE {
		return errors.New("Server sent events disabled")
	}

157
158
159
160
161
162
	var session *session
	if requestor {
		session = s.sessions.get(token)
	} else {
		session = s.sessions.clientGet(token)
	}
163
164
165
166
167
168
169
170
171
	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()
172
173
174
175
176
177
178
179
180
181
182
183
184

	// 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)
185
186
187
	return nil
}

188
func (s *Server) HandleProtocolMessage(
189
190
191
192
	path string,
	method string,
	headers map[string][]string,
	message []byte,
193
194
195
196
) (int, []byte, *server.SessionResult) {
	var start time.Time
	if s.conf.Verbose >= 2 {
		start = time.Now()
197
		server.LogRequest("client", method, path, "", http.Header(headers), message)
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
	}

	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
214
) (status int, output []byte, result *server.SessionResult) {
215
216
217
218
219
220
221
222
223
	// 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]
		}
	}
224

225
	token, noun, args, err := ParsePath(path)
226
227
	if err != nil {
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorUnsupported, ""))
228
229
	}

230
231
232
233
234
235
236
237
238
239
240
	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
241
	// Fetch the session
242
	session := s.sessions.clientGet(token)
243
	if session == nil {
244
		s.conf.Logger.WithField("clientToken", token).Warn("Session not found")
Sietse Ringers's avatar
Sietse Ringers committed
245
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorSessionUnknown, ""))
246
		return
247
	}
248
249
	session.Lock()
	defer session.Unlock()
250

251
252
	// However we return, if the session status has been updated
	// then we should inform the user by returning a SessionResult
253
	defer func() {
254
255
		if session.status != session.prevStatus {
			session.prevStatus = session.status
256
257
258
259
			result = session.result
		}
	}()

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

291
	default:
292
293
294
295
296
297
		if noun == "statusevents" {
			err := server.RemoteError(server.ErrorInvalidRequest, "server sent events not supported by this server")
			status, output = server.JsonResponse(nil, err)
			return
		}

298
299
		if method == http.MethodGet && noun == "status" {
			status, output = server.JsonResponse(session.handleGetStatus())
Sietse Ringers's avatar
Sietse Ringers committed
300
			return
301
302
303
		}

		// Below are only POST enpoints
304
		if method != http.MethodPost {
Sietse Ringers's avatar
Sietse Ringers committed
305
			status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
Sietse Ringers's avatar
Sietse Ringers committed
306
307
308
			return
		}

309
		if noun == "commitments" && session.action == irma.ActionIssuing {
310
311
312
313
			status, output = session.checkCache(message, server.StatusDone)
			if len(output) != 0 {
				return
			}
Sietse Ringers's avatar
Sietse Ringers committed
314
			commitments := &irma.IssueCommitmentMessage{}
315
316
			if err = irma.UnmarshalValidate(message, commitments); err != nil {
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
317
				return
318
			}
Sietse Ringers's avatar
Sietse Ringers committed
319
			status, output = server.JsonResponse(session.handlePostCommitments(commitments))
320
			session.responseCache = responseCache{message: message, response: output, status: status, sessionStatus: server.StatusDone}
Sietse Ringers's avatar
Sietse Ringers committed
321
322
			return
		}
323

324
		if noun == "proofs" && session.action == irma.ActionDisclosing {
325
326
327
328
329
330
331
			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()))
332
				return
333
			}
Sietse Ringers's avatar
Sietse Ringers committed
334
			status, output = server.JsonResponse(session.handlePostDisclosure(disclosure))
335
			session.responseCache = responseCache{message: message, response: output, status: status, sessionStatus: server.StatusDone}
Sietse Ringers's avatar
Sietse Ringers committed
336
337
			return
		}
338

339
		if noun == "proofs" && session.action == irma.ActionSigning {
340
341
342
343
			status, output = session.checkCache(message, server.StatusDone)
			if len(output) != 0 {
				return
			}
Sietse Ringers's avatar
Sietse Ringers committed
344
			signature := &irma.SignedMessage{}
345
346
			if err = irma.UnmarshalValidate(message, signature); err != nil {
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
347
				return
348
			}
Sietse Ringers's avatar
Sietse Ringers committed
349
			status, output = server.JsonResponse(session.handlePostSignature(signature))
350
			session.responseCache = responseCache{message: message, response: output, status: status, sessionStatus: server.StatusDone}
351
			return
352
		}
Sietse Ringers's avatar
Sietse Ringers committed
353

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

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))
	}
384
385
386
387
388
389
390
	//if noun == "revoke" && 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])
	//	return server.JsonResponse(s.handleRevoke(cred, message))
	//}
391
392
393

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