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

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

Sietse Ringers's avatar
Sietse Ringers committed
29
// Server is a requestor server instance.
30
type Server struct {
31 32
	serv, clientserv *http.Server
	conf             *Configuration
33
	irmaserv         *irmaserver.Server
34
}
35

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

45
	// Start server(s)
46 47
	if s.conf.separateClientServer() {
		go s.startClientServer()
48
	}
49
	s.startRequestorServer()
50

51
	return nil
52 53
}

54 55 56 57
func (s *Server) startRequestorServer() {
	s.serv = &http.Server{}
	tlsConf, _ := s.conf.tlsConfig()
	s.startServer(s.serv, s.Handler(), "Server", s.conf.ListenAddress, s.conf.Port, tlsConf)
58 59
}

60 61 62 63
func (s *Server) startClientServer() {
	s.clientserv = &http.Server{}
	tlsConf, _ := s.conf.clientTlsConfig()
	s.startServer(s.clientserv, s.ClientHandler(), "Client server", s.conf.ClientListenAddress, s.conf.ClientPort, tlsConf)
64 65
}

66
func (s *Server) startServer(serv *http.Server, handler http.Handler, name, addr string, port int, tlsConf *tls.Config) {
67
	fulladdr := fmt.Sprintf("%s:%d", addr, port)
68 69 70
	s.conf.Logger.Info(name, " listening at ", fulladdr)
	serv.Addr = fulladdr
	serv.Handler = handler
Sietse Ringers's avatar
Sietse Ringers committed
71 72
	var err error
	if tlsConf != nil {
73
		serv.TLSConfig = tlsConf
74
		// Disable HTTP/2 (see package documentation of http): it breaks server side events :(
75 76 77
		serv.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler))
		s.conf.Logger.Info(name, " TLS enabled")
		err = serv.ListenAndServeTLS("", "")
Sietse Ringers's avatar
Sietse Ringers committed
78
	} else {
79
		err = serv.ListenAndServe()
Sietse Ringers's avatar
Sietse Ringers committed
80 81
	}
	if err != http.ErrServerClosed {
82 83 84 85
		_ = server.LogFatal(err)
	}
}

86
func (s *Server) Stop() error {
87 88 89
	var err1, err2 error

	// Even if closing serv fails, we want to try closing clientserv
90 91 92
	err1 = s.serv.Close()
	if s.clientserv != nil {
		err2 = s.clientserv.Close()
93 94 95
	}

	// Now check errors
96
	if err1 != nil && err1 != http.ErrServerClosed {
97 98
		return err1
	}
99
	if err2 != nil && err2 != http.ErrServerClosed {
100 101 102 103 104
		return err2
	}
	return nil
}

105
func New(config *Configuration) (*Server, error) {
106
	irmaserv, err := irmaserver.New(config.Configuration)
107 108
	if err != nil {
		return nil, err
109
	}
110 111
	if err := config.initialize(); err != nil {
		return nil, err
112
	}
113 114 115 116
	return &Server{
		conf:     config,
		irmaserv: irmaserv,
	}, nil
117
}
118

119 120 121 122 123 124
var corsOptions = cors.Options{
	AllowedOrigins: []string{"*"},
	AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "Cache-Control"},
	AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodDelete},
}

125
func (s *Server) ClientHandler() http.Handler {
126
	router := chi.NewRouter()
127
	router.Use(cors.New(corsOptions).Handler)
Sietse Ringers's avatar
Sietse Ringers committed
128

Sietse Ringers's avatar
Sietse Ringers committed
129
	router.Mount("/irma/", s.irmaserv.HandlerFunc())
130 131 132 133 134 135 136 137 138 139 140 141 142

	if s.conf.StaticPath != "" {
		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)
		middleware.DefaultLogger = middleware.RequestLogger(&middleware.DefaultLogFormatter{
			Logger:  log.New(s.conf.Logger.WriterLevel(logrus.TraceLevel), "static: ", 0),
			NoColor: true,
		})
		router.Mount(s.conf.StaticPrefix,
			http.StripPrefix(s.conf.StaticPrefix, middleware.Logger(http.FileServer(http.Dir(s.conf.StaticPath)))),
		)
	}

143 144 145 146 147
	return router
}

// Handler returns a http.Handler that handles all IRMA requestor messages
// and IRMA client messages.
148
func (s *Server) Handler() http.Handler {
149
	router := chi.NewRouter()
150
	router.Use(cors.New(corsOptions).Handler)
151

152
	if !s.conf.separateClientServer() {
153
		// Mount server for irmaclient
Sietse Ringers's avatar
Sietse Ringers committed
154
		router.Mount("/irma/", s.irmaserv.HandlerFunc())
155
	}
156

157
	// Server routes
158 159 160 161 162
	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
163 164

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

168
	router.Get("/publickey", s.handlePublicKey)
169

170
	return router
171 172
}

