server.go 15.9 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
	"bytes"
9
	"context"
Sietse Ringers's avatar
Sietse Ringers committed
10
	"crypto/tls"
11
	"crypto/x509"
Sietse Ringers's avatar
Sietse Ringers committed
12
	"encoding/json"
13
	"encoding/pem"
14
	"fmt"
15
	"io/ioutil"
16
	"log"
17
	"net/http"
18
	"time"
19

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

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

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

48 49 50 51 52 53 54 55 56
	// 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
57
	if s.conf.separateClientServer() {
58
		count = 2
59
	}
60 61
	done := make(chan error, count)
	s.stop = make(chan struct{})
62
	s.stopped = make(chan struct{}, count)
63

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
	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
86 87
}

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

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

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

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

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

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

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

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

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

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

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

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

173 174 175 176 177
	return router
}

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

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

190 191 192 193 194 195 196 197 198 199 200 201 202 203
	// Group main API endpoints, so we can attach our request/response logger to it
	// while not adding it to the endpoints already added above (which do their own logging).
	router.Group(func(r chi.Router) {
		r.Use(cors.New(corsOptions).Handler)
		if s.conf.Verbose >= 2 {
			r.Use(s.logHandler)
		}

		// Server routes
		r.Post("/session", s.handleCreate)
		r.Delete("/session/{token}", s.handleDelete)
		r.Get("/session/{token}/status", s.handleStatus)
		r.Get("/session/{token}/statusevents", s.handleStatusEvents)
		r.Get("/session/{token}/result", s.handleResult)
Sietse Ringers's avatar
Sietse Ringers committed
204

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

209 210
		r.Get("/publickey", s.handlePublicKey)
	})
211

212
	return router
213 214
}

215
// logHandler is middleware for logging HTTP requests and responses.
216 217
func (s *Server) logHandler(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
218 219 220 221 222 223
		var message []byte
		var err error

		// Read r.Body, and then replace with a fresh ReadCloser for the next handler
		if message, err = ioutil.ReadAll(r.Body); err != nil {
			message = []byte("<failed to read body: " + err.Error() + ">")
224
		}
225 226
		_ = r.Body.Close()
		r.Body = ioutil.NopCloser(bytes.NewBuffer(message))
227

228
		server.LogRequest(r.Method, r.URL.String(), r.Proto, r.RemoteAddr, r.Header, message)
229 230 231 232 233 234 235 236 237 238 239 240

		// copy output of HTTP handler to our buffer for later logging
		ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
		respBuf := new(bytes.Buffer)
		ww.Tee(respBuf)

		// print response after HTTP is served
		start := time.Now()
		defer func() {
			var resp []byte
			if ww.BytesWritten() > 0 {
				resp = respBuf.Bytes()
241
			}
242 243
			server.LogResponse(ww.Status(), time.Since(start), resp)
		}()
244 245 246 247 248 249

		next.ServeHTTP(ww, r)
		return
	})
}

250
func (s *Server) StaticFilesHandler() http.Handler {
251 252 253 254 255 256
	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)
	}
257 258 259 260 261 262 263 264
	// 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))))
}

265
func (s *Server) handleCreate(w http.ResponseWriter, r *http.Request) {
266 267
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
268
		s.conf.Logger.Error("Could not read session request HTTP POST body")
269
		_ = server.LogError(err)
Sietse Ringers's avatar
Sietse Ringers committed
270
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
271 272
		return
	}
273

Sietse Ringers's avatar
Sietse Ringers committed
274 275 276
	// 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.
277
	var (
278
		rrequest  irma.RequestorRequest
279 280 281 282 283
		request   irma.SessionRequest
		requestor string
		rerr      *irma.RemoteError
		applies   bool
	)
Sietse Ringers's avatar
Sietse Ringers committed
284
	for _, authenticator := range authenticators { // rrequest abbreviates "requestor request"
285
		applies, rrequest, requestor, rerr = authenticator.Authenticate(r.Header, body)
286 287 288 289 290
		if applies || rerr != nil {
			break
		}
	}
	if rerr != nil {
291
		_ = server.LogError(rerr)
292 293 294 295
		server.WriteResponse(w, nil, rerr)
		return
	}
	if !applies {
296
		s.conf.Logger.Warnf("Session request uses unknown authentication method, HTTP headers: %s, HTTP POST body: %s",
297
			server.ToJson(r.Header), string(body))
Sietse Ringers's avatar
Sietse Ringers committed
298
		server.WriteError(w, server.ErrorInvalidRequest, "Request could not be authorized")
299 300 301
		return
	}

