server.go 21 KB
Newer Older
1
package keyshareserver
2
3

import (
4
	"bytes"
5
	"context"
6
7
8
9
10
11
12
13
	"crypto/rand"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"sync"
14
	"time"
15

16
17
	"github.com/go-errors/errors"
	"github.com/hashicorp/go-multierror"
18
	"github.com/jasonlvhit/gocron"
19
20
21
22
23
	"github.com/privacybydesign/gabi"
	"github.com/privacybydesign/gabi/big"
	irma "github.com/privacybydesign/irmago"
	"github.com/sirupsen/logrus"

24
	"github.com/privacybydesign/irmago/internal/common"
25
	"github.com/privacybydesign/irmago/internal/keysharecore"
26
27
28
29
30
31
32
	"github.com/privacybydesign/irmago/server"
	"github.com/privacybydesign/irmago/server/irmaserver"

	"github.com/go-chi/chi"
)

type SessionData struct {
33
	LastKeyID    irma.PublicKeyIdentifier // last used key, used in signing the issuance message
34
	LastCommitID uint64
35
	expiry       time.Time
36
37
38
}

type Server struct {
39
	// configuration
40
41
	conf *Configuration

42
	// external components
43
	core          *keysharecore.Core
44
45
	sessionserver *irmaserver.Server
	db            KeyshareDB
46
47

	// Scheduler used to clean sessions
48
49
	scheduler     *gocron.Scheduler
	stopScheduler chan<- bool
50

51
	// Session data, keeping track of current keyshare protocol session state for each user
52
53
54
55
56
57
58
	sessions    map[string]*SessionData
	sessionLock sync.Mutex
}

func New(conf *Configuration) (*Server, error) {
	var err error
	s := &Server{
59
60
61
		conf:      conf,
		sessions:  map[string]*SessionData{},
		scheduler: gocron.NewScheduler(),
62
63
	}

64
65
	// Setup IRMA session server
	s.sessionserver, err = irmaserver.New(conf.Configuration)
66
67
68
69
	if err != nil {
		return nil, err
	}

70
71
	// Process configuration and create keyshare core
	s.core, err = processConfiguration(conf)
72
73
74
75
	if err != nil {
		return nil, err
	}

76
77
	// Load neccessary idemix keys into core, and ensure that future updates
	// to them are processed
78
79
80
81
82
83
84
85
86
	if err = s.LoadIdemixKeys(conf.IrmaConfiguration); err != nil {
		return nil, err
	}
	conf.IrmaConfiguration.UpdateListeners = append(conf.IrmaConfiguration.UpdateListeners, func(conf *irma.Configuration) {
		if err := s.LoadIdemixKeys(conf); err != nil {
			// run periodically; can only log the error here
			_ = server.LogError(err)
		}
	})
87

88
89
	// Setup DB
	s.db = conf.DB
90

91
92
93
94
	// Setup session cache clearing
	s.scheduler.Every(10).Seconds().Do(s.clearSessions)
	s.stopScheduler = s.scheduler.Start()

95
96
97
	return s, nil
}

98
99
100
101
102
func (s *Server) Stop() {
	s.stopScheduler <- true
	s.sessionserver.Stop()
}

103
// clean up any expired sessions
104
105
106
107
108
109
110
111
112
113
114
func (s *Server) clearSessions() {
	now := time.Now()
	s.sessionLock.Lock()
	defer s.sessionLock.Unlock()
	for k, v := range s.sessions {
		if now.After(v.expiry) {
			delete(s.sessions, k)
		}
	}
}

