server.go 10 KB
Newer Older
1
// Package irmaserver is a server allowing IRMA verifiers, issuers or attribute-based signature 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
2
package irmaserver
3
4

import (
5
6
	"crypto/x509"
	"encoding/pem"
7
	"fmt"
8
9
	"io/ioutil"
	"net/http"
10
	"time"
11

12
	"github.com/dgrijalva/jwt-go"
13
	"github.com/go-chi/chi"
Sietse Ringers's avatar
Sietse Ringers committed
14
	"github.com/go-chi/cors"
15
	"github.com/privacybydesign/irmago"
Sietse Ringers's avatar
Sietse Ringers committed
16
17
	"github.com/privacybydesign/irmago/server"
	"github.com/privacybydesign/irmago/server/irmarequestor"
18
19
)

20
var (
21
22
	serv, clientserv *http.Server
	conf             *Configuration
23
)
24

25
// Start the server. If successful then it will not return until Stop() is called.
26
func Start(config *Configuration) error {
27
	if err := Initialize(config); err != nil {
28
29
30
		return err
	}

31
32
33
	// Start server(s)
	if conf.separateClientServer() {
		go startClientServer()
34
	}
35
	startRequestorServer()
36

37
	return nil
38
39
}

40
41
42
func startRequestorServer() {
	serv = &http.Server{}
	startServer(serv, Handler(), "Server", conf.ListenAddress, conf.Port)
43
44
}

45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
func startClientServer() {
	clientserv = &http.Server{}
	startServer(clientserv, ClientHandler(), "Client server", conf.ClientListenAddress, conf.ClientPort)
}

func startServer(s *http.Server, handler http.Handler, name, addr string, port int) {
	fulladdr := fmt.Sprintf("%s:%d", addr, port)
	conf.Logger.Info(name, " listening at ", fulladdr)
	s.Addr = fulladdr
	s.Handler = handler
	if err := s.ListenAndServe(); err != http.ErrServerClosed {
		_ = server.LogFatal(err)
	}
}

func Stop() error {
	var err1, err2 error

	// Even if closing serv fails, we want to try closing clientserv
	err1 = serv.Close()
	if clientserv != nil {
		err2 = clientserv.Close()
	}

	// Now check errors
70
	if err1 != nil && err1 != http.ErrServerClosed {
71
72
		return err1
	}
73
	if err2 != nil && err2 != http.ErrServerClosed {
74
75
76
77
78
79
		return err2
	}
	return nil
}

func Initialize(config *Configuration) error {
80
	conf = config
81
	if err := irmarequestor.Initialize(conf.Configuration); err != nil {
82
		return err
83
	}
84
	if err := conf.initialize(); err != nil {
85
		return err
86
	}
87
88
	return nil
}
89

90
91
92
93
94
95
var corsOptions = cors.Options{
	AllowedOrigins: []string{"*"},
	AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "Cache-Control"},
	AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodDelete},
}

96
func ClientHandler() http.Handler {
97
	router := chi.NewRouter()
98
	router.Use(cors.New(corsOptions).Handler)
Sietse Ringers's avatar
Sietse Ringers committed
99

100
	router.Mount("/irma/", irmarequestor.HttpHandlerFunc())
101
102
103
104
105
106
107
	return router
}

// Handler returns a http.Handler that handles all IRMA requestor messages
// and IRMA client messages.
func Handler() http.Handler {
	router := chi.NewRouter()
108
	router.Use(cors.New(corsOptions).Handler)
109
110
111
112
113

	if !conf.separateClientServer() {
		// Mount server for irmaclient
		router.Mount("/irma/", irmarequestor.HttpHandlerFunc())
	}
114

115
	// Server routes
116
	router.Post("/session", handleCreate)
117
	router.Delete("/session/{token}", handleDelete)
118
	router.Get("/session/{token}/status", handleStatus)
119
	router.Get("/session/{token}/statusevents", handleStatusEvents)
120
	router.Get("/session/{token}/result", handleResult)
Sietse Ringers's avatar
Sietse Ringers committed
121
122

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

126
127
	router.Get("/publickey", handlePublicKey)

128
	return router
129
130
}

