server.go 14.6 KB
Newer Older
Sietse Ringers's avatar
Sietse Ringers committed
1
// Package requestorserver is a server allowing IRMA verifiers, issuers or attribute-based signature
Sietse Ringers's avatar
Sietse Ringers committed
2 3 4
// applications (the requestor) to perform IRMA sessions with irmaclient instances (i.e. the IRMA
// app). It exposes a RESTful protocol with which the requestor can start and manage the session as
// well as HTTP endpoints for the irmaclient.
Sietse Ringers's avatar
Sietse Ringers committed
5
package requestorserver
6 7

import (
8
	"context"
Sietse Ringers's avatar
Sietse Ringers committed
9
	"crypto/tls"
10
	"crypto/x509"
Sietse Ringers's avatar
Sietse Ringers committed
11
	"encoding/json"
12
	"encoding/pem"
13
	"fmt"
14
	"io/ioutil"
15
	"log"
16
	"net/http"
17
	"time"
18

19
	"github.com/dgrijalva/jwt-go"
20
	"github.com/go-chi/chi"
21
	"github.com/go-chi/chi/middleware"
Sietse Ringers's avatar
Sietse Ringers committed
22
	"github.com/go-chi/cors"
23
	"github.com/go-errors/errors"
24
	"github.com/privacybydesign/irmago"
Sietse Ringers's avatar
Sietse Ringers committed
25
	"github.com/privacybydesign/irmago/server"
26
	"github.com/privacybydesign/irmago/server/irmaserver"
27
	"github.com/sirupsen/logrus"
28 29
)

Sietse Ringers's avatar
Sietse Ringers committed
30
// Server is a requestor server instance.
31
type Server struct {
32 33 34
	conf     *Configuration
	irmaserv *irmaserver.Server
	stop     chan struct{}
35
	stopped  chan struct{}
36
}
37

38
// Start the server. If successful then it will not return until Stop() is called.
39 40 41
func (s *Server) Start(config *Configuration) error {
	if s.conf.LogJSON {
		s.conf.Logger.WithField("configuration", s.conf).Debug("Configuration")
42
	} else {
43 44
		bts, _ := json.MarshalIndent(s.conf, "", "   ")
		s.conf.Logger.Debug("Configuration: ", string(bts), "\n")
45
	}
46

47 48 49 50 51 52 53 54 55
	// We start either one or two servers, depending on whether a separate client server is enabled, such that:
	// - if any of them returns, the other is also stopped (neither of them is of use without the other)
	// - if any of them returns an unexpected error (ie. other than http.ErrServerClosed), the error is logged and returned
	// - we have a way of stopping all servers from outside (with Stop())
	// - the function returns only after all servers have been stopped
	// - any unexpected error is dealt with here instead of when stopping using Stop().
	// Inspired by https://dave.cheney.net/practical-go/presentations/qcon-china.html#_never_start_a_goroutine_without_when_it_will_stop

	count := 1
56
	if s.conf.separateClientServer() {
57
		count = 2
58
	}
59 60
	done := make(chan error, count)
	s.stop = make(chan struct{})
61
	s.stopped = make(chan struct{}, count)
62

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
	if s.conf.separateClientServer() {
		go func() {
			done <- s.startClientServer()
		}()
	}
	go func() {
		done <- s.startRequestorServer()
	}()

	var stopped bool
	var err error
	for i := 0; i < cap(done); i++ {
		if err = <-done; err != nil {
			_ = server.LogError(err)
		}
		if !stopped {
			stopped = true
			close(s.stop)
		}
	}

	return err
85 86
}

87
func (s *Server) startRequestorServer() error {
88
	tlsConf, _ := s.conf.tlsConfig()
89
	return s.startServer(s.Handler(), "Server", s.conf.ListenAddress, s.conf.Port, tlsConf)
90 91
}

92
func (s *Server) startClientServer() error {
93
	tlsConf, _ := s.conf.clientTlsConfig()
94
	return s.startServer(s.ClientHandler(), "Client server", s.conf.ClientListenAddress, s.conf.ClientPort, tlsConf)
95 96
}