115
116
func (s *Server) Handler() http.Handler {
	router := chi.NewRouter()
117
118
119

	if s.conf.Verbose >= 2 {
		opts := server.LogOptions{Response: true, Headers: true, From: false, EncodeBinary: true}
120
		router.Use(server.LogMiddleware("keyshareserver", opts))
121
122
	}

123
	// Registration
124
	router.Post("/client/register", s.handleRegister)
125

126
	// Pin logic
127
128
	router.Post("/users/verify/pin", s.handleVerifyPin)
	router.Post("/users/change/pin", s.handleChangePin)
129
130

	// Keyshare sessions
131
132
133
134
135
136
137
	router.Group(func(router chi.Router) {
		router.Use(s.userMiddleware)
		router.Use(s.authorizationMiddleware)
		router.Post("/users/isAuthorized", s.handleValidate)
		router.Post("/prove/getCommitments", s.handleCommitments)
		router.Post("/prove/getResponse", s.handleResponse)
	})
138

139
	// IRMA server for issuing myirma credential during registration
140
141
142
143
	router.Mount("/irma/", s.sessionserver.HandlerFunc())
	return router
}

144
// On configuration changes, inform the keyshare core of any
145
// new IRMA issuer public keys.
146
147
func (s *Server) LoadIdemixKeys(conf *irma.Configuration) error {
	errs := multierror.Error{}
148
	for _, issuer := range conf.Issuers {
149
		keyIDs, err := conf.PublicKeyIndices(issuer.Identifier())
150
		if err != nil {
151
			errs.Errors = append(errs.Errors, errors.Errorf("issuer %v: could not find key IDs: %v", issuer, err))
152
153
			continue
		}
154
		for _, id := range keyIDs {
155
156
			key, err := conf.PublicKey(issuer.Identifier(), id)
			if err != nil {
157
				errs.Errors = append(errs.Errors, server.LogError(errors.Errorf("key %v-%v: could not fetch public key: %v", issuer, id, err)))
158
159
				continue
			}
160
			s.core.DangerousAddTrustedPublicKey(irma.PublicKeyIdentifier{Issuer: issuer.Identifier(), Counter: id}, key)
161
162
		}
	}
163
	return errs.ErrorOrNil()
164
165
}

166
// /prove/getCommitments
167
func (s *Server) handleCommitments(w http.ResponseWriter, r *http.Request) {
168
	// Fetch from context
169
	user := r.Context().Value("user").(*KeyshareUser)
170
171
	authorization := r.Context().Value("authorization").(string)

172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
	// Read keys
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not read request body")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}
	var keys []irma.PublicKeyIdentifier
	err = json.Unmarshal(body, &keys)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not parse request body")
		s.conf.Logger.WithField("body", body).Debug("Malformed request data")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}
	if len(keys) == 0 {
		s.conf.Logger.Info("Malformed request: no keys over which to commit specified")
		server.WriteError(w, server.ErrorInvalidRequest, "No key specified")
		return
	}

193
194
195
196
	commitments, err := s.generateCommitments(user, authorization, keys)
	if err == keysharecore.ErrInvalidChallenge || err == keysharecore.ErrInvalidJWT {
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
197
	}
198
	if err != nil {
199
200
		// already logged
		server.WriteError(w, server.ErrorInternal, err.Error())
201
202
203
		return
	}

204
205
206
	server.WriteJson(w, commitments)
}

207
func (s *Server) generateCommitments(user *KeyshareUser, authorization string, keys []irma.PublicKeyIdentifier) (*irma.ProofPCommitmentMap, error) {
208
	// Generate commitments
209
	commitments, commitID, err := s.core.GenerateCommitments(user.Coredata, authorization, keys)
210
211
	if err != nil {
		s.conf.Logger.WithField("error", err).Warn("Could not generate commitments for request")
212
		return nil, err
213
214
215
	}

	// Prepare output message format
216
	mappedCommitments := map[irma.PublicKeyIdentifier]*gabi.ProofPCommitment{}
217
	for i, keyID := range keys {
218
		mappedCommitments[keyID] = commitments[i]
219
220
221
	}

	// Store needed data for later requests.
222
	username := user.Username
223
224
225
226
	s.sessionLock.Lock()
	if _, ok := s.sessions[username]; !ok {
		s.sessions[username] = &SessionData{}
	}
227
228
229
230
	// Of all keys involved in the current session, store the ID of the first one to be used when
	// the user comes back later to retrieve her response. gabi.ProofP.P will depend on this public
	// key, which is used only during issuance. Thus, this assumes that during issuance, the user
	// puts the key ID of the credential(s) being issued at index 0.
231
	s.sessions[username].LastKeyID = keys[0]
232
	s.sessions[username].LastCommitID = commitID
233
	s.sessions[username].expiry = time.Now().Add(10 * time.Second)
234
235
236
	s.sessionLock.Unlock()

	// And send response
237
	return &irma.ProofPCommitmentMap{Commitments: mappedCommitments}, nil
238
239
}

