api.go 10.3 KB
Newer Older
1
2
3
4
// Package core is the core of the IRMA server library, allowing IRMA verifiers, issuers
// 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
// through cgo. It is used by the irmarequestor 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"
Sietse Ringers's avatar
Sietse Ringers committed
20
	"github.com/privacybydesign/irmago/server"
21
	"github.com/sirupsen/logrus"
22
23
)

24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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)
}
46

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

56
	if s.conf.IrmaConfiguration == nil {
57
		var err error
58
59
		if s.conf.SchemesAssetsPath == "" {
			s.conf.IrmaConfiguration, err = irma.NewConfiguration(s.conf.SchemesPath)
60
		} else {
61
			s.conf.IrmaConfiguration, err = irma.NewConfigurationFromAssets(s.conf.SchemesPath, s.conf.SchemesAssetsPath)
62
		}
63
		if err != nil {
64
			return server.LogError(err)
65
		}
66
		if err = s.conf.IrmaConfiguration.ParseFolder(); err != nil {
67
			return server.LogError(err)
68
69
70
		}
	}

71
72
73
	if len(s.conf.IrmaConfiguration.SchemeManagers) == 0 {
		if s.conf.DownloadDefaultSchemes {
			if err := s.conf.IrmaConfiguration.DownloadDefaultSchemes(); err != nil {
74
				return server.LogError(err)
75
			}
76
		} else {
77
			return server.LogError(errors.New("no schemes found in irma_configuration folder " + s.conf.IrmaConfiguration.Path))
78
		}
79
	}
80
81
	if s.conf.SchemeUpdateInterval != 0 {
		s.conf.IrmaConfiguration.AutoUpdateSchemes(uint(s.conf.SchemeUpdateInterval))
Sietse Ringers's avatar
Sietse Ringers committed
82
83
	}

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

118
119
120
	if s.conf.URL != "" {
		if !strings.HasSuffix(s.conf.URL, "/") {
			s.conf.URL = s.conf.URL + "/"
121
122
		}
	} else {
123
		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")
124
125
	}

126
127
128
	return nil
}

129
func (s *Server) StartSession(req interface{}) (*irma.Qr, string, error) {
130
131
	rrequest, err := server.ParseSessionRequest(req)
	if err != nil {
132
		return nil, "", err
133
	}
134
135
136
137

	request := rrequest.SessionRequest()
	action := request.Action()
	if action == irma.ActionIssuing {
138
		if err := s.validateIssuanceRequest(request.(*irma.IssuanceRequest)); err != nil {
139
			return nil, "", err
140
141
142
		}
	}

143
144
145
146
	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))
147
	} else {
148
		s.conf.Logger.WithFields(logrus.Fields{"session": session.token}).Info("Session request (purged of attribute values): ", server.ToJson(purgeRequest(rrequest)))
149
	}
150
151
	return &irma.Qr{
		Type: action,
152
		URL:  s.conf.URL + session.token,
153
154
155
	}, session.token, nil
}

156
157
func (s *Server) GetSessionResult(token string) *server.SessionResult {
	session := s.sessions.get(token)
158
	if session == nil {
159
		s.conf.Logger.Warn("Session result requested of unknown session ", token)
Sietse Ringers's avatar
Sietse Ringers committed
160
161
162
163
164
		return nil
	}
	return session.result
}

165
166
func (s *Server) GetRequest(token string) irma.RequestorRequest {
	session := s.sessions.get(token)
167
	if session == nil {
168
		s.conf.Logger.Warn("Session request requested of unknown session ", token)
169
170
171
172
173
		return nil
	}
	return session.rrequest
}

174
175
func (s *Server) CancelSession(token string) error {
	session := s.sessions.get(token)
176
	if session == nil {
177
		return server.LogError(errors.Errorf("can't cancel unknown session %s", token))
178
179
180
181
182
	}
	session.handleDelete()
	return nil
}

183
184
185
186
187
188
189
190
191
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
}

192
193
func (s *Server) SubscribeServerSentEvents(w http.ResponseWriter, r *http.Request, token string) error {
	session := s.sessions.get(token)
194
195
196
197
198
199
200
201
202
203
204
205
206
	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
}

207
func (s *Server) HandleProtocolMessage(
208
209
210
211
	path string,
	method string,
	headers map[string][]string,
	message []byte,
Sietse Ringers's avatar
Sietse Ringers committed
212
) (status int, output []byte, result *server.SessionResult) {
213
214
215
216
217
218
219
220
221
	// 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]
		}
	}
