api.go 13.7 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
	s.scheduler.Every(5).Minutes().Do(func() {
		for credid, credtype := range s.conf.IrmaConfiguration.CredentialTypes {
			if !credtype.SupportsRevocation() {
				continue
			}
53
			if s := conf.RevocationSettings[credid]; s != nil && s.Mode != irma.RevocationModeRequestor {
54 55
				continue
			}
56
			if err := s.conf.IrmaConfiguration.Revocation.UpdateDB(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.Revocation.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
	sk, err := s.conf.IrmaConfiguration.PrivateKey(credid.IssuerIdentifier())
144 145 146 147 148 149 150 151 152 153
	if err != nil {
		return err
	}
	if sk == nil {
		return errors.Errorf("cannot revoke: private key of %s not found", credid.IssuerIdentifier())
	}
	rsk, err := sk.RevocationKey()
	if err != nil {
		return err
	}
154
	return s.conf.IrmaConfiguration.Revocation.Revoke(credid, key, rsk)
155 156
}

157
func ParsePath(path string) (token, noun string, arg []string, err error) {
158
	rev := regexp.MustCompile("revocation/(updatefrom|updatelatest|update|issuancerecord)/?(.*)$")
159
	matches := rev.FindStringSubmatch(path)
160 161 162 163 164
	if len(matches) == 3 {
		args := strings.Split(matches[2], "/")
		return "", matches[1], args, nil
	}

165 166 167 168 169 170
	client := regexp.MustCompile("session/(\\w+)/?(|commitments|proofs|status|statusevents)$")
	matches = client.FindStringSubmatch(path)
	if len(matches) == 3 {
		return matches[1], matches[2], nil, nil
	}

171
	return "", "", nil, server.LogWarning(errors.Errorf("Invalid URL: %s", path))
172 173
}

174
func (s *Server) SubscribeServerSentEvents(w http.ResponseWriter, r *http.Request, token string, requestor bool) error {
175 176 177 178
	if !s.conf.EnableSSE {
		return errors.New("Server sent events disabled")
	}

179 180 181 182 183 184
	var session *session
	if requestor {
		session = s.sessions.get(token)
	} else {
		session = s.sessions.clientGet(token)
	}
185 186 187 188 189 190 191 192 193
	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()
194 195 196 197 198 199 200 201 202 203 204 205 206

	// 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)
207 208 209
	return nil
}

210
func (s *Server) HandleProtocolMessage(
211 212 213 214
	path string,
	method string,
	headers map[string][]string,
	message []byte,
215 216 217 218
) (int, []byte, *server.SessionResult) {
	var start time.Time
	if s.conf.Verbose >= 2 {
		start = time.Now()
219
		server.LogRequest("client", method, path, "", http.Header(headers), message)
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
	}

	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
236
) (status int, output []byte, result *server.SessionResult) {
237 238 239 240 241 242 243 244 245
	// 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]
		}
	}
246

247
	token, noun, args, err := ParsePath(path)
248 249
	if err != nil {
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorUnsupported, ""))
250 251
	}

252 253 254 255 256 257 258 259 260 261 262
	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
263
	// Fetch the session
264
	session := s.sessions.clientGet(token)
265
	if session == nil {
266
		s.conf.Logger.WithField("clientToken", token).Warn("Session not found")
Sietse Ringers's avatar
Sietse Ringers committed
267
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorSessionUnknown, ""))
268
		return
269
	}
270 271
	session.Lock()
	defer session.Unlock()
272

273 274
	// However we return, if the session status has been updated
	// then we should inform the user by returning a SessionResult
275
	defer func() {
276 277
		if session.status != session.prevStatus {
			session.prevStatus = session.status
278 279 280 281
			result = session.result
		}
	}()

282
	// Route to handler
283
	var err error
284
	switch len(noun) {
285
	case 0:
286
		if method == http.MethodDelete {
287 288 289
			session.handleDelete()
			status = http.StatusOK
			return
290
		}
291
		if method == http.MethodGet {
292 293 294 295
			status, output = session.checkCache(message, server.StatusConnected)
			if len(output) != 0 {
				return
			}
296 297 298
			h := http.Header(headers)
			min := &irma.ProtocolVersion{}
			max := &irma.ProtocolVersion{}
299
			if err = json.Unmarshal([]byte(h.Get(irma.MinVersionHeader)), min); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
300
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
301
				return
302
			}
303
			if err = json.Unmarshal([]byte(h.Get(irma.MaxVersionHeader)), max); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
304
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
305
				return
306
			}
Sietse Ringers's avatar
Sietse Ringers committed
307
			status, output = server.JsonResponse(session.handleGetRequest(min, max))
308
			session.responseCache = responseCache{message: message, response: output, status: status, sessionStatus: server.StatusConnected}
309
			return
310
		}
Sietse Ringers's avatar
Sietse Ringers committed
311
		status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
312
		return
313

314
	default:
315
		if noun == "statusevents" {
316 317
			rerr := server.RemoteError(server.ErrorInvalidRequest, "server sent events not supported by this server")
			status, output = server.JsonResponse(nil, rerr)
318 319 320
			return
		}