302 303
	// Authorize request: check if the requestor is allowed to verify or issue
	// the requested attributes or credentials
304
	request = rrequest.SessionRequest()
305
	if request.Action() == irma.ActionIssuing {
306
		allowed, reason := s.conf.CanIssue(requestor, request.(*irma.IssuanceRequest).Credentials)
307
		if !allowed {
308
			s.conf.Logger.WithFields(logrus.Fields{"requestor": requestor, "id": reason}).
309
				Warn("Requestor not authorized to issue credential; full request: ", server.ToJson(request))
310 311 312 313
			server.WriteError(w, server.ErrorUnauthorized, reason)
			return
		}
	}
314 315 316
	condiscon := request.Disclosure().Disclose
	if len(condiscon) > 0 {
		allowed, reason := s.conf.CanVerifyOrSign(requestor, request.Action(), condiscon)
317
		if !allowed {
318
			s.conf.Logger.WithFields(logrus.Fields{"requestor": requestor, "id": reason}).
319
				Warn("Requestor not authorized to verify attribute; full request: ", server.ToJson(request))
320 321 322 323
			server.WriteError(w, server.ErrorUnauthorized, reason)
			return
		}
	}
324 325
	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")
326 327 328
		server.WriteError(w, server.ErrorUnsupported, "")
		return
	}
329 330

	// Everything is authenticated and parsed, we're good to go!
331
	qr, token, err := s.irmaserv.StartSession(rrequest, s.doResultCallback)
332
	if err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
333
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
334 335 336
		return
	}

337 338 339 340
	server.WriteJson(w, server.SessionPackage{
		SessionPtr: qr,
		Token:      token,
	})
341 342
}

343 344
func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
	res := s.irmaserv.GetSessionResult(chi.URLParam(r, "token"))
345
	if res == nil {
Sietse Ringers's avatar
Sietse Ringers committed
346
		server.WriteError(w, server.ErrorSessionUnknown, "")
347 348
		return
	}
Sietse Ringers's avatar
Sietse Ringers committed
349
	server.WriteJson(w, res.Status)
350 351
}

352
func (s *Server) handleStatusEvents(w http.ResponseWriter, r *http.Request) {
353
	token := chi.URLParam(r, "token")
354
	s.conf.Logger.WithFields(logrus.Fields{"session": token}).Debug("new client subscribed to server sent events")
355
	if err := s.irmaserv.SubscribeServerSentEvents(w, r, token, true); err != nil {
356 357 358 359 360
		server.WriteResponse(w, nil, &irma.RemoteError{
			Status:      server.ErrorUnsupported.Status,
			ErrorName:   string(server.ErrorUnsupported.Type),
			Description: server.ErrorUnsupported.Description,
		})
361 362 363
	}
}

364 365
func (s *Server) handleDelete(w http.ResponseWriter, r *http.Request) {
	err := s.irmaserv.CancelSession(chi.URLParam(r, "token"))
366 367 368 369 370
	if err != nil {
		server.WriteError(w, server.ErrorSessionUnknown, "")
	}
}

371 372
func (s *Server) handleResult(w http.ResponseWriter, r *http.Request) {
	res := s.irmaserv.GetSessionResult(chi.URLParam(r, "token"))
373
	if res == nil {
Sietse Ringers's avatar
Sietse Ringers committed
374
		server.WriteError(w, server.ErrorSessionUnknown, "")
375 376
		return
	}
Sietse Ringers's avatar
Sietse Ringers committed
377
	server.WriteJson(w, res)
378 379
}

380 381 382
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")
383 384
		server.WriteError(w, server.ErrorUnknown, "JWT signing not supported")
		return
385
	}
386

387
	sessiontoken := chi.URLParam(r, "token")
388
	res := s.irmaserv.GetSessionResult(sessiontoken)
389 390 391
	if res == nil {
		server.WriteError(w, server.ErrorSessionUnknown, "")
		return
392
	}
393

394
	j, err := s.resultJwt(res)
395
	if err != nil {
396
		s.conf.Logger.Error("Failed to sign session result JWT")
397
		_ = server.LogError(err)
398 399 400
		server.WriteError(w, server.ErrorUnknown, err.Error())
		return
	}
