server.go 12.4 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
14
	"io/ioutil"
	"net/http"
15
	"time"
16

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

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

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

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

49
	return nil
50
51
}

52
53
54
55
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)
56
57
}

58
59
60
61
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)
62
63
}

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

84
func (s *Server) Stop() error {
85
86
87
	var err1, err2 error

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

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

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

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

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

Sietse Ringers's avatar
Sietse Ringers committed
127
	router.Mount("/irma/", s.irmaserv.HandlerFunc())
128
129
130
131
132
	return router
}

// Handler returns a http.Handler that handles all IRMA requestor messages
// and IRMA client messages.
133
func (s *Server) Handler() http.Handler {
134
	router := chi.NewRouter()
135
	router.Use(cors.New(corsOptions).Handler)
136

137
	if !s.conf.separateClientServer() {
138
		// Mount server for irmaclient
Sietse Ringers's avatar
Sietse Ringers committed
139
		router.Mount("/irma/", s.irmaserv.HandlerFunc())
140
	}
141

142
	// Server routes
143
144
145
146
147
	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
148
149

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

153
	router.Get("/publickey", s.handlePublicKey)
154

155
	return router
156
157
}

158
func (s *Server) handleCreate(w http.ResponseWriter, r *http.Request) {
159
160
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
161
		s.conf.Logger.Error("Could not read session request HTTP POST body")
162
		_ = server.LogError(err)
Sietse Ringers's avatar
Sietse Ringers committed
163
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
164
165
		return
	}
166

Sietse Ringers's avatar
Sietse Ringers committed
167
168
169
	// 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.
170
	var (
171
		rrequest  irma.RequestorRequest
172
173
174
175
176
		request   irma.SessionRequest
		requestor string
		rerr      *irma.RemoteError
		applies   bool
	)
Sietse Ringers's avatar
Sietse Ringers committed
177
	for _, authenticator := range authenticators { // rrequest abbreviates "requestor request"
178
		applies, rrequest, requestor, rerr = authenticator.Authenticate(r.Header, body)
179
180
181
182
183
		if applies || rerr != nil {
			break
		}
	}
	if rerr != nil {
184
		_ = server.LogError(rerr)
185
186
187
188
		server.WriteResponse(w, nil, rerr)
		return
	}
	if !applies {
189
		s.conf.Logger.Warnf("Session request uses unknown authentication method, HTTP headers: %s, HTTP POST body: %s",
190
			server.ToJson(r.Header), string(body))
Sietse Ringers's avatar
Sietse Ringers committed
191
		server.WriteError(w, server.ErrorInvalidRequest, "Request could not be authorized")
192
193
194
		return
	}

195
196
	// Authorize request: check if the requestor is allowed to verify or issue
	// the requested attributes or credentials
197
	request = rrequest.SessionRequest()
198
	if request.Action() == irma.ActionIssuing {
199
		allowed, reason := s.conf.CanIssue(requestor, request.(*irma.IssuanceRequest).Credentials)
200
		if !allowed {
201
			s.conf.Logger.WithFields(logrus.Fields{"requestor": requestor, "id": reason}).
202
				Warn("Requestor not authorized to issue credential; full request: ", server.ToJson(request))
203
204
205
206
			server.WriteError(w, server.ErrorUnauthorized, reason)
			return
		}
	}
Sietse Ringers's avatar
Sietse Ringers committed
207
	disjunctions := request.ToDisclose()
208
	if len(disjunctions) > 0 {
209
		allowed, reason := s.conf.CanVerifyOrSign(requestor, request.Action(), disjunctions)
210
		if !allowed {
211
			s.conf.Logger.WithFields(logrus.Fields{"requestor": requestor, "id": reason}).
212
				Warn("Requestor not authorized to verify attribute; full request: ", server.ToJson(request))
213
214
215
216
			server.WriteError(w, server.ErrorUnauthorized, reason)
			return
		}
	}
217
218
	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")
219
220
221
		server.WriteError(w, server.ErrorUnsupported, "")
		return
	}
222
223

	// Everything is authenticated and parsed, we're good to go!
224
	qr, _, err := s.irmaserv.StartSession(rrequest, s.doResultCallback)
225
	if err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
226
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
227
228
229
		return
	}

Sietse Ringers's avatar
Sietse Ringers committed
230
	server.WriteJson(w, qr)
231
232
}

233
234
func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
	res := s.irmaserv.GetSessionResult(chi.URLParam(r, "token"))
235
	if res == nil {
Sietse Ringers's avatar
Sietse Ringers committed
236
		server.WriteError(w, server.ErrorSessionUnknown, "")
237
238
		return
	}
Sietse Ringers's avatar
Sietse Ringers committed
239
	server.WriteJson(w, res.Status)
240
241
}

242
func (s *Server) handleStatusEvents(w http.ResponseWriter, r *http.Request) {
243
	token := chi.URLParam(r, "token")
244
245
	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 {
246
247
248
249
		server.WriteError(w, server.ErrorUnexpectedRequest, err.Error())
	}
}

