api.go 11.1 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
15

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

25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
type Server struct {
	conf      *server.Configuration
	sessions  sessionStore
	scheduler *gocron.Scheduler
}

func New(conf *server.Configuration) (*Server, error) {
	s := &Server{
		conf:      conf,
		scheduler: gocron.NewScheduler(),
		sessions: &memorySessionStore{
			m:    make(map[string]*session),
			conf: conf,
		},
	}
	s.scheduler.Every(10).Seconds().Do(func() {
		s.sessions.deleteExpired()
	})
	s.scheduler.Start()

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

48
49
50
51
52
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{}
53
	}
54
55
	server.Logger = s.conf.Logger
	irma.Logger = s.conf.Logger
56

57
	if s.conf.IrmaConfiguration == nil {
58
59
60
61
62
63
64
65
66
67
68
69
70
		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 {
			return server.LogError(errors.New("Nonexisting schemes_path provided"))
		}
71
72
		if s.conf.SchemesAssetsPath == "" {
			s.conf.IrmaConfiguration, err = irma.NewConfiguration(s.conf.SchemesPath)
73
		} else {
74
			s.conf.IrmaConfiguration, err = irma.NewConfigurationFromAssets(s.conf.SchemesPath, s.conf.SchemesAssetsPath)
75
		}
76
		if err != nil {
77
			return server.LogError(err)
78
		}
79
		if err = s.conf.IrmaConfiguration.ParseFolder(); err != nil {
80
			return server.LogError(err)
81
82
83
		}
	}

84
	if len(s.conf.IrmaConfiguration.SchemeManagers) == 0 {
85
86
87
		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)
88
		}
89
	}
90
91
92
93
94
	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
95
96
	}

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

131
132
133
	if s.conf.URL != "" {
		if !strings.HasSuffix(s.conf.URL, "/") {
			s.conf.URL = s.conf.URL + "/"
134
135
		}
	} else {
136
		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")
137
138
	}

Sietse Ringers's avatar
Sietse Ringers committed
139
140
141
142
143
144
145
146
147
148
149
	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"))
		}
		t := irma.NewHTTPTransport("https://metrics.privacybydesign.foundation/history/email")
		t.SetHeader("User-Agent", "irmaserver")
		var x string
		_ = t.Post("", &x, s.conf.Email)
	}

150
151
152
	return nil
}

153
func (s *Server) StartSession(req interface{}) (*irma.Qr, string, error) {
154
155
	rrequest, err := server.ParseSessionRequest(req)
	if err != nil {
156
		return nil, "", err
157
	}
158
159
160
161

	request := rrequest.SessionRequest()
	action := request.Action()
	if action == irma.ActionIssuing {
162
		if err := s.validateIssuanceRequest(request.(*irma.IssuanceRequest)); err != nil {
163
			return nil, "", err
164
165
166
		}
	}

167
168
169
170
	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))
171
	} else {
172
		s.conf.Logger.WithFields(logrus.Fields{"session": session.token}).Info("Session request (purged of attribute values): ", server.ToJson(purgeRequest(rrequest)))
173
	}
174
175
	return &irma.Qr{
		Type: action,
176
		URL:  s.conf.URL + session.token,
177
178
179
	}, session.token, nil
}

180
181
func (s *Server) GetSessionResult(token string) *server.SessionResult {
	session := s.sessions.get(token)
182
	if session == nil {
183
		s.conf.Logger.Warn("Session result requested of unknown session ", token)
Sietse Ringers's avatar
Sietse Ringers committed
184
185
186
187
188
		return nil
	}
	return session.result
}

189
190
func (s *Server) GetRequest(token string) irma.RequestorRequest {
	session := s.sessions.get(token)
191
	if session == nil {
192
		s.conf.Logger.Warn("Session request requested of unknown session ", token)
193
194
195
196
197
		return nil
	}
	return session.rrequest
}

198
199
func (s *Server) CancelSession(token string) error {
	session := s.sessions.get(token)
200
	if session == nil {
201
		return server.LogError(errors.Errorf("can't cancel unknown session %s", token))
202
203
204
205
206
	}
	session.handleDelete()
	return nil
}

207
208
209
210
211
212
213
214
215
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
}

216
217
func (s *Server) SubscribeServerSentEvents(w http.ResponseWriter, r *http.Request, token string) error {
	session := s.sessions.get(token)
218
219
220
221
222
223
224
225
226
227
228
229
230
	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()
	session.eventSource().ServeHTTP(w, r)
	return nil
}