240
// /prove/getResponse
241
func (s *Server) handleResponse(w http.ResponseWriter, r *http.Request) {
242
	// Fetch from context
243
244
	user := r.Context().Value("user").(*KeyshareUser)
	username := user.Username
245
246
	authorization := r.Context().Value("authorization").(string)

247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
	// Read challenge
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not read request body")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}
	challenge := new(big.Int)
	err = json.Unmarshal(body, challenge)
	if err != nil {
		s.conf.Logger.Info("Malformed request: could not parse challenge")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}

262
263
264
265
266
	// verify access (avoids leaking whether there is a session ongoing to unauthorized callers)
	if !r.Context().Value("hasValidAuthorization").(bool) {
		s.conf.Logger.Warn("Could not generate keyshare response due to invalid authorization")
		server.WriteError(w, server.ErrorInvalidRequest, "Invalid authorization")
		return
267
	}
268

269
270
271
272
273
274
275
	// Get data from session
	s.sessionLock.Lock()
	sessionData, ok := s.sessions[username]
	s.sessionLock.Unlock()
	if !ok {
		s.conf.Logger.Warn("Request for response without previous call to get commitments")
		server.WriteError(w, server.ErrorInvalidRequest, "Missing previous call to getCommitments")
276
277
278
		return
	}

279
280
281
	// And do the actual responding
	proofResponse, err := s.doGenerateResponses(user, authorization, challenge, sessionData.LastCommitID, sessionData.LastKeyID)
	if err == keysharecore.ErrInvalidChallenge || err == keysharecore.ErrInvalidJWT {
282
283
284
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}
285
286
287
288
289
290
291
292
	if err != nil {
		// already logged
		server.WriteError(w, server.ErrorInternal, err.Error())
		return
	}

	server.WriteString(w, proofResponse)
}
293

294
func (s *Server) doGenerateResponses(user *KeyshareUser, authorization string, challenge *big.Int, commitID uint64, keyID irma.PublicKeyIdentifier) (string, error) {
David Venhoek's avatar
David Venhoek committed
295
	// Indicate activity on user account
296
	err := s.db.SetSeen(user)
David Venhoek's avatar
David Venhoek committed
297
298
299
300
301
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not mark user as seen recently")
		// Do not send to user
	}

302
303
304
305
	// Make log entry
	err = s.db.AddLog(user, IrmaSession, nil)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not add log entry for user")
306
		return "", err
307
308
	}

309
	proofResponse, err := s.core.GenerateResponse(user.Coredata, authorization, commitID, challenge, keyID)
310
311
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not generate response for request")
312
		return "", err
313
314
	}

315
	return proofResponse, nil
316
317
}

318
// /users/isAuthorized
319
func (s *Server) handleValidate(w http.ResponseWriter, r *http.Request) {
320
	if r.Context().Value("hasValidAuthorization").(bool) {
321
		server.WriteJson(w, &irma.KeyshareAuthorization{Status: "authorized", Candidates: []string{"pin"}})
322
	} else {
323
		server.WriteJson(w, &irma.KeyshareAuthorization{Status: "expired", Candidates: []string{"pin"}})
324
325
326
	}
}