97
func (s *Server) startServer(handler http.Handler, name, addr string, port int, tlsConf *tls.Config) error {
98
	fulladdr := fmt.Sprintf("%s:%d", addr, port)
99
	s.conf.Logger.Info(name, " listening at ", fulladdr)
100 101 102 103 104 105 106 107 108

	serv := &http.Server{
		Addr:      fulladdr,
		Handler:   handler,
		TLSConfig: tlsConf,
	}

	go func() {
		<-s.stop
109 110 111
		ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
		defer cancel()
		if err := serv.Shutdown(ctx); err != nil {
112 113
			_ = server.LogError(err)
		}
114
		s.stopped <- struct{}{}
115 116
	}()

Sietse Ringers's avatar
Sietse Ringers committed
117
	if tlsConf != nil {
118
		// Disable HTTP/2 (see package documentation of http): it breaks server side events :(
119 120
		serv.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler))
		s.conf.Logger.Info(name, " TLS enabled")
121
		return filterStopError(serv.ListenAndServeTLS("", ""))
Sietse Ringers's avatar
Sietse Ringers committed
122
	} else {
123
		return filterStopError(serv.ListenAndServe())
124 125 126
	}
}

127 128 129
func filterStopError(err error) error {
	if err == http.ErrServerClosed {
		return nil
130
	}
131 132
	return err
}
133

134 135 136
func (s *Server) Stop() {
	s.irmaserv.Stop()
	s.stop <- struct{}{}
137 138 139 140
	<-s.stopped
	if s.conf.separateClientServer() {
		<-s.stopped
	}
141 142
}

143
func New(config *Configuration) (*Server, error) {
144
	irmaserv, err := irmaserver.New(config.Configuration)
145 146
	if err != nil {
		return nil, err
147
	}
148 149
	if err := config.initialize(); err != nil {
		return nil, err
150
	}
151 152 153 154
	return &Server{
		conf:     config,
		irmaserv: irmaserv,
	}, nil
155
}
156

157 158 159 160 161 162
var corsOptions = cors.Options{
	AllowedOrigins: []string{"*"},
	AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "Cache-Control"},
	AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodDelete},
}

163
func (s *Server) ClientHandler() http.Handler {
164
	router := chi.NewRouter()
165
	router.Use(cors.New(corsOptions).Handler)
Sietse Ringers's avatar
Sietse Ringers committed
166

Sietse Ringers's avatar
Sietse Ringers committed
167
	router.Mount("/irma/", s.irmaserv.HandlerFunc())
168
	if s.conf.StaticPath != "" {
169
		router.Mount(s.conf.StaticPrefix, s.StaticFilesHandler())
170 171
	}

172 173 174 175 176
	return router
}

// Handler returns a http.Handler that handles all IRMA requestor messages
// and IRMA client messages.
177
func (s *Server) Handler() http.Handler {
178
	router := chi.NewRouter()
179
	router.Use(cors.New(corsOptions).Handler)
180

181
	if !s.conf.separateClientServer() {
182
		// Mount server for irmaclient
Sietse Ringers's avatar
Sietse Ringers committed
183
		router.Mount("/irma/", s.irmaserv.HandlerFunc())
184 185 186
		if s.conf.StaticPath != "" {
			router.Mount(s.conf.StaticPrefix, s.StaticFilesHandler())
		}
187
	}
188

189
	// Server routes
190 191 192 193 194
	router.Post("/session", s.handleCreate)
	router.Delete("/session/{token}", s.handleDelete)
	router.Get("/session/{token}/status", s.handleStatus)
	router.Get("/session/{token}/statusevents", s.handleStatusEvents)
	router.Get("/session/{token}/result", s.handleResult)
Sietse Ringers's avatar
Sietse Ringers committed
195 196

	// Routes for getting signed JWTs containing the session result. Only work if configuration has a private key
197 198
	router.Get("/session/{token}/result-jwt", s.handleJwtResult)
	router.Get("/session/{token}/getproof", s.handleJwtProofs) // irma_api_server-compatible JWT
199

200
	router.Get("/publickey", s.handlePublicKey)
201

202
	return router
203 204
}