231
func (s *Server) HandleProtocolMessage(
232
233
234
235
	path string,
	method string,
	headers map[string][]string,
	message []byte,
Sietse Ringers's avatar
Sietse Ringers committed
236
) (status int, output []byte, result *server.SessionResult) {
237
238
239
240
241
242
243
244
245
	// 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]
		}
	}
246

247
	s.conf.Logger.WithFields(logrus.Fields{"method": method, "path": path}).Debugf("Routing protocol message")
248
	if len(message) > 0 {
249
		s.conf.Logger.Trace("POST body: ", string(message))
250
	}
251
	s.conf.Logger.Trace("HTTP headers: ", server.ToJson(headers))
252
253
254
	token, noun, err := ParsePath(path)
	if err != nil {
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorUnsupported, ""))
255
		return
256
257
	}

Sietse Ringers's avatar
Sietse Ringers committed
258
	// Fetch the session
259
	session := s.sessions.get(token)
260
	if session == nil {
261
		s.conf.Logger.Warnf("Session not found: %s", token)
Sietse Ringers's avatar
Sietse Ringers committed
262
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorSessionUnknown, ""))
263
		return
264
	}
265
266
	session.Lock()
	defer session.Unlock()
267

268
269
	// However we return, if the session status has been updated
	// then we should inform the user by returning a SessionResult
270
	defer func() {
271
272
		if session.status != session.prevStatus {
			session.prevStatus = session.status
273
274
275
276
			result = session.result
		}
	}()

277
	// Route to handler
278
	switch len(noun) {
279
	case 0:
280
		if method == http.MethodDelete {
281
282
283
			session.handleDelete()
			status = http.StatusOK
			return
284
		}
285
		if method == http.MethodGet {
286
287
288
289
			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
290
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
291
				return
292
293
			}
			if err := json.Unmarshal([]byte(h.Get(irma.MaxVersionHeader)), max); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
294
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
295
				return
296
			}
Sietse Ringers's avatar
Sietse Ringers committed
297
			status, output = server.JsonResponse(session.handleGetRequest(min, max))
298
			return
299
		}
Sietse Ringers's avatar
Sietse Ringers committed
300
		status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
301
		return
302
	default:
303
304
305
306
307
308
		if noun == "statusevents" {
			err := server.RemoteError(server.ErrorInvalidRequest, "server sent events not supported by this server")
			status, output = server.JsonResponse(nil, err)
			return
		}

309
310
		if method == http.MethodGet && noun == "status" {
			status, output = server.JsonResponse(session.handleGetStatus())
Sietse Ringers's avatar
Sietse Ringers committed
311
			return
312
313
314
		}

		// Below are only POST enpoints
315
		if method != http.MethodPost {
Sietse Ringers's avatar
Sietse Ringers committed
316
			status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
Sietse Ringers's avatar
Sietse Ringers committed
317
318
319
			return
		}

320
		if noun == "commitments" && session.action == irma.ActionIssuing {
Sietse Ringers's avatar
Sietse Ringers committed
321
			commitments := &irma.IssueCommitmentMessage{}
Sietse Ringers's avatar
Sietse Ringers committed
322
			if err := irma.UnmarshalValidate(message, commitments); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
323
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, ""))
324
				return
325
			}
Sietse Ringers's avatar
Sietse Ringers committed
326
			status, output = server.JsonResponse(session.handlePostCommitments(commitments))
Sietse Ringers's avatar
Sietse Ringers committed
327
328
			return
		}
329
		if noun == "proofs" && session.action == irma.ActionDisclosing {
Sietse Ringers's avatar
Sietse Ringers committed
330
331
			disclosure := irma.Disclosure{}
			if err := irma.UnmarshalValidate(message, &disclosure); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
332
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, ""))
333
				return
334
			}
Sietse Ringers's avatar
Sietse Ringers committed
335
			status, output = server.JsonResponse(session.handlePostDisclosure(disclosure))
Sietse Ringers's avatar
Sietse Ringers committed
336
337
			return
		}
338
		if noun == "proofs" && session.action == irma.ActionSigning {
Sietse Ringers's avatar
Sietse Ringers committed
339
340
			signature := &irma.SignedMessage{}
			if err := irma.UnmarshalValidate(message, signature); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
341
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, ""))
342
				return
343
			}
Sietse Ringers's avatar
Sietse Ringers committed
344
			status, output = server.JsonResponse(session.handlePostSignature(signature))
345
			return
346
		}
Sietse Ringers's avatar
Sietse Ringers committed
347

Sietse Ringers's avatar
Sietse Ringers committed
348
		status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
349
		return
350
351
	}
}