327
// /users/verify/pin
328
329
330
331
332
333
334
335
func (s *Server) handleVerifyPin(w http.ResponseWriter, r *http.Request) {
	// Extract request
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not read request body")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}
336
	var msg irma.KeysharePinMessage
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
	err = json.Unmarshal(body, &msg)
	if err != nil {
		s.conf.Logger.WithFields(logrus.Fields{"error": err}).Info("Malformed request: could not parse request body")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}

	// Fetch user
	user, err := s.db.User(msg.Username)
	if err != nil {
		s.conf.Logger.WithFields(logrus.Fields{"username": msg.Username, "error": err}).Warn("Could not find user in db")
		server.WriteError(w, server.ErrorUserNotRegistered, "")
		return
	}

352
353
	// and verify pin
	result, err := s.doVerifyPin(user, msg.Username, msg.Pin)
354
	if err != nil {
355
		// already logged
356
357
358
		server.WriteError(w, server.ErrorInternal, err.Error())
		return
	}
359
360
361
362

	server.WriteJson(w, result)
}

363
func (s *Server) doVerifyPin(user *KeyshareUser, username, pin string) (irma.KeysharePinStatus, error) {
364
365
366
367
	// Check whether timing allows this pin to be checked
	ok, tries, wait, err := s.db.ReservePincheck(user)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not reserve pin check slot")
368
		return irma.KeysharePinStatus{}, nil
369
	}
370
	if !ok {
371
372
373
		err = s.db.AddLog(user, PinCheckRefused, nil)
		if err != nil {
			s.conf.Logger.WithField("error", err).Error("Could not add log entry for user")
374
			return irma.KeysharePinStatus{}, err
375
		}
376
		return irma.KeysharePinStatus{Status: "error", Message: fmt.Sprintf("%v", wait)}, nil
377
378
	}
	// At this point, we are allowed to do an actual check (we have successfully reserved a spot for it), so do it.
379
	jwtt, err := s.core.ValidatePin(user.Coredata, pin, username)
380
381
382
	if err != nil && err != keysharecore.ErrInvalidPin {
		// Errors other than invalid pin are real errors
		s.conf.Logger.WithField("error", err).Error("Could not validate pin")
383
		return irma.KeysharePinStatus{}, err
384
	}
385

386
	if err == keysharecore.ErrInvalidPin {
387
		// Handle invalid pin
388
389
390
		err = s.db.AddLog(user, PinCheckFailed, tries)
		if err != nil {
			s.conf.Logger.WithField("error", err).Error("Could not add log entry for user")
391
			return irma.KeysharePinStatus{}, err
392
		}
393
		if tries == 0 {
394
395
396
			err = s.db.AddLog(user, PinCheckBlocked, wait)
			if err != nil {
				s.conf.Logger.WithField("error", err).Error("Could not add log entry for user")
397
				return irma.KeysharePinStatus{}, err
398
			}
399
			return irma.KeysharePinStatus{Status: "error", Message: fmt.Sprintf("%v", wait)}, nil
400
		} else {
401
			return irma.KeysharePinStatus{Status: "failure", Message: fmt.Sprintf("%v", tries)}, nil
402
		}
403
	}
404

405
406
407
408
409
410
411
412
413
414
415
416
417
418
	// Handle success
	err = s.db.ClearPincheck(user)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not reset users pin check logic")
		// Do not send to user
	}
	err = s.db.SetSeen(user)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not indicate user activity")
		// Do not send to user
	}
	err = s.db.AddLog(user, PinCheckSuccess, nil)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not add log entry for user")
419
		return irma.KeysharePinStatus{}, err
420
	}
421

422
	return irma.KeysharePinStatus{Status: "success", Message: jwtt}, err
423
424
}

425
// /users/change/pin
426
427
428
429
430
431
432
433
func (s *Server) handleChangePin(w http.ResponseWriter, r *http.Request) {
	// Extract request
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not read request body")
		server.WriteError(w, server.ErrorInvalidRequest, "could not read request body")
		return
	}
