api.go 11.4 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
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{
36 37 38
			requestor: make(map[string]*session),
			client:    make(map[string]*session),
			conf:      conf,
39 40 41 42 43 44 45 46 47
		},
	}
	s.scheduler.Every(10).Seconds().Do(func() {
		s.sessions.deleteExpired()
	})
	s.scheduler.Start()

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

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

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

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

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

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

Sietse Ringers's avatar
Sietse Ringers committed
141 142 143 144 145 146 147 148 149 150 151
	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)
	}

152 153 154
	return nil
}

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

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

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

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

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

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

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

218 219 220 221 222 223 224
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)
	}
225 226 227 228 229 230 231 232 233 234 235 236 237
	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
}

238
func (s *Server) HandleProtocolMessage(
239 240 241 242
	path string,
	method string,
	headers map[string][]string,
	message []byte,
Sietse Ringers's avatar
Sietse Ringers committed
243
) (status int, output []byte, result *server.SessionResult) {
244 245 246 247 248 249 250 251 252
	// 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]
		}
	}
253

254
	s.conf.Logger.WithFields(logrus.Fields{"method": method, "path": path}).Debugf("Routing protocol message")
255
	if len(message) > 0 {
256
		s.conf.Logger.Trace("POST body: ", string(message))
257
	}
258
	s.conf.Logger.Trace("HTTP headers: ", server.ToJson(headers))
259 260 261
	token, noun, err := ParsePath(path)
	if err != nil {
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorUnsupported, ""))
262
		return
263 264
	}

Sietse Ringers's avatar
Sietse Ringers committed
265
	// Fetch the session
266
	session := s.sessions.clientGet(token)
267
	if session == nil {
268
		s.conf.Logger.WithField("clientToken", token).Warn("Session not found")
Sietse Ringers's avatar
Sietse Ringers committed
269
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorSessionUnknown, ""))
270
		return
271
	}
272 273
	session.Lock()
	defer session.Unlock()
274

275 276
	// However we return, if the session status has been updated
	// then we should inform the user by returning a SessionResult
277
	defer func() {
278 279
		if session.status != session.prevStatus {
			session.prevStatus = session.status
280 281 282 283
			result = session.result
		}
	}()

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

316 317
		if method == http.MethodGet && noun == "status" {
			status, output = server.JsonResponse(session.handleGetStatus())
Sietse Ringers's avatar
Sietse Ringers committed
318
			return
319 320 321
		}

		// Below are only POST enpoints
322
		if method != http.MethodPost {
Sietse Ringers's avatar
Sietse Ringers committed
323
			status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
Sietse Ringers's avatar
Sietse Ringers committed
324 325 326
			return
		}

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

Sietse Ringers's avatar
Sietse Ringers committed
355
		status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
356
		return
357 358
	}
}