api.go 12.3 KB
Newer Older
Sietse Ringers's avatar
Sietse Ringers committed
1
// Package servercore is the core of the IRMA server library, allowing IRMA verifiers, issuers
2
3
// or attribute-based signature applications to perform IRMA sessions with irmaclient instances
// (i.e. the IRMA app). It exposes a small interface to expose to other programming languages
Sietse Ringers's avatar
Sietse Ringers committed
4
// through cgo. It is used by the irmaserver package but otherwise not meant for use in Go.
5
package servercore
6
7
8

import (
	"encoding/json"
9
	"io/ioutil"
10
	"net/http"
11
	"path/filepath"
12
	"regexp"
13
	"strings"
14
	"time"
15
16

	"github.com/go-errors/errors"
17
	"github.com/jasonlvhit/gocron"
18
19
	"github.com/privacybydesign/gabi"
	"github.com/privacybydesign/gabi/big"
20
	"github.com/privacybydesign/irmago"
21
	"github.com/privacybydesign/irmago/internal/fs"
Sietse Ringers's avatar
Sietse Ringers committed
22
	"github.com/privacybydesign/irmago/server"
23
	"github.com/sirupsen/logrus"
24
25
)

26
type Server struct {
27
28
29
30
	conf          *server.Configuration
	sessions      sessionStore
	scheduler     *gocron.Scheduler
	stopScheduler chan bool
31
32
33
34
35
36
37
}

func New(conf *server.Configuration) (*Server, error) {
	s := &Server{
		conf:      conf,
		scheduler: gocron.NewScheduler(),
		sessions: &memorySessionStore{
38
39
40
			requestor: make(map[string]*session),
			client:    make(map[string]*session),
			conf:      conf,
41
42
43
44
45
		},
	}
	s.scheduler.Every(10).Seconds().Do(func() {
		s.sessions.deleteExpired()
	})
46
	s.stopScheduler = s.scheduler.Start()
47
48
49

	return s, s.verifyConfiguration(s.conf)
}
50

51
52
53
54
55
func (s *Server) Stop() {
	s.stopScheduler <- true
	s.sessions.stop()
}