205
func (s *Server) StaticFilesHandler() http.Handler {
206 207 208 209 210 211
	if len(s.conf.URL) > 6 {
		url := s.conf.URL[:len(s.conf.URL)-6] + s.conf.StaticPrefix
		s.conf.Logger.Infof("Hosting files at %s under %s", s.conf.StaticPath, url)
	} else { // URL not known, don't log it but otherwise continue
		s.conf.Logger.Infof("Hosting files at %s", s.conf.StaticPath)
	}
212 213 214 215 216 217 218 219
	// Hook up chi middleware logger with our own logger
	middleware.DefaultLogger = middleware.RequestLogger(&middleware.DefaultLogFormatter{
		Logger:  log.New(s.conf.Logger.WriterLevel(logrus.TraceLevel), "static: ", 0),
		NoColor: true,
	})
	return http.StripPrefix(s.conf.StaticPrefix, middleware.Logger(http.FileServer(http.Dir(s.conf.StaticPath))))
}

220
func (s *Server) handleCreate(w http.ResponseWriter, r *http.Request) {
221 222
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
223
		s.conf.Logger.Error("Could not read session request HTTP POST body")
224
		_ = server.LogError(err)
Sietse Ringers's avatar
Sietse Ringers committed
225
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
226 227
		return
	}
228

Sietse Ringers's avatar
Sietse Ringers committed
229 230 231
	// Authenticate request: check if the requestor is known and allowed to submit requests.
	// We do this by feeding the HTTP POST details to all known authenticators, and see if
	// one of them is applicable and able to authenticate the request.
232
	var (
233
		rrequest  irma.RequestorRequest
234 235 236 237 238
		request   irma.SessionRequest
		requestor string
		rerr      *irma.RemoteError
		applies   bool
	)
Sietse Ringers's avatar
Sietse Ringers committed
239
	for _, authenticator := range authenticators { // rrequest abbreviates "requestor request"
240
		applies, rrequest, requestor, rerr = authenticator.Authenticate(r.Header, body)
241 242 243 244 245
		if applies || rerr != nil {
			break
		}
	}
	if rerr != nil {
246
		_ = server.LogError(rerr)
247 248 249 250
		server.WriteResponse(w, nil, rerr)
		return
	}
	if !applies {
251
		s.conf.Logger.Warnf("Session request uses unknown authentication method, HTTP headers: %s, HTTP POST body: %s",
252
			server.ToJson(r.Header), string(body))
Sietse Ringers's avatar
Sietse Ringers committed
253
		server.WriteError(w, server.ErrorInvalidRequest, "Request could not be authorized")
254 255 256
		return
	}

257 258
	// Authorize request: check if the requestor is allowed to verify or issue
	// the requested attributes or credentials
259
	request = rrequest.SessionRequest()
260
	if request.Action() == irma.ActionIssuing {
261
		allowed, reason := s.conf.CanIssue(requestor, request.(*irma.IssuanceRequest).Credentials)
262
		if !allowed {
263
			s.conf.Logger.WithFields(logrus.Fields{"requestor": requestor, "id": reason}).
264
				Warn("Requestor not authorized to issue credential; full request: ", server.ToJson(request))
265 266 267 268
			server.WriteError(w, server.ErrorUnauthorized, reason)
			return
		}
	}
Sietse Ringers's avatar
Sietse Ringers committed
269
	disjunctions := request.ToDisclose()
270
	if len(disjunctions) > 0 {
271
		allowed, reason := s.conf.CanVerifyOrSign(requestor, request.Action(), disjunctions)
272
		if !allowed {
273
			s.conf.Logger.WithFields(logrus.Fields{"requestor": requestor, "id": reason}).
274
				Warn("Requestor not authorized to verify attribute; full request: ", server.ToJson(request))
275 276 277 278
			server.WriteError(w, server.ErrorUnauthorized, reason)
			return
		}
	}