434
	var msg irma.KeyshareChangePin
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
	err = json.Unmarshal(body, &msg)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not parse request body")
		server.WriteError(w, server.ErrorInvalidRequest, "Invalid request")
		return
	}

	// Fetch user
	user, err := s.db.User(msg.Username)
	if err != nil {
		s.conf.Logger.WithFields(logrus.Fields{"username": msg.Username, "error": err}).Warn("Could not find user in db")
		server.WriteError(w, server.ErrorUserNotRegistered, "")
		return
	}

450
	result, err := s.doUpdatePin(user, msg.OldPin, msg.NewPin)
451
	if err != nil {
452
		// already logged
453
		server.WriteError(w, server.ErrorInternal, err.Error())
454
455
		return
	}
456
457
458
	server.WriteJson(w, result)
}

459
func (s *Server) doUpdatePin(user *KeyshareUser, oldPin, newPin string) (irma.KeysharePinStatus, error) {
460
461
462
463
	// Check whether pin check is currently allowed
	ok, tries, wait, err := s.db.ReservePincheck(user)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not reserve pin check slot")
464
		return irma.KeysharePinStatus{}, err
465
	}
466
	if !ok {
467
		return irma.KeysharePinStatus{Status: "error", Message: fmt.Sprintf("%v", wait)}, nil
468
	}
469
470

	// Try to do the update
471
	user.Coredata, err = s.core.ChangePin(user.Coredata, oldPin, newPin)
472
	if err == keysharecore.ErrInvalidPin {
473
		if tries == 0 {
474
			return irma.KeysharePinStatus{Status: "error", Message: fmt.Sprintf("%v", wait)}, nil
475
		} else {
476
			return irma.KeysharePinStatus{Status: "failure", Message: fmt.Sprintf("%v", tries)}, nil
477
478
479
		}
	} else if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not change pin")
480
		return irma.KeysharePinStatus{}, nil
481
	}
482
483

	// Mark pincheck as success, resetting users wait and count
484
485
486
487
488
	err = s.db.ClearPincheck(user)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not reset users pin check logic")
		// Do not send to user
	}
489
490
491
492
493

	// Write user back
	err = s.db.UpdateUser(user)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not write updated user to database")
494
		return irma.KeysharePinStatus{}, err
495
496
	}

497
	return irma.KeysharePinStatus{Status: "success"}, nil
498
499
}

500
// /client/register
501
502
503
504
505
506
507
508
func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {
	// Extract request
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not read request body")
		server.WriteError(w, server.ErrorInvalidRequest, "could not read request body")
		return
	}
509
	var msg irma.KeyshareEnrollment
510
511
512
513
514
515
516
	err = json.Unmarshal(body, &msg)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not parse request body")
		server.WriteError(w, server.ErrorInvalidRequest, "Invalid request")
		return
	}

517
518
519
520
521
522
523
524
525
526
527
528
529
530
	sessionptr, err := s.doRegistration(msg)
	if err == keysharecore.ErrPinTooLong {
		// Too long pin is not an internal error
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}
	if err != nil {
		// Already logged
		server.WriteError(w, server.ErrorInternal, err.Error())
		return
	}
	server.WriteJson(w, sessionptr)
}

531
func (s *Server) doRegistration(msg irma.KeyshareEnrollment) (*irma.Qr, error) {
532
533
534
535
536
	// Generate keyshare server account
	username := generateUsername()
	coredata, err := s.core.GenerateKeyshareSecret(msg.Pin)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not register user")
537
		return nil, err
538
	}
539
540
	user := &KeyshareUser{Username: username, Language: msg.Language, Coredata: coredata}
	err = s.db.NewUser(user)
541
542
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not store new user in database")
543
		return nil, err
544
545
	}

546
	// Send email if user specified email address