131
132
133
func handleCreate(w http.ResponseWriter, r *http.Request) {
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
134
135
		conf.Logger.Error("Could not read session request HTTP POST body")
		_ = server.LogError(err)
Sietse Ringers's avatar
Sietse Ringers committed
136
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
137
138
		return
	}
139

Sietse Ringers's avatar
Sietse Ringers committed
140
141
142
	// 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.
143
	var (
144
		rrequest  irma.RequestorRequest
145
146
147
148
149
150
		request   irma.SessionRequest
		requestor string
		rerr      *irma.RemoteError
		applies   bool
	)
	for _, authenticator := range authenticators {
151
		applies, rrequest, requestor, rerr = authenticator.Authenticate(r.Header, body)
152
153
154
155
156
		if applies || rerr != nil {
			break
		}
	}
	if rerr != nil {
157
		_ = server.LogError(rerr)
158
159
160
161
		server.WriteResponse(w, nil, rerr)
		return
	}
	if !applies {
162
163
		conf.Logger.Warnf("Session request uses unknown authentication method, HTTP headers: %s, HTTP POST body: %s",
			server.ToJson(r.Header), string(body))
Sietse Ringers's avatar
Sietse Ringers committed
164
		server.WriteError(w, server.ErrorInvalidRequest, "Request could not be authorized")
165
166
167
		return
	}

168
169
	// Authorize request: check if the requestor is allowed to verify or issue
	// the requested attributes or credentials
170
	request = rrequest.SessionRequest()
171
172
173
	if request.Action() == irma.ActionIssuing {
		allowed, reason := conf.CanIssue(requestor, request.(*irma.IssuanceRequest).Credentials)
		if !allowed {
174
175
			conf.Logger.Warn("Requestor %s tried to issue credential %s but it is not authorized to; full request: %s",
				requestor, reason, server.ToJson(request))
176
177
178
179
			server.WriteError(w, server.ErrorUnauthorized, reason)
			return
		}
	}
Sietse Ringers's avatar
Sietse Ringers committed
180
	disjunctions := request.ToDisclose()
181
182
183
	if len(disjunctions) > 0 {
		allowed, reason := conf.CanVerifyOrSign(requestor, request.Action(), disjunctions)
		if !allowed {
184
185
			conf.Logger.Warn("Requestor %s tried to verify attribute %s but it is not authorized to; full request: %s",
				requestor, reason, server.ToJson(request))
186
187
188
189
190
191
			server.WriteError(w, server.ErrorUnauthorized, reason)
			return
		}
	}

	// Everything is authenticated and parsed, we're good to go!
192
	qr, _, err := irmarequestor.StartSession(rrequest, nil)
193
	if err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
194
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
195
196
197
		return
	}

Sietse Ringers's avatar
Sietse Ringers committed
198
	server.WriteJson(w, qr)
199
200
201
202
203
}

func handleStatus(w http.ResponseWriter, r *http.Request) {
	res := irmarequestor.GetSessionResult(chi.URLParam(r, "token"))
	if res == nil {
Sietse Ringers's avatar
Sietse Ringers committed
204
		server.WriteError(w, server.ErrorSessionUnknown, "")
205
206
		return
	}
Sietse Ringers's avatar
Sietse Ringers committed
207
	server.WriteJson(w, res.Status)
208
209
}

210
211
212
213
214
215
216
217
func handleStatusEvents(w http.ResponseWriter, r *http.Request) {
	token := chi.URLParam(r, "token")
	conf.Logger.Debug("new client subscribed to server sent events of session " + token)
	if err := irmarequestor.SubscribeServerSentEvents(w, r, token); err != nil {
		server.WriteError(w, server.ErrorUnexpectedRequest, err.Error())
	}
}