222

223
	s.conf.Logger.WithFields(logrus.Fields{"method": method, "path": path}).Debugf("Routing protocol message")
224
	if len(message) > 0 {
225
		s.conf.Logger.Trace("POST body: ", string(message))
226
	}
227
	s.conf.Logger.Trace("HTTP headers: ", server.ToJson(headers))
228
229
230
	token, noun, err := ParsePath(path)
	if err != nil {
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorUnsupported, ""))
231
		return
232
233
	}

Sietse Ringers's avatar
Sietse Ringers committed
234
	// Fetch the session
235
	session := s.sessions.get(token)
236
	if session == nil {
237
		s.conf.Logger.Warnf("Session not found: %s", token)
Sietse Ringers's avatar
Sietse Ringers committed
238
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorSessionUnknown, ""))
239
		return
240
	}
241
242
	session.Lock()
	defer session.Unlock()
243

244
245
	// However we return, if the session status has been updated
	// then we should inform the user by returning a SessionResult
246
	defer func() {
247
248
		if session.status != session.prevStatus {
			session.prevStatus = session.status
249
250
251
252
			result = session.result
		}
	}()

253
	// Route to handler
254
	switch len(noun) {
255
	case 0:
256
		if method == http.MethodDelete {
257
258
259
			session.handleDelete()
			status = http.StatusOK
			return
260
		}
261
		if method == http.MethodGet {
262
263
264
265
			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
266
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
267
				return
268
269
			}
			if err := json.Unmarshal([]byte(h.Get(irma.MaxVersionHeader)), max); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
270
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
271
				return
272
			}
Sietse Ringers's avatar
Sietse Ringers committed
273
			status, output = server.JsonResponse(session.handleGetRequest(min, max))
274
			return
275
		}
Sietse Ringers's avatar
Sietse Ringers committed
276
		status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
277
		return
278
	default:
279
280
281
282
283
284
		if noun == "statusevents" {
			err := server.RemoteError(server.ErrorInvalidRequest, "server sent events not supported by this server")
			status, output = server.JsonResponse(nil, err)
			return
		}

285
286
		if method == http.MethodGet && noun == "status" {
			status, output = server.JsonResponse(session.handleGetStatus())
Sietse Ringers's avatar
Sietse Ringers committed
287
			return
288
289
290
		}

		// Below are only POST enpoints
291
		if method != http.MethodPost {
Sietse Ringers's avatar
Sietse Ringers committed
292
			status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
Sietse Ringers's avatar
Sietse Ringers committed
293
294
295
			return
		}

296
		if noun == "commitments" && session.action == irma.ActionIssuing {
Sietse Ringers's avatar
Sietse Ringers committed
297
			commitments := &irma.IssueCommitmentMessage{}
Sietse Ringers's avatar
Sietse Ringers committed
298
			if err := irma.UnmarshalValidate(message, commitments); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
299
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, ""))
300
				return
301
			}
Sietse Ringers's avatar
Sietse Ringers committed
302
			status, output = server.JsonResponse(session.handlePostCommitments(commitments))
Sietse Ringers's avatar
Sietse Ringers committed
303
304
			return
		}
305
		if noun == "proofs" && session.action == irma.ActionDisclosing {
Sietse Ringers's avatar
Sietse Ringers committed
306
307
			disclosure := irma.Disclosure{}
			if err := irma.UnmarshalValidate(message, &disclosure); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
308
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, ""))
309
				return
310
			}
Sietse Ringers's avatar
Sietse Ringers committed
311
			status, output = server.JsonResponse(session.handlePostDisclosure(disclosure))
Sietse Ringers's avatar
Sietse Ringers committed
312
313
			return
		}
314
		if noun == "proofs" && session.action == irma.ActionSigning {
Sietse Ringers's avatar
Sietse Ringers committed
315
316
			signature := &irma.SignedMessage{}
			if err := irma.UnmarshalValidate(message, signature); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
317
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, ""))
318
				return
319
			}
Sietse Ringers's avatar
Sietse Ringers committed
320
			status, output = server.JsonResponse(session.handlePostSignature(signature))
321
			return
322
		}
Sietse Ringers's avatar
Sietse Ringers committed
323

Sietse Ringers's avatar
Sietse Ringers committed
324
		status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
325
		return
326
327
	}
}