56
57
58
59
60
func (s *Server) verifyConfiguration(configuration *server.Configuration) error {
	if s.conf.Logger == nil {
		s.conf.Logger = logrus.New()
		s.conf.Logger.Level = logrus.DebugLevel
		s.conf.Logger.Formatter = &logrus.TextFormatter{}
61
	}
62
63
	server.Logger = s.conf.Logger
	irma.Logger = s.conf.Logger
64

65
	if s.conf.IrmaConfiguration == nil {
66
67
68
69
70
71
72
73
74
75
76
		var (
			err    error
			exists bool
		)
		if s.conf.SchemesPath == "" {
			s.conf.SchemesPath = server.DefaultSchemesPath() // Returns an existing path
		}
		if exists, err = fs.PathExists(s.conf.SchemesPath); err != nil {
			return server.LogError(err)
		}
		if !exists {
77
			return server.LogError(errors.Errorf("Nonexisting schemes_path provided: %s", s.conf.SchemesPath))
78
		}
79
		s.conf.Logger.WithField("schemes_path", s.conf.SchemesPath).Info("Determined schemes path")
80
81
		if s.conf.SchemesAssetsPath == "" {
			s.conf.IrmaConfiguration, err = irma.NewConfiguration(s.conf.SchemesPath)
82
		} else {
83
			s.conf.IrmaConfiguration, err = irma.NewConfigurationFromAssets(s.conf.SchemesPath, s.conf.SchemesAssetsPath)
84
		}
85
		if err != nil {
86
			return server.LogError(err)
87
		}
88
		if err = s.conf.IrmaConfiguration.ParseFolder(); err != nil {
89
			return server.LogError(err)
90
91
92
		}
	}

93
	if len(s.conf.IrmaConfiguration.SchemeManagers) == 0 {
94
95
96
		s.conf.Logger.Infof("No schemes found in %s, downloading default (irma-demo and pbdf)", s.conf.SchemesPath)
		if err := s.conf.IrmaConfiguration.DownloadDefaultSchemes(); err != nil {
			return server.LogError(err)
97
		}
98
	}
99
100
101
102
103
	if s.conf.SchemesUpdateInterval == 0 {
		s.conf.SchemesUpdateInterval = 60
	}
	if !s.conf.DisableSchemesUpdate {
		s.conf.IrmaConfiguration.AutoUpdateSchemes(uint(s.conf.SchemesUpdateInterval))
Sietse Ringers's avatar
Sietse Ringers committed
104
105
	}

106
107
	if s.conf.IssuerPrivateKeys == nil {
		s.conf.IssuerPrivateKeys = make(map[irma.IssuerIdentifier]*gabi.PrivateKey)
108
	}
109
110
	if s.conf.IssuerPrivateKeysPath != "" {
		files, err := ioutil.ReadDir(s.conf.IssuerPrivateKeysPath)
111
		if err != nil {
112
			return server.LogError(err)
113
114
115
116
		}
		for _, file := range files {
			filename := file.Name()
			issid := irma.NewIssuerIdentifier(strings.TrimSuffix(filename, filepath.Ext(filename))) // strip .xml
117
			if _, ok := s.conf.IrmaConfiguration.Issuers[issid]; !ok {
118
				return server.LogError(errors.Errorf("Private key %s belongs to an unknown issuer", filename))
119
			}
120
			sk, err := gabi.NewPrivateKeyFromFile(filepath.Join(s.conf.IssuerPrivateKeysPath, filename))
121
			if err != nil {
122
				return server.LogError(err)
123
			}
124
			s.conf.IssuerPrivateKeys[issid] = sk
125
126
		}
	}
127
128
	for issid, sk := range s.conf.IssuerPrivateKeys {
		pk, err := s.conf.IrmaConfiguration.PublicKey(issid, int(sk.Counter))
129
		if err != nil {
130
			return server.LogError(err)
131
132
		}
		if pk == nil {
133
			return server.LogError(errors.Errorf("Missing public key belonging to private key %s-%d", issid.String(), sk.Counter))
134
135
		}
		if new(big.Int).Mul(sk.P, sk.Q).Cmp(pk.N) != 0 {
136
			return server.LogError(errors.Errorf("Private key %s-%d does not belong to corresponding public key", issid.String(), sk.Counter))
137
138
139
		}
	}

140
141
142
	if s.conf.URL != "" {
		if !strings.HasSuffix(s.conf.URL, "/") {
			s.conf.URL = s.conf.URL + "/"
143
144
		}
	} else {
145
		s.conf.Logger.Warn("No url parameter specified in configuration; unless an url is elsewhere prepended in the QR, the IRMA client will not be able to connect")
146
147
	}

Sietse Ringers's avatar
Sietse Ringers committed
148
149
150
151
152
	if s.conf.Email != "" {
		// Very basic sanity checks
		if !strings.Contains(s.conf.Email, "@") || strings.Contains(s.conf.Email, "\n") {
			return server.LogError(errors.New("Invalid email address specified"))
		}
Sietse Ringers's avatar
Sietse Ringers committed
153
		t := irma.NewHTTPTransport("https://metrics.privacybydesign.foundation/history")
Sietse Ringers's avatar
Sietse Ringers committed
154
155
		t.SetHeader("User-Agent", "irmaserver")
		var x string
Sietse Ringers's avatar
Sietse Ringers committed
156
		_ = t.Post("email", &x, s.conf.Email)
Sietse Ringers's avatar
Sietse Ringers committed
157
158
	}

159
160
161
	return nil
}

162
func (s *Server) StartSession(req interface{}) (*irma.Qr, string, error) {
163
164
	rrequest, err := server.ParseSessionRequest(req)
	if err != nil {
165
		return nil, "", err
166
	}
167
168
169
170

	request := rrequest.SessionRequest()
	action := request.Action()
	if action == irma.ActionIssuing {
171
		if err := s.validateIssuanceRequest(request.(*irma.IssuanceRequest)); err != nil {
172
			return nil, "", err
173
174
175
		}
	}

176
177
178
179
	session := s.newSession(action, rrequest)
	s.conf.Logger.WithFields(logrus.Fields{"action": action, "session": session.token}).Infof("Session started")
	if s.conf.Logger.IsLevelEnabled(logrus.DebugLevel) {
		s.conf.Logger.WithFields(logrus.Fields{"session": session.token}).Info("Session request: ", server.ToJson(rrequest))
180
	} else {
181
		s.conf.Logger.WithFields(logrus.Fields{"session": session.token}).Info("Session request (purged of attribute values): ", server.ToJson(purgeRequest(rrequest)))
182
	}
183
184
	return &irma.Qr{
		Type: action,
185
		URL:  s.conf.URL + session.clientToken,
186
187
188
	}, session.token, nil
}