250
251
func (s *Server) handleDelete(w http.ResponseWriter, r *http.Request) {
	err := s.irmaserv.CancelSession(chi.URLParam(r, "token"))
252
253
254
255
256
	if err != nil {
		server.WriteError(w, server.ErrorSessionUnknown, "")
	}
}

257
258
func (s *Server) handleResult(w http.ResponseWriter, r *http.Request) {
	res := s.irmaserv.GetSessionResult(chi.URLParam(r, "token"))
259
	if res == nil {
Sietse Ringers's avatar
Sietse Ringers committed
260
		server.WriteError(w, server.ErrorSessionUnknown, "")
261
262
		return
	}
Sietse Ringers's avatar
Sietse Ringers committed
263
	server.WriteJson(w, res)
264
265
}

266
267
268
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")
269
270
		server.WriteError(w, server.ErrorUnknown, "JWT signing not supported")
		return
271
	}
272

273
	sessiontoken := chi.URLParam(r, "token")
274
	res := s.irmaserv.GetSessionResult(sessiontoken)
275
276
277
	if res == nil {
		server.WriteError(w, server.ErrorSessionUnknown, "")
		return
278
	}
279

280
	j, err := s.resultJwt(res)
281
	if err != nil {
282
		s.conf.Logger.Error("Failed to sign session result JWT")
283
		_ = server.LogError(err)
284
285
286
		server.WriteError(w, server.ErrorUnknown, err.Error())
		return
	}
287
	server.WriteString(w, j)
288
289
}

290
291
292
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")
293
294
295
296
		server.WriteError(w, server.ErrorUnknown, "JWT signing not supported")
		return
	}

297
	sessiontoken := chi.URLParam(r, "token")
298
	res := s.irmaserv.GetSessionResult(sessiontoken)
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
	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()
319
320
	if s.conf.JwtIssuer != "" {
		claims["iss"] = s.conf.JwtIssuer
321
322
	}
	claims["status"] = res.Status
323
	validity := s.irmaserv.GetRequest(sessiontoken).Base().ResultJwtValidity
324
325
326
	if validity != 0 {
		claims["exp"] = time.Now().Unix() + int64(validity)
	}
327
328
329
330
331
332
333
334
335
336
337
338
339

	// 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)
340
	resultJwt, err := token.SignedString(s.conf.jwtPrivateKey)
341
	if err != nil {
342
		s.conf.Logger.Error("Failed to sign session result JWT")
343
		_ = server.LogError(err)
344
345
		server.WriteError(w, server.ErrorUnknown, err.Error())
		return
346
	}
347
	server.WriteString(w, resultJwt)
348
}
349

350
351
func (s *Server) handlePublicKey(w http.ResponseWriter, r *http.Request) {
	if s.conf.jwtPrivateKey == nil {
352
353
354
355
		server.WriteError(w, server.ErrorUnsupported, "")
		return
	}

356
	bts, err := x509.MarshalPKIXPublicKey(&s.conf.jwtPrivateKey.PublicKey)
357
358
359
360
361
362
363
364
365
366
	if err != nil {
		server.WriteError(w, server.ErrorUnknown, err.Error())
		return
	}
	pubBytes := pem.EncodeToMemory(&pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: bts,
	})
	_, _ = w.Write(pubBytes)
}
367

368
func (s *Server) resultJwt(sessionresult *server.SessionResult) (string, error) {
369
370
371
372
373
	claims := struct {
		jwt.StandardClaims
		*server.SessionResult
	}{
		StandardClaims: jwt.StandardClaims{
374
			Issuer:   s.conf.JwtIssuer,
375
376
377
378
379
			IssuedAt: time.Now().Unix(),
			Subject:  string(sessionresult.Type) + "_result",
		},
		SessionResult: sessionresult,
	}
380
	validity := s.irmaserv.GetRequest(sessionresult.Token).Base().ResultJwtValidity
381
382
383
384
385
386
	if validity != 0 {
		claims.ExpiresAt = time.Now().Unix() + int64(validity)
	}

	// Sign the jwt and return it
	token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
387
	return token.SignedString(s.conf.jwtPrivateKey)
388
389
}

390
391
392
func (s *Server) doResultCallback(result *server.SessionResult) {
	callbackUrl := s.irmaserv.GetRequest(result.Token).Base().CallbackUrl
	if callbackUrl == "" || s.conf.jwtPrivateKey == nil {
393
394
		return
	}
395
	s.conf.Logger.WithFields(logrus.Fields{"session": result.Token, "callbackUrl": callbackUrl}).Debug("POSTing session result")
396

397
	j, err := s.resultJwt(result)
398
399
400
401
402
403
404
405
	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
406
		s.conf.Logger.Warn(errors.WrapPrefix(err, "Failed to POST session result to callback URL", 0))
407
408
	}
}