server.go 7.7 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
	"fmt"
6
7
	"io/ioutil"
	"net/http"
8
	"time"
9

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

18
19
20
21
var (
	s    *http.Server
	conf *Configuration
)
22

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

30
	// Start server
31
	addr := fmt.Sprintf("%s:%d", conf.ListenAddress, conf.Port)
32
33
	config.Logger.Info("Listening at ", addr)
	s = &http.Server{Addr: addr, Handler: handler}
34
35
36
37
38
	err = s.ListenAndServe()
	if err == http.ErrServerClosed {
		return nil // Server was closed normally
	}

39
	return server.LogError(err)
40
41
42
43
44
45
}

func Stop() {
	s.Close()
}

Sietse Ringers's avatar
Sietse Ringers committed
46
47
// Handler returns a http.Handler that handles all IRMA requestor messages
// and IRMA client messages.
48
49
func Handler(config *Configuration) (http.Handler, error) {
	conf = config
50
	if err := irmarequestor.Initialize(conf.Configuration); err != nil {
51
52
		return nil, err
	}
53
54
55
	if err := conf.initialize(); err != nil {
		return nil, err
	}
56

57
	router := chi.NewRouter()
58

Sietse Ringers's avatar
Sietse Ringers committed
59
60
61
	router.Use(cors.New(cors.Options{
		AllowedOrigins: []string{"*"},
		AllowedHeaders: []string{"Accept", "Authorization", "Content-Type"},
Sietse Ringers's avatar
Sietse Ringers committed
62
		AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodDelete},
Sietse Ringers's avatar
Sietse Ringers committed
63
64
	}).Handler)

65
	// Mount server for irmaclient
66
	router.Mount("/irma/", irmarequestor.HttpHandlerFunc())
67

68
	// Server routes
69
	router.Post("/session", handleCreate)
70
	router.Delete("/session/{token}", handleDelete)
71
72
	router.Get("/session/{token}/status", handleStatus)
	router.Get("/session/{token}/result", handleResult)
Sietse Ringers's avatar
Sietse Ringers committed
73
74

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

78
	return router, nil
79
80
}

81
82
83
func handleCreate(w http.ResponseWriter, r *http.Request) {
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
84
85
		conf.Logger.Error("Could not read session request HTTP POST body")
		_ = server.LogError(err)
Sietse Ringers's avatar
Sietse Ringers committed
86
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
87
88
		return
	}
89

Sietse Ringers's avatar
Sietse Ringers committed
90
91
92
	// 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.
93
94
95
96
97
98
99
100
101
102
103
104
105
	var (
		request   irma.SessionRequest
		requestor string
		rerr      *irma.RemoteError
		applies   bool
	)
	for _, authenticator := range authenticators {
		applies, request, requestor, rerr = authenticator.Authenticate(r.Header, body)
		if applies || rerr != nil {
			break
		}
	}
	if rerr != nil {
106
		_ = server.LogError(rerr)
107
108
109
110
		server.WriteResponse(w, nil, rerr)
		return
	}
	if !applies {
111
112
		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
113
		server.WriteError(w, server.ErrorInvalidRequest, "Request could not be authorized")
114
115
116
		return
	}

117
118
119
120
121
	// Authorize request: check if the requestor is allowed to verify or issue
	// the requested attributes or credentials
	if request.Action() == irma.ActionIssuing {
		allowed, reason := conf.CanIssue(requestor, request.(*irma.IssuanceRequest).Credentials)
		if !allowed {
122
123
			conf.Logger.Warn("Requestor %s tried to issue credential %s but it is not authorized to; full request: %s",
				requestor, reason, server.ToJson(request))
124
125
126
127
			server.WriteError(w, server.ErrorUnauthorized, reason)
			return
		}
	}
Sietse Ringers's avatar
Sietse Ringers committed
128
	disjunctions := request.ToDisclose()
129
130
131
	if len(disjunctions) > 0 {
		allowed, reason := conf.CanVerifyOrSign(requestor, request.Action(), disjunctions)
		if !allowed {
132
133
			conf.Logger.Warn("Requestor %s tried to verify attribute %s but it is not authorized to; full request: %s",
				requestor, reason, server.ToJson(request))
134
135
136
137
138
139
			server.WriteError(w, server.ErrorUnauthorized, reason)
			return
		}
	}

	// Everything is authenticated and parsed, we're good to go!
140
141
	qr, _, err := irmarequestor.StartSession(request, nil)
	if err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
142
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
143
144
145
		return
	}

Sietse Ringers's avatar
Sietse Ringers committed
146
	server.WriteJson(w, qr)
147
148
149
150
151
}

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
152
		server.WriteError(w, server.ErrorSessionUnknown, "")
153
154
		return
	}
Sietse Ringers's avatar
Sietse Ringers committed
155
	server.WriteJson(w, res.Status)
156
157
}

158
159
160
161
162
163
164
func handleDelete(w http.ResponseWriter, r *http.Request) {
	err := irmarequestor.CancelSession(chi.URLParam(r, "token"))
	if err != nil {
		server.WriteError(w, server.ErrorSessionUnknown, "")
	}
}

165
166
167
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
168
		server.WriteError(w, server.ErrorSessionUnknown, "")
169
170
		return
	}
Sietse Ringers's avatar
Sietse Ringers committed
171
	server.WriteJson(w, res)
172
173
}

174
func handleJwtResult(w http.ResponseWriter, r *http.Request) {
175
	if conf.jwtPrivateKey == nil {
176
		conf.Logger.Warn("Session result JWT requested but no JWT private key is configured")
177
178
		server.WriteError(w, server.ErrorUnknown, "JWT signing not supported")
		return
179
	}
180
181
182
183
184

	res := irmarequestor.GetSessionResult(chi.URLParam(r, "token"))
	if res == nil {
		server.WriteError(w, server.ErrorSessionUnknown, "")
		return
185
	}
186
187
188
189
190
191
192
193
194
195
196
197
198

	claims := struct {
		jwt.StandardClaims
		*server.SessionResult
	}{
		SessionResult: res,
	}
	claims.Issuer = conf.JwtIssuer
	claims.IssuedAt = time.Now().Unix()
	claims.Subject = string(res.Type) + "_result"

	// Sign the jwt and return it
	token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
199
	resultJwt, err := token.SignedString(conf.jwtPrivateKey)
200
	if err != nil {
201
202
		conf.Logger.Error("Failed to sign session result JWT")
		_ = server.LogError(err)
203
204
205
206
207
208
209
		server.WriteError(w, server.ErrorUnknown, err.Error())
		return
	}
	server.WriteString(w, resultJwt)
}

func handleJwtProofs(w http.ResponseWriter, r *http.Request) {
210
	if conf.jwtPrivateKey == nil {
211
		conf.Logger.Warn("Session result JWT requested but no JWT private key is configured")
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
		server.WriteError(w, server.ErrorUnknown, "JWT signing not supported")
		return
	}

	res := irmarequestor.GetSessionResult(chi.URLParam(r, "token"))
	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

	// 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)
254
	resultJwt, err := token.SignedString(conf.jwtPrivateKey)
255
	if err != nil {
256
257
		conf.Logger.Error("Failed to sign session result JWT")
		_ = server.LogError(err)
258
259
		server.WriteError(w, server.ErrorUnknown, err.Error())
		return
260
	}
261
	server.WriteString(w, resultJwt)
262
}