279 280
	if rrequest.Base().CallbackUrl != "" && s.conf.jwtPrivateKey == nil {
		s.conf.Logger.WithFields(logrus.Fields{"requestor": requestor}).Warn("Requestor provided callbackUrl but no JWT private key is installed")
281 282 283
		server.WriteError(w, server.ErrorUnsupported, "")
		return
	}
284 285

	// Everything is authenticated and parsed, we're good to go!
286
	qr, token, err := s.irmaserv.StartSession(rrequest, s.doResultCallback)
287
	if err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
288
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
289 290 291
		return
	}

292 293 294 295
	server.WriteJson(w, server.SessionPackage{
		SessionPtr: qr,
		Token:      token,
	})
296 297
}

298 299
func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
	res := s.irmaserv.GetSessionResult(chi.URLParam(r, "token"))
300
	if res == nil {
Sietse Ringers's avatar
Sietse Ringers committed
301
		server.WriteError(w, server.ErrorSessionUnknown, "")
302 303
		return
	}
Sietse Ringers's avatar
Sietse Ringers committed
304
	server.WriteJson(w, res.Status)
305 306
}

307
func (s *Server) handleStatusEvents(w http.ResponseWriter, r *http.Request) {
308
	token := chi.URLParam(r, "token")
309
	s.conf.Logger.WithFields(logrus.Fields{"session": token}).Debug("new client subscribed to server sent events")
310
	if err := s.irmaserv.SubscribeServerSentEvents(w, r, token, true); err != nil {
311 312 313 314 315
		server.WriteResponse(w, nil, &irma.RemoteError{
			Status:      server.ErrorUnsupported.Status,
			ErrorName:   string(server.ErrorUnsupported.Type),
			Description: server.ErrorUnsupported.Description,
		})
316 317 318
	}
}

319 320
func (s *Server) handleDelete(w http.ResponseWriter, r *http.Request) {
	err := s.irmaserv.CancelSession(chi.URLParam(r, "token"))
321 322 323 324 325
	if err != nil {
		server.WriteError(w, server.ErrorSessionUnknown, "")
	}
}

326 327
func (s *Server) handleResult(w http.ResponseWriter, r *http.Request) {
	res := s.irmaserv.GetSessionResult(chi.URLParam(r, "token"))
328
	if res == nil {
Sietse Ringers's avatar
Sietse Ringers committed
329
		server.WriteError(w, server.ErrorSessionUnknown, "")
330 331
		return
	}
Sietse Ringers's avatar
Sietse Ringers committed
332
	server.WriteJson(w, res)
333 334
}

335 336 337
func (s *Server) handleJwtResult(w http.ResponseWriter, r *http.Request) {
	if s.conf.jwtPrivateKey == nil {
		s.conf.Logger.Warn("Session result JWT requested but no JWT private key is configured")
338 339
		server.WriteError(w, server.ErrorUnknown, "JWT signing not supported")
		return
340
	}
341

342
	sessiontoken := chi.URLParam(r, "token")
343
	res := s.irmaserv.GetSessionResult(sessiontoken)
344 345 346
	if res == nil {
		server.WriteError(w, server.ErrorSessionUnknown, "")
		return
347
	}
348

349
	j, err := s.resultJwt(res)
350
	if err != nil {
351
		s.conf.Logger.Error("Failed to sign session result JWT")
352
		_ = server.LogError(err)
353 354 355
		server.WriteError(w, server.ErrorUnknown, err.Error())
		return
	}
356
	server.WriteString(w, j)
357 358
}