189
190
func (s *Server) GetSessionResult(token string) *server.SessionResult {
	session := s.sessions.get(token)
191
	if session == nil {
192
		s.conf.Logger.Warn("Session result requested of unknown session ", token)
Sietse Ringers's avatar
Sietse Ringers committed
193
194
195
196
197
		return nil
	}
	return session.result
}

198
199
func (s *Server) GetRequest(token string) irma.RequestorRequest {
	session := s.sessions.get(token)
200
	if session == nil {
201
		s.conf.Logger.Warn("Session request requested of unknown session ", token)
202
203
204
205
206
		return nil
	}
	return session.rrequest
}

207
208
func (s *Server) CancelSession(token string) error {
	session := s.sessions.get(token)
209
	if session == nil {
210
		return server.LogError(errors.Errorf("can't cancel unknown session %s", token))
211
212
213
214
215
	}
	session.handleDelete()
	return nil
}

216
217
218
219
220
221
222
223
224
func ParsePath(path string) (string, string, error) {
	pattern := regexp.MustCompile("(\\w+)/?(|commitments|proofs|status|statusevents)$")
	matches := pattern.FindStringSubmatch(path)
	if len(matches) != 3 {
		return "", "", server.LogWarning(errors.Errorf("Invalid URL: %s", path))
	}
	return matches[1], matches[2], nil
}

225
226
227
228
229
230
231
func (s *Server) SubscribeServerSentEvents(w http.ResponseWriter, r *http.Request, token string, requestor bool) error {
	var session *session
	if requestor {
		session = s.sessions.get(token)
	} else {
		session = s.sessions.clientGet(token)
	}
232
233
234
235
236
237
238
239
240
	if session == nil {
		return server.LogError(errors.Errorf("can't subscribe to server sent events of unknown session %s", token))
	}
	if session.status.Finished() {
		return server.LogError(errors.Errorf("can't subscribe to server sent events of finished session %s", token))
	}

	session.Lock()
	defer session.Unlock()
241
242
243
244
245
246
247
248
249
250
251
252
253

	// The EventSource.onopen Javascript callback is not consistently called across browsers (Chrome yes, Firefox+Safari no).
	// However, when the SSE connection has been opened the webclient needs some signal so that it can early detect SSE failures.
	// So we manually send an "open" event. Unfortunately:
	// - we need to give the webclient that connected just now some time, otherwise it will miss the "open" event
	// - the "open" event also goes to all other webclients currently listening, as we have no way to send this
	//   event to just the webclient currently listening. (Thus the handler of this "open" event must be idempotent.)
	evtSource := session.eventSource()
	go func() {
		time.Sleep(200 * time.Millisecond)
		evtSource.SendEventMessage("", "open", "")
	}()
	evtSource.ServeHTTP(w, r)
254
255
256
	return nil
}

257
func (s *Server) HandleProtocolMessage(
258
259
260
261
	path string,
	method string,
	headers map[string][]string,
	message []byte,
Sietse Ringers's avatar
Sietse Ringers committed
262
) (status int, output []byte, result *server.SessionResult) {
263
264
265
266
267
268
269
270
271
	// Parse path into session and action
	if len(path) > 0 { // Remove any starting and trailing slash
		if path[0] == '/' {
			path = path[1:]
		}
		if path[len(path)-1] == '/' {
			path = path[:len(path)-1]
		}
	}
272

273
	s.conf.Logger.WithFields(logrus.Fields{"method": method, "path": path}).Debugf("Routing protocol message")
274
	if len(message) > 0 {
275
		s.conf.Logger.Trace("POST body: ", string(message))
276
	}
277
	s.conf.Logger.Trace("HTTP headers: ", server.ToJson(headers))
278
279
280
	token, noun, err := ParsePath(path)
	if err != nil {
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorUnsupported, ""))
281
		return