547
	if msg.Email != nil && *msg.Email != "" && s.conf.EmailServer != "" {
548
		err = s.sendRegistrationEmail(user, msg.Language, *msg.Email)
549
		if err != nil {
550
551
			// already logged in sendRegistrationEmail
			return nil, err
552
		}
553
554
	}

555
556
557
558
559
560
561
562
563
564
565
	// Setup and return issuance session for keyshare credential.
	request := irma.NewIssuanceRequest([]*irma.CredentialRequest{
		{
			CredentialTypeID: irma.NewCredentialTypeIdentifier(s.conf.KeyshareCredential),
			Attributes: map[string]string{
				s.conf.KeyshareAttribute: username,
			},
		}})
	sessionptr, _, err := s.sessionserver.StartSession(request, nil)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not start keyshare credential issuance sessions")
566
		return nil, err
567
	}
568
569
570
	return sessionptr, nil
}

571
func (s *Server) sendRegistrationEmail(user *KeyshareUser, language, email string) error {
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
	// Fetch template and configuration data for users language, falling back if needed
	template, ok := s.conf.RegistrationEmailTemplates[language]
	if !ok {
		template = s.conf.RegistrationEmailTemplates[s.conf.DefaultLanguage]
	}
	verificationBaseURL, ok := s.conf.VerificationURL[language]
	if !ok {
		verificationBaseURL = s.conf.VerificationURL[s.conf.DefaultLanguage]
	}
	subject, ok := s.conf.RegistrationEmailSubject[language]
	if !ok {
		subject = s.conf.RegistrationEmailSubject[s.conf.DefaultLanguage]
	}

	// Generate token
	token := common.NewSessionToken()

	// Add it to the database
	err := s.db.AddEmailVerification(user, email, token)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not generate email verifiation mail record")
		return err
	}

	// Build message
	var msg bytes.Buffer
	err = template.Execute(&msg, map[string]string{"VerificationURL": verificationBaseURL + token})
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not generate email verifiation mail")
		return err
	}

	// And send it
	err = server.SendHTMLMail(
		s.conf.EmailServer,
		s.conf.EmailAuth,
		s.conf.EmailFrom,
		email,
		subject,
		msg.Bytes())

	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not send email verifiation mail")
		return err
	}

	return nil
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
}

// Generate a base62 "username".
//  this is a direct port of what the old java server uses.
func generateUsername() string {
	bts := make([]byte, 8)
	_, err := rand.Read(bts)
	if err != nil {
		panic(err)
	}
	raw := make([]byte, 12)
	base64.StdEncoding.Encode(raw, bts)
	return strings.ReplaceAll(
		strings.ReplaceAll(
			strings.ReplaceAll(
				string(raw),
				"+",
				""),
			"/",
			""),
		"=",
		"")
}
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669

func (s *Server) userMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Extract username from request
		username := r.Header.Get("X-IRMA-Keyshare-Username")

		// and fetch its information
		user, err := s.db.User(username)
		if err != nil {
			s.conf.Logger.WithFields(logrus.Fields{"username": username, "error": err}).Warn("Could not find user in db")
			server.WriteError(w, server.ErrorUserNotRegistered, err.Error())
			return
		}

		next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), "user", user)))
	})
}

func (s *Server) authorizationMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Extract authorization from request
		authorization := r.Header.Get("Authorization")
		if strings.HasPrefix(authorization, "Bearer ") {
			authorization = authorization[7:]
		}

		// verify access
		ctx := r.Context()
670
		err := s.core.ValidateJWT(ctx.Value("user").(*KeyshareUser).Coredata, authorization)
671
672
673
674
675
676
677
678
679
680
		hasValidAuthorization := (err == nil)

		// Construct new context with both authorization and its validity
		nextContext := context.WithValue(
			context.WithValue(ctx, "authorization", authorization),
			"hasValidAuthorization", hasValidAuthorization)

		next.ServeHTTP(w, r.WithContext(nextContext))
	})
}