218
219
220
221
222
223
224
func handleDelete(w http.ResponseWriter, r *http.Request) {
	err := irmarequestor.CancelSession(chi.URLParam(r, "token"))
	if err != nil {
		server.WriteError(w, server.ErrorSessionUnknown, "")
	}
}

225
226
227
func handleResult(w http.ResponseWriter, r *http.Request) {
	res := irmarequestor.GetSessionResult(chi.URLParam(r, "token"))
	if res == nil {
Sietse Ringers's avatar
Sietse Ringers committed
228
		server.WriteError(w, server.ErrorSessionUnknown, "")
229
230
		return
	}
Sietse Ringers's avatar
Sietse Ringers committed
231
	server.WriteJson(w, res)
232
233
}

234
func handleJwtResult(w http.ResponseWriter, r *http.Request) {
235
	if conf.jwtPrivateKey == nil {
236
		conf.Logger.Warn("Session result JWT requested but no JWT private key is configured")
237
238
		server.WriteError(w, server.ErrorUnknown, "JWT signing not supported")
		return
239
	}
240

241
242
	sessiontoken := chi.URLParam(r, "token")
	res := irmarequestor.GetSessionResult(sessiontoken)
243
244
245
	if res == nil {
		server.WriteError(w, server.ErrorSessionUnknown, "")
		return
246
	}
247
248
249
250
251
252
253
254
255
256

	claims := struct {
		jwt.StandardClaims
		*server.SessionResult
	}{
		SessionResult: res,
	}
	claims.Issuer = conf.JwtIssuer
	claims.IssuedAt = time.Now().Unix()
	claims.Subject = string(res.Type) + "_result"
257
258
259
260
	validity := irmarequestor.GetRequest(sessiontoken).Base().ResultJwtValidity
	if validity != 0 {
		claims.ExpiresAt = time.Now().Unix() + int64(validity)
	}
261
262
263

	// Sign the jwt and return it
	token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
264
	resultJwt, err := token.SignedString(conf.jwtPrivateKey)
265
	if err != nil {
266
267
		conf.Logger.Error("Failed to sign session result JWT")
		_ = server.LogError(err)
268
269
270
271
272
273
274
		server.WriteError(w, server.ErrorUnknown, err.Error())
		return
	}
	server.WriteString(w, resultJwt)
}

func handleJwtProofs(w http.ResponseWriter, r *http.Request) {
275
	if conf.jwtPrivateKey == nil {
276
		conf.Logger.Warn("Session result JWT requested but no JWT private key is configured")
277
278
279
280
		server.WriteError(w, server.ErrorUnknown, "JWT signing not supported")
		return
	}

281
282
	sessiontoken := chi.URLParam(r, "token")
	res := irmarequestor.GetSessionResult(sessiontoken)
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
	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()
	if conf.JwtIssuer != "" {
		claims["iss"] = conf.JwtIssuer
	}
	claims["status"] = res.Status
307
308
309
310
	validity := irmarequestor.GetRequest(sessiontoken).Base().ResultJwtValidity
	if validity != 0 {
		claims["exp"] = time.Now().Unix() + int64(validity)
	}
311
312
313
314
315
316
317
318
319
320
321
322
323

	// 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)
324
	resultJwt, err := token.SignedString(conf.jwtPrivateKey)
325
	if err != nil {
326
327
		conf.Logger.Error("Failed to sign session result JWT")
		_ = server.LogError(err)
328
329
		server.WriteError(w, server.ErrorUnknown, err.Error())
		return
330
	}
331
	server.WriteString(w, resultJwt)
332
}
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350

func handlePublicKey(w http.ResponseWriter, r *http.Request) {
	if conf.jwtPrivateKey == nil {
		server.WriteError(w, server.ErrorUnsupported, "")
		return
	}

	bts, err := x509.MarshalPKIXPublicKey(&conf.jwtPrivateKey.PublicKey)
	if err != nil {
		server.WriteError(w, server.ErrorUnknown, err.Error())
		return
	}
	pubBytes := pem.EncodeToMemory(&pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: bts,
	})
	_, _ = w.Write(pubBytes)
}