282
283
	}

Sietse Ringers's avatar
Sietse Ringers committed
284
	// Fetch the session
285
	session := s.sessions.clientGet(token)
286
	if session == nil {
287
		s.conf.Logger.WithField("clientToken", token).Warn("Session not found")
Sietse Ringers's avatar
Sietse Ringers committed
288
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorSessionUnknown, ""))
289
		return
290
	}
291
292
	session.Lock()
	defer session.Unlock()
293

294
295
	// However we return, if the session status has been updated
	// then we should inform the user by returning a SessionResult
296
	defer func() {
297
298
		if session.status != session.prevStatus {
			session.prevStatus = session.status
299
300
301
302
			result = session.result
		}
	}()

303
	// Route to handler
304
	switch len(noun) {
305
	case 0:
306
		if method == http.MethodDelete {
307
308
309
			session.handleDelete()
			status = http.StatusOK
			return
310
		}
311
		if method == http.MethodGet {
312
313
314
315
			h := http.Header(headers)
			min := &irma.ProtocolVersion{}
			max := &irma.ProtocolVersion{}
			if err := json.Unmarshal([]byte(h.Get(irma.MinVersionHeader)), min); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
316
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
317
				return
318
319
			}
			if err := json.Unmarshal([]byte(h.Get(irma.MaxVersionHeader)), max); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
320
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
321
				return
322
			}
Sietse Ringers's avatar
Sietse Ringers committed
323
			status, output = server.JsonResponse(session.handleGetRequest(min, max))
324
			return
325
		}
Sietse Ringers's avatar
Sietse Ringers committed
326
		status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
327
		return
328
	default:
329
330
331
332
333
334
		if noun == "statusevents" {
			err := server.RemoteError(server.ErrorInvalidRequest, "server sent events not supported by this server")
			status, output = server.JsonResponse(nil, err)
			return
		}

335
336
		if method == http.MethodGet && noun == "status" {
			status, output = server.JsonResponse(session.handleGetStatus())
Sietse Ringers's avatar
Sietse Ringers committed
337
			return
338
339
340
		}

		// Below are only POST enpoints
341
		if method != http.MethodPost {
Sietse Ringers's avatar
Sietse Ringers committed
342
			status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
Sietse Ringers's avatar
Sietse Ringers committed
343
344
345
			return
		}

346
		if noun == "commitments" && session.action == irma.ActionIssuing {
Sietse Ringers's avatar
Sietse Ringers committed
347
			commitments := &irma.IssueCommitmentMessage{}
Sietse Ringers's avatar
Sietse Ringers committed
348
			if err := irma.UnmarshalValidate(message, commitments); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
349
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, ""))
350
				return
351
			}
Sietse Ringers's avatar
Sietse Ringers committed
352
			status, output = server.JsonResponse(session.handlePostCommitments(commitments))
Sietse Ringers's avatar
Sietse Ringers committed
353
354
			return
		}
355
		if noun == "proofs" && session.action == irma.ActionDisclosing {
Sietse Ringers's avatar
Sietse Ringers committed
356
357
			disclosure := irma.Disclosure{}
			if err := irma.UnmarshalValidate(message, &disclosure); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
358
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, ""))
359
				return
360
			}
Sietse Ringers's avatar
Sietse Ringers committed
361
			status, output = server.JsonResponse(session.handlePostDisclosure(disclosure))
Sietse Ringers's avatar
Sietse Ringers committed
362
363
			return
		}
364
		if noun == "proofs" && session.action == irma.ActionSigning {
Sietse Ringers's avatar
Sietse Ringers committed
365
366
			signature := &irma.SignedMessage{}
			if err := irma.UnmarshalValidate(message, signature); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
367
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, ""))
368
				return
369
			}
Sietse Ringers's avatar
Sietse Ringers committed
370
			status, output = server.JsonResponse(session.handlePostSignature(signature))
371
			return
372
		}
Sietse Ringers's avatar
Sietse Ringers committed
373

Sietse Ringers's avatar
Sietse Ringers committed
374
		status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
375
		return
376
377
	}
}