401
	server.WriteString(w, j)
402 403
}

404 405 406
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")
407 408 409 410
		server.WriteError(w, server.ErrorUnknown, "JWT signing not supported")
		return
	}

411
	sessiontoken := chi.URLParam(r, "token")
412
	res := s.irmaserv.GetSessionResult(sessiontoken)
413 414 415 416 417 418 419 420 421 422
	if res == nil {
		server.WriteError(w, server.ErrorSessionUnknown, "")
		return
	}

	claims := jwt.MapClaims{}

	// Fill standard claims
	switch res.Type {
	case irma.ActionDisclosing:
423
		claims["sub"] = "disclosure_result"
424
	case irma.ActionSigning:
425
		claims["sub"] = "abs_result"
426
	default:
427 428
		server.WriteError(w, server.ErrorInvalidRequest, "")
		return
429 430
	}
	claims["iat"] = time.Now().Unix()
431 432
	if s.conf.JwtIssuer != "" {
		claims["iss"] = s.conf.JwtIssuer
433
	}
434
	claims["status"] = res.ProofStatus
435
	validity := s.irmaserv.GetRequest(sessiontoken).Base().ResultJwtValidity
436 437 438
	if validity != 0 {
		claims["exp"] = time.Now().Unix() + int64(validity)
	}
439 440 441

	// Disclosed credentials and possibly signature
	m := make(map[irma.AttributeTypeIdentifier]string, len(res.Disclosed))
442 443 444 445
	for _, set := range res.Disclosed {
		for _, attr := range set {
			m[attr.Identifier] = attr.Value[""]
		}
446 447 448 449 450 451 452 453
	}
	claims["attributes"] = m
	if res.Signature != nil {
		claims["signature"] = res.Signature
	}

	// Sign the jwt and return it
	token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
454
	resultJwt, err := token.SignedString(s.conf.jwtPrivateKey)
455
	if err != nil {
456
		s.conf.Logger.Error("Failed to sign session result JWT")
457
		_ = server.LogError(err)
458 459
		server.WriteError(w, server.ErrorUnknown, err.Error())
		return
460
	}
461
	server.WriteString(w, resultJwt)
462
}
463

464 465
func (s *Server) handlePublicKey(w http.ResponseWriter, r *http.Request) {
	if s.conf.jwtPrivateKey == nil {
466 467 468 469
		server.WriteError(w, server.ErrorUnsupported, "")
		return
	}

470
	bts, err := x509.MarshalPKIXPublicKey(&s.conf.jwtPrivateKey.PublicKey)
471 472 473 474 475 476 477 478 479 480
	if err != nil {
		server.WriteError(w, server.ErrorUnknown, err.Error())
		return
	}
	pubBytes := pem.EncodeToMemory(&pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: bts,
	})
	_, _ = w.Write(pubBytes)
}
481

482
func (s *Server) resultJwt(sessionresult *server.SessionResult) (string, error) {
483 484 485 486 487
	claims := struct {
		jwt.StandardClaims
		*server.SessionResult
	}{
		StandardClaims: jwt.StandardClaims{
488
			Issuer:   s.conf.JwtIssuer,
489 490 491 492 493
			IssuedAt: time.Now().Unix(),
			Subject:  string(sessionresult.Type) + "_result",
		},
		SessionResult: sessionresult,
	}
494
	validity := s.irmaserv.GetRequest(sessionresult.Token).Base().ResultJwtValidity
495 496 497 498 499 500
	if validity != 0 {
		claims.ExpiresAt = time.Now().Unix() + int64(validity)
	}

	// Sign the jwt and return it
	token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
501
	return token.SignedString(s.conf.jwtPrivateKey)
502 503
}

504 505 506
func (s *Server) doResultCallback(result *server.SessionResult) {
	callbackUrl := s.irmaserv.GetRequest(result.Token).Base().CallbackUrl
	if callbackUrl == "" || s.conf.jwtPrivateKey == nil {
507 508
		return
	}
509
	s.conf.Logger.WithFields(logrus.Fields{"session": result.Token, "callbackUrl": callbackUrl}).Debug("POSTing session result")
510

511
	j, err := s.resultJwt(result)
512 513 514 515 516 517 518 519
	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
520
		s.conf.Logger.Warn(errors.WrapPrefix(err, "Failed to POST session result to callback URL", 0))
521 522
	}
}