173
func (s *Server) handleCreate(w http.ResponseWriter, r *http.Request) {
174 175
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
176
		s.conf.Logger.Error("Could not read session request HTTP POST body")
177
		_ = server.LogError(err)
Sietse Ringers's avatar
Sietse Ringers committed
178
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
179 180
		return
	}
181

Sietse Ringers's avatar
Sietse Ringers committed
182 183 184
	// 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.
185
	var (
186
		rrequest  irma.RequestorRequest
187 188 189 190 191
		request   irma.SessionRequest
		requestor string
		rerr      *irma.RemoteError
		applies   bool
	)
Sietse Ringers's avatar
Sietse Ringers committed
192
	for _, authenticator := range authenticators { // rrequest abbreviates "requestor request"
193
		applies, rrequest, requestor, rerr = authenticator.Authenticate(r.Header, body)
194 195 196 197 198
		if applies || rerr != nil {
			break
		}
	}
	if rerr != nil {
199
		_ = server.LogError(rerr)
200 201 202 203
		server.WriteResponse(w, nil, rerr)
		return
	}
	if !applies {
204
		s.conf.Logger.Warnf("Session request uses unknown authentication method, HTTP headers: %s, HTTP POST body: %s",
205
			server.ToJson(r.Header), string(body))
Sietse Ringers's avatar
Sietse Ringers committed
206
		server.WriteError(w, server.ErrorInvalidRequest, "Request could not be authorized")
207 208 209
		return
	}

210 211
	// Authorize request: check if the requestor is allowed to verify or issue
	// the requested attributes or credentials
212
	request = rrequest.SessionRequest()
213
	if request.Action() == irma.ActionIssuing {
214
		allowed, reason := s.conf.CanIssue(requestor, request.(*irma.IssuanceRequest).Credentials)
215
		if !allowed {
216
			s.conf.Logger.WithFields(logrus.Fields{"requestor": requestor, "id": reason}).
217
				Warn("Requestor not authorized to issue credential; full request: ", server.ToJson(request))
218 219 220 221
			server.WriteError(w, server.ErrorUnauthorized, reason)
			return
		}
	}
Sietse Ringers's avatar
Sietse Ringers committed
222
	disjunctions := request.ToDisclose()
223
	if len(disjunctions) > 0 {
224
		allowed, reason := s.conf.CanVerifyOrSign(requestor, request.Action(), disjunctions)
225
		if !allowed {
226
			s.conf.Logger.WithFields(logrus.Fields{"requestor": requestor, "id": reason}).
227
				Warn("Requestor not authorized to verify attribute; full request: ", server.ToJson(request))
228 229 230 231
			server.WriteError(w, server.ErrorUnauthorized, reason)
			return
		}
	}
232 233
	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")
234 235 236
		server.WriteError(w, server.ErrorUnsupported, "")
		return
	}
237 238

	// Everything is authenticated and parsed, we're good to go!
239
	qr, _, err := s.irmaserv.StartSession(rrequest, s.doResultCallback)
240
	if err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
241
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
242 243 244
		return
	}

Sietse Ringers's avatar
Sietse Ringers committed
245
	server.WriteJson(w, qr)
246 247
}

248 249
func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
	res := s.irmaserv.GetSessionResult(chi.URLParam(r, "token"))
250
	if res == nil {
Sietse Ringers's avatar
Sietse Ringers committed
251
		server.WriteError(w, server.ErrorSessionUnknown, "")
252 253
		return
	}
Sietse Ringers's avatar
Sietse Ringers committed
254
	server.WriteJson(w, res.Status)
255 256
}

257
func (s *Server) handleStatusEvents(w http.ResponseWriter, r *http.Request) {
258
	token := chi.URLParam(r, "token")
259 260
	s.conf.Logger.WithFields(logrus.Fields{"session": token}).Debug("new client subscribed to server sent events")
	if err := s.irmaserv.SubscribeServerSentEvents(w, r, token); err != nil {
261 262 263 264
		server.WriteError(w, server.ErrorUnexpectedRequest, err.Error())
	}
}

265 266
func (s *Server) handleDelete(w http.ResponseWriter, r *http.Request) {
	err := s.irmaserv.CancelSession(chi.URLParam(r, "token"))
267 268 269 270 271
	if err != nil {
		server.WriteError(w, server.ErrorSessionUnknown, "")
	}
}