359 360 361
func (s *Server) handleJwtProofs(w http.ResponseWriter, r *http.Request) {
	if s.conf.jwtPrivateKey == nil {
		s.conf.Logger.Warn("Session result JWT requested but no JWT private key is configured")
362 363 364 365
		server.WriteError(w, server.ErrorUnknown, "JWT signing not supported")
		return
	}

366
	sessiontoken := chi.URLParam(r, "token")
367
	res := s.irmaserv.GetSessionResult(sessiontoken)
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
	if res == nil {
		server.WriteError(w, server.ErrorSessionUnknown, "")
		return
	}

	claims := jwt.MapClaims{}

	// Fill standard claims
	switch res.Type {
	case irma.ActionDisclosing:
		claims["subject"] = "verification_result"
	case irma.ActionSigning:
		claims["subject"] = "abs_result"
	default:
		if res == nil {
			server.WriteError(w, server.ErrorInvalidRequest, "")
			return
		}
	}
	claims["iat"] = time.Now().Unix()
388 389
	if s.conf.JwtIssuer != "" {
		claims["iss"] = s.conf.JwtIssuer
390 391
	}
	claims["status"] = res.Status
392
	validity := s.irmaserv.GetRequest(sessiontoken).Base().ResultJwtValidity
393 394 395
	if validity != 0 {
		claims["exp"] = time.Now().Unix() + int64(validity)
	}
396 397 398 399 400 401 402 403 404 405 406 407 408

	// Disclosed credentials and possibly signature
	m := make(map[irma.AttributeTypeIdentifier]string, len(res.Disclosed))
	for _, attr := range res.Disclosed {
		m[attr.Identifier] = attr.Value[""]
	}
	claims["attributes"] = m
	if res.Signature != nil {
		claims["signature"] = res.Signature
	}

	// Sign the jwt and return it
	token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
409
	resultJwt, err := token.SignedString(s.conf.jwtPrivateKey)
410
	if err != nil {
411
		s.conf.Logger.Error("Failed to sign session result JWT")
412
		_ = server.LogError(err)
413 414
		server.WriteError(w, server.ErrorUnknown, err.Error())
		return
415
	}
416
	server.WriteString(w, resultJwt)
417
}
418

419 420
func (s *Server) handlePublicKey(w http.ResponseWriter, r *http.Request) {
	if s.conf.jwtPrivateKey == nil {
421 422 423 424
		server.WriteError(w, server.ErrorUnsupported, "")
		return
	}

425
	bts, err := x509.MarshalPKIXPublicKey(&s.conf.jwtPrivateKey.PublicKey)
426 427 428 429 430 431 432 433 434 435
	if err != nil {
		server.WriteError(w, server.ErrorUnknown, err.Error())
		return
	}
	pubBytes := pem.EncodeToMemory(&pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: bts,
	})
	_, _ = w.Write(pubBytes)
}
436

437
func (s *Server) resultJwt(sessionresult *server.SessionResult) (string, error) {
438 439 440 441 442
	claims := struct {
		jwt.StandardClaims
		*server.SessionResult
	}{
		StandardClaims: jwt.StandardClaims{
443
			Issuer:   s.conf.JwtIssuer,
444 445 446 447 448
			IssuedAt: time.Now().Unix(),
			Subject:  string(sessionresult.Type) + "_result",
		},
		SessionResult: sessionresult,
	}
449
	validity := s.irmaserv.GetRequest(sessionresult.Token).Base().ResultJwtValidity
450 451 452 453 454 455
	if validity != 0 {
		claims.ExpiresAt = time.Now().Unix() + int64(validity)
	}

	// Sign the jwt and return it
	token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
456
	return token.SignedString(s.conf.jwtPrivateKey)
457 458
}

459 460 461
func (s *Server) doResultCallback(result *server.SessionResult) {
	callbackUrl := s.irmaserv.GetRequest(result.Token).Base().CallbackUrl
	if callbackUrl == "" || s.conf.jwtPrivateKey == nil {
462 463
		return
	}
464
	s.conf.Logger.WithFields(logrus.Fields{"session": result.Token, "callbackUrl": callbackUrl}).Debug("POSTing session result")
465

466
	j, err := s.resultJwt(result)
467 468 469 470 471 472 473 474
	if err != nil {
		_ = server.LogError(errors.WrapPrefix(err, "Failed to create JWT for result callback", 0))
		return
	}

	var x string // dummy for the server's return value that we don't care about
	if err := irma.NewHTTPTransport(callbackUrl).Post("", &x, j); err != nil {
		// not our problem, log it and go on
475
		s.conf.Logger.Warn(errors.WrapPrefix(err, "Failed to POST session result to callback URL", 0))
476 477
	}
}