321 322
		if method == http.MethodGet && noun == "status" {
			status, output = server.JsonResponse(session.handleGetStatus())
Sietse Ringers's avatar
Sietse Ringers committed
323
			return
324 325 326
		}

		// Below are only POST enpoints
327
		if method != http.MethodPost {
Sietse Ringers's avatar
Sietse Ringers committed
328
			status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
Sietse Ringers's avatar
Sietse Ringers committed
329 330 331
			return
		}

332
		if noun == "commitments" && session.action == irma.ActionIssuing {
333 334 335 336
			status, output = session.checkCache(message, server.StatusDone)
			if len(output) != 0 {
				return
			}
Sietse Ringers's avatar
Sietse Ringers committed
337
			commitments := &irma.IssueCommitmentMessage{}
338 339
			if err = irma.UnmarshalValidate(message, commitments); err != nil {
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
340
				return
341
			}
Sietse Ringers's avatar
Sietse Ringers committed
342
			status, output = server.JsonResponse(session.handlePostCommitments(commitments))
343
			session.responseCache = responseCache{message: message, response: output, status: status, sessionStatus: server.StatusDone}
Sietse Ringers's avatar
Sietse Ringers committed
344 345
			return
		}
346

347
		if noun == "proofs" && session.action == irma.ActionDisclosing {
348 349 350 351 352 353 354
			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()))
355
				return
356
			}
Sietse Ringers's avatar
Sietse Ringers committed
357
			status, output = server.JsonResponse(session.handlePostDisclosure(disclosure))
358
			session.responseCache = responseCache{message: message, response: output, status: status, sessionStatus: server.StatusDone}
Sietse Ringers's avatar
Sietse Ringers committed
359 360
			return
		}
361

362
		if noun == "proofs" && session.action == irma.ActionSigning {
363 364 365 366
			status, output = session.checkCache(message, server.StatusDone)
			if len(output) != 0 {
				return
			}
Sietse Ringers's avatar
Sietse Ringers committed
367
			signature := &irma.SignedMessage{}
368 369
			if err = irma.UnmarshalValidate(message, signature); err != nil {
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
370
				return
371
			}
Sietse Ringers's avatar
Sietse Ringers committed
372
			status, output = server.JsonResponse(session.handlePostSignature(signature))
373
			session.responseCache = responseCache{message: message, response: output, status: status, sessionStatus: server.StatusDone}
374
			return
375
		}
Sietse Ringers's avatar
Sietse Ringers committed
376

Sietse Ringers's avatar
Sietse Ringers committed
377
		status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
378
		return
379 380
	}
}
381 382 383 384

func (s *Server) handleRevocationMessage(
	noun, method string, args []string, headers map[string][]string, message []byte,
) (int, []byte) {
385
	if (noun == "updatefrom" || noun == "updatelatest") && method == http.MethodGet {
386
		if len(args) != 2 {
387
			return server.GobResponse(nil, server.RemoteError(server.ErrorInvalidRequest, "GET "+noun+" expects 2 url arguments"))
388
		}
389
		i, err := strconv.ParseUint(args[1], 10, 64)
390
		if err != nil {
391
			return server.GobResponse(nil, server.RemoteError(server.ErrorMalformedInput, err.Error()))
392 393
		}
		cred := irma.NewCredentialTypeIdentifier(args[0])
394
		if noun == "updatefrom" {
395
			return server.GobResponse(s.handleGetUpdateFrom(cred, i))
396
		} else {
397
			return server.GobResponse(s.handleGetUpdateLatest(cred, i))
398
		}
399
	}
400 401
	if noun == "update" && method == http.MethodPost {
		if len(args) != 1 {
402
			return server.GobResponse(nil, server.RemoteError(server.ErrorInvalidRequest, "POST update expects 1 url argument"))
403
		}
404 405
		cred := irma.NewCredentialTypeIdentifier(args[0])
		var update *revocation.Update
406 407
		if err := irma.UnmarshalBinary(message, update); err != nil {
			return server.GobResponse(nil, server.RemoteError(server.ErrorMalformedInput, err.Error()))
408
		}
409
		return server.GobResponse(s.handlePostUpdate(cred, update))
410
	}
411 412
	if noun == "issuancerecord" && method == http.MethodPost {
		if len(args) != 2 {
413
			return server.GobResponse(nil, server.RemoteError(server.ErrorInvalidRequest, "POST issuancercord expects 2 url arguments"))
414 415
		}
		cred := irma.NewCredentialTypeIdentifier(args[0])
416
		counter, err := strconv.ParseUint(args[1], 10, 64)
417
		if err != nil {
418
			return server.GobResponse(nil, server.RemoteError(server.ErrorMalformedInput, err.Error()))
419
		}
420
		return server.GobResponse(s.handlePostIssuanceRecord(cred, counter, message))
421
	}
422

423
	return server.GobResponse(nil, server.RemoteError(server.ErrorInvalidRequest, ""))
424
}