272 273
func (s *Server) handleResult(w http.ResponseWriter, r *http.Request) {
	res := s.irmaserv.GetSessionResult(chi.URLParam(r, "token"))
274
	if res == nil {
Sietse Ringers's avatar
Sietse Ringers committed
275
		server.WriteError(w, server.ErrorSessionUnknown, "")
276 277
		return
	}
Sietse Ringers's avatar
Sietse Ringers committed
278
	server.WriteJson(w, res)
279 280
}

281 282 283
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")
284 285
		server.WriteError(w, server.ErrorUnknown, "JWT signing not supported")
		return
286
	}
287

288
	sessiontoken := chi.URLParam(r, "token")
289
	res := s.irmaserv.GetSessionResult(sessiontoken)
290 291 292
	if res == nil {
		server.WriteError(w, server.ErrorSessionUnknown, "")
		return
293
	}
294

295
	j, err := s.resultJwt(res)
296
	if err != nil {
297
		s.conf.Logger.Error("Failed to sign session result JWT")
298
		_ = server.LogError(err)
299 300 301
		server.WriteError(w, server.ErrorUnknown, err.Error())
		return
	}
302
	server.WriteString(w, j)
303 304
}

305 306 307
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")
308 309 310 311
		server.WriteError(w, server.ErrorUnknown, "JWT signing not supported")
		return
	}

312
	sessiontoken := chi.URLParam(r, "token")
313
	res := s.irmaserv.GetSessionResult(sessiontoken)
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
	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()
334 335
	if s.conf.JwtIssuer != "" {
		claims["iss"] = s.conf.JwtIssuer
336 337
	}
	claims["status"] = res.Status
338
	validity := s.irmaserv.GetRequest(sessiontoken).Base().ResultJwtValidity
339 340 341
	if validity != 0 {
		claims["exp"] = time.Now().Unix() + int64(validity)
	}
342 343 344 345 346 347 348 349 350 351 352 353 354

	// 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)
355
	resultJwt, err := token.SignedString(s.conf.jwtPrivateKey)
356
	if err != nil {
357
		s.conf.Logger.Error("Failed to sign session result JWT")
358
		_ = server.LogError(err)
359 360
		server.WriteError(w, server.ErrorUnknown, err.Error())
		return
361
	}
362
	server.WriteString(w, resultJwt)
363
}
364

365 366
func (s *Server) handlePublicKey(w http.ResponseWriter, r *http.Request) {
	if s.conf.jwtPrivateKey == nil {
367 368 369 370
		server.WriteError(w, server.ErrorUnsupported, "")
		return
	}

371
	bts, err := x509.MarshalPKIXPublicKey(&s.conf.jwtPrivateKey.PublicKey)
372 373 374 375 376 377 378 379 380 381
	if err != nil {
		server.WriteError(w, server.ErrorUnknown, err.Error())
		return
	}
	pubBytes := pem.EncodeToMemory(&pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: bts,
	})
	_, _ = w.Write(pubBytes)
}
382

383
func (s *Server) resultJwt(sessionresult *server.SessionResult) (string, error) {
384 385 386 387 388
	claims := struct {
		jwt.StandardClaims
		*server.SessionResult
	}{
		StandardClaims: jwt.StandardClaims{
389
			Issuer:   s.conf.JwtIssuer,
390 391 392 393 394
			IssuedAt: time.Now().Unix(),
			Subject:  string(sessionresult.Type) + "_result",
		},
		SessionResult: sessionresult,
	}
395
	validity := s.irmaserv.GetRequest(sessionresult.Token).Base().ResultJwtValidity
396 397 398 399 400 401
	if validity != 0 {
		claims.ExpiresAt = time.Now().Unix() + int64(validity)
	}

	// Sign the jwt and return it
	token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
402
	return token.SignedString(s.conf.jwtPrivateKey)
403 404
}

405 406 407
func (s *Server) doResultCallback(result *server.SessionResult) {
	callbackUrl := s.irmaserv.GetRequest(result.Token).Base().CallbackUrl
	if callbackUrl == "" || s.conf.jwtPrivateKey == nil {
408 409
		return
	}
410
	s.conf.Logger.WithFields(logrus.Fields{"session": result.Token, "callbackUrl": callbackUrl}).Debug("POSTing session result")
411

412
	j, err := s.resultJwt(result)
413 414 415 416 417 418 419 420
	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
421
		s.conf.Logger.Warn(errors.WrapPrefix(err, "Failed to POST session result to callback URL", 0))
422 423
	}
}