api.go 11.5 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
type Server struct {
26 27 28 29
	conf          *server.Configuration
	sessions      sessionStore
	scheduler     *gocron.Scheduler
	stopScheduler chan bool
30 31 32 33 34 35 36
}

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

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

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

55 56 57 58 59
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{}
60
	}
61 62
	server.Logger = s.conf.Logger
	irma.Logger = s.conf.Logger
63

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

92
	if len(s.conf.IrmaConfiguration.SchemeManagers) == 0 {
93 94 95
		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)
96
		}
97
	}
98 99 100 101 102
	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
103 104
	}

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

139 140 141
	if s.conf.URL != "" {
		if !strings.HasSuffix(s.conf.URL, "/") {
			s.conf.URL = s.conf.URL + "/"
142 143
		}
	} else {
144
		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")
145 146
	}

Sietse Ringers's avatar
Sietse Ringers committed
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"))
		}
Sietse Ringers's avatar
Sietse Ringers committed
152
		t := irma.NewHTTPTransport("https://metrics.privacybydesign.foundation/history")
Sietse Ringers's avatar
Sietse Ringers committed
153 154
		t.SetHeader("User-Agent", "irmaserver")
		var x string
Sietse Ringers's avatar
Sietse Ringers committed
155
		_ = t.Post("email", &x, s.conf.Email)
Sietse Ringers's avatar
Sietse Ringers committed
156 157
	}

158 159 160
	return nil
}

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

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

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

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

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

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

215 216 217 218 219 220 221 222 223
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
}

224 225 226 227 228 229 230
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)
	}
231 232 233 234 235 236 237 238 239 240 241 242 243
	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
}

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

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

Sietse Ringers's avatar
Sietse Ringers committed
271
	// Fetch the session
272
	session := s.sessions.clientGet(token)
273
	if session == nil {
274
		s.conf.Logger.WithField("clientToken", token).Warn("Session not found")
Sietse Ringers's avatar
Sietse Ringers committed
275
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorSessionUnknown, ""))
276
		return
277
	}
278 279
	session.Lock()
	defer session.Unlock()
280

281 282
	// However we return, if the session status has been updated
	// then we should inform the user by returning a SessionResult
283
	defer func() {
284 285
		if session.status != session.prevStatus {
			session.prevStatus = session.status
286 287 288 289
			result = session.result
		}
	}()

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

322 323
		if method == http.MethodGet && noun == "status" {
			status, output = server.JsonResponse(session.handleGetStatus())
Sietse Ringers's avatar
Sietse Ringers committed
324
			return
325 326 327
		}

		// Below are only POST enpoints
328
		if method != http.MethodPost {
Sietse Ringers's avatar
Sietse Ringers committed
329
			status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
Sietse Ringers's avatar
Sietse Ringers committed
330 331 332
			return
		}

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

Sietse Ringers's avatar
Sietse Ringers committed
361
		status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
362
		return
363 364
	}
}