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/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
	s.scheduler.Every(5).Minutes().Do(func() {
		for credid, credtype := range s.conf.IrmaConfiguration.CredentialTypes {
			if !credtype.SupportsRevocation() {
				continue
			}
52
			if s := conf.RevocationSettings[credid]; s != nil && s.Mode != irma.RevocationModeRequestor {
53 54
				continue
			}
55
			if err := s.conf.IrmaConfiguration.Revocation.UpdateDB(credid); err != nil {
56 57 58 59 60
				s.conf.Logger.Error("failed to update revocation database for %s:", credid.String())
				_ = server.LogError(err)
			}
		}
	})
61

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

64
	return s, nil
65
}
66

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

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

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

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

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

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

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

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

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

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

141
func (s *Server) Revoke(credid irma.CredentialTypeIdentifier, key string) error {
142 143 144 145 146 147 148 149 150 151 152
	sk, err := s.conf.PrivateKey(credid.IssuerIdentifier())
	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
	}
153
	return s.conf.IrmaConfiguration.Revocation.Revoke(credid, key, rsk)
154 155
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

func (s *Server) handleRevocationMessage(
	noun, method string, args []string, headers map[string][]string, message []byte,
) (int, []byte) {
384
	if (noun == "records" || noun == "latestrecords") && method == http.MethodGet {
385
		if len(args) != 2 {
386
			return server.JsonResponse(nil, server.RemoteError(server.ErrorInvalidRequest, "GET "+noun+" expects 2 url arguments"))
387
		}
388
		i, err := strconv.ParseUint(args[1], 10, 64)
389 390 391 392
		if err != nil {
			return server.JsonResponse(nil, server.RemoteError(server.ErrorMalformedInput, err.Error()))
		}
		cred := irma.NewCredentialTypeIdentifier(args[0])
393 394 395 396 397
		if noun == "records" {
			return server.JsonResponse(s.handleGetRevocationRecords(cred, i))
		} else {
			return server.JsonResponse(s.handleGetLatestRevocationRecords(cred, i))
		}
398 399
	}
	if noun == "records" && method == http.MethodPost {
400 401
		if len(args) != 0 {
			return server.JsonResponse(nil, server.RemoteError(server.ErrorInvalidRequest, "POST records expects no url arguments"))
402
		}
403
		var records []*irma.RevocationRecord
404 405 406
		if err := json.Unmarshal(message, &records); err != nil {
			return server.JsonResponse(nil, server.RemoteError(server.ErrorMalformedInput, err.Error()))
		}
407
		return server.JsonResponse(s.handlePostRevocationRecords(records))
408
	}
409 410 411 412 413
	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])
414
		counter, err := strconv.ParseUint(args[1], 10, 64)
415 416 417 418 419
		if err != nil {
			return server.JsonResponse(nil, server.RemoteError(server.ErrorMalformedInput, err.Error()))
		}
		return server.JsonResponse(s.handlePostIssuanceRecord(cred, counter, message))
	}
420 421 422

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